@theokit/agents 15.1.1 → 16.1.0

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 (50) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +48 -1
  3. package/dist/a2a.d.ts +37 -0
  4. package/dist/a2a.js +90 -0
  5. package/dist/a2a.js.map +1 -0
  6. package/dist/{agent-compiler-DMQcLHIs.d.ts → agent-compiler-JSYkHpa7.d.ts} +2 -2
  7. package/dist/agent-orchestrator-BFWg2URC.d.ts +449 -0
  8. package/dist/agent-runner-BUJKNNuI.d.ts +364 -0
  9. package/dist/agent-sse-handler-BRp9vHrb.d.ts +348 -0
  10. package/dist/{bridge-entry-CDFRjtbb.d.ts → bridge-entry-BNWDrPzg.d.ts} +8 -422
  11. package/dist/bridge.d.ts +8 -5
  12. package/dist/bridge.js +21 -15
  13. package/dist/{chunk-RAN4PBUL.js → chunk-3TE4PJZL.js} +569 -1526
  14. package/dist/chunk-3TE4PJZL.js.map +1 -0
  15. package/dist/{chunk-ULC47RCQ.js → chunk-4SXVNI5O.js} +7 -7
  16. package/dist/{chunk-ULC47RCQ.js.map → chunk-4SXVNI5O.js.map} +1 -1
  17. package/dist/chunk-A2UVVEB3.js +799 -0
  18. package/dist/chunk-A2UVVEB3.js.map +1 -0
  19. package/dist/chunk-FBCT4B2L.js +86 -0
  20. package/dist/chunk-FBCT4B2L.js.map +1 -0
  21. package/dist/{chunk-DZH5F4PP.js → chunk-KXE52FP2.js} +12 -67
  22. package/dist/chunk-KXE52FP2.js.map +1 -0
  23. package/dist/chunk-Z5SYU6Z6.js +353 -0
  24. package/dist/chunk-Z5SYU6Z6.js.map +1 -0
  25. package/dist/client-react.js +2 -1
  26. package/dist/client-react.js.map +1 -1
  27. package/dist/client.d.ts +12 -2
  28. package/dist/client.js +5 -3
  29. package/dist/delegation-scoring-Cn5eM4lQ.d.ts +79 -0
  30. package/dist/evals.d.ts +84 -0
  31. package/dist/evals.js +191 -0
  32. package/dist/evals.js.map +1 -0
  33. package/dist/handoff.d.ts +91 -0
  34. package/dist/handoff.js +268 -0
  35. package/dist/handoff.js.map +1 -0
  36. package/dist/index.d.ts +61 -401
  37. package/dist/index.js +142 -111
  38. package/dist/index.js.map +1 -1
  39. package/dist/mcp-health.d.ts +1 -1
  40. package/dist/sdk-adapter-DQnKx7bA.d.ts +435 -0
  41. package/dist/testing.d.ts +2 -2
  42. package/dist/tools.d.ts +5 -3
  43. package/dist/tools.js +10 -6
  44. package/dist/tools.js.map +1 -1
  45. package/dist/{types-CxI2x6mU.d.ts → types-D5cHmSLi.d.ts} +10 -4
  46. package/docs/capability-map.md +44 -5
  47. package/package.json +16 -2
  48. package/dist/chunk-DZH5F4PP.js.map +0 -1
  49. package/dist/chunk-RAN4PBUL.js.map +0 -1
  50. package/dist/delegation-scoring-CSe_C-iX.d.ts +0 -809
