@theokit/agents 16.0.0 → 16.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 (37) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +47 -1
  3. package/dist/{agent-compiler-BMpuJFAI.d.ts → agent-compiler-JSYkHpa7.d.ts} +2 -2
  4. package/dist/{delegation-scoring-CURe4oSL.d.ts → agent-orchestrator-BFWg2URC.d.ts} +11 -426
  5. package/dist/agent-runner-BUJKNNuI.d.ts +364 -0
  6. package/dist/agent-sse-handler-BRp9vHrb.d.ts +348 -0
  7. package/dist/{bridge-entry-BxJWDpQP.d.ts → bridge-entry-BNWDrPzg.d.ts} +8 -422
  8. package/dist/bridge.d.ts +8 -5
  9. package/dist/bridge.js +19 -15
  10. package/dist/{chunk-4PHZ25JN.js → chunk-A7RXWJZE.js} +62 -1137
  11. package/dist/chunk-A7RXWJZE.js.map +1 -0
  12. package/dist/{chunk-FIGLHWR2.js → chunk-CJMYZKUL.js} +7 -7
  13. package/dist/chunk-MB23MSOK.js +353 -0
  14. package/dist/chunk-MB23MSOK.js.map +1 -0
  15. package/dist/chunk-SAKSZKVK.js +799 -0
  16. package/dist/chunk-SAKSZKVK.js.map +1 -0
  17. package/dist/delegation-scoring-Cn5eM4lQ.d.ts +79 -0
  18. package/dist/evals.d.ts +84 -0
  19. package/dist/evals.js +191 -0
  20. package/dist/evals.js.map +1 -0
  21. package/dist/handoff.d.ts +91 -0
  22. package/dist/handoff.js +268 -0
  23. package/dist/handoff.js.map +1 -0
  24. package/dist/index.d.ts +19 -369
  25. package/dist/index.js +36 -32
  26. package/dist/index.js.map +1 -1
  27. package/dist/mcp-health.d.ts +1 -1
  28. package/dist/sdk-adapter-DQnKx7bA.d.ts +435 -0
  29. package/dist/testing.d.ts +2 -2
  30. package/dist/tools.d.ts +5 -3
  31. package/dist/tools.js +10 -6
  32. package/dist/tools.js.map +1 -1
  33. package/dist/{types-DdltPCj2.d.ts → types-D5cHmSLi.d.ts} +1 -1
  34. package/docs/capability-map.md +31 -1
  35. package/package.json +12 -2
  36. package/dist/chunk-4PHZ25JN.js.map +0 -1
  37. /package/dist/{chunk-FIGLHWR2.js.map → chunk-CJMYZKUL.js.map} +0 -0
