@theokit/agents 10.1.0 → 11.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 (56) hide show
  1. package/CHANGELOG.md +356 -0
  2. package/LICENSE +2 -2
  3. package/README.md +6 -5
  4. package/dist/{agent-compiler-CIPQkehU.d.ts → agent-compiler-tetgj6zR.d.ts} +3 -172
  5. package/dist/{agent-handle-Dgi4ZGbg.d.ts → agent-handle-rEWdERuv.d.ts} +113 -2
  6. package/dist/auth.js +1 -1
  7. package/dist/{bridge-entry-emr2PSXC.d.ts → bridge-entry-DPm1C5li.d.ts} +83 -200
  8. package/dist/bridge.d.ts +8 -7
  9. package/dist/bridge.js +4 -3
  10. package/dist/{chunk-CKRM5Q2K.js → chunk-2I6DQUJP.js} +249 -47
  11. package/dist/chunk-2I6DQUJP.js.map +1 -0
  12. package/dist/{chunk-M6HMASZC.js → chunk-7PNUTDBQ.js} +109 -14
  13. package/dist/chunk-7PNUTDBQ.js.map +1 -0
  14. package/dist/{chunk-QXGSF6WX.js → chunk-D2EFYZBV.js} +1 -1
  15. package/dist/{chunk-QXGSF6WX.js.map → chunk-D2EFYZBV.js.map} +1 -1
  16. package/dist/{chunk-4VHCH6IZ.js → chunk-LLIERPF3.js} +14 -1
  17. package/dist/chunk-LLIERPF3.js.map +1 -0
  18. package/dist/chunk-OXNDJSAJ.js +59 -0
  19. package/dist/chunk-OXNDJSAJ.js.map +1 -0
  20. package/dist/{chunk-QJN2LLPF.js → chunk-ZQOKIZCI.js} +284 -164
  21. package/dist/chunk-ZQOKIZCI.js.map +1 -0
  22. package/dist/client-react.d.ts +24 -2
  23. package/dist/client-react.js +2 -1
  24. package/dist/client-react.js.map +1 -1
  25. package/dist/client.d.ts +99 -5
  26. package/dist/client.js +3 -1
  27. package/dist/config.d.ts +2 -2
  28. package/dist/config.js +2 -2
  29. package/dist/{define-agent-BO5QSjV8.d.ts → define-agent-BnH1MBxs.d.ts} +16 -1
  30. package/dist/{delegation-scoring-CDvtrYKd.d.ts → delegation-scoring-CQtF2Zaf.d.ts} +345 -11
  31. package/dist/hooks.js +2 -2
  32. package/dist/hooks.js.map +1 -1
  33. package/dist/index.d.ts +54 -9
  34. package/dist/index.js +17 -3
  35. package/dist/index.js.map +1 -1
  36. package/dist/mcp-health.d.ts +66 -1
  37. package/dist/mcp-health.js +32 -1
  38. package/dist/mcp-health.js.map +1 -1
  39. package/dist/pty.js.map +1 -1
  40. package/dist/session.d.ts +58 -1
  41. package/dist/session.js +34 -1
  42. package/dist/session.js.map +1 -1
  43. package/dist/testing.d.ts +3 -2
  44. package/dist/testing.js +1 -1
  45. package/dist/tools.d.ts +4 -2
  46. package/dist/tools.js +5 -4
  47. package/dist/tools.js.map +1 -1
  48. package/dist/types-C16Wuh9E.d.ts +173 -0
  49. package/dist/usage.d.ts +94 -1
  50. package/dist/usage.js +5 -1
  51. package/dist/usage.js.map +1 -1
  52. package/package.json +23 -10
  53. package/dist/chunk-4VHCH6IZ.js.map +0 -1
  54. package/dist/chunk-CKRM5Q2K.js.map +0 -1
  55. package/dist/chunk-M6HMASZC.js.map +0 -1
  56. package/dist/chunk-QJN2LLPF.js.map +0 -1
@@ -1,27 +1,350 @@
1
1
  import { PluginsSettings, ProviderRoutingSettings, AgentDefinition, BudgetTracker, CustomTool } from '@theokit/sdk';
2
2
  import { RetryOptions } from '@theokit/sdk/retry';
3
- import { C as CompiledAgentOptions, a as MainLoopMeta, b as CompiledTool } from './agent-compiler-CIPQkehU.js';
3
+ import { C as CompiledAgentOptions, a as CompiledTool } from './agent-compiler-tetgj6zR.js';
4
4
  import { TheokitAgentError } from '@theokit/sdk/errors';
5
5
  import { z } from 'zod';
6
+ import { b as MainLoopMeta } from './types-C16Wuh9E.js';
7
+ import { WireChunk } from '@theokit/presenter/wire';
6
8
  import { H as HookHandlers } from './hook-handlers-Cw2FsnE5.js';
7
9
 
