@a-dray/aglib 0.1.0 → 0.1.1

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.
@@ -1 +1 @@
1
- {"version":3,"file":"model.js","sourceRoot":"","sources":["../../src/model/model.ts"],"names":[],"mappings":"AAyEA,wDAAwD;AACxD,MAAM,CAAC,KAAK,UAAU,OAAO,CAC3B,UAAyE;IAEzE,IAAI,IAAI,GAAG,MAAM,UAAU,CAAC,IAAI,EAAE,CAAC;IACnC,OAAO,CAAC,IAAI,CAAC,IAAI;QAAE,IAAI,GAAG,MAAM,UAAU,CAAC,IAAI,EAAE,CAAC;IAClD,OAAO,IAAI,CAAC,KAAK,CAAC;AACpB,CAAC","sourcesContent":["import type { Content, ContentPart } from \"../content.js\";\nimport type { ToolCall, Usage } from \"../session/entry.js\";\nimport type { Message } from \"../session/messages.js\";\nimport type { ToolSpec } from \"../tools/tool.js\";\nimport type { Failure, Result } from \"../result.js\";\nimport type { JsonValue } from \"../json.js\";\n\n/**\n * One provider call.\n *\n * There is no model *name* here, and that is the point: a model is a value.\n * `createAnthropicModel({ apiKey, model })` is the provider, the credential and\n * the model together, and choosing a different one is choosing a different\n * `Model` — which is already how the loop passes a cheaper one to compaction.\n *\n * A name would have to be resolved, and resolving is what goes wrong. The one\n * application that had a name field to use encoded provider and model into it\n * as `provider/model`, then had to split it back out — ambiguously, because a\n * provider's own ids contain slashes (`z-ai/glm-5.2`), so the split was\n * \"up to the first one\" with a comment apologising for it. One field, two facts.\n * Names leave this library as observations — `ModelResponse.model` says what\n * actually served — and never enter it as selections.\n */\nexport interface ModelRequest {\n messages: readonly Message[];\n tools?: readonly ToolSpec[];\n maxOutputTokens?: number;\n /**\n * Only for providers that still accept sampling controls. The current\n * Anthropic models reject it outright, so that adapter does not send it —\n * declaring the option here and dropping it there is the honest shape, since\n * the alternative is a request the provider 400s.\n */\n temperature?: number;\n /**\n * How much the model should think before answering, where it can. Named\n * levels rather than a token budget, because a budget is the one thing no\n * two providers agree on — and the providers that had one have since removed\n * it. Each adapter maps a level to its own control; one that has none\n * ignores it rather than failing.\n */\n effort?: \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n /** End the cacheable prefix after this many messages. A decision about one request only. */\n cacheAfter?: number;\n signal?: AbortSignal;\n}\n\nexport type ModelDelta =\n | { type: \"text.delta\"; text: string }\n | { type: \"reasoning.delta\"; text: string }\n | { type: \"tool-call.delta\"; callId: string; arguments: string };\n\nexport interface ModelResponse {\n message: { content: Content; calls?: readonly ToolCall[] };\n finishReason: \"stop\" | \"tool-calls\" | \"length\" | \"refusal\";\n usage: Usage;\n model?: string;\n}\n\nexport interface ModelError extends Failure {\n code: \"auth\" | \"rate-limit\" | \"context-length\" | \"cancelled\" | \"provider\" | \"failed\";\n}\n\n/**\n * One method. Streaming is not a second contract: a caller that wants the whole\n * response drains the generator and takes its return value, so no adapter has\n * to implement the same normalization twice.\n */\nexport interface Model {\n readonly id: string;\n generate(request: ModelRequest): AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>>;\n}\n\n/** Drains a generation and returns only its outcome. */\nexport async function collect(\n generation: AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>>,\n): Promise<Result<ModelResponse, ModelError>> {\n let step = await generation.next();\n while (!step.done) step = await generation.next();\n return step.value;\n}\n\n/**\n * The vocabulary an adapter needs, re-exported from the port it implements.\n * An adapter imports these from here rather than reaching into the modules that\n * own them, so the port is the whole of its surface — every one of them appears\n * in a type above, which is what makes this the place to get them.\n */\nexport type { ContentPart, Message, ToolCall, ToolSpec, Usage };\n"]}
1
+ {"version":3,"file":"model.js","sourceRoot":"","sources":["../../src/model/model.ts"],"names":[],"mappings":"AAyEA;;;;;;;GAOG;AACH,MAAM,CAAC,KAAK,UAAU,OAAO,CAC3B,UAAyE;IAEzE,IAAI,IAAI,GAAG,MAAM,UAAU,CAAC,IAAI,EAAE,CAAC;IACnC,OAAO,CAAC,IAAI,CAAC,IAAI;QAAE,IAAI,GAAG,MAAM,UAAU,CAAC,IAAI,EAAE,CAAC;IAClD,OAAO,IAAI,CAAC,KAAK,CAAC;AACpB,CAAC","sourcesContent":["import type { Content, ContentPart } from \"../content.js\";\nimport type { ToolCall, Usage } from \"../session/entry.js\";\nimport type { Message } from \"../session/messages.js\";\nimport type { ToolSpec } from \"../tools/tool.js\";\nimport type { Failure, Result } from \"../result.js\";\nimport type { JsonValue } from \"../json.js\";\n\n/**\n * One provider call.\n *\n * There is no model *name* here, and that is the point: a model is a value.\n * `createAnthropicModel({ apiKey, model })` is the provider, the credential and\n * the model together, and choosing a different one is choosing a different\n * `Model` — which is already how the loop passes a cheaper one to compaction.\n *\n * A name would have to be resolved, and resolving is what goes wrong. The one\n * application that had a name field to use encoded provider and model into it\n * as `provider/model`, then had to split it back out — ambiguously, because a\n * provider's own ids contain slashes (`z-ai/glm-5.2`), so the split was\n * \"up to the first one\" with a comment apologising for it. One field, two facts.\n * Names leave this library as observations — `ModelResponse.model` says what\n * actually served — and never enter it as selections.\n */\nexport interface ModelRequest {\n messages: readonly Message[];\n tools?: readonly ToolSpec[];\n maxOutputTokens?: number;\n /**\n * Only for providers that still accept sampling controls. The current\n * Anthropic models reject it outright, so that adapter does not send it —\n * declaring the option here and dropping it there is the honest shape, since\n * the alternative is a request the provider 400s.\n */\n temperature?: number;\n /**\n * How much the model should think before answering, where it can. Named\n * levels rather than a token budget, because a budget is the one thing no\n * two providers agree on — and the providers that had one have since removed\n * it. Each adapter maps a level to its own control; one that has none\n * ignores it rather than failing.\n */\n effort?: \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n /** End the cacheable prefix after this many messages. A decision about one request only. */\n cacheAfter?: number;\n signal?: AbortSignal;\n}\n\nexport type ModelDelta =\n | { type: \"text.delta\"; text: string }\n | { type: \"reasoning.delta\"; text: string }\n | { type: \"tool-call.delta\"; callId: string; arguments: string };\n\nexport interface ModelResponse {\n message: { content: Content; calls?: readonly ToolCall[] };\n finishReason: \"stop\" | \"tool-calls\" | \"length\" | \"refusal\";\n usage: Usage;\n model?: string;\n}\n\nexport interface ModelError extends Failure {\n code: \"auth\" | \"rate-limit\" | \"context-length\" | \"cancelled\" | \"provider\" | \"failed\";\n}\n\n/**\n * One method. Streaming is not a second contract: a caller that wants the whole\n * response drains the generator and takes its return value, so no adapter has\n * to implement the same normalization twice.\n */\nexport interface Model {\n readonly id: string;\n generate(request: ModelRequest): AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>>;\n}\n\n/**\n * Drains a generation and returns only its outcome.\n *\n * Not on the `aglib/model` subpath. It was, for a recipe that turned a `Model`\n * into an Anthropic response; when that went, nothing outside the package\n * consumed it. `Model`'s own contract above says what a caller who wants the\n * whole response does, and this is the four lines of doing it.\n */\nexport async function collect(\n generation: AsyncGenerator<ModelDelta, Result<ModelResponse, ModelError>>,\n): Promise<Result<ModelResponse, ModelError>> {\n let step = await generation.next();\n while (!step.done) step = await generation.next();\n return step.value;\n}\n\n/**\n * The vocabulary an adapter needs, re-exported from the port it implements.\n * An adapter imports these from here rather than reaching into the modules that\n * own them, so the port is the whole of its surface — every one of them appears\n * in a type above, which is what makes this the place to get them.\n */\nexport type { ContentPart, Message, ToolCall, ToolSpec, Usage };\n"]}
@@ -0,0 +1,100 @@
1
+ /**
2
+ * A run, as lines someone can read.
3
+ *
4
+ * A root file rather than a module, and a projection rather than a port: this
5
+ * is `textOf` one level out. `toMessages` folds committed entries into what a
6
+ * model is shown; this folds the update stream into what a person is shown. No
7
+ * adapter has to prove anything about it, so there is nothing here for a
8
+ * conformance suite to hold, and nothing below it to rank against.
9
+ *
10
+ * **It is not a channel, and the difference is worth stating because it is
11
+ * subtle.** A channel does three jobs: decide which session a person is talking
12
+ * to, deliver a message exactly once, and put the result in a medium's own
13
+ * shape. The first two are an application's — a mail thread maps to a session,
14
+ * a webhook may arrive twice. Only the third is the same work for every medium,
15
+ * and only the third is here. Email is a channel with no projection at all: it
16
+ * sends `RunResult.output` and never looks at the stream. A terminal is the
17
+ * other extreme — its identity is "the one session" and its delivery is a pipe
18
+ * that cannot fail, so a terminal channel is *nothing but* this projection.
19
+ *
20
+ * **The answer and the stream are different things, and only one is a message.**
21
+ * `RunResult.output` is what `finished` hands to `Delivery.input`: the same
22
+ * `Content`, whether the recipient is a person or another session. The stream
23
+ * is not a message and never becomes one — a `cancelled` or `failed` result has
24
+ * no `output` field at all, so a run can stream a paragraph and produce nothing
25
+ * that could be delivered.
26
+ *
27
+ * Showing that paragraph is not a mistake. Watching what an agent was saying
28
+ * when it was cancelled is most of what debugging one is. What would be a
29
+ * mistake is leaving the outcome implicit, so the text reads as an answer that
30
+ * was never given — which is why `finish` always states it, and takes it from
31
+ * the result rather than from whatever happened to stream.
32
+ *
33
+ * **`detail` is the knob that makes one projection serve every medium.** Three
34
+ * levels, because what the knob is graduated in is the *internal stream* and
35
+ * not the conversation: a tool call is the agent talking to itself, while a
36
+ * message arriving from a subagent, a peer or a person is the conversation
37
+ * happening. The log keeps those apart — one is an entry the loop wrote, the
38
+ * other came through `enqueue` — so the projection does too.
39
+ *
40
+ * There is no level below `"minimal"`, and there was one. A medium with no
41
+ * second channel says so by having no `status`, which drops the account
42
+ * entirely; a `detail` that meant the same thing was a second way to state a
43
+ * fact the `Sink` already stated. Failures are not behind a level either — an
44
+ * agent that silently did nothing is the one outcome a reader cannot diagnose
45
+ * from what they were shown.
46
+ *
47
+ * Two channels out, because they answer different questions. `write` carries
48
+ * the answer, so redirecting it captures the answer and nothing else. `status`
49
+ * carries what the agent did on the way — tools, provenance, what it spent.
50
+ */
51
+ import type { AgentRun, RunResult } from "./agent.js";
52
+ import type { Update } from "./harness/harness.js";
53
+ import type { ToolCall, Usage } from "./session/entry.js";
54
+ export interface Sink {
55
+ /** The answer: assistant text, exactly as it streamed. */
56
+ write(text: string): void;
57
+ /**
58
+ * Everything else: tools, provenance, what the run spent.
59
+ *
60
+ * Omit it and that account is **dropped**, not folded into `write`. Falling
61
+ * back would break the one promise `write` makes — that it holds the answer
62
+ * and nothing else — for every caller who only wanted the answer and did not
63
+ * think to say so.
64
+ */
65
+ status?(line: string): void;
66
+ /** Enables colour and the elapsed-time ticker. A caller without a terminal leaves it off. */
67
+ tty?: boolean;
68
+ /**
69
+ * How much of the run to show.
70
+ *
71
+ * `"minimal"` is the conversation: the answer, input that arrived from
72
+ * somewhere else, and anything that failed. `"standard"` adds the internal
73
+ * stream — tool calls, their results, and what the run spent. `"detailed"`
74
+ * adds what it was thinking, arguments as they form, and the structured
75
+ * `details` a tool returned.
76
+ *
77
+ * For the answer and nothing whatever beside it, give a sink with no
78
+ * `status`.
79
+ */
80
+ detail?: "minimal" | "standard" | "detailed";
81
+ /**
82
+ * Marks a run being watched rather than driven — a subagent taken off the
83
+ * queue, most often. A labelled run has no answer channel: nobody asked it
84
+ * anything, so everything it says is an account of what the run it belongs
85
+ * to is doing, and all of it is prefixed and sent to `status`.
86
+ */
87
+ label?: string;
88
+ /** Milliseconds, for durations. Supplied by a test so its output is exact. */
89
+ now?(): number;
90
+ }
91
+ /**
92
+ * Render a run to its end, and answer what it did.
93
+ *
94
+ * The loop every application writes by hand, with the two things a hand-written
95
+ * one keeps getting wrong: everything the stream carries besides text, and an
96
+ * outcome taken from the result rather than from whatever happened to stream.
97
+ */
98
+ export declare function renderRun(run: AgentRun, sink: Sink): Promise<RunResult>;
99
+ /** Re-exported so a caller composing a sink imports one thing. */
100
+ export type { Update, RunResult, Usage, ToolCall };
package/dist/render.js ADDED
@@ -0,0 +1,370 @@
1
+ import { textOf } from "./content.js";
2
+ /**
3
+ * The one animation, and it is data rather than a dependency.
4
+ *
5
+ * Braille dots because they are one column wide in every terminal that has the
6
+ * font and degrade to boxes rather than to a broken layout in the ones that do
7
+ * not. Written to `status`, so the answer channel stays something a pipe can
8
+ * read.
9
+ */
10
+ const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
11
+ const DIM = "\x1b[2m";
12
+ const RED = "\x1b[31m";
13
+ const GREEN = "\x1b[32m";
14
+ const RESET = "\x1b[0m";
15
+ /** One line, however long the thing being described is. */
16
+ const oneLine = (text, limit = 96) => {
17
+ const flat = text.replace(/\s+/g, " ").trim();
18
+ return flat.length > limit ? `${flat.slice(0, limit - 1)}…` : flat;
19
+ };
20
+ const round = (count) => count >= 1000 ? `${(count / 1000).toFixed(1)}k` : `${count}`;
21
+ const seconds = (ms) => `${(ms / 1000).toFixed(1)}s`;
22
+ /**
23
+ * Content as the model sees it, plus a marker for every part it cannot.
24
+ *
25
+ * `textOf` drops images, files and opaque blocks, which is right for a model
26
+ * and wrong for a person: a screen showing less than the log holds, silently,
27
+ * is the omission this package refuses everywhere else.
28
+ */
29
+ function readable(content) {
30
+ if (typeof content === "string")
31
+ return content;
32
+ return content.map((part) => part.type === "text" ? part.text
33
+ : part.type === "image" ? `[image ${part.mediaType}]`
34
+ : part.type === "file" ? `[file ${part.name ?? part.mediaType}]`
35
+ : `[opaque ${part.provider}]`).join("\n");
36
+ }
37
+ function createRenderer(sink) {
38
+ const status = sink.status ?? (() => { });
39
+ const detail = sink.detail ?? "standard";
40
+ const debugging = detail === "detailed";
41
+ /** The agent talking to its own tools, as opposed to the conversation. */
42
+ const internal = debugging || detail === "standard";
43
+ const now = sink.now ?? (() => Date.now());
44
+ const label = sink.label ? `${sink.label} ` : "";
45
+ const started = now();
46
+ const dim = (text) => (sink.tty ? `${DIM}${text}${RESET}` : text);
47
+ const mark = (glyph, bad) => sink.tty ? `${bad ? RED : GREEN}${glyph}${RESET}` : glyph;
48
+ /** Names by call id. A tool entry carries only the id; the assistant entry above holds the name. */
49
+ const names = new Map();
50
+ /** When each call started, so a result can say how long it took. */
51
+ const clocks = new Map();
52
+ /**
53
+ * What has been streamed since the last assistant entry.
54
+ *
55
+ * The harnesses disagree about deltas — some stream tokens, some emit one
56
+ * delta per whole message, and some emit none at all. The entry stream is
57
+ * the one channel every harness fills, so
58
+ * the entry decides what is shown and the deltas decide how much of it
59
+ * already has been.
60
+ *
61
+ * The rule the port does not state, and this therefore does not assume:
62
+ * deltas preceding an assistant entry *ought* to concatenate to its text.
63
+ * Where they do, the remainder is printed and nothing appears twice. Where
64
+ * they are absent, the whole entry is printed. Where they are neither — a
65
+ * harness that streamed something else, or stopped halfway — the entry is
66
+ * printed in full on a fresh line, because showing a reader the same words
67
+ * twice is a smaller failure than silently dropping the half nobody streamed.
68
+ */
69
+ let streamed = "";
70
+ let turns = 0;
71
+ /** Whether the last thing written ended mid-line, so a status line can open a fresh one. */
72
+ let open = false;
73
+ let thinking = false;
74
+ /**
75
+ * The calls in flight, and the one status line describing all of them.
76
+ *
77
+ * One ticker for the renderer rather than one per call. A tool call is not
78
+ * exclusive — a harness may start four at once, and Pi does — and a per-call
79
+ * interval meant each `tool.started` overwrote the last without clearing it:
80
+ * the orphans kept drawing to the same line for the life of the process,
81
+ * fighting each other and interleaving with committed lines. A terminal has
82
+ * one status line, so there is one thing drawing it.
83
+ *
84
+ * No `at` is kept here. `clocks` already holds when each call started, and a
85
+ * second copy is a second answer.
86
+ */
87
+ const running = new Set();
88
+ let ticker;
89
+ /** Whether the status line currently holds a spinner that must be erased before anything else. */
90
+ let drawn = false;
91
+ /**
92
+ * Erase the spinner, leaving the cursor at the start of a clean line.
93
+ *
94
+ * Called before *every* write, because `\r` returns to the start of whatever
95
+ * line is current and half a streamed sentence is as much a casualty as a
96
+ * status line. The ticker redraws on its next tick if work is still in
97
+ * flight, so this costs nothing but a frame.
98
+ */
99
+ const clearSpinner = () => {
100
+ if (!drawn)
101
+ return;
102
+ drawn = false;
103
+ status("\r\x1b[K");
104
+ };
105
+ const line = (text) => {
106
+ clearSpinner();
107
+ if (open) {
108
+ sink.write("\n");
109
+ open = false;
110
+ }
111
+ status(`${label}${text}\n`);
112
+ };
113
+ const stopTicker = () => {
114
+ if (ticker) {
115
+ clearInterval(ticker);
116
+ ticker = undefined;
117
+ }
118
+ clearSpinner();
119
+ };
120
+ /**
121
+ * What is running, in the width of one line.
122
+ *
123
+ * The oldest call names itself and carries the clock, because it is the one a
124
+ * reader is waiting on; the rest are a count. Naming all four would be a
125
+ * line that changes width every time one finishes.
126
+ */
127
+ const inFlight = (glyph) => {
128
+ const oldest = [...running].sort((a, b) => (clocks.get(a) ?? 0) - (clocks.get(b) ?? 0))[0];
129
+ if (oldest === undefined)
130
+ return "";
131
+ const name = names.get(oldest) ?? oldest.slice(0, 8);
132
+ const others = running.size - 1;
133
+ return `${label}${glyph} ${name}${others ? ` +${others}` : ""} ${seconds(now() - (clocks.get(oldest) ?? now()))}`;
134
+ };
135
+ /**
136
+ * The one piece of cursor control in this file, and the only reason a long
137
+ * command is not silence. Unref'd so it can never hold a process open.
138
+ *
139
+ * It does not draw over an open line: `say` leaves the cursor mid-sentence
140
+ * while text streams, and `\r` there would eat the sentence. Nothing is lost
141
+ * — the next tick after the newline draws it.
142
+ */
143
+ const startTicker = () => {
144
+ if (ticker || !sink.tty)
145
+ return;
146
+ let frame = 0;
147
+ ticker = setInterval(() => {
148
+ if (open || !running.size)
149
+ return;
150
+ const text = inFlight(SPINNER[frame++ % SPINNER.length]);
151
+ if (!text)
152
+ return;
153
+ drawn = true;
154
+ status(`\r${DIM}${text}${RESET}\x1b[K`);
155
+ }, 90);
156
+ ticker.unref?.();
157
+ };
158
+ /** Partial line held back while a labelled run streams, so the prefix stays whole. */
159
+ let held = "";
160
+ /**
161
+ * Write text for the reader. The primitive; `say` is the streaming door to it.
162
+ *
163
+ * Only a delta counts as *streamed*. An entry printed through here must not
164
+ * be added to `streamed`, or its own words become the "already shown" prefix
165
+ * the next entry is measured against — and since a second turn's text does
166
+ * not begin with a first turn's, `startsWith` failed and the whole turn was
167
+ * printed again under the half that had already streamed.
168
+ */
169
+ const emit = (text) => {
170
+ clearSpinner();
171
+ if (thinking) {
172
+ thinking = false;
173
+ }
174
+ if (!sink.label) {
175
+ sink.write(text);
176
+ open = !text.endsWith("\n");
177
+ return;
178
+ }
179
+ // A prefix cannot be applied to half a line, so a labelled run buffers to
180
+ // the newline. Nothing is lost: `finish` flushes whatever is left.
181
+ held += text;
182
+ let cut = held.indexOf("\n");
183
+ while (cut !== -1) {
184
+ line(held.slice(0, cut));
185
+ held = held.slice(cut + 1);
186
+ cut = held.indexOf("\n");
187
+ }
188
+ };
189
+ /** A delta: written, and recorded as the part of the coming entry already shown. */
190
+ const say = (text) => { streamed += text; emit(text); };
191
+ const entry = (stored) => {
192
+ if (stored.type === "run.started") {
193
+ // Input with no `from` is what the caller just passed in. Echoing it says
194
+ // everything twice. Input *with* one came from somewhere else — a
195
+ // subagent's report, a peer, a person on a channel — and saying so is the
196
+ // only way that arrival is visible as itself.
197
+ if (stored.from) {
198
+ line(dim(`◦ from ${stored.from.kind} ${stored.from.id.slice(0, 8)} · ${oneLine(readable(stored.input), 72)}`));
199
+ }
200
+ return;
201
+ }
202
+ if (stored.type === "assistant") {
203
+ turns += 1;
204
+ const said = readable(stored.content);
205
+ if (said) {
206
+ const shown = streamed;
207
+ // Cleared first: `say` appends to it, and what matters is what had been
208
+ // streamed *before* this entry arrived.
209
+ streamed = "";
210
+ if (!shown)
211
+ emit(said.endsWith("\n") ? said : `${said}\n`);
212
+ else if (said.startsWith(shown)) {
213
+ const rest = said.slice(shown.length);
214
+ if (rest)
215
+ emit(rest.endsWith("\n") ? rest : `${rest}\n`);
216
+ else if (open)
217
+ emit("\n");
218
+ }
219
+ else {
220
+ if (open)
221
+ sink.write("\n");
222
+ emit(said.endsWith("\n") ? said : `${said}\n`);
223
+ }
224
+ }
225
+ else {
226
+ streamed = "";
227
+ }
228
+ for (const call of stored.calls ?? []) {
229
+ // The name is recorded whatever the level: a result rendered later
230
+ // reads it, and a reader who turns detail up mid-run should not meet a
231
+ // call id where every other line has a name.
232
+ names.set(call.callId, call.name);
233
+ if (internal)
234
+ line(dim(`→ ${call.name} ${oneLine(call.arguments, 72)}`));
235
+ }
236
+ return;
237
+ }
238
+ if (stored.type === "tool.started") {
239
+ clocks.set(stored.callId, now());
240
+ // At every level, unlike everything else about a call. A spinner is not
241
+ // an account of what the agent did — it leaves no trace, and it is the
242
+ // only thing between a reader and thirty seconds of silence.
243
+ running.add(stored.callId);
244
+ startTicker();
245
+ return;
246
+ }
247
+ if (stored.type === "tool.finished") {
248
+ running.delete(stored.callId);
249
+ if (!running.size)
250
+ stopTicker();
251
+ const at = clocks.get(stored.callId);
252
+ clocks.delete(stored.callId);
253
+ const name = names.get(stored.callId) ?? stored.callId.slice(0, 8);
254
+ const took = at === undefined ? "" : ` · ${seconds(now() - at)}`;
255
+ const body = oneLine(readable(stored.result.content), 64);
256
+ const failed = stored.result.isError === true;
257
+ // A success is the agent working; a failure is something the reader has
258
+ // to know about whatever they asked to be shown.
259
+ if (failed || internal) {
260
+ line(`${mark(failed ? "✗" : "✓", failed)} ${dim(`${name}${took}${body ? ` · ${body}` : ""}`)}`);
261
+ }
262
+ // `details` is the structured channel for an application's own UI and
263
+ // holds whatever that application put there — which may include a
264
+ // credential. Asked for explicitly it is shown; it is never volunteered.
265
+ if (debugging && stored.result.details !== undefined) {
266
+ line(dim(` ${oneLine(JSON.stringify(stored.result.details), 96)}`));
267
+ }
268
+ return;
269
+ }
270
+ if (stored.type === "summary") {
271
+ if (internal)
272
+ line(dim(`· compacted through seq ${stored.replaces}`));
273
+ }
274
+ // `run.finished` is not rendered here. `finish` owns the last line, because
275
+ // `RunResult` carries what the entry cannot: what the run spent, on every
276
+ // outcome including the ones with no answer.
277
+ };
278
+ return {
279
+ update(next) {
280
+ if (next.type === "text.delta") {
281
+ say(next.text);
282
+ return;
283
+ }
284
+ if (next.type === "reasoning.delta") {
285
+ // Reasoning can outweigh the answer several times over, so it is behind
286
+ // `"detailed"` rather than dimmed and always present.
287
+ if (!debugging)
288
+ return;
289
+ if (!thinking) {
290
+ line(dim("· thinking"));
291
+ thinking = true;
292
+ }
293
+ clearSpinner();
294
+ status(dim(next.text));
295
+ return;
296
+ }
297
+ // A harness that reports progress reports it several times per call, in
298
+ // whatever shape its protocol happens to use — ACP forwards its whole
299
+ // `session/update`. That is a debugging channel, not a reading one: the
300
+ // call itself is announced by the entry that carries it, and the name is
301
+ // not even known yet on the first of these. So it sits behind `"detailed"`
302
+ // beside `tool-call.delta`, for the same reason.
303
+ if (next.type === "tool.progress") {
304
+ if (!debugging)
305
+ return;
306
+ const name = names.get(next.callId) ?? next.callId.slice(0, 8);
307
+ line(dim(`⋯ ${name} ${oneLine(JSON.stringify(next.data), 64)}`));
308
+ return;
309
+ }
310
+ // Arguments as they form are unparseable until complete and only one
311
+ // harness emits them, so they are worth nothing to a reader and
312
+ // everything to someone asking why a call came out the way it did.
313
+ if (next.type === "tool-call.delta") {
314
+ if (debugging)
315
+ line(dim(` ${next.callId.slice(0, 8)} ${oneLine(next.arguments, 64)}`));
316
+ return;
317
+ }
318
+ if (next.type === "entry")
319
+ entry(next.entry);
320
+ },
321
+ finish(result) {
322
+ running.clear();
323
+ stopTicker();
324
+ if (held) {
325
+ line(held);
326
+ held = "";
327
+ }
328
+ if (open) {
329
+ sink.write("\n");
330
+ open = false;
331
+ }
332
+ const spent = [
333
+ result.usage.inputTokens !== undefined ? `${round(result.usage.inputTokens)} in` : undefined,
334
+ result.usage.cacheReadTokens ? `${round(result.usage.cacheReadTokens)} cached` : undefined,
335
+ result.usage.outputTokens !== undefined ? `${round(result.usage.outputTokens)} out` : undefined,
336
+ ].filter((part) => part !== undefined);
337
+ // A count nobody reported is not a zero, so an absent one is left out
338
+ // rather than printed as 0.
339
+ const parts = [
340
+ seconds(now() - started),
341
+ `${turns} ${turns === 1 ? "turn" : "turns"}`,
342
+ ...spent,
343
+ ].join(" · ");
344
+ if (result.status === "failed") {
345
+ line(`${mark("✗", true)} ${dim(`failed (${result.error.code}): ${oneLine(result.error.message, 80)} · ${parts}`)}`);
346
+ return;
347
+ }
348
+ // `cancelled` is an ending nobody asked for, so it is said at every
349
+ // level that says anything. A clean completion is an accounting line.
350
+ if (result.status === "cancelled" || internal)
351
+ line(dim(`— ${result.status} · ${parts}`));
352
+ },
353
+ };
354
+ }
355
+ /**
356
+ * Render a run to its end, and answer what it did.
357
+ *
358
+ * The loop every application writes by hand, with the two things a hand-written
359
+ * one keeps getting wrong: everything the stream carries besides text, and an
360
+ * outcome taken from the result rather than from whatever happened to stream.
361
+ */
362
+ export async function renderRun(run, sink) {
363
+ const renderer = createRenderer(sink);
364
+ for await (const update of run)
365
+ renderer.update(update);
366
+ const result = await run.result;
367
+ renderer.finish(result);
368
+ return result;
369
+ }
370
+ //# sourceMappingURL=render.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render.js","sourceRoot":"","sources":["../src/render.ts"],"names":[],"mappings":"AAsDA,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAuDtC;;;;;;;GAOG;AACH,MAAM,OAAO,GAAG,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAU,CAAC;AAE5E,MAAM,GAAG,GAAG,SAAS,CAAC;AACtB,MAAM,GAAG,GAAG,UAAU,CAAC;AACvB,MAAM,KAAK,GAAG,UAAU,CAAC;AACzB,MAAM,KAAK,GAAG,SAAS,CAAC;AAExB,2DAA2D;AAC3D,MAAM,OAAO,GAAG,CAAC,IAAY,EAAE,KAAK,GAAG,EAAE,EAAU,EAAE;IACnD,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC;IAC9C,OAAO,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;AACrE,CAAC,CAAC;AAEF,MAAM,KAAK,GAAG,CAAC,KAAa,EAAU,EAAE,CACtC,KAAK,IAAI,IAAI,CAAC,CAAC,CAAC,G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;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAAC,GAAa,EAAE,IAAU;IACvD,MAAM,QAAQ,GAAG,cAAc,CAAC,IAAI,CAAC,CAAC;IACtC,IAAI,KAAK,EAAE,MAAM,MAAM,IAAI,GAAG;QAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IACxD,MAAM,MAAM,GAAG,MAAM,GAAG,CAAC,MAAM,CAAC;IAChC,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;IACxB,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["/**\n * A run, as lines someone can read.\n *\n * A root file rather than a module, and a projection rather than a port: this\n * is `textOf` one level out. `toMessages` folds committed entries into what a\n * model is shown; this folds the update stream into what a person is shown. No\n * adapter has to prove anything about it, so there is nothing here for a\n * conformance suite to hold, and nothing below it to rank against.\n *\n * **It is not a channel, and the difference is worth stating because it is\n * subtle.** A channel does three jobs: decide which session a person is talking\n * to, deliver a message exactly once, and put the result in a medium's own\n * shape. The first two are an application's — a mail thread maps to a session,\n * a webhook may arrive twice. Only the third is the same work for every medium,\n * and only the third is here. Email is a channel with no projection at all: it\n * sends `RunResult.output` and never looks at the stream. A terminal is the\n * other extreme — its identity is \"the one session\" and its delivery is a pipe\n * that cannot fail, so a terminal channel is *nothing but* this projection.\n *\n * **The answer and the stream are different things, and only one is a message.**\n * `RunResult.output` is what `finished` hands to `Delivery.input`: the same\n * `Content`, whether the recipient is a person or another session. The stream\n * is not a message and never becomes one — a `cancelled` or `failed` result has\n * no `output` field at all, so a run can stream a paragraph and produce nothing\n * that could be delivered.\n *\n * Showing that paragraph is not a mistake. Watching what an agent was saying\n * when it was cancelled is most of what debugging one is. What would be a\n * mistake is leaving the outcome implicit, so the text reads as an answer that\n * was never given — which is why `finish` always states it, and takes it from\n * the result rather than from whatever happened to stream.\n *\n * **`detail` is the knob that makes one projection serve every medium.** Three\n * levels, because what the knob is graduated in is the *internal stream* and\n * not the conversation: a tool call is the agent talking to itself, while a\n * message arriving from a subagent, a peer or a person is the conversation\n * happening. The log keeps those apart — one is an entry the loop wrote, the\n * other came through `enqueue` — so the projection does too.\n *\n * There is no level below `\"minimal\"`, and there was one. A medium with no\n * second channel says so by having no `status`, which drops the account\n * entirely; a `detail` that meant the same thing was a second way to state a\n * fact the `Sink` already stated. Failures are not behind a level either — an\n * agent that silently did nothing is the one outcome a reader cannot diagnose\n * from what they were shown.\n *\n * Two channels out, because they answer different questions. `write` carries\n * the answer, so redirecting it captures the answer and nothing else. `status`\n * carries what the agent did on the way — tools, provenance, what it spent.\n */\nimport type { AgentRun, RunResult } from \"./agent.js\";\nimport type { Update } from \"./harness/harness.js\";\nimport type { Content, ContentPart } from \"./content.js\";\nimport type { Stored, ToolCall, Usage } from \"./session/entry.js\";\nimport { textOf } from \"./content.js\";\n\nexport interface Sink {\n /** The answer: assistant text, exactly as it streamed. */\n write(text: string): void;\n /**\n * Everything else: tools, provenance, what the run spent.\n *\n * Omit it and that account is **dropped**, not folded into `write`. Falling\n * back would break the one promise `write` makes — that it holds the answer\n * and nothing else — for every caller who only wanted the answer and did not\n * think to say so.\n */\n status?(line: string): void;\n /** Enables colour and the elapsed-time ticker. A caller without a terminal leaves it off. */\n tty?: boolean;\n /**\n * How much of the run to show.\n *\n * `\"minimal\"` is the conversation: the answer, input that arrived from\n * somewhere else, and anything that failed. `\"standard\"` adds the internal\n * stream — tool calls, their results, and what the run spent. `\"detailed\"`\n * adds what it was thinking, arguments as they form, and the structured\n * `details` a tool returned.\n *\n * For the answer and nothing whatever beside it, give a sink with no\n * `status`.\n */\n detail?: \"minimal\" | \"standard\" | \"detailed\";\n /**\n * Marks a run being watched rather than driven — a subagent taken off the\n * queue, most often. A labelled run has no answer channel: nobody asked it\n * anything, so everything it says is an account of what the run it belongs\n * to is doing, and all of it is prefixed and sent to `status`.\n */\n label?: string;\n /** Milliseconds, for durations. Supplied by a test so its output is exact. */\n now?(): number;\n}\n\n/**\n * Not exported, and that is the gate's doing rather than an oversight.\n *\n * `renderRun` is the whole of what a caller needs, and nothing here composes a\n * renderer by hand. A surface that pushes updates itself — an HTTP stream, a\n * Slack message it keeps editing — would want this, and it can be exported the\n * day one exists. Surface without a consumer is surface nobody is holding to\n * account.\n */\ninterface Renderer {\n update(update: Update): void;\n /** The outcome and what it spent. */\n finish(result: RunResult): void;\n}\n\n/**\n * The one animation, and it is data rather than a dependency.\n *\n * Braille dots because they are one column wide in every terminal that has the\n * font and degrade to boxes rather than to a broken layout in the ones that do\n * not. Written to `status`, so the answer channel stays something a pipe can\n * read.\n */\nconst SPINNER = [\"⠋\", \"⠙\", \"⠹\", \"⠸\", \"⠼\", \"⠴\", \"⠦\", \"⠧\", \"⠇\", \"⠏\"] as const;\n\nconst DIM = \"\\x1b[2m\";\nconst RED = \"\\x1b[31m\";\nconst GREEN = \"\\x1b[32m\";\nconst RESET = \"\\x1b[0m\";\n\n/** One line, however long the thing being described is. */\nconst oneLine = (text: string, limit = 96): string => {\n const flat = text.replace(/\\s+/g, \" \").trim();\n return flat.length > limit ? `${flat.slice(0, limit - 1)}…` : flat;\n};\n\nconst round = (count: number): string =>\n count >= 1000 ? `${(count / 1000).toFixed(1)}k` : `${count}`;\n\nconst seconds = (ms: number): string => `${(ms / 1000).toFixed(1)}s`;\n\n/**\n * Content as the model sees it, plus a marker for every part it cannot.\n *\n * `textOf` drops images, files and opaque blocks, which is right for a model\n * and wrong for a person: a screen showing less than the log holds, silently,\n * is the omission this package refuses everywhere else.\n */\nfunction readable(content: Content): string {\n if (typeof content === \"string\") return content;\n return content.map((part: ContentPart) =>\n part.type === \"text\" ? part.text\n : part.type === \"image\" ? `[image ${part.mediaType}]`\n : part.type === \"file\" ? `[file ${part.name ?? part.mediaType}]`\n : `[opaque ${part.provider}]`).join(\"\\n\");\n}\n\nfunction createRenderer(sink: Sink): Renderer {\n const status = sink.status ?? (() => {});\n const detail = sink.detail ?? \"standard\";\n const debugging = detail === \"detailed\";\n /** The agent talking to its own tools, as opposed to the conversation. */\n const internal = debugging || detail === \"standard\";\n const now = sink.now ?? (() => Date.now());\n const label = sink.label ? `${sink.label} ` : \"\";\n const started = now();\n\n const dim = (text: string) => (sink.tty ? `${DIM}${text}${RESET}` : text);\n const mark = (glyph: string, bad: boolean) =>\n sink.tty ? `${bad ? RED : GREEN}${glyph}${RESET}` : glyph;\n\n /** Names by call id. A tool entry carries only the id; the assistant entry above holds the name. */\n const names = new Map<string, string>();\n /** When each call started, so a result can say how long it took. */\n const clocks = new Map<string, number>();\n /**\n * What has been streamed since the last assistant entry.\n *\n * The harnesses disagree about deltas — some stream tokens, some emit one\n * delta per whole message, and some emit none at all. The entry stream is\n * the one channel every harness fills, so\n * the entry decides what is shown and the deltas decide how much of it\n * already has been.\n *\n * The rule the port does not state, and this therefore does not assume:\n * deltas preceding an assistant entry *ought* to concatenate to its text.\n * Where they do, the remainder is printed and nothing appears twice. Where\n * they are absent, the whole entry is printed. Where they are neither — a\n * harness that streamed something else, or stopped halfway — the entry is\n * printed in full on a fresh line, because showing a reader the same words\n * twice is a smaller failure than silently dropping the half nobody streamed.\n */\n let streamed = \"\";\n let turns = 0;\n /** Whether the last thing written ended mid-line, so a status line can open a fresh one. */\n let open = false;\n let thinking = false;\n\n /**\n * The calls in flight, and the one status line describing all of them.\n *\n * One ticker for the renderer rather than one per call. A tool call is not\n * exclusive — a harness may start four at once, and Pi does — and a per-call\n * interval meant each `tool.started` overwrote the last without clearing it:\n * the orphans kept drawing to the same line for the life of the process,\n * fighting each other and interleaving with committed lines. A terminal has\n * one status line, so there is one thing drawing it.\n *\n * No `at` is kept here. `clocks` already holds when each call started, and a\n * second copy is a second answer.\n */\n const running = new Set<string>();\n let ticker: ReturnType<typeof setInterval> | undefined;\n /** Whether the status line currently holds a spinner that must be erased before anything else. */\n let drawn = false;\n\n /**\n * Erase the spinner, leaving the cursor at the start of a clean line.\n *\n * Called before *every* write, because `\\r` returns to the start of whatever\n * line is current and half a streamed sentence is as much a casualty as a\n * status line. The ticker redraws on its next tick if work is still in\n * flight, so this costs nothing but a frame.\n */\n const clearSpinner = () => {\n if (!drawn) return;\n drawn = false;\n status(\"\\r\\x1b[K\");\n };\n\n const line = (text: string) => {\n clearSpinner();\n if (open) { sink.write(\"\\n\"); open = false; }\n status(`${label}${text}\\n`);\n };\n\n const stopTicker = () => {\n if (ticker) { clearInterval(ticker); ticker = undefined; }\n clearSpinner();\n };\n\n /**\n * What is running, in the width of one line.\n *\n * The oldest call names itself and carries the clock, because it is the one a\n * reader is waiting on; the rest are a count. Naming all four would be a\n * line that changes width every time one finishes.\n */\n const inFlight = (glyph: string): string => {\n const oldest = [...running].sort((a, b) => (clocks.get(a) ?? 0) - (clocks.get(b) ?? 0))[0];\n if (oldest === undefined) return \"\";\n const name = names.get(oldest) ?? oldest.slice(0, 8);\n const others = running.size - 1;\n return `${label}${glyph} ${name}${others ? ` +${others}` : \"\"} ${seconds(now() - (clocks.get(oldest) ?? now()))}`;\n };\n\n /**\n * The one piece of cursor control in this file, and the only reason a long\n * command is not silence. Unref'd so it can never hold a process open.\n *\n * It does not draw over an open line: `say` leaves the cursor mid-sentence\n * while text streams, and `\\r` there would eat the sentence. Nothing is lost\n * — the next tick after the newline draws it.\n */\n const startTicker = () => {\n if (ticker || !sink.tty) return;\n let frame = 0;\n ticker = setInterval(() => {\n if (open || !running.size) return;\n const text = inFlight(SPINNER[frame++ % SPINNER.length]!);\n if (!text) return;\n drawn = true;\n status(`\\r${DIM}${text}${RESET}\\x1b[K`);\n }, 90);\n ticker.unref?.();\n };\n\n /** Partial line held back while a labelled run streams, so the prefix stays whole. */\n let held = \"\";\n\n /**\n * Write text for the reader. The primitive; `say` is the streaming door to it.\n *\n * Only a delta counts as *streamed*. An entry printed through here must not\n * be added to `streamed`, or its own words become the \"already shown\" prefix\n * the next entry is measured against — and since a second turn's text does\n * not begin with a first turn's, `startsWith` failed and the whole turn was\n * printed again under the half that had already streamed.\n */\n const emit = (text: string) => {\n clearSpinner();\n if (thinking) { thinking = false; }\n if (!sink.label) {\n sink.write(text);\n open = !text.endsWith(\"\\n\");\n return;\n }\n // A prefix cannot be applied to half a line, so a labelled run buffers to\n // the newline. Nothing is lost: `finish` flushes whatever is left.\n held += text;\n let cut = held.indexOf(\"\\n\");\n while (cut !== -1) {\n line(held.slice(0, cut));\n held = held.slice(cut + 1);\n cut = held.indexOf(\"\\n\");\n }\n };\n\n /** A delta: written, and recorded as the part of the coming entry already shown. */\n const say = (text: string) => { streamed += text; emit(text); };\n\n const entry = (stored: Stored) => {\n if (stored.type === \"run.started\") {\n // Input with no `from` is what the caller just passed in. Echoing it says\n // everything twice. Input *with* one came from somewhere else — a\n // subagent's report, a peer, a person on a channel — and saying so is the\n // only way that arrival is visible as itself.\n if (stored.from) {\n line(dim(`◦ from ${stored.from.kind} ${stored.from.id.slice(0, 8)} · ${oneLine(readable(stored.input), 72)}`));\n }\n return;\n }\n if (stored.type === \"assistant\") {\n turns += 1;\n const said = readable(stored.content);\n if (said) {\n const shown = streamed;\n // Cleared first: `say` appends to it, and what matters is what had been\n // streamed *before* this entry arrived.\n streamed = \"\";\n if (!shown) emit(said.endsWith(\"\\n\") ? said : `${said}\\n`);\n else if (said.startsWith(shown)) {\n const rest = said.slice(shown.length);\n if (rest) emit(rest.endsWith(\"\\n\") ? rest : `${rest}\\n`);\n else if (open) emit(\"\\n\");\n } else {\n if (open) sink.write(\"\\n\");\n emit(said.endsWith(\"\\n\") ? said : `${said}\\n`);\n }\n } else {\n streamed = \"\";\n }\n for (const call of stored.calls ?? []) {\n // The name is recorded whatever the level: a result rendered later\n // reads it, and a reader who turns detail up mid-run should not meet a\n // call id where every other line has a name.\n names.set(call.callId, call.name);\n if (internal) line(dim(`→ ${call.name} ${oneLine(call.arguments, 72)}`));\n }\n return;\n }\n if (stored.type === \"tool.started\") {\n clocks.set(stored.callId, now());\n // At every level, unlike everything else about a call. A spinner is not\n // an account of what the agent did — it leaves no trace, and it is the\n // only thing between a reader and thirty seconds of silence.\n running.add(stored.callId);\n startTicker();\n return;\n }\n if (stored.type === \"tool.finished\") {\n running.delete(stored.callId);\n if (!running.size) stopTicker();\n const at = clocks.get(stored.callId);\n clocks.delete(stored.callId);\n const name = names.get(stored.callId) ?? stored.callId.slice(0, 8);\n const took = at === undefined ? \"\" : ` · ${seconds(now() - at)}`;\n const body = oneLine(readable(stored.result.content), 64);\n const failed = stored.result.isError === true;\n // A success is the agent working; a failure is something the reader has\n // to know about whatever they asked to be shown.\n if (failed || internal) {\n line(`${mark(failed ? \"✗\" : \"✓\", failed)} ${dim(`${name}${took}${body ? ` · ${body}` : \"\"}`)}`);\n }\n // `details` is the structured channel for an application's own UI and\n // holds whatever that application put there — which may include a\n // credential. Asked for explicitly it is shown; it is never volunteered.\n if (debugging && stored.result.details !== undefined) {\n line(dim(` ${oneLine(JSON.stringify(stored.result.details), 96)}`));\n }\n return;\n }\n if (stored.type === \"summary\") {\n if (internal) line(dim(`· compacted through seq ${stored.replaces}`));\n }\n // `run.finished` is not rendered here. `finish` owns the last line, because\n // `RunResult` carries what the entry cannot: what the run spent, on every\n // outcome including the ones with no answer.\n };\n\n return {\n update(next) {\n if (next.type === \"text.delta\") { say(next.text); return; }\n if (next.type === \"reasoning.delta\") {\n // Reasoning can outweigh the answer several times over, so it is behind\n // `\"detailed\"` rather than dimmed and always present.\n if (!debugging) return;\n if (!thinking) { line(dim(\"· thinking\")); thinking = true; }\n clearSpinner();\n status(dim(next.text));\n return;\n }\n // A harness that reports progress reports it several times per call, in\n // whatever shape its protocol happens to use — ACP forwards its whole\n // `session/update`. That is a debugging channel, not a reading one: the\n // call itself is announced by the entry that carries it, and the name is\n // not even known yet on the first of these. So it sits behind `\"detailed\"`\n // beside `tool-call.delta`, for the same reason.\n if (next.type === \"tool.progress\") {\n if (!debugging) return;\n const name = names.get(next.callId) ?? next.callId.slice(0, 8);\n line(dim(`⋯ ${name} ${oneLine(JSON.stringify(next.data), 64)}`));\n return;\n }\n // Arguments as they form are unparseable until complete and only one\n // harness emits them, so they are worth nothing to a reader and\n // everything to someone asking why a call came out the way it did.\n if (next.type === \"tool-call.delta\") {\n if (debugging) line(dim(` ${next.callId.slice(0, 8)} ${oneLine(next.arguments, 64)}`));\n return;\n }\n if (next.type === \"entry\") entry(next.entry);\n },\n\n finish(result) {\n running.clear();\n stopTicker();\n if (held) { line(held); held = \"\"; }\n if (open) { sink.write(\"\\n\"); open = false; }\n\n const spent = [\n result.usage.inputTokens !== undefined ? `${round(result.usage.inputTokens)} in` : undefined,\n result.usage.cacheReadTokens ? `${round(result.usage.cacheReadTokens)} cached` : undefined,\n result.usage.outputTokens !== undefined ? `${round(result.usage.outputTokens)} out` : undefined,\n ].filter((part): part is string => part !== undefined);\n\n // A count nobody reported is not a zero, so an absent one is left out\n // rather than printed as 0.\n const parts = [\n seconds(now() - started),\n `${turns} ${turns === 1 ? \"turn\" : \"turns\"}`,\n ...spent,\n ].join(\" · \");\n\n if (result.status === \"failed\") {\n line(`${mark(\"✗\", true)} ${dim(`failed (${result.error.code}): ${oneLine(result.error.message, 80)} · ${parts}`)}`);\n return;\n }\n // `cancelled` is an ending nobody asked for, so it is said at every\n // level that says anything. A clean completion is an accounting line.\n if (result.status === \"cancelled\" || internal) line(dim(`— ${result.status} · ${parts}`));\n },\n };\n}\n\n/**\n * Render a run to its end, and answer what it did.\n *\n * The loop every application writes by hand, with the two things a hand-written\n * one keeps getting wrong: everything the stream carries besides text, and an\n * outcome taken from the result rather than from whatever happened to stream.\n */\nexport async function renderRun(run: AgentRun, sink: Sink): Promise<RunResult> {\n const renderer = createRenderer(sink);\n for await (const update of run) renderer.update(update);\n const result = await run.result;\n renderer.finish(result);\n return result;\n}\n\n/** Re-exported so a caller composing a sink imports one thing. */\nexport type { Update, RunResult, Usage, ToolCall };\n"]}
@@ -1,5 +1,5 @@
1
1
  import { err, ok } from "../../result.js";
