@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.
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 +143 -2
  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 +43 -3
package/dist/otlp.js ADDED
@@ -0,0 +1,110 @@
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 { SEMCONV_GENAI_COMMIT } from "@buildanagent/sdk/otel";
8
+ import { CliError } from "./errors.js";
9
+ const hex = (bytes) => Array.from(globalThis.crypto.getRandomValues(new Uint8Array(bytes)), (byte) => byte.toString(16).padStart(2, "0")).join("");
10
+ // The API's SpanKind counts from 0 and OTLP's from 1, where 0 means unspecified.
11
+ const otlpKind = (kind) => (kind ?? 0) + 1;
12
+ const nanos = (millis) => (BigInt(Math.round(millis)) * 1000000n).toString();
13
+ function anyValue(value) {
14
+ if (Array.isArray(value))
15
+ return { arrayValue: { values: value.map((item) => ({ stringValue: item })) } };
16
+ if (typeof value === "string")
17
+ return { stringValue: value };
18
+ if (typeof value === "boolean")
19
+ return { boolValue: value };
20
+ return Number.isInteger(value) ? { intValue: String(value) } : { doubleValue: value };
21
+ }
22
+ const attributesOf = (attributes) => [...attributes].map(([key, value]) => ({ key, value: anyValue(value) }));
23
+ function wireSpan(span) {
24
+ return {
25
+ traceId: span.traceId,
26
+ spanId: span.spanId,
27
+ ...(span.parentSpanId === undefined ? {} : { parentSpanId: span.parentSpanId }),
28
+ name: span.name,
29
+ kind: span.kind,
30
+ startTimeUnixNano: nanos(span.start),
31
+ endTimeUnixNano: nanos(span.end ?? span.start),
32
+ attributes: attributesOf(span.attributes),
33
+ ...(span.status === undefined ? {} : { status: span.status }),
34
+ };
35
+ }
36
+ const tracesUrl = (endpoint) => endpoint.endsWith("/v1/traces") ? endpoint : `${endpoint.replace(/\/+$/, "")}/v1/traces`;
37
+ /** A tracer that sends the spans it records to `options.endpoint` when flushed. */
38
+ export function otlpTracer(options) {
39
+ const now = options.now ?? Date.now;
40
+ const ended = [];
41
+ const records = new WeakMap();
42
+ const resource = new Map([
43
+ ["service.name", "buildanagent"],
44
+ ["buildanagent.semconv_genai.commit", SEMCONV_GENAI_COMMIT],
45
+ ]);
46
+ const startSpan = (name, spanOptions = {}, context) => {
47
+ const parent = context instanceof Object ? records.get(context) : undefined;
48
+ const record = {
49
+ traceId: parent?.traceId ?? hex(16),
50
+ spanId: hex(8),
51
+ ...(parent === undefined ? {} : { parentSpanId: parent.spanId }),
52
+ name,
53
+ kind: otlpKind(spanOptions.kind),
54
+ start: spanOptions.startTime ?? now(),
55
+ attributes: new Map(Object.entries(spanOptions.attributes ?? {})),
56
+ };
57
+ const span = {
58
+ setAttribute: (key, value) => record.attributes.set(key, value),
59
+ setStatus: (status) => {
60
+ record.status = { code: status.code, ...(status.message === undefined ? {} : { message: status.message }) };
61
+ },
62
+ end: (endTime) => {
63
+ // OpenTelemetry ignores a second end(), so a span ended twice is still one span on the collector.
64
+ if (record.end !== undefined)
65
+ return;
66
+ record.end = endTime ?? now();
67
+ ended.push(record);
68
+ },
69
+ };
70
+ records.set(span, record);
71
+ return span;
72
+ };
73
+ return {
74
+ startSpan,
75
+ childContext: (parent) => parent,
76
+ async flush() {
77
+ if (ended.length === 0)
78
+ return;
79
+ const spans = ended.splice(0).map(wireSpan);
80
+ const body = {
81
+ resourceSpans: [
82
+ {
83
+ resource: { attributes: attributesOf(resource) },
84
+ scopeSpans: [{ scope: { name: "buildanagent" }, spans }],
85
+ },
86
+ ],
87
+ };
88
+ const send = options.fetch ?? globalThis.fetch;
89
+ const url = tracesUrl(options.endpoint);
90
+ let response;
91
+ try {
92
+ response = await send(url, {
93
+ method: "POST",
94
+ headers: { "content-type": "application/json" },
95
+ body: JSON.stringify(body),
96
+ });
97
+ }
98
+ catch (error) {
99
+ // A refused connection or an unknown host is the caller's to fix, like an error status, so it exits 2 too.
100
+ const why = error instanceof Error ? error.message : String(error);
101
+ throw new CliError("otlp_failed", `could not send the spans to the OTLP endpoint ${url}: ${why}`, {
102
+ cause: error,
103
+ });
104
+ }
105
+ if (!response.ok)
106
+ throw new CliError("otlp_failed", `the OTLP endpoint answered ${response.status}`);
107
+ },
108
+ };
109
+ }
110
+ //# sourceMappingURL=otlp.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"otlp.js","sourceRoot":"","sources":["../src/otlp.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,oBAAoB,EAAwD,MAAM,wBAAwB,CAAC;AACpH,OAAO,EAAE,QAAQ,EAAE,MAAM,aAAa,CAAC;AAqCvC,MAAM,GAAG,GAAG,CAAC,KAAa,EAAU,EAAE,CACpC,KAAK,CAA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C;iBAC3B,CAAC,CAAC;YACL,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,2GAA2G;gBAC3G,MAAM,GAAG,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;gBACnE,MAAM,IAAI,QAAQ,CAAC,aAAa,EAAE,iDAAiD,GAAG,KAAK,GAAG,EAAE,EAAE;oBAChG,KAAK,EAAE,KAAK;iBACb,CAAC,CAAC;YACL,CAAC;YACD,IAAI,CAAC,QAAQ,CAAC,EAAE;gBAAE,MAAM,IAAI,QAAQ,CAAC,aAAa,EAAE,8BAA8B,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;QACvG,CAAC;KACF,CAAC;AACJ,CAAC","sourcesContent":["/**\n * A tracer that sends its spans to one OTLP/HTTP endpoint as JSON, for `--otlp-endpoint`. It is the CLI's only\n * exporter, so nothing leaves the machine unless that flag names where to. It implements the SDK's `TracerLike`, so\n * the SDK's OpenTelemetry observer writes to it without the OpenTelemetry packages, and it holds every span until\n * `flush()`, which a command calls once before it exits.\n */\n\nimport { SEMCONV_GENAI_COMMIT, type SpanLike, type SpanOptionsLike, type TracerLike } from \"@buildanagent/sdk/otel\";\nimport { CliError } from \"./errors.js\";\n\ntype Value = string | number | boolean | string[];\n\ninterface Recorded {\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n readonly name: string;\n readonly kind: number;\n readonly start: number;\n end?: number;\n readonly attributes: Map<string, Value>;\n status?: { code: number; message?: string };\n}\n\n/** What `otlpTracer()` takes. */\nexport interface OtlpTracerOptions {\n /** The collector's base URL, such as `http://localhost:4318`, or its full `/v1/traces` URL. */\n readonly endpoint: string;\n /** The `fetch` that sends the spans. Default the global one. */\n readonly fetch?: typeof globalThis.fetch;\n /** The clock for a span that names no start or end time, in milliseconds. Default `Date.now`. */\n readonly now?: () => number;\n}\n\n/** A `TracerLike` that also sends what it holds. */\nexport interface OtlpTracer extends TracerLike {\n /** The context a child span starts in, for the observer's `childContext`. */\n childContext(parent: SpanLike): unknown;\n /**\n * Sends every ended span in one request and forgets them. Rejects with a `CliError` when the collector can't be\n * reached or answers with an error.\n */\n flush(): Promise<void>;\n}\n\nconst hex = (bytes: number): string =>\n Array.from(globalThis.crypto.getRandomValues(new Uint8Array(bytes)), (byte) =>\n byte.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n\n// The API's SpanKind counts from 0 and OTLP's from 1, where 0 means unspecified.\nconst otlpKind = (kind: number | undefined): number => (kind ?? 0) + 1;\n\nconst nanos = (millis: number): string => (BigInt(Math.round(millis)) * 1_000_000n).toString();\n\nfunction anyValue(value: Value): Record<string, unknown> {\n if (Array.isArray(value)) return { arrayValue: { values: value.map((item) => ({ stringValue: item })) } };\n if (typeof value === \"string\") return { stringValue: value };\n if (typeof value === \"boolean\") return { boolValue: value };\n return Number.isInteger(value) ? { intValue: String(value) } : { doubleValue: value };\n}\n\nconst attributesOf = (attributes: ReadonlyMap<string, Value>) =>\n [...attributes].map(([key, value]) => ({ key, value: anyValue(value) }));\n\nfunction wireSpan(span: Recorded) {\n return {\n traceId: span.traceId,\n spanId: span.spanId,\n ...(span.parentSpanId === undefined ? {} : { parentSpanId: span.parentSpanId }),\n name: span.name,\n kind: span.kind,\n startTimeUnixNano: nanos(span.start),\n endTimeUnixNano: nanos(span.end ?? span.start),\n attributes: attributesOf(span.attributes),\n ...(span.status === undefined ? {} : { status: span.status }),\n };\n}\n\nconst tracesUrl = (endpoint: string): string =>\n endpoint.endsWith(\"/v1/traces\") ? endpoint : `${endpoint.replace(/\\/+$/, \"\")}/v1/traces`;\n\n/** A tracer that sends the spans it records to `options.endpoint` when flushed. */\nexport function otlpTracer(options: OtlpTracerOptions): OtlpTracer {\n const now = options.now ?? Date.now;\n const ended: Recorded[] = [];\n const records = new WeakMap<SpanLike, Recorded>();\n const resource = new Map<string, Value>([\n [\"service.name\", \"buildanagent\"],\n [\"buildanagent.semconv_genai.commit\", SEMCONV_GENAI_COMMIT],\n ]);\n const startSpan = (name: string, spanOptions: SpanOptionsLike = {}, context?: unknown): SpanLike => {\n const parent = context instanceof Object ? records.get(context as SpanLike) : undefined;\n const record: Recorded = {\n traceId: parent?.traceId ?? hex(16),\n spanId: hex(8),\n ...(parent === undefined ? {} : { parentSpanId: parent.spanId }),\n name,\n kind: otlpKind(spanOptions.kind),\n start: spanOptions.startTime ?? now(),\n attributes: new Map(Object.entries(spanOptions.attributes ?? {})),\n };\n const span: SpanLike = {\n setAttribute: (key, value) => record.attributes.set(key, value),\n setStatus: (status) => {\n record.status = { code: status.code, ...(status.message === undefined ? {} : { message: status.message }) };\n },\n end: (endTime) => {\n // OpenTelemetry ignores a second end(), so a span ended twice is still one span on the collector.\n if (record.end !== undefined) return;\n record.end = endTime ?? now();\n ended.push(record);\n },\n };\n records.set(span, record);\n return span;\n };\n return {\n startSpan,\n childContext: (parent) => parent,\n async flush() {\n if (ended.length === 0) return;\n const spans = ended.splice(0).map(wireSpan);\n const body = {\n resourceSpans: [\n {\n resource: { attributes: attributesOf(resource) },\n scopeSpans: [{ scope: { name: \"buildanagent\" }, spans }],\n },\n ],\n };\n const send = options.fetch ?? globalThis.fetch;\n const url = tracesUrl(options.endpoint);\n let response: Response;\n try {\n response = await send(url, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: JSON.stringify(body),\n });\n } catch (error) {\n // A refused connection or an unknown host is the caller's to fix, like an error status, so it exits 2 too.\n const why = error instanceof Error ? error.message : String(error);\n throw new CliError(\"otlp_failed\", `could not send the spans to the OTLP endpoint ${url}: ${why}`, {\n cause: error,\n });\n }\n if (!response.ok) throw new CliError(\"otlp_failed\", `the OTLP endpoint answered ${response.status}`);\n },\n };\n}\n"]}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Where a command's results go. With `--json` every result is one JSON object on its own line of standard output,
3
+ * so a script reads the stream line by line. Without it, results are text, and progress and warnings go to standard
4
+ * error so standard output holds only the answer.
5
+ */
6
+ import type { CliIo } from "./io.js";
7
+ /** A command's output, as text or as JSON lines. */
8
+ export declare class Output {
9
+ #private;
10
+ readonly json: boolean;
11
+ constructor(io: CliIo, json: boolean);
12
+ /** Writes one JSON object as one line of standard output. */
13
+ line(value: object): void;
14
+ /** A result: `text` on standard output, or `value` as a JSON line. */
15
+ result(text: string, value: object): void;
16
+ /** Progress or a warning: `text` on standard error, or `value` as a JSON line. */
17
+ note(text: string, value: object): void;
18
+ }
package/dist/output.js ADDED
@@ -0,0 +1,28 @@
1
+ /** A command's output, as text or as JSON lines. */
2
+ export class Output {
3
+ json;
4
+ #io;
5
+ constructor(io, json) {
6
+ this.#io = io;
7
+ this.json = json;
8
+ }
9
+ /** Writes one JSON object as one line of standard output. */
10
+ line(value) {
11
+ this.#io.write(`${JSON.stringify(value)}\n`);
12
+ }
13
+ /** A result: `text` on standard output, or `value` as a JSON line. */
14
+ result(text, value) {
15
+ if (this.json)
16
+ this.line(value);
17
+ else
18
+ this.#io.write(`${text}\n`);
19
+ }
20
+ /** Progress or a warning: `text` on standard error, or `value` as a JSON line. */
21
+ note(text, value) {
22
+ if (this.json)
23
+ this.line(value);
24
+ else
25
+ this.#io.error(`${text}\n`);
26
+ }
27
+ }
28
+ //# sourceMappingURL=output.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"output.js","sourceRoot":"","sources":["../src/output.ts"],"names":[],"mappings":"AAOA,oDAAoD;AACpD,MAAM,OAAO,MAAM;IACR,IAAI,CAAU;IACd,GAAG,CAAQ;IAEpB,YAAY,EAAS,EAAE,IAAa;QAClC,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC;QACd,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACnB,CAAC;IAED,6DAA6D;IAC7D,IAAI,CAAC,KAAa;QAChB,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;IAC/C,CAAC;IAED,sEAAsE;IACtE,MAAM,CAAC,IAAY,EAAE,KAAa;QAChC,IAAI,IAAI,CAAC,IAAI;YAAE,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;;YAC3B,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,IAAI,IAAI,CAAC,CAAC;IACnC,CAAC;IAED,kFAAkF;IAClF,IAAI,CAAC,IAAY,EAAE,KAAa;QAC9B,IAAI,IAAI,CAAC,IAAI;YAAE,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;;YAC3B,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,IAAI,IAAI,CAAC,CAAC;IACnC,CAAC;CACF","sourcesContent":["/**\n * Where a command's results go. With `--json` every result is one JSON object on its own line of standard output,\n * so a script reads the stream line by line. Without it, results are text, and progress and warnings go to standard\n * error so standard output holds only the answer.\n */\nimport type { CliIo } from \"./io.js\";\n\n/** A command's output, as text or as JSON lines. */\nexport class Output {\n readonly json: boolean;\n readonly #io: CliIo;\n\n constructor(io: CliIo, json: boolean) {\n this.#io = io;\n this.json = json;\n }\n\n /** Writes one JSON object as one line of standard output. */\n line(value: object): void {\n this.#io.write(`${JSON.stringify(value)}\\n`);\n }\n\n /** A result: `text` on standard output, or `value` as a JSON line. */\n result(text: string, value: object): void {\n if (this.json) this.line(value);\n else this.#io.write(`${text}\\n`);\n }\n\n /** Progress or a warning: `text` on standard error, or `value` as a JSON line. */\n note(text: string, value: object): void {\n if (this.json) this.line(value);\n else this.#io.error(`${text}\\n`);\n }\n}\n"]}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * How a session reads in a terminal. A live turn streams the model's text to standard output as it arrives and
3
+ * reports each tool call on standard error; a replay or `sessions show` prints the same conversation from the log's
4
+ * entries, so the two read alike. Every text the model, a tool or the log supplied goes through `visible()` or
5
+ * `visibleBlock()`, so an escape sequence or a `\r` in it can't move the cursor or overwrite what was printed.
6
+ */
7
+ import type { HarnessEvent, SessionEntry } from "@buildanagent/protocol";
8
+ import type { AgentEvent } from "@buildanagent/sdk";
9
+ import type { CliIo } from "./io.js";
10
+ /**
11
+ * A call's input on one line: a command as its chained commands, anything else as compact JSON, with control
12
+ * characters escaped and cut at 200 characters.
13
+ */
14
+ export declare function inputText(input: unknown): string;
15
+ /** Prints a live turn's events: the answer to standard output, tool calls and results to standard error. */
16
+ export declare function liveRenderer(io: CliIo): (event: AgentEvent | HarnessEvent) => void;
17
+ /** One entry as a line of the conversation, or `undefined` for an entry a reader doesn't need. */
18
+ export declare function entryLine(entry: SessionEntry): string | undefined;
package/dist/render.js ADDED
@@ -0,0 +1,65 @@
1
+ import { chainedCommands, commandOf } from "./command-lines.js";
2
+ import { visible, visibleBlock } from "./visible.js";
3
+ const MAX_INPUT_CHARS = 200;
4
+ /**
5
+ * A call's input on one line: a command as its chained commands, anything else as compact JSON, with control
6
+ * characters escaped and cut at 200 characters.
7
+ */
8
+ export function inputText(input) {
9
+ const command = commandOf(input);
10
+ const text = visible(command === undefined
11
+ ? (JSON.stringify(input) ?? "")
12
+ : chainedCommands(command)
13
+ .map((part) => `${part.operator} ${part.command}`.trim())
14
+ .join(" "));
15
+ return text.length > MAX_INPUT_CHARS ? `${text.slice(0, MAX_INPUT_CHARS)}…` : text;
16
+ }
17
+ /** The first line of a tool result's text, or a note that it held none. */
18
+ function resultText(entry) {
19
+ const text = entry.content.flatMap((block) => (block.type === "text" ? [block.text] : [])).join(" ");
20
+ const first = text.split("\n")[0] ?? "";
21
+ return `${first === "" ? "(no text)" : visible(first)}${entry.isError ? " (error)" : ""}`;
22
+ }
23
+ /** Prints a live turn's events: the answer to standard output, tool calls and results to standard error. */
24
+ export function liveRenderer(io) {
25
+ return (event) => {
26
+ if (event.type === "text_delta")
27
+ io.write(visibleBlock(event.delta));
28
+ else if (event.type === "text_end")
29
+ io.write("\n");
30
+ else if (event.type === "tool_call_start")
31
+ io.error(`· ${visible(event.tool)} ${inputText(event.input)}\n`);
32
+ else if (event.type === "entry_appended" && event.entry.type === "tool_result") {
33
+ io.error(` ${visible(event.entry.tool)} → ${resultText(event.entry)}\n`);
34
+ }
35
+ };
36
+ }
37
+ /** One entry as a line of the conversation, or `undefined` for an entry a reader doesn't need. */
38
+ export function entryLine(entry) {
39
+ switch (entry.type) {
40
+ case "message_block": {
41
+ const who = entry.role === "user" ? "you" : "assistant";
42
+ if (entry.block.type === "text")
43
+ return `${who}: ${visibleBlock(entry.block.text)}`;
44
+ if (entry.block.type === "tool_call")
45
+ return `· ${visible(entry.block.name)} ${inputText(entry.block.input)}`;
46
+ return undefined;
47
+ }
48
+ case "tool_result":
49
+ return ` ${visible(entry.tool)} → ${resultText(entry)}`;
50
+ case "approval_requested":
51
+ return `? ${visible(entry.request.tool)} waited for ${entry.request.kind === "clarification" ? "an answer" : "approval"}`;
52
+ case "approval_resolved": {
53
+ const { resolution } = entry;
54
+ const answer = "answer" in resolution ? `answered ${visible(JSON.stringify(resolution.answer))}` : resolution.decision;
55
+ return ` ${answer}${resolution.by === undefined ? "" : ` by ${visible(resolution.by)}`}`;
56
+ }
57
+ case "compaction":
58
+ return `[earlier turns summarised: ${entry.tokensBefore} → ${entry.tokensAfter} tokens]`;
59
+ case "turn_end":
60
+ return `[turn ended: ${entry.stopReason} after ${entry.steps} step${entry.steps === 1 ? "" : "s"}]`;
61
+ default:
62
+ return undefined;
63
+ }
64
+ }
65
+ //# sourceMappingURL=render.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render.js","sourceRoot":"","sources":["../src/render.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAEhE,OAAO,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAErD,MAAM,eAAe,GAAG,GAAG,CAAC;AAE5B;;;GAGG;AACH,MAAM,UAAU,SAAS,CAAC,KAAc;IACtC,MAAM,OAAO,GAAG,SAAS,CAAC,KAAK,CAAC,CAAC;IACjC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,KAAK,aAAa;YAChB,OAAO,KAAK,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,UAAU,CAAC,KAAK,CAAC,EAAE,CAAC;QAC3D,KAAK,oBAAoB;YACvB,OAAO,KAAK,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,eAAe,KAAK,CAAC,OAAO,CAAC,IAAI,KAAK,eAAe,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,UAAU,EAAE,CAAC;QAC5H,KAAK,mBAAmB,EAAE,CAAC;YACzB,MAAM,EAAE,UAAU,EAAE,GAAG,KAAK,CAAC;YAC7B,MAAM,MAAM,GACV,QAAQ,IAAI,UAAU,CAAC,CAAC,CAAC,YAAY,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,UAAU,CAAC,QAAQ,CAAC;YAC1G,OAAO,KAAK,MAAM,GAAG,UAAU,CAAC,EAAE,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,OAAO,CAAC,UAAU,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;QAC5F,CAAC;QACD,KAAK,YAAY;YACf,OAAO,8BAA8B,KAAK,CAAC,YAAY,MAAM,KAAK,CAAC,WAAW,UAAU,CAAC;QAC3F,KAAK,UAAU;YACb,OAAO,gBAAgB,KAAK,CAAC,UAAU,UAAU,KAAK,CAAC,KAAK,QAAQ,KAAK,CAAC,KAAK,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC;QACtG;YACE,OAAO,SAAS,CAAC;IACrB,CAAC;AACH,CAAC","sourcesContent":["/**\n * How a session reads in a terminal. A live turn streams the model's text to standard output as it arrives and\n * reports each tool call on standard error; a replay or `sessions show` prints the same conversation from the log's\n * entries, so the two read alike. Every text the model, a tool or the log supplied goes through `visible()` or\n * `visibleBlock()`, so an escape sequence or a `\\r` in it can't move the cursor or overwrite what was printed.\n */\nimport type { HarnessEvent, SessionEntry } from \"@buildanagent/protocol\";\nimport type { AgentEvent } from \"@buildanagent/sdk\";\nimport { chainedCommands, commandOf } from \"./command-lines.js\";\nimport type { CliIo } from \"./io.js\";\nimport { visible, visibleBlock } from \"./visible.js\";\n\nconst MAX_INPUT_CHARS = 200;\n\n/**\n * A call's input on one line: a command as its chained commands, anything else as compact JSON, with control\n * characters escaped and cut at 200 characters.\n */\nexport function inputText(input: unknown): string {\n const command = commandOf(input);\n const text = visible(\n command === undefined\n ? (JSON.stringify(input) ?? \"\")\n : chainedCommands(command)\n .map((part) => `${part.operator} ${part.command}`.trim())\n .join(\" \"),\n );\n return text.length > MAX_INPUT_CHARS ? `${text.slice(0, MAX_INPUT_CHARS)}…` : text;\n}\n\n/** The first line of a tool result's text, or a note that it held none. */\nfunction resultText(entry: Extract<SessionEntry, { type: \"tool_result\" }>): string {\n const text = entry.content.flatMap((block) => (block.type === \"text\" ? [block.text] : [])).join(\" \");\n const first = text.split(\"\\n\")[0] ?? \"\";\n return `${first === \"\" ? \"(no text)\" : visible(first)}${entry.isError ? \" (error)\" : \"\"}`;\n}\n\n/** Prints a live turn's events: the answer to standard output, tool calls and results to standard error. */\nexport function liveRenderer(io: CliIo): (event: AgentEvent | HarnessEvent) => void {\n return (event) => {\n if (event.type === \"text_delta\") io.write(visibleBlock(event.delta));\n else if (event.type === \"text_end\") io.write(\"\\n\");\n else if (event.type === \"tool_call_start\") io.error(`· ${visible(event.tool)} ${inputText(event.input)}\\n`);\n else if (event.type === \"entry_appended\" && event.entry.type === \"tool_result\") {\n io.error(` ${visible(event.entry.tool)} → ${resultText(event.entry)}\\n`);\n }\n };\n}\n\n/** One entry as a line of the conversation, or `undefined` for an entry a reader doesn't need. */\nexport function entryLine(entry: SessionEntry): string | undefined {\n switch (entry.type) {\n case \"message_block\": {\n const who = entry.role === \"user\" ? \"you\" : \"assistant\";\n if (entry.block.type === \"text\") return `${who}: ${visibleBlock(entry.block.text)}`;\n if (entry.block.type === \"tool_call\") return `· ${visible(entry.block.name)} ${inputText(entry.block.input)}`;\n return undefined;\n }\n case \"tool_result\":\n return ` ${visible(entry.tool)} → ${resultText(entry)}`;\n case \"approval_requested\":\n return `? ${visible(entry.request.tool)} waited for ${entry.request.kind === \"clarification\" ? \"an answer\" : \"approval\"}`;\n case \"approval_resolved\": {\n const { resolution } = entry;\n const answer =\n \"answer\" in resolution ? `answered ${visible(JSON.stringify(resolution.answer))}` : resolution.decision;\n return ` ${answer}${resolution.by === undefined ? \"\" : ` by ${visible(resolution.by)}`}`;\n }\n case \"compaction\":\n return `[earlier turns summarised: ${entry.tokensBefore} → ${entry.tokensAfter} tokens]`;\n case \"turn_end\":\n return `[turn ended: ${entry.stopReason} after ${entry.steps} step${entry.steps === 1 ? \"\" : \"s\"}]`;\n default:\n return undefined;\n }\n}\n"]}
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Makes text from the model or the log safe to print. A control character in a command, a reason or a tool result
3
+ * would otherwise act on the terminal: a `\r` returns the cursor and the text after it overwrites what an approver
4
+ * read, and an escape sequence can move the cursor, clear the line or recolour it. Each one is shown as an escape
5
+ * instead, so the approver sees that it is there; nothing is dropped. Unicode's direction overrides and invisible
6
+ * separators are escaped too, because they reorder or hide the text around them in the same way.
7
+ */
8
+ /** `text` on one line, with every control character, invisible character and non-ASCII space shown as an escape. */
9
+ export declare const visible: (text: string) => string;
10
+ /** `text` with its line breaks, tabs and spaces kept, and every other control or invisible character escaped. */
11
+ export declare const visibleBlock: (text: string) => string;
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Makes text from the model or the log safe to print. A control character in a command, a reason or a tool result
3
+ * would otherwise act on the terminal: a `\r` returns the cursor and the text after it overwrites what an approver
4
+ * read, and an escape sequence can move the cursor, clear the line or recolour it. Each one is shown as an escape
5
+ * instead, so the approver sees that it is there; nothing is dropped. Unicode's direction overrides and invisible
6
+ * separators are escaped too, because they reorder or hide the text around them in the same way.
7
+ */
8
+ const NAMED = { "\n": "\\n", "\r": "\\r", "\t": "\\t" };
9
+ // The control characters below space, DEL and those from 0x80 to 0x9f, the soft hyphen, the combining grapheme
10
+ // joiner, the Arabic letter mark, the Mongolian vowel separator, the zero-width characters, the bidirectional marks,
11
+ // embeddings, overrides and isolates, the line and paragraph separators, the word joiner and the invisible operators,
12
+ // the variation selectors, the byte-order mark, the tag characters, and a surrogate that pairs with nothing. A
13
+ // variation selector or a tag character draws nothing, so a run of them can carry text an approver never sees.
14
+ const INVISIBLE = [
15
+ [0x00, 0x1f],
16
+ [0x7f, 0x9f],
17
+ [0xad, 0xad],
18
+ [0x34f, 0x34f],
19
+ [0x61c, 0x61c],
20
+ [0x180e, 0x180e],
21
+ [0x200b, 0x200f],
22
+ [0x2028, 0x202e],
23
+ [0x2060, 0x2064],
24
+ [0x2066, 0x2069],
25
+ [0xd800, 0xdfff],
26
+ [0xfe00, 0xfe0f],
27
+ [0xfeff, 0xfeff],
28
+ [0xe0000, 0xe007f],
29
+ [0xe0100, 0xe01ef],
30
+ ];
31
+ // The spaces that are not ASCII's. The shell reads a no-break space as part of a word, so on one line, such as a
32
+ // command, `rm a<no-break space>b` would otherwise read as removing two files.
33
+ const SPACES = [
34
+ [0xa0, 0xa0],
35
+ [0x1680, 0x1680],
36
+ [0x2000, 0x200a],
37
+ [0x202f, 0x202f],
38
+ [0x205f, 0x205f],
39
+ [0x3000, 0x3000],
40
+ ];
41
+ const within = (code, ranges) => ranges.some(([low, high]) => code >= low && code <= high);
42
+ // Every code point outside printable ASCII, which the functions below then sort into safe and unsafe. The `u` flag
43
+ // makes a character beyond U+FFFF, such as a tag character, one match instead of two halves of a surrogate pair.
44
+ const NOT_PRINTABLE_ASCII = /[^ -~]/gu;
45
+ const codeOf = (char) => char.codePointAt(0);
46
+ function escaped(char) {
47
+ const named = NAMED[char];
48
+ if (named !== undefined)
49
+ return named;
50
+ const code = codeOf(char);
51
+ const hex = code.toString(16);
52
+ if (code <= 0xff)
53
+ return `\\x${hex.padStart(2, "0")}`;
54
+ return code <= 0xffff ? `\\u${hex.padStart(4, "0")}` : `\\u{${hex}}`;
55
+ }
56
+ /** `text` on one line, with every control character, invisible character and non-ASCII space shown as an escape. */
57
+ export const visible = (text) => text.replace(NOT_PRINTABLE_ASCII, (char) => {
58
+ const code = codeOf(char);
59
+ return within(code, INVISIBLE) || within(code, SPACES) ? escaped(char) : char;
60
+ });
61
+ /** `text` with its line breaks, tabs and spaces kept, and every other control or invisible character escaped. */
62
+ export const visibleBlock = (text) => text.replace(NOT_PRINTABLE_ASCII, (char) => char !== "\n" && char !== "\t" && within(codeOf(char), INVISIBLE) ? escaped(char) : char);
63
+ //# sourceMappingURL=visible.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"visible.js","sourceRoot":"","sources":["../src/visible.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,MAAM,KAAK,GAAqC,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,KAAK,EAAE,CAAC;AAI1F,+GAA+G;AAC/G,qHAAqH;AACrH,sHAAsH;AACtH,+GAA+G;AAC/G,+GAA+G;AAC/G,MAAM,SAAS,GAAqB;IAClC,CAAC,IAAI,EAAE,IAAI,CAAC;IACZ,CAAC,IAAI,EAAE,IAAI,CAAC;IACZ,CAAC,IAAI,EAAE,IAAI,CAAC;IACZ,CAAC,KAAK,EAAE,KAAK,CAAC;IACd,CAAC,KAAK,EAAE,KAAK,CAAC;IACd,CAAC,MAAM,EAAE,MAAM,CAAC;IAChB,CAAC,MAAM,EAAE,MAAM,CAAC;IAChB,CAAC,MAAM,EAAE,MAAM,CAAC;IAChB,CAAC,MAAM,EAAE,MAAM,CAAC;IAChB,CAAC,MAAM,EAAE,MAAM,CAAC;IAChB,CAAC,MAAM,EAAE,MAAM,CAAC;IAChB,CAAC,MAAM,EAAE,MAAM,CAAC;IAChB,CAAC,MAAM,EAAE,MAAM,CAAC;IAChB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,OAAO,GAAG,GAAG,CAAC;AACvE,CAAC;AAED,oHAAoH;AACpH,MAAM,CAAC,MAAM,OAAO,GAAG,CAAC,IAAY,EAAU,EAAE,CAC9C,IAAI,CAAC,OAAO,CAAC,mBAAmB,EAAE,CAAC,IAAI,EAAE,EAAE;IACzC,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;IAC1B,OAAO,MAAM,CAAC,IAAI,EAAE,SAAS,CAAC,IAAI,MAAM,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AAChF,CAAC,CAAC,CAAC;AAEL,iHAAiH;AACjH,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,IAAY,EAAU,EAAE,CACnD,IAAI,CAAC,OAAO,CAAC,mBAAmB,EAAE,CAAC,IAAI,EAAE,EAAE,CACzC,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,IAAI,IAAI,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,EAAE,SAAS,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CACzF,CAAC","sourcesContent":["/**\n * Makes text from the model or the log safe to print. A control character in a command, a reason or a tool result\n * would otherwise act on the terminal: a `\\r` returns the cursor and the text after it overwrites what an approver\n * read, and an escape sequence can move the cursor, clear the line or recolour it. Each one is shown as an escape\n * instead, so the approver sees that it is there; nothing is dropped. Unicode's direction overrides and invisible\n * separators are escaped too, because they reorder or hide the text around them in the same way.\n */\n\nconst NAMED: Readonly<Record<string, string>> = { \"\\n\": \"\\\\n\", \"\\r\": \"\\\\r\", \"\\t\": \"\\\\t\" };\n\ntype Range = readonly [number, number];\n\n// The control characters below space, DEL and those from 0x80 to 0x9f, the soft hyphen, the combining grapheme\n// joiner, the Arabic letter mark, the Mongolian vowel separator, the zero-width characters, the bidirectional marks,\n// embeddings, overrides and isolates, the line and paragraph separators, the word joiner and the invisible operators,\n// the variation selectors, the byte-order mark, the tag characters, and a surrogate that pairs with nothing. A\n// variation selector or a tag character draws nothing, so a run of them can carry text an approver never sees.\nconst INVISIBLE: readonly Range[] = [\n [0x00, 0x1f],\n [0x7f, 0x9f],\n [0xad, 0xad],\n [0x34f, 0x34f],\n [0x61c, 0x61c],\n [0x180e, 0x180e],\n [0x200b, 0x200f],\n [0x2028, 0x202e],\n [0x2060, 0x2064],\n [0x2066, 0x2069],\n [0xd800, 0xdfff],\n [0xfe00, 0xfe0f],\n [0xfeff, 0xfeff],\n [0xe0000, 0xe007f],\n [0xe0100, 0xe01ef],\n];\n\n// The spaces that are not ASCII's. The shell reads a no-break space as part of a word, so on one line, such as a\n// command, `rm a<no-break space>b` would otherwise read as removing two files.\nconst SPACES: readonly Range[] = [\n [0xa0, 0xa0],\n [0x1680, 0x1680],\n [0x2000, 0x200a],\n [0x202f, 0x202f],\n [0x205f, 0x205f],\n [0x3000, 0x3000],\n];\n\nconst within = (code: number, ranges: readonly Range[]): boolean =>\n ranges.some(([low, high]) => code >= low && code <= high);\n\n// Every code point outside printable ASCII, which the functions below then sort into safe and unsafe. The `u` flag\n// makes a character beyond U+FFFF, such as a tag character, one match instead of two halves of a surrogate pair.\nconst NOT_PRINTABLE_ASCII = /[^ -~]/gu;\n\nconst codeOf = (char: string): number => char.codePointAt(0) as number;\n\nfunction escaped(char: string): string {\n const named = NAMED[char];\n if (named !== undefined) return named;\n const code = codeOf(char);\n const hex = code.toString(16);\n if (code <= 0xff) return `\\\\x${hex.padStart(2, \"0\")}`;\n return code <= 0xffff ? `\\\\u${hex.padStart(4, \"0\")}` : `\\\\u{${hex}}`;\n}\n\n/** `text` on one line, with every control character, invisible character and non-ASCII space shown as an escape. */\nexport const visible = (text: string): string =>\n text.replace(NOT_PRINTABLE_ASCII, (char) => {\n const code = codeOf(char);\n return within(code, INVISIBLE) || within(code, SPACES) ? escaped(char) : char;\n });\n\n/** `text` with its line breaks, tabs and spaces kept, and every other control or invisible character escaped. */\nexport const visibleBlock = (text: string): string =>\n text.replace(NOT_PRINTABLE_ASCII, (char) =>\n char !== \"\\n\" && char !== \"\\t\" && within(codeOf(char), INVISIBLE) ? escaped(char) : char,\n );\n"]}
@@ -0,0 +1,63 @@
1
+ /**
2
+ * One session as the CLI's client sees it: the events the server streams for it, the turns that settle, and the
3
+ * requests for a person that wait for an answer. Opening a stored session replays its log first, and the replayed
4
+ * events are marked, so the meter counts what the session has already cost while the screen shows only what is new.
5
+ */
6
+ import type { InProcessClient } from "@buildanagent/harness/server";
7
+ import { type HarnessEvent, type ServerRequest, type TurnResultSummary } from "@buildanagent/protocol";
8
+ import type { AgentEvent, Resolution } from "@buildanagent/sdk";
9
+ /** A request for a person: an approval or a clarification. */
10
+ export type PersonRequest = Extract<ServerRequest, {
11
+ method: "approval/request" | "clarification/request";
12
+ }>;
13
+ /** Called with each event of the session; `replayed` is true for an event read back from the log on open. */
14
+ export type EventListener = (event: AgentEvent | HarnessEvent, seq: number, replayed: boolean) => void;
15
+ /** A settled turn. */
16
+ export interface Settled {
17
+ readonly turn: string;
18
+ readonly result: TurnResultSummary;
19
+ }
20
+ /** The stop reasons that mean a turn waits for a person. */
21
+ export declare const WAITING_REASONS: ReadonlySet<string>;
22
+ /** How long `whenAsked()` waits for the server to ask about a request before it checks the log. */
23
+ export declare const ASK_WAIT_MS = 5000;
24
+ /** Watches one session on `client`. Call `stop()` when done with it. */
25
+ export declare class SessionWatch {
26
+ #private;
27
+ readonly session: string;
28
+ /** The requests for a person that wait on this client, by request id. */
29
+ readonly asked: Map<string, PersonRequest>;
30
+ /** The input each approval request's call would run with, from its `approval_requested` entry. */
31
+ readonly inputs: Map<string, unknown>;
32
+ constructor(client: InProcessClient, session: string, listener: EventListener);
33
+ /** Marks the events that follow as replayed until `replayed` is called with false. */
34
+ replaying(on: boolean): void;
35
+ /** The next turn to settle, or one that settled and has not been taken yet. */
36
+ nextSettled(): Promise<Settled>;
37
+ /**
38
+ * Resolves once every request in `ids` has been asked on this client, answered, withdrawn or settled elsewhere. The
39
+ * server asks about a stored session's requests when it opens, but it skips them when it can't read the log in
40
+ * time, so after `waitMs` without a change the log decides. Throws a `CliError`, code `session_unavailable`, when a
41
+ * request still waits there that the server never asked about.
42
+ */
43
+ whenAsked(ids: readonly string[], waitMs?: number): Promise<void>;
44
+ /** Answers one request for a person. */
45
+ answer(request: PersonRequest, resolution: Resolution): void;
46
+ /**
47
+ * Whether another turn will settle for an answer this client gave: a settled turn is ready to take, a resume has
48
+ * written one of the answers and still runs, or the log still shows an answered request waiting, so a resume will
49
+ * take it. An answered request the log no longer shows, and that no resume of ours wrote, was settled by another
50
+ * process, and no turn settles for it here.
51
+ */
52
+ settlePending(): Promise<boolean>;
53
+ /** Stops listening. */
54
+ stop(): void;
55
+ }
56
+ /**
57
+ * Opens a stored session on `watch`'s client and replays its log into the watch, marked as replayed. Resolves with
58
+ * the ids of the requests that still wait, once the replay is in: the `approval/list` answer comes after it. Throws a
59
+ * `CliError`, code `unknown_session`, when no session has the id.
60
+ */
61
+ export declare function openStored(client: InProcessClient, watch: SessionWatch, cwd: string): Promise<string[]>;
62
+ /** Starts a turn with `text` and resolves once it settles. Throws a `CliError` when the session refuses the turn. */
63
+ export declare function runTurn(client: InProcessClient, watch: SessionWatch, text: string): Promise<TurnResultSummary>;