@theokit/agents 7.6.0 → 8.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.
Files changed (52) hide show
  1. package/dist/{agent-handle-BX4oFqfb.d.ts → agent-handle-Dgi4ZGbg.d.ts} +11 -1
  2. package/dist/ask.d.ts +190 -0
  3. package/dist/ask.js +167 -0
  4. package/dist/ask.js.map +1 -0
  5. package/dist/auth.d.ts +95 -1
  6. package/dist/auth.js +83 -0
  7. package/dist/auth.js.map +1 -1
  8. package/dist/{bridge-entry-CvmBrmc9.d.ts → bridge-entry-BEniSXWE.d.ts} +223 -700
  9. package/dist/bridge.d.ts +6 -3
  10. package/dist/bridge.js +16 -8
  11. package/dist/chunk-4VHCH6IZ.js +181 -0
  12. package/dist/chunk-4VHCH6IZ.js.map +1 -0
  13. package/dist/{chunk-22IPZFVT.js → chunk-C7UXZWVY.js} +167 -207
  14. package/dist/chunk-C7UXZWVY.js.map +1 -0
  15. package/dist/{chunk-2BAFKRXT.js → chunk-M6HMASZC.js} +9 -4
  16. package/dist/chunk-M6HMASZC.js.map +1 -0
  17. package/dist/client-react.d.ts +2 -1
  18. package/dist/client-react.js +1 -1
  19. package/dist/client.d.ts +3 -2
  20. package/dist/client.js +1 -1
  21. package/dist/commands.d.ts +120 -0
  22. package/dist/commands.js +145 -0
  23. package/dist/commands.js.map +1 -0
  24. package/dist/define-agent-3Kuf6iKM.d.ts +633 -0
  25. package/dist/doctor.d.ts +119 -0
  26. package/dist/doctor.js +84 -0
  27. package/dist/doctor.js.map +1 -0
  28. package/dist/hook-handlers-Cw2FsnE5.d.ts +56 -0
  29. package/dist/hooks.d.ts +225 -0
  30. package/dist/hooks.js +286 -0
  31. package/dist/hooks.js.map +1 -0
  32. package/dist/index.d.ts +170 -26
  33. package/dist/index.js +90 -22
  34. package/dist/index.js.map +1 -1
  35. package/dist/mcp-health.d.ts +69 -0
  36. package/dist/mcp-health.js +42 -0
  37. package/dist/mcp-health.js.map +1 -0
  38. package/dist/session.d.ts +238 -0
  39. package/dist/session.js +338 -0
  40. package/dist/session.js.map +1 -0
  41. package/dist/testing.d.ts +90 -1
  42. package/dist/testing.js +76 -1
  43. package/dist/testing.js.map +1 -1
  44. package/dist/tool-scope.d.ts +133 -0
  45. package/dist/tool-scope.js +61 -0
  46. package/dist/tool-scope.js.map +1 -0
  47. package/dist/usage.d.ts +98 -0
  48. package/dist/usage.js +55 -0
  49. package/dist/usage.js.map +1 -0
  50. package/package.json +34 -2
  51. package/dist/chunk-22IPZFVT.js.map +0 -1
  52. package/dist/chunk-2BAFKRXT.js.map +0 -1
