{"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"","sourcesContent":["#!/usr/bin/env node\nimport { existsSync, mkdirSync, readFileSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { createAgoraServer } from \"./api/server.js\";\nimport { parseDuration } from \"./duration.js\";\nimport { frontier, unverifiedResults } from \"./graph.js\";\nimport { createPiRunner } from \"./pi-runner.js\";\nimport { createPiTextCaller } from \"./pi-text-caller.js\";\nimport { runIterate } from \"./iterate.js\";\nimport { writeGoalFromPrompt } from \"./goal-writer.js\";\nimport { runWorker } from \"./worker.js\";\nimport { createGitStore } from \"./store.js\";\nimport { ensureProductMarker } from \"./project-config.js\";\nimport { loadProjectTasks } from \"./tasks.js\";\n\nconst USAGE = `Usage:\n  pi-agora init <project-dir>\n  pi-agora tasks <project-dir>\n  pi-agora frontier <project-dir>\n  pi-agora run <project-dir> --model provider/model [--pi <bin>] [--max-attempts N]\n                        [--forever] [--time 1h30m] [--retry-passed]\n  pi-agora start <project-dir> --from \"<prompt>\" --model provider/model [--pi <bin>]\n                        [--goal <file>] [--product <dir>] [--max-tasks N] [--max-attempts N]\n                        [--time 1h30m]\n  pi-agora iterate <project-dir> --model provider/model [--pi <bin>] [--goal <file>]\n                        [--product <dir>] [--max-tasks N] [--max-attempts N] [--time 1h30m]\n  pi-agora serve <project-dir> [--port N] [--host H]\n\ninit:     create the .agora git store. Publish one task contribution per task.\ntasks:    list the project tasks.\nfrontier: list frontier contributions. List results without verification.\nrun:      work tasks, at most max-attempts attempts per task this run. Publish\n          results. Each result gets a verification contribution. Passed tasks\n          are skipped on every later run. Use --pi to set the pi\n          binary path. Use --model to set the model for the agent. --forever\n          removes the attempt budget: iterate until you stop it with Ctrl-C.\n          Every attempt is published, so stopping loses nothing.\nstart:    turn a free-text prompt into GOAL.md, then run iterate. If GOAL.md\n          already exists, keep it. Then: as iterate.\niterate:  run the worker, then when the pool is dry, generate the next task\n          from the project goal (GOAL.md by default, or --goal <file>) and\n          keep going. Generated tasks must fail verification against the\n          current product, so they always encode new work. Stops when the\n          generator says the goal is complete, when --max-tasks is reached,\n          or at --time (same graceful drain as run).\nserve:    serve the project's contribution DAG over HTTP (read-only).`;\n\nfunction value(flag: string, args: string[]): string {\n\tconst index = args.indexOf(flag);\n\tif (index === -1 || index + 1 >= args.length) {\n\t\tthrow new Error(`${flag} requires a value`);\n\t}\n\treturn args[index + 1];\n}\n\nasync function main(): Promise<void> {\n\tconst argv = process.argv.slice(2);\n\tif (argv.length === 0 || argv[0] === \"--help\" || argv[0] === \"-h\") {\n\t\tconsole.log(USAGE);\n\t\tprocess.exit(argv.length === 0 ? 2 : 0);\n\t}\n\tconst command = argv[0];\n\tconst projectDir = argv[1];\n\tif (!projectDir) {\n\t\tthrow new Error(`${command} requires a project directory`);\n\t}\n\tif (command === \"init\") {\n\t\tconst store = await createGitStore(projectDir);\n\t\tconst tasks = loadProjectTasks(projectDir);\n\t\tfor (const task of tasks) {\n\t\t\tawait store.publish({\n\t\t\t\ttype: \"task\",\n\t\t\t\tdescription: task.description.split(\"\\n\")[0].replace(/^#\\s*/, \"\").slice(0, 100),\n\t\t\t\ttags: [`task:${task.name}`],\n\t\t\t});\n\t\t}\n\t\tconsole.log(`published ${tasks.length} task contributions to ${projectDir}/.agora`);\n\t\treturn;\n\t}\n\tif (command === \"tasks\") {\n\t\tfor (const task of loadProjectTasks(projectDir)) {\n\t\t\tconsole.log(`${task.name}: ${task.description.split(\"\\n\")[0].replace(/^#\\s*/, \"\")}`);\n\t\t}\n\t\treturn;\n\t}\n\tif (command === \"frontier\") {\n\t\tconst store = await createGitStore(projectDir);\n\t\tconst contributions = await store.query();\n\t\tconsole.log(`contributions: ${contributions.length}`);\n\t\tfor (const leaf of frontier(contributions)) {\n\t\t\tconsole.log(`  [leaf] ${leaf.type}: ${leaf.description.slice(0, 80)}`);\n\t\t}\n\t\tconst pending = unverifiedResults(contributions);\n\t\tconsole.log(`unverified results: ${pending.length}`);\n\t\tfor (const result of pending) {\n\t\t\tconsole.log(`  [unverified] ${result.description.slice(0, 80)}`);\n\t\t}\n\t\treturn;\n\t}\n\tif (command === \"serve\") {\n\t\tif (!projectDir) {\n\t\t\tthrow new Error(\"serve requires a project directory\");\n\t\t}\n\t\tconst rest = argv.slice(2);\n\t\tconst port = rest.includes(\"--port\") ? Number.parseInt(value(\"--port\", rest), 10) : 8788;\n\t\tconst host = rest.includes(\"--host\") ? value(\"--host\", rest) : \"127.0.0.1\";\n\t\tif (!Number.isInteger(port) || port <= 0 || port > 65535) {\n\t\t\tthrow new Error(\"--port must be a valid port number\");\n\t\t}\n\t\tconst store = await createGitStore(projectDir);\n\t\tconst server = createAgoraServer({ store, projectDir, host, port });\n\t\tserver.listen(port, host, () => {\n\t\t\tconsole.log(`pi-agora serve: http://${host}:${port} (project: ${projectDir})`);\n\t\t});\n\t\treturn;\n\t}\n\tif (command === \"iterate\" || command === \"start\") {\n\t\tconst isStart = command === \"start\";\n\t\tconst rest = argv.slice(2);\n\t\tconst model = value(\"--model\", rest);\n\t\tif (!model) {\n\t\t\tthrow new Error(\"--model requires a value\");\n\t\t}\n\t\tconst piBin = rest.includes(\"--pi\") ? value(\"--pi\", rest) : \"pi\";\n\t\tconst prompt = rest.includes(\"--from\") ? value(\"--from\", rest) : null;\n\t\tconst productDir = rest.includes(\"--product\")\n\t\t\t? value(\"--product\", rest)\n\t\t\t: isStart\n\t\t\t\t? \"tasks/product/workspace\"\n\t\t\t\t: undefined;\n\t\tconst maxTasks = rest.includes(\"--max-tasks\") ? Number.parseInt(value(\"--max-tasks\", rest), 10) : 10;\n\t\tconst maxAttempts = rest.includes(\"--max-attempts\") ? Number.parseInt(value(\"--max-attempts\", rest), 10) : 3;\n\t\tconst timeRaw = rest.includes(\"--time\") ? value(\"--time\", rest) : null;\n\t\tconst timeMs = timeRaw !== null ? parseDuration(timeRaw) : null;\n\t\tif (isStart && !prompt) {\n\t\t\tthrow new Error(\"start requires --from \\\"<prompt>\\\" describing what to build\");\n\t\t}\n\t\tif (!isStart && prompt) {\n\t\t\tthrow new Error(\"--from belongs to start; iterate reads GOAL.md (--goal <file> to override)\");\n\t\t}\n\t\tif (!Number.isInteger(maxTasks) || maxTasks <= 0) {\n\t\t\tthrow new Error(\"--max-tasks must be a positive integer\");\n\t\t}\n\t\tif (!Number.isInteger(maxAttempts) || maxAttempts <= 0) {\n\t\t\tthrow new Error(\"--max-attempts must be a positive integer\");\n\t\t}\n\t\tif (isStart) {\n\t\t\tmkdirSync(join(projectDir, \"tasks\"), { recursive: true });\n\t\t\tensureProductMarker(projectDir, productDir ?? \"tasks/product/workspace\");\n\t\t}\n\t\tconst goalPath = join(projectDir, rest.includes(\"--goal\") ? value(\"--goal\", rest) : \"GOAL.md\");\n\t\tif (isStart) {\n\t\t\tif (!existsSync(goalPath)) {\n\t\t\t\tconsole.log(\"writing the project goal from your prompt.\");\n\t\t\t\tawait writeGoalFromPrompt({ projectDir, prompt: prompt as string, caller: createPiTextCaller(piBin, model), goalPath });\n\t\t\t\tconsole.log(`goal written to ${goalPath}`);\n\t\t\t}\n\t\t} else {\n\t\t\ttry {\n\t\t\t\treadFileSync(goalPath, \"utf8\");\n\t\t\t} catch {\n\t\t\t\tthrow new Error(`goal file not found: ${goalPath}`);\n\t\t\t}\n\t\t}\n\t\tconst store = await createGitStore(projectDir);\n\t\tif (isStart) {\n\t\t\tfor (const task of loadProjectTasks(projectDir)) {\n\t\t\t\tconst known = (await store.query()).some((c) => c.type === \"task\" && c.tags.includes(`task:${task.name}`));\n\t\t\t\tif (!known) {\n\t\t\t\t\tawait store.publish({\n\t\t\t\t\t\ttype: \"task\",\n\t\t\t\t\t\tdescription: task.description.split(\"\\n\")[0].replace(/^#\\s*/, \"\").slice(0, 100),\n\t\t\t\t\t\ttags: [`task:${task.name}`],\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst report = await runIterate({\n\t\t\tprojectDir,\n\t\t\tstore,\n\t\t\tgoalPath,\n\t\t\tmodel,\n\t\t\tpiBin,\n\t\t\tmaxTasks,\n\t\t\tmaxAttempts,\n\t\t\ttimeMs,\n\t\t\t...(productDir ? { productDir } : {}),\n\t\t\tlog: (message) => console.log(message),\n\t\t});\n\t\tconsole.log(`${command} finished: ${report.tasksGenerated} task(s) generated, ${report.attempts} attempt(s), stopped because: ${report.stoppedBecause}.`);\n\t\treturn;\n\t}\n\tif (command === \"run\") {\n\t\tconst rest = argv.slice(2);\n\t\tconst model = value(\"--model\", rest);\n\t\tconst piBin = rest.includes(\"--pi\") ? value(\"--pi\", rest) : \"pi\";\n\t\tconst forever = rest.includes(\"--forever\");\n\t\tconst timeRaw = rest.includes(\"--time\") ? value(\"--time\", rest) : null;\n\t\tconst timeMs = timeRaw !== null ? parseDuration(timeRaw) : null;\n\t\tconst maxAttempts = forever\n\t\t\t? Number.POSITIVE_INFINITY\n\t\t\t: rest.includes(\"--max-attempts\")\n\t\t\t\t? Number.parseInt(value(\"--max-attempts\", rest), 10)\n\t\t\t\t: 2;\n\t\tif (maxAttempts !== Number.POSITIVE_INFINITY && (!Number.isInteger(maxAttempts) || maxAttempts <= 0)) {\n\t\t\tthrow new Error(\"--max-attempts must be a positive integer\");\n\t\t}\n\t\tconst store = await createGitStore(projectDir);\n\t\tconst tasks = loadProjectTasks(projectDir);\n\t\tconst runner = createPiRunner({ piBin, model });\n\t\tlet timeUp = false;\n\t\tlet stopTimer: NodeJS.Timeout | null = null;\n\t\tif (timeMs !== null) {\n\t\t\tstopTimer = setTimeout(() => {\n\t\t\t\ttimeUp = true;\n\t\t\t\tconsole.log(`time budget of ${timeRaw} reached. Asking the running agent to commit and stop.`);\n\t\t\t\trunner.signalStop();\n\t\t\t}, timeMs);\n\t\t}\n\t\tconst report = await runWorker({\n\t\t\tstore,\n\t\t\ttasks,\n\t\t\trunner,\n\t\t\tmaxAttempts,\n\t\t\tshouldContinue: timeMs === null ? undefined : () => !timeUp,\n\t\t\tretryPassed: rest.includes(\"--retry-passed\"),\n\t\t});\n\t\tif (stopTimer !== null) {\n\t\t\tclearTimeout(stopTimer);\n\t\t}\n\t\tif (timeUp) {\n\t\t\tconsole.log(\"time budget reached. No new attempts were started.\");\n\t\t}\n\t\tfor (const attempt of report.attempts) {\n\t\t\tconsole.log(`${attempt.task}: ${attempt.passed ? \"verified\" : \"failed\"} — ${attempt.summary.slice(0, 120)}`);\n\t\t}\n\t\tconsole.log(`published ${report.published} contributions`);\n\t\treturn;\n\t}\n\tthrow new Error(`unknown command '${command}'. Run pi-agora --help.`);\n}\n\nmain().catch((error: unknown) => {\n\tconsole.error(error instanceof Error ? error.message : error);\n\tprocess.exit(1);\n});\n"]}