2
- const schema = `
2
+ const tables = `
3
3
  CREATE TABLE IF NOT EXISTS sessions (
4
4
  id TEXT PRIMARY KEY,
5
5
  agent_id TEXT NOT NULL,
@@ -25,6 +25,20 @@ const schema = `
25
25
  at TEXT NOT NULL,
26
26
  PRIMARY KEY (session_id, sender, delivery_id)
27
27
  );
28
+ `;
29
+ /**
30
+ * Columns added after a table had already shipped.
31
+ *
32
+ * `CREATE TABLE IF NOT EXISTS` is a no-op against a table that exists, so a
33
+ * column added later never appears in a database made by an older build — and
34
+ * the first index over it fails with a raw `SQLiteError` from inside `bun:sqlite`,
35
+ * which is no way to meet a store whose whole promise is that the log survives.
36
+ * Additive only: a column is added, nothing is dropped, rewritten or lost.
37
+ */
38
+ const added = [
39
+ { table: "sessions", column: "running_since", type: "TEXT" },
40
+ ];
41
+ const indexes = `
28
42
  CREATE INDEX IF NOT EXISTS sessions_by_key ON sessions (key, updated_at DESC, id DESC);
29
43
  CREATE INDEX IF NOT EXISTS sessions_runnable ON sessions (updated_at) WHERE pending <> '[]';
30
44
  DROP INDEX IF EXISTS sessions_stranded; -- sessions_interrupted under its former name
@@ -59,7 +73,16 @@ export function createSqliteStore(input) {
59
73
  const database = input.database;
60
74
  const claimMs = input.claimMs ?? DEFAULT_CLAIM_MS;
61
75
  const deliveryMemoryMs = input.deliveryMemoryMs ?? DEFAULT_DELIVERY_MEMORY_MS;
62
- database.exec(schema);
76
+ // Tables, then the columns an older build's tables lack, then the indexes —
77
+ // which is the only order that works, because an index may be over a column
78
+ // the migration is about to add.
79
+ database.exec(tables);
80
+ for (const { table, column, type } of added) {
81
+ const present = database.query(`SELECT 1 FROM pragma_table_info(?) WHERE name = ?`).all(table, column);
82
+ if (!present.length)
83
+ database.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${type}`);
84
+ }
85
+ database.exec(indexes);
63
86
  const one = (sql, parameters) => database.query(sql).all(...parameters)[0];
64
87
  const run = (sql, parameters) => { database.query(sql).run(...parameters); };
65
88
  const notFound = (sessionId) => ({ code: "not-found", message: `No session ${sessionId}`, retryable: false });