@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
@@ -0,0 +1,449 @@
1
+ import { PluginsSettings, ProviderRoutingSettings, AgentDefinition, BudgetTracker, CustomTool } from '@theokit/sdk';
2
+ import { RetryOptions } from '@theokit/sdk/retry';
3
+ import { a as CompiledAgentOptions, C as CompiledTool } from './agent-compiler-JSYkHpa7.js';
4
+ import { TheokitAgentError } from '@theokit/sdk/errors';
5
+ import { z } from 'zod';
6
+ import { M as MainLoopMeta } from './types-D5cHmSLi.js';
7
+ import { S as StreamEvent } from './agent-sse-handler-BRp9vHrb.js';
8
+ import { H as HookHandlers } from './hook-handlers-Cw2FsnE5.js';
9
+
10
+ /**
11
+ * LoopStrategy — the per-round terminal-decision contract that gives runtime to
12
+ * `@MainLoop({ strategy })`.
13
+ *
14
+ * V4-A proved `@MainLoop`'s `strategy` field was metadata-only (declared +
15
+ * compiled, never executed). This module is the foundation Phase 2's
16
+ * `runReflectiveLoop` branches on. Modeled on Mastra's `agentic-loop`/`stopWhen`
17
+ * (inverted) + `maxSteps` ceiling — NOT Spring's per-call Advisor (plan ADR D1).
18
+ * Config is Zod-validated so an invalid `maxIterations` fails fast at resolve
19
+ * time, never as a silent infinite loop at runtime (plan ADR D3).
20
+ */
21
+
22
+ /** Why a single round ended (or, for the V4-D terminals, why the whole loop ended). */
23
+ type LoopFinishReason = 'tool-calls' | 'stop' | 'length' | 'error' | 'step_limit' | 'no_progress';
24
+ /** Value object describing one round's result. */
25
+ interface LoopOutcome {
26
+ /** Why the round ended (the continuation signal). */
27
+ readonly finishReason: LoopFinishReason;
28
+ /** 1-indexed round number that just completed. */
29
+ readonly round: number;
30
+ /** Tool calls executed during the round (V4-N: `id` correlates the call to its result). */
31
+ readonly toolCalls: readonly {
32
+ id: string;
33
+ name: string;
34
+ input: unknown;
35
+ output: string;
36
+ }[];
37
+ /** Accumulated assistant text for the round. */
38
+ readonly responseText: string;
39
+ }
40
+ /** The terminal-decision contract. `shouldContinue` is the inverted `stopWhen`. */
41
+ interface LoopStrategy {
42
+ /**
43
+ * The strategy name, surfaced in `finalize`/logs. M54 relaxes this from
44
+ * `MainLoopMeta['strategy']` to `string` so a caller-injected `.loopStrategy(custom)` can name
45
+ * itself freely — the three built-ins keep their names, but the seam is no longer union-locked.
46
+ * The INTERNAL resolution (`loopStrategyConfigSchema`) still validates the three built-in names
47
+ * via `z.enum`; a custom never passes through it (it enters by the seam, not by name).
48
+ */
49
+ readonly name: string;
50
+ /** Hard ceiling on rounds — guarantees termination (enforced by the runner since M54). */
51
+ readonly maxIterations: number;
52
+ /** True ⇒ re-enter for another round; false ⇒ terminate. The runner caps it at `maxIterations`. */
53
+ shouldContinue(outcome: LoopOutcome): boolean;
54
+ }
55
+ /** Default round ceiling when `@MainLoop` declares no `maxIterations` (EC-3: finite, never Infinity). */
56
+ declare const DEFAULT_MAX_ITERATIONS = 8;
57
+ /** Serializable config for a LoopStrategy. SSoT per type-safety.md (ADR D3). */
58
+ declare const loopStrategyConfigSchema: z.ZodObject<{
59
+ name: z.ZodEnum<{
60
+ "simple-chat": "simple-chat";
61
+ "plan-act-reflect": "plan-act-reflect";
62
+ react: "react";
63
+ }>;
64
+ maxIterations: z.ZodNumber;
65
+ }, z.core.$strip>;
66
+ type LoopStrategyConfig = z.infer<typeof loopStrategyConfigSchema>;
67
+ /**
68
+ * Map a `@MainLoop` strategy + ceiling to a concrete {@link LoopStrategy}.
69
+ *
70
+ * - `simple-chat` ⇒ exactly one round (`shouldContinue` always false).
71
+ * - `react` ⇒ continue while the round ended on `tool-calls` AND the ceiling has not been reached
72
+ * (`round < maxIterations`) — the reflection is `noop` (no feedback), so the strategy IS the gate.
73
+ * - `plan-act-reflect` ⇒ DEFER continuation to the reflection (V4-S): `shouldContinue` is
74
+ * `round < maxIterations`, so the loop continues iff the (custom) `ReflectionStrategy` returns
75
+ * `continue: true` within the ceiling — letting a reflection extend even a terminal (`stop`)
76
+ * round (e.g. "you answered without editing — make the edit now"). Backward-compatible with the
77
+ * default `ladderReflectionStrategy`, which itself returns `continue: true` only on `tool-calls`,
78
+ * so the observable behavior with the shipped ladder is unchanged.
79
+ *
80
+ * Throws (Zod) when `maxIterations < 1` — fail fast, never a silent infinite loop.
81
+ */
82
+ declare function resolveLoopStrategy(strategy: string, maxIterations?: number): LoopStrategy;
83
+
84
+ interface DelegationResult {
85
+ response: string;
86
+ toolCalls: {
87
+ id: string;
88
+ name: string;
89
+ input: unknown;
90
+ output: string;
91
+ }[];
92
+ /**
93
+ * USD the run's priced rounds cost. A round the SDK could not price adds nothing here, so read it
94
+ * with {@link costUnknown}: when that is set, this is the known spend and not the run's cost.
95
+ */
96
+ cost: number;
97
+ /**
98
+ * Present, and `true`, when at least one round reported no finite cost (B-409): the run cost
99
+ * {@link cost} plus an amount nobody knows. Absent on a run whose every round was priced. A
100
+ * consumer summing runs must not read such a `cost` as the run's price (#969).
101
+ */
102
+ costUnknown?: true;
103
+ /**
104
+ * Input plus output tokens across rounds, the SDK's `TokenUsage.totalTokens`. Cache reads and
105
+ * writes are not in it: from `@theokit/sdk` 5.11.0 `tokensInput` is the uncached part of the
106
+ * prompt on the chat-completions and Anthropic clients, so the whole prompt there is `tokensInput + cacheReadTokens +
107
+ * cacheWriteTokens`, and a consumer pricing a run must add the cache buckets.
108
+ */
109
+ tokens: number;
110
+ /** V4-N: split token usage accumulated across rounds; `tokensInput` excludes cache reads and writes. Absent for the single-shot path. */
111
+ tokensInput?: number;
112
+ tokensOutput?: number;
113
+ /** V4-O: reasoning/cache token buckets accumulated across rounds (0 on any loop-driven run; the loop seeds them). Optional for type compat. */
114
+ reasoningTokens?: number;
115
+ cacheReadTokens?: number;
116
+ cacheWriteTokens?: number;
117
+ /** Rounds the reflective loop ran (set by `runReflectiveLoop`; absent for the single-shot path). */
118
+ rounds?: number;
119
+ /**
120
+ * The loop's terminal reason (set by `runReflectiveLoop`): `'stop'`/`'length'` natural end,
121
+ * `'step_limit'` (hit maxIterations), `'no_progress'` (stuck). Absent for the single-shot path. (V4-D)
122
+ */
123
+ finishReason?: LoopFinishReason;
124
+ }
125
+ /**
126
+ * Why a run stopped BEFORE a round rather than after one. Without it the error reports an
127
+ * overspend (`$actual > $limit`), which is only true once the spend passed the limit; a refusal
128
+ * stops while the spend is still under it, so it needs wording that does not claim otherwise.
129
+ */
130
+ type BudgetRefusal =
131
+ /** The next round's projected cost (the last completed round's), which would pass the limit. */
132
+ {
133
+ readonly projectedRoundCost: number;
134
+ }
135
+ /** The last round's cost is not known, so the limit cannot be enforced for the next one. */
136
+ | {
137
+ readonly costUnknown: true;
138
+ }
139
+ /** The limit is 0 or below, so no round fits: the run stops before its first one. */
140
+ | {
141
+ readonly nothingToSpend: true;
142
+ };
143
+ /**
144
+ * DELEGATION budget exceeded — the dollar cost of a delegated agent.
145
+ *
146
+ * ## Why the name changed in M91
147
+ *
148
+ * It was called `BudgetExceededError` and **shadowed** the SDK class of the same name, which belongs
149
+ * to another domain: context-WINDOW budget (`budgetName`/`window`/`mode`) against DELEGATION budget
150
+ * (`agentName`/`actualCost`). Since the consumer holds an unbreakable rule never to import
151
+ * `@theokit/sdk` directly, it **could never reach the SDK's** — and an `instanceof` against this
152
+ * barrel silently matched the wrong domain.
153
+ *
154
+ * It is the failure mode M73 documented in `auth-parity.test.ts`: when two classes compete for the
155
+ * same name, no behavioural test goes red — only an identity `toBe` catches it.
156
+ *
157
+ * `subpath-coverage.test.ts` recorded the collision as a `gap` on `./errors`, with the reason written
158
+ * down and the acknowledgement that renaming was breaking and out of M78's scope. M91 paid the bill.
159
+ */
160
+ /**
161
+ * M80 — extends {@link TheokitAgentError}, not plain `Error`.
162
+ *
163
+ * `isTransientError` is defined over `TheokitAgentError`, so a class outside that hierarchy is
164
+ * INVISIBLE to it and the only recourse left to a consumer is matching on message text. `code` is
165
+ * stable across a rename; `isRetryable` is DECLARED, because a default would be a retry policy
166
+ * nobody chose.
167
+ */
168
+ declare class DelegationBudgetExceededError extends TheokitAgentError {
169
+ readonly agentName: string;
170
+ readonly actualCost: number;
171
+ readonly budgetLimit: number;
172
+ readonly name = "DelegationBudgetExceededError";
173
+ /** The cost the refused round was projected at; absent when the spend already passed the limit. */
174
+ readonly projectedRoundCost: number | undefined;
175
+ constructor(agentName: string, actualCost: number, budgetLimit: number, refusal?: BudgetRefusal);
176
+ }
177
+ /**
178
+ * A run with a USD ceiling stopped because the cost of its last round is not known (B-409).
179
+ *
180
+ * A model with no price reports no cost, and reading that as $0 would let the run keep spending
181
+ * against a limit it can no longer check, so the run stops instead (fail closed). `actualCost` is
182
+ * the spend that IS known. A subclass so it can be caught on its own while every existing
183
+ * `instanceof DelegationBudgetExceededError` and the `DELEGATION_BUDGET_EXCEEDED` code still match;
184
+ * `name` is inherited because the parent declares it as a string literal, which a subclass cannot
185
+ * override with another.
186
+ */
187
+ declare class DelegationBudgetCostUnknownError extends DelegationBudgetExceededError {
188
+ constructor(agentName: string, knownSpend: number, budgetLimit: number);
189
+ }
190
+ /**
191
+ * @deprecated Use {@link DelegationBudgetExceededError}. The alias is kept for one major so anyone
192
+ * catching by the old name is not broken; it is the **same** class, not a copy — `instanceof` still
193
+ * holds in both directions, and a referential-identity test (`toBe`) pins that.
194
+ *
195
+ * knip reports the value/type pair as a duplicate export, which is exactly what a deprecation
196
+ * alias is; `rules.duplicates` is "warn" for that reason. Removing it is the breaking change it
197
+ * exists to avoid.
198
+ */
199
+ declare const BudgetExceededError: typeof DelegationBudgetExceededError;
200
+ /** @deprecated Use {@link DelegationBudgetExceededError}. */
201
+ type BudgetExceededError = DelegationBudgetExceededError;
202
+ /**
203
+ * M80 — extends {@link TheokitAgentError}, not plain `Error`.
204
+ *
205
+ * `isTransientError` is defined over `TheokitAgentError`, so a class outside that hierarchy is
206
+ * INVISIBLE to it and the only recourse left to a consumer is matching on message text. `code` is
207
+ * stable across a rename; `isRetryable` is DECLARED, because a default would be a retry policy
208
+ * nobody chose.
209
+ */
210
+ declare class DelegationError extends TheokitAgentError {
211
+ readonly agentName: string;
212
+ readonly cause: unknown;
213
+ readonly name = "DelegationError";
214
+ constructor(agentName: string, cause: unknown);
215
+ }
216
+
217
+ /**
218
+ * ReflectionStrategy — composes INTO the loop between rounds (the loop calls
219
+ * `reflect()` then `LoopStrategy.shouldContinue()`).
220
+ *
221
+ * `'plan-act-reflect'` resolves to the `'ladder'` default shipped here; a custom
222
+ * strategy may be supplied (OCP — plan Drawback #2). `reflect()` is pure (no
223
+ * I/O, no LLM) — it inspects the round's outcome and returns feedback to inject
224
+ * into the next round's prompt plus a `continue` hint. The hard round ceiling
225
+ * lives in `LoopStrategy.shouldContinue` (maxIterations), NOT here.
226
+ */
227
+
228
+ /** Result of reflecting on a completed round. */
229
+ interface ReflectionResult {
230
+ /** Optional text prepended to the next round's prompt. */
231
+ readonly feedback?: string;
232
+ /** Hint: should the loop reflect-and-continue? (the ceiling still bounds it) */
233
+ readonly continue: boolean;
234
+ }
235
+ /**
236
+ * V4-K: a per-run mutable scratch bag threaded to every `reflect()` call within one
237
+ * `runReflectiveLoopStream` run, so a STATEFUL strategy can accumulate cumulative state
238
+ * (counters, one-shot flags) across rounds. The framework owns the lifecycle (creates
239
+ * one per run, passes the SAME ref each round) but writes NOTHING into it — the strategy
240
+ * owns the contents. Generic by design: the framework cannot know app semantics (e.g.
241
+ * what an "edit" is). A consumer narrows it locally (`ctx as MyState`).
242
+ */
243
+ type ReflectionContext = Record<string, unknown>;
244
+ /** Pluggable between-round reflection. Pure — never performs I/O. */
245
+ interface ReflectionStrategy {
246
+ /** Strategy identifier (e.g. `'ladder'`). */
247
+ readonly name: string;
248
+ /**
249
+ * Inspect the round outcome; return feedback + continue hint. `ctx` (V4-K) is the
250
+ * per-run mutable scratch — optional for backward compatibility (shipped strategies
251
+ * ignore it; stateful custom strategies accumulate in it across rounds).
252
+ */
253
+ reflect(outcome: LoopOutcome, ctx?: ReflectionContext): ReflectionResult;
254
+ }
255
+ /** Serializable config for a ReflectionStrategy. SSoT per type-safety.md (ADR D3). */
256
+ declare const reflectionStrategyConfigSchema: z.ZodObject<{
257
+ name: z.ZodString;
258
+ }, z.core.$strip>;
259
+ type ReflectionStrategyConfig = z.infer<typeof reflectionStrategyConfigSchema>;
260
+ /**
261
+ * The default `'ladder'` reflection (what `'plan-act-reflect'` resolves to).
262
+ *
263
+ * Continues with bounded templated feedback while the round ended on
264
+ * `tool-calls`; terminates on any terminal `finishReason` (`stop`/`error`/
265
+ * `length`). The feedback is a short fixed template (bounded — EC-5; context
266
+ * growth is the SDK's responsibility, not the loop's).
267
+ */
268
+ declare const ladderReflectionStrategy: ReflectionStrategy;
269
+ /**
270
+ * No-op reflection for `'react'` (multi-round WITHOUT reflection feedback).
271
+ *
272
+ * Returns `{ continue: true }` (no feedback) so the round-continuation decision
273
+ * is delegated entirely to `LoopStrategy.shouldContinue` (i.e. `react` loops
274
+ * while `finishReason === 'tool-calls'` under the ceiling). NOTE: the plan's
275
+ * pseudo-code (Files-to-edit) sketched `{ continue: false }`, which would make
276
+ * `react` single-shot — that contradicts the plan's own Deep Dives ("`react`
277
+ * still multi-rounds while finishReason==='tool-calls'"); `continue: true` is
278
+ * the behavior the resolved react LoopStrategy requires.
279
+ */
280
+ declare const noopReflectionStrategy: ReflectionStrategy;
281
+
282
+ /**
283
+ * runReflectiveLoop — the multi-round reflective driver that gives `@MainLoop`
284
+ * its runtime (closes the metadata-only gap, V4-A / plan ADR D2).
285
+ *
286
+ * Per round it consumes ONE SDK stream turn (the model call stays in the SDK —
287
+ * the factory is `createSdkAgentStream(...)`, injected for testability), derives
288
+ * a {@link LoopOutcome}, asks the {@link ReflectionStrategy} for feedback, then
289
+ * the {@link LoopStrategy} whether to continue. Bounded by `maxIterations`
290
+ * (forced terminal at the ceiling — never an infinite loop). The bridge owns the
291
+ * loop; the SDK owns the model call (sdk-runtime.md / ADR 0031 — no second runtime).
292
+ *
293
+ * `runReflectiveLoop` is INTERNAL (not re-exported from the package barrel,
294
+ * Drawback #4) — consumed by `delegate()` (T2.2) and `AgentRunner` (T3.1).
295
+ */
296
+
297
+ /** One SDK stream turn: `createSdkAgentStream(...)` returns this shape. */
298
+ /**
299
+ * Opens one round's SDK stream. `opts.disableTools` (step-cap force-close) asks the factory to
300
+ * gate tools OFF for THIS round (the SDK adapter maps it to `tool_choice:"none"` at send-time, so a
301
+ * cached agent — whose tools can't be un-registered — is still forced to a text summary). Optional +
302
+ * ignored by injected test factories ⇒ backward-compatible.
303
+ */
304
+ type RoundStreamFactory = (message: string, sessionId: string, opts?: {
305
+ disableTools?: boolean;
306
+ }) => AsyncIterable<StreamEvent>;
307
+
308
+ /**
309
+ * Multi-agent orchestration runtime.
310
+ *
311
+ * Provides `delegate()` — a function that lets a parent agent invoke a
312
+ * sub-agent and receive its result. Handles budget clamping (D4), tool sharing,
313
+ * toolbox auto-instantiation (EC-1), and routes the resolved `@MainLoop` strategy
314
+ * through `runReflectiveLoop` — the SAME driver `AgentRunner.run()` uses, so both
315
+ * on-ramps are one runtime (ADR D4). `simple-chat` ⇒ `shouldContinue:()=>false`
316
+ * ⇒ exactly one round; `react`/`plan-act-reflect` ⇒ multi-round reflective loop.
317
+ */
318
+
319
+ interface DelegateOptions {
320
+ /**
321
+ * M81 — wall-clock cap for the delegation, in milliseconds. Absent ⇒ no clock cap.
322
+ *
323
+ * A DIFFERENT guard from `budget`: money is spent by work that progresses, and a delegation that
324
+ * HANGS burns clock without spending a cent. A consumer wrote its own timeout race with its own
325
+ * typed error because this was missing. Exceeding it raises `DelegationTimeoutError`, which —
326
+ * unlike the budget errors — is marked retryable, because a hang is often transient.
327
+ */
328
+ readonly timeoutMs?: number;
329
+ /**
330
+ * Max USD for this sub-agent call. `NaN` is refused with `DelegationError`; 0 or below stops the
331
+ * call before any round with `DelegationBudgetExceededError`; `Infinity` is no ceiling.
332
+ */
333
+ budget?: number;
334
+ /**
335
+ * Parent's remaining budget (for clamping), read on the same terms as `budget`: a parent that
336
+ * has spent its ceiling (0 or below) ends the call as budget exceeded before any round.
337
+ */
338
+ parentBudgetRemaining?: number;
339
+ /** Parent's tools (for sharing — sub-agent inherits these). */
340
+ parentTools?: CompiledTool[];
341
+ /**
342
+ * Parent's hooks. The member inherits them, and inheritance may only TIGHTEN: both
343
+ * `pre_tool_call` gates run and the first refusal wins, so a member cannot widen what the parent
344
+ * refused.
345
+ *
346
+ * Symmetric with `parentTools` on purpose — `delegate` already carried the parent's tools and its
347
+ * budget into the member's run and left its AUTHORITY behind, which is how a squad member could
348
+ * call a tool the supervisor had vetoed. The failure was silent: nothing threw, and the member's
349
+ * own suite passed because the member never declared the gate.
350
+ *
351
+ * To scope a member differently, pass its handlers on `spec.compiled.hooks` — they compose with
352
+ * these rather than replacing them, because a widening that a call site cannot see is the state
353
+ * this option exists to remove.
354
+ */
355
+ parentHooks?: HookHandlers;
356
+ /**
357
+ * LLM API key (inherited from parent).
358
+ *
359
+ * `null` says the provider takes NO credential — a model on the developer's own machine
360
+ * (usetheokit/theokit#423). It is a distinct value from `''` on purpose: an empty string is what
361
+ * an unset environment variable produces, and treating the two alike is how a typo becomes an
362
+ * unauthenticated run. `undefined` still means the caller supplied nothing and is still refused.
363
+ */
364
+ apiKey?: string | null;
365
+ /** Session ID override (default: crypto.randomUUID for isolation). */
366
+ sessionId?: string;
367
+ /** Cancellation — aborts stop the reflective loop from re-entering. */
368
+ signal?: AbortSignal;
369
+ /** Per-run model override (`?? SubAgent @Agent model`). */
370
+ model?: string;
371
+ /**
372
+ * Per-run working directory → `Agent.create({ local: { cwd } })`.
373
+ *
374
+ * B-073 — if you point this at a git worktree you created, the sub-agent runs in a checkout with
375
+ * none of the repository's gitignored files: no `.env`, no local config, no credentials. This
376
+ * layer does not copy them, and it has no `.worktreeinclude` — the reference's one-file answer to
377
+ * the same problem — because it never creates a worktree in the first place (measured with
378
+ * controls: zero `git worktree` calls, zero `isolation` options; held falsifiable by
379
+ * `tests/unit/this-layer-creates-no-worktree.test.ts`, which goes red the day that changes).
380
+ *
381
+ * Stated here rather than left to be discovered, because the failure does not look like a missing
382
+ * file — it looks like a broken agent.
383
+ */
384
+ cwd?: string;
385
+ /** Per-run plugins (e.g. a read-only permission gate for an explore sub-agent). */
386
+ plugins?: PluginsSettings;
387
+ /** Per-run provider routing (e.g. OpenRouter). */
388
+ providers?: ProviderRoutingSettings;
389
+ /** Per-run sub-agent definitions. */
390
+ agents?: Record<string, AgentDefinition>;
391
+ /** Per-run SDK budget tracker (inner tool-loop cap). */
392
+ budgetTracker?: BudgetTracker;
393
+ /** Per-run pre-built SDK tools forwarded raw (V4-Q). */
394
+ sdkTools?: readonly CustomTool[];
395
+ /** Per-round transient retry (V4-P). */
396
+ retry?: RetryOptions;
397
+ /** Custom between-round reflection (default: ladder for `plan-act-reflect`, else noop). */
398
+ reflection?: ReflectionStrategy;
399
+ /** Per-run loop-ceiling override (`?? SubAgent @MainLoop maxIterations`). */
400
+ maxIterations?: number;
401
+ /**
402
+ * Called BEFORE the sub-agent runs. Returns the input the sub-agent will receive — return
403
+ * `ctx.input` unchanged, or a rewritten string (e.g. inject a persona). A transform, not a veto.
404
+ */
405
+ onDelegationStart?: (ctx: {
406
+ subAgent: string;
407
+ input: string;
408
+ }) => string | Promise<string>;
409
+ /**
410
+ * Called AFTER the sub-agent completes. Returns the result the supervisor sees — return
411
+ * `ctx.result` unchanged, or a transformed one (e.g. redact, score, re-wrap).
412
+ */
413
+ onDelegationComplete?: (ctx: {
414
+ subAgent: string;
415
+ result: DelegationResult;
416
+ }) => DelegationResult | Promise<DelegationResult>;
417
+ /**
418
+ * Injected stream factory (parity with `AgentRunnerRunOptions.streamFactory`) — drives the loop
419
+ * directly instead of the SDK adapter (tests / custom transport). Absent ⇒ `createSdkAgentStream`.
420
+ */
421
+ streamFactory?: RoundStreamFactory;
422
+ }
423
+ /**
424
+ * Delegate a task to a sub-agent and collect its result.
425
+ *
426
+ * - Budget clamping: `min(parentBudgetRemaining, budget)` (D4)
427
+ * - Tool sharing: parent tools merged with sub-agent tools (sub wins on collision)
428
+ * - Toolbox auto-instantiation: sub-agent toolboxes instantiated without DI (EC-1)
429
+ * - Session isolation: each delegation gets a unique session ID (EC-4)
430
+ * - `@MainLoop` strategy runtime: routes through `runReflectiveLoop` (the same loop
431
+ * `AgentRunner.run` uses — one runtime for both on-ramps, ADR D4). The runtime
432
+ * metric (`THEO_AGENT_MAINLOOP_RUNTIME_APPLIED`) + typed-error + cumulative budget
433
+ * all live in the shared driver, so they fire identically on both paths.
434
+ */
435
+ /**
436
+ * What `delegate` needs from a sub-agent: a name and already-compiled options (built by
437
+ * `applyCapabilities`). Compatible with {@link AgentRunnerSpec} — one spec drives both on-ramps.
438
+ */
439
+ interface SubAgentSpec {
440
+ readonly name: string;
441
+ readonly compiled: CompiledAgentOptions;
442
+ /** Loop strategy (`@MainLoop({ strategy })`); absent ⇒ the same `'simple-chat'` default. */
443
+ readonly strategy?: MainLoopMeta['strategy'];
444
+ /** Loop ceiling (`@MainLoop({ maxIterations })`); a per-run override still wins. */
445
+ readonly maxIterations?: number;
446
+ }
447
+ declare function delegate(spec: SubAgentSpec, message: string, opts?: DelegateOptions): Promise<DelegationResult>;
448
+
449
+ export { BudgetExceededError as B, type DelegationResult as D, type LoopStrategy as L, type RoundStreamFactory as R, type SubAgentSpec as S, type DelegateOptions as a, type ReflectionStrategy as b, DEFAULT_MAX_ITERATIONS as c, DelegationBudgetCostUnknownError as d, DelegationBudgetExceededError as e, DelegationError as f, type LoopFinishReason as g, type LoopOutcome as h, type LoopStrategyConfig as i, type ReflectionContext as j, type ReflectionResult as k, type ReflectionStrategyConfig as l, delegate as m, ladderReflectionStrategy as n, loopStrategyConfigSchema as o, noopReflectionStrategy as p, resolveLoopStrategy as q, reflectionStrategyConfigSchema as r };