@theokit/agents 9.3.0 → 9.4.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.
- package/CHANGELOG.md +135 -0
- package/dist/{define-agent-3Kuf6iKM.d.ts → agent-compiler-CIPQkehU.d.ts} +3 -233
- package/dist/{bridge-entry-51lU7LQw.d.ts → bridge-entry-CmYUgNit.d.ts} +4 -464
- package/dist/bridge.d.ts +4 -2
- package/dist/bridge.js +19 -17
- package/dist/chunk-CAXGTLRU.js +1110 -0
- package/dist/chunk-CAXGTLRU.js.map +1 -0
- package/dist/{chunk-RZCNKKOG.js → chunk-W6TABP2S.js} +11 -1105
- package/dist/chunk-W6TABP2S.js.map +1 -0
- package/dist/config.d.ts +48 -2
- package/dist/config.js +45 -16
- package/dist/config.js.map +1 -1
- package/dist/define-agent-BO5QSjV8.d.ts +236 -0
- package/dist/delegation-scoring-CDvtrYKd.d.ts +469 -0
- package/dist/index.d.ts +8 -4
- package/dist/index.js +33 -31
- package/dist/index.js.map +1 -1
- package/dist/interactive.d.ts +0 -1
- package/dist/session.d.ts +26 -1
- package/dist/session.js +28 -3
- package/dist/session.js.map +1 -1
- package/dist/testing.d.ts +2 -1
- package/dist/tools.d.ts +54 -0
- package/dist/tools.js +100 -1
- package/dist/tools.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-RZCNKKOG.js.map +0 -1
|
@@ -0,0 +1,469 @@
|
|
|
1
|
+
import { PluginsSettings, ProviderRoutingSettings, AgentDefinition, BudgetTracker, CustomTool } from '@theokit/sdk';
|
|
2
|
+
import { RetryOptions } from '@theokit/sdk/retry';
|
|
3
|
+
import { C as CompiledAgentOptions, a as MainLoopMeta, b as CompiledTool } from './agent-compiler-CIPQkehU.js';
|
|
4
|
+
import { TheokitAgentError } from '@theokit/sdk/errors';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { H as HookHandlers } from './hook-handlers-Cw2FsnE5.js';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* SSE streaming handler — Web Standard Response with ReadableStream.
|
|
10
|
+
*
|
|
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.
|
|
14
|
+
*/
|
|
15
|
+
/** Minimal event shape matching SDK's SDKMessage discriminated union. */
|
|
16
|
+
interface StreamEvent {
|
|
17
|
+
type: string;
|
|
18
|
+
[key: string]: unknown;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Create a Web Standard Response that streams SSE events.
|
|
22
|
+
* Each event becomes: `event: {type}\ndata: {json}\n\n`
|
|
23
|
+
*/
|
|
24
|
+
declare function streamAgentResponse(eventStream: AsyncIterable<StreamEvent>): Response;
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* LoopStrategy — the per-round terminal-decision contract that gives runtime to
|
|
28
|
+
* `@MainLoop({ strategy })`.
|
|
29
|
+
*
|
|
30
|
+
* V4-A proved `@MainLoop`'s `strategy` field was metadata-only (declared +
|
|
31
|
+
* compiled, never executed). This module is the foundation Phase 2's
|
|
32
|
+
* `runReflectiveLoop` branches on. Modeled on Mastra's `agentic-loop`/`stopWhen`
|
|
33
|
+
* (inverted) + `maxSteps` ceiling — NOT Spring's per-call Advisor (plan ADR D1).
|
|
34
|
+
* Config is Zod-validated so an invalid `maxIterations` fails fast at resolve
|
|
35
|
+
* time, never as a silent infinite loop at runtime (plan ADR D3).
|
|
36
|
+
*
|
|
37
|
+
* reference: knowledge-base/references/mastra agentic-loop/index.ts (stopWhen + maxSteps).
|
|
38
|
+
*/
|
|
39
|
+
|
|
40
|
+
/** Why a single round ended (or, for the V4-D terminals, why the whole loop ended). */
|
|
41
|
+
type LoopFinishReason = 'tool-calls' | 'stop' | 'length' | 'error' | 'step_limit' | 'no_progress';
|
|
42
|
+
/** Value object describing one round's result. */
|
|
43
|
+
interface LoopOutcome {
|
|
44
|
+
/** Why the round ended (the continuation signal). */
|
|
45
|
+
readonly finishReason: LoopFinishReason;
|
|
46
|
+
/** 1-indexed round number that just completed. */
|
|
47
|
+
readonly round: number;
|
|
48
|
+
/** Tool calls executed during the round (V4-N: `id` correlates the call to its result). */
|
|
49
|
+
readonly toolCalls: readonly {
|
|
50
|
+
id: string;
|
|
51
|
+
name: string;
|
|
52
|
+
input: unknown;
|
|
53
|
+
output: string;
|
|
54
|
+
}[];
|
|
55
|
+
/** Accumulated assistant text for the round. */
|
|
56
|
+
readonly responseText: string;
|
|
57
|
+
}
|
|
58
|
+
/** The terminal-decision contract. `shouldContinue` is the inverted `stopWhen`. */
|
|
59
|
+
interface LoopStrategy {
|
|
60
|
+
/**
|
|
61
|
+
* The strategy name, surfaced in `finalize`/logs. M54 relaxes this from
|
|
62
|
+
* `MainLoopMeta['strategy']` to `string` so a caller-injected `.loopStrategy(custom)` can name
|
|
63
|
+
* itself freely — the three built-ins keep their names, but the seam is no longer union-locked.
|
|
64
|
+
* The INTERNAL resolution (`loopStrategyConfigSchema`) still validates the three built-in names
|
|
65
|
+
* via `z.enum`; a custom never passes through it (it enters by the seam, not by name).
|
|
66
|
+
*/
|
|
67
|
+
readonly name: string;
|
|
68
|
+
/** Hard ceiling on rounds — guarantees termination (enforced by the runner since M54). */
|
|
69
|
+
readonly maxIterations: number;
|
|
70
|
+
/** True ⇒ re-enter for another round; false ⇒ terminate. The runner caps it at `maxIterations`. */
|
|
71
|
+
shouldContinue(outcome: LoopOutcome): boolean;
|
|
72
|
+
}
|
|
73
|
+
/** Default round ceiling when `@MainLoop` declares no `maxIterations` (EC-3: finite, never Infinity). */
|
|
74
|
+
declare const DEFAULT_MAX_ITERATIONS = 8;
|
|
75
|
+
/** Serializable config for a LoopStrategy. SSoT per type-safety.md (ADR D3). */
|
|
76
|
+
declare const loopStrategyConfigSchema: z.ZodObject<{
|
|
77
|
+
name: z.ZodEnum<{
|
|
78
|
+
"simple-chat": "simple-chat";
|
|
79
|
+
"plan-act-reflect": "plan-act-reflect";
|
|
80
|
+
react: "react";
|
|
81
|
+
}>;
|
|
82
|
+
maxIterations: z.ZodNumber;
|
|
83
|
+
}, z.core.$strip>;
|
|
84
|
+
type LoopStrategyConfig = z.infer<typeof loopStrategyConfigSchema>;
|
|
85
|
+
/**
|
|
86
|
+
* Map a `@MainLoop` strategy + ceiling to a concrete {@link LoopStrategy}.
|
|
87
|
+
*
|
|
88
|
+
* - `simple-chat` ⇒ exactly one round (`shouldContinue` always false).
|
|
89
|
+
* - `react` ⇒ continue while the round ended on `tool-calls` AND the ceiling has not been reached
|
|
90
|
+
* (`round < maxIterations`) — the reflection is `noop` (no feedback), so the strategy IS the gate.
|
|
91
|
+
* - `plan-act-reflect` ⇒ DEFER continuation to the reflection (V4-S): `shouldContinue` is
|
|
92
|
+
* `round < maxIterations`, so the loop continues iff the (custom) `ReflectionStrategy` returns
|
|
93
|
+
* `continue: true` within the ceiling — letting a reflection extend even a terminal (`stop`)
|
|
94
|
+
* round (e.g. "you answered without editing — make the edit now"). Backward-compatible with the
|
|
95
|
+
* default `ladderReflectionStrategy`, which itself returns `continue: true` only on `tool-calls`,
|
|
96
|
+
* so the observable behavior with the shipped ladder is unchanged.
|
|
97
|
+
*
|
|
98
|
+
* Throws (Zod) when `maxIterations < 1` — fail fast, never a silent infinite loop.
|
|
99
|
+
*/
|
|
100
|
+
declare function resolveLoopStrategy(strategy: string, maxIterations?: number): LoopStrategy;
|
|
101
|
+
|
|
102
|
+
interface DelegationResult {
|
|
103
|
+
response: string;
|
|
104
|
+
toolCalls: {
|
|
105
|
+
id: string;
|
|
106
|
+
name: string;
|
|
107
|
+
input: unknown;
|
|
108
|
+
output: string;
|
|
109
|
+
}[];
|
|
110
|
+
cost: number;
|
|
111
|
+
tokens: number;
|
|
112
|
+
/** V4-N: split token usage accumulated across rounds (`tokens` stays as the total). Absent for the single-shot path. */
|
|
113
|
+
tokensInput?: number;
|
|
114
|
+
tokensOutput?: number;
|
|
115
|
+
/** V4-O: reasoning/cache token buckets accumulated across rounds (0 on any loop-driven run; the loop seeds them). Optional for type compat. */
|
|
116
|
+
reasoningTokens?: number;
|
|
117
|
+
cacheReadTokens?: number;
|
|
118
|
+
cacheWriteTokens?: number;
|
|
119
|
+
/** Rounds the reflective loop ran (set by `runReflectiveLoop`; absent for the single-shot path). */
|
|
120
|
+
rounds?: number;
|
|
121
|
+
/**
|
|
122
|
+
* The loop's terminal reason (set by `runReflectiveLoop`): `'stop'`/`'length'` natural end,
|
|
123
|
+
* `'step_limit'` (hit maxIterations), `'no_progress'` (stuck). Absent for the single-shot path. (V4-D)
|
|
124
|
+
*/
|
|
125
|
+
finishReason?: LoopFinishReason;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* DELEGATION budget exceeded — the dollar cost of a delegated agent.
|
|
129
|
+
*
|
|
130
|
+
* ## Why the name changed in M91
|
|
131
|
+
*
|
|
132
|
+
* It was called `BudgetExceededError` and **shadowed** the SDK class of the same name, which belongs
|
|
133
|
+
* to another domain: context-WINDOW budget (`budgetName`/`window`/`mode`) against DELEGATION budget
|
|
134
|
+
* (`agentName`/`actualCost`). Since the consumer holds an unbreakable rule never to import
|
|
135
|
+
* `@theokit/sdk` directly, it **could never reach the SDK's** — and an `instanceof` against this
|
|
136
|
+
* barrel silently matched the wrong domain.
|
|
137
|
+
*
|
|
138
|
+
* It is the failure mode M73 documented in `auth-parity.test.ts`: when two classes compete for the
|
|
139
|
+
* same name, no behavioural test goes red — only an identity `toBe` catches it.
|
|
140
|
+
*
|
|
141
|
+
* `subpath-coverage.test.ts` recorded the collision as a `gap` on `./errors`, with the reason written
|
|
142
|
+
* down and the acknowledgement that renaming was breaking and out of M78's scope. M91 paid the bill.
|
|
143
|
+
*/
|
|
144
|
+
/**
|
|
145
|
+
* M80 — extends {@link TheokitAgentError}, not plain `Error`.
|
|
146
|
+
*
|
|
147
|
+
* `isTransientError` is defined over `TheokitAgentError`, so a class outside that hierarchy is
|
|
148
|
+
* INVISIBLE to it and the only recourse left to a consumer is matching on message text. `code` is
|
|
149
|
+
* stable across a rename; `isRetryable` is DECLARED, because a default would be a retry policy
|
|
150
|
+
* nobody chose.
|
|
151
|
+
*/
|
|
152
|
+
declare class DelegationBudgetExceededError extends TheokitAgentError {
|
|
153
|
+
readonly agentName: string;
|
|
154
|
+
readonly actualCost: number;
|
|
155
|
+
readonly budgetLimit: number;
|
|
156
|
+
readonly name = "DelegationBudgetExceededError";
|
|
157
|
+
constructor(agentName: string, actualCost: number, budgetLimit: number);
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* @deprecated Use {@link DelegationBudgetExceededError}. The alias is kept for one major so anyone
|
|
161
|
+
* catching by the old name is not broken; it is the **same** class, not a copy — `instanceof` still
|
|
162
|
+
* holds in both directions, and a referential-identity test (`toBe`) pins that.
|
|
163
|
+
*/
|
|
164
|
+
declare const BudgetExceededError: typeof DelegationBudgetExceededError;
|
|
165
|
+
/** @deprecated Use {@link DelegationBudgetExceededError}. */
|
|
166
|
+
type BudgetExceededError = DelegationBudgetExceededError;
|
|
167
|
+
/**
|
|
168
|
+
* M80 — extends {@link TheokitAgentError}, not plain `Error`.
|
|
169
|
+
*
|
|
170
|
+
* `isTransientError` is defined over `TheokitAgentError`, so a class outside that hierarchy is
|
|
171
|
+
* INVISIBLE to it and the only recourse left to a consumer is matching on message text. `code` is
|
|
172
|
+
* stable across a rename; `isRetryable` is DECLARED, because a default would be a retry policy
|
|
173
|
+
* nobody chose.
|
|
174
|
+
*/
|
|
175
|
+
declare class DelegationError extends TheokitAgentError {
|
|
176
|
+
readonly agentName: string;
|
|
177
|
+
readonly cause: unknown;
|
|
178
|
+
readonly name = "DelegationError";
|
|
179
|
+
constructor(agentName: string, cause: unknown);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* ReflectionStrategy — composes INTO the loop between rounds (the loop calls
|
|
184
|
+
* `reflect()` then `LoopStrategy.shouldContinue()`).
|
|
185
|
+
*
|
|
186
|
+
* `'plan-act-reflect'` resolves to the `'ladder'` default shipped here; a custom
|
|
187
|
+
* strategy may be supplied (OCP — plan Drawback #2). `reflect()` is pure (no
|
|
188
|
+
* I/O, no LLM) — it inspects the round's outcome and returns feedback to inject
|
|
189
|
+
* into the next round's prompt plus a `continue` hint. The hard round ceiling
|
|
190
|
+
* lives in `LoopStrategy.shouldContinue` (maxIterations), NOT here.
|
|
191
|
+
*
|
|
192
|
+
* reference: knowledge-base/references/mastra agentic-loop/index.ts (onIterationComplete → { feedback, continue }).
|
|
193
|
+
*/
|
|
194
|
+
|
|
195
|
+
/** Result of reflecting on a completed round. */
|
|
196
|
+
interface ReflectionResult {
|
|
197
|
+
/** Optional text prepended to the next round's prompt. */
|
|
198
|
+
readonly feedback?: string;
|
|
199
|
+
/** Hint: should the loop reflect-and-continue? (the ceiling still bounds it) */
|
|
200
|
+
readonly continue: boolean;
|
|
201
|
+
}
|
|
202
|
+
/**
|
|
203
|
+
* V4-K: a per-run mutable scratch bag threaded to every `reflect()` call within one
|
|
204
|
+
* `runReflectiveLoopStream` run, so a STATEFUL strategy can accumulate cumulative state
|
|
205
|
+
* (counters, one-shot flags) across rounds. The framework owns the lifecycle (creates
|
|
206
|
+
* one per run, passes the SAME ref each round) but writes NOTHING into it — the strategy
|
|
207
|
+
* owns the contents. Generic by design: the framework cannot know app semantics (e.g.
|
|
208
|
+
* what an "edit" is). A consumer narrows it locally (`ctx as MyState`).
|
|
209
|
+
*/
|
|
210
|
+
type ReflectionContext = Record<string, unknown>;
|
|
211
|
+
/** Pluggable between-round reflection. Pure — never performs I/O. */
|
|
212
|
+
interface ReflectionStrategy {
|
|
213
|
+
/** Strategy identifier (e.g. `'ladder'`). */
|
|
214
|
+
readonly name: string;
|
|
215
|
+
/**
|
|
216
|
+
* Inspect the round outcome; return feedback + continue hint. `ctx` (V4-K) is the
|
|
217
|
+
* per-run mutable scratch — optional for backward compatibility (shipped strategies
|
|
218
|
+
* ignore it; stateful custom strategies accumulate in it across rounds).
|
|
219
|
+
*/
|
|
220
|
+
reflect(outcome: LoopOutcome, ctx?: ReflectionContext): ReflectionResult;
|
|
221
|
+
}
|
|
222
|
+
/** Serializable config for a ReflectionStrategy. SSoT per type-safety.md (ADR D3). */
|
|
223
|
+
declare const reflectionStrategyConfigSchema: z.ZodObject<{
|
|
224
|
+
name: z.ZodString;
|
|
225
|
+
}, z.core.$strip>;
|
|
226
|
+
type ReflectionStrategyConfig = z.infer<typeof reflectionStrategyConfigSchema>;
|
|
227
|
+
/**
|
|
228
|
+
* The default `'ladder'` reflection (what `'plan-act-reflect'` resolves to).
|
|
229
|
+
*
|
|
230
|
+
* Continues with bounded templated feedback while the round ended on
|
|
231
|
+
* `tool-calls`; terminates on any terminal `finishReason` (`stop`/`error`/
|
|
232
|
+
* `length`). The feedback is a short fixed template (bounded — EC-5; context
|
|
233
|
+
* growth is the SDK's responsibility, not the loop's).
|
|
234
|
+
*/
|
|
235
|
+
declare const ladderReflectionStrategy: ReflectionStrategy;
|
|
236
|
+
/**
|
|
237
|
+
* No-op reflection for `'react'` (multi-round WITHOUT reflection feedback).
|
|
238
|
+
*
|
|
239
|
+
* Returns `{ continue: true }` (no feedback) so the round-continuation decision
|
|
240
|
+
* is delegated entirely to `LoopStrategy.shouldContinue` (i.e. `react` loops
|
|
241
|
+
* while `finishReason === 'tool-calls'` under the ceiling). NOTE: the plan's
|
|
242
|
+
* pseudo-code (Files-to-edit) sketched `{ continue: false }`, which would make
|
|
243
|
+
* `react` single-shot — that contradicts the plan's own Deep Dives ("`react`
|
|
244
|
+
* still multi-rounds while finishReason==='tool-calls'"); `continue: true` is
|
|
245
|
+
* the behavior the resolved react LoopStrategy requires.
|
|
246
|
+
*/
|
|
247
|
+
declare const noopReflectionStrategy: ReflectionStrategy;
|
|
248
|
+
|
|
249
|
+
/**
|
|
250
|
+
* runReflectiveLoop — the multi-round reflective driver that gives `@MainLoop`
|
|
251
|
+
* its runtime (closes the metadata-only gap, V4-A / plan ADR D2).
|
|
252
|
+
*
|
|
253
|
+
* Per round it consumes ONE SDK stream turn (the model call stays in the SDK —
|
|
254
|
+
* the factory is `createSdkAgentStream(...)`, injected for testability), derives
|
|
255
|
+
* a {@link LoopOutcome}, asks the {@link ReflectionStrategy} for feedback, then
|
|
256
|
+
* the {@link LoopStrategy} whether to continue. Bounded by `maxIterations`
|
|
257
|
+
* (forced terminal at the ceiling — never an infinite loop). The bridge owns the
|
|
258
|
+
* loop; the SDK owns the model call (sdk-runtime.md / ADR 0031 — no second runtime).
|
|
259
|
+
*
|
|
260
|
+
* `runReflectiveLoop` is INTERNAL (not re-exported from the package barrel,
|
|
261
|
+
* Drawback #4) — consumed by `delegate()` (T2.2) and `AgentRunner` (T3.1).
|
|
262
|
+
*
|
|
263
|
+
* reference: knowledge-base/references/mastra agent.ts (re-enter the loop with feedback).
|
|
264
|
+
*/
|
|
265
|
+
|
|
266
|
+
/** One SDK stream turn: `createSdkAgentStream(...)` returns this shape. */
|
|
267
|
+
/**
|
|
268
|
+
* Opens one round's SDK stream. `opts.disableTools` (step-cap force-close) asks the factory to
|
|
269
|
+
* gate tools OFF for THIS round (the SDK adapter maps it to `tool_choice:"none"` at send-time, so a
|
|
270
|
+
* cached agent — whose tools can't be un-registered — is still forced to a text summary). Optional +
|
|
271
|
+
* ignored by injected test factories ⇒ backward-compatible.
|
|
272
|
+
*/
|
|
273
|
+
type RoundStreamFactory = (message: string, sessionId: string, opts?: {
|
|
274
|
+
disableTools?: boolean;
|
|
275
|
+
}) => AsyncIterable<StreamEvent>;
|
|
276
|
+
|
|
277
|
+
/**
|
|
278
|
+
* Multi-agent orchestration runtime.
|
|
279
|
+
*
|
|
280
|
+
* Provides `delegate()` — a function that lets a parent agent invoke a
|
|
281
|
+
* sub-agent and receive its result. Handles budget clamping (D4), tool sharing,
|
|
282
|
+
* toolbox auto-instantiation (EC-1), and routes the resolved `@MainLoop` strategy
|
|
283
|
+
* through `runReflectiveLoop` — the SAME driver `AgentRunner.run()` uses, so both
|
|
284
|
+
* on-ramps are one runtime (ADR D4). `simple-chat` ⇒ `shouldContinue:()=>false`
|
|
285
|
+
* ⇒ exactly one round; `react`/`plan-act-reflect` ⇒ multi-round reflective loop.
|
|
286
|
+
*/
|
|
287
|
+
|
|
288
|
+
interface DelegateOptions {
|
|
289
|
+
/**
|
|
290
|
+
* M81 — wall-clock cap for the delegation, in milliseconds. Absent ⇒ no clock cap.
|
|
291
|
+
*
|
|
292
|
+
* A DIFFERENT guard from `budget`: money is spent by work that progresses, and a delegation that
|
|
293
|
+
* HANGS burns clock without spending a cent. A consumer wrote its own timeout race with its own
|
|
294
|
+
* typed error because this was missing. Exceeding it raises `DelegationTimeoutError`, which —
|
|
295
|
+
* unlike the budget errors — is marked retryable, because a hang is often transient.
|
|
296
|
+
*/
|
|
297
|
+
readonly timeoutMs?: number;
|
|
298
|
+
/** Max USD for this sub-agent call. */
|
|
299
|
+
budget?: number;
|
|
300
|
+
/** Parent's remaining budget (for clamping). */
|
|
301
|
+
parentBudgetRemaining?: number;
|
|
302
|
+
/** Parent's tools (for sharing — sub-agent inherits these). */
|
|
303
|
+
parentTools?: CompiledTool[];
|
|
304
|
+
/**
|
|
305
|
+
* Parent's hooks. The member inherits them, and inheritance may only TIGHTEN: both
|
|
306
|
+
* `pre_tool_call` gates run and the first refusal wins, so a member cannot widen what the parent
|
|
307
|
+
* refused.
|
|
308
|
+
*
|
|
309
|
+
* Symmetric with `parentTools` on purpose — `delegate` already carried the parent's tools and its
|
|
310
|
+
* budget into the member's run and left its AUTHORITY behind, which is how a squad member could
|
|
311
|
+
* call a tool the supervisor had vetoed. The failure was silent: nothing threw, and the member's
|
|
312
|
+
* own suite passed because the member never declared the gate.
|
|
313
|
+
*
|
|
314
|
+
* To scope a member differently, pass its handlers on `spec.compiled.hooks` — they compose with
|
|
315
|
+
* these rather than replacing them, because a widening that a call site cannot see is the state
|
|
316
|
+
* this option exists to remove.
|
|
317
|
+
*/
|
|
318
|
+
parentHooks?: HookHandlers;
|
|
319
|
+
/** LLM API key (inherited from parent). */
|
|
320
|
+
apiKey?: string;
|
|
321
|
+
/** Session ID override (default: crypto.randomUUID for isolation). */
|
|
322
|
+
sessionId?: string;
|
|
323
|
+
/** Cancellation — aborts stop the reflective loop from re-entering. */
|
|
324
|
+
signal?: AbortSignal;
|
|
325
|
+
/** Per-run model override (`?? SubAgent @Agent model`). */
|
|
326
|
+
model?: string;
|
|
327
|
+
/** Per-run working directory → `Agent.create({ local: { cwd } })`. */
|
|
328
|
+
cwd?: string;
|
|
329
|
+
/** Per-run plugins (e.g. a read-only permission gate for an explore sub-agent). */
|
|
330
|
+
plugins?: PluginsSettings;
|
|
331
|
+
/** Per-run provider routing (e.g. OpenRouter). */
|
|
332
|
+
providers?: ProviderRoutingSettings;
|
|
333
|
+
/** Per-run sub-agent definitions. */
|
|
334
|
+
agents?: Record<string, AgentDefinition>;
|
|
335
|
+
/** Per-run SDK budget tracker (inner tool-loop cap). */
|
|
336
|
+
budgetTracker?: BudgetTracker;
|
|
337
|
+
/** Per-run pre-built SDK tools forwarded raw (V4-Q). */
|
|
338
|
+
sdkTools?: readonly CustomTool[];
|
|
339
|
+
/** Per-round transient retry (V4-P). */
|
|
340
|
+
retry?: RetryOptions;
|
|
341
|
+
/** Custom between-round reflection (default: ladder for `plan-act-reflect`, else noop). */
|
|
342
|
+
reflection?: ReflectionStrategy;
|
|
343
|
+
/** Per-run loop-ceiling override (`?? SubAgent @MainLoop maxIterations`). */
|
|
344
|
+
maxIterations?: number;
|
|
345
|
+
/**
|
|
346
|
+
* Called BEFORE the sub-agent runs. Returns the input the sub-agent will receive — return
|
|
347
|
+
* `ctx.input` unchanged, or a rewritten string (e.g. inject a persona). A transform, not a veto.
|
|
348
|
+
*/
|
|
349
|
+
onDelegationStart?: (ctx: {
|
|
350
|
+
subAgent: string;
|
|
351
|
+
input: string;
|
|
352
|
+
}) => string | Promise<string>;
|
|
353
|
+
/**
|
|
354
|
+
* Called AFTER the sub-agent completes. Returns the result the supervisor sees — return
|
|
355
|
+
* `ctx.result` unchanged, or a transformed one (e.g. redact, score, re-wrap).
|
|
356
|
+
*/
|
|
357
|
+
onDelegationComplete?: (ctx: {
|
|
358
|
+
subAgent: string;
|
|
359
|
+
result: DelegationResult;
|
|
360
|
+
}) => DelegationResult | Promise<DelegationResult>;
|
|
361
|
+
/**
|
|
362
|
+
* Injected stream factory (parity with `AgentRunnerRunOptions.streamFactory`) — drives the loop
|
|
363
|
+
* directly instead of the SDK adapter (tests / custom transport). Absent ⇒ `createSdkAgentStream`.
|
|
364
|
+
*/
|
|
365
|
+
streamFactory?: RoundStreamFactory;
|
|
366
|
+
}
|
|
367
|
+
/**
|
|
368
|
+
* Delegate a task to a sub-agent and collect its result.
|
|
369
|
+
*
|
|
370
|
+
* - Budget clamping: `min(parentBudgetRemaining, budget)` (D4)
|
|
371
|
+
* - Tool sharing: parent tools merged with sub-agent tools (sub wins on collision)
|
|
372
|
+
* - Toolbox auto-instantiation: sub-agent toolboxes instantiated without DI (EC-1)
|
|
373
|
+
* - Session isolation: each delegation gets a unique session ID (EC-4)
|
|
374
|
+
* - `@MainLoop` strategy runtime: routes through `runReflectiveLoop` (the same loop
|
|
375
|
+
* `AgentRunner.run` uses — one runtime for both on-ramps, ADR D4). The runtime
|
|
376
|
+
* metric (`THEO_AGENT_MAINLOOP_RUNTIME_APPLIED`) + typed-error + cumulative budget
|
|
377
|
+
* all live in the shared driver, so they fire identically on both paths.
|
|
378
|
+
*/
|
|
379
|
+
/**
|
|
380
|
+
* What `delegate` needs from a sub-agent: a name and already-compiled options (built by
|
|
381
|
+
* `applyCapabilities`). Compatible with {@link AgentRunnerSpec} — one spec drives both on-ramps.
|
|
382
|
+
*/
|
|
383
|
+
interface SubAgentSpec {
|
|
384
|
+
readonly name: string;
|
|
385
|
+
readonly compiled: CompiledAgentOptions;
|
|
386
|
+
/** Loop strategy (`@MainLoop({ strategy })`); absent ⇒ the same `'simple-chat'` default. */
|
|
387
|
+
readonly strategy?: MainLoopMeta['strategy'];
|
|
388
|
+
/** Loop ceiling (`@MainLoop({ maxIterations })`); a per-run override still wins. */
|
|
389
|
+
readonly maxIterations?: number;
|
|
390
|
+
}
|
|
391
|
+
declare function delegate(spec: SubAgentSpec, message: string, opts?: DelegateOptions): Promise<DelegationResult>;
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* M25 (theokit-ai-first) — background delegation + task-completion scoring.
|
|
395
|
+
*
|
|
396
|
+
* Two THIN wrappers over the M12 `delegate` (ADR 0038/0040): no new orchestration engine, no second
|
|
397
|
+
* loop, no new store. `delegateBackground` kicks off a sub-agent without blocking the supervisor and
|
|
398
|
+
* hands back a handle to await later. `delegateWithScoring` runs `delegate`, scores the result with
|
|
399
|
+
* an injected scorer, and re-delegates with the scorer's feedback until it passes or `maxRounds` is
|
|
400
|
+
* hit. The `delegate` implementation is injectable (`delegateFn`) so this is testable without a
|
|
401
|
+
* SubAgent class or an LLM — and so it NEVER re-implements the delegation runtime.
|
|
402
|
+
*/
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* M81 — anything that can run a delegation.
|
|
406
|
+
*
|
|
407
|
+
* The reach gap this closes: both wrappers took a `SubAgentSpec` produced by the capability
|
|
408
|
+
* compiler, so a consumer holding an SDK `SubAgent` or `Squad` could not feed them. That is why the
|
|
409
|
+
* scoring loop — the layer's highest-value piece — had ZERO adoption in a product that runs an
|
|
410
|
+
* explicit review pass: it was unreachable from the primitives that product actually holds.
|
|
411
|
+
*
|
|
412
|
+
* An SDK `SubAgent` or `Squad` satisfies this by having `run`. So does a test double, which is why
|
|
413
|
+
* the loop is now testable without a compiler, a class or an LLM.
|
|
414
|
+
*/
|
|
415
|
+
interface DelegationPort {
|
|
416
|
+
run(message: string): Promise<DelegationResult>;
|
|
417
|
+
}
|
|
418
|
+
/** What both wrappers accept: the compiled spec (unchanged) or the port (M81, additive). */
|
|
419
|
+
type DelegationTarget = SubAgentSpec | DelegationPort;
|
|
420
|
+
/** The delegation primitive both wrappers drive. Defaults to the M12 {@link delegate}. */
|
|
421
|
+
type DelegateFn = (subAgent: SubAgentSpec, message: string, opts?: DelegateOptions) => Promise<DelegationResult>;
|
|
422
|
+
/** A running background delegation the supervisor can await/poll later. */
|
|
423
|
+
interface BackgroundDelegation {
|
|
424
|
+
/** Await the sub-agent's result (or rejection). Idempotent — returns the same settled promise. */
|
|
425
|
+
wait(): Promise<DelegationResult>;
|
|
426
|
+
/** Whether the underlying delegation has resolved or rejected. */
|
|
427
|
+
settled(): boolean;
|
|
428
|
+
}
|
|
429
|
+
/**
|
|
430
|
+
* Start a sub-agent WITHOUT blocking the supervisor. Returns immediately with a handle; the
|
|
431
|
+
* supervisor keeps working and calls `wait()` when it needs the result. A thin async wrapper over
|
|
432
|
+
* `delegate` — not a scheduler (Top-risk 1). Rejections are still observable via `wait()`.
|
|
433
|
+
*/
|
|
434
|
+
declare function delegateBackground(subAgent: DelegationTarget, message: string, opts?: DelegateOptions & {
|
|
435
|
+
delegateFn?: DelegateFn;
|
|
436
|
+
}): BackgroundDelegation;
|
|
437
|
+
/** A scorer's verdict on a sub-agent result. `feedback` is fed back into the next round on failure. */
|
|
438
|
+
interface ScoreVerdict {
|
|
439
|
+
pass: boolean;
|
|
440
|
+
/** Optional numeric score (0..1) for logging/telemetry. */
|
|
441
|
+
score?: number;
|
|
442
|
+
/** Guidance appended to the next delegation when `pass` is false. */
|
|
443
|
+
feedback?: string;
|
|
444
|
+
}
|
|
445
|
+
/** Scores a sub-agent result. Opt-in (Top-risk 2) — the caller supplies it, and pays its cost. */
|
|
446
|
+
type Scorer = (result: DelegationResult) => ScoreVerdict | Promise<ScoreVerdict>;
|
|
447
|
+
/** The outcome of a scored delegation: the final result plus the per-round verdict trail. */
|
|
448
|
+
interface ScoredDelegation {
|
|
449
|
+
result: DelegationResult;
|
|
450
|
+
/** Rounds actually run (1..maxRounds). */
|
|
451
|
+
rounds: number;
|
|
452
|
+
/** Whether the final round passed the scorer. */
|
|
453
|
+
passed: boolean;
|
|
454
|
+
/** The verdict from each round, in order. */
|
|
455
|
+
verdicts: ScoreVerdict[];
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Run `delegate`, score the result, and re-delegate with the scorer's feedback until it passes or
|
|
459
|
+
* `maxRounds` is reached. Each round is ONE `delegate` call — no second loop, no new store. Returns
|
|
460
|
+
* the final result (passing, or the last attempt) with the per-round verdict trail.
|
|
461
|
+
*/
|
|
462
|
+
declare function delegateWithScoring(subAgent: DelegationTarget, message: string, opts: DelegateOptions & {
|
|
463
|
+
scorer: Scorer;
|
|
464
|
+
maxRounds?: number;
|
|
465
|
+
delegateFn?: DelegateFn;
|
|
466
|
+
feedbackTemplate?: (message: string, feedback: string) => string;
|
|
467
|
+
}): Promise<ScoredDelegation>;
|
|
468
|
+
|
|
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 };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
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,
|
|
4
|
-
export { c as
|
|
5
|
-
import {
|
|
6
|
-
export {
|
|
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-CmYUgNit.js';
|
|
6
|
+
export { b as AfterToolCallContext, c as AgentBuilder, d as AgentDefinitionError, e as AgentExecutionContext, f as AgentManifest, g as AgentManifestSource, h as AgentManifestTool, i as AgentRoute, j as AgentRouteContext, k as AgentRunInfo, l as AgentStreamEvent, m as AgentTurnMetadata, n as AgentsPluginOptions, o as ApiErrorContext, p as ApiErrorDecision, q as ApiErrorPolicy, r as ApprovalRequiredEvent, t as ArtifactChunkEvent, u as ArtifactStartEvent, B as BeforeToolCallContext, v as CheckpointSavedEvent, w as CompiledContextWindow, x as ContextualTool, D as DefinitionOrThunk, y as DelegationTimeoutError, z as DoneEvent, E as EphemeralAgent, F as ErrorEvent, G as FileEditEvent, I as IterationEvent, L as LLMCallContext, M as McpApprovalSpec, J as McpFileError, K as McpRegistryConfig, N as McpRequestContext, O as McpSelection, P as PartialToolCallEvent, Q as ProcessInputContext, R as RunStartedEvent, T as SdkAgentHandle, U as SdkMessage, V as SdkSendOptions, W as SdkTurnHandle, X as Segment, Y as StateUpdateEvent, Z as TextDeltaEvent, _ as ThinkingEvent, $ as ToolCallEvent, a0 as ToolCallVeto, a1 as ToolHooks, a2 as ToolHooksPlugin, a3 as ToolResultEvent, a4 as agentsPlugin, a5 as buildModelSelection, a6 as compileAgentModule, a7 as compileContextWindow, a8 as compileProjectContext, a9 as compileSkills, aa as createAgentExecutionContext, ab as createApiErrorHandler, ac as createSdkAgentStream, ad as createThinkTagExtractor, ae as createToolHooksPlugin, af as extractThinkTagStream, ag as generateAgentManifest, ah as generateAgentRoutes, ai as isAgentContext, aj as isApprovalRequired, ak as isDone, al as isError, am as isPartialToolCall, an as isTextDelta, ao as isToolCall, ap as isToolResult, aq as loadMcpJson, ar as mcpRegistry, as as mcpToolApprovals, at as presentUIMessageStream, au as projectContextMetadataOnlyKnobs, av as reasoningEffortOf, aw as resolveMcpServers, ax as runWithApiErrorHandling, ay as toAgentFactory, az as translateSdkEvent, aA as withClockCap, aB as withEphemeralAgent } from './bridge-entry-CmYUgNit.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
14
|
import { RetryOptions } from '@theokit/sdk/retry';
|
|
11
15
|
export * from '@theokit/sdk/retry';
|
|
12
16
|
import { CompressibleMessage } from '@theokit/sdk/compaction';
|
package/dist/index.js
CHANGED
|
@@ -1,11 +1,41 @@
|
|
|
1
1
|
import {
|
|
2
2
|
AgentBuilder,
|
|
3
3
|
AgentDefinitionError,
|
|
4
|
+
ConfigurationError,
|
|
5
|
+
ContextualTool,
|
|
6
|
+
McpFileError,
|
|
7
|
+
agentsPlugin,
|
|
8
|
+
compileAgentModule,
|
|
9
|
+
compileContextWindow,
|
|
10
|
+
compileHitlGates,
|
|
11
|
+
compileSkills,
|
|
12
|
+
compileTools,
|
|
13
|
+
createAgentExecutionContext,
|
|
14
|
+
createApiErrorHandler,
|
|
15
|
+
generateAgentManifest,
|
|
16
|
+
generateAgentRoutes,
|
|
17
|
+
isAgentContext,
|
|
18
|
+
isApprovalRequired,
|
|
19
|
+
isDone,
|
|
20
|
+
isError,
|
|
21
|
+
isPartialToolCall,
|
|
22
|
+
isTextDelta,
|
|
23
|
+
isToolCall,
|
|
24
|
+
isToolResult,
|
|
25
|
+
loadMcpJson,
|
|
26
|
+
mcpRegistry,
|
|
27
|
+
mcpToolApprovals,
|
|
28
|
+
presentUIMessageStream,
|
|
29
|
+
resolveMcpServers,
|
|
30
|
+
runWithApiErrorHandling,
|
|
31
|
+
streamAgentResponse,
|
|
32
|
+
streamAgentUIMessages,
|
|
33
|
+
toolRuntimeName
|
|
34
|
+
} from "./chunk-CAXGTLRU.js";
|
|
35
|
+
import {
|
|
4
36
|
AgentRunner,
|
|
5
37
|
AgentRunnerBuilder,
|
|
6
38
|
BudgetExceededError,
|
|
7
|
-
ConfigurationError,
|
|
8
|
-
ContextualTool,
|
|
9
39
|
CostBudgetExceededError,
|
|
10
40
|
DEFAULT_KEEP_TOKENS,
|
|
11
41
|
DEFAULT_MAX_ITERATIONS,
|
|
@@ -15,19 +45,10 @@ import {
|
|
|
15
45
|
GoalRunner,
|
|
16
46
|
GuardrailViolationError,
|
|
17
47
|
JudgeCredentialError,
|
|
18
|
-
McpFileError,
|
|
19
|
-
agentsPlugin,
|
|
20
48
|
buildModelSelection,
|
|
21
49
|
compactionStrategyConfigSchema,
|
|
22
|
-
compileAgentModule,
|
|
23
|
-
compileContextWindow,
|
|
24
|
-
compileHitlGates,
|
|
25
50
|
compileProjectContext,
|
|
26
|
-
compileSkills,
|
|
27
|
-
compileTools,
|
|
28
51
|
costGuard,
|
|
29
|
-
createAgentExecutionContext,
|
|
30
|
-
createApiErrorHandler,
|
|
31
52
|
createSdkAgentStream,
|
|
32
53
|
createThinkTagExtractor,
|
|
33
54
|
createToolHooksPlugin,
|
|
@@ -37,46 +58,27 @@ import {
|
|
|
37
58
|
estimateTokens,
|
|
38
59
|
extractThinkTagStream,
|
|
39
60
|
formatGoalEvent,
|
|
40
|
-
generateAgentManifest,
|
|
41
|
-
generateAgentRoutes,
|
|
42
|
-
isAgentContext,
|
|
43
|
-
isApprovalRequired,
|
|
44
|
-
isDone,
|
|
45
|
-
isError,
|
|
46
|
-
isPartialToolCall,
|
|
47
|
-
isTextDelta,
|
|
48
|
-
isToolCall,
|
|
49
|
-
isToolResult,
|
|
50
61
|
ladderReflectionStrategy,
|
|
51
|
-
loadMcpJson,
|
|
52
62
|
loopStrategyConfigSchema,
|
|
53
|
-
mcpRegistry,
|
|
54
|
-
mcpToolApprovals,
|
|
55
63
|
moderateOutputStream,
|
|
56
64
|
noopReflectionStrategy,
|
|
57
65
|
outputModeration,
|
|
58
66
|
piiDetector,
|
|
59
|
-
presentUIMessageStream,
|
|
60
67
|
projectContextMetadataOnlyKnobs,
|
|
61
68
|
promptInjectionDetector,
|
|
62
69
|
reasoningEffortOf,
|
|
63
70
|
reflectionStrategyConfigSchema,
|
|
64
71
|
resolveCompactionStrategy,
|
|
65
72
|
resolveLoopStrategy,
|
|
66
|
-
resolveMcpServers,
|
|
67
73
|
runInputGuards,
|
|
68
74
|
runOutputGuards,
|
|
69
|
-
runWithApiErrorHandling,
|
|
70
|
-
streamAgentResponse,
|
|
71
|
-
streamAgentUIMessages,
|
|
72
75
|
toAgentFactory,
|
|
73
76
|
tokenBudgetCompactionStrategy,
|
|
74
|
-
toolRuntimeName,
|
|
75
77
|
translateSdkEvent,
|
|
76
78
|
unicodeNormalizer,
|
|
77
79
|
withClockCap,
|
|
78
80
|
withEphemeralAgent
|
|
79
|
-
} from "./chunk-
|
|
81
|
+
} from "./chunk-W6TABP2S.js";
|
|
80
82
|
import "./chunk-RKWCXVYG.js";
|
|
81
83
|
import {
|
|
82
84
|
AGENT_BRAND,
|