@theokit/agents 0.47.0 → 1.0.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.
@@ -1,10 +1,188 @@
1
1
  import { ExecutionContext } from '@theokit/http';
2
- import { A as AgentOptions, g as ToolOptions, M as MainLoopMeta, a as ApprovalOptions, B as BudgetOptions, H as HumanInTheLoopOptions, t as GatewayOptions, z as MemoryOptions, O as SkillsOptions, r as ContextWindowOptions, K as ProjectContextOptions, x as McpServersMap, G as Guardrail, o as CompactionDecoratorConfig, j as CheckpointOptions, R as ReasoningEffort } from './types-DVA4LQsA.js';
3
- import { InlineSkill, SystemPromptResolver, SettingSource, MemorySettings, SkillsSettings, ContextSettings, CustomTool, PluginsSettings, Plugin, ProviderRoutingSettings, AgentDefinition as AgentDefinition$1, BudgetTracker, ModelSelection } from '@theokit/sdk';
2
+ import { SystemPromptResolver, InlineSkill, SettingSource, MemorySettings, SkillsSettings, ContextSettings, CustomTool, PluginsSettings, Plugin, ProviderRoutingSettings, AgentDefinition as AgentDefinition$1, BudgetTracker, ModelSelection } from '@theokit/sdk';
4
3
  import { z } from 'zod';
5
4
  import { UIMessageChunk } from 'ai';
6
5
  import { RetryOptions } from '@theokit/sdk/retry';
7
6
 
