@buildanagent/cli 0.0.0-bootstrap.0 → 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.
Files changed (78) hide show
  1. package/LICENSE +54 -0
  2. package/LICENSE-APACHE +202 -0
  3. package/LICENSE-MIT +21 -0
  4. package/README.md +144 -0
  5. package/dist/args.d.ts +20 -0
  6. package/dist/args.js +76 -0
  7. package/dist/args.js.map +1 -0
  8. package/dist/ask.d.ts +22 -0
  9. package/dist/ask.js +108 -0
  10. package/dist/ask.js.map +1 -0
  11. package/dist/bin.d.ts +2 -0
  12. package/dist/bin.js +26 -0
  13. package/dist/bin.js.map +1 -0
  14. package/dist/cli.d.ts +9 -0
  15. package/dist/cli.js +111 -0
  16. package/dist/cli.js.map +1 -0
  17. package/dist/command-lines.d.ts +25 -0
  18. package/dist/command-lines.js +166 -0
  19. package/dist/command-lines.js.map +1 -0
  20. package/dist/commands/chat.d.ts +18 -0
  21. package/dist/commands/chat.js +52 -0
  22. package/dist/commands/chat.js.map +1 -0
  23. package/dist/commands/keys.d.ts +3 -0
  24. package/dist/commands/keys.js +47 -0
  25. package/dist/commands/keys.js.map +1 -0
  26. package/dist/commands/rpc.d.ts +3 -0
  27. package/dist/commands/rpc.js +33 -0
  28. package/dist/commands/rpc.js.map +1 -0
  29. package/dist/commands/run.d.ts +3 -0
  30. package/dist/commands/run.js +20 -0
  31. package/dist/commands/run.js.map +1 -0
  32. package/dist/commands/sessions.d.ts +3 -0
  33. package/dist/commands/sessions.js +161 -0
  34. package/dist/commands/sessions.js.map +1 -0
  35. package/dist/commands/unlock.d.ts +3 -0
  36. package/dist/commands/unlock.js +31 -0
  37. package/dist/commands/unlock.js.map +1 -0
  38. package/dist/errors.d.ts +31 -0
  39. package/dist/errors.js +22 -0
  40. package/dist/errors.js.map +1 -0
  41. package/dist/host.d.ts +61 -0
  42. package/dist/host.js +114 -0
  43. package/dist/host.js.map +1 -0
  44. package/dist/index.d.ts +12 -0
  45. package/dist/index.js +11 -0
  46. package/dist/index.js.map +1 -0
  47. package/dist/io.d.ts +36 -0
  48. package/dist/io.js +18 -0
  49. package/dist/io.js.map +1 -0
  50. package/dist/live.d.ts +33 -0
  51. package/dist/live.js +100 -0
  52. package/dist/live.js.map +1 -0
  53. package/dist/meter.d.ts +50 -0
  54. package/dist/meter.js +91 -0
  55. package/dist/meter.js.map +1 -0
  56. package/dist/model.d.ts +12 -0
  57. package/dist/model.js +35 -0
  58. package/dist/model.js.map +1 -0
  59. package/dist/options.d.ts +30 -0
  60. package/dist/options.js +2 -0
  61. package/dist/options.js.map +1 -0
  62. package/dist/otlp.d.ts +28 -0
  63. package/dist/otlp.js +110 -0
  64. package/dist/otlp.js.map +1 -0
  65. package/dist/output.d.ts +18 -0
  66. package/dist/output.js +28 -0
  67. package/dist/output.js.map +1 -0
  68. package/dist/render.d.ts +18 -0
  69. package/dist/render.js +65 -0
  70. package/dist/render.js.map +1 -0
  71. package/dist/visible.d.ts +11 -0
  72. package/dist/visible.js +63 -0
  73. package/dist/visible.js.map +1 -0
  74. package/dist/watch.d.ts +63 -0
  75. package/dist/watch.js +219 -0
  76. package/dist/watch.js.map +1 -0
  77. package/llms.txt +31 -0
  78. package/package.json +44 -5