8
10
  /**
9
- * SSE streaming handler Web Standard Response with ReadableStream.
11
+ * Typed discriminated union for agent SSE stream events.
10
12
  *
11
- * Per ADR D4: SSE is the v1 transport.
12
- * Per EC-2: uses ReadableStream with controller.enqueue() instead of res.write().
13
- * Works natively on Node, Bun, Deno, CF Workers.
13
+ * Every event has a `type` field for discrimination.
14
+ * Clients narrow via `if (event.type === 'text_delta') event.content`.
14
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
+
15
330
  /** Minimal event shape matching SDK's SDKMessage discriminated union. */
16
331
  interface StreamEvent {
17
332
  type: string;
18
333
  [key: string]: unknown;
19
334
  }
20
335
  /**
21
- * Create a Web Standard Response that streams SSE events.
22
- * Each event becomes: `event: {type}\ndata: {json}\n\n`
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)
23
344
  */
24
- declare function streamAgentResponse(eventStream: AsyncIterable<StreamEvent>): Response;
345
+ declare function streamAgentResponse(eventStream: AsyncIterable<StreamEvent>, opts?: {
346
+ onError?: Parameters<typeof presentUIMessageStream>[1]['onError'];
347
+ }): Response;
25
348
 
26
349
  /**
27
350
  * LoopStrategy — the per-round terminal-decision contract that gives runtime to
@@ -160,6 +483,10 @@ declare class DelegationBudgetExceededError extends TheokitAgentError {
160
483
  * @deprecated Use {@link DelegationBudgetExceededError}. The alias is kept for one major so anyone
161
484
  * catching by the old name is not broken; it is the **same** class, not a copy — `instanceof` still
162
485
  * holds in both directions, and a referential-identity test (`toBe`) pins that.
486
+ *
487
+ * knip reports the value/type pair as a duplicate export, which is exactly what a deprecation
488
+ * alias is; `rules.duplicates` is "warn" for that reason. Removing it is the breaking change it
489
+ * exists to avoid.
163
490
  */
164
491
  declare const BudgetExceededError: typeof DelegationBudgetExceededError;
165
492
  /** @deprecated Use {@link DelegationBudgetExceededError}. */
@@ -316,8 +643,15 @@ interface DelegateOptions {
316
643
  * this option exists to remove.
317
644
  */
318
645
  parentHooks?: HookHandlers;
319
- /** LLM API key (inherited from parent). */
320
- apiKey?: string;
646
+ /**
647
+ * LLM API key (inherited from parent).
648
+ *
649
+ * `null` says the provider takes NO credential — a model on the developer's own machine
650
+ * (usetheokit/theokit#423). It is a distinct value from `''` on purpose: an empty string is what
651
+ * an unset environment variable produces, and treating the two alike is how a typo becomes an
652
+ * unauthenticated run. `undefined` still means the caller supplied nothing and is still refused.
653
+ */
654
+ apiKey?: string | null;
321
655
  /** Session ID override (default: crypto.randomUUID for isolation). */
322
656
  sessionId?: string;
323
657
  /** Cancellation — aborts stop the reflective loop from re-entering. */
@@ -466,4 +800,4 @@ declare function delegateWithScoring(subAgent: DelegationTarget, message: string
466
800
  feedbackTemplate?: (message: string, feedback: string) => string;
467
801
  }): Promise<ScoredDelegation>;
468
802
 
469
- export { streamAgentResponse as A, type BackgroundDelegation as B, type DelegationTarget as D, type LoopStrategy as L, type ReflectionStrategy as R, type StreamEvent as S, type DelegateOptions as a, type RoundStreamFactory as b, type DelegationResult as c, BudgetExceededError as d, DEFAULT_MAX_ITERATIONS as e, type DelegateFn as f, DelegationBudgetExceededError as g, DelegationError as h, type DelegationPort as i, type LoopFinishReason as j, type LoopOutcome as k, type LoopStrategyConfig as l, type ReflectionContext as m, type ReflectionResult as n, type ReflectionStrategyConfig as o, type ScoreVerdict as p, type ScoredDelegation as q, type Scorer as r, delegate as s, delegateBackground as t, delegateWithScoring as u, ladderReflectionStrategy as v, loopStrategyConfigSchema as w, noopReflectionStrategy as x, reflectionStrategyConfigSchema as y, resolveLoopStrategy as z };
803
+ 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 };
package/dist/hooks.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  readSecureJson,
3
3
  writeSecureJson
