@wraith-ai/core 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.
Files changed (153) hide show
  1. package/README.md +1 -1
  2. package/dist/{attempt-BeB7EltG.d.mts → attempt-HgararU3.d.mts} +2 -1
  3. package/dist/attempt-HgararU3.d.mts.map +1 -0
  4. package/dist/{capabilities-BPb5HSH6.d.mts → capabilities-CNsPrkB7.d.mts} +2 -1
  5. package/dist/capabilities-CNsPrkB7.d.mts.map +1 -0
  6. package/dist/index.d.mts +6 -5
  7. package/dist/index.d.mts.map +1 -0
  8. package/dist/index.mjs +11 -9
  9. package/dist/index.mjs.map +1 -0
  10. package/dist/{methods-CZp6XGn8.mjs → methods-7Ryz6zbd.mjs} +4 -2
  11. package/dist/methods-7Ryz6zbd.mjs.map +1 -0
  12. package/dist/{model-B6tJ9kX_.mjs → model-C16NUwXW.mjs} +2 -0
  13. package/dist/model-C16NUwXW.mjs.map +1 -0
  14. package/dist/{model-D6LQSveS.d.mts → model-_wqePNTL.d.mts} +4 -3
  15. package/dist/model-_wqePNTL.d.mts.map +1 -0
  16. package/dist/{models-dev-Y0ZikMBQ.d.mts → models-dev-DNgymZy3.d.mts} +3 -2
  17. package/dist/models-dev-DNgymZy3.d.mts.map +1 -0
  18. package/dist/{openai-codex-BhtZvNpm.mjs → openai-codex-Bz1EFPEi.mjs} +3 -1
  19. package/dist/openai-codex-Bz1EFPEi.mjs.map +1 -0
  20. package/dist/{openai-codex-Bk-iG7MZ.mjs → openai-codex-uvjhVoVy.mjs} +6 -4
  21. package/dist/openai-codex-uvjhVoVy.mjs.map +1 -0
  22. package/dist/{openai-compatible-hkXv-P74.mjs → openai-compatible-DBppnQ_N.mjs} +4 -2
  23. package/dist/openai-compatible-DBppnQ_N.mjs.map +1 -0
  24. package/dist/{openrouter-BflQBug2.mjs → openrouter-D8nTOAQo.mjs} +5 -3
  25. package/dist/openrouter-D8nTOAQo.mjs.map +1 -0
  26. package/dist/providers/openai-codex.d.mts +4 -3
  27. package/dist/providers/openai-codex.d.mts.map +1 -0
  28. package/dist/providers/openai-codex.mjs +1 -1
  29. package/dist/providers/openai-compatible.d.mts +3 -2
  30. package/dist/providers/openai-compatible.d.mts.map +1 -0
  31. package/dist/providers/openai-compatible.mjs +1 -1
  32. package/dist/providers/openrouter.d.mts +3 -2
  33. package/dist/providers/openrouter.d.mts.map +1 -0
  34. package/dist/providers/openrouter.mjs +1 -1
  35. package/dist/{shared-8d7RsyPH.mjs → shared-BIJaPhMm.mjs} +3 -1
  36. package/dist/shared-BIJaPhMm.mjs.map +1 -0
  37. package/dist/snapshot.d.mts +3 -2
  38. package/dist/snapshot.d.mts.map +1 -0
  39. package/dist/snapshot.mjs +4999 -4977
  40. package/dist/snapshot.mjs.map +1 -0
  41. package/dist/{turn-effort-DquDDwdE.mjs → turn-effort-C61L4JIt.mjs} +2 -0
  42. package/dist/turn-effort-C61L4JIt.mjs.map +1 -0
  43. package/package.json +3 -2
  44. package/src/agent/agent.ts +90 -0
  45. package/src/agent/attachments.ts +195 -0
  46. package/src/agent/classifier.ts +525 -0
  47. package/src/agent/compact.ts +384 -0
  48. package/src/agent/conversation.ts +300 -0
  49. package/src/agent/cost.ts +164 -0
  50. package/src/agent/inbox.ts +80 -0
  51. package/src/agent/instructions.ts +62 -0
  52. package/src/agent/loop.ts +675 -0
  53. package/src/agent/messages.ts +252 -0
  54. package/src/agent/on-demand.ts +58 -0
  55. package/src/agent/prompts.ts +35 -0
  56. package/src/agent/request-images.ts +94 -0
  57. package/src/agent/stop.ts +37 -0
  58. package/src/agent/title.ts +122 -0
  59. package/src/agent/tool-groups.ts +186 -0
  60. package/src/agent/tools.ts +106 -0
  61. package/src/app.ts +67 -0
  62. package/src/config/credential-file-store.ts +66 -0
  63. package/src/config/environment.ts +105 -0
  64. package/src/config/instructions.ts +157 -0
  65. package/src/config/load.ts +667 -0
  66. package/src/config/locked-file.ts +85 -0
  67. package/src/config/paths.ts +368 -0
  68. package/src/config/schema.ts +363 -0
  69. package/src/config/subagents.ts +156 -0
  70. package/src/config/trust.ts +53 -0
  71. package/src/config/write.ts +241 -0
  72. package/src/errors.ts +85 -0
  73. package/src/events/types.ts +258 -0
  74. package/src/glob.ts +161 -0
  75. package/src/index.ts +681 -0
  76. package/src/logger.ts +47 -0
  77. package/src/paths.ts +143 -0
  78. package/src/permissions/chain.ts +42 -0
  79. package/src/permissions/command.ts +233 -0
  80. package/src/permissions/layered.ts +77 -0
  81. package/src/permissions/match.ts +80 -0
  82. package/src/permissions/modes.ts +48 -0
  83. package/src/permissions/policy.ts +160 -0
  84. package/src/permissions/types.ts +159 -0
  85. package/src/providers/cache.ts +107 -0
  86. package/src/providers/capabilities.ts +77 -0
  87. package/src/providers/catalog-view.ts +91 -0
  88. package/src/providers/catalog.ts +65 -0
  89. package/src/providers/errors.ts +108 -0
  90. package/src/providers/factories/index.ts +15 -0
  91. package/src/providers/factories/openai-codex.ts +382 -0
  92. package/src/providers/factories/openai-compatible.ts +81 -0
  93. package/src/providers/factories/openrouter.ts +165 -0
  94. package/src/providers/factories/shared.ts +22 -0
  95. package/src/providers/model.ts +197 -0
  96. package/src/providers/models-dev.ts +355 -0
  97. package/src/providers/oauth/methods.ts +10 -0
  98. package/src/providers/oauth/openai-codex.ts +228 -0
  99. package/src/providers/oauth.ts +177 -0
  100. package/src/providers/openai-codex.ts +7 -0
  101. package/src/providers/openai-compatible.ts +2 -0
  102. package/src/providers/openrouter.ts +2 -0
  103. package/src/providers/registry.ts +464 -0
  104. package/src/providers/turn-effort.ts +156 -0
  105. package/src/providers/types.ts +83 -0
  106. package/src/session/backend.ts +44 -0
  107. package/src/session/file-store.ts +278 -0
  108. package/src/session/format.ts +1037 -0
  109. package/src/session/memory-store.ts +73 -0
  110. package/src/session/session.ts +153 -0
  111. package/src/session/store.ts +219 -0
  112. package/src/sign-in/attempt.ts +166 -0
  113. package/src/sign-in/loopback.ts +74 -0
  114. package/src/snapshot/data.json +8936 -0
  115. package/src/snapshot/index.ts +37 -0
  116. package/src/tools/bin.ts +364 -0
  117. package/src/tools/builtin.ts +48 -0
  118. package/src/tools/change.ts +88 -0
  119. package/src/tools/define.ts +267 -0
  120. package/src/tools/describe.ts +96 -0
  121. package/src/tools/fs/edit-file.ts +129 -0
  122. package/src/tools/fs/glob.ts +75 -0
  123. package/src/tools/fs/grep.ts +212 -0
  124. package/src/tools/fs/line-endings.ts +17 -0
  125. package/src/tools/fs/list-dir.ts +85 -0
  126. package/src/tools/fs/read-file.ts +230 -0
  127. package/src/tools/fs/ripgrep.ts +211 -0
  128. package/src/tools/fs/write-file.ts +97 -0
  129. package/src/tools/job.ts +252 -0
  130. package/src/tools/mcp/auth-store.ts +127 -0
  131. package/src/tools/mcp/command.ts +151 -0
  132. package/src/tools/mcp/config.ts +168 -0
  133. package/src/tools/mcp/servers.ts +463 -0
  134. package/src/tools/mcp/sign-in.ts +226 -0
  135. package/src/tools/mcp/stdio.ts +204 -0
  136. package/src/tools/mcp/tools.ts +173 -0
  137. package/src/tools/on-demand.ts +184 -0
  138. package/src/tools/registry.ts +935 -0
  139. package/src/tools/shell/bash.ts +217 -0
  140. package/src/tools/shell/find-bash.ts +162 -0
  141. package/src/tools/source.ts +35 -0
  142. package/src/tools/spill.ts +127 -0
  143. package/src/tools/subagents.ts +597 -0
  144. package/src/tools/tasks.ts +603 -0
  145. package/src/tools/to-model.ts +33 -0
  146. package/src/tools/web/address.ts +95 -0
  147. package/src/tools/web/exa.ts +163 -0
  148. package/src/tools/web/fetch.ts +373 -0
  149. package/src/tools/web/html.ts +173 -0
  150. package/src/tools/web/search.ts +111 -0
  151. package/src/tools/web/source.ts +51 -0
  152. package/src/units.ts +18 -0
  153. package/src/version.ts +23 -0