@@ -0,0 +1 @@
1
+ {"version":3,"file":"host.js","sourceRoot":"","sources":["../src/host.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,mBAAmB,EAAE,MAAM,+BAA+B,CAAC;AACpE,OAAO,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AACpE,OAAO,EAAE,wBAAwB,EAAE,eAAe,EAAa,MAAM,mCAAmC,CAAC;AACzG,OAAO,EACL,gBAAgB,EAChB,aAAa,EAIb,kBAAkB,GACnB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,YAAY,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,qCAAqC,CAAC;AACpG,OAAO,EAAE,kBAAkB,EAAyB,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,CAAC,EAAE,GAAG,EAAE,KAAK,CAAC,KAAK,EAAE,CAAC,EAAE,CAAC;QAC7E,SAAS;QACT,GAAG,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC;KAC5C,CAAC,CAAC;IACH,MAAM,UAAU,GAAG,gBAAgB,CAAC;QAClC,OAAO;QACP,KAAK,EAAE,UAAU,CAAC,EAAE,GAAG,EAAE,KAAK,CAAC,QAAQ,EAAE,CAAC;QAC1C,KAAK,EAAE,SAAS,CAAC,EAAE,GAAG,EAAE,KAAK,CAAC,QAAQ,EAAE,CAAC;QACzC,IAAI,EAAE,QAAQ,CAAC,EAAE,GAAG,EAAE,KAAK,CAAC,KAAK,EAAE,CAAC;QACpC,MAAM,EAAE,OAAO;QACf,UAAU,EAAE,cAAc;QAC1B,GAAG,CAAC,OAAO,CAAC,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,SAAS,EAAE,OAAO,CAAC,SAAS,EAAE,EAAE,CAAC;KACvF,CAAC,CAAC;IACH,MAAM,MAAM,GAAG,kBAAkB,CAAC,UAAU,CAAC,CAAC;IAC9C,OAAO;QACL,OAAO;QACP,UAAU;QACV,MAAM;QACN,KAAK;QACL,KAAK,CAAC,KAAK;YACT,MAAM,UAAU,CAAC,KAAK,EAAE,CAAC;YACzB,MAAM,CAAC,KAAK,EAAE,CAAC;YACf,MAAM,MAAM,EAAE,KAAK,EAAE,CAAC;QACxB,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * The harness a command runs on, and the in-process client it talks to it through. Sessions, locks, spilled tool\n * output and the approval key ring live under one state folder on this machine, and the only connections a host can\n * open are to the model a command names and to the `--otlp-endpoint` collector.\n */\nimport type { Model } from \"@buildanagent/gateway\";\nimport { createContextPolicy } from \"@buildanagent/harness/context\";\nimport { fileSpillStore } from \"@buildanagent/harness/context/file\";\nimport { createPermissionPipeline, defaultAskRules, type Rule } from \"@buildanagent/harness/permissions\";\nimport {\n createDispatcher,\n createHarness,\n type Dispatcher,\n type Harness,\n type InProcessClient,\n inProcessTransport,\n} from \"@buildanagent/harness/server\";\nimport { fileIndex, fileKeyStore, fileLock, jsonlStore } from \"@buildanagent/harness/session/jsonl\";\nimport { createToolRegistry, type ToolRegistration } from \"@buildanagent/harness/tools\";\nimport { hmacSigner, type Observer } from \"@buildanagent/sdk\";\nimport { otelObserver } from \"@buildanagent/sdk/otel\";\nimport { CliError } from \"./errors.js\";\nimport { type OtlpTracer, otlpTracer } from \"./otlp.js\";\n\n/** The system prompt every turn starts from. */\nexport const SYSTEM_PROMPT = \"You are a coding agent. Work in the user's project, and ask before you change anything.\";\n\n/** The user every session is stored under: the CLI serves the one person at the terminal. */\nexport const USER_ID = \"local\";\n\n/** The policy version every approval the CLI asks for carries. */\nconst POLICY_VERSION = \"buildanagent-cli-1\";\n\n/** Where a host keeps its files. */\nexport interface StatePaths {\n readonly root: string;\n readonly sessions: string;\n readonly locks: string;\n readonly spill: string;\n readonly keys: string;\n}\n\n/** The permission rules a host adds to the harness's default ask rules. */\nexport interface HostRules {\n readonly deny?: readonly Rule[];\n readonly ask?: readonly Rule[];\n readonly allow?: readonly Rule[];\n}\n\n/** What `openHost()` takes. */\nexport interface HostOptions {\n readonly paths: StatePaths;\n readonly cwd: string;\n /** The model turns use. Left out, a turn that calls a model fails, which suits the commands that only read. */\n readonly model?: Model;\n /** Whether a person answers approvals. Without one, a call no rule settles is denied instead of asked. */\n readonly interactive: boolean;\n /** Load the approval key ring, which a turn needs to sign its pauses. Read-only commands leave it unloaded. */\n readonly signing: boolean;\n readonly tools?: readonly ToolRegistration[];\n readonly rules?: HostRules;\n readonly budgetUsd?: number;\n readonly otlpEndpoint?: string;\n readonly fetch?: typeof globalThis.fetch;\n}\n\n/** A harness, its dispatcher and one in-process client. */\nexport interface Host {\n readonly harness: Harness;\n readonly dispatcher: Dispatcher;\n readonly client: InProcessClient;\n readonly paths: StatePaths;\n /** Ends every turn, closes the client and sends any spans. */\n close(): Promise<void>;\n}\n\n/** The folders under `root`, which `--state-dir` names or the environment implies. */\nexport function statePaths(root: string): StatePaths {\n const base = root.replace(/\\/+$/, \"\");\n return {\n root: base,\n sessions: `${base}/sessions`,\n locks: `${base}/locks`,\n spill: `${base}/spill`,\n keys: `${base}/keys.json`,\n };\n}\n\n/**\n * The state folder: `--state-dir`, else `$XDG_STATE_HOME/buildanagent`, else `~/.local/state/buildanagent`, which is\n * where the harness keeps its key ring by default too. Throws a `CliError`, code `no_state_dir`, when none is known.\n */\nexport function stateRoot(flag: string | undefined, env: Readonly<Record<string, string | undefined>>): string {\n if (flag !== undefined && flag !== \"\") return flag;\n if (env.XDG_STATE_HOME !== undefined && env.XDG_STATE_HOME !== \"\") return `${env.XDG_STATE_HOME}/buildanagent`;\n if (env.HOME !== undefined && env.HOME !== \"\") return `${env.HOME}/.local/state/buildanagent`;\n throw new CliError(\"no_state_dir\", \"set HOME or XDG_STATE_HOME, or pass --state-dir <folder>\");\n}\n\n/** A model for the commands that only read: any call fails at once, so it can never reach a provider. */\nconst NO_MODEL: Model = {\n ref: { api: \"none\", provider: \"none\", id: \"none\" },\n caps: { contextWindow: 200_000, maxOutputTokens: 4_096, images: false, reasoning: false },\n stream() {\n throw new CliError(\"no_model\", \"this command calls a model: pass --model <provider>:<model id>\");\n },\n complete() {\n return Promise.reject(new CliError(\"no_model\", \"this command calls a model: pass --model <provider>:<model id>\"));\n },\n price: () => ({ total: null, basis: \"unknown\", currency: \"USD\" }),\n};\n\nfunction telemetry(options: HostOptions): { observers: Observer[]; tracer?: OtlpTracer } {\n if (options.otlpEndpoint === undefined) return { observers: [] };\n const tracer = otlpTracer({\n endpoint: options.otlpEndpoint,\n ...(options.fetch === undefined ? {} : { fetch: options.fetch }),\n });\n return {\n observers: [otelObserver({ tracer, agentName: \"buildanagent\", childContext: tracer.childContext })],\n tracer,\n };\n}\n\n/** Builds the harness for one command and connects a client to it. */\nexport async function openHost(options: HostOptions): Promise<Host> {\n const { paths } = options;\n const registry = createToolRegistry();\n for (const tool of options.tools ?? []) registry.register(tool);\n const rules = options.rules ?? {};\n const pipeline = createPermissionPipeline(\n {\n mode: \"default\",\n interactive: options.interactive,\n policyVersion: POLICY_VERSION,\n ask: [...defaultAskRules, ...(rules.ask ?? [])],\n ...(rules.deny === undefined ? {} : { deny: rules.deny }),\n ...(rules.allow === undefined ? {} : { allow: rules.allow }),\n },\n registry,\n );\n const { observers, tracer } = telemetry(options);\n const signer = options.signing ? hmacSigner(await fileKeyStore(paths.keys).load()) : undefined;\n const harness = createHarness({\n registry,\n model: options.model ?? NO_MODEL,\n system: SYSTEM_PROMPT,\n env: { cwd: options.cwd },\n pipeline,\n context: createContextPolicy({ spill: fileSpillStore({ dir: paths.spill }) }),\n observers,\n ...(signer === undefined ? {} : { signer }),\n });\n const dispatcher = createDispatcher({\n harness,\n store: jsonlStore({ dir: paths.sessions }),\n index: fileIndex({ dir: paths.sessions }),\n lock: fileLock({ dir: paths.locks }),\n userId: USER_ID,\n serverName: \"buildanagent\",\n ...(options.budgetUsd === undefined ? {} : { turn: { budgetUsd: options.budgetUsd } }),\n });\n const client = inProcessTransport(dispatcher);\n return {\n harness,\n dispatcher,\n client,\n paths,\n async close() {\n await dispatcher.close();\n client.close();\n await tracer?.flush();\n },\n };\n}\n"]}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * `@buildanagent/cli`, the buildanagent command line, which runs the harness in a terminal. `runCli()` runs one
3
+ * command line against the terminal a `CliIo` describes, which is what the `buildanagent` binary does with the
4
+ * process's own streams.
5
+ */
6
+ export { HELP, runCli } from "./cli.js";
7
+ export { CliError, type CliErrorCode, isCliError } from "./errors.js";
8
+ export type { HostRules } from "./host.js";
9
+ export { type CliIo, type CliStreams, linesOf } from "./io.js";
10
+ export type { CliOptions } from "./options.js";
11
+ /** The package name, `@buildanagent/cli`. */
12
+ export declare const PACKAGE_NAME = "@buildanagent/cli";
package/dist/index.js ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * `@buildanagent/cli`, the buildanagent command line, which runs the harness in a terminal. `runCli()` runs one
3
+ * command line against the terminal a `CliIo` describes, which is what the `buildanagent` binary does with the
4
+ * process's own streams.
5
+ */
6
+ export { HELP, runCli } from "./cli.js";
7
+ export { CliError, isCliError } from "./errors.js";
8
+ export { linesOf } from "./io.js";
9
+ /** The package name, `@buildanagent/cli`. */
10
+ export const PACKAGE_NAME = "@buildanagent/cli";
11
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AACxC,OAAO,EAAE,QAAQ,EAAqB,UAAU,EAAE,MAAM,aAAa,CAAC;AAEtE,OAAO,EAA+B,OAAO,EAAE,MAAM,SAAS,CAAC;AAG/D,6CAA6C;AAC7C,MAAM,CAAC,MAAM,YAAY,GAAG,mBAAmB,CAAC","sourcesContent":["/**\n * `@buildanagent/cli`, the buildanagent command line, which runs the harness in a terminal. `runCli()` runs one\n * command line against the terminal a `CliIo` describes, which is what the `buildanagent` binary does with the\n * process's own streams.\n */\nexport { HELP, runCli } from \"./cli.js\";\nexport { CliError, type CliErrorCode, isCliError } from \"./errors.js\";\nexport type { HostRules } from \"./host.js\";\nexport { type CliIo, type CliStreams, linesOf } from \"./io.js\";\nexport type { CliOptions } from \"./options.js\";\n\n/** The package name, `@buildanagent/cli`. */\nexport const PACKAGE_NAME = \"@buildanagent/cli\";\n"]}
package/dist/io.d.ts ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * What a command reads and writes. The binary gives it the process's standard streams, environment and folder; a
3
+ * test or a host program gives it its own. Every command except `rpc` runs without a terminal, and `rpc` needs the byte
4
+ * `streams`.
5
+ */
6
+ import type { StdioInput, StdioOutput } from "@buildanagent/harness/server";
7
+ /**
8
+ * The standard streams as bytes, which `rpc` serves the protocol over. They take Node or Web streams, so a test can
9
+ * pass a pair of its own.
10
+ */
11
+ export interface CliStreams {
12
+ /** Standard input: the client's protocol lines. */
13
+ readonly input: StdioInput;
14
+ /** Standard output: the server's protocol lines, and nothing else. */
15
+ readonly output: StdioOutput;
16
+ }
17
+ /** The terminal a command talks to. */
18
+ export interface CliIo {
19
+ /** Writes to standard output: a run's answer, or its JSON lines. */
20
+ readonly write: (text: string) => void;
21
+ /** Writes to standard error: progress, prompts, warnings and errors. */
22
+ readonly error: (text: string) => void;
23
+ /** Reads the next line of standard input without its line break, or `undefined` once input has ended. */
24
+ readonly readLine: () => Promise<string | undefined>;
25
+ /** The environment variables. The CLI reads `HOME`, `XDG_STATE_HOME` and the key of the provider `--model` names. */
26
+ readonly env: Readonly<Record<string, string | undefined>>;
27
+ /** The folder a new session records as its working folder. */
28
+ readonly cwd: string;
29
+ /**
30
+ * The standard streams as bytes, for `rpc`. Only `rpc` reads them, and it refuses to start without them; every other
31
+ * command reads through `readLine` and writes through `write`.
32
+ */
33
+ readonly streams?: CliStreams;
34
+ }
35
+ /** Splits a stream of text or bytes into lines at `\n`, dropping a `\r` before it. */
36
+ export declare function linesOf(chunks: AsyncIterable<string | Uint8Array>): AsyncGenerator<string>;
package/dist/io.js ADDED
@@ -0,0 +1,18 @@
1
+ /** Splits a stream of text or bytes into lines at `\n`, dropping a `\r` before it. */
2
+ export async function* linesOf(chunks) {
3
+ const decoder = new TextDecoder();
4
+ let rest = "";
5
+ for await (const chunk of chunks) {
6
+ rest += typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true });
7
+ let end = rest.indexOf("\n");
8
+ while (end >= 0) {
9
+ yield rest.slice(0, end).replace(/\r$/, "");
10
+ rest = rest.slice(end + 1);
11
+ end = rest.indexOf("\n");
12
+ }
13
+ }
14
+ rest += decoder.decode();
15
+ if (rest !== "")
16
+ yield rest.replace(/\r$/, "");
17
+ }
18
+ //# sourceMappingURL=io.js.map
package/dist/io.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"io.js","sourceRoot":"","sources":["../src/io.ts"],"names":[],"mappings":"AAqCA,sFAAsF;AACtF,MAAM,CAAC,KAAK,SAAS,CAAC,CAAC,OAAO,CAAC,MAA0C;IACvE,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;IAClC,IAAI,IAAI,GAAG,EAAE,CAAC;IACd,IAAI,KAAK,EAAE,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QACjC,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QACpF,IAAI,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QAC7B,OAAO,GAAG,IAAI,CAAC,EAAE,CAAC;YAChB,MAAM,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;YAC5C,IAAI,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC;YAC3B,GAAG,GAAG,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC;QAC3B,CAAC;IACH,CAAC;IACD,IAAI,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;IACzB,IAAI,IAAI,KAAK,EAAE;QAAE,MAAM,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;AACjD,CAAC","sourcesContent":["/**\n * What a command reads and writes. The binary gives it the process's standard streams, environment and folder; a\n * test or a host program gives it its own. Every command except `rpc` runs without a terminal, and `rpc` needs the byte\n * `streams`.\n */\nimport type { StdioInput, StdioOutput } from \"@buildanagent/harness/server\";\n\n/**\n * The standard streams as bytes, which `rpc` serves the protocol over. They take Node or Web streams, so a test can\n * pass a pair of its own.\n */\nexport interface CliStreams {\n /** Standard input: the client's protocol lines. */\n readonly input: StdioInput;\n /** Standard output: the server's protocol lines, and nothing else. */\n readonly output: StdioOutput;\n}\n\n/** The terminal a command talks to. */\nexport interface CliIo {\n /** Writes to standard output: a run's answer, or its JSON lines. */\n readonly write: (text: string) => void;\n /** Writes to standard error: progress, prompts, warnings and errors. */\n readonly error: (text: string) => void;\n /** Reads the next line of standard input without its line break, or `undefined` once input has ended. */\n readonly readLine: () => Promise<string | undefined>;\n /** The environment variables. The CLI reads `HOME`, `XDG_STATE_HOME` and the key of the provider `--model` names. */\n readonly env: Readonly<Record<string, string | undefined>>;\n /** The folder a new session records as its working folder. */\n readonly cwd: string;\n /**\n * The standard streams as bytes, for `rpc`. Only `rpc` reads them, and it refuses to start without them; every other\n * command reads through `readLine` and writes through `write`.\n */\n readonly streams?: CliStreams;\n}\n\n/** Splits a stream of text or bytes into lines at `\\n`, dropping a `\\r` before it. */\nexport async function* linesOf(chunks: AsyncIterable<string | Uint8Array>): AsyncGenerator<string> {\n const decoder = new TextDecoder();\n let rest = \"\";\n for await (const chunk of chunks) {\n rest += typeof chunk === \"string\" ? chunk : decoder.decode(chunk, { stream: true });\n let end = rest.indexOf(\"\\n\");\n while (end >= 0) {\n yield rest.slice(0, end).replace(/\\r$/, \"\");\n rest = rest.slice(end + 1);\n end = rest.indexOf(\"\\n\");\n }\n }\n rest += decoder.decode();\n if (rest !== \"\") yield rest.replace(/\\r$/, \"\");\n}\n"]}
package/dist/live.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The setup `run`, `chat` and `resume` share: a host with a model, a session created or opened on its client, and
3
+ * the meter and renderer its events go to. It reports the preamble's size when the session starts, the meter's
4
+ * warnings as they happen, and how each turn settled.
5
+ */
6
+ import type { TurnResultSummary } from "@buildanagent/protocol";
7
+ import { type Host } from "./host.js";
8
+ import { Meter } from "./meter.js";
9
+ import type { CommandContext } from "./options.js";
10
+ import { Output } from "./output.js";
11
+ import { SessionWatch } from "./watch.js";
12
+ /** The version `initialize` reports for this client. */
13
+ export declare const CLI_VERSION = "0.0.0";
14
+ /** A session ready for turns. */
15
+ export interface Live {
16
+ readonly host: Host;
17
+ readonly watch: SessionWatch;
18
+ readonly meter: Meter;
19
+ readonly out: Output;
20
+ /** The requests that waited when a stored session was opened. */
21
+ readonly pending: readonly string[];
22
+ }
23
+ /** Opens a host with a model and a session on it: the stored session `id`, or a new one. */
24
+ export declare function startLive(context: CommandContext, interactive: boolean, id?: string): Promise<Live>;
25
+ /**
26
+ * Runs `body`, then stops the watch and closes the host, which sends any spans. When `body` throws, a close that
27
+ * fails as well is dropped, so the error that ended the command is the one reported.
28
+ */
29
+ export declare function withLive<T>(live: Live, body: () => Promise<T>): Promise<T>;
30
+ /** Reports how a turn settled, with the meter's totals. */
31
+ export declare function reportSettled(live: Live, result: TurnResultSummary): void;
32
+ /** The exit status for how a turn settled: 0 for `done`, 3 while it waits for a person, and 1 otherwise. */
33
+ export declare function exitStatus(result: TurnResultSummary): number;
package/dist/live.js ADDED
@@ -0,0 +1,100 @@
1
+ import { openHost } from "./host.js";
2
+ import { Meter, readingText, warningText } from "./meter.js";
3
+ import { modelFromSpec } from "./model.js";
4
+ import { Output } from "./output.js";
5
+ import { liveRenderer } from "./render.js";
6
+ import { visible } from "./visible.js";
7
+ import { openStored, SessionWatch, WAITING_REASONS } from "./watch.js";
8
+ /** The version `initialize` reports for this client. */
9
+ export const CLI_VERSION = "0.0.0";
10
+ function listenerFor(context, meter, out, session) {
11
+ const render = liveRenderer(context.io);
12
+ return (event, seq, replayed) => {
13
+ const notes = meter.observe(event, replayed);
14
+ if (replayed)
15
+ return;
16
+ if (out.json)
17
+ out.line({ type: "event", session: session(), seq, event });
18
+ else
19
+ render(event);
20
+ for (const note of notes)
21
+ out.note(warningText(note), { type: "warning", ...note });
22
+ };
23
+ }
24
+ async function attach(context, host, listener, id) {
25
+ const { client } = host;
26
+ await client.request("initialize", { clientInfo: { name: "buildanagent", version: CLI_VERSION }, capabilities: [] });
27
+ if (id === undefined) {
28
+ const { session } = await client.request("session/create", { cwd: context.io.cwd });
29
+ return { watch: new SessionWatch(client, session, listener), pending: [] };
30
+ }
31
+ const watch = new SessionWatch(client, id, listener);
32
+ return { watch, pending: await openStored(client, watch, context.io.cwd) };
33
+ }
34
+ /** Opens a host with a model and a session on it: the stored session `id`, or a new one. */
35
+ export async function startLive(context, interactive, id) {
36
+ const { flags } = context;
37
+ const model = context.options.model ?? modelFromSpec(flags.model, context.io.env);
38
+ const host = await openHost({ ...context.hostOptions, model, interactive, signing: true });
39
+ const meter = new Meter(flags.budgetUsd);
40
+ const out = new Output(context.io, flags.json);
41
+ let session = id ?? "";
42
+ try {
43
+ const attached = await attach(context, host, listenerFor(context, meter, out, () => session), id);
44
+ session = attached.watch.session;
45
+ const { registry, system } = host.harness;
46
+ const tools = registry.list().filter((tool) => tool.exposure === "direct").length;
47
+ const preambleTokens = registry.preambleTokens({ system });
48
+ out.note(`session ${session} · preamble ~${preambleTokens} tokens (system prompt and ${tools} tools)`, {
49
+ type: "session",
50
+ session,
51
+ preambleTokens,
52
+ tools,
53
+ });
54
+ return { host, meter, out, ...attached };
55
+ }
56
+ catch (error) {
57
+ // A close that fails too, such as a collector that can't be reached, must not hide why the session didn't start.
58
+ await host.close().catch(() => undefined);
59
+ throw error;
60
+ }
61
+ }
62
+ /**
63
+ * Runs `body`, then stops the watch and closes the host, which sends any spans. When `body` throws, a close that
64
+ * fails as well is dropped, so the error that ended the command is the one reported.
65
+ */
66
+ export async function withLive(live, body) {
67
+ let result;
68
+ try {
69
+ result = await body();
70
+ }
71
+ catch (error) {
72
+ live.watch.stop();
73
+ await live.host.close().catch(() => undefined);
74
+ throw error;
75
+ }
76
+ live.watch.stop();
77
+ await live.host.close();
78
+ return result;
79
+ }
80
+ /** Reports how a turn settled, with the meter's totals. */
81
+ export function reportSettled(live, result) {
82
+ const reading = live.meter.reading();
83
+ const why = result.error === undefined ? "" : `: ${visible(result.error.message)}`;
84
+ const waiting = WAITING_REASONS.has(result.stopReason)
85
+ ? ` · answer with: buildanagent resume ${live.watch.session}`
86
+ : "";
87
+ live.out.note(`[${result.stopReason}${why}] ${readingText(reading)}${waiting}`, {
88
+ type: "settled",
89
+ session: live.watch.session,
90
+ result,
91
+ meter: reading,
92
+ });
93
+ }
94
+ /** The exit status for how a turn settled: 0 for `done`, 3 while it waits for a person, and 1 otherwise. */
95
+ export function exitStatus(result) {
96
+ if (result.stopReason === "done")
97
+ return 0;
98
+ return WAITING_REASONS.has(result.stopReason) ? 3 : 1;
99
+ }
100
+ //# sourceMappingURL=live.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"live.js","sourceRoot":"","sources":["../src/live.ts"],"names":[],"mappings":"AAMA,OAAO,EAAa,QAAQ,EAAE,MAAM,WAAW,CAAC;AAChD,OAAO,EAAE,KAAK,EAAE,WAAW,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAE3C,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EAAsB,UAAU,EAAE,YAAY,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAE3F,wDAAwD;AACxD,MAAM,CAAC,MAAM,WAAW,GAAG,OAAO,CAAC;AAYnC,SAAS,WAAW,CAAC,OAAuB,EAAE,KAAY,EAAE,GAAW,EAAE,OAAqB;IAC5F,MAAM,MAAM,GAAG,YAAY,CAAC,OAAO,CAAC,EAAE,CAAC,CAAC;IACxC,OAAO,CAAC,KAAK,EAAE,GAAG,EAAE,QAAQ,EAAE,EAAE;QAC9B,MAAM,KAAK,GAAG,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC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,GAAG,eAAe,CAAC,GAAG,CAAC,MAAM,CAAC,UAAU,CAAC;QACpD,CAAC,CAAC,uCAAuC,IAAI,CAAC,KAAK,CAAC,OAAO,EAAE;QAC7D,CAAC,CAAC,EAAE,CAAC;IACP,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,UAAU,GAAG,GAAG,KAAK,WAAW,CAAC,OAAO,CAAC,GAAG,OAAO,EAAE,EAAE;QAC9E,IAAI,EAAE,SAAS;QACf,OAAO,EAAE,IAAI,CAAC,KAAK,CAAC,OAAO;QAC3B,MAAM;QACN,KAAK,EAAE,OAAO;KACf,CAAC,CAAC;AACL,CAAC;AAED,4GAA4G;AAC5G,MAAM,UAAU,UAAU,CAAC,MAAyB;IAClD,IAAI,MAAM,CAAC,UAAU,KAAK,MAAM;QAAE,OAAO,CAAC,CAAC;IAC3C,OAAO,eAAe,CAAC,GAAG,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AACxD,CAAC","sourcesContent":["/**\n * The setup `run`, `chat` and `resume` share: a host with a model, a session created or opened on its client, and\n * the meter and renderer its events go to. It reports the preamble's size when the session starts, the meter's\n * warnings as they happen, and how each turn settled.\n */\nimport type { TurnResultSummary } from \"@buildanagent/protocol\";\nimport { type Host, openHost } from \"./host.js\";\nimport { Meter, readingText, warningText } from \"./meter.js\";\nimport { modelFromSpec } from \"./model.js\";\nimport type { CommandContext } from \"./options.js\";\nimport { Output } from \"./output.js\";\nimport { liveRenderer } from \"./render.js\";\nimport { visible } from \"./visible.js\";\nimport { type EventListener, openStored, SessionWatch, WAITING_REASONS } from \"./watch.js\";\n\n/** The version `initialize` reports for this client. */\nexport const CLI_VERSION = \"0.0.0\";\n\n/** A session ready for turns. */\nexport interface Live {\n readonly host: Host;\n readonly watch: SessionWatch;\n readonly meter: Meter;\n readonly out: Output;\n /** The requests that waited when a stored session was opened. */\n readonly pending: readonly string[];\n}\n\nfunction listenerFor(context: CommandContext, meter: Meter, out: Output, session: () => string): EventListener {\n const render = liveRenderer(context.io);\n return (event, seq, replayed) => {\n const notes = meter.observe(event, replayed);\n if (replayed) return;\n if (out.json) out.line({ type: \"event\", session: session(), seq, event });\n else render(event);\n for (const note of notes) out.note(warningText(note), { type: \"warning\", ...note });\n };\n}\n\nasync function attach(context: CommandContext, host: Host, listener: EventListener, id: string | undefined) {\n const { client } = host;\n await client.request(\"initialize\", { clientInfo: { name: \"buildanagent\", version: CLI_VERSION }, capabilities: [] });\n if (id === undefined) {\n const { session } = await client.request(\"session/create\", { cwd: context.io.cwd });\n return { watch: new SessionWatch(client, session, listener), pending: [] };\n }\n const watch = new SessionWatch(client, id, listener);\n return { watch, pending: await openStored(client, watch, context.io.cwd) };\n}\n\n/** Opens a host with a model and a session on it: the stored session `id`, or a new one. */\nexport async function startLive(context: CommandContext, interactive: boolean, id?: string): Promise<Live> {\n const { flags } = context;\n const model = context.options.model ?? modelFromSpec(flags.model, context.io.env);\n const host = await openHost({ ...context.hostOptions, model, interactive, signing: true });\n const meter = new Meter(flags.budgetUsd);\n const out = new Output(context.io, flags.json);\n let session = id ?? \"\";\n try {\n const attached = await attach(\n context,\n host,\n listenerFor(context, meter, out, () => session),\n id,\n );\n session = attached.watch.session;\n const { registry, system } = host.harness;\n const tools = registry.list().filter((tool) => tool.exposure === \"direct\").length;\n const preambleTokens = registry.preambleTokens({ system });\n out.note(`session ${session} · preamble ~${preambleTokens} tokens (system prompt and ${tools} tools)`, {\n type: \"session\",\n session,\n preambleTokens,\n tools,\n });\n return { host, meter, out, ...attached };\n } catch (error) {\n // A close that fails too, such as a collector that can't be reached, must not hide why the session didn't start.\n await host.close().catch(() => undefined);\n throw error;\n }\n}\n\n/**\n * Runs `body`, then stops the watch and closes the host, which sends any spans. When `body` throws, a close that\n * fails as well is dropped, so the error that ended the command is the one reported.\n */\nexport async function withLive<T>(live: Live, body: () => Promise<T>): Promise<T> {\n let result: T;\n try {\n result = await body();\n } catch (error) {\n live.watch.stop();\n await live.host.close().catch(() => undefined);\n throw error;\n }\n live.watch.stop();\n await live.host.close();\n return result;\n}\n\n/** Reports how a turn settled, with the meter's totals. */\nexport function reportSettled(live: Live, result: TurnResultSummary): void {\n const reading = live.meter.reading();\n const why = result.error === undefined ? \"\" : `: ${visible(result.error.message)}`;\n const waiting = WAITING_REASONS.has(result.stopReason)\n ? ` · answer with: buildanagent resume ${live.watch.session}`\n : \"\";\n live.out.note(`[${result.stopReason}${why}] ${readingText(reading)}${waiting}`, {\n type: \"settled\",\n session: live.watch.session,\n result,\n meter: reading,\n });\n}\n\n/** The exit status for how a turn settled: 0 for `done`, 3 while it waits for a person, and 1 otherwise. */\nexport function exitStatus(result: TurnResultSummary): number {\n if (result.stopReason === \"done\") return 0;\n return WAITING_REASONS.has(result.stopReason) ? 3 : 1;\n}\n"]}
@@ -0,0 +1,50 @@
1
+ /**
2
+ * The meter: what a session has cost so far and how full its context is, read from the events a turn streams. It
3
+ * warns once a session when the context passes 80% of its budget, and once a run when the run's spend passes 80% of
4
+ * `--budget`, so you see the warning before the budget stops the run or the context has to be summarised. The budget
5
+ * is per run, as the harness applies it: a turn is one run, and each resume after an answer is another.
6
+ */
7
+ import type { HarnessEvent } from "@buildanagent/protocol";
8
+ import type { AgentEvent } from "@buildanagent/sdk";
9
+ /** The share of a limit at which the meter warns. */
10
+ export declare const WARN_AT = 0.8;
11
+ /** A warning or reading the meter reports. */
12
+ export type MeterNote = {
13
+ readonly kind: "context_warning";
14
+ readonly tokens: number;
15
+ readonly budget: number;
16
+ } | {
17
+ readonly kind: "budget_warning";
18
+ readonly spentUsd: number;
19
+ readonly capUsd: number;
20
+ };
21
+ /** The meter's totals. */
22
+ export interface MeterReading {
23
+ /** The cost of every priced call in US dollars. */
24
+ readonly costUsd: number;
25
+ /** How many calls had no price, so `costUsd` leaves them out. */
26
+ readonly unpriced: number;
27
+ /** The last context fill, when the harness reported one. */
28
+ readonly fill?: {
29
+ readonly tokens: number;
30
+ readonly budget: number;
31
+ };
32
+ }
33
+ /** Counts cost and context fill for one session, and says when to warn. */
34
+ export declare class Meter {
35
+ #private;
36
+ /** `budgetUsd` is the spend cap of each run, when it has one. */
37
+ constructor(budgetUsd?: number);
38
+ /**
39
+ * Takes one event and returns the warnings it causes: the context warning at most once a session, and the budget
40
+ * warning at most once a run. A `replayed` event, read back from the log, counts toward the session's totals but
41
+ * never warns, so it leaves both warnings for the live runs that follow.
42
+ */
43
+ observe(event: AgentEvent | HarnessEvent, replayed?: boolean): MeterNote[];
44
+ /** The totals so far. */
45
+ reading(): MeterReading;
46
+ }
47
+ /** One line for a warning. */
48
+ export declare function warningText(note: MeterNote): string;
49
+ /** One status line: the cost so far, and the context fill when the harness reported one. */
50
+ export declare function readingText(reading: MeterReading): string;
package/dist/meter.js ADDED
@@ -0,0 +1,91 @@
1
+ /** The share of a limit at which the meter warns. */
2
+ export const WARN_AT = 0.8;
3
+ /** Counts cost and context fill for one session, and says when to warn. */
4
+ export class Meter {
5
+ #budgetUsd;
6
+ #costUsd = 0;
7
+ #runCostUsd = 0;
8
+ #unpriced = 0;
9
+ #fill;
10
+ #contextWarned = false;
11
+ #budgetWarned = false;
12
+ /** `budgetUsd` is the spend cap of each run, when it has one. */
13
+ constructor(budgetUsd) {
14
+ this.#budgetUsd = budgetUsd;
15
+ }
16
+ /**
17
+ * Takes one event and returns the warnings it causes: the context warning at most once a session, and the budget
18
+ * warning at most once a run. A `replayed` event, read back from the log, counts toward the session's totals but
19
+ * never warns, so it leaves both warnings for the live runs that follow.
20
+ */
21
+ observe(event, replayed = false) {
22
+ if (event.type === "run_start") {
23
+ // A nested run streams into its parent's run, which keeps one budget.
24
+ if (event.parentRunId === undefined)
25
+ this.#startRun();
26
+ return [];
27
+ }
28
+ if (event.type === "context_fill")
29
+ return this.#contextFill(event.tokens, event.budget, replayed);
30
+ if (event.type === "budget_warning") {
31
+ if (replayed || this.#budgetWarned)
32
+ return [];
33
+ this.#budgetWarned = true;
34
+ return [{ kind: "budget_warning", spentUsd: event.spentUsd, capUsd: event.capUsd }];
35
+ }
36
+ if (event.type !== "entry_appended" || event.entry.type !== "usage")
37
+ return [];
38
+ const total = event.entry.cost.total;
39
+ if (total === null)
40
+ this.#unpriced += 1;
41
+ else {
42
+ this.#costUsd += total;
43
+ this.#runCostUsd += total;
44
+ }
45
+ return replayed ? [] : this.#checkBudget();
46
+ }
47
+ #contextFill(tokens, budget, replayed) {
48
+ this.#fill = { tokens, budget };
49
+ if (replayed || this.#contextWarned || budget <= 0 || tokens < budget * WARN_AT)
50
+ return [];
51
+ this.#contextWarned = true;
52
+ return [{ kind: "context_warning", tokens, budget }];
53
+ }
54
+ #startRun() {
55
+ this.#runCostUsd = 0;
56
+ this.#budgetWarned = false;
57
+ }
58
+ #checkBudget() {
59
+ const cap = this.#budgetUsd;
60
+ if (cap === undefined || this.#budgetWarned || this.#runCostUsd < cap * WARN_AT)
61
+ return [];
62
+ this.#budgetWarned = true;
63
+ return [{ kind: "budget_warning", spentUsd: this.#runCostUsd, capUsd: cap }];
64
+ }
65
+ /** The totals so far. */
66
+ reading() {
67
+ return {
68
+ costUsd: this.#costUsd,
69
+ unpriced: this.#unpriced,
70
+ ...(this.#fill === undefined ? {} : { fill: this.#fill }),
71
+ };
72
+ }
73
+ }
74
+ const percent = (part, whole) => `${Math.round((part / whole) * 100)}%`;
75
+ const usd = (value) => `$${value.toFixed(4)}`;
76
+ /** One line for a warning. */
77
+ export function warningText(note) {
78
+ return note.kind === "context_warning"
79
+ ? `warning: the context is ${percent(note.tokens, note.budget)} full (${note.tokens} of ${note.budget} tokens)`
80
+ : `warning: this turn has spent ${usd(note.spentUsd)}, ${percent(note.spentUsd, note.capUsd)} of its ${usd(note.capUsd)} budget`;
81
+ }
82
+ /** One status line: the cost so far, and the context fill when the harness reported one. */
83
+ export function readingText(reading) {
84
+ const unpriced = reading.unpriced === 0 ? "" : ` (+${reading.unpriced} unpriced)`;
85
+ const cost = `cost ${usd(reading.costUsd)}${unpriced}`;
86
+ if (reading.fill === undefined || reading.fill.budget <= 0)
87
+ return cost;
88
+ const { tokens, budget } = reading.fill;
89
+ return `context ${percent(tokens, budget)} (${tokens} of ${budget} tokens) · ${cost}`;
90
+ }
91
+ //# sourceMappingURL=meter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"meter.js","sourceRoot":"","sources":["../src/meter.ts"],"names":[],"mappings":"AASA,qDAAqD;AACrD,MAAM,CAAC,MAAM,OAAO,GAAG,GAAG,CAAC;AAiB3B,2EAA2E;AAC3E,MAAM,OAAO,KAAK;IACP,UAAU,CAAqB;IACxC,QAAQ,GAAG,CAAC,CAAC;IACb,WAAW,GAAG,CAAC,CAAC;IAChB,SAAS,GAAG,CAAC,CAAC;IACd,KAAK,CAAiD;IACtD,cAAc,GAAG,KAAK,CAAC;IACvB,aAAa,GAAG,KAAK,CAAC;IAEtB,iEAAiE;IACjE,YAAY,SAAkB;QAC5B,IAAI,CAAC,UAAU,GAAG,SAAS,CAAC;IAC9B,CAAC;IAED;;;;OAIG;IACH,OAAO,CAAC,KAAgC,EAAE,QAAQ,GAAG,KAAK;QACxD,IAAI,KAAK,CAAC,IAAI,KAAK,WAAW,EAAE,CAAC;YAC/B,sEAAsE;YACtE,IAAI,KAAK,CAAC,WAAW,KAAK,SAAS;gBAAE,IAAI,CAAC,SAAS,EAAE,CAAC;YACtD,OAAO,EAAE,CAAC;QACZ,CAAC;QACD,IAAI,KAAK,CAAC,IAAI,KAAK,cAAc;YAAE,OAAO,IAAI,CAAC,YAAY,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;QAClG,IAAI,KAAK,CAAC,IAAI,KAAK,gBAAgB,EAAE,CAAC;YACpC,IAAI,QAAQ,IAAI,IAAI,CAAC,aAAa;gBAAE,OAAO,EAAE,CAAC;YAC9C,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;YAC1B,OAAO,CAAC,EAAE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M,UAAU,WAAW,CAAC,OAAqB;IAC/C,MAAM,QAAQ,GAAG,OAAO,CAAC,QAAQ,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM,OAAO,CAAC,QAAQ,YAAY,CAAC;IAClF,MAAM,IAAI,GAAG,QAAQ,GAAG,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,QAAQ,EAAE,CAAC;IACvD,IAAI,OAAO,CAAC,IAAI,KAAK,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC;IACxE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IACxC,OAAO,WAAW,OAAO,CAAC,MAAM,EAAE,MAAM,CAAC,KAAK,MAAM,OAAO,MAAM,cAAc,IAAI,EAAE,CAAC;AACxF,CAAC","sourcesContent":["/**\n * The meter: what a session has cost so far and how full its context is, read from the events a turn streams. It\n * warns once a session when the context passes 80% of its budget, and once a run when the run's spend passes 80% of\n * `--budget`, so you see the warning before the budget stops the run or the context has to be summarised. The budget\n * is per run, as the harness applies it: a turn is one run, and each resume after an answer is another.\n */\nimport type { HarnessEvent } from \"@buildanagent/protocol\";\nimport type { AgentEvent } from \"@buildanagent/sdk\";\n\n/** The share of a limit at which the meter warns. */\nexport const WARN_AT = 0.8;\n\n/** A warning or reading the meter reports. */\nexport type MeterNote =\n | { readonly kind: \"context_warning\"; readonly tokens: number; readonly budget: number }\n | { readonly kind: \"budget_warning\"; readonly spentUsd: number; readonly capUsd: number };\n\n/** The meter's totals. */\nexport interface MeterReading {\n /** The cost of every priced call in US dollars. */\n readonly costUsd: number;\n /** How many calls had no price, so `costUsd` leaves them out. */\n readonly unpriced: number;\n /** The last context fill, when the harness reported one. */\n readonly fill?: { readonly tokens: number; readonly budget: number };\n}\n\n/** Counts cost and context fill for one session, and says when to warn. */\nexport class Meter {\n readonly #budgetUsd: number | undefined;\n #costUsd = 0;\n #runCostUsd = 0;\n #unpriced = 0;\n #fill: { tokens: number; budget: number } | undefined;\n #contextWarned = false;\n #budgetWarned = false;\n\n /** `budgetUsd` is the spend cap of each run, when it has one. */\n constructor(budgetUsd?: number) {\n this.#budgetUsd = budgetUsd;\n }\n\n /**\n * Takes one event and returns the warnings it causes: the context warning at most once a session, and the budget\n * warning at most once a run. A `replayed` event, read back from the log, counts toward the session's totals but\n * never warns, so it leaves both warnings for the live runs that follow.\n */\n observe(event: AgentEvent | HarnessEvent, replayed = false): MeterNote[] {\n if (event.type === \"run_start\") {\n // A nested run streams into its parent's run, which keeps one budget.\n if (event.parentRunId === undefined) this.#startRun();\n return [];\n }\n if (event.type === \"context_fill\") return this.#contextFill(event.tokens, event.budget, replayed);\n if (event.type === \"budget_warning\") {\n if (replayed || this.#budgetWarned) return [];\n this.#budgetWarned = true;\n return [{ kind: \"budget_warning\", spentUsd: event.spentUsd, capUsd: event.capUsd }];\n }\n if (event.type !== \"entry_appended\" || event.entry.type !== \"usage\") return [];\n const total = event.entry.cost.total;\n if (total === null) this.#unpriced += 1;\n else {\n this.#costUsd += total;\n this.#runCostUsd += total;\n }\n return replayed ? [] : this.#checkBudget();\n }\n\n #contextFill(tokens: number, budget: number, replayed: boolean): MeterNote[] {\n this.#fill = { tokens, budget };\n if (replayed || this.#contextWarned || budget <= 0 || tokens < budget * WARN_AT) return [];\n this.#contextWarned = true;\n return [{ kind: \"context_warning\", tokens, budget }];\n }\n\n #startRun(): void {\n this.#runCostUsd = 0;\n this.#budgetWarned = false;\n }\n\n #checkBudget(): MeterNote[] {\n const cap = this.#budgetUsd;\n if (cap === undefined || this.#budgetWarned || this.#runCostUsd < cap * WARN_AT) return [];\n this.#budgetWarned = true;\n return [{ kind: \"budget_warning\", spentUsd: this.#runCostUsd, capUsd: cap }];\n }\n\n /** The totals so far. */\n reading(): MeterReading {\n return {\n costUsd: this.#costUsd,\n unpriced: this.#unpriced,\n ...(this.#fill === undefined ? {} : { fill: this.#fill }),\n };\n }\n}\n\nconst percent = (part: number, whole: number): string => `${Math.round((part / whole) * 100)}%`;\nconst usd = (value: number): string => `$${value.toFixed(4)}`;\n\n/** One line for a warning. */\nexport function warningText(note: MeterNote): string {\n return note.kind === \"context_warning\"\n ? `warning: the context is ${percent(note.tokens, note.budget)} full (${note.tokens} of ${note.budget} tokens)`\n : `warning: this turn has spent ${usd(note.spentUsd)}, ${percent(note.spentUsd, note.capUsd)} of its ${usd(note.capUsd)} budget`;\n}\n\n/** One status line: the cost so far, and the context fill when the harness reported one. */\nexport function readingText(reading: MeterReading): string {\n const unpriced = reading.unpriced === 0 ? \"\" : ` (+${reading.unpriced} unpriced)`;\n const cost = `cost ${usd(reading.costUsd)}${unpriced}`;\n if (reading.fill === undefined || reading.fill.budget <= 0) return cost;\n const { tokens, budget } = reading.fill;\n return `context ${percent(tokens, budget)} (${tokens} of ${budget} tokens) · ${cost}`;\n}\n"]}
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Picks the model a command runs from `--model <provider>:<model id>`. The key comes from the provider's own
3
+ * environment variable, read here and passed to the adapter, because the gateway never reads one itself.
4
+ */
5
+ import { type Model } from "@buildanagent/gateway";
6
+ type Env = Readonly<Record<string, string | undefined>>;
7
+ /**
8
+ * The model `spec` names, such as `anthropic:claude-sonnet-5-5`. Throws a `CliError`: `no_model` without a spec,
9
+ * `usage` for an unknown provider, and `missing_api_key` when the provider's variable is unset.
10
+ */
11
+ export declare function modelFromSpec(spec: string | undefined, env: Env): Model;
12
+ export {};
package/dist/model.js ADDED
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Picks the model a command runs from `--model <provider>:<model id>`. The key comes from the provider's own
3
+ * environment variable, read here and passed to the adapter, because the gateway never reads one itself.
4
+ */
5
+ import { createModel } from "@buildanagent/gateway";
6
+ import { anthropic } from "@buildanagent/gateway/anthropic";
7
+ import { openaiChat } from "@buildanagent/gateway/openai-chat";
8
+ import { CliError } from "./errors.js";
9
+ const PROVIDERS = {
10
+ anthropic: { variable: "ANTHROPIC_API_KEY", adapter: (apiKey) => anthropic({ apiKey }) },
11
+ openai: { variable: "OPENAI_API_KEY", adapter: (apiKey) => openaiChat({ apiKey }) },
12
+ };
13
+ const EXAMPLE = "anthropic:claude-sonnet-5-5";
14
+ /**
15
+ * The model `spec` names, such as `anthropic:claude-sonnet-5-5`. Throws a `CliError`: `no_model` without a spec,
16
+ * `usage` for an unknown provider, and `missing_api_key` when the provider's variable is unset.
17
+ */
18
+ export function modelFromSpec(spec, env) {
19
+ if (spec === undefined) {
20
+ throw new CliError("no_model", `this command calls a model: pass --model <provider>:<model id>, such as ${EXAMPLE}`);
21
+ }
22
+ const split = spec.indexOf(":");
23
+ const provider = split < 0 ? spec : spec.slice(0, split);
24
+ const id = split < 0 ? "" : spec.slice(split + 1);
25
+ if (!Object.hasOwn(PROVIDERS, provider) || id === "") {
26
+ throw new CliError("usage", `--model takes anthropic:<model id> or openai:<model id>, got ${JSON.stringify(spec)}`);
27
+ }
28
+ const { variable, adapter } = PROVIDERS[provider];
29
+ const key = env[variable];
30
+ if (key === undefined || key.trim() === "") {
31
+ throw new CliError("missing_api_key", `--model ${provider}:… reads its key from ${variable}, which is not set`);
32
+ }
33
+ return createModel({ adapter: adapter(key), id });
34
+ }
35
+ //# sourceMappingURL=model.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"model.js","sourceRoot":"","sources":["../src/model.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,WAAW,EAAc,MAAM,uBAAuB,CAAC;AAChE,OAAO,EAAE,SAAS,EAAE,MAAM,iCAAiC,CAAC;AAC5D,OAAO,EAAE,UAAU,EAAE,MAAM,mCAAmC,CAAC;AAC/D,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAIvC,MAAM,SAAS,GAAG;IAChB,SAAS,EAAE,EAAE,QAAQ,EAAE,mBAAmB,EAAE,OAAO,EAAE,CAAC,MAAc,EAAE,EAAE,CAAC,SAAS,CAAC,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AAiB,EAAE,WAAW,QAAQ,yBAAyB,QAAQ,oBAAoB,CAAC,CAAC;IAClH,CAAC;IACD,OAAO,WAAW,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AACpD,CAAC","sourcesContent":["/**\n * Picks the model a command runs from `--model <provider>:<model id>`. The key comes from the provider's own\n * environment variable, read here and passed to the adapter, because the gateway never reads one itself.\n */\nimport { createModel, type Model } from \"@buildanagent/gateway\";\nimport { anthropic } from \"@buildanagent/gateway/anthropic\";\nimport { openaiChat } from \"@buildanagent/gateway/openai-chat\";\nimport { CliError } from \"./errors.js\";\n\ntype Env = Readonly<Record<string, string | undefined>>;\n\nconst PROVIDERS = {\n anthropic: { variable: \"ANTHROPIC_API_KEY\", adapter: (apiKey: string) => anthropic({ apiKey }) },\n openai: { variable: \"OPENAI_API_KEY\", adapter: (apiKey: string) => openaiChat({ apiKey }) },\n} as const;\n\nconst EXAMPLE = \"anthropic:claude-sonnet-5-5\";\n\n/**\n * The model `spec` names, such as `anthropic:claude-sonnet-5-5`. Throws a `CliError`: `no_model` without a spec,\n * `usage` for an unknown provider, and `missing_api_key` when the provider's variable is unset.\n */\nexport function modelFromSpec(spec: string | undefined, env: Env): Model {\n if (spec === undefined) {\n throw new CliError(\n \"no_model\",\n `this command calls a model: pass --model <provider>:<model id>, such as ${EXAMPLE}`,\n );\n }\n const split = spec.indexOf(\":\");\n const provider = split < 0 ? spec : spec.slice(0, split);\n const id = split < 0 ? \"\" : spec.slice(split + 1);\n if (!Object.hasOwn(PROVIDERS, provider) || id === \"\") {\n throw new CliError(\"usage\", `--model takes anthropic:<model id> or openai:<model id>, got ${JSON.stringify(spec)}`);\n }\n const { variable, adapter } = PROVIDERS[provider as keyof typeof PROVIDERS];\n const key = env[variable];\n if (key === undefined || key.trim() === \"\") {\n throw new CliError(\"missing_api_key\", `--model ${provider}:… reads its key from ${variable}, which is not set`);\n }\n return createModel({ adapter: adapter(key), id });\n}\n"]}
@@ -0,0 +1,30 @@
1
+ /**
2
+ * What `runCli()` takes, and what each command gets from it: the terminal, the flags, and the settings of the host
3
+ * it builds.
4
+ */
5
+ import type { Model } from "@buildanagent/gateway";
6
+ import type { ToolRegistration } from "@buildanagent/harness/tools";
7
+ import type { Flags } from "./args.js";
8
+ import type { HostOptions, HostRules } from "./host.js";
9
+ import type { CliIo } from "./io.js";
10
+ /** The options of `runCli()`. */
11
+ export interface CliOptions {
12
+ /** The terminal: standard streams, environment and working folder. */
13
+ readonly io: CliIo;
14
+ /** The model turns use. It replaces `--model`, so a program can pass a model it built itself. */
15
+ readonly model?: Model;
16
+ /** Tools to register besides the harness's own. They run in process: a `client_request` tool's call fails. */
17
+ readonly tools?: readonly ToolRegistration[];
18
+ /** Deny, ask and allow rules added to the harness's defaults. */
19
+ readonly rules?: HostRules;
20
+ /** The `fetch` that `--otlp-endpoint` sends spans with. Default the global one. */
21
+ readonly fetch?: typeof globalThis.fetch;
22
+ }
23
+ /** What a command runs with. */
24
+ export interface CommandContext {
25
+ readonly io: CliIo;
26
+ readonly flags: Flags;
27
+ readonly options: CliOptions;
28
+ /** The host settings every command shares; a command adds the model, `interactive` and `signing`. */
29
+ readonly hostOptions: Omit<HostOptions, "model" | "interactive" | "signing">;
30
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=options.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"options.js","sourceRoot":"","sources":["../src/options.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * What `runCli()` takes, and what each command gets from it: the terminal, the flags, and the settings of the host\n * it builds.\n */\nimport type { Model } from \"@buildanagent/gateway\";\nimport type { ToolRegistration } from \"@buildanagent/harness/tools\";\nimport type { Flags } from \"./args.js\";\nimport type { HostOptions, HostRules } from \"./host.js\";\nimport type { CliIo } from \"./io.js\";\n\n/** The options of `runCli()`. */\nexport interface CliOptions {\n /** The terminal: standard streams, environment and working folder. */\n readonly io: CliIo;\n /** The model turns use. It replaces `--model`, so a program can pass a model it built itself. */\n readonly model?: Model;\n /** Tools to register besides the harness's own. They run in process: a `client_request` tool's call fails. */\n readonly tools?: readonly ToolRegistration[];\n /** Deny, ask and allow rules added to the harness's defaults. */\n readonly rules?: HostRules;\n /** The `fetch` that `--otlp-endpoint` sends spans with. Default the global one. */\n readonly fetch?: typeof globalThis.fetch;\n}\n\n/** What a command runs with. */\nexport interface CommandContext {\n readonly io: CliIo;\n readonly flags: Flags;\n readonly options: CliOptions;\n /** The host settings every command shares; a command adds the model, `interactive` and `signing`. */\n readonly hostOptions: Omit<HostOptions, \"model\" | \"interactive\" | \"signing\">;\n}\n"]}
package/dist/otlp.d.ts ADDED
@@ -0,0 +1,28 @@
1
+ /**
2
+ * A tracer that sends its spans to one OTLP/HTTP endpoint as JSON, for `--otlp-endpoint`. It is the CLI's only
3
+ * exporter, so nothing leaves the machine unless that flag names where to. It implements the SDK's `TracerLike`, so
4
+ * the SDK's OpenTelemetry observer writes to it without the OpenTelemetry packages, and it holds every span until
5
+ * `flush()`, which a command calls once before it exits.
6
+ */
7
+ import { type SpanLike, type TracerLike } from "@buildanagent/sdk/otel";
8
+ /** What `otlpTracer()` takes. */
9
+ export interface OtlpTracerOptions {
10
+ /** The collector's base URL, such as `http://localhost:4318`, or its full `/v1/traces` URL. */
11
+ readonly endpoint: string;
12
+ /** The `fetch` that sends the spans. Default the global one. */
13
+ readonly fetch?: typeof globalThis.fetch;
14
+ /** The clock for a span that names no start or end time, in milliseconds. Default `Date.now`. */
15
+ readonly now?: () => number;
16
+ }
17
+ /** A `TracerLike` that also sends what it holds. */
18
+ export interface OtlpTracer extends TracerLike {
19
+ /** The context a child span starts in, for the observer's `childContext`. */
20
+ childContext(parent: SpanLike): unknown;
21
+ /**
22
+ * Sends every ended span in one request and forgets them. Rejects with a `CliError` when the collector can't be
23
+ * reached or answers with an error.
24
+ */
25
+ flush(): Promise<void>;
26
+ }
27
+ /** A tracer that sends the spans it records to `options.endpoint` when flushed. */
28
+ export declare function otlpTracer(options: OtlpTracerOptions): OtlpTracer;