7
+ /**
8
+ * Provider-agnostic extended-thinking knob (M1 reasoning-visibility). The common set autocompletes;
9
+ * `(string & {})` accepts provider-specific values forward-compat (mirrors `AgentRunErrorCode`) — the
10
+ * SDK validates the value against the model's catalog. Defined in this leaf module so every layer
11
+ * (`@Agent` config, compiler, runner, sdk-adapter) imports it without an import cycle.
12
+ */
13
+ type ReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | (string & {});
14
+ /** Scalar agent configuration. */
15
+ interface AgentOptions {
16
+ /** Unique agent name (kebab-case). */
17
+ name: string;
18
+ /** HTTP route prefix (e.g., '/api/agents/support'). */
19
+ route: string;
20
+ /** LLM model identifier (e.g., 'claude-sonnet-4-5-20250929'). */
21
+ model?: string;
22
+ /** Extended-thinking effort; mapped to the SDK `ModelSelection.params` so the provider reasons. */
23
+ reasoningEffort?: ReasoningEffort;
24
+ /**
25
+ * Opt-in (default false): convert inline `<think>…</think>` in the text stream into `thinking`
26
+ * events (M2) — for models that emit reasoning as inline tags (qwen/deepseek) rather than via a
27
+ * native reasoning param. Off by default since a code assistant may emit literal `<think>` in text.
28
+ */
29
+ parseThinkTags?: boolean;
30
+ /**
31
+ * Opt-in (default false): strip a leaked Hermes `<function=…></tool_call>` tool-call dialect out of
32
+ * the visible text (theocode#32) — for models (qwen/qwen3-coder) that intermittently emit tool calls
33
+ * as text instead of native `tool_calls`. Off by default since a code assistant may emit a literal
34
+ * `<function=` in answer/code text. Sibling of {@link parseThinkTags}.
35
+ */
36
+ stripToolDialect?: boolean;
37
+ /**
38
+ * Opt-in (default false): recover a leaked Hermes `<function=…></tool_call>` tool-call dialect so the
39
+ * call actually EXECUTES (theokit#58 follow-up). Where {@link stripToolDialect} only hides the leaked
40
+ * block from the visible text, this enables the SDK's `extractToolCallsFromContent` on the chat route,
41
+ * so a `chat_completions` finish with ZERO native `tool_calls` has its text scanned for the dialect and
42
+ * any recovered calls are dispatched by the loop. For models (qwen/qwen3-coder via OpenRouter) that
43
+ * leak tool calls as text. Off by default (a code assistant may print a literal `<function=`); fail-open.
44
+ * Has effect only when {@link AgentOptions} routes a provider via `providers.routes`. Sibling of
45
+ * {@link stripToolDialect} — typically enabled together.
46
+ */
47
+ recoverLeakedToolCalls?: boolean;
48
+ /** Enable SSE streaming (default: true). */
49
+ stream?: boolean;
50
+ /** Maximum loop iterations before forcing a terminal response. */
51
+ maxIterations?: number;
52
+ /** Timeout in milliseconds for the entire agent run. */
53
+ timeoutMs?: number;
54
+ /**
55
+ * System prompt for the agent. Either a static string OR a
56
+ * {@link SystemPromptResolver} computed per request (V4-L.1, Axis-B) — the SDK
57
+ * invokes the resolver each send with the run's `SystemPromptContext` (cwd, etc.).
58
+ */
59
+ systemPrompt?: string | SystemPromptResolver;
60
+ }
61
+ /** Configuration stored by @MainLoop() decorator. */
62
+ interface MainLoopOptions {
63
+ /** Execution strategy. */
64
+ strategy?: 'simple-chat' | 'plan-act-reflect' | 'react';
65
+ /** Maximum iterations for this loop. */
66
+ maxIterations?: number;
67
+ /** Timeout in milliseconds. */
68
+ timeoutMs?: number;
69
+ }
70
+ /** Internal representation of a resolved @MainLoop. */
71
+ interface MainLoopMeta {
72
+ propertyKey: string | symbol;
73
+ strategy: 'simple-chat' | 'plan-act-reflect' | 'react';
74
+ maxIterations?: number;
75
+ timeoutMs?: number;
76
+ }
77
+ /** Configuration stored by @Toolbox() decorator. */
78
+ interface ToolboxOptions {
79
+ /** Namespace prefix for all tools in this toolbox (e.g., 'support'). */
80
+ namespace?: string;
81
+ }
82
+ /** Configuration stored by @Tool() decorator. */
83
+ interface ToolOptions {
84
+ /** Tool name (surfaced to LLM). */
85
+ name: string;
86
+ /** LLM-facing description. */
87
+ description: string;
88
+ /** Zod input schema — compiled to JSON Schema via defineTool(). */
89
+ input: z.ZodType;
90
+ /** Risk level (informational — feeds manifest + UI). */
91
+ risk?: 'low' | 'medium' | 'high';
92
+ }
93
+ /** Budget configuration for @Budget() decorator. */
94
+ interface BudgetOptions {
95
+ /** Maximum cost in USD for this scope. */
96
+ maxCostUsd: number;
97
+ /** Rolling window for budget tracking. */
98
+ window?: 'daily' | 'monthly';
99
+ }
100
+ /** Approval configuration for @RequiresApproval() decorator. */
101
+ interface ApprovalOptions {
102
+ /** Reason shown to the approver. */
103
+ reason: string;
104
+ }
105
+ /** Policy handler function type. */
106
+ type PolicyHandler = (user: {
107
+ roles: string[];
108
+ }) => boolean;
109
+ /**
110
+ * M53 — moved here from the `@HumanInTheLoop` decorator, which is being deleted: the type is
111
+ * consumed by `compileHitlGates` and the toolbox capability, not by the decorator alone.
112
+ */
113
+ type TimeoutAction = 'abort' | 'proceed' | 'retry';
114
+ interface HumanInTheLoopOptions {
115
+ /** Question shown to the human approver. */
116
+ question: string;
117
+ /** Timeout in milliseconds before onTimeout fires (default: 300_000 = 5 min). */
118
+ timeout?: number;
119
+ /** Action when timeout expires (default: 'abort'). */
120
+ onTimeout?: TimeoutAction;
121
+ /** Show the tool input to the approver (default: true). */
122
+ showInput?: boolean;
123
+ /**
124
+ * M20 — an optional JSON-schema descriptor of the custom payload the approver may attach (edited
125
+ * args, a review note). Carried into the `approval_required` event + `GET /approvals` so the UI
126
+ * knows what to collect. A plain JSON object, not a live Zod schema (keeps the wire serializable).
127
+ */
128
+ payloadSchema?: Record<string, unknown>;
129
+ }
130
+ /** M53 — moved from the `@MCP` decorator being deleted; consumed by the bridge and the adapter. */
131
+ interface McpServerConfig {
132
+ /** Command to start the MCP server. */
133
+ command: string;
134
+ /** Arguments passed to the command. */
135
+ args?: string[];
136
+ /** Environment variables for the server process. */
137
+ env?: Record<string, string>;
138
+ /** Working directory for the server process. */
139
+ cwd?: string;
140
+ }
141
+ type McpServersMap = Record<string, McpServerConfig>;
142
+ /** M53 — moved from the `@ProjectContext` decorator being deleted; read by the compiler. */
143
+ type IndexStrategy = 'tree-sitter' | 'regex' | 'none';
144
+ type RelevanceStrategy = 'git-history' | 'import-graph' | 'semantic' | 'manual';
145
+ interface ProjectContextOptions {
146
+ /** Files that mark the project root (searched upward from cwd). */
147
+ rootMarkers?: string[];
148
+ /** How to index the codebase for structural understanding. */
149
+ indexStrategy?: IndexStrategy;
150
+ /** Maximum files to include in context per request. */
151
+ maxFilesInContext?: number;
152
+ /** How to rank file relevance when selecting context. */
153
+ relevanceStrategy?: RelevanceStrategy;
154
+ /** Glob patterns to exclude from indexing and context. */
155
+ ignorePatterns?: string[];
156
+ /** File extensions to include in indexing (default: all text files). */
157
+ includeExtensions?: string[];
158
+ }
159
+ type CheckpointStrategy = 'after-tool-call' | 'after-iteration' | 'manual';
160
+ type CheckpointStorage = 'memory' | 'filesystem' | 'drizzle' | 'redis';
161
+ interface CheckpointOptions {
162
+ /** Where to persist checkpoints. */
163
+ storage?: CheckpointStorage;
164
+ /** When to auto-checkpoint (default: 'after-tool-call'). */
165
+ strategy?: CheckpointStrategy;
166
+ /** Maximum checkpoints to retain per run (rolling window). */
167
+ maxCheckpoints?: number;
168
+ /** Time-to-live in ms before checkpoints expire (default: 3_600_000 = 1h). */
169
+ ttl?: number;
170
+ }
171
+ type MemoryProvider = 'built-in' | 'honcho' | 'supermemory' | 'mem0';
172
+ type MemoryScope = 'per-user' | 'per-agent' | 'per-tenant' | 'global';
173
+ interface MemoryOptions {
174
+ /** Memory provider backend. */
175
+ provider?: MemoryProvider;
176
+ /** Enable semantic search via embeddings. */
177
+ embeddings?: boolean;
178
+ /** Enable full-text search (FTS5). */
179
+ fts?: boolean;
180
+ /** Memory isolation scope (default: 'per-user'). */
181
+ scope?: MemoryScope;
182
+ /** Maximum facts to retain per scope (0 = unlimited). */
183
+ maxFacts?: number;
184
+ }
185
+
8
186
  /**
9
187
  * AgentExecutionContext — extends http-decorators' ExecutionContext with agent-specific methods.
10
188
  *
@@ -17,7 +195,7 @@ interface AgentRunInfo {
17
195
  startedAt: Date;
18
196
  }
19
197
  interface AgentExecutionContext extends ExecutionContext {
20
- /** The agent's configuration from @Agent() decorator. */
198
+ /** The agent's scalar configuration. */
21
199
  getAgent(): AgentOptions;
