Compare commits

..

1 Commits

Author SHA1 Message Date
c0a4d3ec58 Fixes 2025-11-05 23:22:07 -08:00
7 changed files with 40 additions and 340 deletions

View File

@@ -1,254 +0,0 @@
// SECRET
// Return a random valid action on the given board.
// Used as a last resort.
fn random_action(board) {
let symb = rand_symb();
let pos = rand_int(0, 10);
let action = Action(symb, pos);
while !board.can_play(action) {
let symb = rand_symb();
let pos = rand_int(0, 10);
action = Action(symb, pos);
}
return action
}
/// Returns an array of (idx, f32) for each empty slot in the board.
/// - idx is the index of this slot
/// - f32 is the "influence of" this slot
fn compute_influence(board) {
// Fill all empty slots with fives and compute starting value
let filled = board;
for i in filled.free_spots_idx() {
filled[i] = 5;
}
// Compute the value of the filled board
let base = filled.evaluate();
// Exit early if the board is invalid.
// This is usually caused by zero-division.
if (base == ()) {
return [];
}
// Increase each slot's value by 1
// and record the effect on the expression's total value.
//
// `influence` is an array of (slot_idx, value)
let influence = [];
for i in 0..board.size() {
let slot = board[i];
// Ignore slots that are not empty
if slot != "" {
continue
}
// Don't assign directly to `filled`,
// we want to keep it full of fives.
// Assigning to `b` make a copy of the board.
let b = filled;
b[i] = 6;
influence.push([i, b.evaluate() - base]);
}
// Sort by increasing absolute score
influence.sort(|a, b| {
let a_abs = a[1].abs();
let b_abs = b[1].abs();
// Returns...
// 1 if positive (a_abs > b_abs),
// -1 if negative,
// 0 if equal
return sign(a_abs - b_abs);
});
return influence;
}
fn place_number(board, minimize) {
let numbers = [0,1,2,3,4,5,6,7,8,9];
let available_numbers = numbers.retain(|x| board.contains(x));
let influence = compute_influence(board);
// Stupid edge cases, fall back to random
if influence.len() == 0 || available_numbers.len() == 0 {
return random_action(board);
}
// Get the most influential position
let pos = influence[-1][0];
let val = influence[-1][1];
// Pick the number we should use,
// This is always either the largest
// or the smallest number available to us.
let symbol = 0;
if minimize {
if val > 0 {
symbol = available_numbers[0];
} else {
symbol = available_numbers[-1];
}
} else {
if val > 0 {
symbol = available_numbers[-1];
} else {
symbol = available_numbers[0];
}
}
return Action(symbol, pos);
}
fn op_value(board) {
print(board);
let actions = [];
for o in ["+", "-", "*", "/"] {
if board.contains(o) {
continue;
}
for p in 0..=10 {
let action = Action(o, p);
if board.can_play(action) {
actions.push(action);
}
}
}
// No other operators can be placed, return value of fives
if actions.is_empty() {
let filled = board;
for i in filled.free_spots_idx() {
filled[i] = 5;
}
let v = filled.evaluate();
if v == () {
return ();
} else {
return [v, v];
}
}
let max = ();
let min = ();
for a in actions {
let tmp = board;
tmp.play(a);
let vals = op_value(tmp);
if vals != () {
for v in vals {
if max == () || min == () {
max = v;
min = v;
}
if v > max {
max = v;
} else if v < min {
min = v;
}
}
}
}
if min == () || max == () {
return ();
}
return [min, max];
}
fn place_op(board, minimize) {
let ops = ["+", "-", "*", "/"];
let available_ops = ops.retain(|x| board.contains(x));
// Performance optimization if board is empty.
// This is the move we would pick, hard-coded.
if available_ops.len() == 4 {
if minimize {
let act = Action("+", 3);
if board.can_play(act) {return act}
} else {
let act = Action("/", 9);
if board.can_play(act) {return act}
}
}
// All possible operator actions
let actions = [];
for o in ["+", "-", "*", "/"] {
for p in 0..=10 {
let action = Action(o, p);
if board.can_play(action) {
let tmp = board;
tmp.play(action);
let v = op_value(tmp);
if v != () {
actions.push([action, v]);
}
}
}
}
if actions.is_empty() {
return ();
}
let action = ();
if minimize {
// Sort by increasing minimum score
actions.sort(|a, b| sign(a[1][0] - b[1][0]));
action = actions[0][0];
} else {
// Sort by increasing maximum score
actions.sort(|a, b| sign(a[1][1] - b[1][1]));
action = actions[-1][0];
}
debug(action);
return action;
}
// Main step function (shared between min and max)
fn greed_step(board, minimize) {
let action = place_op(board, minimize);
if action == () {
action = place_number(board, minimize);
}
if board.can_play(action) {
return action;
}
// Prevent invalid moves, random fallback
return random_action(board);
}
// Minimizer step
fn step_min(board) {
greed_step(board, true)
}
// Maximizer step
fn step_max(board) {
greed_step(board, false)
}