@@ -0,0 +1,633 @@
1
+ import { McpServerConfig, SystemPromptResolver, InlineSkill, SettingSource, MemorySettings, SkillsSettings, ContextSettings, TrustPosture, CustomTool } from '@theokit/sdk';
2
+ import { z } from 'zod';
3
+ import { TheokitAgentError } from '@theokit/sdk/errors';
4
+ import { H as HookHandlers } from './hook-handlers-Cw2FsnE5.js';
5
+
6
+ /**
7
+ * Provider-agnostic extended-thinking knob (M1 reasoning-visibility). The common set autocompletes;
8
+ * `(string & {})` accepts provider-specific values forward-compat (mirrors `AgentRunErrorCode`) — the
9
+ * SDK validates the value against the model's catalog. Defined in this leaf module so every layer
10
+ * (`@Agent` config, compiler, runner, sdk-adapter) imports it without an import cycle.
11
+ */
12
+ type ReasoningEffort = 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | (string & {});
13
+ /** Scalar agent configuration. */
14
+ interface AgentOptions {
15
+ /** Unique agent name (kebab-case). */
16
+ name: string;
17
+ /** HTTP route prefix (e.g., '/api/agents/support'). */
18
+ route: string;
19
+ /** LLM model identifier (e.g., 'claude-sonnet-4-5-20250929'). */
20
+ model?: string;
21
+ /** Extended-thinking effort; mapped to the SDK `ModelSelection.params` so the provider reasons. */
22
+ reasoningEffort?: ReasoningEffort;
23
+ /**
24
+ * Opt-in (default false): convert inline `<think>…</think>` in the text stream into `thinking`
25
+ * events (M2) — for models that emit reasoning as inline tags (qwen/deepseek) rather than via a
26
+ * native reasoning param. Off by default since a code assistant may emit literal `<think>` in text.
27
+ */
28
+ parseThinkTags?: boolean;
29
+ /**
30
+ * Opt-in (default false): strip a leaked Hermes `<function=…></tool_call>` tool-call dialect out of
31
+ * the visible text (theocode#32) — for models (qwen/qwen3-coder) that intermittently emit tool calls
32
+ * as text instead of native `tool_calls`. Off by default since a code assistant may emit a literal
33
+ * `<function=` in answer/code text. Sibling of {@link parseThinkTags}.
34
+ */
35
+ stripToolDialect?: boolean;
36
+ /**
37
+ * Opt-in (default false): recover a leaked Hermes `<function=…></tool_call>` tool-call dialect so the
38
+ * call actually EXECUTES (theokit#58 follow-up). Where {@link stripToolDialect} only hides the leaked
39
+ * block from the visible text, this enables the SDK's `extractToolCallsFromContent` on the chat route,
40
+ * so a `chat_completions` finish with ZERO native `tool_calls` has its text scanned for the dialect and
41
+ * any recovered calls are dispatched by the loop. For models (qwen/qwen3-coder via OpenRouter) that
42
+ * leak tool calls as text. Off by default (a code assistant may print a literal `<function=`); fail-open.
43
+ * Has effect only when {@link AgentOptions} routes a provider via `providers.routes`. Sibling of
44
+ * {@link stripToolDialect} — typically enabled together.
45
+ */
46
+ recoverLeakedToolCalls?: boolean;
47
+ /** Enable SSE streaming (default: true). */
48
+ stream?: boolean;
49
+ /** Maximum loop iterations before forcing a terminal response. */
50
+ maxIterations?: number;
51
+ /** Timeout in milliseconds for the entire agent run. */
52
+ timeoutMs?: number;
53
+ /**
54
+ * System prompt for the agent. Either a static string OR a
55
+ * {@link SystemPromptResolver} computed per request (V4-L.1, Axis-B) — the SDK
56
+ * invokes the resolver each send with the run's `SystemPromptContext` (cwd, etc.).
57
+ */
58
+ systemPrompt?: string | SystemPromptResolver;
59
+ }
60
+ /** Configuration stored by @MainLoop() decorator. */
61
+ interface MainLoopOptions {
62
+ /** Execution strategy. */
63
+ strategy?: 'simple-chat' | 'plan-act-reflect' | 'react';
64
+ /** Maximum iterations for this loop. */
65
+ maxIterations?: number;
66
+ /** Timeout in milliseconds. */
67
+ timeoutMs?: number;
68
+ }
69
+ /** Internal representation of a resolved @MainLoop. */
70
+ interface MainLoopMeta {
71
+ propertyKey: string | symbol;
72
+ strategy: 'simple-chat' | 'plan-act-reflect' | 'react';
73
+ maxIterations?: number;
74
+ timeoutMs?: number;
75
+ }
76
+ /** Configuration stored by @Toolbox() decorator. */
77
+ interface ToolboxOptions {
78
+ /** Namespace prefix for all tools in this toolbox (e.g., 'support'). */
79
+ namespace?: string;
80
+ }
81
+ /** Configuration stored by @Tool() decorator. */
82
+ interface ToolOptions {
83
+ /** Tool name (surfaced to LLM). */
84
+ name: string;
85
+ /** LLM-facing description. */
86
+ description: string;
87
+ /** Zod input schema — compiled to JSON Schema via defineTool(). */
88
+ input: z.ZodType;
89
+ /** Risk level (informational — feeds manifest + UI). */
90
+ risk?: 'low' | 'medium' | 'high';
91
+ }
92
+ /** Budget configuration for @Budget() decorator. */
93
+ interface BudgetOptions {
94
+ /** Maximum cost in USD for this scope. */
95
+ maxCostUsd: number;
96
+ /** Rolling window for budget tracking. */
97
+ window?: 'daily' | 'monthly';
98
+ }
99
+ /** Approval configuration for @RequiresApproval() decorator. */
100
+ interface ApprovalOptions {
101
+ /** Reason shown to the approver. */
102
+ reason: string;
103
+ }
104
+ /** Policy handler function type. */
105
+ type PolicyHandler = (user: {
106
+ roles: string[];
107
+ }) => boolean;
108
+ /**
109
+ * M53 — moved here from the `@HumanInTheLoop` decorator, which is being deleted: the type is
110
+ * consumed by `compileHitlGates` and the toolbox capability, not by the decorator alone.
111
+ */
112
+ type TimeoutAction = 'abort' | 'proceed' | 'retry';
113
+ interface HumanInTheLoopOptions {
114
+ /** Question shown to the human approver. */
115
+ question: string;
116
+ /** Timeout in milliseconds before onTimeout fires (default: 300_000 = 5 min). */
117
+ timeout?: number;
118
+ /** Action when timeout expires (default: 'abort'). */
119
+ onTimeout?: TimeoutAction;
120
+ /** Show the tool input to the approver (default: true). */
121
+ showInput?: boolean;
122
+ /**
123
+ * M20 — an optional JSON-schema descriptor of the custom payload the approver may attach (edited
124
+ * args, a review note). Carried into the `approval_required` event + `GET /approvals` so the UI
125
+ * knows what to collect. A plain JSON object, not a live Zod schema (keeps the wire serializable).
126
+ */
127
+ payloadSchema?: Record<string, unknown>;
128
+ }
129
+
130
+ type McpServersMap = Record<string, McpServerConfig>;
131
+ /** M53 — moved from the `@ProjectContext` decorator being deleted; read by the compiler. */
132
+ type IndexStrategy = 'tree-sitter' | 'regex' | 'none';
133
+ type RelevanceStrategy = 'git-history' | 'import-graph' | 'semantic' | 'manual';
134
+ interface ProjectContextOptions {
135
+ /** Files that mark the project root (searched upward from cwd). */
136
+ rootMarkers?: string[];
137
+ /** How to index the codebase for structural understanding. */
138
+ indexStrategy?: IndexStrategy;
139
+ /** Maximum files to include in context per request. */
140
+ maxFilesInContext?: number;
141
+ /** How to rank file relevance when selecting context. */
142
+ relevanceStrategy?: RelevanceStrategy;
143
+ /** Glob patterns to exclude from indexing and context. */
144
+ ignorePatterns?: string[];
145
+ /** File extensions to include in indexing (default: all text files). */
146
+ includeExtensions?: string[];
147
+ }
148
+ type CheckpointStrategy = 'after-tool-call' | 'after-iteration' | 'manual';
149
+ type CheckpointStorage = 'memory' | 'filesystem' | 'drizzle' | 'redis';
150
+ interface CheckpointOptions {
151
+ /** Where to persist checkpoints. */
152
+ storage?: CheckpointStorage;
153
+ /** When to auto-checkpoint (default: 'after-tool-call'). */
154
+ strategy?: CheckpointStrategy;
155
+ /** Maximum checkpoints to retain per run (rolling window). */
156
+ maxCheckpoints?: number;
157
+ /** Time-to-live in ms before checkpoints expire (default: 3_600_000 = 1h). */
158
+ ttl?: number;
159
+ }
160
+ type MemoryProvider = 'built-in' | 'honcho' | 'supermemory' | 'mem0';
161
+ type MemoryScope = 'per-user' | 'per-agent' | 'per-tenant' | 'global';
162
+ interface MemoryOptions {
163
+ /** Memory provider backend. */
164
+ provider?: MemoryProvider;
165
+ /** Enable semantic search via embeddings. */
166
+ embeddings?: boolean;
167
+ /** Enable full-text search (FTS5). */
168
+ fts?: boolean;
169
+ /** Memory isolation scope (default: 'per-user'). */
170
+ scope?: MemoryScope;
171
+ /** Maximum facts to retain per scope (0 = unlimited). */
172
+ maxFacts?: number;
173
+ }
174
+
175
+ /**
176
+ * M9 (theokit-ai-first) — guardrail contract + typed errors.
177
+ *
178
+ * ADR-0040 § D2: guardrails are a HOME/BOUNDARY concern (filter user input before the SDK,
179
+ * filter model output before the client). They REUSE the SDK runtime — this module makes zero
180
+ * LLM calls. A guard reports one of three actions; the pipeline (`pipeline.ts`) enforces them.
181
+ */
182
+ /** What a guard decided for a piece of text. */
183
+ type GuardrailAction = 'allow' | 'block' | 'redact';
184
+ /**
185
+ * The result of a single guard check.
186
+ * - `allow` — text passes untouched.
187
+ * - `block` — the pipeline throws {@link GuardrailViolationError}; the run stops fail-fast.
188
+ * - `redact` — the pipeline replaces the text with {@link GuardrailResult.text} and continues.
189
+ */
190
+ interface GuardrailResult {
191
+ action: GuardrailAction;
192
+ /** Human-readable reason — required in spirit for `block`, surfaced in the thrown error. */
193
+ reason?: string;
194
+ /** The transformed text — present (and used) only when `action === 'redact'`. */
195
+ text?: string;
196
+ }
197
+ /**
198
+ * A guardrail. A guard MAY inspect input (before the model), output (after the model), or both.
199
+ * A guard that omits a phase hook is skipped for that phase.
200
+ */
201
+ interface Guardrail {
202
+ readonly name: string;
203
+ checkInput?(text: string): GuardrailResult | Promise<GuardrailResult>;
204
+ checkOutput?(text: string): GuardrailResult | Promise<GuardrailResult>;
205
+ }
206
+ /** Which boundary phase a violation happened in. */
207
+ type GuardrailPhase = 'input' | 'output';
208
+ /** Thrown (fail-fast) when a guard returns `action: 'block'`. Typed per error-handling.md. */
209
+ /**
210
+ * M80 — extends {@link TheokitAgentError}, not plain `Error`.
211
+ *
212
+ * `isTransientError` is defined over `TheokitAgentError`, so a class outside that hierarchy is
213
+ * INVISIBLE to it and the only recourse left to a consumer is matching on message text — a regex
214
+ * over an eight-level `cause` chain, which is what one actually wrote. `code` is stable across a
215
+ * rename of the class; `isRetryable` is DECLARED rather than defaulted, because a default would be a
216
+ * retry policy nobody chose.
217
+ */
218
+ declare class GuardrailViolationError extends TheokitAgentError {
219
+ readonly guardName: string;
220
+ readonly phase: GuardrailPhase;
221
+ readonly reason: string;
222
+ readonly name = "GuardrailViolationError";
223
+ constructor(guardName: string, phase: GuardrailPhase, reason: string);
224
+ }
225
+ /** Thrown when {@link costGuard}'s cumulative token budget is exceeded. */
226
+ /**
227
+ * M80 — extends {@link TheokitAgentError}, not plain `Error`.
228
+ *
229
+ * `isTransientError` is defined over `TheokitAgentError`, so a class outside that hierarchy is
230
+ * INVISIBLE to it and the only recourse left to a consumer is matching on message text — a regex
231
+ * over an eight-level `cause` chain, which is what one actually wrote. `code` is stable across a
232
+ * rename of the class; `isRetryable` is DECLARED rather than defaulted, because a default would be a
233
+ * retry policy nobody chose.
234
+ */
235
+ declare class CostBudgetExceededError extends TheokitAgentError {
236
+ readonly usedTokens: number;
237
+ readonly maxTokens: number;
238
+ readonly name = "CostBudgetExceededError";
239
+ constructor(usedTokens: number, maxTokens: number);
240
+ }
241
+
242
+ /**
243
+ * M13 (theokit-ai-first) — per-request skills resolution (ADR-0040 § D2, home/boundary concern).
244
+ *
245
+ * The static `skills.enabled` filter already works (`compile-skills` maps `include` → the SDK's
246
+ * `enabled`). This adds a PER-REQUEST resolver so multi-tenant apps expose different skill sets to
247
+ * different users. A selection is either a static list or a function of the request context (the M7
248
+ * run-context). Discovery + injection stay in the SDK; this only CHOOSES the enabled set per call.
249
+ */
250
+
251
+ /** The request context handed to a skills resolver (the M7 run-context — opaque per-request data). */
252
+ type SkillsRequestContext = Record<string, unknown>;
253
+ /**
254
+ * How the skill set is chosen:
255
+ * - a static array of `string` (filesystem skill NAMES → `skills.enabled`) and/or `InlineSkill`
256
+ * objects from `createSkill` (code-defined skills → `skills.inline`, injected into the `<skills>`
257
+ * block). A mixed list is split at compile time.
258
+ * - a function — resolved per request from the {@link SkillsRequestContext} (sync or async). The
259
+ * resolver returns filesystem skill NAMES (inline skills are static — declared on the agent).
260
+ */
261
+ type SkillsSelection = readonly (string | InlineSkill)[] | ((ctx: SkillsRequestContext) => readonly string[] | Promise<readonly string[]>);
262
+ /**
263
+ * Resolve the enabled skill names for a request. Returns `undefined` when no selection is given (the
264
+ * SDK then enables every discovered skill). Fails fast if a resolver returns a non-array. The static
265
+ * array is compiled ahead of time (see `compileSkillsSelection`), so this is exercised for the
266
+ * resolver form; a static array is defensively narrowed to its string (name) members.
267
+ */
268
+ declare function resolveEnabledSkills(selection: SkillsSelection | undefined, ctx: SkillsRequestContext): Promise<string[] | undefined>;
269
+
270
+ /**
271
+ * Agent compiler — transforms decorator metadata into SDK calls.
272
+ *
273
+ * Per ADR D1: @Agent is a macro over Agent.create().
274
+ * Per ADR D3: @Tool compiles to defineTool().
275
+ *
276
+ * EC-3: throws if toolbox instance is missing from the instances map.
277
+ */
278
+
279
+ /**
280
+ * M53 — the input shape `compileTools`/`compileHitlGates` consume, declared WITH them now that the
281
+ * metadata walk that used to own it is gone. `ToolboxCapability` builds this from a class'
282
+ * `static tools` declaration.
283
+ */
284
+ /** A guard/interceptor class token — identity only (the DI container instantiates it). */
285
+ type ClassToken = abstract new (...args: never[]) => object;
286
+ interface ToolWalkResult {
287
+ propertyKey: string | symbol;
288
+ config: ToolOptions;
289
+ guards: ClassToken[];
290
+ approval?: ApprovalOptions;
291
+ capabilities?: string[];
292
+ budget?: BudgetOptions;
293
+ trace: boolean;
294
+ audit: boolean;
295
+ /** HITL config when the tool is gated (M4); absent ⇒ not gated. */
296
+ hitl?: HumanInTheLoopOptions;
297
+ }
298
+ interface ToolboxWalkResult {
299
+ /** The toolbox class — used as the identity key into `toolboxInstances`. */
300
+ class: ClassToken;
301
+ namespace: string;
302
+ tools: ToolWalkResult[];
303
+ guards: ClassToken[];
304
+ }
305
+ /** Minimal interface matching defineTool() result shape. */
306
+ interface CompiledTool {
307
+ name: string;
308
+ description: string;
309
+ inputSchema: unknown;
310
+ /**
311
+ * M7 — the optional 2nd `ctx` arg carries the SDK run context: `ctx.context` is the
312
+ * `defineAgent({ context })` / per-run value, `ctx.signal` the abort signal. Optional so the
313
+ * decorator `@Tool` handlers (which ignore it) stay assignable. The SDK calls the tool with
314
+ * both args; a handler that needs run-context (e.g. a filesystem tool reading `projectRoot`)
315
+ * reads `ctx?.context`.
316
+ */
317
+ handler: (input: unknown, ctx?: {
318
+ signal?: AbortSignal;
319
+ context?: unknown;
320
+ }) => string | Promise<string>;
321
+ }
322
+ /**
323
+ * Compile @Tool metadata into tool definitions.
324
+ *
325
+ * @param toolboxes - Walked toolbox metadata
326
+ * @param toolboxInstances - Map of Toolbox class → instantiated object (for `this` binding)
327
+ */
328
+ declare function compileTools(toolboxes: ToolboxWalkResult[], toolboxInstances: Map<ClassToken, object>): CompiledTool[];
329
+ /** Compiled sub-agent definition matching SDK AgentDefinition shape. */
330
+ interface CompiledSubAgent {
331
+ model?: string;
332
+ /**
333
+ * V4-L.1: typed as the union for consistency with `AgentOptions.systemPrompt`,
334
+ * so `compileSubAgents` carries whatever the sub-agent declared. Sub-agent
335
+ * resolver EXECUTION is out of scope this slice (ADR D3): `compiled.agents` is
336
+ * not spread into `Agent.create` by `createSdkAgentStream`; a resolver here is
337
+ * carried, not invoked. Top-level agent resolvers are the supported path.
338
+ */
339
+ systemPrompt?: string | SystemPromptResolver;
340
+ }
341
+ /** Compiled agent options ready for SDK Agent.create(). */
342
+ interface CompiledAgentOptions {
343
+ model?: string;
344
+ /** Extended-thinking effort; mapped to SDK ModelSelection.params. */
345
+ reasoningEffort?: ReasoningEffort;
346
+ /** Opt-in `<think>`-tag extraction (M2); wraps the stream when true. */
347
+ parseThinkTags?: boolean;
348
+ /** Opt-in tool-dialect stripping (theocode#32); strips leaked `<function=…></tool_call>` from text when true. */
349
+ stripToolDialect?: boolean;
350
+ /** Opt-in leaked-dialect recovery (theokit#58); enables the SDK route's `extractToolCallsFromContent` so leaked tool calls EXECUTE when true. */
351
+ recoverLeakedToolCalls?: boolean;
352
+ /** Static prompt OR a per-request {@link SystemPromptResolver} (V4-L.1, Axis-B). */
353
+ systemPrompt?: string | SystemPromptResolver;
354
+ /**
355
+ * theokit-file-based-config — opt-in `.theokit/` file-based config roots (`"project"`/`"user"`/…).
356
+ * Projected into `Agent.create({ local: { settingSources } })` by `assembleM8CreateOptions`
357
+ * (merged with `cwd`, decoupled from inline skills). Absent ⇒ inline (code) config only.
358
+ */
359
+ settingSources?: readonly SettingSource[];
360
+ /** Code `Plugin` objects forwarded to `Agent.create({ plugins })` (lifecycle-hook seam). */
361
+ plugins?: readonly unknown[];
362
+ tools: CompiledTool[];
363
+ agents: Record<string, CompiledSubAgent>;
364
+ memory?: MemoryOptions | MemorySettings;
365
+ skills?: SkillsSettings;
366
+ context?: ContextSettings;
367
+ /**
368
+ * M7 — run-context injected into every tool handler's `ctx.context` by the theokit adapter
369
+ * (`buildSdkTools` wrapper). Populated by `defineAgent({ context })` (functional surface).
370
+ * NAME NOTE: distinct from the context-window `context` (`ContextSettings`) above — this is
371
+ * per-run user data for tools, not token-budget config.
372
+ */
373
+ runContext?: Record<string, unknown>;
374
+ /** Raw @ProjectContext config; the adapter builds the (async) systemPrompt resolver from it. */
375
+ projectContext?: ProjectContextOptions;
376
+ mcpServers?: McpServersMap;
377
+ maxIterations?: number;
378
+ timeoutMs?: number;
379
+ stream: boolean;
380
+ /**
381
+ * HITL gate map (M4): runtime tool name → `@HumanInTheLoop` config. Absent/empty ⇒ no gated
382
+ * tools. The harness (`mountAgent`) turns this into the `pre_tool_call` pause wiring.
383
+ */
384
+ hitl?: Map<string, HumanInTheLoopOptions>;
385
+ /**
386
+ * `@Checkpoint` config (M4): when present the harness emits `checkpoint_saved` and selects the
387
+ * durable SDK conversation storage (`storage: 'filesystem'`) so a same-`sessionId` request resumes.
388
+ */
389
+ checkpoint?: CheckpointOptions;
390
+ /**
391
+ * M9 — guardrails: input/output guards applied at the framework boundary (ADR-0040 § D2).
392
+ * Input guards run on the user message BEFORE the SDK runtime sees it (fail-fast on `block`).
393
+ * They REUSE the runtime; they never reimplement it. Absent/empty ⇒ no guards.
394
+ */
395
+ guardrails?: readonly Guardrail[];
396
+ /**
397
+ * M13 — per-request skills resolver (from `defineAgent({ skills: (ctx) => [...] })`). The request
398
+ * path resolves it against the run-context (`resolveEnabledSkills`) and sets `skills.enabled`
399
+ * before the SDK runs. Not consumed by the SDK directly (it reads `skills`). Absent ⇒ no resolver.
400
+ */
401
+ skillsResolver?: SkillsSelection;
402
+ }
403
+
404
+ /**
405
+ * M68 — the trust gate for `settingSources`.
406
+ *
407
+ * ## The defect this module closes
408
+ *
409
+ * `settingSources` enables on-disk config discovery. `'user'` reads `~/.theokit/` — the operator's
410
+ * own machine, which no third party controls. `'project'` reads `<cwd>/.theokit/`, **including
411
+ * `hooks.json`, which executes shell**.
412
+ *
413
+ * The previous API took `readonly SettingSource[]`, and its JSDoc justified the risk this way:
414
+ * *"it is opt-in because `.theokit/` is the app's own repo (informed consent)"*. That premise holds
415
+ * for a web app whose `cwd` is its own deploy. It does **not** hold for the class of product this
416
+ * framework addresses — an agent whose `cwd` is a repository the user just cloned. There `.theokit/`
417
+ * is attacker-controlled content, and enabling `'project'` is remote code execution on the first
418
+ * `build()`.
419
+ *
420
+ * Documenting it did not prevent it. The measured consumer (TheoCode) did not trust the API: it
421
+ * gated from the outside, with a `posture.allows` of its own (`chat.ts:386`, comment B-008). It
422
+ * already **had** the right decision and could not pass it through, because the API only accepted
423
+ * strings. The gate existed on its side and evaporated at the boundary.
424
+ *
425
+ * ## The evidence is the SDK's, not one invented here
426
+ *
427
+ * `TrustPosture` is `@theokit/sdk`'s own trust primitive, and `recordWiring`'s doc says *"a posture
428
+ * is the only thing in this package that retains a capability"*. A bespoke type would make two trust
429
+ * grammars coexist and drift apart (ADR 0063).
430
+ */
431
+ /**
432
+ * The framework's capability vocabulary — deliberately a single name (ADR 0065).
433
+ *
434
+ * `allows` is all-or-nothing in the SDK: every declared `K` gets the same boolean. A finer
435
+ * vocabulary (`hooks`, `skills`, `subagents`, `mcp`) would promise the consumer it can gate one
436
+ * without gating the other, and the primitive does not deliver that. An API that suggests a
437
+ * distinction the runtime does not make teaches the wrong thing, and the error only surfaces when
438
+ * somebody depends on the distinction.
439
+ */
440
+ type SettingSourceCapability = 'projectSettings';
441
+ /** Authorization to read config from the working directory. Requires the posture, never a claim. */
442
+ interface ProjectSettingsGrant {
443
+ /**
444
+ * Typically the output of `resolveTrustPosture` — which is what gives it `source` (`'env' |
445
+ * 'store' | 'default'`) and therefore a refusal that says WHERE the decision came from instead of
446
+ * merely denying.
447
+ */
448
+ readonly trustedBy: TrustPosture<SettingSourceCapability>;
449
+ }
450
+ /**
451
+ * Which on-disk config roots the agent may read.
452
+ *
453
+ * The asymmetry is the design: `user` is a boolean because `~/.theokit/` belongs to the operator;
454
+ * `project` requires evidence because `<cwd>/.theokit/` may not. Omitting a root is not enabling it
455
+ * — never "enabling without a gate". The asymmetry is inherited from the SDK itself, whose
456
+ * `TrustPostureInput.envOverride` documents that `false` and `undefined` both mean "the operator did
457
+ * not turn it on", not "turned it off".
458
+ */
459
+ interface SettingSourcesSelection {
460
+ /** `~/.theokit/` — the operator's machine. No gate: no third party controls it. */
461
+ readonly user?: boolean;
462
+ /** `<cwd>/.theokit/` — controlled by whoever wrote the open repository. Requires evidence. */
463
+ readonly project?: ProjectSettingsGrant;
464
+ }
465
+ /**
466
+ * Refusal to read the working directory for lack of trust.
467
+ *
468
+ * Descends from `TheokitAgentError` because typed errors are an unbreakable rule here — and because
469
+ * `isTransientError` only sees this hierarchy. A class extending plain `Error` would be invisible to
470
+ * the predicate that separates recoverable from unrecoverable (the defect M67 fixed in five
471
+ * classes).
472
+ */
473
+ declare class UntrustedSettingSourceError extends TheokitAgentError {
474
+ /** Where the trust decision came from: `'env' | 'store' | 'default'`. */
475
+ readonly trustSource: string;
476
+ /** The refused capability. */
477
+ readonly capability: SettingSourceCapability;
478
+ readonly name = "UntrustedSettingSourceError";
479
+ constructor(message: string,
480
+ /** Where the trust decision came from: `'env' | 'store' | 'default'`. */
481
+ trustSource: string,
482
+ /** The refused capability. */
483
+ capability: SettingSourceCapability);
484
+ }
485
+ /**
486
+ * Translate the declared selection into the `SettingSource`s the SDK accepts, refusing what the
487
+ * posture does not authorize.
488
+ *
489
+ * Refuses rather than ignores (ADR 0064). Ignoring would leave the product running in the belief
490
+ * that the repository's hooks are active — a silent failure mode, on the wrong side. The SDK already
491
+ * picked that side for the same problem: `recordWiring` throws `UngatedCapabilityError` when
492
+ * somebody registers a capability the posture does not gate.
493
+ *
494
+ * @throws {UntrustedSettingSourceError} when `project` is requested and the posture does not grant it.
495
+ */
496
+ declare function resolveSettingSources(selection: SettingSourcesSelection | undefined): readonly SettingSource[];
497
+
498
+ /**
499
+ * M2 (theokit-ai-first) — `defineAgent`, the zero-config imperative agent surface.
500
+ *
501
+ * ADR-B1: `defineAgent({...})` (default-exported from a top-level `agents/<name>.ts`) is
502
+ * the canonical zero-config surface; the `@Agent` class decorator stays the advanced/DI
503
+ * surface. Both compile to {@link CompiledAgentOptions} and run through the same SDK
504
+ * runtime (`createSdkAgentStream`) — one runtime, two syntaxes.
505
+ *
506
+ * This module is PURE metadata (sdk-runtime.md / G2): `defineAgent` describes an agent, it
507
+ * NEVER calls an LLM. It imports only `zod` (types) + the compiler shape — no `theokit`
508
+ * core, preserving the agents → (nothing) dependency direction (G1).
509
+ */
510
+
511
+ /**
512
+ * Brand tag for a `defineAgent` value. `Symbol.for` (global registry, not `Symbol()`) so
513
+ * the brand survives duplicate module instances (dual-package / bundling) — the scanner's
514
+ * brand-check then works regardless of which copy created the definition.
515
+ */
516
+ declare const AGENT_BRAND: unique symbol;
517
+ /** Config accepted by {@link defineAgent}. */
518
+ interface DefineAgentConfig<TInput extends z.ZodType = z.ZodType> {
519
+ /** Zod schema for the request body — lifted into the typed client (M2, {@link InferAgentInput}). */
520
+ input?: TInput;
521
+ /** Model id (e.g. `claude-sonnet-4-6`). Falls back to the SDK default when omitted. */
522
+ model?: string;
523
+ /** Static system prompt. */
524
+ system?: string;
525
+ /** Extended-thinking effort. */
526
+ reasoningEffort?: ReasoningEffort;
527
+ /**
528
+ * Pre-built tools. Accepts the `@theokit/sdk` `CustomTool` that `defineAgentTool`
529
+ * (theokit/server) and every `@theokit/sdk-tools` factory return (issue #81) — they are
530
+ * normalized to the internal {@link CompiledTool} shape at compile time.
531
+ */
532
+ tools?: readonly CustomTool[];
533
+ /**
534
+ * M7 — run-context: an opaque, per-agent object forwarded to every tool handler's
535
+ * `ctx.context` at run time (injected by the theokit adapter's tool wrapper). Set shared config
536
+ * (e.g. `{ projectRoot }`) ONCE at the agent level instead of baking it into each tool
537
+ * factory. Mirrors ai-sdk `experimental_context`, mastra `RuntimeContext`, and
538
+ * openai-agents-js `RunContext`. Distinct from `@Agent`'s context-window `context`.
539
+ */
540
+ context?: Record<string, unknown>;
541
+ /**
542
+ * M9 — guardrails: input/output guards applied at the framework boundary (ADR-0040 § D2).
543
+ * Input guards run on the user message before the SDK runtime; a `block` fails the run fast.
544
+ * Built-ins live in `@theokit/agents` (`promptInjectionDetector`, `piiDetector`, `costGuard`,
545
+ * `unicodeNormalizer`, `outputModeration`).
546
+ */
547
+ guardrails?: readonly Guardrail[];
548
+ /**
549
+ * M14 — HITL approvals keyed by tool name. Each gated tool pauses the run and emits an
550
+ * `approval_required` event until approved (reuses the same `compiled.hitl` wiring the `@Agent`
551
+ * + `@HumanInTheLoop` path produces). A key that does not match a declared tool fails fast at
552
+ * compile time.
553
+ */
554
+ approvals?: Record<string, HumanInTheLoopOptions>;
555
+ /**
556
+ * M13 — skills selection: a static list (compiled straight to the SDK `skills.enabled`) OR a
557
+ * per-request resolver `(ctx) => string[]` (carried on `compiled.skillsResolver`, resolved by the
558
+ * request path against the run-context). Absent ⇒ the SDK enables every discovered skill.
559
+ */
560
+ skills?: SkillsSelection;
561
+ /**
562
+ * theokit-file-based-config — opt into `.theokit/` file-based config (skills, subagents, hooks,
563
+ * MCP, context, cron). The SDK discovers config from these roots under the app's `cwd`:
564
+ * `project` = `<cwd>/.theokit/`, `user` = `~/.theokit/`. Absent ⇒ inline (code) config only.
565
+ *
566
+ * SECURITY (M68): `project` reads `.theokit/hooks.json`, which **executes shell**, so it requires
567
+ * a `TrustPosture` rather than a string. This field used to take `readonly SettingSource[]`, and
568
+ * its own JSDoc justified the risk as *"opt-in because `.theokit/` is the app's own repo (informed
569
+ * consent)"*. That premise holds for a web app whose `cwd` is its own deploy; it does not hold for
570
+ * an agent whose `cwd` is a repository the user just cloned, where `.theokit/` is
571
+ * attacker-controlled content.
572
+ *
573
+ * `user` stays a plain boolean — `~/.theokit/` is the operator's own machine. Omitting a root is
574
+ * not enabling it. The SDK owns discovery + execution (G2 / ADR-0040); theokit resolves the
575
+ * selection through `resolveSettingSources` and wires the result into
576
+ * `Agent.create({ local.settingSources })`.
577
+ */
578
+ settingSources?: SettingSourcesSelection;
579
+ /**
580
+ * M49 — durable memory (the SDK's `.theokit/memory/` subsystem: `Remember:` capture, MEMORY.md
581
+ * store, auto-injected `<memory>` block, `memory_search`/`memory_get` tools). The shape is the
582
+ * SDK's own `MemorySettings` — the canonical runtime contract. Projected into
583
+ * `Agent.create({ memory })` by `assembleM8CreateOptions`.
584
+ */
585
+ memory?: MemorySettings;
586
+ /**
587
+ * Code `Plugin` objects forwarded to `Agent.create({ plugins })` — EXTENSION units (tools,
588
+ * commands, model providers, memory adapters). For lifecycle interception use {@link hooks}.
589
+ */
590
+ plugins?: readonly unknown[];
591
+ /**
592
+ * Lifecycle hooks keyed by `HookName` (`pre_tool_call` may veto via `{ block, message }`). Set by
593
+ * the builder's `hooks()`; converted into a code plugin at `build()` and never reaching the SDK
594
+ * under this name — the plugin is the TRANSPORT, this is the contract callers write against.
595
+ */
596
+ hooks?: HookHandlers | Readonly<Record<string, unknown>>;
597
+ /**
598
+ * MCP servers available to the agent — the builder-chain equivalent of the `@MCP` class
599
+ * decorator. Each key is a server name; the value is the server configuration. Forwarded
600
+ * unchanged to `Agent.create({ mcpServers })` (the SDK owns MCP execution). Absent ⇒ no MCP.
601
+ */
602
+ mcpServers?: McpServersMap;
603
+ }
604
+ /**
605
+ * A branded agent definition — the value {@link defineAgent} returns.
606
+ *
607
+ * `TTools` (M8) is a phantom type parameter carrying the tool-name union: the `AgentBuilder.create()` builder
608
+ * threads its accumulated literal tool names here (`.build()` returns `AgentDefinition<TInput,
609
+ * 'a' | 'b'>`), so the generated client (`.theokit/agents.d.ts`) can expose them via
610
+ * {@link InferAgentToolNames}. `defineAgent` leaves it `string` (its tools array carries no literal
611
+ * names). Never present at runtime.
612
+ */
613
+ type AgentDefinition<TInput extends z.ZodType = z.ZodType, TTools extends string = string> = DefineAgentConfig<TInput> & {
614
+ readonly [AGENT_BRAND]: true;
615
+ readonly __toolNames?: TTools;
616
+ };
617
+ /** Infer the request type of an agent definition from its `input` Zod schema. */
618
+ type InferAgentInput<T> = T extends AgentDefinition<infer S> ? (S extends z.ZodType ? z.infer<S> : never) : never;
619
+ /**
620
+ * Infer the tool-name union of an agent definition (M8). Yields the literal union for agents built
621
+ * with the `AgentBuilder.create()` builder (`'read_file' | 'count_lines'`), or `string` for `defineAgent` agents
622
+ * whose tools array carries no literal names.
623
+ */
624
+ type InferAgentToolNames<T> = T extends AgentDefinition<z.ZodType, infer N> ? N : never;
625
+ /** Brand-check: is `value` a {@link defineAgent} result? */
626
+ declare function isAgentDefinition(value: unknown): value is AgentDefinition;
627
+ /**
628
+ * Lower a definition to the SDK-ready {@link CompiledAgentOptions} — the same shape
629
+ * `compileAgent` (decorator path) produces, so both surfaces converge on one runtime.
630
+ */
631
+ declare function compileAgentDefinition(def: AgentDefinition): CompiledAgentOptions;
632
+
633
+ export { type AgentDefinition as A, type BudgetOptions as B, type CompiledAgentOptions as C, type DefineAgentConfig as D, type Guardrail as G, type HumanInTheLoopOptions as H, type InferAgentInput as I, type MainLoopMeta as M, type PolicyHandler as P, type ReasoningEffort as R, type SettingSourcesSelection as S, type ToolOptions as T, UntrustedSettingSourceError as U, type CompiledTool as a, type ApprovalOptions as b, AGENT_BRAND as c, type AgentOptions as d, CostBudgetExceededError as e, type GuardrailAction as f, type GuardrailPhase as g, type GuardrailResult as h, GuardrailViolationError as i, type InferAgentToolNames as j, type MainLoopOptions as k, type McpServersMap as l, type ProjectSettingsGrant as m, type SettingSourceCapability as n, type SkillsRequestContext as o, type SkillsSelection as p, type TimeoutAction as q, type ToolWalkResult as r, type ToolboxOptions as s, type ToolboxWalkResult as t, compileAgentDefinition as u, compileTools as v, isAgentDefinition as w, resolveEnabledSkills as x, resolveSettingSources as y, type ProjectContextOptions as z };