@@ -0,0 +1,675 @@
1
+ import { type ModelMessage, streamText } from "ai";
2
+ import {
3
+ type AgentEvent,
4
+ type AgentEventPayload,
5
+ type FinishReason,
6
+ type Usage,
7
+ addUsage,
8
+ normaliseUsage,
9
+ } from "../events/types";
10
+ import { AgentError, type SerializedError, serializeError } from "../errors";
11
+ import { withRequestFields } from "../providers/cache";
12
+ import { mapProviderError } from "../providers/errors";
13
+ import { explicitEffort, stampEffort } from "../providers/turn-effort";
14
+ import { messageOf, usageOwed, type SessionRecordInput } from "../session/format";
15
+ import type { Session } from "../session/session";
16
+ import type { Agent } from "./agent";
17
+ import type { Prompt } from "./attachments";
18
+ import { imagesForModel } from "./request-images";
19
+ import { applyCompaction, type CompactionResult } from "./compact";
20
+ import { priceCall, routedProvider } from "./cost";
21
+ import type { Inbox, InboxRecord } from "./inbox";
22
+ import {
23
+ hostMessage,
24
+ toolResultMessage,
25
+ unansweredCalls,
26
+ userMessage,
27
+ withoutResultsFor,
28
+ } from "./messages";
29
+ import { instructionsMessage, lastInstructions } from "./instructions";
30
+ import { lastOnDemandNotice, onDemandNotice } from "./on-demand";
31
+ import { drainAll, planGroups } from "./tool-groups";
32
+ import type { ToolCall, ToolOutcome } from "./tools";
33
+
34
+ /**
35
+ * Our tool loop. Tools go to the model without an `execute` function, so the
36
+ * SDK validates the arguments and hands each call back without running it;
37
+ * this loop decides what runs.
38
+ *
39
+ * On abort, `fullStream` emits an `abort` part and ends instead of throwing,
40
+ * while `response`, `toolCalls` and `usage` reject with AbortError. That is why
41
+ * the abort check comes before anything is awaited.
42
+ */
43
+
44
+ export interface RunInput {
45
+ session: Session;
46
+ /** Absent: the run starts from what is waiting in the inbox. */
47
+ prompt?: Prompt;
48
+ }
49
+
50
+ export interface RunDeps {
51
+ signal?: AbortSignal;
52
+ /** Set by a sub-agent so its events can be told apart. */
53
+ parentRunId?: string;
54
+ /** Emptied before every model call. Absent: nothing enters from outside. */
55
+ inbox?: Inbox;
56
+ }
57
+
58
+ /**
59
+ * How a run ended. What it added to the session went out as `record` events,
60
+ * and nothing here repeats it: a second copy is one a host can write twice.
61
+ */
62
+ export interface RunResult {
63
+ runId: string;
64
+ /** The run's total, also of a run that ended without `run-finish`. */
65
+ usage: Usage;
66
+ reason: FinishReason;
67
+ }
68
+
69
+ /**
70
+ * Each record leaves as a `record` event before the loop's next event, `run-start`
71
+ * excepted, so a host that writes them as they come loses at most one event's worth.
72
+ */
73
+ export async function* run(
74
+ agent: Agent,
75
+ input: RunInput,
76
+ deps: RunDeps = {},
77
+ ): AsyncGenerator<AgentEvent, RunResult> {
78
+ // Ours, because only its owner may abort the host's signal, which may outlive this run.
79
+ const stop = new AbortController();
80
+ const signal = deps.signal === undefined ? stop.signal : AbortSignal.any([deps.signal, stop.signal]);
81
+ const held: AgentEvent[] = [];
82
+ const steps = loop(agent, input, { ...deps, signal }, (event) => held.push(event));
83
+ let ended = false;
84
+ try {
85
+ let next = await steps.next();
86
+ while (next.done !== true) {
87
+ // Nothing goes before `run-start`: a script takes the session's id from the first line.
88
+ if (next.value.type !== "run-start") yield* held.splice(0);
89
+ yield next.value;
90
+ next = await steps.next();
91
+ }
92
+ yield* held.splice(0);
93
+ ended = true;
94
+ return next.value;
95
+ } finally {
96
+ // A host that stops reading gets nothing more, so nothing goes on without it: the
97
+ // model's request is aborted and the tools still running are told to stop.
98
+ if (!ended) stop.abort();
99
+ // Closed as `yield*` would close it, rather than left suspended mid-step.
100
+ await steps.return(undefined as never);
101
+ }
102
+ }
103
+
104
+ /**
105
+ * `hold` takes the record events: `keep` is called from callbacks that cannot
106
+ * yield, so `run()` sends them out at the loop's next yield.
107
+ */
108
+ async function* loop(
109
+ agent: Agent,
110
+ input: RunInput,
111
+ deps: RunDeps & { signal: AbortSignal },
112
+ hold: (event: AgentEvent) => void,
113
+ ): AsyncGenerator<AgentEvent, RunResult> {
114
+ const runId = agent.newId("run");
115
+ const parentRunId = deps.parentRunId ?? null;
116
+ const { signal } = deps;
117
+ const startedAt = agent.now();
118
+
119
+ const event = (payload: AgentEventPayload): AgentEvent =>
120
+ ({ runId, parentRunId, ts: agent.now(), ...payload }) as AgentEvent;
121
+
122
+ let messages: ModelMessage[] = [...input.session.messages];
123
+
124
+ // Dated when made, and the event carries the same reading, so a replay shows these times.
125
+ const keep = <T extends SessionRecordInput>(record: T): T => {
126
+ const dated = { ...record, ts: agent.now() };
127
+ hold({ runId, parentRunId, ts: dated.ts, type: "record", record: dated });
128
+ return dated;
129
+ };
130
+
131
+ // Which model wrote which turn, written only when it changes. A model change
132
+ // is also when the prompt cache resets.
133
+ const identity = modelIdentity(agent);
134
+ const modelChanged = identityChanged(input.session.meta, identity);
135
+ if (modelChanged) {
136
+ keep({ type: "meta", meta: identity });
137
+ }
138
+
139
+ // Beside the identity, not in it: an identity change sends a fresh system
140
+ // prompt, and an effort change there would break the cache. Null rather than
141
+ // absent, for the key-by-key merge.
142
+ const effort = explicitEffort(agent.model.settings.reasoning);
143
+ if ((input.session.meta.reasoning ?? null) !== (effort ?? null)) {
144
+ keep({ type: "meta", meta: { reasoning: effort ?? null } });
145
+ }
146
+
147
+ // Reuses the prompt this session was last sent with, not the one the host
148
+ // just built: one character of difference loses the cache for the whole
149
+ // history. A fresh one enters only where the cache is lost anyway: another
150
+ // model, or a compaction.
151
+ let system =
152
+ modelChanged || input.session.system === undefined ? agent.system : input.session.system;
153
+ const useSystem = (next: string | undefined): void => {
154
+ system = next;
155
+ if (next !== undefined) keep({ type: "system", text: next });
156
+ };
157
+ if (system !== input.session.system) useSystem(system);
158
+
159
+ let usage: Usage = {};
160
+ const addUsageRecord = (delta: Usage): void => {
161
+ usage = addUsage(usage, delta);
162
+ keep({ type: "usage", usage: delta });
163
+ };
164
+
165
+ // Kept at once, so what was taken survives every way out of the run.
166
+ const takeInbox = async (): Promise<AgentEvent[]> => {
167
+ let taken: InboxRecord[] = [];
168
+ try {
169
+ taken = (await deps.inbox?.take()) ?? [];
170
+ } catch (error) {
171
+ // Thrown out of run(), this would lose every record of the turn.
172
+ agent.logger.warn("inbox failed, continuing without it", { error: String(error) });
173
+ }
174
+
175
+ const delivered: AgentEvent[] = [];
176
+ for (const record of taken) {
177
+ // The type forbids it; a host written in JavaScript can still send one.
178
+ if (record.type === "message" && (record.message as ModelMessage).role !== "user") {
179
+ agent.logger.warn("inbox message skipped: only a user message may enter");
180
+ continue;
181
+ }
182
+ const message = messageOf(record);
183
+ if (message !== undefined) messages = [...messages, message];
184
+ delivered.push(event({ type: "delivery", record: keep(record) }));
185
+ // A task that ran models of its own, as an agent does, is billed where its ending is heard.
186
+ for (const owed of usageOwed([record])) addUsageRecord(owed.usage);
187
+ }
188
+ return delivered;
189
+ };
190
+
191
+ // Compared with the history, not with a variable: after `/model`, a resume or
192
+ // a compaction, the history is what the model was last told.
193
+ const announceOnDemand = async (): Promise<AgentEvent[]> => {
194
+ if (agent.tools.onDemandTools === undefined) return [];
195
+ let names: readonly string[];
196
+ try {
197
+ names = await agent.tools.onDemandTools();
198
+ } catch (error) {
199
+ agent.logger.warn("on-demand tools could not be listed", { error: String(error) });
200
+ return [];
201
+ }
202
+ const notice = onDemandNotice(names);
203
+ const last = lastOnDemandNotice(messages);
204
+ if (last === undefined ? names.length === 0 : last === notice) return [];
205
+
206
+ const record: InboxRecord = { type: "message", message: hostMessage(notice) };
207
+ messages = [...messages, record.message];
208
+ return [event({ type: "delivery", record: keep(record) })];
209
+ };
210
+
211
+ // Compared with the history, like the notice above: a compaction that drops
212
+ // them sends them again, and a changed file sends the new text.
213
+ const announceInstructions = (): AgentEvent[] => {
214
+ if (agent.instructions === undefined || agent.instructions === "") return [];
215
+ const last = lastInstructions(messages);
216
+ if (last === agent.instructions) return [];
217
+ const record: InboxRecord = {
218
+ type: "message",
219
+ message: instructionsMessage(agent.instructions, last !== undefined),
220
+ };
221
+ messages = [...messages, record.message];
222
+ return [event({ type: "delivery", record: keep(record) })];
223
+ };
224
+
225
+ // A run that stopped between a step and its tools left calls without results,
226
+ // and every provider rejects that history. They are answered before anything new enters.
227
+ const unanswered = unansweredCalls(messages);
228
+ if (unanswered.length > 0) {
229
+ agent.logger.warn("answering tool calls an earlier run left without results", {
230
+ calls: unanswered.length,
231
+ });
232
+ const answers = toolResultMessage(unanswered.map(interrupted));
233
+ messages = [...messages, answers];
234
+ keep({ type: "message", message: answers });
235
+ }
236
+
237
+ // Before the prompt, so the model reads them first, as context for what it is asked.
238
+ const instructed = announceInstructions();
239
+ if (input.prompt !== undefined) {
240
+ const prompt = userMessage(input.prompt);
241
+ messages = [...messages, prompt];
242
+ keep({ type: "message", message: prompt });
243
+ }
244
+ // What waits takes the prompt's place. Having neither is the host's mistake,
245
+ // raised before any event, so nothing reaches a log.
246
+ const opening = input.prompt === undefined ? await takeInbox() : [];
247
+ if (input.prompt === undefined && opening.length === 0) {
248
+ throw new AgentError(
249
+ "run/nothing-to-run",
250
+ "A run needs a prompt or something waiting in its inbox.",
251
+ );
252
+ }
253
+
254
+ let lastInputTokens: number | undefined;
255
+ let lastRoutedProvider = typeof input.session.meta.routedProvider === "string"
256
+ ? input.session.meta.routedProvider
257
+ : undefined;
258
+ let text = "";
259
+
260
+ // Recorded so a resumed conversation can end each turn the way the live one did.
261
+ const finish = (
262
+ reason: FinishReason,
263
+ error?: SerializedError,
264
+ durationMs = agent.now() - startedAt,
265
+ ): RunResult => {
266
+ keep({ type: "finish", reason, durationMs, ...(error === undefined ? {} : { error }) });
267
+ return { runId, usage, reason };
268
+ };
269
+
270
+ // One reading of the clock for the event and the record, so the live line and a replay agree.
271
+ // The record goes before the event, so a host that stops reading at `run-finish` has it.
272
+ const close = function* (reason: FinishReason): Generator<AgentEvent, RunResult> {
273
+ const durationMs = agent.now() - startedAt;
274
+ const result = finish(reason, undefined, durationMs);
275
+ yield event({ type: "run-finish", reason, usage, text, durationMs });
276
+ return result;
277
+ };
278
+
279
+ yield event({
280
+ type: "run-start",
281
+ sessionId: input.session.id,
282
+ model: agent.model.modelId,
283
+ provider: agent.model.providerName,
284
+ // Only when known: a front end without it draws no context meter at all,
285
+ // rather than a bar against a window somebody guessed.
286
+ ...(agent.contextLimit === undefined ? {} : { contextLimit: agent.contextLimit }),
287
+ });
288
+ yield* instructed;
289
+ yield* opening;
290
+
291
+ for (let step = 0; step < agent.maxSteps; step += 1) {
292
+ yield event({ type: "step-start", step });
293
+ // `run-finish` carries the last answer alone, not every step's text glued together.
294
+ text = "";
295
+
296
+ // Before the request, never after a context-length error: recovering from
297
+ // one costs a wasted round trip at the least convenient moment.
298
+ if (agent.compactor !== undefined) {
299
+ let markStarted = (): void => {};
300
+ const started = new Promise<"started">((resolve) => {
301
+ markStarted = () => resolve("started");
302
+ });
303
+ const compacting = agent.compactor.maybeCompact({
304
+ messages,
305
+ ...(lastInputTokens === undefined ? {} : { lastInputTokens }),
306
+ signal,
307
+ onStart: markStarted,
308
+ cacheKey: input.session.id,
309
+ });
310
+
311
+ // A generator cannot yield while it awaits, so the start races the result;
312
+ // nearly every step ends with a null and no event at all.
313
+ const first = await Promise.race([started, compacting.then(() => "done", () => "done")]);
314
+ const announced = first === "started";
315
+ if (announced) yield event({ type: "compaction-start" });
316
+
317
+ let compacted: CompactionResult | null = null;
318
+ let failure: SerializedError | undefined;
319
+ try {
320
+ compacted = await compacting;
321
+ } catch (error) {
322
+ // Thrown out of run(), this lost every record of the turn, including
323
+ // tool calls that had already changed files.
324
+ if (signal.aborted) {
325
+ const cancelled = serializeError(new AgentError("run/aborted", "The run was cancelled."));
326
+ yield event({ type: "compaction-failed", error: cancelled });
327
+ yield event({ type: "error", error: cancelled });
328
+ return finish("aborted", cancelled);
329
+ }
330
+ agent.logger.warn("compaction failed, continuing without it", { error: String(error) });
331
+ failure = serializeError(error);
332
+ }
333
+
334
+ // Every start gets an end, so a front end's "compacting…" always goes away.
335
+ if (failure === undefined && announced && compacted === null) {
336
+ failure = serializeError(new Error("The summary came back empty."));
337
+ }
338
+ if (failure !== undefined) yield event({ type: "compaction-failed", error: failure });
339
+
340
+ if (compacted !== null) {
341
+ // Rebuilt here rather than taken from the compactor, so the live
342
+ // history and the one a reload projects are the same by construction.
343
+ messages = applyCompaction(messages, compacted);
344
+ keep({
345
+ type: "compaction",
346
+ summary: compacted.summary,
347
+ keptMessages: compacted.keptMessages,
348
+ droppedMessages: compacted.droppedMessages,
349
+ tokensBefore: compacted.tokensBefore,
350
+ tokensAfter: compacted.tokensAfter,
351
+ });
352
+ addUsageRecord(compacted.usage);
353
+ // The history was just rewritten, so the cache is lost either way and a
354
+ // frozen prompt has nothing left to protect.
355
+ if (agent.system !== undefined && agent.system !== system) useSystem(agent.system);
356
+ yield event({
357
+ type: "compaction",
358
+ summary: compacted.summary,
359
+ droppedMessages: compacted.droppedMessages,
360
+ tokensBefore: compacted.tokensBefore,
361
+ tokensAfter: compacted.tokensAfter,
362
+ });
363
+ }
364
+ }
365
+
366
+ // Here and nowhere else: every tool call has its result by now, and a
367
+ // compaction has already counted the messages it replaced.
368
+ yield* await takeInbox();
369
+ yield* announceInstructions();
370
+ yield* await announceOnDemand();
371
+
372
+ // The SDK's overloads are keyed on the shape of `tools`, so the options are
373
+ // built once and cast here, leaving the rest of the file free of SDK type
374
+ // workarounds.
375
+ const callOptions = {
376
+ model: agent.model.languageModel,
377
+ ...(system === undefined ? {} : { system }),
378
+ // Only the request: the log keeps one form whatever the vendor, so a switch of model breaks nothing.
379
+ messages: imagesForModel(messages, agent.model),
380
+ tools: agent.tools.modelTools,
381
+ abortSignal: signal,
382
+ // The error is read off the stream below; the SDK's default prints it.
383
+ onError: () => {},
384
+ // The session is the routing key, so one agent can serve many sessions.
385
+ ...withRequestFields(agent.model.settings, agent.model.requestFields(input.session.id)),
386
+ } as Parameters<typeof streamText>[0];
387
+
388
+ const result = streamText(callOptions);
389
+
390
+ let aborted = false;
391
+ let streamError: unknown;
392
+ /**
393
+ * The one part carrying both tokens and provider bookkeeping, so the bill
394
+ * is read here. It replaces `await result.usage` rather than joining it:
395
+ * two sources for one number agree until the stream is interrupted.
396
+ */
397
+ let stepUsage: Usage = {};
398
+ let stepMetadata: unknown;
399
+ /**
400
+ * The vendor's own usage block, kept beside the normalised counters. Only
401
+ * here does `is_byok` survive; without that flag, OpenRouter's
402
+ * `upstream_inference_cost` cannot be told apart from the same money
403
+ * reported twice.
404
+ */
405
+ let stepProviderUsage: unknown;
406
+
407
+ // The SDK's ids name a part only within one request; outside the loop a part is (step, index).
408
+ let nextPart = 0;
409
+ const texts = new Map<string, { index: number; text: string }>();
410
+ const reasonings = new Map<string, { index: number; text: string }>();
411
+
412
+ try {
413
+ for await (const part of result.fullStream) {
414
+ switch (part.type) {
415
+ // The SDK sends it with the first chunk after the stream opens, not with the headers.
416
+ case "start-step":
417
+ yield event({ type: "response-start", step });
418
+ break;
419
+ case "finish-step":
420
+ stepUsage = normaliseUsage(part.usage);
421
+ stepProviderUsage = (part.usage as { raw?: unknown }).raw;
422
+ stepMetadata = part.providerMetadata;
423
+ break;
424
+ case "text-start": {
425
+ const index = nextPart++;
426
+ texts.set(part.id, { index, text: "" });
427
+ yield event({ type: "text-start", step, index });
428
+ break;
429
+ }
430
+ case "text-delta": {
431
+ const open = texts.get(part.id);
432
+ // The SDK answers a delta with no start with an error part, which ends the run.
433
+ if (open === undefined) break;
434
+ open.text += part.text;
435
+ text += part.text;
436
+ yield event({ type: "text-delta", step, index: open.index, text: part.text });
437
+ break;
438
+ }
439
+ case "text-end": {
440
+ const open = texts.get(part.id);
441
+ if (open === undefined) break;
442
+ texts.delete(part.id);
443
+ yield event({ type: "text-end", step, index: open.index, text: open.text });
444
+ break;
445
+ }
446
+ case "reasoning-start": {
447
+ const index = nextPart++;
448
+ reasonings.set(part.id, { index, text: "" });
449
+ yield event({ type: "reasoning-start", step, index });
450
+ break;
451
+ }
452
+ case "reasoning-delta": {
453
+ const open = reasonings.get(part.id);
454
+ if (open === undefined) break;
455
+ open.text += part.text;
456
+ yield event({ type: "reasoning-delta", step, index: open.index, text: part.text });
457
+ break;
458
+ }
459
+ case "reasoning-end": {
460
+ const open = reasonings.get(part.id);
461
+ if (open === undefined) break;
462
+ reasonings.delete(part.id);
463
+ yield event({ type: "reasoning-end", step, index: open.index, text: open.text });
464
+ break;
465
+ }
466
+ case "tool-input-start":
467
+ yield event({ type: "tool-input-start", toolCallId: part.id, toolName: part.toolName });
468
+ break;
469
+ case "tool-call":
470
+ yield event({
471
+ type: "tool-call",
472
+ toolCallId: part.toolCallId,
473
+ toolName: part.toolName,
474
+ input: part.input,
475
+ });
476
+ break;
477
+ case "abort":
478
+ aborted = true;
479
+ break;
480
+ case "error":
481
+ streamError = part.error;
482
+ break;
483
+ default:
484
+ break;
485
+ }
486
+ }
487
+ } catch (error) {
488
+ streamError = error;
489
+ }
490
+
491
+ // Every start gets its end, also when the stream broke off inside a part.
492
+ for (const open of texts.values()) {
493
+ yield event({ type: "text-end", step, index: open.index, text: open.text });
494
+ }
495
+ for (const open of reasonings.values()) {
496
+ yield event({ type: "reasoning-end", step, index: open.index, text: open.text });
497
+ }
498
+
499
+ if (aborted) {
500
+ const error = serializeError(new AgentError("run/aborted", "The run was cancelled."));
501
+ yield event({ type: "error", error });
502
+ return finish("aborted", error);
503
+ }
504
+
505
+ if (streamError !== undefined) {
506
+ const mapped = mapProviderError(streamError, {
507
+ providerName: agent.model.providerName,
508
+ modelId: agent.model.modelId,
509
+ });
510
+ const error = serializeError(mapped);
511
+ yield event({ type: "error", error });
512
+ return finish("error", error);
513
+ }
514
+
515
+ const priced = priceCall(stepUsage, agent.pricing, {
516
+ providerUsage: stepProviderUsage,
517
+ metadata: stepMetadata,
518
+ });
519
+ lastInputTokens = priced.inputTokens;
520
+ addUsageRecord(priced);
521
+
522
+ // Which upstream OpenRouter routed to, recorded only when it changes, as
523
+ // the model is. Sticky routing can send a turn to an upstream without the
524
+ // prefix, which a bare `cacheReadTokens: 0` does not show.
525
+ const routed = routedProvider(stepMetadata);
526
+ if (routed !== undefined && routed !== lastRoutedProvider) {
527
+ lastRoutedProvider = routed;
528
+ keep({ type: "meta", meta: { routedProvider: routed } });
529
+ }
530
+
531
+ // The SDK's tool-call object carries provider bookkeeping we do not want
532
+ // crossing into the ToolRunner port, so it is narrowed to our own shape.
533
+ const calls: ToolCall[] = (await result.toolCalls).map((call) => ({
534
+ toolCallId: call.toolCallId,
535
+ toolName: call.toolName,
536
+ input: call.input,
537
+ }));
538
+
539
+ // Each answer carries the effort it was produced at, so a factory can place
540
+ // later changes without touching the prefix.
541
+ const responseMessages = withoutResultsFor(
542
+ (await result.response).messages,
543
+ new Set(calls.map((call) => call.toolCallId)),
544
+ ).map((message) => stampEffort(message, effort));
545
+ messages = [...messages, ...responseMessages];
546
+ for (const message of responseMessages) keep({ type: "message", message });
547
+ // `usage` stays the running total: consumers already read it, and its
548
+ // meaning must not change quietly. `stepUsage` is the per-step figure, so
549
+ // no front end derives it from two totals, where front ends could disagree.
550
+ yield event({ type: "step-finish", step, usage, stepUsage: priced });
551
+
552
+ if (calls.length === 0) {
553
+ return yield* close(toFinishReason(await result.finishReason));
554
+ }
555
+
556
+ /**
557
+ * Records an approval in the session. A verdict that reaches only the
558
+ * stream dies with the process, leaving the call without its decision, so
559
+ * both routes out of the runner come through here, and the record is
560
+ * written once whichever one a runner uses.
561
+ */
562
+ const noteApproval = (call: ToolCall, payload: AgentEventPayload): void => {
563
+ if (payload.type !== "tool-approval-resolved") return;
564
+ const record: SessionRecordInput = {
565
+ type: "approval",
566
+ toolCallId: call.toolCallId,
567
+ toolName: call.toolName,
568
+ decision: payload.decision,
569
+ decidedBy: payload.decidedBy,
570
+ };
571
+ if (payload.reason !== undefined) record.reason = payload.reason;
572
+ if (payload.usage !== undefined) record.usage = payload.usage;
573
+ keep(record);
574
+
575
+ // A classifier answers on a model of its own, outside this loop, so this
576
+ // is the only door its tokens have into the session's bill. Compaction's
577
+ // spending comes through the same door.
578
+ if (payload.usage !== undefined) addUsageRecord(payload.usage);
579
+ };
580
+
581
+ // Allowed reads run side by side; anything else runs alone as a barrier.
582
+ const outcomes: ToolOutcome[] = [];
583
+ for (const group of planGroups(calls, agent.tools)) {
584
+ const settled = yield* drainAll(group, {
585
+ start: (call, emit) =>
586
+ // `messages` already carries this step's assistant message, so an
587
+ // approval handler that judges intent sees the call it is judging.
588
+ agent.tools.execute(call, {
589
+ signal,
590
+ sessionId: input.session.id,
591
+ runId,
592
+ emit,
593
+ messages,
594
+ }),
595
+ event,
596
+ note: noteApproval,
597
+ signal,
598
+ });
599
+ outcomes.push(...settled);
600
+ }
601
+
602
+ // Beside the result, never in it: the model gets `output` alone.
603
+ for (const outcome of outcomes) {
604
+ if (outcome.change !== undefined) {
605
+ keep({ type: "change", toolCallId: outcome.toolCallId, change: outcome.change });
606
+ }
607
+ // What a call spent on models of its own, when it ended before it became a task.
608
+ if (outcome.usage !== undefined) addUsageRecord(outcome.usage);
609
+ }
610
+
611
+ const resultMessage = toolResultMessage(outcomes);
612
+ messages = [...messages, resultMessage];
613
+ keep({ type: "message", message: resultMessage });
614
+
615
+ const state = {
616
+ step: step + 1,
617
+ toolCalls: calls.map((call) => call.toolName),
618
+ usage,
619
+ };
620
+ if (agent.stopWhen(state)) return yield* close("max-steps");
621
+ }
622
+
623
+ return yield* close("max-steps");
624
+ }
625
+
626
+ /**
627
+ * The same three fields `run-start` carries, in the shape the log stores.
628
+ *
629
+ * `profile` is written as null rather than omitted: a projection merges meta
630
+ * records key by key, so a missing key would leave the previous run's profile
631
+ * next to the new model.
632
+ */
633
+ function modelIdentity(agent: Agent): Record<string, unknown> {
634
+ return {
635
+ model: agent.model.modelId,
636
+ provider: agent.model.providerName,
637
+ profile: agent.model.ref ?? null,
638
+ };
639
+ }
640
+
641
+ function identityChanged(meta: Record<string, unknown>, identity: Record<string, unknown>): boolean {
642
+ return (
643
+ meta.model !== identity.model ||
644
+ meta.provider !== identity.provider ||
645
+ meta.profile !== identity.profile
646
+ );
647
+ }
648
+
649
+ /** Whether it ran is unknown, so the model is told to look before doing it again. */
650
+ function interrupted(call: { toolCallId: string; toolName: string }): ToolOutcome {
651
+ return {
652
+ toolCallId: call.toolCallId,
653
+ toolName: call.toolName,
654
+ error: serializeError(
655
+ new AgentError(
656
+ "run/aborted",
657
+ `${call.toolName} was interrupted: the run ended before it returned, so it may or may not have taken effect. Check before repeating it.`,
658
+ { details: { toolName: call.toolName } },
659
+ ),
660
+ ),
661
+ };
662
+ }
663
+
664
+ const KNOWN_REASONS: readonly FinishReason[] = [
665
+ "stop",
666
+ "tool-calls",
667
+ "length",
668
+ "content-filter",
669
+ "error",
670
+ "other",
671
+ ];
672
+
673
+ function toFinishReason(reason: string): FinishReason {
674
+ return KNOWN_REASONS.includes(reason as FinishReason) ? (reason as FinishReason) : "other";
675
+ }