4
- } from "./chunk-QXGSF6WX.js";
4
+ } from "./chunk-D2EFYZBV.js";
5
5
  import {
6
6
  hooksPlugin,
7
7
  inheritHooks
@@ -306,7 +306,7 @@ function fenceHookOutput(output) {
306
306
  const nonce = randomBytes(8).toString("hex");
307
307
  const open = `<hook-output nonce="${nonce}">`;
308
308
  const close = `</hook-output nonce="${nonce}">`;
309
- const escaped = output.replaceAll(close, close.replace("<", "&lt;"));
309
+ const escaped = output.replaceAll(close, close.replaceAll("<", "&lt;"));
310
310
  return `${open}
311
311
  ${escaped}
312
312
  ${close}`;
package/dist/hooks.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/hooks/hook-spec.ts","../src/hooks/hook-fingerprint.ts","../src/hooks/hook-runner.ts","../src/hooks/approval-store.ts"],"mappings":";;;;;;;;;;;;;AAAA,SAASA,mBAAmB;AAG5B,SAASC,yBAAyB;AAClC,SAASC,SAAS;;;ACJlB,SAASC,kBAAkB;AAsC3B,IAAMC,kBAAkB;AASjB,SAASC,gBAAgBC,UAAsB;AACpD,QAAMC,YAAY;IAChBD,SAASE;IACTF,SAASG;IACTH,SAASI,WAAW;IACpBC,OAAOL,SAASM,SAAS;IACzBC,KAAKT,eAAAA;AACP,SAAOU,WAAW,QAAA,EAAUC,OAAOR,WAAW,MAAA,EAAQS,OAAO,KAAA;AAC/D;AARgBX;;;AC/ChB,SAASY,aAAa;AA+Bf,IAAMC,mBAAmB;AAQzB,IAAMC,kBAAkB;AAGxB,IAAMC,0BAA0B;AAgCvC,eAAsBC,eAAeC,OAAmB;AACtD,SAAO,IAAIC,QAAuB,CAACC,aAAAA;AAcjC,UAAMC,QAAQC,MAAMJ,MAAMK,SAAS;MACjCC,KAAKN,MAAMM;MACXC,OAAO;;MAEPC,UAAU;MACVC,KAAKT,MAAMS;MACXC,OAAO;QAAC;QAAQ;QAAQ;;IAC1B,CAAA;AAEA,QAAIC,SAAS;AACb,QAAIC,SAAS;AACb,QAAIC,YAAY;AAChB,QAAIC,WAAW;AACf,QAAIC,UAAU;AAEd,UAAMC,UAAU,wBAACC,SAAiBC,UAAAA;AAChC,UAAID,QAAQE,UAAUvB,kBAAkB;AACtCiB,oBAAY;AACZ,eAAOI;MACT;AACA,YAAMG,OAAOH,UAAUC,MAAMG,SAAS,MAAA;AACtC,UAAID,KAAKD,UAAUvB,iBAAkB,QAAOwB;AAC5CP,kBAAY;AACZ,aAAOO,KAAKE,MAAM,GAAG1B,gBAAAA;IACvB,GATgB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,QAAAA,CAAAA,EAAW,GAAG;AAChF,WAAK,SAAS+B,OAAAA;IAChB;EACF;;;;;;;EAQA,QAAK;AACH,UAAM,EAAEQ,OAAOC,MAAK,IAAKC,eACvB,KAAKjC,MACL,CAACkC,QAAAA;AACC,YAAMC,SAAkBC,KAAKC,MAAMH,GAAAA;AACnC,UAAI,CAACI,MAAMC,QAAQJ,MAAAA,EAAS,OAAM,IAAIK,MAAM,uCAAA;AAC5C,aAAOL;IACT,GACA,CAAA,CAAE;AAEJ,SAAKlC,gBAAgB+B;AAErB,SAAK,WAAW,IAAIS,IAAIV,MAAMnB,IAAI,CAACD,MAAM;MAAC,GAAGA,EAAEL,KAAK,KAASK,EAAEE,WAAW;MAAIF;KAAE,CAAA;AAChF,WAAO,KAAK;EACd;EAEA,SAASY,SAAoC;AAC3CmB,oBAAgB,KAAK1C,MAAM,MAAM,GAAGoC,KAAKO,UAAU;SAAIpB,QAAQd,OAAM;OAAK,MAAM,CAAA,CAAA;CAAM;EACxF;AACF;","names":["randomBytes","TheokitAgentError","z","createHash","FIELD_SEPARATOR","hookFingerprint","identity","canonical","command","event","matcher","String","timeoutMs","join","createHash","update","digest","spawn","MAX_OUTPUT_BYTES","DRAIN_BUDGET_MS","CHAIN_BUDGET_MULTIPLIER","runHookCommand","input","Promise","resolve","child","spawn","command","cwd","shell","detached","env","stdio","stdout","stderr","truncated","timedOut","settled","capture","current","chunk","length","next","toString","slice","on","settle","exitCode","clearTimeout","timer","drainTimer","setTimeout","killGroup","pid","timeoutMs","undefined","code","stdin","end","process","kill","HOOK_EVENTS","DEFAULT_HOOK_TIMEOUT_MS","DEFAULT_CONTINUATION_BUDGET","hookSpecSchema","z","object","event","enum","command","string","min","refine","value","test","message","matcher","optional","timeout_ms","number","int","positive","default","strict","HookSpecError","TheokitAgentError","name","code","isRetryable","parseHookSpecs","input","parsed","array","safeParse","success","error","issues","map","issue","path","join","data","IGNORE_WARNING","undefined","WIRED_EVENTS","Set","buildHookHandlers","specs","options","warn","onWarn","trusted","length","String","fingerprintOf","fingerprint","hookFingerprint","runnable","filter","spec","approved","has","identityOf","handlers","chainBudgetMs","Math","max","CHAIN_BUDGET_MULTIPLIER","preHooks","pre_tool_call","ctx","started","Date","now","onVeto","tool","reason","block","matches","result","runHookCommand","cwd","timeoutMs","stdin","JSON","stringify","args","env","exitCode","fenceHookOutput","stdout","stderr","postHooks","post_tool_call","truncated","transformHooks","transform_tool_result","buildTransformHandler","OBSERVATIONAL_EVENTS","list","fire","buildObservationalHandler","on_session_start","post_assistant_reply","toolName","RegExp","output","nonce","randomBytes","toString","open","close","escaped","replaceAll","replace","remaining","continuationBudget","results","out","targets","toolCalls","call","feedback","trim","realpathSync","join","resolve","slotOf","identity","event","matcher","canonicalScope","dir","realpathSync","resolve","HookApprovalStore","path","lastReadError","options","join","home","approvedFingerprints","scope","key","Set","values","filter","r","map","fingerprint","approvals","stateOf","inScope","some","hookFingerprint","slot","record","command","approve","records","set","undefined","approvedAt","Date","toISOString","revoke","delete","value","error","readSecureJson","raw","parsed","JSON","parse","Array","isArray","Error","Map","writeSecureJson","stringify"]}
1
+ {"version":3,"sources":["../src/hooks/hook-spec.ts","../src/hooks/hook-fingerprint.ts","../src/hooks/hook-runner.ts","../src/hooks/approval-store.ts"],"mappings":";;;;;;;;;;;;;AAAA,SAASA,mBAAmB;AAG5B,SAASC,yBAAyB;AAClC,SAASC,SAAS;;;ACJlB,SAASC,kBAAkB;AAsC3B,IAAMC,kBAAkB;AASjB,SAASC,gBAAgBC,UAAsB;AACpD,QAAMC,YAAY;IAChBD,SAASE;IACTF,SAASG;IACTH,SAASI,WAAW;IACpBC,OAAOL,SAASM,SAAS;IACzBC,KAAKT,eAAAA;AACP,SAAOU,WAAW,QAAA,EAAUC,OAAOR,WAAW,MAAA,EAAQS,OAAO,KAAA;AAC/D;AARgBX;;;AC/ChB,SAASY,aAAa;AA+Bf,IAAMC,mBAAmB;AAQzB,IAAMC,kBAAkB;AAGxB,IAAMC,0BAA0B;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heokitAgentError","z","createHash","FIELD_SEPARATOR","hookFingerprint","identity","canonical","command","event","matcher","String","timeoutMs","join","createHash","update","digest","spawn","MAX_OUTPUT_BYTES","DRAIN_BUDGET_MS","CHAIN_BUDGET_MULTIPLIER","runHookCommand","input","Promise","resolve","child","spawn","command","cwd","shell","detached","env","stdio","stdout","stderr","truncated","timedOut","settled","capture","current","chunk","length","next","toString","slice","on","settle","exitCode","clearTimeout","timer","drainTimer","setTimeout","killGroup","pid","timeoutMs","undefined","code","stdin","end","process","kill","HOOK_EVENTS","DEFAULT_HOOK_TIMEOUT_MS","DEFAULT_CONTINUATION_BUDGET","hookSpecSchema","z","object","event","enum","command","string","min","refine","value","test","message","matcher","optional","timeout_ms","number","int","positive","default","strict","HookSpecError","TheokitAgentError","name","code","isRetryable","parseHookSpecs","input","parsed","array","safeParse","success","error","issues","map","issue","path","join","data","IGNORE_WARNING","undefined","WIRED_EVENTS","Set","buildHookHandlers","specs","options","warn","onWarn","trusted","length","String","fingerprintOf","fingerprint","hookFingerprint","runnable","filter","spec","approved","has","identityOf","handlers","chainBudgetMs","Math","max","CHAIN_BUDGET_MULTIPLIER","preHooks","pre_tool_call","ctx","started","Date","now","onVeto","tool","reason","block","matches","result","runHookCommand","cwd","timeoutMs","stdin","JSON","stringify","args","env","exitCode","fenceHookOutput","stdout","stderr","postHooks","post_tool_call","truncated","transformHooks","transform_tool_result","buildTransformHandler","OBSERVATIONAL_EVENTS","list","fire","buildObservationalHandler","on_session_start","post_assistant_reply","toolName","RegExp","output","nonce","randomBytes","toString","open","close","escaped","replaceAll","remaining","continuationBudget","results","out","targets","toolCalls","call","feedback","trim","realpathSync","join","resolve","slotOf","identity","event","matcher","canonicalScope","dir","realpathSync","resolve","HookApprovalStore","path","lastReadError","options","join","home","approvedFingerprints","scope","key","Set","values","filter","r","map","fingerprint","approvals","stateOf","inScope","some","hookFingerprint","slot","record","command","approve","records","set","undefined","approvedAt","Date","toISOString","revoke","delete","value","error","readSecureJson","raw","parsed","JSON","parse","Array","isArray","Error","Map","writeSecureJson","stringify"]}
package/dist/index.d.ts CHANGED
@@ -1,16 +1,18 @@
1
1
  import { PluginsSettings, Plugin, ProviderRoutingSettings, AgentDefinition, BudgetTracker, CustomTool, GoalLoopAgent, GoalOptions, runGoalLoop, GoalEvent, GoalResult, InlineSkill, Agent as Agent$1, ListAgentsOptions, ListResult, SDKAgentInfo } from '@theokit/sdk';
2
2
  export { CustomTool, DiagnosticsSink, GenerateObjectError, GoalEvent, GoalLoopAgent, GoalOptions, GoalResult, JudgeCredentialError, JudgeResult, LayerOrderError, McpAuthConfig, McpHttpServerConfig, McpOAuthConfig, McpServerConfig, McpStdioServerConfig, Provider, RunEvent, SDKAgent, SessionRecord, Squad, StreamObjectError, Tool, ToolError, ToolResultContentBlock, TrustLevel, TrustPosture, TrustPostureInput, TrustSource, UngatedCapabilityError, Verdict, WiredEntity, applySecurityFloor, auditEnvReachability, foldLayers, recordWiring, resolveTrustPosture, setDiagnosticsSink, verifyLayerOrdering } from '@theokit/sdk';
3
- import { G as Guardrail, C as CompiledAgentOptions, a as MainLoopMeta, b as CompiledTool, R as ReasoningEffort, T as ToolOptions, A as ApprovalOptions, H as HumanInTheLoopOptions } from './agent-compiler-CIPQkehU.js';
4
- export { c as AgentOptions, B as BudgetOptions, d as CostBudgetExceededError, e as GuardrailAction, f as GuardrailPhase, g as GuardrailResult, h as GuardrailViolationError, i as MainLoopOptions, M as McpServersMap, P as PolicyHandler, j as SkillsRequestContext, S as SkillsSelection, k as TimeoutAction, l as ToolWalkResult, m as ToolboxOptions, n as ToolboxWalkResult, o as compileTools, r as resolveEnabledSkills } from './agent-compiler-CIPQkehU.js';
5
- import { C as ContextWindowOptions, S as SkillsOptions, A as AgentManifestEntry, H as HitlDecision, s as streamAgentUIMessages, a as ApprovalPosture } from './bridge-entry-emr2PSXC.js';
6
- export { b as APPROVAL_MODES, c as AfterToolCallContext, d as AgentBuilder, e as AgentDefinitionError, f as AgentExecutionContext, g as AgentManifest, h as AgentManifestSource, i as AgentManifestTool, j as AgentRoute, k as AgentRouteContext, l as AgentRunInfo, m as AgentStreamEvent, n as AgentTurnMetadata, o as AgentsPluginOptions, p as ApiErrorContext, q as ApiErrorDecision, r as ApiErrorPolicy, t as ApprovalMode, u as ApprovalRequiredEvent, v as ArtifactChunkEvent, w as ArtifactStartEvent, B as BeforeToolCallContext, x as CheckpointSavedEvent, y as CompiledContextWindow, z as ContextualTool, D as DefinitionOrThunk, E as DelegationTimeoutError, F as DoneEvent, G as EphemeralAgent, I as ErrorEvent, J as FileEditEvent, K as IterationEvent, L as LLMCallContext, M as McpApprovalSpec, N as McpFileError, O as McpRegistryConfig, P as McpRequestContext, Q as McpSelection, R as PartialToolCallEvent, T as ProcessInputContext, U as RunStartedEvent, V as SdkAgentHandle, W as SdkMessage, X as SdkSendOptions, Y as SdkTurnHandle, Z as Segment, _ as ShouldAutoApproveOptions, $ as StateUpdateEvent, a0 as TextDeltaEvent, a1 as ThinkingEvent, a2 as ToolCallEvent, a3 as ToolCallVeto, a4 as ToolHooks, a5 as ToolHooksPlugin, a6 as ToolResultEvent, a7 as WRITE_SCOPED_TOOLS, a8 as agentsPlugin, a9 as applyPosture, aa as buildModelSelection, ab as compileAgentModule, ac as compileContextWindow, ad as compileProjectContext, ae as compileSkills, af as createAgentExecutionContext, ag as createApiErrorHandler, ah as createSdkAgentStream, ai as createThinkTagExtractor, aj as createToolHooksPlugin, ak as extractThinkTagStream, al as generateAgentManifest, am as generateAgentRoutes, an as isAgentContext, ao as isApprovalRequired, ap as isDone, aq as isError, ar as isPartialToolCall, as as isTextDelta, at as isToolCall, au as isToolResult, av as loadMcpJson, aw as mcpRegistry, ax as mcpToolApprovals, ay as presentUIMessageStream, az as projectContextMetadataOnlyKnobs, aA as reasoningEffortOf, aB as resolveMcpServers, aC as runWithApiErrorHandling, aD as shouldAutoApprove, aE as toAgentFactory, aF as translateSdkEvent, aG as withClockCap, aH as withEphemeralAgent } from './bridge-entry-emr2PSXC.js';
3
+ import { b as MainLoopMeta, R as ReasoningEffort, T as ToolOptions, A as ApprovalOptions, H as HumanInTheLoopOptions } from './types-C16Wuh9E.js';
4
+ export { c as AgentOptions, B as BudgetOptions, d as MainLoopOptions, M as McpServersMap, e as PolicyHandler, f as TimeoutAction, g as ToolboxOptions } from './types-C16Wuh9E.js';
5
+ import { C as ContextWindowOptions, S as SkillsOptions, A as AgentManifestEntry, H as HitlDecision, s as streamAgentUIMessages, a as ApprovalPosture } from './bridge-entry-DPm1C5li.js';
6
+ export { b as APPROVAL_MODES, c as AfterToolCallContext, d as AgentBuilder, e as AgentDefinitionError, f as AgentExecutionContext, g as AgentManifest, h as AgentManifestSource, i as AgentManifestTool, j as AgentRoute, k as AgentRouteContext, l as AgentRunInfo, m as AgentsPluginOptions, n as ApiErrorContext, o as ApiErrorDecision, p as ApiErrorPolicy, q as ApprovalMode, B as BeforeToolCallContext, r as CompiledContextWindow, t as ContextualTool, D as DefinitionOrThunk, u as DelegationTimeoutError, E as EphemeralAgent, L as LLMCallContext, M as McpApprovalSpec, v as McpFileError, w as McpRegistryConfig, x as McpRequestContext, y as McpSelection, P as ProcessInputContext, z as SdkAgentHandle, F as SdkMessage, G as SdkSendOptions, I as SdkTurnHandle, J as Segment, K as ShouldAutoApproveOptions, T as ToolCallVeto, N as ToolHooks, O as ToolHooksPlugin, W as WRITE_SCOPED_TOOLS, Q as agentsPlugin, R as applyPosture, U as buildModelSelection, V as compileAgentModule, X as compileContextWindow, Y as compileProjectContext, Z as compileSkills, _ as createAgentExecutionContext, $ as createApiErrorHandler, a0 as createSdkAgentStream, a1 as createThinkTagExtractor, a2 as createToolHooksPlugin, a3 as extractThinkTagStream, a4 as generateAgentManifest, a5 as generateAgentRoutes, a6 as isAgentContext, a7 as loadMcpJson, a8 as mcpRegistry, a9 as mcpToolApprovals, aa as projectContextMetadataOnlyKnobs, ab as reasoningEffortOf, ac as resolveMcpServers, ad as runWithApiErrorHandling, ae as shouldAutoApprove, af as toAgentFactory, ag as translateSdkEvent, ah as withClockCap, ai as withEphemeralAgent } from './bridge-entry-DPm1C5li.js';
7
7
  import { TheokitAgentError } from '@theokit/sdk/errors';
8
8
  export * from '@theokit/sdk/errors';
9
9
  export { ConfigurationError, BudgetExceededError as WindowBudgetExceededError } from '@theokit/sdk/errors';
10
- import { S as SettingSourcesSelection } from './define-agent-BO5QSjV8.js';
11
- export { a as AGENT_BRAND, A as AgentDefinition, D as DefineAgentConfig, I as InferAgentInput, b as InferAgentToolNames, P as ProjectSettingsGrant, c as SettingSourceCapability, U as UntrustedSettingSourceError, d as compileAgentDefinition, i as isAgentDefinition, r as resolveSettingSources } from './define-agent-BO5QSjV8.js';
12
- import { L as LoopStrategy, R as ReflectionStrategy, b as RoundStreamFactory, S as StreamEvent, c as DelegationResult } from './delegation-scoring-CDvtrYKd.js';
13
- export { B as BackgroundDelegation, d as BudgetExceededError, e as DEFAULT_MAX_ITERATIONS, f as DelegateFn, a as DelegateOptions, g as DelegationBudgetExceededError, h as DelegationError, i as DelegationPort, D as DelegationTarget, j as LoopFinishReason, k as LoopOutcome, l as LoopStrategyConfig, m as ReflectionContext, n as ReflectionResult, o as ReflectionStrategyConfig, p as ScoreVerdict, q as ScoredDelegation, r as Scorer, s as delegate, t as delegateBackground, u as delegateWithScoring, v as ladderReflectionStrategy, w as loopStrategyConfigSchema, x as noopReflectionStrategy, y as reflectionStrategyConfigSchema, z as resolveLoopStrategy, A as streamAgentResponse } from './delegation-scoring-CDvtrYKd.js';
10
+ import { G as Guardrail, C as CompiledAgentOptions, a as CompiledTool } from './agent-compiler-tetgj6zR.js';
11
+ export { b as CostBudgetExceededError, c as GuardrailAction, d as GuardrailPhase, e as GuardrailResult, f as GuardrailViolationError, g as SkillsRequestContext, S as SkillsSelection, T as ToolWalkResult, h as ToolboxWalkResult, i as compileTools, r as resolveEnabledSkills } from './agent-compiler-tetgj6zR.js';
12
+ import { S as SettingSourcesSelection } from './define-agent-BnH1MBxs.js';
13
+ export { a as AGENT_BRAND, A as AgentDefinition, D as DefineAgentConfig, I as InferAgentInput, b as InferAgentToolNames, P as ProjectSettingsGrant, c as SettingSourceCapability, U as UntrustedSettingSourceError, d as compileAgentDefinition, i as isAgentDefinition, r as resolveSettingSources } from './define-agent-BnH1MBxs.js';
14
+ import { L as LoopStrategy, R as ReflectionStrategy, b as RoundStreamFactory, S as StreamEvent, c as DelegationResult } from './delegation-scoring-CQtF2Zaf.js';
15
+ export { A as AgentStopReason, d as AgentStreamEvent, e as AgentTurnMetadata, f as ApprovalRequiredEvent, g as ArtifactChunkEvent, h as ArtifactStartEvent, B as BackgroundDelegation, i as BudgetExceededError, C as CheckpointSavedEvent, j as DEFAULT_MAX_ITERATIONS, k as DelegateFn, a as DelegateOptions, l as DelegationBudgetExceededError, m as DelegationError, n as DelegationPort, D as DelegationTarget, o as DoneEvent, E as ErrorEvent, F as FileEditEvent, I as IterationEvent, p as LoopFinishReason, q as LoopOutcome, r as LoopStrategyConfig, P as PartialToolCallEvent, s as ReflectionContext, t as ReflectionResult, u as ReflectionStrategyConfig, v as RunStartedEvent, w as ScoreVerdict, x as ScoredDelegation, y as Scorer, z as StateUpdateEvent, T as TextDeltaEvent, G as ThinkingEvent, H as ToolCallEvent, J as ToolResultEvent, K as delegate, M as delegateBackground, N as delegateWithScoring, O as isApprovalRequired, Q as isDone, U as isError, V as isPartialToolCall, W as isTextDelta, X as isToolCall, Y as isToolResult, Z as ladderReflectionStrategy, _ as loopStrategyConfigSchema, $ as noopReflectionStrategy, a0 as presentUIMessageStream, a1 as reflectionStrategyConfigSchema, a2 as resolveLoopStrategy, a3 as streamAgentResponse } from './delegation-scoring-CQtF2Zaf.js';
14
16
  import { RetryOptions } from '@theokit/sdk/retry';
15
17
  export * from '@theokit/sdk/retry';
16
18
  import { CompressibleMessage } from '@theokit/sdk/compaction';
@@ -630,7 +632,7 @@ declare class CapabilityPreset implements Capability {
630
632
 
631
633
  /**
632
634
  * M53 — the capabilities that replace the waist-bound agent decorators, one per field the decorator
633
- * pipeline produces today (`wiki/agents/decorator-to-capability.md` § A).
635
+ * pipeline produces today.
634
636
  *
635
637
  * M57 reverses ADR 0001 § 4 (which kept the pure-assignment ones as a factory function to avoid
636
638
  * "13 near-identical classes"): the authoring surface is now 100% classes, aligned with the SDK's
@@ -1216,6 +1218,17 @@ interface InProcessApprovalRequest {
1216
1218
  type InProcessAwaitApproval = (req: InProcessApprovalRequest) => Promise<boolean | HitlDecision>;
1217
1219
  interface StreamAgentTurnInProcessInput {
1218
1220
  message: string;
1221
+ /**
1222
+ * What a consumer is told a failure was (usetheokit/theokit#390).
1223
+ *
1224
+ * Declared here as well as on the HTTP entry point because the parity gate is right: a masking
1225
+ * default that applied over HTTP and not in-process would make "does the server's raw text
1226
+ * escape?" depend on which transport the caller picked — a rule nobody could hold, and the exact
1227
+ * asymmetry `rules/three-target-parity.md` exists to refuse.
1228
+ *
1229
+ * Absent ⇒ masked to a fixed string, the same default the HTTP path takes.
1230
+ */
1231
+ onError?: Parameters<typeof streamAgentUIMessages>[2]['onError'];
1219
1232
  /**
1220
1233
  * M35 (multimodal) — images to send alongside the text. Threaded to the SDK's structured
1221
1234
  * `SDKUserMessage { text, images }` send form. Absent ⇒ the string send path is byte-unchanged.
@@ -1257,6 +1270,38 @@ interface StreamAgentTurnInProcessInput {
1257
1270
  * before.
1258
1271
  */
1259
1272
  onRunEvent?: Parameters<typeof streamAgentUIMessages>[2]['onRunEvent'];
1273
+ /**
1274
+ * theokit#474 — per-turn transient retry: a 429/5xx/network blip that kills the turn before it
1275
+ * produced anything is recovered instead of ending it.
1276
+ *
1277
+ * The same shape as theokit#189 above, and one layer deeper. `AgentRunnerRunOptions.retry` has
1278
+ * carried this option since V4-P, so a reader of the package concludes the capability exists —
1279
+ * but it belongs to the reflective loop, and an EMBEDDED surface does not run one: a TUI and a CLI
1280
+ * both come through here, one SDK turn at a time, and had no way to ask for a second attempt. A
1281
+ * transient ended the turn, and the person at the keyboard retyped the prompt.
1282
+ *
1283
+ * It is not the same hop `onRunEvent` was. There the far end already accepted the field and the
1284
+ * middle simply did not pass it; here `streamAgentUIMessages` had no `retry` parameter and the SDK
1285
+ * reports a provider failure as the run's terminal `error` EVENT rather than as a rejection, so
1286
+ * the wrapper the loop uses would have compiled, shipped, and never fired. What was added is in
1287
+ * `turn-retry.ts`, along with the invariant that makes retrying safe: the window closes on the
1288
+ * FIRST event, so nothing has reached the caller and no tool has run.
1289
+ *
1290
+ * Absent ⇒ the key is omitted from the SDK call entirely, so the stream is byte-identical to
1291
+ * before and the turn is a single attempt.
1292
+ */
1293
+ retry?: Parameters<typeof streamAgentUIMessages>[2]['retry'];
1294
+ /**
1295
+ * theokit#475 — expose the run's REAL token usage to tool handlers as `ctx.usage`, so a tool can
1296
+ * answer "how much context is left?" from the provider's own numbers.
1297
+ *
1298
+ * Read it with `readRunUsage` from `@theokit/agents/usage`. It reports `undefined` until the first
1299
+ * provider report arrives: "not known yet" and "zero tokens" are different facts, and only one of
1300
+ * them is ever true.
1301
+ *
1302
+ * Absent ⇒ handlers receive exactly the ctx they did before.
1303
+ */
1304
+ exposeUsageToTools?: Parameters<typeof streamAgentUIMessages>[2]['exposeUsageToTools'];
1260
1305
  }
1261
1306
  /** Injectable stream fn (defaults to the real SDK bridge) — lets tests drive a deterministic stream. */
1262
1307
  interface StreamAgentTurnDeps {
package/dist/index.js CHANGED
@@ -31,7 +31,7 @@ import {
31
31
  streamAgentResponse,
32
32
  streamAgentUIMessages,
33
33
  toolRuntimeName
34
- } from "./chunk-QJN2LLPF.js";
34
+ } from "./chunk-ZQOKIZCI.js";
35
35
  import {
36
36
  APPROVAL_MODES,
37
37
  AgentRunner,
@@ -82,7 +82,7 @@ import {
82
82
  unicodeNormalizer,
83
83
  withClockCap,
84
84
  withEphemeralAgent
85
- } from "./chunk-CKRM5Q2K.js";
85
+ } from "./chunk-2I6DQUJP.js";
86
86
  import "./chunk-RKWCXVYG.js";
87
87
  import {
88
88
  AGENT_BRAND,
@@ -91,7 +91,8 @@ import {
91
91
  compileSkillsSelection,
92
92
  isAgentDefinition,
93
93
  resolveSettingSources
94
- } from "./chunk-4VHCH6IZ.js";
94
+ } from "./chunk-LLIERPF3.js";
95
+ import "./chunk-OXNDJSAJ.js";
95
96
  import {
96
97
  __name
97
98
  } from "./chunk-Z4QWC7IK.js";
@@ -1094,6 +1095,19 @@ function streamAgentTurnInProcess(mod, apiKey, input, deps = {
1094
1095
  signal: input.signal,
1095
1096
  ...input.onRunEvent !== void 0 ? {
1096
1097
  onRunEvent: input.onRunEvent
1098
+ } : {},
1099
+ // theokit#474 / #475 — omitted when absent, for the same reason as the sink above: a key set
1100
+ // to `undefined` still changes what the far end receives on the non-opted-in path.
1101
+ ...input.retry !== void 0 ? {
1102
+ retry: input.retry
1103
+ } : {},
1104
+ ...input.exposeUsageToTools !== void 0 ? {
1105
+ exposeUsageToTools: input.exposeUsageToTools
1106
+ } : {},
1107
+ // #390 — absent is meaningful: it selects the masking default, and it must select the SAME
1108
+ // one here as over HTTP.
1109
+ ...input.onError !== void 0 ? {
1110
+ onError: input.onError
1097
1111
  } : {}
1098
1112
  });
1099
1113
  })();