@@ -0,0 +1,348 @@
1
+ import { WireChunk } from '@theokit/presenter/wire';
2
+
3
+ /**
4
+ * Typed discriminated union for agent SSE stream events.
5
+ *
6
+ * Every event has a `type` field for discrimination.
7
+ * Clients narrow via `if (event.type === 'text_delta') event.content`.
8
+ */
9
+ /** Partial text content from the LLM. */
10
+ interface TextDeltaEvent {
11
+ type: 'text_delta';
12
+ content: string;
13
+ }
14
+ /** Agent started a tool call. */
15
+ interface ToolCallEvent {
16
+ type: 'tool_call';
17
+ callId: string;
18
+ toolName: string;
19
+ input: unknown;
20
+ }
21
+ /**
22
+ * Tool-call arguments streaming in incrementally (theokit-sdk#70). Emitted repeatedly as the
23
+ * model generates a tool call's args, BEFORE they are committed. The same `callId` correlates to
24
+ * the later `tool_call` (args committed) and `tool_result`. Consumers opt in to render tool-input
25
+ * progressively; those that don't simply ignore this variant (it never replaces `tool_call`).
26
+ */
27
+ interface PartialToolCallEvent {
28
+ type: 'partial_tool_call';
29
+ callId: string;
30
+ toolName: string;
31
+ input: unknown;
32
+ }
33
+ /** Tool execution completed. */
34
+ interface ToolResultEvent {
35
+ type: 'tool_result';
36
+ callId: string;
37
+ toolName: string;
38
+ output: string;
39
+ durationMs: number;
40
+ isError: boolean;
41
+ }
42
+ /** Extended thinking / reasoning (when model supports it). */
43
+ interface ThinkingEvent {
44
+ type: 'thinking';
45
+ content: string;
46
+ }
47
+ /** Agent loop iteration. */
48
+ interface IterationEvent {
49
+ type: 'iteration';
50
+ step: number;
51
+ totalSteps: number | null;
52
+ }
53
+ /** Human approval required before proceeding. */
54
+ interface ApprovalRequiredEvent {
55
+ type: 'approval_required';
56
+ callId: string;
57
+ toolName: string;
58
+ question: string;
59
+ input?: unknown;
60
+ callbackUrl: string;
61
+ timeoutMs: number;
62
+ /** M20 — JSON-schema descriptor of the custom payload the approver may attach (optional). */
63
+ payloadSchema?: Record<string, unknown>;
64
+ }
65
+ /**
66
+ * The run is blocked awaiting user input or approval — theokit#141.
67
+ *
68
+ * The SDK's low-fidelity pause signal (`SDKRequestMessage`), distinct from {@link
69
+ * ApprovalRequiredEvent}. The latter is the framework's own, produced by `createHitlPlugin`, and
70
+ * carries everything an approval UI needs to be actionable. This one carries only the request id,
71
+ * because that is all the SDK provides — and it matters most exactly where the plugin is absent
72
+ * (the ACP/serving path of theokit#139), which is where a dropped pause reads to the user as a
73
+ * hang with no explanation.
74
+ *
75
+ * A consumer that cannot resolve the request should still SHOW that the run is waiting. Silence is
76
+ * the one response that is always wrong.
77
+ */
78
+ interface InputRequestedEvent {
79
+ type: 'input_requested';
80
+ requestId: string;
81
+ }
82
+ /** Task-level milestone or summary — theokit#141. Both fields are optional at the source. */
83
+ interface TaskProgressEvent {
84
+ type: 'task_progress';
85
+ status?: string;
86
+ text?: string;
87
+ }
88
+ /**
89
+ * Live output from a shell command the SDK is running — theokit#141.
90
+ *
91
+ * `event` is passed through opaquely because the SDK types it as `Record<string, unknown>`. The
92
+ * layer deliberately does not interpret or render it: guessing a shape here would be a second,
93
+ * weaker oracle over a payload whose real contract lives upstream.
94
+ */
95
+ interface ShellOutputEvent {
96
+ type: 'shell_output';
97
+ event: Record<string, unknown>;
98
+ }
99
+ /** Agent encountered an error. */
100
+ interface ErrorEvent {
101
+ type: 'error';
102
+ code: string;
103
+ message: string;
104
+ retryable: boolean;
105
+ }
106
+ /**
107
+ * Why a run stopped short of finishing on its own — theokit#379.
108
+ *
109
+ * ## Why it is an enum and not a `truncated: boolean`
110
+ *
111
+ * The two members demand OPPOSITE reactions from the caller, and a boolean cannot carry the
112
+ * difference:
113
+ *
114
+ * - `'step_limit'` — the loop ran out of tool-calling turns while the model still wanted more.
115
+ * The work is unfinished but progressing; re-sending is the sane continuation.
116
+ * - `'no_progress'` — the doom-loop guard stopped the model repeating IDENTICAL tool calls. The
117
+ * SDK's own wording: "a controlled stop, NOT a truncation to re-send". Re-sending repeats the
118
+ * loop that was just cut.
119
+ *
120
+ * A caller that reads `truncated: true` and re-sends does the right thing in the first case and
121
+ * feeds the doom loop in the second.
122
+ *
123
+ * ## Why these spellings
124
+ *
125
+ * Both sides of the boundary had already agreed on them before this field existed: the framework's
126
+ * own `LoopFinishReason` (`../loop/loop-strategy.ts`) spells the outer-loop terminals `step_limit`
127
+ * and `no_progress`, and so does the SDK's continuation driver
128
+ * (`RunToCompletionResult.terminal: "done" | "step_limit" | "no_progress"`). Inventing a third
129
+ * vocabulary for the same two outcomes was the only way to get this wrong.
130
+ *
131
+ * ## Why there is no `'finished'` member
132
+ *
133
+ * A clean run carries NO `stopReason` at all — absence is the finished case. Stamping every
134
+ * ordinary turn with a new field would change what every existing consumer receives in order to
135
+ * describe the one case that was already correct. A consumer that has never heard of `stopReason`
136
+ * therefore keeps receiving byte-identical frames for every run that finishes on its own, and for a
137
+ * truncated one it receives one extra optional key it ignores — the same degradation the ai-sdk
138
+ * `finish` chunk already allows, since its `messageMetadata` is `unknown`.
139
+ */
140
+ type AgentStopReason = 'step_limit' | 'no_progress';
141
+ /** Agent completed with a final result. */
142
+ interface DoneEvent {
143
+ type: 'done';
144
+ result: string;
145
+ usage: {
146
+ inputTokens: number;
147
+ outputTokens: number;
148
+ totalTokens: number;
149
+ /** V4-O: SDK reasoning/cache token buckets (0 when the provider omits them). */
150
+ reasoningTokens?: number;
151
+ cacheReadTokens?: number;
152
+ cacheWriteTokens?: number;
153
+ };
154
+ durationMs: number;
155
+ /**
156
+ * Total cost in USD for this agent run, as the SDK priced it (`CostBreakdown.amountUsd`).
157
+ *
158
+ * Absent when the run's price is not known (the SDK has no pricing data for the model); 0 means
159
+ * the SDK priced the run at zero, for example a subscription-included route. A consumer summing
160
+ * runs must not read an absent cost as 0 (usetheokit/theokit#969).
161
+ */
162
+ cost?: number;
163
+ /**
164
+ * theokit#379 — why the run stopped, when it did NOT stop because the agent was done.
165
+ *
166
+ * ABSENT on a clean finish. Present only when the SDK reports that the run was cut: the terminal
167
+ * frame is a `done` either way (a reached ceiling is not an error — see `sdk-adapter.ts`'s
168
+ * `applyStepCeiling`), so without this field a cut run and a finished one are the same event.
169
+ *
170
+ * Read from `RunResult.stoppedByDoomLoop` / `RunResult.stoppedAtIterationLimit` at the adapter
171
+ * boundary. See {@link AgentStopReason} for why the caller needs to tell the two apart.
172
+ */
173
+ stopReason?: AgentStopReason;
174
+ /**
175
+ * The model this turn actually ran on — the EFFECTIVE id, not the declared one.
176
+ *
177
+ * It is resolved at the one place that knows: `createSdkAgentStream`, where
178
+ * `overrides.model ?? compiled.model ?? 'openai/gpt-4o-mini'` is decided. A consumer reading
179
+ * `CompiledAgentOptions.model` instead would be wrong twice — it misses a per-run override, and
180
+ * it reads `undefined` for an agent that declared no model and still ran one.
181
+ *
182
+ * Tokens are on this event already, and tokens alone convert to no cost: price is per model.
183
+ * This is the other half of that question, and the reason it travels rather than staying inside
184
+ * the adapter (usetheokit/theokit#368's fifth criterion).
185
+ *
186
+ * Optional so a producer that predates it — or one building a `done` from a source with no model
187
+ * to report — degrades to absence rather than to a fabricated id.
188
+ */
189
+ model?: string;
190
+ }
191
+ /**
192
+ * Per-turn usage the translator attaches to the ai-sdk `finish` chunk's `messageMetadata`, so it
193
+ * lands on the reconstructed assistant `UIMessage.metadata` on the client (via `readUIMessageStream`)
194
+ * with NO extra header/store wiring. It is the seam that lets a surface (a TUI status bar, a web
195
+ * cost meter) show real tokens/cost for the turn it just streamed. Mirrors `DoneEvent`'s usage/cost
196
+ * (the authoritative totals the SDK reports at turn end) plus the wall-clock `durationMs`.
197
+ */
198
+ interface AgentTurnMetadata {
199
+ usage: DoneEvent['usage'];
200
+ /** Total cost in USD for the turn (present iff the SDK reported it). */
201
+ cost?: number;
202
+ durationMs: number;
203
+ /**
204
+ * theokit#379 — mirrors {@link DoneEvent.stopReason} so a surface that only ever sees the wire
205
+ * (a web client reading `UIMessage.metadata`, the observability translator reading the `finish`
206
+ * chunk) can tell a cut turn from a finished one without a second transport. Absent on a clean
207
+ * finish, exactly as on `DoneEvent`.
208
+ */
209
+ stopReason?: AgentStopReason;
210
+ /**
211
+ * Mirrors {@link DoneEvent.model} — the model the turn ran on, carried to whoever only ever sees
212
+ * the wire. The observability translator is the caller that needs it: it reads the `finish`
213
+ * chunk and records the model beside the token counts, which is what makes a cost answerable
214
+ * from a trace at all. Absent when the producer reported none.
215
+ */
216
+ model?: string;
217
+ }
218
+ /** Agent run started. */
219
+ interface RunStartedEvent {
220
+ type: 'run_started';
221
+ runId: string;
222
+ agentName: string;
223
+ model?: string;
224
+ }
225
+ /** Artifact generation started (code, document, diagram). */
226
+ interface ArtifactStartEvent {
227
+ type: 'artifact_start';
228
+ artifactId: string;
229
+ mimeType: string;
230
+ filename?: string;
231
+ metadata?: Record<string, unknown>;
232
+ }
233
+ /** Artifact content chunk (streamable artifacts). */
234
+ interface ArtifactChunkEvent {
235
+ type: 'artifact_chunk';
236
+ artifactId: string;
237
+ chunk: string;
238
+ isLast: boolean;
239
+ }
240
+ /** Real-time state update from @Observable channels. */
241
+ interface StateUpdateEvent {
242
+ type: 'state_update';
243
+ channel: string;
244
+ data: unknown;
245
+ }
246
+ /** Checkpoint saved (resumable agents). */
247
+ interface CheckpointSavedEvent {
248
+ type: 'checkpoint_saved';
249
+ checkpointId: string;
250
+ step: number;
251
+ resumeToken: string;
252
+ }
253
+ /** File edit produced by a code assistant tool. */
254
+ interface FileEditEvent {
255
+ type: 'file_edit';
256
+ file: string;
257
+ format: 'search-replace' | 'unified-diff' | 'full-file' | 'line-range';
258
+ search?: string;
259
+ replace?: string;
260
+ content?: string;
261
+ diff?: string;
262
+ startLine?: number;
263
+ endLine?: number;
264
+ }
265
+ /** Discriminated union of all agent stream events. */
266
+ type AgentStreamEvent = RunStartedEvent | TextDeltaEvent | ToolCallEvent | PartialToolCallEvent | ToolResultEvent | ThinkingEvent | IterationEvent | ApprovalRequiredEvent | InputRequestedEvent | TaskProgressEvent | ShellOutputEvent | ArtifactStartEvent | ArtifactChunkEvent | StateUpdateEvent | CheckpointSavedEvent | FileEditEvent | ErrorEvent | DoneEvent;
267
+ /** Type guard helpers. */
268
+ declare function isTextDelta(e: AgentStreamEvent): e is TextDeltaEvent;
269
+ declare function isToolCall(e: AgentStreamEvent): e is ToolCallEvent;
270
+ declare function isPartialToolCall(e: AgentStreamEvent): e is PartialToolCallEvent;
271
+ declare function isToolResult(e: AgentStreamEvent): e is ToolResultEvent;
272
+ declare function isDone(e: AgentStreamEvent): e is DoneEvent;
273
+ declare function isError(e: AgentStreamEvent): e is ErrorEvent;
274
+ declare function isApprovalRequired(e: AgentStreamEvent): e is ApprovalRequiredEvent;
275
+
276
+ /**
277
+ * The failure, as chunks the protocol accepts — theokit#161 (B).
278
+ *
279
+ * ## The measured defect
280
+ *
281
+ * M95 put the `code` INSIDE the error chunk (`{type:'error', errorText, errorCode}`), for a good
282
+ * reason: without it a consumer that must DISTINGUISH the failure has only the message, and matching
283
+ * on error text is the heuristic this ecosystem already paid for once — M93 classified failures as
284
+ * transient by regex over the message and read `ECONNREFUSED ...:443` as definitive because the PORT
285
+ * matched its "4xx" pattern.
286
+ *
287
+ * But the `error` variant of ai's `uiMessageChunkSchema` is STRICT: any extra key invalidates it.
288
+ * Measured against `ai@7.0.14` — `{type:'error',errorText:'boom'}` validates; the same chunk with
289
+ * `errorCode` does NOT. So since M95 this path emitted a chunk outside the protocol it claims to
290
+ * speak, and a consumer that validates would reject the whole frame — losing the text along with it.
291
+ *
292
+ * Nobody saw it because the test written to catch exactly this stopped BEFORE validating: its
293
+ * precondition (`toContainEqual({type:'error',errorText:'boom'})`) went stale when `errorCode`
294
+ * appeared, `expect` threw, and the validation loop never ran.
295
+ *
296
+ * ## Why a data part, and not one of the easy exits
297
+ *
298
+ * Dropping the code returns the consumer to the text matching M95 removed. Embedding it in
299
+ * `errorText` is the same thing under another name. The protocol already has the right place — a
300
+ * data part — and this file already uses one for `data-checkpoint`. Measured: it validates.
301
+ *
302
+ * `transient: true` because an error code is turn diagnostics, not message content: the SDK does not
303
+ * persist it in history, which is exactly what we want.
304
+ *
305
+ * The data part comes BEFORE the error chunk deliberately: a sequential consumer already holds the
306
+ * code when the failure arrives. In the other order it would have to handle the error first and only
307
+ * then learn which one it was.
308
+ */
309
+ /**
310
+ * What the browser is told a failure was.
311
+ *
312
+ * Masked by default (usetheokit/theokit#390): the server's raw text — a driver's message, an HTTP
313
+ * client's, a filesystem call's — reached the client verbatim, and `ai@7` on the same protocol
314
+ * masks by default for the reason its own comment gives, "prevent leaking server error details to
315
+ * the client by default".
316
+ *
317
+ * The full text is NOT lost: it reaches the server's logs and the `agent.run` span, and it reaches
318
+ * this hook. What stops is it reaching the browser unless a host decides otherwise.
319
+ */
320
+ type MaskError = (error: {
321
+ message: string;
322
+ code?: string;
323
+ }) => string;
324
+ declare function presentUIMessageStream(events: AsyncIterable<AgentStreamEvent>, opts: {
325
+ textId: string;
326
+ onError?: MaskError;
327
+ }): AsyncGenerator<WireChunk, void, unknown>;
328
+
329
+ /** Minimal event shape matching SDK's SDKMessage discriminated union. */
330
+ interface StreamEvent {
331
+ type: string;
332
+ [key: string]: unknown;
333
+ }
334
+ /**
335
+ * Create a Web Standard Response that streams the agent's turn as UIMessage wire chunks.
336
+ *
337
+ * The `event:` line carries the chunk's own type. It is informational — `parseWireStream` reads
338
+ * only `data:` lines, per WHATWG SSE — and kept because an `EventSource` consumer can dispatch on
339
+ * it.
340
+ *
341
+ * @param eventStream - the framework's own run events
342
+ * @param opts.onError - what a consumer is told a failure was; masked by default (#390)
343
+ */
344
+ declare function streamAgentResponse(eventStream: AsyncIterable<StreamEvent>, opts?: {
345
+ onError?: Parameters<typeof presentUIMessageStream>[1]['onError'];
346
+ }): Response;
347
+
348
+ export { type ApprovalRequiredEvent as A, type CheckpointSavedEvent as C, type DoneEvent as D, type ErrorEvent as E, type FileEditEvent as F, type IterationEvent as I, type MaskError as M, type PartialToolCallEvent as P, type RunStartedEvent as R, type StreamEvent as S, type TextDeltaEvent as T, type AgentStopReason as a, type AgentStreamEvent as b, type AgentTurnMetadata as c, type ArtifactChunkEvent as d, type ArtifactStartEvent as e, type StateUpdateEvent as f, type ThinkingEvent as g, type ToolCallEvent as h, type ToolResultEvent as i, isApprovalRequired as j, isDone as k, isError as l, isPartialToolCall as m, isTextDelta as n, isToolCall as o, isToolResult as p, presentUIMessageStream as q, streamAgentResponse as s };