22
200
  /** The current run information. */
23
201
  getRun(): AgentRunInfo;
@@ -32,77 +210,51 @@ declare function createAgentExecutionContext(base: ExecutionContext, agent: Agen
32
210
  declare function isAgentContext(ctx: ExecutionContext): ctx is AgentExecutionContext;
33
211
 
34
212
  /**
35
- * Walk decorator metadata on agent + toolbox classes.
36
- * Mirrors http-decorators' walkControllerMetadata() pattern.
213
+ * M9 (theokit-ai-first) guardrail contract + typed errors.
37
214
  *
38
- * EC-1: throws if @Agent class is missing @MainLoop.
39
- * EC-4: throws on duplicate routes across agents.
215
+ * ADR-0040 § D2: guardrails are a HOME/BOUNDARY concern (filter user input before the SDK,
216
+ * filter model output before the client). They REUSE the SDK runtime — this module makes zero
217
+ * LLM calls. A guard reports one of three actions; the pipeline (`pipeline.ts`) enforces them.
40
218
  */
41
-
219
+ /** What a guard decided for a piece of text. */
220
+ type GuardrailAction = 'allow' | 'block' | 'redact';
42
221
  /**
43
- * Stable warning codes for agent pipeline metadata-only decorators.
44
- * Test by code, not by message string. Document in agent support matrix.
222
+ * The result of a single guard check.
223
+ * - `allow` — text passes untouched.
224
+ * - `block` — the pipeline throws {@link GuardrailViolationError}; the run stops fail-fast.
225
+ * - `redact` — the pipeline replaces the text with {@link GuardrailResult.text} and continues.
45
226
  */
46
- declare const AgentWarningCode: {
47
- readonly INTERCEPTOR_METADATA_ONLY: "THEO_AGENT_INTERCEPTOR_METADATA_ONLY";
48
- readonly FILTER_METADATA_ONLY: "THEO_AGENT_FILTER_METADATA_ONLY";
49
- readonly BUDGET_TOP_LEVEL_METADATA_ONLY: "THEO_AGENT_BUDGET_TOP_LEVEL_METADATA_ONLY";
50
- readonly CONTEXT_STRATEGY_METADATA_ONLY: "THEO_AGENT_CONTEXT_STRATEGY_METADATA_ONLY";
51
- readonly PROJECT_CONTEXT_KNOB_METADATA_ONLY: "THEO_AGENT_PROJECT_CONTEXT_KNOB_METADATA_ONLY";
52
- readonly CHECKPOINT_STORAGE_METADATA_ONLY: "THEO_AGENT_CHECKPOINT_STORAGE_METADATA_ONLY";
53
- };
54
- interface AgentWalkResult {
55
- agentConfig: AgentOptions;
56
- mainLoop: MainLoopMeta;
57
- toolboxes: ToolboxWalkResult[];
58
- guards: Function[];
59
- interceptors: Function[];
60
- filters: Function[];
61
- route: string;
62
- gateway?: GatewayOptions;
63
- subAgentClasses: Function[];
64
- memory?: MemoryOptions;
65
- skills?: SkillsOptions;
66
- contextWindow?: ContextWindowOptions;
67
- projectContext?: ProjectContextOptions;
68
- mcpServers?: McpServersMap;
69
- /** M9 — `@Guardrails([...])` input/output guards when the class declares them; absent ⇒ none. */
70
- guardrails?: readonly Guardrail[];
71
- compaction?: CompactionDecoratorConfig;
72
- /** `@Checkpoint` config (M4) when the agent declares resumable execution; absent ⇒ no checkpoint. */
73
- checkpoint?: CheckpointOptions;
74
- }
75
- interface ToolboxWalkResult {
76
- class: Function;
77
- namespace: string;
78
- tools: ToolWalkResult[];
79
- guards: Function[];
80
- }
81
- interface ToolWalkResult {
82
- propertyKey: string | symbol;
83
- config: ToolOptions;
84
- guards: Function[];
85
- approval?: ApprovalOptions;
86
- capabilities?: string[];
87
- budget?: BudgetOptions;
88
- trace: boolean;
89
- audit: boolean;
90
- /** `@HumanInTheLoop` config when the tool method is gated (M4); absent ⇒ not gated. */
91
- hitl?: HumanInTheLoopOptions;
227
+ interface GuardrailResult {
228
+ action: GuardrailAction;
229
+ /** Human-readable reason — required in spirit for `block`, surfaced in the thrown error. */
230
+ reason?: string;
231
+ /** The transformed text — present (and used) only when `action === 'redact'`. */
232
+ text?: string;
92
233
  }
93
234
  /**
94
- * Walk all metadata on an agent class and its toolboxes.
95
- * Memoized per AgentClass via WeakMap.
96
- *
97
- * @throws Error if @Agent is missing @MainLoop (EC-1)
235
+ * A guardrail. A guard MAY inspect input (before the model), output (after the model), or both.
236
+ * A guard that omits a phase hook is skipped for that phase.
98
237
  */
99
- declare function walkAgentMetadata(AgentClass: Function, toolboxClasses?: Function[]): AgentWalkResult;
100
- /**
101
- * Validate that no two agents share the same route prefix.
102
- *
103
- * @throws Error on duplicate routes (EC-4)
104
- */
105
- declare function validateUniqueRoutes(results: AgentWalkResult[]): void;
238
+ interface Guardrail {
239
+ readonly name: string;
240
+ checkInput?(text: string): GuardrailResult | Promise<GuardrailResult>;
241
+ checkOutput?(text: string): GuardrailResult | Promise<GuardrailResult>;
242
+ }
243
+ /** Which boundary phase a violation happened in. */
244
+ type GuardrailPhase = 'input' | 'output';
245
+ /** Thrown (fail-fast) when a guard returns `action: 'block'`. Typed per error-handling.md. */
246
+ declare class GuardrailViolationError extends Error {
247
+ readonly guardName: string;
248
+ readonly phase: GuardrailPhase;
249
+ readonly reason: string;
250
+ constructor(guardName: string, phase: GuardrailPhase, reason: string);
251
+ }
252
+ /** Thrown when {@link costGuard}'s cumulative token budget is exceeded. */
253
+ declare class CostBudgetExceededError extends Error {
254
+ readonly usedTokens: number;
255
+ readonly maxTokens: number;
256
+ constructor(usedTokens: number, maxTokens: number);
257
+ }
106
258
 
107
259
  /**
108
260
  * M13 (theokit-ai-first) — per-request skills resolution (ADR-0040 § D2, home/boundary concern).
@@ -141,6 +293,32 @@ declare function resolveEnabledSkills(selection: SkillsSelection | undefined, ct
141
293
  * EC-3: throws if toolbox instance is missing from the instances map.
142
294
  */
143
295
 
296
+ /**
297
+ * M53 — the input shape `compileTools`/`compileHitlGates` consume, declared WITH them now that the
298
+ * metadata walk that used to own it is gone. `ToolboxCapability` builds this from a class'
299
+ * `static tools` declaration.
300
+ */
301
+ /** A guard/interceptor class token — identity only (the DI container instantiates it). */
302
+ type ClassToken = abstract new (...args: never[]) => object;
303
+ interface ToolWalkResult {
304
+ propertyKey: string | symbol;
305
+ config: ToolOptions;
306
+ guards: ClassToken[];
307
+ approval?: ApprovalOptions;
308
+ capabilities?: string[];
309
+ budget?: BudgetOptions;
310
+ trace: boolean;
311
+ audit: boolean;
312
+ /** HITL config when the tool is gated (M4); absent ⇒ not gated. */
313
+ hitl?: HumanInTheLoopOptions;
314
+ }
315
+ interface ToolboxWalkResult {
316
+ /** The toolbox class — used as the identity key into `toolboxInstances`. */
317
+ class: ClassToken;
318
+ namespace: string;
319
+ tools: ToolWalkResult[];
320
+ guards: ClassToken[];
321
+ }
144
322
  /** Minimal interface matching defineTool() result shape. */
145
323
  interface CompiledTool {
146
324
  name: string;
@@ -164,7 +342,7 @@ interface CompiledTool {
164
342
  * @param toolboxes - Walked toolbox metadata
165
343
  * @param toolboxInstances - Map of Toolbox class → instantiated object (for `this` binding)
166
344
  */
167
- declare function compileTools(toolboxes: ToolboxWalkResult[], toolboxInstances: Map<Function, object>): CompiledTool[];
345
+ declare function compileTools(toolboxes: ToolboxWalkResult[], toolboxInstances: Map<ClassToken, object>): CompiledTool[];
168
346
  /** Compiled sub-agent definition matching SDK AgentDefinition shape. */
169
347
  interface CompiledSubAgent {
170
348
  model?: string;
@@ -180,13 +358,13 @@ interface CompiledSubAgent {
180
358
  /** Compiled agent options ready for SDK Agent.create(). */
181
359
  interface CompiledAgentOptions {
182
360
  model?: string;
183
- /** Extended-thinking effort declared via `@Agent({ reasoningEffort })`; mapped to SDK ModelSelection.params. */
361
+ /** Extended-thinking effort; mapped to SDK ModelSelection.params. */
184
362
  reasoningEffort?: ReasoningEffort;
185
- /** Opt-in `<think>`-tag extraction declared via `@Agent({ parseThinkTags })` (M2); wraps the stream when true. */
363
+ /** Opt-in `<think>`-tag extraction (M2); wraps the stream when true. */
186
364
  parseThinkTags?: boolean;
187
- /** Opt-in tool-dialect stripping declared via `@Agent({ stripToolDialect })` (theocode#32); strips leaked `<function=…></tool_call>` from text when true. */
365
+ /** Opt-in tool-dialect stripping (theocode#32); strips leaked `<function=…></tool_call>` from text when true. */
188
366
  stripToolDialect?: boolean;
189
- /** Opt-in leaked-dialect recovery declared via `@Agent({ recoverLeakedToolCalls })` (theokit#58); enables the SDK route's `extractToolCallsFromContent` so leaked tool calls EXECUTE when true. */
367
+ /** Opt-in leaked-dialect recovery (theokit#58); enables the SDK route's `extractToolCallsFromContent` so leaked tool calls EXECUTE when true. */
190
368
  recoverLeakedToolCalls?: boolean;
191
369
  /** Static prompt OR a per-request {@link SystemPromptResolver} (V4-L.1, Axis-B). */
192
370
  systemPrompt?: string | SystemPromptResolver;
@@ -239,12 +417,6 @@ interface CompiledAgentOptions {
239
417
  */
240
418
  skillsResolver?: SkillsSelection;
241
419
  }
242
- /**
243
- * Compile @Agent metadata into SDK-compatible options.
244
- *
245
- * EC-7: agents without toolboxes produce tools: [].
246
- */
247
- declare function compileAgent(walkResult: AgentWalkResult, toolboxInstances?: Map<Function, object>): CompiledAgentOptions;
248
420
 
249
421
  /**
250
422
  * M8-3 — compile `@Skills` metadata into the SDK's `SkillsSettings`.
@@ -261,6 +433,16 @@ declare function compileAgent(walkResult: AgentWalkResult, toolboxInstances?: Ma
261
433
  * enables every discovered skill)
262
434
  */
263
435
 
436
+ /**
437
+ * M53 — the options shape lives WITH its conversion now. It used to be declared on the decorator
438
+ * that is being deleted, which would have taken a type the compiler needs down with it.
439
+ */
440
+ interface SkillsOptions {
441
+ /** Skill names to include (resolved from `.theokit/skills/<name>/SKILL.md`). */
442
+ include: string[];
443
+ /** Auto-discover every skill under `.theokit/skills/` (default: false). */
444
+ autoDiscover?: boolean;
445
+ }
264
446
  declare function compileSkills(options: SkillsOptions): SkillsSettings;
265
447
 
266
448
  /**
@@ -275,6 +457,23 @@ declare function compileSkills(options: SkillsOptions): SkillsSettings;
275
457
  * (ADR D2) instead of silently dropping them (G10 — honest enforcement).
276
458
  */
277
459
 
460
+ /** How to compact the transcript when `maxTokens` is exceeded. */
461
+ type ContextCompactionStrategy = 'truncate-oldest' | 'summarize-oldest' | 'sliding-window' | 'priority-based';
462
+ /**
463
+ * M53 — declared here, with its conversion, instead of on the decorator being deleted.
464
+ */
465
+ interface ContextWindowOptions {
466
+ /** Maximum tokens before compaction triggers. */
467
+ maxTokens?: number;
468
+ /** How to compact when maxTokens is exceeded. */
469
+ compactionStrategy?: ContextCompactionStrategy;
470
+ /** Always preserve the system prompt during compaction (default: true). */
471
+ preserveSystemPrompt?: boolean;
472
+ /** Number of recent messages to always keep intact (default: 10). */
473
+ preserveLastN?: number;
474
+ /** Keep all tool results even during compaction (default: true). */
475
+ preserveToolResults?: boolean;
476
+ }
278
477
  interface CompiledContextWindow {
279
478
  /** SDK-shaped context budget passed to `Agent.create({ context })`. */
280
479
  context: ContextSettings;
@@ -490,7 +689,7 @@ declare function isApprovalRequired(e: AgentStreamEvent): e is ApprovalRequiredE
490
689
  /**
491
690
  * Auto-generate HTTP routes from @Agent metadata — Web Standard.
492
691
  *
493
- * Per ADR D5: @Agent({ route }) auto-generates two endpoints:
692
+ * Per ADR D5: an agent's `route` auto-generates two endpoints:
494
693
  * - POST {route}/chat — send message, receive SSE stream
495
694
  * - GET {route}/runs/:runId — get run status/result
496
695
  *
@@ -503,7 +702,14 @@ interface AgentRoute {
503
702
  handler: (request: Request) => Promise<Response>;
504
703
  }
505
704
  interface AgentRouteContext {
506
- walkResult: AgentWalkResult;
705
+ /**
706
+ * M53 — only the mounting `route` was ever read from the walk, so the generator declares that
707
+ * instead of the whole `AgentWalkResult` (which chained it to the decorator metadata walk).
708
+ * `AgentWalkResult` satisfies this structurally, so the decorator path is unchanged.
709
+ */
710
+ walkResult: {
711
+ route: string;
712
+ };
507
713
  compiledOptions: CompiledAgentOptions;
508
714
  createRun: (message: string, sessionId: string) => AsyncIterable<StreamEvent>;
509
715
  getRun?: (runId: string) => Promise<{
@@ -542,7 +748,7 @@ interface DefineAgentConfig<TInput extends z.ZodType = z.ZodType> {
542
748
  model?: string;
543
749
  /** Static system prompt. */
544
750
  system?: string;
545
- /** Extended-thinking effort (mirrors `@Agent({ reasoningEffort })`). */
751
+ /** Extended-thinking effort. */
546
752
  reasoningEffort?: ReasoningEffort;
547
753
  /**
548
754
  * Pre-built tools. Accepts the `@theokit/sdk` `CustomTool` that `defineAgentTool`
@@ -738,9 +944,11 @@ interface RuntimeOverrides {
738
944
  * Returns a function that, given a message + sessionId, yields TheoKit
739
945
  * AgentStreamEvent via the SDK's Agent.create() + Run.stream() pipeline.
740
946
  */
741
- declare function createSdkAgentStream(compiled: CompiledAgentOptions, compiledTools: CompiledTool[], apiKey: string, overrides?: RuntimeOverrides): (message: string, sessionId: string, factoryOpts?: {
947
+ declare function createSdkAgentStream(compiled: CompiledAgentOptions, compiledTools: CompiledTool[], apiKey: string, overrides?: RuntimeOverrides): ((message: string, sessionId: string, factoryOpts?: {
742
948
  disableTools?: boolean;
743
- }) => AsyncIterable<StreamEvent>;
949
+ }) => AsyncIterable<StreamEvent>) & {
950
+ resolvedModel: string;
951
+ };
744
952
  /**
745
953
  * The minimal `SDKAgent` surface a serving host needs (ACP checks `agentId: string` + `send: fn`).
746
954
  * `Agent.getOrCreate` returns the real SDK agent — this alias just types what {@link toAgentFactory}
@@ -1080,16 +1288,6 @@ interface HitlWiring {
1080
1288
  declare class AgentDefinitionError extends Error {
1081
1289
  constructor(source: string);
1082
1290
  }
1083
- /**
1084
- * Compile a loaded `agents/` module to SDK-ready options. Accepts a `defineAgent` value
1085
- * (zero-config surface) OR an `@Agent`-decorated class (advanced surface). `source` labels
1086
- * the fail-fast error (typically the file path).
1087
- *
1088
- * For a class agent, its `@Mixin(...)` toolboxes are gathered (the declared tool-association
1089
- * mechanism, same as `app.ts`/`theokit-plugin.ts`) and instantiated with a no-arg `new` — the
1090
- * zero-config file convention has no DI container. This is what makes a `@HumanInTheLoop`-gated
1091
- * tool on a mixin actually gate through the M2 endpoint (M4): its config reaches `compiled.hitl`.
1092
- */
1093
1291
  declare function compileAgentModule(mod: unknown, source?: string): CompiledAgentOptions;
1094
1292
  /** HITL wiring supplied by the harness (mount-agent): the gated-tool map + the approval resolver. */
1095
1293
  interface StreamHitlOptions {
@@ -1423,7 +1621,19 @@ interface DelegateOptions {
1423
1621
  * metric (`THEO_AGENT_MAINLOOP_RUNTIME_APPLIED`) + typed-error + cumulative budget
1424
1622
  * all live in the shared driver, so they fire identically on both paths.
1425
1623
  */
1426
- declare function delegate(SubAgentClass: Function, message: string, opts?: DelegateOptions): Promise<DelegationResult>;
1624
+ /**
1625
+ * What `delegate` needs from a sub-agent: a name and already-compiled options (built by
1626
+ * `applyCapabilities`). Compatible with {@link AgentRunnerSpec} — one spec drives both on-ramps.
1627
+ */
1628
+ interface SubAgentSpec {
1629
+ readonly name: string;
1630
+ readonly compiled: CompiledAgentOptions;
1631
+ /** Loop strategy (`@MainLoop({ strategy })`); absent ⇒ the same `'simple-chat'` default. */
1632
+ readonly strategy?: MainLoopMeta['strategy'];
1633
+ /** Loop ceiling (`@MainLoop({ maxIterations })`); a per-run override still wins. */
1634
+ readonly maxIterations?: number;
1635
+ }
1636
+ declare function delegate(spec: SubAgentSpec, message: string, opts?: DelegateOptions): Promise<DelegationResult>;
1427
1637
 
1428
1638
  /**
1429
1639
  * M10 (theokit-ai-first) — createToolHooksPlugin: `beforeToolCall` / `afterToolCall` observability.
@@ -1585,7 +1795,7 @@ declare function createApiErrorHandler<R = unknown>(policy: ApiErrorPolicy<R>):
1585
1795
  */
1586
1796
 
1587
1797
  /** The delegation primitive both wrappers drive. Defaults to the M12 {@link delegate}. */
1588
- type DelegateFn = (subAgent: Function, message: string, opts?: DelegateOptions) => Promise<DelegationResult>;
1798
+ type DelegateFn = (subAgent: SubAgentSpec, message: string, opts?: DelegateOptions) => Promise<DelegationResult>;
1589
1799
  /** A running background delegation the supervisor can await/poll later. */
1590
1800
  interface BackgroundDelegation {
1591
1801
  /** Await the sub-agent's result (or rejection). Idempotent — returns the same settled promise. */
@@ -1598,7 +1808,7 @@ interface BackgroundDelegation {
1598
1808
  * supervisor keeps working and calls `wait()` when it needs the result. A thin async wrapper over
1599
1809
  * `delegate` — not a scheduler (Top-risk 1). Rejections are still observable via `wait()`.
1600
1810
  */
1601
- declare function delegateBackground(subAgent: Function, message: string, opts?: DelegateOptions & {
1811
+ declare function delegateBackground(subAgent: SubAgentSpec, message: string, opts?: DelegateOptions & {
1602
1812
  delegateFn?: DelegateFn;
1603
1813
  }): BackgroundDelegation;
1604
1814
  /** A scorer's verdict on a sub-agent result. `feedback` is fed back into the next round on failure. */
@@ -1626,7 +1836,7 @@ interface ScoredDelegation {
1626
1836
  * `maxRounds` is reached. Each round is ONE `delegate` call — no second loop, no new store. Returns
1627
1837
  * the final result (passing, or the last attempt) with the per-round verdict trail.
1628
1838
  */
1629
- declare function delegateWithScoring(subAgent: Function, message: string, opts: DelegateOptions & {
1839
+ declare function delegateWithScoring(subAgent: SubAgentSpec, message: string, opts: DelegateOptions & {
1630
1840
  scorer: Scorer;
1631
1841
  maxRounds?: number;
1632
1842
  delegateFn?: DelegateFn;
@@ -1690,7 +1900,63 @@ declare function mcpToolApprovals(specs: Record<string, McpApprovalSpec>): Recor
1690
1900
  *
1691
1901
  * Feeds: theokit agents list/inspect, TheoCloud deploy, UI agent consoles.
1692
1902
  */
1693
-
1903
+ /**
1904
+ * M53 — the manifest's OWN input contract, listing exactly the members it reads. It used to take an
1905
+ * `AgentWalkResult`, which chained the manifest to the decorator metadata walk that M53 deletes.
1906
+ *
1907
+ * `AgentWalkResult` satisfies this structurally, so the decorator path keeps working unchanged while
1908
+ * the migration is in flight; once the walk is gone, the capability path builds this directly. The
1909
+ * point is that the manifest never needed the whole walk — only these members.
1910
+ */
1911
+ interface AgentManifestSource {
1912
+ readonly agentConfig: {
1913
+ name: string;
1914
+ model?: string;
1915
+ stream?: boolean;
1916
+ };
1917
+ readonly route: string;
1918
+ readonly mainLoop: {
1919
+ propertyKey: string | symbol;
1920
+ strategy: string;
1921
+ };
1922
+ readonly guards: readonly {
1923
+ name: string;
1924
+ }[];
1925
+ readonly interceptors: readonly {
1926
+ name: string;
1927
+ }[];
1928
+ readonly toolboxes: readonly {
1929
+ namespace?: string;
1930
+ tools: readonly {
1931
+ config: {
1932
+ name: string;
1933
+ description: string;
1934
+ risk?: string;
1935
+ };
1936
+ approval?: unknown;
1937
+ capabilities?: string[];
1938
+ trace: boolean;
1939
+ audit: boolean;
1940
+ }[];
1941
+ }[];
1942
+ readonly gateway?: {
1943
+ platforms: string[];
1944
+ sessionStrategy?: string;
1945
+ };
1946
+ readonly subAgentClasses: readonly {
1947
+ name: string;
1948
+ }[];
1949
+ readonly memory?: {
1950
+ provider?: string;
1951
+ embeddings?: boolean;
1952
+ fts?: boolean;
1953
+ scope?: string;
1954
+ };
1955
+ readonly skills?: {
1956
+ include?: string[];
1957
+ };
1958
+ readonly mcpServers?: Record<string, unknown>;
1959
+ }
1694
1960
  interface AgentManifest {
1695
1961
  version: '1.0';
1696
1962
  generatedAt: string;
@@ -1732,10 +1998,10 @@ interface AgentManifestTool {
1732
1998
  audit: boolean;
1733
1999
  }
1734
2000
  /**
1735
- * Generate a serializable agent manifest from walked metadata.
2001
+ * Generate a serializable agent manifest from an {@link AgentManifestSource} per agent.
1736
2002
  * All Function references are converted to string names for JSON safety.
1737
2003
  */
1738
- declare function generateAgentManifest(walkResults: AgentWalkResult[]): AgentManifest;
2004
+ declare function generateAgentManifest(sources: AgentManifestSource[]): AgentManifest;
1739
2005
 
1740
2006
  /**
1741
2007
  * agentsPlugin() — TheoKit dev-server plugin for agent routes.
@@ -1746,13 +2012,19 @@ declare function generateAgentManifest(walkResults: AgentWalkResult[]): AgentMan
1746
2012
  * Per ADR D6: structural { name, register } shape (no compile-time theokit dep).
1747
2013
  */
1748
2014
 
2015
+ /**
2016
+ * An agent the plugin mounts: its name, route and already-compiled options (from `applyCapabilities`).
2017
+ */
2018
+ interface PluginAgentEntry {
2019
+ readonly name: string;
2020
+ readonly route: string;
2021
+ readonly compiled: CompiledAgentOptions;
2022
+ }
1749
2023
  interface AgentsPluginOptions {
1750
- /** Agent classes decorated with @Agent(). */
1751
- agents: Function[];
1752
- /** Toolbox classes (or use @Mixin on agents). */
1753
- toolboxes?: Function[];
2024
+ /** Agents to mount: prepared entries built by `applyCapabilities`. */
2025
+ agents: PluginAgentEntry[];
1754
2026
  /** Factory that creates agent runs — bridges to SDK Agent.create() + agent.send(). */
1755
- createRunFactory?: (compiled: CompiledAgentOptions, walkResult: AgentWalkResult) => (message: string, sessionId: string) => AsyncIterable<StreamEvent>;
2027
+ createRunFactory?: (compiled: CompiledAgentOptions) => (message: string, sessionId: string) => AsyncIterable<StreamEvent>;
1756
2028
  }
1757
2029
  interface PluginApp {
1758
2030
  addHook(name: string, fn: (ctx: {
@@ -1768,4 +2040,4 @@ declare function agentsPlugin(opts: AgentsPluginOptions): {
1768
2040
  register(app: PluginApp): void;
1769
2041
  };
1770
2042
 
1771
- export { type McpRegistryConfig as $, type AgentManifestEntry as A, type BackgroundDelegation as B, type CompiledAgentOptions as C, type DelegationResult as D, type CheckpointSavedEvent as E, type CompiledContextWindow as F, type ContextualTool as G, DEFAULT_MAX_ITERATIONS as H, type DefineAgentConfig as I, type DelegateFn as J, type DelegateOptions as K, type LoopStrategy as L, DelegationError as M, type DoneEvent as N, type ErrorEvent as O, type FileEditEvent as P, type HitlDecision as Q, type ReflectionStrategy as R, type StreamEvent as S, type InferAgentInput as T, type InferAgentToolNames as U, type IterationEvent as V, type LLMCallContext as W, type LoopFinishReason as X, type LoopOutcome as Y, type LoopStrategyConfig as Z, type McpApprovalSpec as _, type CompiledTool as a, projectContextMetadataOnlyKnobs as a$, type McpRequestContext as a0, type McpSelection as a1, type PartialToolCallEvent as a2, type ProcessInputContext as a3, type ReflectionContext as a4, type ReflectionResult as a5, type ReflectionStrategyConfig as a6, type RunStartedEvent as a7, type ScoreVerdict as a8, type ScoredDelegation as a9, contextualTool as aA, createAgentExecutionContext as aB, createApiErrorHandler as aC, createSdkAgentStream as aD, createThinkTagExtractor as aE, createToolHooksPlugin as aF, delegate as aG, delegateBackground as aH, delegateWithScoring as aI, extractThinkTagStream as aJ, generateAgentManifest as aK, generateAgentRoutes as aL, isAgentContext as aM, isAgentDefinition as aN, isApprovalRequired as aO, isDone as aP, isError as aQ, isPartialToolCall as aR, isTextDelta as aS, isToolCall as aT, isToolResult as aU, ladderReflectionStrategy as aV, loopStrategyConfigSchema as aW, mcpRegistry as aX, mcpToolApprovals as aY, noopReflectionStrategy as aZ, presentUIMessageStream as a_, type Scorer as aa, type SdkAgentHandle as ab, type SdkMessage as ac, type Segment as ad, type SkillsRequestContext as ae, type SkillsSelection as af, type StateUpdateEvent as ag, type TextDeltaEvent as ah, type ThinkingEvent as ai, type ToolCallEvent as aj, type ToolCallVeto as ak, type ToolHooks as al, type ToolHooksPlugin as am, type ToolResultEvent as an, type ToolWalkResult as ao, type ToolboxWalkResult as ap, agent as aq, agentsPlugin as ar, buildModelSelection as as, compileAgent as at, compileAgentDefinition as au, compileAgentModule as av, compileContextWindow as aw, compileProjectContext as ax, compileSkills as ay, compileTools as az, type RoundStreamFactory as b, reflectionStrategyConfigSchema as b0, resolveEnabledSkills as b1, resolveLoopStrategy as b2, resolveMcpServers as b3, runWithApiErrorHandling as b4, streamAgentResponse as b5, streamAgentUIMessages as b6, toAgentFactory as b7, translateSdkEvent as b8, validateUniqueRoutes as b9, walkAgentMetadata as ba, AGENT_BRAND as c, type AfterToolCallContext as d, type AgentBuilder as e, type AgentDefinition as f, AgentDefinitionError as g, type AgentExecutionContext as h, type AgentManifest as i, type AgentManifestTool as j, type AgentRoute as k, type AgentRouteContext as l, type AgentRunInfo as m, type AgentStreamEvent as n, type AgentTurnMetadata as o, type AgentWalkResult as p, AgentWarningCode as q, type AgentsPluginOptions as r, type ApiErrorContext as s, type ApiErrorDecision as t, type ApiErrorPolicy as u, type ApprovalRequiredEvent as v, type ArtifactChunkEvent as w, type ArtifactStartEvent as x, type BeforeToolCallContext as y, BudgetExceededError as z };
2043
+ export { type DelegateOptions as $, type ApprovalOptions as A, type ApiErrorDecision as B, type CompiledAgentOptions as C, type DelegationResult as D, type ApiErrorPolicy as E, type ApprovalRequiredEvent as F, type Guardrail as G, type HumanInTheLoopOptions as H, type ArtifactChunkEvent as I, type ArtifactStartEvent as J, type BackgroundDelegation as K, type LoopStrategy as L, type MainLoopMeta as M, type BeforeToolCallContext as N, BudgetExceededError as O, type ProjectContextOptions as P, type BudgetOptions as Q, type ReflectionStrategy as R, type StreamEvent as S, type ToolOptions as T, type CheckpointSavedEvent as U, type CompiledContextWindow as V, type ContextualTool as W, CostBudgetExceededError as X, DEFAULT_MAX_ITERATIONS as Y, type DefineAgentConfig as Z, type DelegateFn as _, type CompiledTool as a, delegateBackground as a$, DelegationError as a0, type DoneEvent as a1, type ErrorEvent as a2, type FileEditEvent as a3, type GuardrailAction as a4, type GuardrailPhase as a5, type GuardrailResult as a6, GuardrailViolationError as a7, type HitlDecision as a8, type InferAgentInput as a9, type TextDeltaEvent as aA, type ThinkingEvent as aB, type TimeoutAction as aC, type ToolCallEvent as aD, type ToolCallVeto as aE, type ToolHooks as aF, type ToolHooksPlugin as aG, type ToolResultEvent as aH, type ToolWalkResult as aI, type ToolboxOptions as aJ, type ToolboxWalkResult as aK, agent as aL, agentsPlugin as aM, buildModelSelection as aN, compileAgentDefinition as aO, compileAgentModule as aP, compileContextWindow as aQ, compileProjectContext as aR, compileSkills as aS, compileTools as aT, contextualTool as aU, createAgentExecutionContext as aV, createApiErrorHandler as aW, createSdkAgentStream as aX, createThinkTagExtractor as aY, createToolHooksPlugin as aZ, delegate as a_, type InferAgentToolNames as aa, type IterationEvent as ab, type LLMCallContext as ac, type LoopFinishReason as ad, type LoopOutcome as ae, type LoopStrategyConfig as af, type MainLoopOptions as ag, type McpApprovalSpec as ah, type McpRegistryConfig as ai, type McpRequestContext as aj, type McpSelection as ak, type PartialToolCallEvent as al, type PolicyHandler as am, type ProcessInputContext as an, type ReflectionContext as ao, type ReflectionResult as ap, type ReflectionStrategyConfig as aq, type RunStartedEvent as ar, type ScoreVerdict as as, type ScoredDelegation as at, type Scorer as au, type SdkAgentHandle as av, type SdkMessage as aw, type Segment as ax, type SkillsRequestContext as ay, type StateUpdateEvent as az, type ReasoningEffort as b, delegateWithScoring as b0, extractThinkTagStream as b1, generateAgentManifest as b2, generateAgentRoutes as b3, isAgentContext as b4, isAgentDefinition as b5, isApprovalRequired as b6, isDone as b7, isError as b8, isPartialToolCall as b9, isTextDelta as ba, isToolCall as bb, isToolResult as bc, ladderReflectionStrategy as bd, loopStrategyConfigSchema as be, mcpRegistry as bf, mcpToolApprovals as bg, noopReflectionStrategy as bh, presentUIMessageStream as bi, projectContextMetadataOnlyKnobs as bj, reflectionStrategyConfigSchema as bk, resolveEnabledSkills as bl, resolveLoopStrategy as bm, resolveMcpServers as bn, runWithApiErrorHandling as bo, streamAgentResponse as bp, streamAgentUIMessages as bq, toAgentFactory as br, translateSdkEvent as bs, type RoundStreamFactory as c, type ContextWindowOptions as d, type McpServersMap as e, type MemoryOptions as f, type SkillsOptions as g, type SkillsSelection as h, type AgentManifestEntry as i, AGENT_BRAND as j, type AfterToolCallContext as k, type AgentBuilder as l, type AgentDefinition as m, AgentDefinitionError as n, type AgentExecutionContext as o, type AgentManifest as p, type AgentManifestSource as q, type AgentManifestTool as r, type AgentOptions as s, type AgentRoute as t, type AgentRouteContext as u, type AgentRunInfo as v, type AgentStreamEvent as w, type AgentTurnMetadata as x, type AgentsPluginOptions as y, type ApiErrorContext as z };