@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
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `buildanagent keys rotate|prune`: change the approval key ring. `rotate` adds a key that signs every new request;
|
|
3
|
+
* the older keys still verify the requests they signed. `prune` removes the keys that no waiting request names, so a
|
|
4
|
+
* request signed with an old key never stops verifying while it waits.
|
|
5
|
+
*/
|
|
6
|
+
import { pruneKeys, rotateKeys } from "@buildanagent/harness/session";
|
|
7
|
+
import { fileKeyStore } from "@buildanagent/harness/session/jsonl";
|
|
8
|
+
import { CliError } from "../errors.js";
|
|
9
|
+
import { openHost } from "../host.js";
|
|
10
|
+
import { CLI_VERSION } from "../live.js";
|
|
11
|
+
import { Output } from "../output.js";
|
|
12
|
+
/** The ids of the keys that sign a request still waiting in any session. */
|
|
13
|
+
async function keysInUse(context) {
|
|
14
|
+
const host = await openHost({ ...context.hostOptions, interactive: false, signing: false });
|
|
15
|
+
try {
|
|
16
|
+
const { pending } = await host.client.request("initialize", {
|
|
17
|
+
clientInfo: { name: "buildanagent", version: CLI_VERSION },
|
|
18
|
+
capabilities: [],
|
|
19
|
+
});
|
|
20
|
+
return new Set(pending.map(({ request }) => request.keyId));
|
|
21
|
+
}
|
|
22
|
+
finally {
|
|
23
|
+
await host.close();
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** Runs `keys rotate` or `keys prune` and returns the exit status. */
|
|
27
|
+
export async function keysCommand(context, words) {
|
|
28
|
+
const [verb, ...rest] = words;
|
|
29
|
+
if ((verb !== "rotate" && verb !== "prune") || rest.length > 0) {
|
|
30
|
+
throw new CliError("usage", "keys takes rotate or prune");
|
|
31
|
+
}
|
|
32
|
+
const store = fileKeyStore(context.hostOptions.paths.keys);
|
|
33
|
+
const out = new Output(context.io, context.flags.json);
|
|
34
|
+
if (verb === "rotate") {
|
|
35
|
+
const id = await rotateKeys(store);
|
|
36
|
+
out.result(`new current key ${id}`, { rotated: id });
|
|
37
|
+
return 0;
|
|
38
|
+
}
|
|
39
|
+
const inUse = await keysInUse(context);
|
|
40
|
+
const removed = await pruneKeys(store, inUse);
|
|
41
|
+
out.result(removed.length === 0 ? "no key to remove" : `removed ${removed.join(", ")}`, {
|
|
42
|
+
removed,
|
|
43
|
+
kept: [...inUse],
|
|
44
|
+
});
|
|
45
|
+
return 0;
|
|
46
|
+
}
|
|
47
|
+
//# sourceMappingURL=keys.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"keys.js","sourceRoot":"","sources":["../../src/commands/keys.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AACtE,OAAO,EAAE,YAAY,EAAE,MAAM,qCAAqC,CAAC;AACnE,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAEzC,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAEtC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AAG,MAAM,UAAU,CAAC,KAAK,CAAC,CAAC;QACnC,GAAG,CAAC,MAAM,CAAC,mBAAmB,EAAE,EAAE,EAAE,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,CAAC;QACrD,OAAO,CAAC,CAAC;IACX,CAAC;IACD,MAAM,KAAK,GAAG,MAAM,SAAS,CAAC,OAAO,CAAC,CAAC;IACvC,MAAM,OAAO,GAAG,MAAM,SAAS,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;IAC9C,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,WAAW,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE;QACtF,OAAO;QACP,IAAI,EAAE,CAAC,GAAG,KAAK,CAAC;KACjB,CAAC,CAAC;IACH,OAAO,CAAC,CAAC;AACX,CAAC","sourcesContent":["/**\n * `buildanagent keys rotate|prune`: change the approval key ring. `rotate` adds a key that signs every new request;\n * the older keys still verify the requests they signed. `prune` removes the keys that no waiting request names, so a\n * request signed with an old key never stops verifying while it waits.\n */\nimport { pruneKeys, rotateKeys } from \"@buildanagent/harness/session\";\nimport { fileKeyStore } from \"@buildanagent/harness/session/jsonl\";\nimport { CliError } from \"../errors.js\";\nimport { openHost } from \"../host.js\";\nimport { CLI_VERSION } from \"../live.js\";\nimport type { CommandContext } from \"../options.js\";\nimport { Output } from \"../output.js\";\n\n/** The ids of the keys that sign a request still waiting in any session. */\nasync function keysInUse(context: CommandContext): Promise<Set<string>> {\n const host = await openHost({ ...context.hostOptions, interactive: false, signing: false });\n try {\n const { pending } = await host.client.request(\"initialize\", {\n clientInfo: { name: \"buildanagent\", version: CLI_VERSION },\n capabilities: [],\n });\n return new Set(pending.map(({ request }) => request.keyId));\n } finally {\n await host.close();\n }\n}\n\n/** Runs `keys rotate` or `keys prune` and returns the exit status. */\nexport async function keysCommand(context: CommandContext, words: readonly string[]): Promise<number> {\n const [verb, ...rest] = words;\n if ((verb !== \"rotate\" && verb !== \"prune\") || rest.length > 0) {\n throw new CliError(\"usage\", \"keys takes rotate or prune\");\n }\n const store = fileKeyStore(context.hostOptions.paths.keys);\n const out = new Output(context.io, context.flags.json);\n if (verb === \"rotate\") {\n const id = await rotateKeys(store);\n out.result(`new current key ${id}`, { rotated: id });\n return 0;\n }\n const inUse = await keysInUse(context);\n const removed = await pruneKeys(store, inUse);\n out.result(removed.length === 0 ? \"no key to remove\" : `removed ${removed.join(\", \")}`, {\n removed,\n kept: [...inUse],\n });\n return 0;\n}\n"]}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `buildanagent rpc`: serves the harness protocol as JSON-RPC lines over standard input and output, for a client in
|
|
3
|
+
* another process or language. Standard output carries protocol lines only, so the transport's diagnostics go to
|
|
4
|
+
* standard error.
|
|
5
|
+
*
|
|
6
|
+
* The host is interactive, because the client is the person's side: a call no rule settles is asked over the wire with
|
|
7
|
+
* `approval/request` instead of denied, and its pause is signed so a later process can resolve it. The command ends
|
|
8
|
+
* when the client closes standard input, or when the server stops the connection, and only then closes the host.
|
|
9
|
+
*/
|
|
10
|
+
import { stdioTransport } from "@buildanagent/harness/server";
|
|
11
|
+
import { CliError } from "../errors.js";
|
|
12
|
+
import { openHost } from "../host.js";
|
|
13
|
+
import { modelFromSpec } from "../model.js";
|
|
14
|
+
/** Serves one client over the process's standard streams until it is done, and returns exit status 0. */
|
|
15
|
+
export async function rpcCommand(context, words) {
|
|
16
|
+
if (words.length > 0)
|
|
17
|
+
throw new CliError("usage", "rpc takes no arguments");
|
|
18
|
+
const { io, flags, options } = context;
|
|
19
|
+
if (io.streams === undefined) {
|
|
20
|
+
throw new CliError("no_streams", "rpc needs the standard streams as bytes: give the CliIo its streams");
|
|
21
|
+
}
|
|
22
|
+
const { input, output } = io.streams;
|
|
23
|
+
const model = options.model ?? modelFromSpec(flags.model, io.env);
|
|
24
|
+
const host = await openHost({ ...context.hostOptions, model, interactive: true, signing: true });
|
|
25
|
+
try {
|
|
26
|
+
await stdioTransport(host.dispatcher, { input, output, log: (line) => io.error(`${line}\n`) });
|
|
27
|
+
}
|
|
28
|
+
finally {
|
|
29
|
+
await host.close();
|
|
30
|
+
}
|
|
31
|
+
return 0;
|
|
32
|
+
}
|
|
33
|
+
//# sourceMappingURL=rpc.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rpc.js","sourceRoot":"","sources":["../../src/commands/rpc.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AACtC,OAAO,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAG5C,yGAAyG;AACzG,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,OAAuB,EAAE,KAAwB;IAChF,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC;QAAE,MAAM,IAAI,QAAQ,CAAC,OAAO,EAAE,wBAAwB,CAAC,CAAC;IAC5E,MAAM,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC;IACvC,IAAI,EAAE,CAAC,OAAO,KAAK,SAAS,EAAE,CAAC;QAC7B,MAAM,IAAI,QAAQ,CAAC,YAAY,EAAE,qEAAqE,CAAC,CAAC;IAC1G,CAAC;IACD,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC;IACrC,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,IAAI,aAAa,CAAC,KAAK,CAAC,KAAK,EAAE,EAAE,CAAC,GAAG,CAAC,CAAC;IAClE,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,EAAE,GAAG,OAAO,CAAC,WAAW,EAAE,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;IACjG,IAAI,CAAC;QACH,MAAM,cAAc,CAAC,IAAI,CAAC,UAAU,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,CAAC,KAAK,CAAC,GAAG,IAAI,IAAI,CAAC,EAAE,CAAC,CAAC;IACjG,CAAC;YAAS,CAAC;QACT,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;IACrB,CAAC;IACD,OAAO,CAAC,CAAC;AACX,CAAC","sourcesContent":["/**\n * `buildanagent rpc`: serves the harness protocol as JSON-RPC lines over standard input and output, for a client in\n * another process or language. Standard output carries protocol lines only, so the transport's diagnostics go to\n * standard error.\n *\n * The host is interactive, because the client is the person's side: a call no rule settles is asked over the wire with\n * `approval/request` instead of denied, and its pause is signed so a later process can resolve it. The command ends\n * when the client closes standard input, or when the server stops the connection, and only then closes the host.\n */\nimport { stdioTransport } from \"@buildanagent/harness/server\";\nimport { CliError } from \"../errors.js\";\nimport { openHost } from \"../host.js\";\nimport { modelFromSpec } from \"../model.js\";\nimport type { CommandContext } from \"../options.js\";\n\n/** Serves one client over the process's standard streams until it is done, and returns exit status 0. */\nexport async function rpcCommand(context: CommandContext, words: readonly string[]): Promise<number> {\n if (words.length > 0) throw new CliError(\"usage\", \"rpc takes no arguments\");\n const { io, flags, options } = context;\n if (io.streams === undefined) {\n throw new CliError(\"no_streams\", \"rpc needs the standard streams as bytes: give the CliIo its streams\");\n }\n const { input, output } = io.streams;\n const model = options.model ?? modelFromSpec(flags.model, io.env);\n const host = await openHost({ ...context.hostOptions, model, interactive: true, signing: true });\n try {\n await stdioTransport(host.dispatcher, { input, output, log: (line) => io.error(`${line}\\n`) });\n } finally {\n await host.close();\n }\n return 0;\n}\n"]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `buildanagent run <prompt>`: one turn, then exit. A call that needs a person is not asked about, because nobody may
|
|
3
|
+
* be at the terminal: the turn ends waiting, the exit status is 3, and `resume` answers it later.
|
|
4
|
+
*/
|
|
5
|
+
import { CliError } from "../errors.js";
|
|
6
|
+
import { exitStatus, reportSettled, startLive, withLive } from "../live.js";
|
|
7
|
+
import { runTurn } from "../watch.js";
|
|
8
|
+
/** Runs one turn of a new session with the prompt `words` make up, and returns the exit status. */
|
|
9
|
+
export async function runCommand(context, words) {
|
|
10
|
+
const prompt = words.join(" ");
|
|
11
|
+
if (prompt.trim() === "")
|
|
12
|
+
throw new CliError("usage", "run needs a prompt: buildanagent run <prompt>");
|
|
13
|
+
const live = await startLive(context, false);
|
|
14
|
+
return withLive(live, async () => {
|
|
15
|
+
const result = await runTurn(live.host.client, live.watch, prompt);
|
|
16
|
+
reportSettled(live, result);
|
|
17
|
+
return exitStatus(result);
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
//# sourceMappingURL=run.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"run.js","sourceRoot":"","sources":["../../src/commands/run.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAE5E,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAEtC,mGAAmG;AACnG,MAAM,CAAC,KAAK,UAAU,UAAU,CAAC,OAAuB,EAAE,KAAwB;IAChF,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAC/B,IAAI,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE;QAAE,MAAM,IAAI,QAAQ,CAAC,OAAO,EAAE,+CAA+C,CAAC,CAAC;IACvG,MAAM,IAAI,GAAG,MAAM,SAAS,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IAC7C,OAAO,QAAQ,CAAC,IAAI,EAAE,KAAK,IAAI,EAAE;QAC/B,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QACnE,aAAa,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC;QAC5B,OAAO,UAAU,CAAC,MAAM,CAAC,CAAC;IAC5B,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["/**\n * `buildanagent run <prompt>`: one turn, then exit. A call that needs a person is not asked about, because nobody may\n * be at the terminal: the turn ends waiting, the exit status is 3, and `resume` answers it later.\n */\nimport { CliError } from \"../errors.js\";\nimport { exitStatus, reportSettled, startLive, withLive } from \"../live.js\";\nimport type { CommandContext } from \"../options.js\";\nimport { runTurn } from \"../watch.js\";\n\n/** Runs one turn of a new session with the prompt `words` make up, and returns the exit status. */\nexport async function runCommand(context: CommandContext, words: readonly string[]): Promise<number> {\n const prompt = words.join(\" \");\n if (prompt.trim() === \"\") throw new CliError(\"usage\", \"run needs a prompt: buildanagent run <prompt>\");\n const live = await startLive(context, false);\n return withLive(live, async () => {\n const result = await runTurn(live.host.client, live.watch, prompt);\n reportSettled(live, result);\n return exitStatus(result);\n });\n}\n"]}
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { CliError } from "../errors.js";
|
|
2
|
+
import { openHost } from "../host.js";
|
|
3
|
+
import { CLI_VERSION } from "../live.js";
|
|
4
|
+
import { Meter, readingText } from "../meter.js";
|
|
5
|
+
import { Output } from "../output.js";
|
|
6
|
+
import { entryLine } from "../render.js";
|
|
7
|
+
import { visible } from "../visible.js";
|
|
8
|
+
import { openStored, SessionWatch } from "../watch.js";
|
|
9
|
+
const SNIPPET_CHARS = 60;
|
|
10
|
+
async function readOnlyHost(context) {
|
|
11
|
+
const host = await openHost({ ...context.hostOptions, interactive: false, signing: false });
|
|
12
|
+
await host.client.request("initialize", {
|
|
13
|
+
clientInfo: { name: "buildanagent", version: CLI_VERSION },
|
|
14
|
+
capabilities: [],
|
|
15
|
+
});
|
|
16
|
+
return host;
|
|
17
|
+
}
|
|
18
|
+
async function listAll(host) {
|
|
19
|
+
const all = [];
|
|
20
|
+
let cursor;
|
|
21
|
+
do {
|
|
22
|
+
const page = await host.client.request("session/list", cursor === undefined ? {} : { cursor });
|
|
23
|
+
all.push(...page.sessions);
|
|
24
|
+
cursor = page.nextCursor;
|
|
25
|
+
} while (cursor !== undefined);
|
|
26
|
+
return all;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Every entry of the session's current file, read back through `session/open`. The open takes no writer lock, so a
|
|
30
|
+
* read never stops another process's turn. The dispatcher does keep the session open for this connection, watching
|
|
31
|
+
* its events and asking it about waiting requests, and the protocol has no call to close one session, so that state
|
|
32
|
+
* lasts until the command closes the host, which ends it for every session read.
|
|
33
|
+
*/
|
|
34
|
+
async function entriesOf(context, host, session) {
|
|
35
|
+
const entries = [];
|
|
36
|
+
const watch = new SessionWatch(host.client, session, (event) => {
|
|
37
|
+
if (event.type === "entry_appended")
|
|
38
|
+
entries.push(event.entry);
|
|
39
|
+
});
|
|
40
|
+
try {
|
|
41
|
+
await openStored(host.client, watch, context.io.cwd);
|
|
42
|
+
}
|
|
43
|
+
finally {
|
|
44
|
+
watch.stop();
|
|
45
|
+
}
|
|
46
|
+
return entries;
|
|
47
|
+
}
|
|
48
|
+
function list(out, sessions) {
|
|
49
|
+
if (sessions.length === 0 && !out.json)
|
|
50
|
+
out.note("no sessions yet", {});
|
|
51
|
+
for (const item of sessions) {
|
|
52
|
+
out.result(`${item.session} started ${item.startedAt} last ${item.lastEntryAt} ${item.entryCount} entries`, item);
|
|
53
|
+
}
|
|
54
|
+
return 0;
|
|
55
|
+
}
|
|
56
|
+
function show(out, session, entries) {
|
|
57
|
+
out.note(`session ${session}: ${entries.length} entries`, { type: "session", session, entries: entries.length });
|
|
58
|
+
for (const entry of entries) {
|
|
59
|
+
const line = entryLine(entry);
|
|
60
|
+
out.result(`#${entry.seq} ${entry.type}${line === undefined ? "" : ` ${line.trim()}`}`, entry);
|
|
61
|
+
}
|
|
62
|
+
return 0;
|
|
63
|
+
}
|
|
64
|
+
function replay(out, session, entries) {
|
|
65
|
+
const meter = new Meter();
|
|
66
|
+
for (const entry of entries) {
|
|
67
|
+
meter.observe({ type: "entry_appended", entry });
|
|
68
|
+
const line = entryLine(entry);
|
|
69
|
+
if (out.json)
|
|
70
|
+
out.line({ type: "event", session, seq: entry.seq, event: { type: "entry_appended", entry } });
|
|
71
|
+
else if (line !== undefined)
|
|
72
|
+
out.result(line, entry);
|
|
73
|
+
}
|
|
74
|
+
out.note(`[replayed ${entries.length} entries] ${readingText(meter.reading())}`, {
|
|
75
|
+
type: "replayed",
|
|
76
|
+
session,
|
|
77
|
+
entries: entries.length,
|
|
78
|
+
meter: meter.reading(),
|
|
79
|
+
});
|
|
80
|
+
return 0;
|
|
81
|
+
}
|
|
82
|
+
/** The text an entry holds that search reads: a message's text, or a tool result's. */
|
|
83
|
+
function searchable(entry) {
|
|
84
|
+
if (entry.type === "message_block" && entry.block.type === "text") {
|
|
85
|
+
return { who: entry.role === "user" ? "you" : "assistant", text: entry.block.text };
|
|
86
|
+
}
|
|
87
|
+
if (entry.type === "tool_result") {
|
|
88
|
+
const text = entry.content.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("\n");
|
|
89
|
+
return { who: entry.tool, text };
|
|
90
|
+
}
|
|
91
|
+
return undefined;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* `text` in lower case where that keeps its length, character by character. `toLowerCase()` turns some characters
|
|
95
|
+
* into longer ones, such as `İ` into `i̇`, so a match found in the lowered text would sit at another index of the
|
|
96
|
+
* original; a character like that is compared as it is written instead.
|
|
97
|
+
*/
|
|
98
|
+
const folded = (text) => Array.from(text, (char) => {
|
|
99
|
+
const lower = char.toLowerCase();
|
|
100
|
+
return lower.length === char.length ? lower : char;
|
|
101
|
+
}).join("");
|
|
102
|
+
function snippet(text, at, length) {
|
|
103
|
+
const start = Math.max(0, at - SNIPPET_CHARS);
|
|
104
|
+
const end = Math.min(text.length, at + length + SNIPPET_CHARS);
|
|
105
|
+
const flat = text.slice(start, end).replace(/\s+/g, " ");
|
|
106
|
+
return `${start > 0 ? "…" : ""}${flat}${end < text.length ? "…" : ""}`;
|
|
107
|
+
}
|
|
108
|
+
async function search(context, host, out, query) {
|
|
109
|
+
const needle = folded(query);
|
|
110
|
+
let found = 0;
|
|
111
|
+
for (const { session } of await listAll(host)) {
|
|
112
|
+
for (const entry of await entriesOf(context, host, session)) {
|
|
113
|
+
const hit = searchable(entry);
|
|
114
|
+
const at = hit === undefined ? -1 : folded(hit.text).indexOf(needle);
|
|
115
|
+
if (hit === undefined || at < 0)
|
|
116
|
+
continue;
|
|
117
|
+
found += 1;
|
|
118
|
+
const text = snippet(hit.text, at, needle.length);
|
|
119
|
+
out.result(`${session} #${entry.seq} ${visible(`${hit.who}: ${text}`)}`, {
|
|
120
|
+
session,
|
|
121
|
+
seq: entry.seq,
|
|
122
|
+
who: hit.who,
|
|
123
|
+
text,
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
if (found === 0)
|
|
128
|
+
out.note(`no message holds ${JSON.stringify(query)}`, { type: "no_match", query });
|
|
129
|
+
return found === 0 ? 1 : 0;
|
|
130
|
+
}
|
|
131
|
+
const USAGE = "sessions takes list, show <session>, search <text> or replay <session>";
|
|
132
|
+
function oneSession(words, verb) {
|
|
133
|
+
if (words.length !== 1)
|
|
134
|
+
throw new CliError("usage", `sessions ${verb} takes one session id`);
|
|
135
|
+
return words[0];
|
|
136
|
+
}
|
|
137
|
+
/** Runs one `sessions` subcommand and returns the exit status. `search` exits 1 when nothing matches. */
|
|
138
|
+
export async function sessionsCommand(context, words) {
|
|
139
|
+
const [verb, ...rest] = words;
|
|
140
|
+
if (verb === undefined || !["list", "show", "search", "replay"].includes(verb))
|
|
141
|
+
throw new CliError("usage", USAGE);
|
|
142
|
+
if (verb === "list" && rest.length > 0)
|
|
143
|
+
throw new CliError("usage", "sessions list takes no arguments");
|
|
144
|
+
if (verb === "search" && rest.join(" ").trim() === "")
|
|
145
|
+
throw new CliError("usage", "sessions search needs a text");
|
|
146
|
+
const session = verb === "show" || verb === "replay" ? oneSession(rest, verb) : "";
|
|
147
|
+
const host = await readOnlyHost(context);
|
|
148
|
+
const out = new Output(context.io, context.flags.json);
|
|
149
|
+
try {
|
|
150
|
+
if (verb === "list")
|
|
151
|
+
return list(out, await listAll(host));
|
|
152
|
+
if (verb === "search")
|
|
153
|
+
return await search(context, host, out, rest.join(" "));
|
|
154
|
+
const entries = await entriesOf(context, host, session);
|
|
155
|
+
return verb === "show" ? show(out, session, entries) : replay(out, session, entries);
|
|
156
|
+
}
|
|
157
|
+
finally {
|
|
158
|
+
await host.close();
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
//# sourceMappingURL=sessions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sessions.js","sourceRoot":"","sources":["../../src/commands/sessions.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,EAAa,QAAQ,EAAE,MAAM,YAAY,CAAC;AACjD,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AACzC,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAEjD,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AACzC,OAAO,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACxC,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAEvD,MAAM,aAAa,GAAG,EAAE,CAAC;AAEzB,KAAK,UAAU,YAAY,CAAC,OAAuB;IACjD,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,EAAE,GAA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AE,EAAE,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACvD,IAAI,CAAC;QACH,IAAI,IAAI,KAAK,MAAM;YAAE,OAAO,IAAI,CAAC,GAAG,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;QAC3D,IAAI,IAAI,KAAK,QAAQ;YAAE,OAAO,MAAM,MAAM,CAAC,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAC;QAC/E,MAAM,OAAO,GAAG,MAAM,SAAS,CAAC,OAAO,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;QACxD,OAAO,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IACvF,CAAC;YAAS,CAAC;QACT,MAAM,IAAI,CAAC,KAAK,EAAE,CAAC;IACrB,CAAC;AACH,CAAC","sourcesContent":["/**\n * `buildanagent sessions list|show|search|replay`: read the stored sessions. Each one reads the log through the\n * harness's own replay, so nothing is re-run: a replay makes no model call and runs no tool.\n */\nimport type { SessionEntry, SessionListItem } from \"@buildanagent/protocol\";\nimport { CliError } from \"../errors.js\";\nimport { type Host, openHost } from \"../host.js\";\nimport { CLI_VERSION } from \"../live.js\";\nimport { Meter, readingText } from \"../meter.js\";\nimport type { CommandContext } from \"../options.js\";\nimport { Output } from \"../output.js\";\nimport { entryLine } from \"../render.js\";\nimport { visible } from \"../visible.js\";\nimport { openStored, SessionWatch } from \"../watch.js\";\n\nconst SNIPPET_CHARS = 60;\n\nasync function readOnlyHost(context: CommandContext): Promise<Host> {\n const host = await openHost({ ...context.hostOptions, interactive: false, signing: false });\n await host.client.request(\"initialize\", {\n clientInfo: { name: \"buildanagent\", version: CLI_VERSION },\n capabilities: [],\n });\n return host;\n}\n\nasync function listAll(host: Host): Promise<SessionListItem[]> {\n const all: SessionListItem[] = [];\n let cursor: string | undefined;\n do {\n const page = await host.client.request(\"session/list\", cursor === undefined ? {} : { cursor });\n all.push(...page.sessions);\n cursor = page.nextCursor;\n } while (cursor !== undefined);\n return all;\n}\n\n/**\n * Every entry of the session's current file, read back through `session/open`. The open takes no writer lock, so a\n * read never stops another process's turn. The dispatcher does keep the session open for this connection, watching\n * its events and asking it about waiting requests, and the protocol has no call to close one session, so that state\n * lasts until the command closes the host, which ends it for every session read.\n */\nasync function entriesOf(context: CommandContext, host: Host, session: string): Promise<SessionEntry[]> {\n const entries: SessionEntry[] = [];\n const watch = new SessionWatch(host.client, session, (event) => {\n if (event.type === \"entry_appended\") entries.push(event.entry);\n });\n try {\n await openStored(host.client, watch, context.io.cwd);\n } finally {\n watch.stop();\n }\n return entries;\n}\n\nfunction list(out: Output, sessions: readonly SessionListItem[]): number {\n if (sessions.length === 0 && !out.json) out.note(\"no sessions yet\", {});\n for (const item of sessions) {\n out.result(\n `${item.session} started ${item.startedAt} last ${item.lastEntryAt} ${item.entryCount} entries`,\n item,\n );\n }\n return 0;\n}\n\nfunction show(out: Output, session: string, entries: readonly SessionEntry[]): number {\n out.note(`session ${session}: ${entries.length} entries`, { type: \"session\", session, entries: entries.length });\n for (const entry of entries) {\n const line = entryLine(entry);\n out.result(`#${entry.seq} ${entry.type}${line === undefined ? \"\" : ` ${line.trim()}`}`, entry);\n }\n return 0;\n}\n\nfunction replay(out: Output, session: string, entries: readonly SessionEntry[]): number {\n const meter = new Meter();\n for (const entry of entries) {\n meter.observe({ type: \"entry_appended\", entry });\n const line = entryLine(entry);\n if (out.json) out.line({ type: \"event\", session, seq: entry.seq, event: { type: \"entry_appended\", entry } });\n else if (line !== undefined) out.result(line, entry);\n }\n out.note(`[replayed ${entries.length} entries] ${readingText(meter.reading())}`, {\n type: \"replayed\",\n session,\n entries: entries.length,\n meter: meter.reading(),\n });\n return 0;\n}\n\n/** The text an entry holds that search reads: a message's text, or a tool result's. */\nfunction searchable(entry: SessionEntry): { who: string; text: string } | undefined {\n if (entry.type === \"message_block\" && entry.block.type === \"text\") {\n return { who: entry.role === \"user\" ? \"you\" : \"assistant\", text: entry.block.text };\n }\n if (entry.type === \"tool_result\") {\n const text = entry.content.flatMap((block) => (block.type === \"text\" ? [block.text] : [])).join(\"\\n\");\n return { who: entry.tool, text };\n }\n return undefined;\n}\n\n/**\n * `text` in lower case where that keeps its length, character by character. `toLowerCase()` turns some characters\n * into longer ones, such as `İ` into `i̇`, so a match found in the lowered text would sit at another index of the\n * original; a character like that is compared as it is written instead.\n */\nconst folded = (text: string): string =>\n Array.from(text, (char) => {\n const lower = char.toLowerCase();\n return lower.length === char.length ? lower : char;\n }).join(\"\");\n\nfunction snippet(text: string, at: number, length: number): string {\n const start = Math.max(0, at - SNIPPET_CHARS);\n const end = Math.min(text.length, at + length + SNIPPET_CHARS);\n const flat = text.slice(start, end).replace(/\\s+/g, \" \");\n return `${start > 0 ? \"…\" : \"\"}${flat}${end < text.length ? \"…\" : \"\"}`;\n}\n\nasync function search(context: CommandContext, host: Host, out: Output, query: string): Promise<number> {\n const needle = folded(query);\n let found = 0;\n for (const { session } of await listAll(host)) {\n for (const entry of await entriesOf(context, host, session)) {\n const hit = searchable(entry);\n const at = hit === undefined ? -1 : folded(hit.text).indexOf(needle);\n if (hit === undefined || at < 0) continue;\n found += 1;\n const text = snippet(hit.text, at, needle.length);\n out.result(`${session} #${entry.seq} ${visible(`${hit.who}: ${text}`)}`, {\n session,\n seq: entry.seq,\n who: hit.who,\n text,\n });\n }\n }\n if (found === 0) out.note(`no message holds ${JSON.stringify(query)}`, { type: \"no_match\", query });\n return found === 0 ? 1 : 0;\n}\n\nconst USAGE = \"sessions takes list, show <session>, search <text> or replay <session>\";\n\nfunction oneSession(words: readonly string[], verb: string): string {\n if (words.length !== 1) throw new CliError(\"usage\", `sessions ${verb} takes one session id`);\n return words[0] as string;\n}\n\n/** Runs one `sessions` subcommand and returns the exit status. `search` exits 1 when nothing matches. */\nexport async function sessionsCommand(context: CommandContext, words: readonly string[]): Promise<number> {\n const [verb, ...rest] = words;\n if (verb === undefined || ![\"list\", \"show\", \"search\", \"replay\"].includes(verb)) throw new CliError(\"usage\", USAGE);\n if (verb === \"list\" && rest.length > 0) throw new CliError(\"usage\", \"sessions list takes no arguments\");\n if (verb === \"search\" && rest.join(\" \").trim() === \"\") throw new CliError(\"usage\", \"sessions search needs a text\");\n const session = verb === \"show\" || verb === \"replay\" ? oneSession(rest, verb) : \"\";\n const host = await readOnlyHost(context);\n const out = new Output(context.io, context.flags.json);\n try {\n if (verb === \"list\") return list(out, await listAll(host));\n if (verb === \"search\") return await search(context, host, out, rest.join(\" \"));\n const entries = await entriesOf(context, host, session);\n return verb === \"show\" ? show(out, session, entries) : replay(out, session, entries);\n } finally {\n await host.close();\n }\n}\n"]}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `buildanagent session unlock <session> --force`: remove a session's writer lock. A lock outlives a crash only by
|
|
3
|
+
* its lease, and one from another host is never taken over, so this is the way out when you know its writer is gone.
|
|
4
|
+
* Removing the lock of a writer that still runs lets two writers into one log, so the command needs `--force`.
|
|
5
|
+
*/
|
|
6
|
+
import { unlockSession } from "@buildanagent/harness/session/jsonl";
|
|
7
|
+
import { CliError } from "../errors.js";
|
|
8
|
+
import { USER_ID } from "../host.js";
|
|
9
|
+
import { Output } from "../output.js";
|
|
10
|
+
/** Runs `session unlock` and returns the exit status: 0 once no lock remains, 2 without `--force`. */
|
|
11
|
+
export async function unlockCommand(context, words) {
|
|
12
|
+
const [verb, session, ...rest] = words;
|
|
13
|
+
if (verb !== "unlock" || session === undefined || rest.length > 0) {
|
|
14
|
+
throw new CliError("usage", "session takes unlock <session> --force");
|
|
15
|
+
}
|
|
16
|
+
if (!context.flags.force) {
|
|
17
|
+
context.io.error(`buildanagent: unlocking lets a second writer into ${session}; check that no other buildanagent runs it, then pass --force\n`);
|
|
18
|
+
return 2;
|
|
19
|
+
}
|
|
20
|
+
const removed = await unlockSession({ dir: context.hostOptions.paths.locks }, { userId: USER_ID, sessionId: session });
|
|
21
|
+
const out = new Output(context.io, context.flags.json);
|
|
22
|
+
if (removed === undefined)
|
|
23
|
+
out.result(`${session} had no lock`, { session, removed: null });
|
|
24
|
+
else if (removed === "unreadable")
|
|
25
|
+
out.result(`removed an unreadable lock from ${session}`, { session, removed });
|
|
26
|
+
else {
|
|
27
|
+
out.result(`removed the lock of process ${removed.pid} on ${removed.host} from ${session}`, { session, removed });
|
|
28
|
+
}
|
|
29
|
+
return 0;
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=unlock.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"unlock.js","sourceRoot":"","sources":["../../src/commands/unlock.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,aAAa,EAAE,MAAM,qCAAqC,CAAC;AACpE,OAAO,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AACxC,OAAO,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAErC,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAEtC,sGAAsG;AACtG,MAAM,CAAC,KAAK,UAAU,aAAa,CAAC,OAAuB,EAAE,KAAwB;IACnF,MAAM,CAAC,IAAI,EAAE,OAAO,EAAE,GAAG,IAAI,CAAC,GAAG,KAAK,CAAC;IACvC,IAAI,IAAI,KAAK,QAAQ,IAAI,OAAO,KAAK,SAAS,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAClE,MAAM,IAAI,QAAQ,CAAC,OAAO,EAAE,wCAAwC,CAAC,CAAC;IACxE,CAAC;IACD,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;QACzB,OAAO,CAAC,EAAE,CAAC,KAAK,CACd,qDAAqD,OAAO,iEAAiE,CAC9H,CAAC;QACF,OAAO,CAAC,CAAC;IACX,CAAC;IACD,MAAM,OAAO,GAAG,MAAM,aAAa,CACjC,EAAE,GAAG,EAAE,OAAO,CAAC,WAAW,CAAC,KAAK,CAAC,KAAK,EAAE,EACxC,EAAE,MAAM,EAAE,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,CACxC,CAAC;IACF,MAAM,GAAG,GAAG,IAAI,MAAM,CAAC,OAAO,CAAC,EAAE,EAAE,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IACvD,IAAI,OAAO,KAAK,SAAS;QAAE,GAAG,CAAC,MAAM,CAAC,GAAG,OAAO,cAAc,EAAE,EAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC;SACvF,IAAI,OAAO,KAAK,YAAY;QAAE,GAAG,CAAC,MAAM,CAAC,mCAAmC,OAAO,EAAE,EAAE,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC;SAC7G,CAAC;QACJ,GAAG,CAAC,MAAM,CAAC,+BAA+B,OAAO,CAAC,GAAG,OAAO,OAAO,CAAC,IAAI,SAAS,OAAO,EAAE,EAAE,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC,CAAC;IACpH,CAAC;IACD,OAAO,CAAC,CAAC;AACX,CAAC","sourcesContent":["/**\n * `buildanagent session unlock <session> --force`: remove a session's writer lock. A lock outlives a crash only by\n * its lease, and one from another host is never taken over, so this is the way out when you know its writer is gone.\n * Removing the lock of a writer that still runs lets two writers into one log, so the command needs `--force`.\n */\nimport { unlockSession } from \"@buildanagent/harness/session/jsonl\";\nimport { CliError } from \"../errors.js\";\nimport { USER_ID } from \"../host.js\";\nimport type { CommandContext } from \"../options.js\";\nimport { Output } from \"../output.js\";\n\n/** Runs `session unlock` and returns the exit status: 0 once no lock remains, 2 without `--force`. */\nexport async function unlockCommand(context: CommandContext, words: readonly string[]): Promise<number> {\n const [verb, session, ...rest] = words;\n if (verb !== \"unlock\" || session === undefined || rest.length > 0) {\n throw new CliError(\"usage\", \"session takes unlock <session> --force\");\n }\n if (!context.flags.force) {\n context.io.error(\n `buildanagent: unlocking lets a second writer into ${session}; check that no other buildanagent runs it, then pass --force\\n`,\n );\n return 2;\n }\n const removed = await unlockSession(\n { dir: context.hostOptions.paths.locks },\n { userId: USER_ID, sessionId: session },\n );\n const out = new Output(context.io, context.flags.json);\n if (removed === undefined) out.result(`${session} had no lock`, { session, removed: null });\n else if (removed === \"unreadable\") out.result(`removed an unreadable lock from ${session}`, { session, removed });\n else {\n out.result(`removed the lock of process ${removed.pid} on ${removed.host} from ${session}`, { session, removed });\n }\n return 0;\n}\n"]}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/** `CliError`: the CLI's one error class, with a `code` that says why the command could not run. */
|
|
2
|
+
/** Why a `CliError` was thrown. */
|
|
3
|
+
export type CliErrorCode =
|
|
4
|
+
/** An unknown command, flag or missing argument. */
|
|
5
|
+
"usage"
|
|
6
|
+
/** A command that calls a model was given no `--model`. */
|
|
7
|
+
| "no_model"
|
|
8
|
+
/** The provider's key variable is unset. */
|
|
9
|
+
| "missing_api_key"
|
|
10
|
+
/** Neither `--state-dir`, `XDG_STATE_HOME` nor `HOME` names a folder for sessions. */
|
|
11
|
+
| "no_state_dir"
|
|
12
|
+
/** No stored session has the id given. */
|
|
13
|
+
| "unknown_session"
|
|
14
|
+
/** The session refused a turn, such as one that another process is writing. */
|
|
15
|
+
| "session_unavailable"
|
|
16
|
+
/** The `--otlp-endpoint` collector could not be reached or refused the spans. */
|
|
17
|
+
| "otlp_failed"
|
|
18
|
+
/** `rpc` was run on a `CliIo` that gives no standard streams. */
|
|
19
|
+
| "no_streams";
|
|
20
|
+
/**
|
|
21
|
+
* Thrown for a command the CLI can't run as given. `runCli()` reports one on standard error and exits 2, so a script
|
|
22
|
+
* reads `code` to tell a bad command line from a missing key or a session it can't use. A model or provider failure
|
|
23
|
+
* during a turn is a stop reason, so it exits 1.
|
|
24
|
+
*/
|
|
25
|
+
export declare class CliError extends Error {
|
|
26
|
+
readonly name = "CliError";
|
|
27
|
+
readonly code: CliErrorCode;
|
|
28
|
+
constructor(code: CliErrorCode, message: string, options?: ErrorOptions);
|
|
29
|
+
}
|
|
30
|
+
/** True for a `CliError`, including one from another copy of the package. */
|
|
31
|
+
export declare function isCliError(error: unknown): error is CliError;
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/** `CliError`: the CLI's one error class, with a `code` that says why the command could not run. */
|
|
2
|
+
// A registered symbol, so the guard still works when two copies of the package are bundled.
|
|
3
|
+
const CLI_ERROR = Symbol.for("buildanagent.cli.CliError");
|
|
4
|
+
/**
|
|
5
|
+
* Thrown for a command the CLI can't run as given. `runCli()` reports one on standard error and exits 2, so a script
|
|
6
|
+
* reads `code` to tell a bad command line from a missing key or a session it can't use. A model or provider failure
|
|
7
|
+
* during a turn is a stop reason, so it exits 1.
|
|
8
|
+
*/
|
|
9
|
+
export class CliError extends Error {
|
|
10
|
+
name = "CliError";
|
|
11
|
+
code;
|
|
12
|
+
constructor(code, message, options) {
|
|
13
|
+
super(message, options);
|
|
14
|
+
this.code = code;
|
|
15
|
+
Object.defineProperty(this, CLI_ERROR, { value: true });
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
/** True for a `CliError`, including one from another copy of the package. */
|
|
19
|
+
export function isCliError(error) {
|
|
20
|
+
return typeof error === "object" && error !== null && error[CLI_ERROR] === true;
|
|
21
|
+
}
|
|
22
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,oGAAoG;AAqBpG,4FAA4F;AAC5F,MAAM,SAAS,GAAG,MAAM,CAAC,GAAG,CAAC,2BAA2B,CAAC,CAAC;AAE1D;;;;GAIG;AACH,MAAM,OAAO,QAAS,SAAQ,KAAK;IACf,IAAI,GAAG,UAAU,CAAC;IAC3B,IAAI,CAAe;IAE5B,YAAY,IAAkB,EAAE,OAAe,EAAE,OAAsB;QACrE,KAAK,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QACxB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,SAAS,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC1D,CAAC;CACF;AAED,6EAA6E;AAC7E,MAAM,UAAU,UAAU,CAAC,KAAc;IACvC,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAK,KAAiC,CAAC,SAAS,CAAC,KAAK,IAAI,CAAC;AAC/G,CAAC","sourcesContent":["/** `CliError`: the CLI's one error class, with a `code` that says why the command could not run. */\n\n/** Why a `CliError` was thrown. */\nexport type CliErrorCode =\n /** An unknown command, flag or missing argument. */\n | \"usage\"\n /** A command that calls a model was given no `--model`. */\n | \"no_model\"\n /** The provider's key variable is unset. */\n | \"missing_api_key\"\n /** Neither `--state-dir`, `XDG_STATE_HOME` nor `HOME` names a folder for sessions. */\n | \"no_state_dir\"\n /** No stored session has the id given. */\n | \"unknown_session\"\n /** The session refused a turn, such as one that another process is writing. */\n | \"session_unavailable\"\n /** The `--otlp-endpoint` collector could not be reached or refused the spans. */\n | \"otlp_failed\"\n /** `rpc` was run on a `CliIo` that gives no standard streams. */\n | \"no_streams\";\n\n// A registered symbol, so the guard still works when two copies of the package are bundled.\nconst CLI_ERROR = Symbol.for(\"buildanagent.cli.CliError\");\n\n/**\n * Thrown for a command the CLI can't run as given. `runCli()` reports one on standard error and exits 2, so a script\n * reads `code` to tell a bad command line from a missing key or a session it can't use. A model or provider failure\n * during a turn is a stop reason, so it exits 1.\n */\nexport class CliError extends Error {\n override readonly name = \"CliError\";\n readonly code: CliErrorCode;\n\n constructor(code: CliErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n this.code = code;\n Object.defineProperty(this, CLI_ERROR, { value: true });\n }\n}\n\n/** True for a `CliError`, including one from another copy of the package. */\nexport function isCliError(error: unknown): error is CliError {\n return typeof error === \"object\" && error !== null && (error as Record<symbol, unknown>)[CLI_ERROR] === true;\n}\n"]}
|
package/dist/host.d.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The harness a command runs on, and the in-process client it talks to it through. Sessions, locks, spilled tool
|
|
3
|
+
* output and the approval key ring live under one state folder on this machine, and the only connections a host can
|
|
4
|
+
* open are to the model a command names and to the `--otlp-endpoint` collector.
|
|
5
|
+
*/
|
|
6
|
+
import type { Model } from "@buildanagent/gateway";
|
|
7
|
+
import { type Rule } from "@buildanagent/harness/permissions";
|
|
8
|
+
import { type Dispatcher, type Harness, type InProcessClient } from "@buildanagent/harness/server";
|
|
9
|
+
import { type ToolRegistration } from "@buildanagent/harness/tools";
|
|
10
|
+
/** The system prompt every turn starts from. */
|
|
11
|
+
export declare const SYSTEM_PROMPT = "You are a coding agent. Work in the user's project, and ask before you change anything.";
|
|
12
|
+
/** The user every session is stored under: the CLI serves the one person at the terminal. */
|
|
13
|
+
export declare const USER_ID = "local";
|
|
14
|
+
/** Where a host keeps its files. */
|
|
15
|
+
export interface StatePaths {
|
|
16
|
+
readonly root: string;
|
|
17
|
+
readonly sessions: string;
|
|
18
|
+
readonly locks: string;
|
|
19
|
+
readonly spill: string;
|
|
20
|
+
readonly keys: string;
|
|
21
|
+
}
|
|
22
|
+
/** The permission rules a host adds to the harness's default ask rules. */
|
|
23
|
+
export interface HostRules {
|
|
24
|
+
readonly deny?: readonly Rule[];
|
|
25
|
+
readonly ask?: readonly Rule[];
|
|
26
|
+
readonly allow?: readonly Rule[];
|
|
27
|
+
}
|
|
28
|
+
/** What `openHost()` takes. */
|
|
29
|
+
export interface HostOptions {
|
|
30
|
+
readonly paths: StatePaths;
|
|
31
|
+
readonly cwd: string;
|
|
32
|
+
/** The model turns use. Left out, a turn that calls a model fails, which suits the commands that only read. */
|
|
33
|
+
readonly model?: Model;
|
|
34
|
+
/** Whether a person answers approvals. Without one, a call no rule settles is denied instead of asked. */
|
|
35
|
+
readonly interactive: boolean;
|
|
36
|
+
/** Load the approval key ring, which a turn needs to sign its pauses. Read-only commands leave it unloaded. */
|
|
37
|
+
readonly signing: boolean;
|
|
38
|
+
readonly tools?: readonly ToolRegistration[];
|
|
39
|
+
readonly rules?: HostRules;
|
|
40
|
+
readonly budgetUsd?: number;
|
|
41
|
+
readonly otlpEndpoint?: string;
|
|
42
|
+
readonly fetch?: typeof globalThis.fetch;
|
|
43
|
+
}
|
|
44
|
+
/** A harness, its dispatcher and one in-process client. */
|
|
45
|
+
export interface Host {
|
|
46
|
+
readonly harness: Harness;
|
|
47
|
+
readonly dispatcher: Dispatcher;
|
|
48
|
+
readonly client: InProcessClient;
|
|
49
|
+
readonly paths: StatePaths;
|
|
50
|
+
/** Ends every turn, closes the client and sends any spans. */
|
|
51
|
+
close(): Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
/** The folders under `root`, which `--state-dir` names or the environment implies. */
|
|
54
|
+
export declare function statePaths(root: string): StatePaths;
|
|
55
|
+
/**
|
|
56
|
+
* The state folder: `--state-dir`, else `$XDG_STATE_HOME/buildanagent`, else `~/.local/state/buildanagent`, which is
|
|
57
|
+
* where the harness keeps its key ring by default too. Throws a `CliError`, code `no_state_dir`, when none is known.
|
|
58
|
+
*/
|
|
59
|
+
export declare function stateRoot(flag: string | undefined, env: Readonly<Record<string, string | undefined>>): string;
|
|
60
|
+
/** Builds the harness for one command and connects a client to it. */
|
|
61
|
+
export declare function openHost(options: HostOptions): Promise<Host>;
|
package/dist/host.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { createContextPolicy } from "@buildanagent/harness/context";
|
|
2
|
+
import { fileSpillStore } from "@buildanagent/harness/context/file";
|
|
3
|
+
import { createPermissionPipeline, defaultAskRules } from "@buildanagent/harness/permissions";
|
|
4
|
+
import { createDispatcher, createHarness, inProcessTransport, } from "@buildanagent/harness/server";
|
|
5
|
+
import { fileIndex, fileKeyStore, fileLock, jsonlStore } from "@buildanagent/harness/session/jsonl";
|
|
6
|
+
import { createToolRegistry } from "@buildanagent/harness/tools";
|
|
7
|
+
import { hmacSigner } from "@buildanagent/sdk";
|
|
8
|
+
import { otelObserver } from "@buildanagent/sdk/otel";
|
|
9
|
+
import { CliError } from "./errors.js";
|
|
10
|
+
import { otlpTracer } from "./otlp.js";
|
|
11
|
+
/** The system prompt every turn starts from. */
|
|
12
|
+
export const SYSTEM_PROMPT = "You are a coding agent. Work in the user's project, and ask before you change anything.";
|
|
13
|
+
/** The user every session is stored under: the CLI serves the one person at the terminal. */
|
|
14
|
+
export const USER_ID = "local";
|
|
15
|
+
/** The policy version every approval the CLI asks for carries. */
|
|
16
|
+
const POLICY_VERSION = "buildanagent-cli-1";
|
|
17
|
+
/** The folders under `root`, which `--state-dir` names or the environment implies. */
|
|
18
|
+
export function statePaths(root) {
|
|
19
|
+
const base = root.replace(/\/+$/, "");
|
|
20
|
+
return {
|
|
21
|
+
root: base,
|
|
22
|
+
sessions: `${base}/sessions`,
|
|
23
|
+
locks: `${base}/locks`,
|
|
24
|
+
spill: `${base}/spill`,
|
|
25
|
+
keys: `${base}/keys.json`,
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The state folder: `--state-dir`, else `$XDG_STATE_HOME/buildanagent`, else `~/.local/state/buildanagent`, which is
|
|
30
|
+
* where the harness keeps its key ring by default too. Throws a `CliError`, code `no_state_dir`, when none is known.
|
|
31
|
+
*/
|
|
32
|
+
export function stateRoot(flag, env) {
|
|
33
|
+
if (flag !== undefined && flag !== "")
|
|
34
|
+
return flag;
|
|
35
|
+
if (env.XDG_STATE_HOME !== undefined && env.XDG_STATE_HOME !== "")
|
|
36
|
+
return `${env.XDG_STATE_HOME}/buildanagent`;
|
|
37
|
+
if (env.HOME !== undefined && env.HOME !== "")
|
|
38
|
+
return `${env.HOME}/.local/state/buildanagent`;
|
|
39
|
+
throw new CliError("no_state_dir", "set HOME or XDG_STATE_HOME, or pass --state-dir <folder>");
|
|
40
|
+
}
|
|
41
|
+
/** A model for the commands that only read: any call fails at once, so it can never reach a provider. */
|
|
42
|
+
const NO_MODEL = {
|
|
43
|
+
ref: { api: "none", provider: "none", id: "none" },
|
|
44
|
+
caps: { contextWindow: 200_000, maxOutputTokens: 4_096, images: false, reasoning: false },
|
|
45
|
+
stream() {
|
|
46
|
+
throw new CliError("no_model", "this command calls a model: pass --model <provider>:<model id>");
|
|
47
|
+
},
|
|
48
|
+
complete() {
|
|
49
|
+
return Promise.reject(new CliError("no_model", "this command calls a model: pass --model <provider>:<model id>"));
|
|
50
|
+
},
|
|
51
|
+
price: () => ({ total: null, basis: "unknown", currency: "USD" }),
|
|
52
|
+
};
|
|
53
|
+
function telemetry(options) {
|
|
54
|
+
if (options.otlpEndpoint === undefined)
|
|
55
|
+
return { observers: [] };
|
|
56
|
+
const tracer = otlpTracer({
|
|
57
|
+
endpoint: options.otlpEndpoint,
|
|
58
|
+
...(options.fetch === undefined ? {} : { fetch: options.fetch }),
|
|
59
|
+
});
|
|
60
|
+
return {
|
|
61
|
+
observers: [otelObserver({ tracer, agentName: "buildanagent", childContext: tracer.childContext })],
|
|
62
|
+
tracer,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
/** Builds the harness for one command and connects a client to it. */
|
|
66
|
+
export async function openHost(options) {
|
|
67
|
+
const { paths } = options;
|
|
68
|
+
const registry = createToolRegistry();
|
|
69
|
+
for (const tool of options.tools ?? [])
|
|
70
|
+
registry.register(tool);
|
|
71
|
+
const rules = options.rules ?? {};
|
|
72
|
+
const pipeline = createPermissionPipeline({
|
|
73
|
+
mode: "default",
|
|
74
|
+
interactive: options.interactive,
|
|
75
|
+
policyVersion: POLICY_VERSION,
|
|
76
|
+
ask: [...defaultAskRules, ...(rules.ask ?? [])],
|
|
77
|
+
...(rules.deny === undefined ? {} : { deny: rules.deny }),
|
|
78
|
+
...(rules.allow === undefined ? {} : { allow: rules.allow }),
|
|
79
|
+
}, registry);
|
|
80
|
+
const { observers, tracer } = telemetry(options);
|
|
81
|
+
const signer = options.signing ? hmacSigner(await fileKeyStore(paths.keys).load()) : undefined;
|
|
82
|
+
const harness = createHarness({
|
|
83
|
+
registry,
|
|
84
|
+
model: options.model ?? NO_MODEL,
|
|
85
|
+
system: SYSTEM_PROMPT,
|
|
86
|
+
env: { cwd: options.cwd },
|
|
87
|
+
pipeline,
|
|
88
|
+
context: createContextPolicy({ spill: fileSpillStore({ dir: paths.spill }) }),
|
|
89
|
+
observers,
|
|
90
|
+
...(signer === undefined ? {} : { signer }),
|
|
91
|
+
});
|
|
92
|
+
const dispatcher = createDispatcher({
|
|
93
|
+
harness,
|
|
94
|
+
store: jsonlStore({ dir: paths.sessions }),
|
|
95
|
+
index: fileIndex({ dir: paths.sessions }),
|
|
96
|
+
lock: fileLock({ dir: paths.locks }),
|
|
97
|
+
userId: USER_ID,
|
|
98
|
+
serverName: "buildanagent",
|
|
99
|
+
...(options.budgetUsd === undefined ? {} : { turn: { budgetUsd: options.budgetUsd } }),
|
|
100
|
+
});
|
|
101
|
+
const client = inProcessTransport(dispatcher);
|
|
102
|
+
return {
|
|
103
|
+
harness,
|
|
104
|
+
dispatcher,
|
|
105
|
+
client,
|
|
106
|
+
paths,
|
|
107
|
+
async close() {
|
|
108
|
+
await dispatcher.close();
|
|
109
|
+
client.close();
|
|
110
|
+
await tracer?.flush();
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
//# sourceMappingURL=host.js.map
|