@@ -1,809 +0,0 @@
1
- import { PluginsSettings, ProviderRoutingSettings, AgentDefinition, BudgetTracker, CustomTool } from '@theokit/sdk';
2
- import { RetryOptions } from '@theokit/sdk/retry';
3
- import { C as CompiledAgentOptions, a as CompiledTool } from './agent-compiler-DMQcLHIs.js';
4
- import { TheokitAgentError } from '@theokit/sdk/errors';
5
- import { z } from 'zod';
6
- import { b as MainLoopMeta } from './types-CxI2x6mU.js';
7
- import { WireChunk } from '@theokit/presenter/wire';
8
- import { H as HookHandlers } from './hook-handlers-Cw2FsnE5.js';
9
-
10
- /**
11
- * Typed discriminated union for agent SSE stream events.
12
- *
13
- * Every event has a `type` field for discrimination.
14
- * Clients narrow via `if (event.type === 'text_delta') event.content`.
15
- */
16
- /** Partial text content from the LLM. */
17
- interface TextDeltaEvent {
18
- type: 'text_delta';
19
- content: string;
20
- }
21
- /** Agent started a tool call. */
22
- interface ToolCallEvent {
23
- type: 'tool_call';
24
- callId: string;
25
- toolName: string;
26
- input: unknown;
27
- }
28
- /**
29
- * Tool-call arguments streaming in incrementally (theokit-sdk#70). Emitted repeatedly as the
30
- * model generates a tool call's args, BEFORE they are committed. The same `callId` correlates to
31
- * the later `tool_call` (args committed) and `tool_result`. Consumers opt in to render tool-input
32
- * progressively; those that don't simply ignore this variant (it never replaces `tool_call`).
33
- */
34
- interface PartialToolCallEvent {
35
- type: 'partial_tool_call';
36
- callId: string;
37
- toolName: string;
38
- input: unknown;
39
- }
40
- /** Tool execution completed. */
41
- interface ToolResultEvent {
42
- type: 'tool_result';
43
- callId: string;
44
- toolName: string;
45
- output: string;
46
- durationMs: number;
47
- isError: boolean;
48
- }
49
- /** Extended thinking / reasoning (when model supports it). */
50
- interface ThinkingEvent {
51
- type: 'thinking';
52
- content: string;
53
- }
54
- /** Agent loop iteration. */
55
- interface IterationEvent {
56
- type: 'iteration';
57
- step: number;
58
- totalSteps: number | null;
59
- }
60
- /** Human approval required before proceeding. */
61
- interface ApprovalRequiredEvent {
62
- type: 'approval_required';
63
- callId: string;
64
- toolName: string;
65
- question: string;
66
- input?: unknown;
67
- callbackUrl: string;
68
- timeoutMs: number;
69
- /** M20 — JSON-schema descriptor of the custom payload the approver may attach (optional). */
70
- payloadSchema?: Record<string, unknown>;
71
- }
72
- /**
73
- * The run is blocked awaiting user input or approval — theokit#141.
74
- *
75
- * The SDK's low-fidelity pause signal (`SDKRequestMessage`), distinct from {@link
76
- * ApprovalRequiredEvent}. The latter is the framework's own, produced by `createHitlPlugin`, and
77
- * carries everything an approval UI needs to be actionable. This one carries only the request id,
78
- * because that is all the SDK provides — and it matters most exactly where the plugin is absent
79
- * (the ACP/serving path of theokit#139), which is where a dropped pause reads to the user as a
80
- * hang with no explanation.
81
- *
82
- * A consumer that cannot resolve the request should still SHOW that the run is waiting. Silence is
83
- * the one response that is always wrong.
84
- */
85
- interface InputRequestedEvent {
86
- type: 'input_requested';
87
- requestId: string;
88
- }
89
- /** Task-level milestone or summary — theokit#141. Both fields are optional at the source. */
90
- interface TaskProgressEvent {
91
- type: 'task_progress';
92
- status?: string;
93
- text?: string;
94
- }
95
- /**
96
- * Live output from a shell command the SDK is running — theokit#141.
97
- *
98
- * `event` is passed through opaquely because the SDK types it as `Record<string, unknown>`. The
99
- * layer deliberately does not interpret or render it: guessing a shape here would be a second,
100
- * weaker oracle over a payload whose real contract lives upstream.
101
- */
102
- interface ShellOutputEvent {
103
- type: 'shell_output';
104
- event: Record<string, unknown>;
105
- }
106
- /** Agent encountered an error. */
107
- interface ErrorEvent {
108
- type: 'error';
109
- code: string;
110
- message: string;
111
- retryable: boolean;
112
- }
113
- /**
114
- * Why a run stopped short of finishing on its own — theokit#379.
115
- *
116
- * ## Why it is an enum and not a `truncated: boolean`
117
- *
118
- * The two members demand OPPOSITE reactions from the caller, and a boolean cannot carry the
119
- * difference:
120
- *
121
- * - `'step_limit'` — the loop ran out of tool-calling turns while the model still wanted more.
122
- * The work is unfinished but progressing; re-sending is the sane continuation.
123
- * - `'no_progress'` — the doom-loop guard stopped the model repeating IDENTICAL tool calls. The
124
- * SDK's own wording: "a controlled stop, NOT a truncation to re-send". Re-sending repeats the
125
- * loop that was just cut.
126
- *
127
- * A caller that reads `truncated: true` and re-sends does the right thing in the first case and
128
- * feeds the doom loop in the second.
129
- *
130
- * ## Why these spellings
131
- *
132
- * Both sides of the boundary had already agreed on them before this field existed: the framework's
133
- * own `LoopFinishReason` (`../loop/loop-strategy.ts`) spells the outer-loop terminals `step_limit`
134
- * and `no_progress`, and so does the SDK's continuation driver
135
- * (`RunToCompletionResult.terminal: "done" | "step_limit" | "no_progress"`). Inventing a third
136
- * vocabulary for the same two outcomes was the only way to get this wrong.
137
- *
138
- * ## Why there is no `'finished'` member
139
- *
140
- * A clean run carries NO `stopReason` at all — absence is the finished case. Stamping every
141
- * ordinary turn with a new field would change what every existing consumer receives in order to
142
- * describe the one case that was already correct. A consumer that has never heard of `stopReason`
143
- * therefore keeps receiving byte-identical frames for every run that finishes on its own, and for a
144
- * truncated one it receives one extra optional key it ignores — the same degradation the ai-sdk
145
- * `finish` chunk already allows, since its `messageMetadata` is `unknown`.
146
- */
147
- type AgentStopReason = 'step_limit' | 'no_progress';
148
- /** Agent completed with a final result. */
149
- interface DoneEvent {
150
- type: 'done';
151
- result: string;
152
- usage: {
153
- inputTokens: number;
154
- outputTokens: number;
155
- totalTokens: number;
156
- /** V4-O: SDK reasoning/cache token buckets (0 when the provider omits them). */
157
- reasoningTokens?: number;
158
- cacheReadTokens?: number;
159
- cacheWriteTokens?: number;
160
- };
161
- durationMs: number;
162
- /** Total cost in USD for this agent run (EC-2: added for budget tracking). */
163
- cost?: number;
164
- /**
165
- * theokit#379 — why the run stopped, when it did NOT stop because the agent was done.
166
- *
167
- * ABSENT on a clean finish. Present only when the SDK reports that the run was cut: the terminal
168
- * frame is a `done` either way (a reached ceiling is not an error — see `sdk-adapter.ts`'s
169
- * `applyStepCeiling`), so without this field a cut run and a finished one are the same event.
170
- *
171
- * Read from `RunResult.stoppedByDoomLoop` / `RunResult.stoppedAtIterationLimit` at the adapter
172
- * boundary. See {@link AgentStopReason} for why the caller needs to tell the two apart.
173
- */
174
- stopReason?: AgentStopReason;
175
- /**
176
- * The model this turn actually ran on — the EFFECTIVE id, not the declared one.
177
- *
178
- * It is resolved at the one place that knows: `createSdkAgentStream`, where
179
- * `overrides.model ?? compiled.model ?? 'openai/gpt-4o-mini'` is decided. A consumer reading
180
- * `CompiledAgentOptions.model` instead would be wrong twice — it misses a per-run override, and
181
- * it reads `undefined` for an agent that declared no model and still ran one.
182
- *
183
- * Tokens are on this event already, and tokens alone convert to no cost: price is per model.
184
- * This is the other half of that question, and the reason it travels rather than staying inside
185
- * the adapter (usetheokit/theokit#368's fifth criterion).
186
- *
187
- * Optional so a producer that predates it — or one building a `done` from a source with no model
188
- * to report — degrades to absence rather than to a fabricated id.
189
- */
190
- model?: string;
191
- }
192
- /**
193
- * Per-turn usage the translator attaches to the ai-sdk `finish` chunk's `messageMetadata`, so it
194
- * lands on the reconstructed assistant `UIMessage.metadata` on the client (via `readUIMessageStream`)
195
- * with NO extra header/store wiring. It is the seam that lets a surface (a TUI status bar, a web
196
- * cost meter) show real tokens/cost for the turn it just streamed. Mirrors `DoneEvent`'s usage/cost
197
- * (the authoritative totals the SDK reports at turn end) plus the wall-clock `durationMs`.
198
- */
199
- interface AgentTurnMetadata {
200
- usage: DoneEvent['usage'];
201
- /** Total cost in USD for the turn (present iff the SDK reported it). */
202
- cost?: number;
203
- durationMs: number;
204
- /**
205
- * theokit#379 — mirrors {@link DoneEvent.stopReason} so a surface that only ever sees the wire
206
- * (a web client reading `UIMessage.metadata`, the observability translator reading the `finish`
207
- * chunk) can tell a cut turn from a finished one without a second transport. Absent on a clean
208
- * finish, exactly as on `DoneEvent`.
209
- */
210
- stopReason?: AgentStopReason;
211
- /**
212
- * Mirrors {@link DoneEvent.model} — the model the turn ran on, carried to whoever only ever sees
213
- * the wire. The observability translator is the caller that needs it: it reads the `finish`
214
- * chunk and records the model beside the token counts, which is what makes a cost answerable
215
- * from a trace at all. Absent when the producer reported none.
216
- */
217
- model?: string;
218
- }
219
- /** Agent run started. */
220
- interface RunStartedEvent {
221
- type: 'run_started';
222
- runId: string;
223
- agentName: string;
224
- model?: string;
225
- }
226
- /** Artifact generation started (code, document, diagram). */
227
- interface ArtifactStartEvent {
228
- type: 'artifact_start';
229
- artifactId: string;
230
- mimeType: string;
231
- filename?: string;
232
- metadata?: Record<string, unknown>;
233
- }
234
- /** Artifact content chunk (streamable artifacts). */
235
- interface ArtifactChunkEvent {
236
- type: 'artifact_chunk';
237
- artifactId: string;
238
- chunk: string;
239
- isLast: boolean;
240
- }
241
- /** Real-time state update from @Observable channels. */
242
- interface StateUpdateEvent {
243
- type: 'state_update';
244
- channel: string;
245
- data: unknown;
246
- }
247
- /** Checkpoint saved (resumable agents). */
248
- interface CheckpointSavedEvent {
249
- type: 'checkpoint_saved';
250
- checkpointId: string;
251
- step: number;
252
- resumeToken: string;
253
- }
254
- /** File edit produced by a code assistant tool. */
255
- interface FileEditEvent {
256
- type: 'file_edit';
257
- file: string;
258
- format: 'search-replace' | 'unified-diff' | 'full-file' | 'line-range';
259
- search?: string;
260
- replace?: string;
261
- content?: string;
262
- diff?: string;
263
- startLine?: number;
264
- endLine?: number;
265
- }
266
- /** Discriminated union of all agent stream events. */
267
- type AgentStreamEvent = RunStartedEvent | TextDeltaEvent | ToolCallEvent | PartialToolCallEvent | ToolResultEvent | ThinkingEvent | IterationEvent | ApprovalRequiredEvent | InputRequestedEvent | TaskProgressEvent | ShellOutputEvent | ArtifactStartEvent | ArtifactChunkEvent | StateUpdateEvent | CheckpointSavedEvent | FileEditEvent | ErrorEvent | DoneEvent;
268
- /** Type guard helpers. */
269
- declare function isTextDelta(e: AgentStreamEvent): e is TextDeltaEvent;
270
- declare function isToolCall(e: AgentStreamEvent): e is ToolCallEvent;
271
- declare function isPartialToolCall(e: AgentStreamEvent): e is PartialToolCallEvent;
272
- declare function isToolResult(e: AgentStreamEvent): e is ToolResultEvent;
273
- declare function isDone(e: AgentStreamEvent): e is DoneEvent;
274
- declare function isError(e: AgentStreamEvent): e is ErrorEvent;
275
- declare function isApprovalRequired(e: AgentStreamEvent): e is ApprovalRequiredEvent;
276
-
277
- /**
278
- * The failure, as chunks the protocol accepts — theokit#161 (B).
279
- *
280
- * ## The measured defect
281
- *
282
- * M95 put the `code` INSIDE the error chunk (`{type:'error', errorText, errorCode}`), for a good
283
- * reason: without it a consumer that must DISTINGUISH the failure has only the message, and matching
284
- * on error text is the heuristic this ecosystem already paid for once — M93 classified failures as
285
- * transient by regex over the message and read `ECONNREFUSED ...:443` as definitive because the PORT
286
- * matched its "4xx" pattern.
287
- *
288
- * But the `error` variant of ai's `uiMessageChunkSchema` is STRICT: any extra key invalidates it.
289
- * Measured against `ai@7.0.14` — `{type:'error',errorText:'boom'}` validates; the same chunk with
290
- * `errorCode` does NOT. So since M95 this path emitted a chunk outside the protocol it claims to
291
- * speak, and a consumer that validates would reject the whole frame — losing the text along with it.
292
- *
293
- * Nobody saw it because the test written to catch exactly this stopped BEFORE validating: its
294
- * precondition (`toContainEqual({type:'error',errorText:'boom'})`) went stale when `errorCode`
295
- * appeared, `expect` threw, and the validation loop never ran.
296
- *
297
- * ## Why a data part, and not one of the easy exits
298
- *
299
- * Dropping the code returns the consumer to the text matching M95 removed. Embedding it in
300
- * `errorText` is the same thing under another name. The protocol already has the right place — a
301
- * data part — and this file already uses one for `data-checkpoint`. Measured: it validates.
302
- *
303
- * `transient: true` because an error code is turn diagnostics, not message content: the SDK does not
304
- * persist it in history, which is exactly what we want.
305
- *
306
- * The data part comes BEFORE the error chunk deliberately: a sequential consumer already holds the
307
- * code when the failure arrives. In the other order it would have to handle the error first and only
308
- * then learn which one it was.
309
- */
310
- /**
311
- * What the browser is told a failure was.
312
- *
313
- * Masked by default (usetheokit/theokit#390): the server's raw text — a driver's message, an HTTP
314
- * client's, a filesystem call's — reached the client verbatim, and `ai@7` on the same protocol
315
- * masks by default for the reason its own comment gives, "prevent leaking server error details to
316
- * the client by default".
317
- *
318
- * The full text is NOT lost: it reaches the server's logs and the `agent.run` span, and it reaches
319
- * this hook. What stops is it reaching the browser unless a host decides otherwise.
320
- */
321
- type MaskError = (error: {
322
- message: string;
323
- code?: string;
324
- }) => string;
325
- declare function presentUIMessageStream(events: AsyncIterable<AgentStreamEvent>, opts: {
326
- textId: string;
327
- onError?: MaskError;
328
- }): AsyncGenerator<WireChunk, void, unknown>;
329
-
330
- /** Minimal event shape matching SDK's SDKMessage discriminated union. */
331
- interface StreamEvent {
332
- type: string;
333
- [key: string]: unknown;
334
- }
335
- /**
336
- * Create a Web Standard Response that streams the agent's turn as UIMessage wire chunks.
337
- *
338
- * The `event:` line carries the chunk's own type. It is informational — `parseWireStream` reads
339
- * only `data:` lines, per WHATWG SSE — and kept because an `EventSource` consumer can dispatch on
340
- * it.
341
- *
342
- * @param eventStream - the framework's own run events
343
- * @param opts.onError - what a consumer is told a failure was; masked by default (#390)
344
- */
345
- declare function streamAgentResponse(eventStream: AsyncIterable<StreamEvent>, opts?: {
346
- onError?: Parameters<typeof presentUIMessageStream>[1]['onError'];
347
- }): Response;
348
-
349
- /**
350
- * LoopStrategy — the per-round terminal-decision contract that gives runtime to
351
- * `@MainLoop({ strategy })`.
352
- *
353
- * V4-A proved `@MainLoop`'s `strategy` field was metadata-only (declared +
354
- * compiled, never executed). This module is the foundation Phase 2's
355
- * `runReflectiveLoop` branches on. Modeled on Mastra's `agentic-loop`/`stopWhen`
356
- * (inverted) + `maxSteps` ceiling — NOT Spring's per-call Advisor (plan ADR D1).
357
- * Config is Zod-validated so an invalid `maxIterations` fails fast at resolve
358
- * time, never as a silent infinite loop at runtime (plan ADR D3).
359
- */
360
-
361
- /** Why a single round ended (or, for the V4-D terminals, why the whole loop ended). */
362
- type LoopFinishReason = 'tool-calls' | 'stop' | 'length' | 'error' | 'step_limit' | 'no_progress';
363
- /** Value object describing one round's result. */
364
- interface LoopOutcome {
365
- /** Why the round ended (the continuation signal). */
366
- readonly finishReason: LoopFinishReason;
367
- /** 1-indexed round number that just completed. */
368
- readonly round: number;
369
- /** Tool calls executed during the round (V4-N: `id` correlates the call to its result). */
370
- readonly toolCalls: readonly {
371
- id: string;
372
- name: string;
373
- input: unknown;
374
- output: string;
375
- }[];
376
- /** Accumulated assistant text for the round. */
377
- readonly responseText: string;
378
- }
379
- /** The terminal-decision contract. `shouldContinue` is the inverted `stopWhen`. */
380
- interface LoopStrategy {
381
- /**
382
- * The strategy name, surfaced in `finalize`/logs. M54 relaxes this from
383
- * `MainLoopMeta['strategy']` to `string` so a caller-injected `.loopStrategy(custom)` can name
384
- * itself freely — the three built-ins keep their names, but the seam is no longer union-locked.
385
- * The INTERNAL resolution (`loopStrategyConfigSchema`) still validates the three built-in names
386
- * via `z.enum`; a custom never passes through it (it enters by the seam, not by name).
387
- */
388
- readonly name: string;
389
- /** Hard ceiling on rounds — guarantees termination (enforced by the runner since M54). */
390
- readonly maxIterations: number;
391
- /** True ⇒ re-enter for another round; false ⇒ terminate. The runner caps it at `maxIterations`. */
392
- shouldContinue(outcome: LoopOutcome): boolean;
393
- }
394
- /** Default round ceiling when `@MainLoop` declares no `maxIterations` (EC-3: finite, never Infinity). */
395
- declare const DEFAULT_MAX_ITERATIONS = 8;
396
- /** Serializable config for a LoopStrategy. SSoT per type-safety.md (ADR D3). */
397
- declare const loopStrategyConfigSchema: z.ZodObject<{
398
- name: z.ZodEnum<{
399
- "simple-chat": "simple-chat";
400
- "plan-act-reflect": "plan-act-reflect";
401
- react: "react";
402
- }>;
403
- maxIterations: z.ZodNumber;
404
- }, z.core.$strip>;
405
- type LoopStrategyConfig = z.infer<typeof loopStrategyConfigSchema>;
406
- /**
407
- * Map a `@MainLoop` strategy + ceiling to a concrete {@link LoopStrategy}.
408
- *
409
- * - `simple-chat` ⇒ exactly one round (`shouldContinue` always false).
410
- * - `react` ⇒ continue while the round ended on `tool-calls` AND the ceiling has not been reached
411
- * (`round < maxIterations`) — the reflection is `noop` (no feedback), so the strategy IS the gate.
412
- * - `plan-act-reflect` ⇒ DEFER continuation to the reflection (V4-S): `shouldContinue` is
413
- * `round < maxIterations`, so the loop continues iff the (custom) `ReflectionStrategy` returns
414
- * `continue: true` within the ceiling — letting a reflection extend even a terminal (`stop`)
415
- * round (e.g. "you answered without editing — make the edit now"). Backward-compatible with the
416
- * default `ladderReflectionStrategy`, which itself returns `continue: true` only on `tool-calls`,
417
- * so the observable behavior with the shipped ladder is unchanged.
418
- *
419
- * Throws (Zod) when `maxIterations < 1` — fail fast, never a silent infinite loop.
420
- */
421
- declare function resolveLoopStrategy(strategy: string, maxIterations?: number): LoopStrategy;
422
-
423
- interface DelegationResult {
424
- response: string;
425
- toolCalls: {
426
- id: string;
427
- name: string;
428
- input: unknown;
429
- output: string;
430
- }[];
431
- cost: number;
432
- tokens: number;
433
- /** V4-N: split token usage accumulated across rounds (`tokens` stays as the total). Absent for the single-shot path. */
434
- tokensInput?: number;
435
- tokensOutput?: number;
436
- /** V4-O: reasoning/cache token buckets accumulated across rounds (0 on any loop-driven run; the loop seeds them). Optional for type compat. */
437
- reasoningTokens?: number;
438
- cacheReadTokens?: number;
439
- cacheWriteTokens?: number;
440
- /** Rounds the reflective loop ran (set by `runReflectiveLoop`; absent for the single-shot path). */
441
- rounds?: number;
442
- /**
443
- * The loop's terminal reason (set by `runReflectiveLoop`): `'stop'`/`'length'` natural end,
444
- * `'step_limit'` (hit maxIterations), `'no_progress'` (stuck). Absent for the single-shot path. (V4-D)
445
- */
446
- finishReason?: LoopFinishReason;
447
- }
448
- /**
449
- * DELEGATION budget exceeded — the dollar cost of a delegated agent.
450
- *
451
- * ## Why the name changed in M91
452
- *
453
- * It was called `BudgetExceededError` and **shadowed** the SDK class of the same name, which belongs
454
- * to another domain: context-WINDOW budget (`budgetName`/`window`/`mode`) against DELEGATION budget
455
- * (`agentName`/`actualCost`). Since the consumer holds an unbreakable rule never to import
456
- * `@theokit/sdk` directly, it **could never reach the SDK's** — and an `instanceof` against this
457
- * barrel silently matched the wrong domain.
458
- *
459
- * It is the failure mode M73 documented in `auth-parity.test.ts`: when two classes compete for the
460
- * same name, no behavioural test goes red — only an identity `toBe` catches it.
461
- *
462
- * `subpath-coverage.test.ts` recorded the collision as a `gap` on `./errors`, with the reason written
463
- * down and the acknowledgement that renaming was breaking and out of M78's scope. M91 paid the bill.
464
- */
465
- /**
466
- * M80 — extends {@link TheokitAgentError}, not plain `Error`.
467
- *
468
- * `isTransientError` is defined over `TheokitAgentError`, so a class outside that hierarchy is
469
- * INVISIBLE to it and the only recourse left to a consumer is matching on message text. `code` is
470
- * stable across a rename; `isRetryable` is DECLARED, because a default would be a retry policy
471
- * nobody chose.
472
- */
473
- declare class DelegationBudgetExceededError extends TheokitAgentError {
474
- readonly agentName: string;
475
- readonly actualCost: number;
476
- readonly budgetLimit: number;
477
- readonly name = "DelegationBudgetExceededError";
478
- constructor(agentName: string, actualCost: number, budgetLimit: number);
479
- }
480
- /**
481
- * @deprecated Use {@link DelegationBudgetExceededError}. The alias is kept for one major so anyone
482
- * catching by the old name is not broken; it is the **same** class, not a copy — `instanceof` still
483
- * holds in both directions, and a referential-identity test (`toBe`) pins that.
484
- *
485
- * knip reports the value/type pair as a duplicate export, which is exactly what a deprecation
486
- * alias is; `rules.duplicates` is "warn" for that reason. Removing it is the breaking change it
487
- * exists to avoid.
488
- */
489
- declare const BudgetExceededError: typeof DelegationBudgetExceededError;
490
- /** @deprecated Use {@link DelegationBudgetExceededError}. */
491
- type BudgetExceededError = DelegationBudgetExceededError;
492
- /**
493
- * M80 — extends {@link TheokitAgentError}, not plain `Error`.
494
- *
495
- * `isTransientError` is defined over `TheokitAgentError`, so a class outside that hierarchy is
496
- * INVISIBLE to it and the only recourse left to a consumer is matching on message text. `code` is
497
- * stable across a rename; `isRetryable` is DECLARED, because a default would be a retry policy
498
- * nobody chose.
499
- */
500
- declare class DelegationError extends TheokitAgentError {
501
- readonly agentName: string;
502
- readonly cause: unknown;
503
- readonly name = "DelegationError";
504
- constructor(agentName: string, cause: unknown);
505
- }
506
-
507
- /**
508
- * ReflectionStrategy — composes INTO the loop between rounds (the loop calls
509
- * `reflect()` then `LoopStrategy.shouldContinue()`).
510
- *
511
- * `'plan-act-reflect'` resolves to the `'ladder'` default shipped here; a custom
512
- * strategy may be supplied (OCP — plan Drawback #2). `reflect()` is pure (no
513
- * I/O, no LLM) — it inspects the round's outcome and returns feedback to inject
514
- * into the next round's prompt plus a `continue` hint. The hard round ceiling
515
- * lives in `LoopStrategy.shouldContinue` (maxIterations), NOT here.
516
- */
517
-
518
- /** Result of reflecting on a completed round. */
519
- interface ReflectionResult {
520
- /** Optional text prepended to the next round's prompt. */
521
- readonly feedback?: string;
522
- /** Hint: should the loop reflect-and-continue? (the ceiling still bounds it) */
523
- readonly continue: boolean;
524
- }
525
- /**
526
- * V4-K: a per-run mutable scratch bag threaded to every `reflect()` call within one
527
- * `runReflectiveLoopStream` run, so a STATEFUL strategy can accumulate cumulative state
528
- * (counters, one-shot flags) across rounds. The framework owns the lifecycle (creates
529
- * one per run, passes the SAME ref each round) but writes NOTHING into it — the strategy
530
- * owns the contents. Generic by design: the framework cannot know app semantics (e.g.
531
- * what an "edit" is). A consumer narrows it locally (`ctx as MyState`).
532
- */
533
- type ReflectionContext = Record<string, unknown>;
534
- /** Pluggable between-round reflection. Pure — never performs I/O. */
535
- interface ReflectionStrategy {
536
- /** Strategy identifier (e.g. `'ladder'`). */
537
- readonly name: string;
538
- /**
539
- * Inspect the round outcome; return feedback + continue hint. `ctx` (V4-K) is the
540
- * per-run mutable scratch — optional for backward compatibility (shipped strategies
541
- * ignore it; stateful custom strategies accumulate in it across rounds).
542
- */
543
- reflect(outcome: LoopOutcome, ctx?: ReflectionContext): ReflectionResult;
544
- }
545
- /** Serializable config for a ReflectionStrategy. SSoT per type-safety.md (ADR D3). */
546
- declare const reflectionStrategyConfigSchema: z.ZodObject<{
547
- name: z.ZodString;
548
- }, z.core.$strip>;
549
- type ReflectionStrategyConfig = z.infer<typeof reflectionStrategyConfigSchema>;
550
- /**
551
- * The default `'ladder'` reflection (what `'plan-act-reflect'` resolves to).
552
- *
553
- * Continues with bounded templated feedback while the round ended on
554
- * `tool-calls`; terminates on any terminal `finishReason` (`stop`/`error`/
555
- * `length`). The feedback is a short fixed template (bounded — EC-5; context
556
- * growth is the SDK's responsibility, not the loop's).
557
- */
558
- declare const ladderReflectionStrategy: ReflectionStrategy;
559
- /**
560
- * No-op reflection for `'react'` (multi-round WITHOUT reflection feedback).
561
- *
562
- * Returns `{ continue: true }` (no feedback) so the round-continuation decision
563
- * is delegated entirely to `LoopStrategy.shouldContinue` (i.e. `react` loops
564
- * while `finishReason === 'tool-calls'` under the ceiling). NOTE: the plan's
565
- * pseudo-code (Files-to-edit) sketched `{ continue: false }`, which would make
566
- * `react` single-shot — that contradicts the plan's own Deep Dives ("`react`
567
- * still multi-rounds while finishReason==='tool-calls'"); `continue: true` is
568
- * the behavior the resolved react LoopStrategy requires.
569
- */
570
- declare const noopReflectionStrategy: ReflectionStrategy;
571
-
572
- /**
573
- * runReflectiveLoop — the multi-round reflective driver that gives `@MainLoop`
574
- * its runtime (closes the metadata-only gap, V4-A / plan ADR D2).
575
- *
576
- * Per round it consumes ONE SDK stream turn (the model call stays in the SDK —
577
- * the factory is `createSdkAgentStream(...)`, injected for testability), derives
578
- * a {@link LoopOutcome}, asks the {@link ReflectionStrategy} for feedback, then
579
- * the {@link LoopStrategy} whether to continue. Bounded by `maxIterations`
580
- * (forced terminal at the ceiling — never an infinite loop). The bridge owns the
581
- * loop; the SDK owns the model call (sdk-runtime.md / ADR 0031 — no second runtime).
582
- *
583
- * `runReflectiveLoop` is INTERNAL (not re-exported from the package barrel,
584
- * Drawback #4) — consumed by `delegate()` (T2.2) and `AgentRunner` (T3.1).
585
- */
586
-
587
- /** One SDK stream turn: `createSdkAgentStream(...)` returns this shape. */
588
- /**
589
- * Opens one round's SDK stream. `opts.disableTools` (step-cap force-close) asks the factory to
590
- * gate tools OFF for THIS round (the SDK adapter maps it to `tool_choice:"none"` at send-time, so a
591
- * cached agent — whose tools can't be un-registered — is still forced to a text summary). Optional +
592
- * ignored by injected test factories ⇒ backward-compatible.
593
- */
594
- type RoundStreamFactory = (message: string, sessionId: string, opts?: {
595
- disableTools?: boolean;
596
- }) => AsyncIterable<StreamEvent>;
597
-
598
- /**
599
- * Multi-agent orchestration runtime.
600
- *
601
- * Provides `delegate()` — a function that lets a parent agent invoke a
602
- * sub-agent and receive its result. Handles budget clamping (D4), tool sharing,
603
- * toolbox auto-instantiation (EC-1), and routes the resolved `@MainLoop` strategy
604
- * through `runReflectiveLoop` — the SAME driver `AgentRunner.run()` uses, so both
605
- * on-ramps are one runtime (ADR D4). `simple-chat` ⇒ `shouldContinue:()=>false`
606
- * ⇒ exactly one round; `react`/`plan-act-reflect` ⇒ multi-round reflective loop.
607
- */
608
-
609
- interface DelegateOptions {
610
- /**
611
- * M81 — wall-clock cap for the delegation, in milliseconds. Absent ⇒ no clock cap.
612
- *
613
- * A DIFFERENT guard from `budget`: money is spent by work that progresses, and a delegation that
614
- * HANGS burns clock without spending a cent. A consumer wrote its own timeout race with its own
615
- * typed error because this was missing. Exceeding it raises `DelegationTimeoutError`, which —
616
- * unlike the budget errors — is marked retryable, because a hang is often transient.
617
- */
618
- readonly timeoutMs?: number;
619
- /** Max USD for this sub-agent call. */
620
- budget?: number;
621
- /** Parent's remaining budget (for clamping). */
622
- parentBudgetRemaining?: number;
623
- /** Parent's tools (for sharing — sub-agent inherits these). */
624
- parentTools?: CompiledTool[];
625
- /**
626
- * Parent's hooks. The member inherits them, and inheritance may only TIGHTEN: both
627
- * `pre_tool_call` gates run and the first refusal wins, so a member cannot widen what the parent
628
- * refused.
629
- *
630
- * Symmetric with `parentTools` on purpose — `delegate` already carried the parent's tools and its
631
- * budget into the member's run and left its AUTHORITY behind, which is how a squad member could
632
- * call a tool the supervisor had vetoed. The failure was silent: nothing threw, and the member's
633
- * own suite passed because the member never declared the gate.
634
- *
635
- * To scope a member differently, pass its handlers on `spec.compiled.hooks` — they compose with
636
- * these rather than replacing them, because a widening that a call site cannot see is the state
637
- * this option exists to remove.
638
- */
639
- parentHooks?: HookHandlers;
640
- /**
641
- * LLM API key (inherited from parent).
642
- *
643
- * `null` says the provider takes NO credential — a model on the developer's own machine
644
- * (usetheokit/theokit#423). It is a distinct value from `''` on purpose: an empty string is what
645
- * an unset environment variable produces, and treating the two alike is how a typo becomes an
646
- * unauthenticated run. `undefined` still means the caller supplied nothing and is still refused.
647
- */
648
- apiKey?: string | null;
649
- /** Session ID override (default: crypto.randomUUID for isolation). */
650
- sessionId?: string;
651
- /** Cancellation — aborts stop the reflective loop from re-entering. */
652
- signal?: AbortSignal;
653
- /** Per-run model override (`?? SubAgent @Agent model`). */
654
- model?: string;
655
- /**
656
- * Per-run working directory → `Agent.create({ local: { cwd } })`.
657
- *
658
- * B-073 — if you point this at a git worktree you created, the sub-agent runs in a checkout with
659
- * none of the repository's gitignored files: no `.env`, no local config, no credentials. This
660
- * layer does not copy them, and it has no `.worktreeinclude` — the reference's one-file answer to
661
- * the same problem — because it never creates a worktree in the first place (measured with
662
- * controls: zero `git worktree` calls, zero `isolation` options; held falsifiable by
663
- * `tests/unit/this-layer-creates-no-worktree.test.ts`, which goes red the day that changes).
664
- *
665
- * Stated here rather than left to be discovered, because the failure does not look like a missing
666
- * file — it looks like a broken agent.
667
- */
668
- cwd?: string;
669
- /** Per-run plugins (e.g. a read-only permission gate for an explore sub-agent). */
670
- plugins?: PluginsSettings;
671
- /** Per-run provider routing (e.g. OpenRouter). */
672
- providers?: ProviderRoutingSettings;
673
- /** Per-run sub-agent definitions. */
674
- agents?: Record<string, AgentDefinition>;
675
- /** Per-run SDK budget tracker (inner tool-loop cap). */
676
- budgetTracker?: BudgetTracker;
677
- /** Per-run pre-built SDK tools forwarded raw (V4-Q). */
678
- sdkTools?: readonly CustomTool[];
679
- /** Per-round transient retry (V4-P). */
680
- retry?: RetryOptions;
681
- /** Custom between-round reflection (default: ladder for `plan-act-reflect`, else noop). */
682
- reflection?: ReflectionStrategy;
683
- /** Per-run loop-ceiling override (`?? SubAgent @MainLoop maxIterations`). */
684
- maxIterations?: number;
685
- /**
686
- * Called BEFORE the sub-agent runs. Returns the input the sub-agent will receive — return
687
- * `ctx.input` unchanged, or a rewritten string (e.g. inject a persona). A transform, not a veto.
688
- */
689
- onDelegationStart?: (ctx: {
690
- subAgent: string;
691
- input: string;
692
- }) => string | Promise<string>;
693
- /**
694
- * Called AFTER the sub-agent completes. Returns the result the supervisor sees — return
695
- * `ctx.result` unchanged, or a transformed one (e.g. redact, score, re-wrap).
696
- */
697
- onDelegationComplete?: (ctx: {
698
- subAgent: string;
699
- result: DelegationResult;
700
- }) => DelegationResult | Promise<DelegationResult>;
701
- /**
702
- * Injected stream factory (parity with `AgentRunnerRunOptions.streamFactory`) — drives the loop
703
- * directly instead of the SDK adapter (tests / custom transport). Absent ⇒ `createSdkAgentStream`.
704
- */
705
- streamFactory?: RoundStreamFactory;
706
- }
707
- /**
708
- * Delegate a task to a sub-agent and collect its result.
709
- *
710
- * - Budget clamping: `min(parentBudgetRemaining, budget)` (D4)
711
- * - Tool sharing: parent tools merged with sub-agent tools (sub wins on collision)
712
- * - Toolbox auto-instantiation: sub-agent toolboxes instantiated without DI (EC-1)
713
- * - Session isolation: each delegation gets a unique session ID (EC-4)
714
- * - `@MainLoop` strategy runtime: routes through `runReflectiveLoop` (the same loop
715
- * `AgentRunner.run` uses — one runtime for both on-ramps, ADR D4). The runtime
716
- * metric (`THEO_AGENT_MAINLOOP_RUNTIME_APPLIED`) + typed-error + cumulative budget
717
- * all live in the shared driver, so they fire identically on both paths.
718
- */
719
- /**
720
- * What `delegate` needs from a sub-agent: a name and already-compiled options (built by
721
- * `applyCapabilities`). Compatible with {@link AgentRunnerSpec} — one spec drives both on-ramps.
722
- */
723
- interface SubAgentSpec {
724
- readonly name: string;
725
- readonly compiled: CompiledAgentOptions;
726
- /** Loop strategy (`@MainLoop({ strategy })`); absent ⇒ the same `'simple-chat'` default. */
727
- readonly strategy?: MainLoopMeta['strategy'];
728
- /** Loop ceiling (`@MainLoop({ maxIterations })`); a per-run override still wins. */
729
- readonly maxIterations?: number;
730
- }
731
- declare function delegate(spec: SubAgentSpec, message: string, opts?: DelegateOptions): Promise<DelegationResult>;
732
-
733
- /**
734
- * M25 (theokit-ai-first) — background delegation + task-completion scoring.
735
- *
736
- * Two THIN wrappers over the M12 `delegate` (ADR 0038/0040): no new orchestration engine, no second
737
- * loop, no new store. `delegateBackground` kicks off a sub-agent without blocking the supervisor and
738
- * hands back a handle to await later. `delegateWithScoring` runs `delegate`, scores the result with
739
- * an injected scorer, and re-delegates with the scorer's feedback until it passes or `maxRounds` is
740
- * hit. The `delegate` implementation is injectable (`delegateFn`) so this is testable without a
741
- * SubAgent class or an LLM — and so it NEVER re-implements the delegation runtime.
742
- */
743
-
744
- /**
745
- * M81 — anything that can run a delegation.
746
- *
747
- * The reach gap this closes: both wrappers took a `SubAgentSpec` produced by the capability
748
- * compiler, so a consumer holding an SDK `SubAgent` or `Squad` could not feed them. That is why the
749
- * scoring loop — the layer's highest-value piece — had ZERO adoption in a product that runs an
750
- * explicit review pass: it was unreachable from the primitives that product actually holds.
751
- *
752
- * An SDK `SubAgent` or `Squad` satisfies this by having `run`. So does a test double, which is why
753
- * the loop is now testable without a compiler, a class or an LLM.
754
- */
755
- interface DelegationPort {
756
- run(message: string): Promise<DelegationResult>;
757
- }
758
- /** What both wrappers accept: the compiled spec (unchanged) or the port (M81, additive). */
759
- type DelegationTarget = SubAgentSpec | DelegationPort;
760
- /** The delegation primitive both wrappers drive. Defaults to the M12 {@link delegate}. */
761
- type DelegateFn = (subAgent: SubAgentSpec, message: string, opts?: DelegateOptions) => Promise<DelegationResult>;
762
- /** A running background delegation the supervisor can await/poll later. */
763
- interface BackgroundDelegation {
764
- /** Await the sub-agent's result (or rejection). Idempotent — returns the same settled promise. */
765
- wait(): Promise<DelegationResult>;
766
- /** Whether the underlying delegation has resolved or rejected. */
767
- settled(): boolean;
768
- }
769
- /**
770
- * Start a sub-agent WITHOUT blocking the supervisor. Returns immediately with a handle; the
771
- * supervisor keeps working and calls `wait()` when it needs the result. A thin async wrapper over
772
- * `delegate` — not a scheduler (Top-risk 1). Rejections are still observable via `wait()`.
773
- */
774
- declare function delegateBackground(subAgent: DelegationTarget, message: string, opts?: DelegateOptions & {
775
- delegateFn?: DelegateFn;
776
- }): BackgroundDelegation;
777
- /** A scorer's verdict on a sub-agent result. `feedback` is fed back into the next round on failure. */
778
- interface ScoreVerdict {
779
- pass: boolean;
780
- /** Optional numeric score (0..1) for logging/telemetry. */
781
- score?: number;
782
- /** Guidance appended to the next delegation when `pass` is false. */
783
- feedback?: string;
784
- }
785
- /** Scores a sub-agent result. Opt-in (Top-risk 2) — the caller supplies it, and pays its cost. */
786
- type Scorer = (result: DelegationResult) => ScoreVerdict | Promise<ScoreVerdict>;
787
- /** The outcome of a scored delegation: the final result plus the per-round verdict trail. */
788
- interface ScoredDelegation {
789
- result: DelegationResult;
790
- /** Rounds actually run (1..maxRounds). */
791
- rounds: number;
792
- /** Whether the final round passed the scorer. */
793
- passed: boolean;
794
- /** The verdict from each round, in order. */
795
- verdicts: ScoreVerdict[];
796
- }
797
- /**
798
- * Run `delegate`, score the result, and re-delegate with the scorer's feedback until it passes or
799
- * `maxRounds` is reached. Each round is ONE `delegate` call — no second loop, no new store. Returns
800
- * the final result (passing, or the last attempt) with the per-round verdict trail.
801
- */
802
- declare function delegateWithScoring(subAgent: DelegationTarget, message: string, opts: DelegateOptions & {
803
- scorer: Scorer;
804
- maxRounds?: number;
805
- delegateFn?: DelegateFn;
806
- feedbackTemplate?: (message: string, feedback: string) => string;
807
- }): Promise<ScoredDelegation>;
808
-
809
- export { noopReflectionStrategy as $, type AgentStopReason as A, type BackgroundDelegation as B, type CheckpointSavedEvent as C, type DelegationTarget as D, type ErrorEvent as E, type FileEditEvent as F, type ThinkingEvent as G, type ToolCallEvent as H, type IterationEvent as I, type ToolResultEvent as J, delegate as K, type LoopStrategy as L, delegateBackground as M, delegateWithScoring as N, isApprovalRequired as O, type PartialToolCallEvent as P, isDone as Q, type ReflectionStrategy as R, type StreamEvent as S, type TextDeltaEvent as T, isError as U, isPartialToolCall as V, isTextDelta as W, isToolCall as X, isToolResult as Y, ladderReflectionStrategy as Z, loopStrategyConfigSchema as _, type DelegateOptions as a, presentUIMessageStream as a0, reflectionStrategyConfigSchema as a1, resolveLoopStrategy as a2, streamAgentResponse as a3, type MaskError as a4, type RoundStreamFactory as b, type DelegationResult as c, type AgentStreamEvent as d, type AgentTurnMetadata as e, type ApprovalRequiredEvent as f, type ArtifactChunkEvent as g, type ArtifactStartEvent as h, BudgetExceededError as i, DEFAULT_MAX_ITERATIONS as j, type DelegateFn as k, DelegationBudgetExceededError as l, DelegationError as m, type DelegationPort as n, type DoneEvent as o, type LoopFinishReason as p, type LoopOutcome as q, type LoopStrategyConfig as r, type ReflectionContext as s, type ReflectionResult as t, type ReflectionStrategyConfig as u, type RunStartedEvent as v, type ScoreVerdict as w, type ScoredDelegation as x, type Scorer as y, type StateUpdateEvent as z };