@buildanagent/cli 0.0.0-stage → 0.1.0-alpha.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +54 -0
- package/LICENSE-APACHE +202 -0
- package/LICENSE-MIT +21 -0
- package/README.md +143 -2
- package/dist/args.d.ts +20 -0
- package/dist/args.js +76 -0
- package/dist/args.js.map +1 -0
- package/dist/ask.d.ts +22 -0
- package/dist/ask.js +108 -0
- package/dist/ask.js.map +1 -0
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +26 -0
- package/dist/bin.js.map +1 -0
- package/dist/cli.d.ts +9 -0
- package/dist/cli.js +111 -0
- package/dist/cli.js.map +1 -0
- package/dist/command-lines.d.ts +25 -0
- package/dist/command-lines.js +166 -0
- package/dist/command-lines.js.map +1 -0
- package/dist/commands/chat.d.ts +18 -0
- package/dist/commands/chat.js +52 -0
- package/dist/commands/chat.js.map +1 -0
- package/dist/commands/keys.d.ts +3 -0
- package/dist/commands/keys.js +47 -0
- package/dist/commands/keys.js.map +1 -0
- package/dist/commands/rpc.d.ts +3 -0
- package/dist/commands/rpc.js +33 -0
- package/dist/commands/rpc.js.map +1 -0
- package/dist/commands/run.d.ts +3 -0
- package/dist/commands/run.js +20 -0
- package/dist/commands/run.js.map +1 -0
- package/dist/commands/sessions.d.ts +3 -0
- package/dist/commands/sessions.js +161 -0
- package/dist/commands/sessions.js.map +1 -0
- package/dist/commands/unlock.d.ts +3 -0
- package/dist/commands/unlock.js +31 -0
- package/dist/commands/unlock.js.map +1 -0
- package/dist/errors.d.ts +31 -0
- package/dist/errors.js +22 -0
- package/dist/errors.js.map +1 -0
- package/dist/host.d.ts +61 -0
- package/dist/host.js +114 -0
- package/dist/host.js.map +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +11 -0
- package/dist/index.js.map +1 -0
- package/dist/io.d.ts +36 -0
- package/dist/io.js +18 -0
- package/dist/io.js.map +1 -0
- package/dist/live.d.ts +33 -0
- package/dist/live.js +100 -0
- package/dist/live.js.map +1 -0
- package/dist/meter.d.ts +50 -0
- package/dist/meter.js +91 -0
- package/dist/meter.js.map +1 -0
- package/dist/model.d.ts +12 -0
- package/dist/model.js +35 -0
- package/dist/model.js.map +1 -0
- package/dist/options.d.ts +30 -0
- package/dist/options.js +2 -0
- package/dist/options.js.map +1 -0
- package/dist/otlp.d.ts +28 -0
- package/dist/otlp.js +110 -0
- package/dist/otlp.js.map +1 -0
- package/dist/output.d.ts +18 -0
- package/dist/output.js +28 -0
- package/dist/output.js.map +1 -0
- package/dist/render.d.ts +18 -0
- package/dist/render.js +65 -0
- package/dist/render.js.map +1 -0
- package/dist/visible.d.ts +11 -0
- package/dist/visible.js +63 -0
- package/dist/visible.js.map +1 -0
- package/dist/watch.d.ts +63 -0
- package/dist/watch.js +219 -0
- package/dist/watch.js.map +1 -0
- package/llms.txt +31 -0
- package/package.json +43 -3
package/dist/ask.js
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { chainedCommands, commandOf } from "./command-lines.js";
|
|
2
|
+
import { visible } from "./visible.js";
|
|
3
|
+
/**
|
|
4
|
+
* What tells two calls apart: the tool and the input exactly as the call would run it. A key from the laid-out text
|
|
5
|
+
* would let two commands that run differently but read alike share one answer, so only identical calls group.
|
|
6
|
+
*/
|
|
7
|
+
function groupKey(request, input) {
|
|
8
|
+
return `${request.tool}\u0000${JSON.stringify(input) ?? request.inputHash}`;
|
|
9
|
+
}
|
|
10
|
+
/** The approvals grouped by tool and input, in the order they were asked; each clarification stands alone. */
|
|
11
|
+
export function groupRequests(requests, inputs) {
|
|
12
|
+
const groups = new Map();
|
|
13
|
+
for (const request of requests) {
|
|
14
|
+
const signed = request.params.request;
|
|
15
|
+
const input = inputs.get(signed.id);
|
|
16
|
+
const key = request.method === "clarification/request" || !inputs.has(signed.id)
|
|
17
|
+
? `request\u0000${signed.id}`
|
|
18
|
+
: groupKey(signed, input);
|
|
19
|
+
const group = groups.get(key);
|
|
20
|
+
if (group === undefined)
|
|
21
|
+
groups.set(key, { requests: [request], input });
|
|
22
|
+
else
|
|
23
|
+
group.requests.push(request);
|
|
24
|
+
}
|
|
25
|
+
return [...groups.values()];
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* The lines that describe a group's input: each chained command on its own line, or the input as JSON. The input's
|
|
29
|
+
* other fields follow the command as compact JSON, because they change what it does: `rm -rf build` with `cwd` set to
|
|
30
|
+
* `/` is not the command it reads as alone. A command whose quotes never close gets a warning line, since its split
|
|
31
|
+
* may hide a command inside the last line.
|
|
32
|
+
*/
|
|
33
|
+
export function inputLines(input) {
|
|
34
|
+
const command = commandOf(input);
|
|
35
|
+
if (command === undefined)
|
|
36
|
+
return [visible(JSON.stringify(input) ?? "(no input)")];
|
|
37
|
+
const parts = chainedCommands(command);
|
|
38
|
+
const lines = parts.map((part) => visible(`${part.operator} ${part.command}`.trim()));
|
|
39
|
+
if (parts.at(-1)?.unclosed === true) {
|
|
40
|
+
lines.push("(a quote or parenthesis never closes, so the last line may hold more than one command)");
|
|
41
|
+
}
|
|
42
|
+
const { command: _command, ...rest } = input;
|
|
43
|
+
if (Object.keys(rest).length > 0)
|
|
44
|
+
lines.push(`with ${visible(JSON.stringify(rest))}`);
|
|
45
|
+
return lines;
|
|
46
|
+
}
|
|
47
|
+
function describe(group) {
|
|
48
|
+
const [first] = group.requests;
|
|
49
|
+
const signed = first.params.request;
|
|
50
|
+
const count = group.requests.length;
|
|
51
|
+
const who = count === 1
|
|
52
|
+
? `${visible(signed.tool)} needs your approval`
|
|
53
|
+
: `${count} calls of ${visible(signed.tool)} need your approval`;
|
|
54
|
+
const reason = signed.reason === undefined ? "" : `: ${visible(signed.reason)}`;
|
|
55
|
+
const shown = group.input === undefined ? [`(input hash ${signed.inputHash})`] : inputLines(group.input);
|
|
56
|
+
return `${who}${reason}\n${shown.map((line) => ` ${line}\n`).join("")}`;
|
|
57
|
+
}
|
|
58
|
+
/** Reads `y` or `n` until the person gives one, or `undefined` once input ends. */
|
|
59
|
+
async function readDecision(io) {
|
|
60
|
+
for (;;) {
|
|
61
|
+
io.error("Allow? [y/n] ");
|
|
62
|
+
const line = await io.readLine();
|
|
63
|
+
if (line === undefined)
|
|
64
|
+
return undefined;
|
|
65
|
+
const word = line.trim().toLowerCase();
|
|
66
|
+
if (word === "y" || word === "yes")
|
|
67
|
+
return "allow";
|
|
68
|
+
if (word === "n" || word === "no")
|
|
69
|
+
return "deny";
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
async function askClarification(io, watch, request) {
|
|
73
|
+
const { question } = request.params.request;
|
|
74
|
+
io.error(`The agent asks: ${question === undefined ? "(no question)" : visible(question)}\n`);
|
|
75
|
+
for (;;) {
|
|
76
|
+
io.error("answer> ");
|
|
77
|
+
const line = await io.readLine();
|
|
78
|
+
if (line === undefined)
|
|
79
|
+
return false;
|
|
80
|
+
if (line.trim() === "")
|
|
81
|
+
continue;
|
|
82
|
+
watch.answer(request, { requestId: request.params.request.id, answer: line });
|
|
83
|
+
return true;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Asks about every request waiting on `watch`, group by group, and sends each answer. Resolves `false` when input
|
|
88
|
+
* ends first, leaving the unanswered requests waiting in the log for `resume`.
|
|
89
|
+
*/
|
|
90
|
+
export async function askPerson(io, watch) {
|
|
91
|
+
for (const group of groupRequests([...watch.asked.values()], watch.inputs)) {
|
|
92
|
+
const [first] = group.requests;
|
|
93
|
+
if (first?.method === "clarification/request") {
|
|
94
|
+
if (!(await askClarification(io, watch, first)))
|
|
95
|
+
return false;
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
io.error(describe(group));
|
|
99
|
+
const decision = await readDecision(io);
|
|
100
|
+
if (decision === undefined)
|
|
101
|
+
return false;
|
|
102
|
+
for (const request of group.requests) {
|
|
103
|
+
watch.answer(request, { requestId: request.params.request.id, decision });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
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,MAAM,QAAQ,GAAG,MAAM,YAAY,CAAC,EAAE,CAAC,CAAC;QACxC,IAAI,QAAQ,KAAK,SAAS;YAAE,OAAO,KAAK,CAAC;QACzC,KAAK,MAAM,OAAO,IAAI,KAAK,CAAC,QAAQ,EAAE,CAAC;YACrC,KAAK,CAAC,MAAM,CAAC,OAAO,EAAE,EAAE,SAAS,EAAE,OAAO,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,EAAE,QAAQ,EAAE,CAAC,CAAC;QAC5E,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["/**\n * Asks the person at the terminal about the requests a turn paused on. Calls of one tool with the same input are shown\n * as one group and take one answer, and a chained command is shown one command per line, so an approver sees every\n * command an approval would run. Everything the model or the log supplied passes through `visible()` on its way to\n * the terminal, so a control character in it can't rewrite the prompt the approver reads.\n */\nimport type { SignedPendingRequest } from \"@buildanagent/sdk\";\nimport { chainedCommands, commandOf } from \"./command-lines.js\";\nimport type { CliIo } from \"./io.js\";\nimport { visible } from \"./visible.js\";\nimport type { PersonRequest, SessionWatch } from \"./watch.js\";\n\n/** Several requests that one answer settles. */\ninterface Group {\n readonly requests: PersonRequest[];\n readonly input: unknown;\n}\n\n/**\n * What tells two calls apart: the tool and the input exactly as the call would run it. A key from the laid-out text\n * would let two commands that run differently but read alike share one answer, so only identical calls group.\n */\nfunction groupKey(request: SignedPendingRequest, input: unknown): string {\n return `${request.tool}\\u0000${JSON.stringify(input) ?? request.inputHash}`;\n}\n\n/** The approvals grouped by tool and input, in the order they were asked; each clarification stands alone. */\nexport function groupRequests(requests: readonly PersonRequest[], inputs: ReadonlyMap<string, unknown>): Group[] {\n const groups = new Map<string, Group>();\n for (const request of requests) {\n const signed = request.params.request;\n const input = inputs.get(signed.id);\n const key =\n request.method === \"clarification/request\" || !inputs.has(signed.id)\n ? `request\\u0000${signed.id}`\n : groupKey(signed, input);\n const group = groups.get(key);\n if (group === undefined) groups.set(key, { requests: [request], input });\n else group.requests.push(request);\n }\n return [...groups.values()];\n}\n\n/**\n * The lines that describe a group's input: each chained command on its own line, or the input as JSON. The input's\n * other fields follow the command as compact JSON, because they change what it does: `rm -rf build` with `cwd` set to\n * `/` is not the command it reads as alone. A command whose quotes never close gets a warning line, since its split\n * may hide a command inside the last line.\n */\nexport function inputLines(input: unknown): string[] {\n const command = commandOf(input);\n if (command === undefined) return [visible(JSON.stringify(input) ?? \"(no input)\")];\n const parts = chainedCommands(command);\n const lines = parts.map((part) => visible(`${part.operator} ${part.command}`.trim()));\n if (parts.at(-1)?.unclosed === true) {\n lines.push(\"(a quote or parenthesis never closes, so the last line may hold more than one command)\");\n }\n const { command: _command, ...rest } = input as Record<string, unknown>;\n if (Object.keys(rest).length > 0) lines.push(`with ${visible(JSON.stringify(rest))}`);\n return lines;\n}\n\nfunction describe(group: Group): string {\n const [first] = group.requests;\n const signed = (first as PersonRequest).params.request;\n const count = group.requests.length;\n const who =\n count === 1\n ? `${visible(signed.tool)} needs your approval`\n : `${count} calls of ${visible(signed.tool)} need your approval`;\n const reason = signed.reason === undefined ? \"\" : `: ${visible(signed.reason)}`;\n const shown = group.input === undefined ? [`(input hash ${signed.inputHash})`] : inputLines(group.input);\n return `${who}${reason}\\n${shown.map((line) => ` ${line}\\n`).join(\"\")}`;\n}\n\n/** Reads `y` or `n` until the person gives one, or `undefined` once input ends. */\nasync function readDecision(io: CliIo): Promise<\"allow\" | \"deny\" | undefined> {\n for (;;) {\n io.error(\"Allow? [y/n] \");\n const line = await io.readLine();\n if (line === undefined) return undefined;\n const word = line.trim().toLowerCase();\n if (word === \"y\" || word === \"yes\") return \"allow\";\n if (word === \"n\" || word === \"no\") return \"deny\";\n }\n}\n\nasync function askClarification(io: CliIo, watch: SessionWatch, request: PersonRequest): Promise<boolean> {\n const { question } = request.params.request;\n io.error(`The agent asks: ${question === undefined ? \"(no question)\" : visible(question)}\\n`);\n for (;;) {\n io.error(\"answer> \");\n const line = await io.readLine();\n if (line === undefined) return false;\n if (line.trim() === \"\") continue;\n watch.answer(request, { requestId: request.params.request.id, answer: line });\n return true;\n }\n}\n\n/**\n * Asks about every request waiting on `watch`, group by group, and sends each answer. Resolves `false` when input\n * ends first, leaving the unanswered requests waiting in the log for `resume`.\n */\nexport async function askPerson(io: CliIo, watch: SessionWatch): Promise<boolean> {\n for (const group of groupRequests([...watch.asked.values()], watch.inputs)) {\n const [first] = group.requests;\n if (first?.method === \"clarification/request\") {\n if (!(await askClarification(io, watch, first))) return false;\n continue;\n }\n io.error(describe(group));\n const decision = await readDecision(io);\n if (decision === undefined) return false;\n for (const request of group.requests) {\n watch.answer(request, { requestId: request.params.request.id, decision });\n }\n }\n return true;\n}\n"]}
|
package/dist/bin.d.ts
ADDED
package/dist/bin.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The `buildanagent` command: it hands the process's arguments, streams, environment and folder to `runCli()` and
|
|
3
|
+
// exits with the status it returns. Everything else lives in modules a test can drive without a process. `tsc` keeps
|
|
4
|
+
// the first line, which makes `dist/bin.js` run as a Node script from the `bin` link a package manager makes.
|
|
5
|
+
import process from "node:process";
|
|
6
|
+
import { linesOf, runCli } from "./index.js";
|
|
7
|
+
const lines = linesOf(process.stdin)[Symbol.asyncIterator]();
|
|
8
|
+
const status = await runCli(process.argv.slice(2), {
|
|
9
|
+
io: {
|
|
10
|
+
write: (text) => process.stdout.write(text),
|
|
11
|
+
error: (text) => process.stderr.write(text),
|
|
12
|
+
readLine: async () => {
|
|
13
|
+
const next = await lines.next();
|
|
14
|
+
return next.done === true ? undefined : next.value;
|
|
15
|
+
},
|
|
16
|
+
env: process.env,
|
|
17
|
+
cwd: process.cwd(),
|
|
18
|
+
// Only `rpc` reads these, and the line reader above starts reading standard input only when a command asks for
|
|
19
|
+
// a line, so the two never share it.
|
|
20
|
+
streams: { input: process.stdin, output: process.stdout },
|
|
21
|
+
},
|
|
22
|
+
});
|
|
23
|
+
process.exitCode = status;
|
|
24
|
+
// A chat that ended on `/exit` leaves standard input open, which would keep the process alive.
|
|
25
|
+
process.stdin.destroy();
|
|
26
|
+
//# sourceMappingURL=bin.js.map
|
package/dist/bin.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bin.js","sourceRoot":"","sources":["../src/bin.ts"],"names":[],"mappings":";AACA,kHAAkH;AAClH,qHAAqH;AACrH,8GAA8G;AAC9G,OAAO,OAAO,MAAM,cAAc,CAAC;AACnC,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAC;AAE7C,MAAM,KAAK,GAAG,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,MAAM,CAAC,aAAa,CAAC,EAAE,CAAC;AAE7D,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE;IACjD,EAAE,EAAE;QACF,KAAK,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC;QAC3C,KAAK,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC;QAC3C,QAAQ,EAAE,KAAK,IAAI,EAAE;YACnB,MAAM,IAAI,GAAG,MAAM,KAAK,CAAC,IAAI,EAAE,CAAC;YAChC,OAAO,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC;QACrD,CAAC;QACD,GAAG,EAAE,OAAO,CAAC,GAAG;QAChB,GAAG,EAAE,OAAO,CAAC,GAAG,EAAE;QAClB,+GAA+G;QAC/G,qCAAqC;QACrC,OAAO,EAAE,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE;KAC1D;CACF,CAAC,CAAC;AACH,OAAO,CAAC,QAAQ,GAAG,MAAM,CAAC;AAC1B,+FAA+F;AAC/F,OAAO,CAAC,KAAK,CAAC,OAAO,EAAE,CAAC","sourcesContent":["#!/usr/bin/env node\n// The `buildanagent` command: it hands the process's arguments, streams, environment and folder to `runCli()` and\n// exits with the status it returns. Everything else lives in modules a test can drive without a process. `tsc` keeps\n// the first line, which makes `dist/bin.js` run as a Node script from the `bin` link a package manager makes.\nimport process from \"node:process\";\nimport { linesOf, runCli } from \"./index.js\";\n\nconst lines = linesOf(process.stdin)[Symbol.asyncIterator]();\n\nconst status = await runCli(process.argv.slice(2), {\n io: {\n write: (text) => process.stdout.write(text),\n error: (text) => process.stderr.write(text),\n readLine: async () => {\n const next = await lines.next();\n return next.done === true ? undefined : next.value;\n },\n env: process.env,\n cwd: process.cwd(),\n // Only `rpc` reads these, and the line reader above starts reading standard input only when a command asks for\n // a line, so the two never share it.\n streams: { input: process.stdin, output: process.stdout },\n },\n});\nprocess.exitCode = status;\n// A chat that ended on `/exit` leaves standard input open, which would keep the process alive.\nprocess.stdin.destroy();\n"]}
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { CliOptions } from "./options.js";
|
|
2
|
+
/** The help `--help` prints. */
|
|
3
|
+
export declare const HELP = "Usage: buildanagent <command> [options]\n\nRuns the buildanagent harness in a terminal. Nothing leaves this machine unless\n--model names a provider or --otlp-endpoint names a collector.\n\nCommands:\n run <prompt> Run one turn and exit: 0 when done, 3 when it waits\n for a person, 1 otherwise.\n chat Start a session and chat, one line per turn.\n resume <session> Chat in a stored session, answering what it waits on.\n sessions list List the stored sessions.\n sessions show <session> Print every entry of a session's log.\n sessions search <text> Find the messages that hold a text.\n sessions replay <session> Play a session back from its log, with no model call.\n session unlock <session> --force\n Remove a session's writer lock.\n keys rotate Add a new approval key and make it current.\n keys prune Remove the approval keys no waiting request names.\n rpc Serve the protocol as JSON-RPC lines over standard\n input and output, until input ends. It\n authenticates nobody: whoever holds the streams\n acts as the session's user.\n\nOptions:\n --model <provider>:<id> The model to run, such as anthropic:claude-sonnet-5-5\n (key from ANTHROPIC_API_KEY) or openai:<id>\n (key from OPENAI_API_KEY).\n --json Print one JSON object per line on standard output.\n --budget <usd> Stop each turn, and each resume after an answer,\n before it spends more; warn at 80%. It caps each\n turn, not the session.\n --state-dir <folder> Where sessions, locks and keys live. Default\n $XDG_STATE_HOME/buildanagent or\n ~/.local/state/buildanagent.\n --otlp-endpoint <url> Send OpenTelemetry spans, without content, here.\n --force Confirm session unlock.\n -h, --help Print this help and exit.\n";
|
|
4
|
+
/**
|
|
5
|
+
* Runs the `buildanagent` command line `argv`, the arguments after the program's name, and resolves with the exit
|
|
6
|
+
* status. It writes only through `options.io`, and it opens a connection only to the provider `--model` names and to
|
|
7
|
+
* the collector `--otlp-endpoint` names. An error that is not a `CliError` rejects.
|
|
8
|
+
*/
|
|
9
|
+
export declare function runCli(argv: readonly string[], options: CliOptions): Promise<number>;
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `runCli()`: reads the command line, runs one command and returns its exit status. A mistake in the command line is
|
|
3
|
+
* reported with the help and exits 2; any other `CliError` is reported on one line and exits 2 as well, because each
|
|
4
|
+
* is something the caller can fix before running again.
|
|
5
|
+
*/
|
|
6
|
+
import { parseArgs } from "./args.js";
|
|
7
|
+
import { chatCommand, resumeCommand } from "./commands/chat.js";
|
|
8
|
+
import { keysCommand } from "./commands/keys.js";
|
|
9
|
+
import { rpcCommand } from "./commands/rpc.js";
|
|
10
|
+
import { runCommand } from "./commands/run.js";
|
|
11
|
+
import { sessionsCommand } from "./commands/sessions.js";
|
|
12
|
+
import { unlockCommand } from "./commands/unlock.js";
|
|
13
|
+
import { CliError, isCliError } from "./errors.js";
|
|
14
|
+
import { statePaths, stateRoot } from "./host.js";
|
|
15
|
+
/** The help `--help` prints. */
|
|
16
|
+
export const HELP = `Usage: buildanagent <command> [options]
|
|
17
|
+
|
|
18
|
+
Runs the buildanagent harness in a terminal. Nothing leaves this machine unless
|
|
19
|
+
--model names a provider or --otlp-endpoint names a collector.
|
|
20
|
+
|
|
21
|
+
Commands:
|
|
22
|
+
run <prompt> Run one turn and exit: 0 when done, 3 when it waits
|
|
23
|
+
for a person, 1 otherwise.
|
|
24
|
+
chat Start a session and chat, one line per turn.
|
|
25
|
+
resume <session> Chat in a stored session, answering what it waits on.
|
|
26
|
+
sessions list List the stored sessions.
|
|
27
|
+
sessions show <session> Print every entry of a session's log.
|
|
28
|
+
sessions search <text> Find the messages that hold a text.
|
|
29
|
+
sessions replay <session> Play a session back from its log, with no model call.
|
|
30
|
+
session unlock <session> --force
|
|
31
|
+
Remove a session's writer lock.
|
|
32
|
+
keys rotate Add a new approval key and make it current.
|
|
33
|
+
keys prune Remove the approval keys no waiting request names.
|
|
34
|
+
rpc Serve the protocol as JSON-RPC lines over standard
|
|
35
|
+
input and output, until input ends. It
|
|
36
|
+
authenticates nobody: whoever holds the streams
|
|
37
|
+
acts as the session's user.
|
|
38
|
+
|
|
39
|
+
Options:
|
|
40
|
+
--model <provider>:<id> The model to run, such as anthropic:claude-sonnet-5-5
|
|
41
|
+
(key from ANTHROPIC_API_KEY) or openai:<id>
|
|
42
|
+
(key from OPENAI_API_KEY).
|
|
43
|
+
--json Print one JSON object per line on standard output.
|
|
44
|
+
--budget <usd> Stop each turn, and each resume after an answer,
|
|
45
|
+
before it spends more; warn at 80%. It caps each
|
|
46
|
+
turn, not the session.
|
|
47
|
+
--state-dir <folder> Where sessions, locks and keys live. Default
|
|
48
|
+
$XDG_STATE_HOME/buildanagent or
|
|
49
|
+
~/.local/state/buildanagent.
|
|
50
|
+
--otlp-endpoint <url> Send OpenTelemetry spans, without content, here.
|
|
51
|
+
--force Confirm session unlock.
|
|
52
|
+
-h, --help Print this help and exit.
|
|
53
|
+
`;
|
|
54
|
+
const COMMANDS = {
|
|
55
|
+
run: runCommand,
|
|
56
|
+
chat: (context, words) => {
|
|
57
|
+
if (words.length > 0)
|
|
58
|
+
throw new CliError("usage", "chat takes no arguments; use resume <session> for a stored one");
|
|
59
|
+
return chatCommand(context);
|
|
60
|
+
},
|
|
61
|
+
resume: resumeCommand,
|
|
62
|
+
sessions: sessionsCommand,
|
|
63
|
+
session: unlockCommand,
|
|
64
|
+
keys: keysCommand,
|
|
65
|
+
rpc: rpcCommand,
|
|
66
|
+
};
|
|
67
|
+
async function dispatch(argv, options) {
|
|
68
|
+
const { positionals, flags } = parseArgs(argv);
|
|
69
|
+
const [name, ...words] = positionals;
|
|
70
|
+
if (name === undefined || flags.help) {
|
|
71
|
+
options.io.write(HELP);
|
|
72
|
+
return 0;
|
|
73
|
+
}
|
|
74
|
+
const command = COMMANDS[name];
|
|
75
|
+
if (command === undefined || !Object.hasOwn(COMMANDS, name)) {
|
|
76
|
+
throw new CliError("usage", `unknown command ${JSON.stringify(name)}`);
|
|
77
|
+
}
|
|
78
|
+
const paths = statePaths(stateRoot(flags.stateDir, options.io.env));
|
|
79
|
+
const context = {
|
|
80
|
+
io: options.io,
|
|
81
|
+
flags,
|
|
82
|
+
options,
|
|
83
|
+
hostOptions: {
|
|
84
|
+
paths,
|
|
85
|
+
cwd: options.io.cwd,
|
|
86
|
+
...(options.tools === undefined ? {} : { tools: options.tools }),
|
|
87
|
+
...(options.rules === undefined ? {} : { rules: options.rules }),
|
|
88
|
+
...(flags.budgetUsd === undefined ? {} : { budgetUsd: flags.budgetUsd }),
|
|
89
|
+
...(flags.otlpEndpoint === undefined ? {} : { otlpEndpoint: flags.otlpEndpoint }),
|
|
90
|
+
...(options.fetch === undefined ? {} : { fetch: options.fetch }),
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
return await command(context, words);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Runs the `buildanagent` command line `argv`, the arguments after the program's name, and resolves with the exit
|
|
97
|
+
* status. It writes only through `options.io`, and it opens a connection only to the provider `--model` names and to
|
|
98
|
+
* the collector `--otlp-endpoint` names. An error that is not a `CliError` rejects.
|
|
99
|
+
*/
|
|
100
|
+
export async function runCli(argv, options) {
|
|
101
|
+
try {
|
|
102
|
+
return await dispatch(argv, options);
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
if (!isCliError(error))
|
|
106
|
+
throw error;
|
|
107
|
+
options.io.error(`buildanagent: ${error.message}\n${error.code === "usage" ? `\n${HELP}` : ""}`);
|
|
108
|
+
return 2;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
//# sourceMappingURL=cli.js.map
|
package/dist/cli.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli.js","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAChE,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AACzD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AACrD,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACnD,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAGlD,gCAAgC;AAChC,MAAM,CAAC,MAAM,IAAI,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqCnB,CAAC;AAIF,MAAM,QAAQ,GAAsC;IAClD,GAAG,EAAE,UAAU;IACf,IAAI,EAAE,CAAC,OAAO,EAAE,KAAK,EAAE,EAAE;QACvB,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC;YAAE,MAAM,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its exit status. A mistake in the command line is\n * reported with the help and exits 2; any other `CliError` is reported on one line and exits 2 as well, because each\n * is something the caller can fix before running again.\n */\nimport { parseArgs } from \"./args.js\";\nimport { chatCommand, resumeCommand } from \"./commands/chat.js\";\nimport { keysCommand } from \"./commands/keys.js\";\nimport { rpcCommand } from \"./commands/rpc.js\";\nimport { runCommand } from \"./commands/run.js\";\nimport { sessionsCommand } from \"./commands/sessions.js\";\nimport { unlockCommand } from \"./commands/unlock.js\";\nimport { CliError, isCliError } from \"./errors.js\";\nimport { statePaths, stateRoot } from \"./host.js\";\nimport type { CliOptions, CommandContext } from \"./options.js\";\n\n/** The help `--help` prints. */\nexport const HELP = `Usage: buildanagent <command> [options]\n\nRuns the buildanagent harness in a terminal. Nothing leaves this machine unless\n--model names a provider or --otlp-endpoint names a collector.\n\nCommands:\n run <prompt> Run one turn and exit: 0 when done, 3 when it waits\n for a person, 1 otherwise.\n chat Start a session and chat, one line per turn.\n resume <session> Chat in a stored session, answering what it waits on.\n sessions list List the stored sessions.\n sessions show <session> Print every entry of a session's log.\n sessions search <text> Find the messages that hold a text.\n sessions replay <session> Play a session back from its log, with no model call.\n session unlock <session> --force\n Remove a session's writer lock.\n keys rotate Add a new approval key and make it current.\n keys prune Remove the approval keys no waiting request names.\n rpc Serve the protocol as JSON-RPC lines over standard\n input and output, until input ends. It\n authenticates nobody: whoever holds the streams\n acts as the session's user.\n\nOptions:\n --model <provider>:<id> The model to run, such as anthropic:claude-sonnet-5-5\n (key from ANTHROPIC_API_KEY) or openai:<id>\n (key from OPENAI_API_KEY).\n --json Print one JSON object per line on standard output.\n --budget <usd> Stop each turn, and each resume after an answer,\n before it spends more; warn at 80%. It caps each\n turn, not the session.\n --state-dir <folder> Where sessions, locks and keys live. Default\n $XDG_STATE_HOME/buildanagent or\n ~/.local/state/buildanagent.\n --otlp-endpoint <url> Send OpenTelemetry spans, without content, here.\n --force Confirm session unlock.\n -h, --help Print this help and exit.\n`;\n\ntype Command = (context: CommandContext, words: readonly string[]) => Promise<number> | number;\n\nconst COMMANDS: Readonly<Record<string, Command>> = {\n run: runCommand,\n chat: (context, words) => {\n if (words.length > 0) throw new CliError(\"usage\", \"chat takes no arguments; use resume <session> for a stored one\");\n return chatCommand(context);\n },\n resume: resumeCommand,\n sessions: sessionsCommand,\n session: unlockCommand,\n keys: keysCommand,\n rpc: rpcCommand,\n};\n\nasync function dispatch(argv: readonly string[], options: CliOptions): Promise<number> {\n const { positionals, flags } = parseArgs(argv);\n const [name, ...words] = positionals;\n if (name === undefined || flags.help) {\n options.io.write(HELP);\n return 0;\n }\n const command = COMMANDS[name];\n if (command === undefined || !Object.hasOwn(COMMANDS, name)) {\n throw new CliError(\"usage\", `unknown command ${JSON.stringify(name)}`);\n }\n const paths = statePaths(stateRoot(flags.stateDir, options.io.env));\n const context: CommandContext = {\n io: options.io,\n flags,\n options,\n hostOptions: {\n paths,\n cwd: options.io.cwd,\n ...(options.tools === undefined ? {} : { tools: options.tools }),\n ...(options.rules === undefined ? {} : { rules: options.rules }),\n ...(flags.budgetUsd === undefined ? {} : { budgetUsd: flags.budgetUsd }),\n ...(flags.otlpEndpoint === undefined ? {} : { otlpEndpoint: flags.otlpEndpoint }),\n ...(options.fetch === undefined ? {} : { fetch: options.fetch }),\n },\n };\n return await command(context, words);\n}\n\n/**\n * Runs the `buildanagent` command line `argv`, the arguments after the program's name, and resolves with the exit\n * status. It writes only through `options.io`, and it opens a connection only to the provider `--model` names and to\n * the collector `--otlp-endpoint` names. An error that is not a `CliError` rejects.\n */\nexport async function runCli(argv: readonly string[], options: CliOptions): Promise<number> {\n try {\n return await dispatch(argv, options);\n } catch (error) {\n if (!isCliError(error)) throw error;\n options.io.error(`buildanagent: ${error.message}\\n${error.code === \"usage\" ? `\\n${HELP}` : \"\"}`);\n return 2;\n }\n}\n"]}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shows a shell command the way an approver should read it: one command per line, with the operator that chains it
|
|
3
|
+
* in front, and the spaces outside quotes and substitutions normalised. `git status && curl x | sh` reads as three
|
|
4
|
+
* lines, so a second command can't hide at the end of a long first one. It only lays the text out; the permission
|
|
5
|
+
* pipeline decides. The text it returns may still hold control characters, so a caller that prints it passes it
|
|
6
|
+
* through `visible()` first.
|
|
7
|
+
*/
|
|
8
|
+
/** One command of a chain, with the operator that joins it to the one before (empty for the first). */
|
|
9
|
+
export interface ChainedCommand {
|
|
10
|
+
readonly operator: string;
|
|
11
|
+
readonly command: string;
|
|
12
|
+
/**
|
|
13
|
+
* Set on the last command when the text ends inside a quote or a parenthesis the scan never saw closed, such as a
|
|
14
|
+
* here-document's `it's`. The shell may read that text differently, so the split before it can't be trusted.
|
|
15
|
+
*/
|
|
16
|
+
readonly unclosed?: true;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Splits `command` at its list and pipe operators outside quotes, escapes, substitutions and comments. A comment runs
|
|
20
|
+
* to the end of its line, and a quote inside it opens nothing, as in the shell: otherwise the `'` of `# it's` would
|
|
21
|
+
* hide the commands on the lines after it inside one displayed line.
|
|
22
|
+
*/
|
|
23
|
+
export declare function chainedCommands(command: string): ChainedCommand[];
|
|
24
|
+
/** The command a tool call's input carries in its `command` field, when it has one. */
|
|
25
|
+
export declare function commandOf(input: unknown): string | undefined;
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shows a shell command the way an approver should read it: one command per line, with the operator that chains it
|
|
3
|
+
* in front, and the spaces outside quotes and substitutions normalised. `git status && curl x | sh` reads as three
|
|
4
|
+
* lines, so a second command can't hide at the end of a long first one. It only lays the text out; the permission
|
|
5
|
+
* pipeline decides. The text it returns may still hold control characters, so a caller that prints it passes it
|
|
6
|
+
* through `visible()` first.
|
|
7
|
+
*/
|
|
8
|
+
const OPERATORS = ["&&", "||", ";;", ";", "|&", "|", "&", "\n"];
|
|
9
|
+
/**
|
|
10
|
+
* The words of `text` outside quotes and substitutions joined by single spaces. Quoted text, backticks and the inside
|
|
11
|
+
* of `$(...)` and `(...)` are kept as written, line breaks included, because the shell runs a line break there as a
|
|
12
|
+
* separate command: collapsing it would show `echo $(id\nrm -rf ~)` as one command. A backslash outside single quotes
|
|
13
|
+
* is kept with the character after it, so `foo\ bar` keeps its escaped space and `"a\"b"` stays one quoted word. Only
|
|
14
|
+
* a space or a tab is a blank, as it is to the shell: a no-break space is part of a word and is kept.
|
|
15
|
+
*/
|
|
16
|
+
function normalised(text) {
|
|
17
|
+
let out = "";
|
|
18
|
+
const scan = newScan();
|
|
19
|
+
let space = false;
|
|
20
|
+
// No trim: leading and trailing spaces are dropped by the loop, and an escaped trailing space is kept.
|
|
21
|
+
for (let at = 0; at < text.length;) {
|
|
22
|
+
const token = tokenAt(text, at, scan.open.at(-1));
|
|
23
|
+
at += token.length;
|
|
24
|
+
if (outside(scan) && (token === " " || token === "\t")) {
|
|
25
|
+
space = true;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
if (space && out !== "")
|
|
29
|
+
out += " ";
|
|
30
|
+
space = false;
|
|
31
|
+
out += token;
|
|
32
|
+
if (token.length === 1)
|
|
33
|
+
step(scan, token);
|
|
34
|
+
else
|
|
35
|
+
stepEscaped(scan);
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The text at `at` that stays together: a backslash outside single quotes with the character it escapes,
|
|
41
|
+
* or one character.
|
|
42
|
+
*/
|
|
43
|
+
const tokenAt = (text, at, quote) => text[at] === "\\" && quote !== "'" ? text.slice(at, at + 2) : text[at];
|
|
44
|
+
/**
|
|
45
|
+
* The operator that starts at `at` outside quotes, or `undefined`. `afterRedirect` says the character before is an
|
|
46
|
+
* unescaped `<` or `>`, so the `&` of `2>&1` or `<&3` and the `|` of `>|` belong to a redirection, as does the `&` of
|
|
47
|
+
* `&>` and `&>>`; none of them ends a command.
|
|
48
|
+
*/
|
|
49
|
+
function operatorAt(text, at, afterRedirect) {
|
|
50
|
+
const found = OPERATORS.find((operator) => text.startsWith(operator, at));
|
|
51
|
+
if (found === "&" && (afterRedirect || text[at + 1] === ">"))
|
|
52
|
+
return undefined;
|
|
53
|
+
if (found === "|" && afterRedirect)
|
|
54
|
+
return undefined;
|
|
55
|
+
return found;
|
|
56
|
+
}
|
|
57
|
+
const newScan = () => ({ open: [], last: "" });
|
|
58
|
+
/** Whether the scan is outside every quote and parenthesis. */
|
|
59
|
+
const outside = (scan) => scan.open.length === 0;
|
|
60
|
+
/** Whether the scan is inside a quote, rather than in a parenthesis or outside. */
|
|
61
|
+
const quoted = (scan) => ['"', "'", "`"].includes(scan.open.at(-1) ?? "");
|
|
62
|
+
/** Moves the scan past `char` inside double quotes, where only `"`, a backtick and `$(` open or close anything. */
|
|
63
|
+
function stepDoubleQuoted(scan, char, last) {
|
|
64
|
+
if (char === '"')
|
|
65
|
+
scan.open.pop();
|
|
66
|
+
else if (char === "`" || (char === "(" && last === "$"))
|
|
67
|
+
scan.open.push(char);
|
|
68
|
+
}
|
|
69
|
+
/** Moves the scan past `char` outside quotes, and says whether `char` is outside every parenthesis too. */
|
|
70
|
+
function stepUnquoted(scan, char) {
|
|
71
|
+
if (char === '"' || char === "'" || char === "`" || char === "(")
|
|
72
|
+
scan.open.push(char);
|
|
73
|
+
else if (char === ")") {
|
|
74
|
+
if (scan.open.at(-1) === "(")
|
|
75
|
+
scan.open.pop();
|
|
76
|
+
}
|
|
77
|
+
else
|
|
78
|
+
return outside(scan);
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
/** Moves the scan past `char`, and says whether `char` is outside every quote and parenthesis. */
|
|
82
|
+
function step(scan, char) {
|
|
83
|
+
const last = scan.last;
|
|
84
|
+
scan.last = char;
|
|
85
|
+
const inner = scan.open.at(-1);
|
|
86
|
+
if (inner === "'" || inner === "`") {
|
|
87
|
+
if (char === inner)
|
|
88
|
+
scan.open.pop();
|
|
89
|
+
return false;
|
|
90
|
+
}
|
|
91
|
+
if (inner === '"') {
|
|
92
|
+
stepDoubleQuoted(scan, char, last);
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
return stepUnquoted(scan, char);
|
|
96
|
+
}
|
|
97
|
+
/** Moves the scan past a character a backslash escaped, which is a plain character and opens or closes nothing. */
|
|
98
|
+
function stepEscaped(scan) {
|
|
99
|
+
scan.last = "";
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Whether a comment starts at `at`: an unquoted `#` that starts a word, not one inside a word such as `$#` or `a#b`.
|
|
103
|
+
* `escaped` is the index of the last character a backslash escaped, which is part of a word.
|
|
104
|
+
*/
|
|
105
|
+
const startsComment = (command, at, scan, escaped) => !quoted(scan) &&
|
|
106
|
+
command[at] === "#" &&
|
|
107
|
+
(at === 0 || (escaped !== at - 1 && " \t\n;&|()".includes(command[at - 1])));
|
|
108
|
+
/** The index just before the line break that ends the comment at `at`, which the next pass reads as an operator. */
|
|
109
|
+
function commentEnd(command, at) {
|
|
110
|
+
const end = command.indexOf("\n", at);
|
|
111
|
+
return (end < 0 ? command.length : end) - 1;
|
|
112
|
+
}
|
|
113
|
+
/** Whether the character before `at` is an unescaped `<` or `>`, so what starts at `at` belongs to a redirection. */
|
|
114
|
+
const afterRedirect = (command, at, escaped) => at > 0 && escaped !== at - 1 && (command[at - 1] === ">" || command[at - 1] === "<");
|
|
115
|
+
/**
|
|
116
|
+
* Splits `command` at its list and pipe operators outside quotes, escapes, substitutions and comments. A comment runs
|
|
117
|
+
* to the end of its line, and a quote inside it opens nothing, as in the shell: otherwise the `'` of `# it's` would
|
|
118
|
+
* hide the commands on the lines after it inside one displayed line.
|
|
119
|
+
*/
|
|
120
|
+
export function chainedCommands(command) {
|
|
121
|
+
const parts = [];
|
|
122
|
+
const scan = newScan();
|
|
123
|
+
let operator = "";
|
|
124
|
+
let start = 0;
|
|
125
|
+
const close = (end, next) => {
|
|
126
|
+
const text = normalised(command.slice(start, end));
|
|
127
|
+
if (text !== "")
|
|
128
|
+
parts.push({ operator, command: text });
|
|
129
|
+
operator = next;
|
|
130
|
+
};
|
|
131
|
+
// The index of the last character a backslash escaped, which is a plain character and never a redirection.
|
|
132
|
+
let escaped = -1;
|
|
133
|
+
for (let at = 0; at < command.length; at++) {
|
|
134
|
+
const char = command[at];
|
|
135
|
+
if (char === "\\" && scan.open.at(-1) !== "'") {
|
|
136
|
+
at += 1;
|
|
137
|
+
escaped = at;
|
|
138
|
+
stepEscaped(scan);
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
if (startsComment(command, at, scan, escaped)) {
|
|
142
|
+
at = commentEnd(command, at);
|
|
143
|
+
scan.last = "";
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
const found = step(scan, char) ? operatorAt(command, at, afterRedirect(command, at, escaped)) : undefined;
|
|
147
|
+
if (found === undefined)
|
|
148
|
+
continue;
|
|
149
|
+
close(at, found === "\n" ? ";" : found);
|
|
150
|
+
at += found.length - 1;
|
|
151
|
+
start = at + 1;
|
|
152
|
+
}
|
|
153
|
+
close(command.length, "");
|
|
154
|
+
const last = parts.at(-1);
|
|
155
|
+
if (last !== undefined && !outside(scan))
|
|
156
|
+
parts[parts.length - 1] = { ...last, unclosed: true };
|
|
157
|
+
return parts;
|
|
158
|
+
}
|
|
159
|
+
/** The command a tool call's input carries in its `command` field, when it has one. */
|
|
160
|
+
export function commandOf(input) {
|
|
161
|
+
if (typeof input !== "object" || input === null)
|
|
162
|
+
return undefined;
|
|
163
|
+
const command = input.command;
|
|
164
|
+
return typeof command === "string" ? command : undefined;
|
|
165
|
+
}
|
|
166
|
+
//# sourceMappingURL=command-lines.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"command-lines.js","sourceRoot":"","sources":["../src/command-lines.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,MAAM,SAAS,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,GAAG,EA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,CAAC;IAC1B,MAAM,IAAI,GAAG,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC;IAC1B,IAAI,IAAI,KAAK,SAAS,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;QAAE,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,GAAG,EAAE,GAAG,IAAI,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;IAChG,OAAO,KAAK,CAAC;AACf,CAAC;AAED,uFAAuF;AACvF,MAAM,UAAU,SAAS,CAAC,KAAc;IACtC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,SAAS,CAAC;IAClE,MAAM,OAAO,GAAI,KAA+B,CAAC,OAAO,CAAC;IACzD,OAAO,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC;AAC3D,CAAC","sourcesContent":["/**\n * Shows a shell command the way an approver should read it: one command per line, with the operator that chains it\n * in front, and the spaces outside quotes and substitutions normalised. `git status && curl x | sh` reads as three\n * lines, so a second command can't hide at the end of a long first one. It only lays the text out; the permission\n * pipeline decides. The text it returns may still hold control characters, so a caller that prints it passes it\n * through `visible()` first.\n */\n\nconst OPERATORS = [\"&&\", \"||\", \";;\", \";\", \"|&\", \"|\", \"&\", \"\\n\"] as const;\n\n/** One command of a chain, with the operator that joins it to the one before (empty for the first). */\nexport interface ChainedCommand {\n readonly operator: string;\n readonly command: string;\n /**\n * Set on the last command when the text ends inside a quote or a parenthesis the scan never saw closed, such as a\n * here-document's `it's`. The shell may read that text differently, so the split before it can't be trusted.\n */\n readonly unclosed?: true;\n}\n\n/**\n * The words of `text` outside quotes and substitutions joined by single spaces. Quoted text, backticks and the inside\n * of `$(...)` and `(...)` are kept as written, line breaks included, because the shell runs a line break there as a\n * separate command: collapsing it would show `echo $(id\\nrm -rf ~)` as one command. A backslash outside single quotes\n * is kept with the character after it, so `foo\\ bar` keeps its escaped space and `\"a\\\"b\"` stays one quoted word. Only\n * a space or a tab is a blank, as it is to the shell: a no-break space is part of a word and is kept.\n */\nfunction normalised(text: string): string {\n let out = \"\";\n const scan = newScan();\n let space = false;\n // No trim: leading and trailing spaces are dropped by the loop, and an escaped trailing space is kept.\n for (let at = 0; at < text.length; ) {\n const token = tokenAt(text, at, scan.open.at(-1));\n at += token.length;\n if (outside(scan) && (token === \" \" || token === \"\\t\")) {\n space = true;\n continue;\n }\n if (space && out !== \"\") out += \" \";\n space = false;\n out += token;\n if (token.length === 1) step(scan, token);\n else stepEscaped(scan);\n }\n return out;\n}\n\n/**\n * The text at `at` that stays together: a backslash outside single quotes with the character it escapes,\n * or one character.\n */\nconst tokenAt = (text: string, at: number, quote: string | undefined): string =>\n text[at] === \"\\\\\" && quote !== \"'\" ? text.slice(at, at + 2) : (text[at] as string);\n\n/**\n * The operator that starts at `at` outside quotes, or `undefined`. `afterRedirect` says the character before is an\n * unescaped `<` or `>`, so the `&` of `2>&1` or `<&3` and the `|` of `>|` belong to a redirection, as does the `&` of\n * `&>` and `&>>`; none of them ends a command.\n */\nfunction operatorAt(text: string, at: number, afterRedirect: boolean): string | undefined {\n const found = OPERATORS.find((operator) => text.startsWith(operator, at));\n if (found === \"&\" && (afterRedirect || text[at + 1] === \">\")) return undefined;\n if (found === \"|\" && afterRedirect) return undefined;\n return found;\n}\n\n/**\n * Where the scan of a command stands: the quotes and parentheses it is inside, innermost last, and the character it\n * read last, which is empty after an escape. Inside double quotes, `$(` opens a substitution whose own quotes nest, as\n * in the shell: `\"$(echo '\"')\"` is one word, and a flat scan would read its inner `\"` as the end of the outer quote.\n */\ninterface Scan {\n readonly open: string[];\n last: string;\n}\n\nconst newScan = (): Scan => ({ open: [], last: \"\" });\n\n/** Whether the scan is outside every quote and parenthesis. */\nconst outside = (scan: Scan): boolean => scan.open.length === 0;\n\n/** Whether the scan is inside a quote, rather than in a parenthesis or outside. */\nconst quoted = (scan: Scan): boolean => ['\"', \"'\", \"`\"].includes(scan.open.at(-1) ?? \"\");\n\n/** Moves the scan past `char` inside double quotes, where only `\"`, a backtick and `$(` open or close anything. */\nfunction stepDoubleQuoted(scan: Scan, char: string, last: string): void {\n if (char === '\"') scan.open.pop();\n else if (char === \"`\" || (char === \"(\" && last === \"$\")) scan.open.push(char);\n}\n\n/** Moves the scan past `char` outside quotes, and says whether `char` is outside every parenthesis too. */\nfunction stepUnquoted(scan: Scan, char: string): boolean {\n if (char === '\"' || char === \"'\" || char === \"`\" || char === \"(\") scan.open.push(char);\n else if (char === \")\") {\n if (scan.open.at(-1) === \"(\") scan.open.pop();\n } else return outside(scan);\n return false;\n}\n\n/** Moves the scan past `char`, and says whether `char` is outside every quote and parenthesis. */\nfunction step(scan: Scan, char: string): boolean {\n const last = scan.last;\n scan.last = char;\n const inner = scan.open.at(-1);\n if (inner === \"'\" || inner === \"`\") {\n if (char === inner) scan.open.pop();\n return false;\n }\n if (inner === '\"') {\n stepDoubleQuoted(scan, char, last);\n return false;\n }\n return stepUnquoted(scan, char);\n}\n\n/** Moves the scan past a character a backslash escaped, which is a plain character and opens or closes nothing. */\nfunction stepEscaped(scan: Scan): void {\n scan.last = \"\";\n}\n\n/**\n * Whether a comment starts at `at`: an unquoted `#` that starts a word, not one inside a word such as `$#` or `a#b`.\n * `escaped` is the index of the last character a backslash escaped, which is part of a word.\n */\nconst startsComment = (command: string, at: number, scan: Scan, escaped: number): boolean =>\n !quoted(scan) &&\n command[at] === \"#\" &&\n (at === 0 || (escaped !== at - 1 && \" \\t\\n;&|()\".includes(command[at - 1] as string)));\n\n/** The index just before the line break that ends the comment at `at`, which the next pass reads as an operator. */\nfunction commentEnd(command: string, at: number): number {\n const end = command.indexOf(\"\\n\", at);\n return (end < 0 ? command.length : end) - 1;\n}\n\n/** Whether the character before `at` is an unescaped `<` or `>`, so what starts at `at` belongs to a redirection. */\nconst afterRedirect = (command: string, at: number, escaped: number): boolean =>\n at > 0 && escaped !== at - 1 && (command[at - 1] === \">\" || command[at - 1] === \"<\");\n\n/**\n * Splits `command` at its list and pipe operators outside quotes, escapes, substitutions and comments. A comment runs\n * to the end of its line, and a quote inside it opens nothing, as in the shell: otherwise the `'` of `# it's` would\n * hide the commands on the lines after it inside one displayed line.\n */\nexport function chainedCommands(command: string): ChainedCommand[] {\n const parts: ChainedCommand[] = [];\n const scan = newScan();\n let operator = \"\";\n let start = 0;\n const close = (end: number, next: string) => {\n const text = normalised(command.slice(start, end));\n if (text !== \"\") parts.push({ operator, command: text });\n operator = next;\n };\n // The index of the last character a backslash escaped, which is a plain character and never a redirection.\n let escaped = -1;\n for (let at = 0; at < command.length; at++) {\n const char = command[at] as string;\n if (char === \"\\\\\" && scan.open.at(-1) !== \"'\") {\n at += 1;\n escaped = at;\n stepEscaped(scan);\n continue;\n }\n if (startsComment(command, at, scan, escaped)) {\n at = commentEnd(command, at);\n scan.last = \"\";\n continue;\n }\n const found = step(scan, char) ? operatorAt(command, at, afterRedirect(command, at, escaped)) : undefined;\n if (found === undefined) continue;\n close(at, found === \"\\n\" ? \";\" : found);\n at += found.length - 1;\n start = at + 1;\n }\n close(command.length, \"\");\n const last = parts.at(-1);\n if (last !== undefined && !outside(scan)) parts[parts.length - 1] = { ...last, unclosed: true };\n return parts;\n}\n\n/** The command a tool call's input carries in its `command` field, when it has one. */\nexport function commandOf(input: unknown): string | undefined {\n if (typeof input !== \"object\" || input === null) return undefined;\n const command = (input as { command?: unknown }).command;\n return typeof command === \"string\" ? command : undefined;\n}\n"]}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `buildanagent chat` and `buildanagent resume <session>`: a conversation, one line of input per turn. When a turn
|
|
3
|
+
* pauses for a person, the requests are asked about at the terminal and the turn goes on once they are answered.
|
|
4
|
+
* Resuming a session first asks about whatever it was left waiting on.
|
|
5
|
+
*/
|
|
6
|
+
import type { TurnResultSummary } from "@buildanagent/protocol";
|
|
7
|
+
import type { CliIo } from "../io.js";
|
|
8
|
+
import type { CommandContext } from "../options.js";
|
|
9
|
+
import { type SessionWatch } from "../watch.js";
|
|
10
|
+
/**
|
|
11
|
+
* Asks about each request the turn waits on and follows the resumes until the turn no longer waits, or until input
|
|
12
|
+
* ends or no answer of ours is left for a turn to settle, such as one another process settled first.
|
|
13
|
+
*/
|
|
14
|
+
export declare function settle(io: CliIo, watch: SessionWatch, first: TurnResultSummary): Promise<TurnResultSummary>;
|
|
15
|
+
/** Chats in a new session, or in the stored session `id`, until input ends or a line says `/exit`. */
|
|
16
|
+
export declare function chatCommand(context: CommandContext, id?: string): Promise<number>;
|
|
17
|
+
/** `resume <session>`: chats in a stored session. */
|
|
18
|
+
export declare function resumeCommand(context: CommandContext, words: readonly string[]): Promise<number>;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { askPerson } from "../ask.js";
|
|
2
|
+
import { CliError } from "../errors.js";
|
|
3
|
+
import { reportSettled, startLive, withLive } from "../live.js";
|
|
4
|
+
import { runTurn, WAITING_REASONS } from "../watch.js";
|
|
5
|
+
const QUIT = new Set(["/exit", "/quit"]);
|
|
6
|
+
/**
|
|
7
|
+
* Asks about each request the turn waits on and follows the resumes until the turn no longer waits, or until input
|
|
8
|
+
* ends or no answer of ours is left for a turn to settle, such as one another process settled first.
|
|
9
|
+
*/
|
|
10
|
+
export async function settle(io, watch, first) {
|
|
11
|
+
let result = first;
|
|
12
|
+
while (WAITING_REASONS.has(result.stopReason)) {
|
|
13
|
+
if (watch.asked.size > 0 && !(await askPerson(io, watch)))
|
|
14
|
+
return result;
|
|
15
|
+
if (!(await watch.settlePending()))
|
|
16
|
+
return result;
|
|
17
|
+
result = (await watch.nextSettled()).result;
|
|
18
|
+
}
|
|
19
|
+
return result;
|
|
20
|
+
}
|
|
21
|
+
async function converse(context, live) {
|
|
22
|
+
if (live.pending.length > 0) {
|
|
23
|
+
await live.watch.whenAsked(live.pending);
|
|
24
|
+
reportSettled(live, await settle(context.io, live.watch, { stopReason: "awaiting_approval", steps: 0, costUsd: null }));
|
|
25
|
+
}
|
|
26
|
+
for (;;) {
|
|
27
|
+
context.io.error("> ");
|
|
28
|
+
const line = await context.io.readLine();
|
|
29
|
+
if (line === undefined || QUIT.has(line.trim()))
|
|
30
|
+
return;
|
|
31
|
+
if (line.trim() === "")
|
|
32
|
+
continue;
|
|
33
|
+
const result = await runTurn(live.host.client, live.watch, line);
|
|
34
|
+
reportSettled(live, await settle(context.io, live.watch, result));
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
/** Chats in a new session, or in the stored session `id`, until input ends or a line says `/exit`. */
|
|
38
|
+
export async function chatCommand(context, id) {
|
|
39
|
+
const live = await startLive(context, true, id);
|
|
40
|
+
return withLive(live, async () => {
|
|
41
|
+
await converse(context, live);
|
|
42
|
+
return 0;
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
/** `resume <session>`: chats in a stored session. */
|
|
46
|
+
export function resumeCommand(context, words) {
|
|
47
|
+
const [id] = words;
|
|
48
|
+
if (id === undefined || words.length > 1)
|
|
49
|
+
throw new CliError("usage", "resume takes one session id");
|
|
50
|
+
return chatCommand(context, id);
|
|
51
|
+
}
|
|
52
|
+
//# sourceMappingURL=chat.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chat.js","sourceRoot":"","sources":["../../src/commands/chat.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AACtC,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAExC,OAAO,EAAa,aAAa,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE3E,OAAO,EAAE,OAAO,EAAqB,eAAe,EAAE,MAAM,aAAa,CAAC;AAE1E,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC;AAEzC;;;GAGG;AACH,MAAM,CAAC,KAAK,UAAU,MAAM,CAAC,EAAS,EA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AAO,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,CAAC,CAAC;QACjE,aAAa,CAAC,IAAI,EAAE,MAAM,MAAM,CAAC,OAAO,CAAC,EAAE,EAAE,IAAI,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC;IACpE,CAAC;AACH,CAAC;AAED,sGAAsG;AACtG,MAAM,CAAC,KAAK,UAAU,WAAW,CAAC,OAAuB,EAAE,EAAW;IACpE,MAAM,IAAI,GAAG,MAAM,SAAS,CAAC,OAAO,EAAE,IAAI,EAAE,EAAE,CAAC,CAAC;IAChD,OAAO,QAAQ,CAAC,IAAI,EAAE,KAAK,IAAI,EAAE;QAC/B,MAAM,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;QAC9B,OAAO,CAAC,CAAC;IACX,CAAC,CAAC,CAAC;AACL,CAAC;AAED,qDAAqD;AACrD,MAAM,UAAU,aAAa,CAAC,OAAuB,EAAE,KAAwB;IAC7E,MAAM,CAAC,EAAE,CAAC,GAAG,KAAK,CAAC;IACnB,IAAI,EAAE,KAAK,SAAS,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC;QAAE,MAAM,IAAI,QAAQ,CAAC,OAAO,EAAE,6BAA6B,CAAC,CAAC;IACrG,OAAO,WAAW,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC;AAClC,CAAC","sourcesContent":["/**\n * `buildanagent chat` and `buildanagent resume <session>`: a conversation, one line of input per turn. When a turn\n * pauses for a person, the requests are asked about at the terminal and the turn goes on once they are answered.\n * Resuming a session first asks about whatever it was left waiting on.\n */\nimport type { TurnResultSummary } from \"@buildanagent/protocol\";\nimport { askPerson } from \"../ask.js\";\nimport { CliError } from \"../errors.js\";\nimport type { CliIo } from \"../io.js\";\nimport { type Live, reportSettled, startLive, withLive } from \"../live.js\";\nimport type { CommandContext } from \"../options.js\";\nimport { runTurn, type SessionWatch, WAITING_REASONS } from \"../watch.js\";\n\nconst QUIT = new Set([\"/exit\", \"/quit\"]);\n\n/**\n * Asks about each request the turn waits on and follows the resumes until the turn no longer waits, or until input\n * ends or no answer of ours is left for a turn to settle, such as one another process settled first.\n */\nexport async function settle(io: CliIo, watch: SessionWatch, first: TurnResultSummary): Promise<TurnResultSummary> {\n let result = first;\n while (WAITING_REASONS.has(result.stopReason)) {\n if (watch.asked.size > 0 && !(await askPerson(io, watch))) return result;\n if (!(await watch.settlePending())) return result;\n result = (await watch.nextSettled()).result;\n }\n return result;\n}\n\nasync function converse(context: CommandContext, live: Live): Promise<void> {\n if (live.pending.length > 0) {\n await live.watch.whenAsked(live.pending);\n reportSettled(\n live,\n await settle(context.io, live.watch, { stopReason: \"awaiting_approval\", steps: 0, costUsd: null }),\n );\n }\n for (;;) {\n context.io.error(\"> \");\n const line = await context.io.readLine();\n if (line === undefined || QUIT.has(line.trim())) return;\n if (line.trim() === \"\") continue;\n const result = await runTurn(live.host.client, live.watch, line);\n reportSettled(live, await settle(context.io, live.watch, result));\n }\n}\n\n/** Chats in a new session, or in the stored session `id`, until input ends or a line says `/exit`. */\nexport async function chatCommand(context: CommandContext, id?: string): Promise<number> {\n const live = await startLive(context, true, id);\n return withLive(live, async () => {\n await converse(context, live);\n return 0;\n });\n}\n\n/** `resume <session>`: chats in a stored session. */\nexport function resumeCommand(context: CommandContext, words: readonly string[]): Promise<number> {\n const [id] = words;\n if (id === undefined || words.length > 1) throw new CliError(\"usage\", \"resume takes one session id\");\n return chatCommand(context, id);\n}\n"]}
|