View File

@@ -1,3 +1,5 @@
// Return a random valid action on the given board. // Return a random valid action on the given board.
// Used as a last resort. // Used as a last resort.
fn random_action(board) { fn random_action(board) {
@@ -57,8 +59,8 @@ fn compute_influence(board) {
} }
// Sort by increasing absolute score // Sort by increasing absolute score
influence.sort(|a, b| { influence.sort(|a, b| {
let a_abs = a[1].abs(); let a_abs = a[1].abs();
let b_abs = b[1].abs(); let b_abs = b[1].abs();
@@ -83,6 +85,7 @@ fn place_number(board, minimize) {
return random_action(board); return random_action(board);
} }
// Get the most influential position // Get the most influential position
let pos = influence[-1][0]; let pos = influence[-1][0];
let val = influence[-1][1]; let val = influence[-1][1];
@@ -101,7 +104,7 @@ fn place_number(board, minimize) {
if val > 0 { if val > 0 {
symbol = available_numbers[-1]; symbol = available_numbers[-1];
} else { } else {
symbol = available_numbers[0]; symbol = available_numbers[0];
} }
} }
@@ -136,20 +139,25 @@ fn place_op(board, minimize) {
return (); return ();
} }
// Main step function (shared between min and max) // Main step function (shared between min and max)
fn greed_step(board, minimize) { fn greed_step(board, minimize) {
let action = place_op(board, minimize);
// We could not place an op, so place a number let action = place_op(board, minimize);
if action == () { if action == () {
action = place_number(board, minimize); action = place_number(board, minimize);
} }
if board.can_play(action) {
return action;
}
// Prevent invalid moves, random fallback // Prevent invalid moves, random fallback
if board.can_play(action) { return action; }
return random_action(board); return random_action(board);
} }
// Minimizer step // Minimizer step
fn step_min(board) { fn step_min(board) {
greed_step(board, true) greed_step(board, true)

View File

@@ -2,10 +2,10 @@ import { NextRequest, NextResponse } from "next/server";
import { readFile } from "fs/promises"; import { readFile } from "fs/promises";
import { join } from "path"; import { join } from "path";
import { existsSync } from "fs"; import { existsSync } from "fs";
import { CONFIG } from "@/lib/config"; import { SAVE_CONFIG } from "@/lib/saveConfig";
// Force dynamic rendering for this API route // Force dynamic rendering for this API route
export const dynamic = "force-dynamic"; export const dynamic = 'force-dynamic';
export async function GET(request: NextRequest) { export async function GET(request: NextRequest) {
try { try {
@@ -20,14 +20,14 @@ export async function GET(request: NextRequest) {
} }
// Validate filename (same validation as save) // Validate filename (same validation as save)
if (!CONFIG.FILENAME_REGEX.test(name)) { if (!SAVE_CONFIG.FILENAME_REGEX.test(name)) {
return NextResponse.json( return NextResponse.json(
{ error: "Invalid script name" }, { error: "Invalid script name" },
{ status: 400 } { status: 400 }
); );
} }
const saveDir = CONFIG.SAVE_DIRECTORY; const saveDir = SAVE_CONFIG.SAVE_DIRECTORY;
const filename = `${name}.rhai`; const filename = `${name}.rhai`;
const filepath = join(saveDir, filename); const filepath = join(saveDir, filename);
@@ -38,7 +38,7 @@ export async function GET(request: NextRequest) {
); );
} }
let content = await readFile(filepath, "utf8"); const content = await readFile(filepath, "utf8");
return NextResponse.json({ return NextResponse.json({
name, name,

View File

@@ -1,7 +1,7 @@
import { NextRequest, NextResponse } from "next/server"; import { NextRequest, NextResponse } from "next/server";
import { readdir } from "fs/promises"; import { readdir } from "fs/promises";
import { existsSync } from "fs"; import { existsSync } from "fs";
import { CONFIG } from "@/lib/config"; import { SAVE_CONFIG } from "@/lib/saveConfig";
// Force dynamic rendering for this API route // Force dynamic rendering for this API route
export const dynamic = "force-dynamic"; export const dynamic = "force-dynamic";
@@ -14,7 +14,7 @@ const headers = {
export async function GET(_request: NextRequest) { export async function GET(_request: NextRequest) {
try { try {
const saveDir = CONFIG.SAVE_DIRECTORY; const saveDir = SAVE_CONFIG.SAVE_DIRECTORY;
// If save directory doesn't exist, return empty array // If save directory doesn't exist, return empty array
if (!existsSync(saveDir)) { if (!existsSync(saveDir)) {

View File

@@ -2,12 +2,12 @@ import { NextRequest, NextResponse } from "next/server";
import { writeFile, mkdir } from "fs/promises"; import { writeFile, mkdir } from "fs/promises";
import { join } from "path"; import { join } from "path";
import { existsSync } from "fs"; import { existsSync } from "fs";
import { CONFIG } from "@/lib/config"; import { SAVE_CONFIG } from "@/lib/saveConfig";
export async function POST(request: NextRequest) { export async function POST(request: NextRequest) {
try { try {
// Check if saving is enabled // Check if saving is enabled
if (!CONFIG.ENABLE_SAVE) { if (!SAVE_CONFIG.ENABLE_SAVE) {
return NextResponse.json( return NextResponse.json(
{ error: "Script saving is disabled" }, { error: "Script saving is disabled" },
{ status: 403 } { status: 403 }
@@ -16,13 +16,15 @@ export async function POST(request: NextRequest) {
const { name, content, secret } = await request.json(); const { name, content, secret } = await request.json();
if (secret !== CONFIG.SAVE_SECRET) { // Validate secret
if (secret !== SAVE_CONFIG.SAVE_SECRET) {
return NextResponse.json( return NextResponse.json(
{ error: "Invalid secret" }, { error: "Invalid save secret" },
{ status: 401 } { status: 401 }
); );
} }
// Validate required fields
if (!name || !content) { if (!name || !content) {
return NextResponse.json( return NextResponse.json(
{ error: "Name and content are required" }, { error: "Name and content are required" },
@@ -30,25 +32,17 @@ export async function POST(request: NextRequest) {
); );
} }
if (name.length > CONFIG.MAX_FILENAME_LENGTH) { // Validate filename
if (name.length > SAVE_CONFIG.MAX_FILENAME_LENGTH) {
return NextResponse.json( return NextResponse.json(
{ {
error: `Filename must be ${CONFIG.MAX_FILENAME_LENGTH} characters or less`, error: `Filename must be ${SAVE_CONFIG.MAX_FILENAME_LENGTH} characters or less`,
}, },
{ status: 400 } { status: 400 }
); );
} }
if (content.length > CONFIG.MAX_FILE_SIZE) { if (!SAVE_CONFIG.FILENAME_REGEX.test(name)) {
return NextResponse.json(
{
error: `File is too large`,
},
{ status: 400 }
);
}
if (!CONFIG.FILENAME_REGEX.test(name)) {
return NextResponse.json( return NextResponse.json(
{ {
error: "Filename can only contain alphanumerics, underscores, spaces, and hyphens", error: "Filename can only contain alphanumerics, underscores, spaces, and hyphens",
@@ -58,7 +52,7 @@ export async function POST(request: NextRequest) {
} }
// Ensure save directory exists // Ensure save directory exists
const saveDir = CONFIG.SAVE_DIRECTORY; const saveDir = SAVE_CONFIG.SAVE_DIRECTORY;
if (!existsSync(saveDir)) { if (!existsSync(saveDir)) {
await mkdir(saveDir, { recursive: true }); await mkdir(saveDir, { recursive: true });
} }

View File

@@ -47,27 +47,9 @@ const AGENTS = {
export default function Playground() { export default function Playground() {
const [isScriptRunning, setIsScriptRunning] = useState(false); const [isScriptRunning, setIsScriptRunning] = useState(false);
const [isEditorReady, setIsEditorReady] = useState(false); const [isEditorReady, setIsEditorReady] = useState(false);
const [fontSize, setFontSize] = useState(() => { const [fontSize, setFontSize] = useState(14);
if (typeof window !== "undefined") { const [bulkRounds, setBulkRounds] = useState(1000);
const saved = localStorage.getItem("playground-fontSize"); const [selectedAgent, setSelectedAgent] = useState("Self");
return saved ? parseInt(saved, 10) : 14;
}
return 14;
});
const [bulkRounds, setBulkRounds] = useState(() => {
if (typeof window !== "undefined") {
const saved = localStorage.getItem("playground-bulkRounds");
return saved ? parseInt(saved, 10) : 1000;
}
return 1000;
});
const [selectedAgent, setSelectedAgent] = useState(() => {
if (typeof window !== "undefined") {
const saved = localStorage.getItem("playground-selectedAgent");
return saved || "Self";
}
return "Self";
});
const [isHelpOpen, setIsHelpOpen] = useState(false); const [isHelpOpen, setIsHelpOpen] = useState(false);
const [scriptName, setScriptName] = useState(""); const [scriptName, setScriptName] = useState("");
const [saveSecret, setSaveSecret] = useState(""); const [saveSecret, setSaveSecret] = useState("");
@@ -140,30 +122,6 @@ export default function Playground() {
loadSavedScripts(); loadSavedScripts();
}, [loadSavedScripts]); }, [loadSavedScripts]);
// Save font size to localStorage
useEffect(() => {
if (typeof window !== "undefined") {
localStorage.setItem("playground-fontSize", fontSize.toString());
}
}, [fontSize]);
// Save bulk rounds to localStorage
useEffect(() => {
if (typeof window !== "undefined") {
localStorage.setItem(
"playground-bulkRounds",
bulkRounds.toString()
);
}
}, [bulkRounds]);
// Save selected agent to localStorage
useEffect(() => {
if (typeof window !== "undefined") {
localStorage.setItem("playground-selectedAgent", selectedAgent);
}
}, [selectedAgent]);
const runHuman = useCallback(async () => { const runHuman = useCallback(async () => {
if (resultRef.current) { if (resultRef.current) {
resultRef.current.value = ""; resultRef.current.value = "";
@@ -282,7 +240,7 @@ export default function Playground() {
} }
if (!saveSecret.trim()) { if (!saveSecret.trim()) {
alert("Please enter a secret"); alert("Please enter the save secret");
return; return;
} }
@@ -340,11 +298,6 @@ export default function Playground() {
return; return;
} }
if (scriptContent.trim().startsWith("// SECRET")) {
alert("This script is hidden :)");
return;
}
// Warn user about losing current content // Warn user about losing current content
const confirmed = confirm( const confirmed = confirm(
`This will replace your current script with "${selectedAgent}". Your current work will be lost. Continue?` `This will replace your current script with "${selectedAgent}". Your current work will be lost. Continue?`
@@ -455,11 +408,11 @@ export default function Playground() {
</div> </div>
<div className={styles.configField}> <div className={styles.configField}>
<label>Secret</label> <label>Save secret</label>
<input <input
type="password" type="password"
className={styles.saveInput} className={styles.saveInput}
placeholder="Enter secret..." placeholder="Enter save secret..."
value={saveSecret} value={saveSecret}
onChange={(e) => onChange={(e) =>
setSaveSecret( setSaveSecret(

View File

@@ -1,9 +1,8 @@
export const CONFIG = { export const SAVE_CONFIG = {
ENABLE_SAVE: process.env.ENABLE_SAVE === "true" || true, ENABLE_SAVE: process.env.ENABLE_SAVE === 'true' || true,
SAVE_SECRET: process.env.SAVE_SECRET || "save", SAVE_SECRET: process.env.SAVE_SECRET || "save",
SAVE_DIRECTORY: process.env.SAVE_DIRECTORY || "./data/scripts", SAVE_DIRECTORY: process.env.SAVE_DIRECTORY || "./data/scripts",
MAX_FILENAME_LENGTH: parseInt(process.env.MAX_FILENAME_LENGTH || "32"), MAX_FILENAME_LENGTH: parseInt(process.env.MAX_FILENAME_LENGTH || "32"),
MAX_FILE_SIZE: parseInt(process.env.MAX_FILE_SIZE || "1048576"),
FILENAME_REGEX: /^[a-zA-Z0-9_\s-]+$/, FILENAME_REGEX: /^[a-zA-Z0-9_\s-]+$/,
} as const; } as const;