@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
package/dist/hooks.js ADDED
@@ -0,0 +1,286 @@
1
+ import {
2
+ __name
3
+ } from "./chunk-Z4QWC7IK.js";
4
+
5
+ // src/hooks/hook-spec.ts
6
+ import { randomBytes } from "crypto";
7
+ import { TheokitAgentError } from "@theokit/sdk/errors";
8
+ import { z } from "zod";
9
+
10
+ // src/hooks/hook-fingerprint.ts
11
+ import { createHash } from "crypto";
12
+ var FIELD_SEPARATOR = "";
13
+ function hookFingerprint(identity) {
14
+ const canonical = [
15
+ identity.command,
16
+ identity.event,
17
+ identity.matcher ?? "",
18
+ String(identity.timeoutMs)
19
+ ].join(FIELD_SEPARATOR);
20
+ return createHash("sha256").update(canonical, "utf8").digest("hex");
21
+ }
22
+ __name(hookFingerprint, "hookFingerprint");
23
+
24
+ // src/hooks/hook-runner.ts
25
+ import { spawn } from "child_process";
26
+ var MAX_OUTPUT_BYTES = 1048576;
27
+ var DRAIN_BUDGET_MS = 2e3;
28
+ var CHAIN_BUDGET_MULTIPLIER = 4;
29
+ async function runHookCommand(input) {
30
+ return new Promise((resolve) => {
31
+ const child = spawn(input.command, {
32
+ cwd: input.cwd,
33
+ shell: true,
34
+ // Trap 3: its own process group, so the timeout can kill the whole tree.
35
+ detached: true,
36
+ env: input.env,
37
+ stdio: [
38
+ "pipe",
39
+ "pipe",
40
+ "pipe"
41
+ ]
42
+ });
43
+ let stdout = "";
44
+ let stderr = "";
45
+ let truncated = false;
46
+ let timedOut = false;
47
+ let settled = false;
48
+ const capture = /* @__PURE__ */ __name((current, chunk) => {
49
+ if (current.length >= MAX_OUTPUT_BYTES) {
50
+ truncated = true;
51
+ return current;
52
+ }
53
+ const next = current + chunk.toString("utf8");
54
+ if (next.length <= MAX_OUTPUT_BYTES) return next;
55
+ truncated = true;
56
+ return next.slice(0, MAX_OUTPUT_BYTES);
57
+ }, "capture");
58
+ child.stdout.on("data", (chunk) => {
59
+ stdout = capture(stdout, chunk);
60
+ });
61
+ child.stderr.on("data", (chunk) => {
62
+ stderr = capture(stderr, chunk);
63
+ });
64
+ const settle = /* @__PURE__ */ __name((exitCode) => {
65
+ if (settled) return;
66
+ settled = true;
67
+ clearTimeout(timer);
68
+ clearTimeout(drainTimer);
69
+ resolve({
70
+ exitCode,
71
+ stdout,
72
+ stderr,
73
+ truncated,
74
+ timedOut
75
+ });
76
+ }, "settle");
77
+ const timer = setTimeout(() => {
78
+ timedOut = true;
79
+ killGroup(child.pid);
80
+ }, input.timeoutMs);
81
+ let drainTimer = setTimeout(() => void 0, 0);
82
+ child.on("exit", (code) => {
83
+ drainTimer = setTimeout(() => {
84
+ settle(code);
85
+ }, DRAIN_BUDGET_MS);
86
+ });
87
+ child.on("close", (code) => {
88
+ settle(code);
89
+ });
90
+ child.on("error", () => {
91
+ settle(null);
92
+ });
93
+ child.stdin.on("error", () => void 0);
94
+ if (input.stdin !== void 0) child.stdin.end(input.stdin);
95
+ else child.stdin.end();
96
+ });
97
+ }
98
+ __name(runHookCommand, "runHookCommand");
99
+ function killGroup(pid) {
100
+ if (pid === void 0) return;
101
+ try {
102
+ process.kill(-pid, "SIGKILL");
103
+ } catch {
104
+ }
105
+ }
106
+ __name(killGroup, "killGroup");
107
+
108
+ // src/hooks/hook-spec.ts
109
+ var HOOK_EVENTS = [
110
+ "pre_tool_call",
111
+ "post_tool_call",
112
+ "transform_tool_result",
113
+ "transform_llm_output",
114
+ "on_session_start",
115
+ "on_session_end",
116
+ "pre_user_send",
117
+ "post_assistant_reply"
118
+ ];
119
+ var DEFAULT_HOOK_TIMEOUT_MS = 3e4;
120
+ var DEFAULT_CONTINUATION_BUDGET = 3;
121
+ var hookSpecSchema = z.object({
122
+ event: z.enum(HOOK_EVENTS),
123
+ command: z.string().min(1).refine((value) => !/[\u0000-\u001f\u007f]/.test(value), {
124
+ message: "command contains control characters that would be hidden in the approval dialog"
125
+ }),
126
+ /** Selector for which tools/messages this fires on. Absent means all. */
127
+ matcher: z.string().optional(),
128
+ timeout_ms: z.number().int().positive().default(DEFAULT_HOOK_TIMEOUT_MS)
129
+ }).strict();
130
+ var HookSpecError = class extends TheokitAgentError {
131
+ static {
132
+ __name(this, "HookSpecError");
133
+ }
134
+ name = "HookSpecError";
135
+ constructor(message) {
136
+ super(message, {
137
+ code: "HOOK_SPEC_INVALID",
138
+ // A typo in a config file is not a transient condition.
139
+ isRetryable: false
140
+ });
141
+ }
142
+ };
143
+ function parseHookSpecs(input) {
144
+ const parsed = z.array(hookSpecSchema).safeParse(input);
145
+ if (!parsed.success) {
146
+ throw new HookSpecError(`invalid hook configuration: ${parsed.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ")}`);
147
+ }
148
+ return parsed.data;
149
+ }
150
+ __name(parseHookSpecs, "parseHookSpecs");
151
+ var IGNORE_WARNING = /* @__PURE__ */ __name(() => void 0, "IGNORE_WARNING");
152
+ function buildHookHandlers(specs, options) {
153
+ const warn = options.onWarn ?? IGNORE_WARNING;
154
+ if (!options.trusted) {
155
+ if (specs.length > 0) {
156
+ warn(`${String(specs.length)} hook(s) declared but the directory is not trusted \u2014 none will run.`);
157
+ }
158
+ return {};
159
+ }
160
+ const runnable = specs.filter((spec) => {
161
+ const approved = options.approved.has(hookFingerprint(identityOf(spec)));
162
+ if (!approved) {
163
+ warn(`hook not approved and will not run: "${spec.command}" on ${spec.event}. Approve it by fingerprint \u2014 editing the command invalidates any previous approval, by design.`);
164
+ }
165
+ return approved;
166
+ });
167
+ if (runnable.length === 0) return {};
168
+ const handlers = {};
169
+ const chainBudgetMs = Math.max(...runnable.map((spec) => spec.timeout_ms)) * CHAIN_BUDGET_MULTIPLIER;
170
+ const preHooks = runnable.filter((spec) => spec.event === "pre_tool_call");
171
+ if (preHooks.length > 0) {
172
+ handlers.pre_tool_call = async (ctx) => {
173
+ const started = Date.now();
174
+ for (const spec of preHooks) {
175
+ if (Date.now() - started > chainBudgetMs) {
176
+ return {
177
+ block: true,
178
+ message: "hook chain exceeded its time budget"
179
+ };
180
+ }
181
+ if (!matches(spec, ctx.name)) continue;
182
+ const result = await runHookCommand({
183
+ command: spec.command,
184
+ cwd: options.cwd,
185
+ timeoutMs: spec.timeout_ms,
186
+ stdin: JSON.stringify({
187
+ tool: ctx.name,
188
+ args: ctx.args
189
+ }),
190
+ ...options.env !== void 0 && {
191
+ env: options.env
192
+ }
193
+ });
194
+ if (result.exitCode !== 0) {
195
+ return {
196
+ block: true,
197
+ message: fenceHookOutput(result.stdout || result.stderr || `hook exited ${String(result.exitCode)}`)
198
+ };
199
+ }
200
+ }
201
+ return void 0;
202
+ };
203
+ }
204
+ const postHooks = runnable.filter((spec) => spec.event === "post_tool_call");
205
+ if (postHooks.length > 0) {
206
+ handlers.post_tool_call = async (ctx) => {
207
+ const started = Date.now();
208
+ for (const spec of postHooks) {
209
+ if (Date.now() - started > chainBudgetMs) {
210
+ warn("hook chain exceeded its time budget; remaining post hooks were skipped");
211
+ return;
212
+ }
213
+ if (!matches(spec, ctx.name)) continue;
214
+ try {
215
+ const result = await runHookCommand({
216
+ command: spec.command,
217
+ cwd: options.cwd,
218
+ timeoutMs: spec.timeout_ms,
219
+ stdin: JSON.stringify({
220
+ tool: ctx.name,
221
+ args: ctx.args,
222
+ result: ctx.result
223
+ }),
224
+ ...options.env !== void 0 && {
225
+ env: options.env
226
+ }
227
+ });
228
+ if (result.exitCode !== 0) {
229
+ warn(`post hook "${spec.command}" exited ${String(result.exitCode)}`);
230
+ }
231
+ if (result.truncated) warn(`post hook "${spec.command}" output was truncated`);
232
+ } catch (error) {
233
+ warn(`post hook "${spec.command}" failed: ${error.message}`);
234
+ }
235
+ }
236
+ };
237
+ }
238
+ return handlers;
239
+ }
240
+ __name(buildHookHandlers, "buildHookHandlers");
241
+ function identityOf(spec) {
242
+ return {
243
+ command: spec.command,
244
+ event: spec.event,
245
+ ...spec.matcher !== void 0 && {
246
+ matcher: spec.matcher
247
+ },
248
+ timeoutMs: spec.timeout_ms
249
+ };
250
+ }
251
+ __name(identityOf, "identityOf");
252
+ function matches(spec, toolName) {
253
+ if (spec.matcher === void 0) return true;
254
+ try {
255
+ return new RegExp(spec.matcher).test(toolName);
256
+ } catch {
257
+ return false;
258
+ }
259
+ }
260
+ __name(matches, "matches");
261
+ function fenceHookOutput(output) {
262
+ const nonce = randomBytes(8).toString("hex");
263
+ const open = `<hook-output nonce="${nonce}">`;
264
+ const close = `</hook-output nonce="${nonce}">`;
265
+ const escaped = output.replaceAll(close, close.replace("<", "&lt;"));
266
+ return `${open}
267
+ ${escaped}
268
+ ${close}`;
269
+ }
270
+ __name(fenceHookOutput, "fenceHookOutput");
271
+ export {
272
+ CHAIN_BUDGET_MULTIPLIER,
273
+ DEFAULT_CONTINUATION_BUDGET,
274
+ DEFAULT_HOOK_TIMEOUT_MS,
275
+ DRAIN_BUDGET_MS,
276
+ HOOK_EVENTS,
277
+ HookSpecError,
278
+ MAX_OUTPUT_BYTES,
279
+ buildHookHandlers,
280
+ fenceHookOutput,
281
+ hookFingerprint,
282
+ hookSpecSchema,
283
+ parseHookSpecs,
284
+ runHookCommand
285
+ };
286
+ //# sourceMappingURL=hooks.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/hooks/hook-spec.ts","../src/hooks/hook-fingerprint.ts","../src/hooks/hook-runner.ts"],"mappings":";;;;;AAAA,SAASA,mBAAmB;AAE5B,SAASC,yBAAyB;AAClC,SAASC,SAAS;;;ACHlB,SA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AAAA;EAAYD,KAAAA;AACjC;AARgBb;","names":["randomBytes","TheokitAgentError","z","createHash","FIELD_SEPARATOR","hookFingerprint","identity","canonical","command","event","matcher","String","timeoutMs","join","createHash","update","digest","spawn","MAX_OUTPUT_BYTES","DRAIN_BUDGET_MS","CHAIN_BUDGET_MULTIPLIER","runHookCommand","input","Promise","resolve","child","spawn","command","cwd","shell","detached","env","stdio","stdout","stderr","truncated","timedOut","settled","capture","current","chunk","length","next","toString","slice","on","settle","exitCode","clearTimeout","timer","drainTimer","setTimeout","killGroup","pid","timeoutMs","undefined","code","stdin","end","process","kill","HOOK_EVENTS","DEFAULT_HOOK_TIMEOUT_MS","DEFAULT_CONTINUATION_BUDGET","hookSpecSchema","z","object","event","enum","command","string","min","refine","value","test","message","matcher","optional","timeout_ms","number","int","positive","default","strict","HookSpecError","TheokitAgentError","name","code","isRetryable","parseHookSpecs","input","parsed","array","safeParse","success","error","issues","map","issue","path","join","data","IGNORE_WARNING","undefined","buildHookHandlers","specs","options","warn","onWarn","trusted","length","String","runnable","filter","spec","approved","has","hookFingerprint","identityOf","handlers","chainBudgetMs","Math","max","CHAIN_BUDGET_MULTIPLIER","preHooks","pre_tool_call","ctx","started","Date","now","block","matches","result","runHookCommand","cwd","timeoutMs","stdin","JSON","stringify","tool","args","env","exitCode","fenceHookOutput","stdout","stderr","postHooks","post_tool_call","truncated","toolName","RegExp","output","nonce","randomBytes","toString","open","close","escaped","replaceAll","replace"]}
package/dist/index.d.ts CHANGED
@@ -1,7 +1,9 @@
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
- export { CustomTool, DiagnosticsSink, GenerateObjectError, GoalEvent, GoalLoopAgent, GoalOptions, GoalResult, JudgeCredentialError, JudgeResult, LayerOrderError, McpAuthConfig, McpHttpServerConfig, McpOAuthConfig, McpServerConfig, McpStdioServerConfig, Provider, 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, L as LoopStrategy, R as ReflectionStrategy, C as CompiledAgentOptions, M as MainLoopMeta, a as CompiledTool, b as ReasoningEffort, c as RoundStreamFactory, S as StreamEvent, D as DelegationResult, d as ContextWindowOptions, e as SkillsOptions, T as ToolOptions, A as ApprovalOptions, H as HumanInTheLoopOptions, f as AgentManifestEntry, g as HitlDecision, s as streamAgentUIMessages, h as ApprovalPosture } from './bridge-entry-CvmBrmc9.js';
4
- export { i as AGENT_BRAND, j as AfterToolCallContext, k as AgentBuilder, l as AgentDefinition, m as AgentDefinitionError, n as AgentExecutionContext, o as AgentManifest, p as AgentManifestSource, q as AgentManifestTool, r as AgentOptions, t as AgentRoute, u as AgentRouteContext, v as AgentRunInfo, w as AgentStreamEvent, x as AgentTurnMetadata, y as AgentsPluginOptions, z as ApiErrorContext, B as ApiErrorDecision, E as ApiErrorPolicy, F as ApprovalRequiredEvent, I as ArtifactChunkEvent, J as ArtifactStartEvent, K as BackgroundDelegation, N as BeforeToolCallContext, O as BudgetExceededError, P as BudgetOptions, Q as CheckpointSavedEvent, U as CompiledContextWindow, V as ContextualTool, W as CostBudgetExceededError, X as DEFAULT_MAX_ITERATIONS, Y as DefineAgentConfig, Z as DefinitionOrThunk, _ as DelegateFn, $ as DelegateOptions, a0 as DelegationBudgetExceededError, a1 as DelegationError, a2 as DoneEvent, a3 as ErrorEvent, a4 as FileEditEvent, a5 as GuardrailAction, a6 as GuardrailPhase, a7 as GuardrailResult, a8 as GuardrailViolationError, a9 as HookHandlers, aa as InferAgentInput, ab as InferAgentToolNames, ac as IterationEvent, ad as LLMCallContext, ae as LoopFinishReason, af as LoopOutcome, ag as LoopStrategyConfig, ah as MainLoopOptions, ai as McpApprovalSpec, aj as McpFileError, ak as McpRegistryConfig, al as McpRequestContext, am as McpSelection, an as McpServersMap, ao as PartialToolCallEvent, ap as PolicyHandler, aq as ProcessInputContext, ar as ProjectSettingsGrant, as as ReflectionContext, at as ReflectionResult, au as ReflectionStrategyConfig, av as RunStartedEvent, aw as ScoreVerdict, ax as ScoredDelegation, ay as Scorer, az as SdkAgentHandle, aA as SdkMessage, aB as SdkSendOptions, aC as SdkTurnHandle, aD as Segment, aE as SettingSourceCapability, aF as SettingSourcesSelection, aG as SkillsRequestContext, aH as SkillsSelection, aI as StateUpdateEvent, aJ as TextDeltaEvent, aK as ThinkingEvent, aL as TimeoutAction, aM as ToolCallEvent, aN as ToolCallVeto, aO as ToolHooks, aP as ToolHooksPlugin, aQ as ToolResultEvent, aR as ToolWalkResult, aS as ToolboxOptions, aT as ToolboxWalkResult, aU as UntrustedSettingSourceError, aV as agentsPlugin, aW as buildModelSelection, aX as compileAgentDefinition, aY as compileAgentModule, aZ as compileContextWindow, a_ as compileProjectContext, a$ as compileSkills, b0 as compileTools, b1 as createAgentExecutionContext, b2 as createApiErrorHandler, b3 as createSdkAgentStream, b4 as createThinkTagExtractor, b5 as createToolHooksPlugin, b6 as delegate, b7 as delegateBackground, b8 as delegateWithScoring, b9 as extractThinkTagStream, ba as generateAgentManifest, bb as generateAgentRoutes, bc as isAgentContext, bd as isAgentDefinition, be as isApprovalRequired, bf as isDone, bg as isError, bh as isPartialToolCall, bi as isTextDelta, bj as isToolCall, bk as isToolResult, bl as ladderReflectionStrategy, bm as loadMcpJson, bn as loopStrategyConfigSchema, bo as mcpRegistry, bp as mcpToolApprovals, bq as noopReflectionStrategy, br as presentUIMessageStream, bs as projectContextMetadataOnlyKnobs, bt as reasoningEffortOf, bu as reflectionStrategyConfigSchema, bv as resolveEnabledSkills, bw as resolveLoopStrategy, bx as resolveMcpServers, by as resolveSettingSources, bz as runWithApiErrorHandling, bA as streamAgentResponse, bB as toAgentFactory, bC as translateSdkEvent } from './bridge-entry-CvmBrmc9.js';
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, M as MainLoopMeta, a as CompiledTool, R as ReasoningEffort, S as SettingSourcesSelection, T as ToolOptions, b as ApprovalOptions, H as HumanInTheLoopOptions } from './define-agent-3Kuf6iKM.js';
4
+ export { c as AGENT_BRAND, A as AgentDefinition, d as AgentOptions, B as BudgetOptions, e as CostBudgetExceededError, D as DefineAgentConfig, f as GuardrailAction, g as GuardrailPhase, h as GuardrailResult, i as GuardrailViolationError, I as InferAgentInput, j as InferAgentToolNames, k as MainLoopOptions, l as McpServersMap, P as PolicyHandler, m as ProjectSettingsGrant, n as SettingSourceCapability, o as SkillsRequestContext, p as SkillsSelection, q as TimeoutAction, r as ToolWalkResult, s as ToolboxOptions, t as ToolboxWalkResult, U as UntrustedSettingSourceError, u as compileAgentDefinition, v as compileTools, w as isAgentDefinition, x as resolveEnabledSkills, y as resolveSettingSources } from './define-agent-3Kuf6iKM.js';
5
+ import { L as LoopStrategy, R as ReflectionStrategy, a as RoundStreamFactory, S as StreamEvent, D as DelegationResult, C as ContextWindowOptions, b as SkillsOptions, A as AgentManifestEntry, H as HitlDecision, s as streamAgentUIMessages, c as ApprovalPosture } from './bridge-entry-BEniSXWE.js';
6
+ export { d as AfterToolCallContext, e as AgentBuilder, f as AgentDefinitionError, g as AgentExecutionContext, h as AgentManifest, i as AgentManifestSource, j as AgentManifestTool, k as AgentRoute, l as AgentRouteContext, m as AgentRunInfo, n as AgentStreamEvent, o as AgentTurnMetadata, p as AgentsPluginOptions, q as ApiErrorContext, r as ApiErrorDecision, t as ApiErrorPolicy, u as ApprovalRequiredEvent, v as ArtifactChunkEvent, w as ArtifactStartEvent, B as BackgroundDelegation, x as BeforeToolCallContext, y as BudgetExceededError, z as CheckpointSavedEvent, E as CompiledContextWindow, F as ContextualTool, G as DEFAULT_MAX_ITERATIONS, I as DefinitionOrThunk, J as DelegateFn, K as DelegateOptions, M as DelegationBudgetExceededError, N as DelegationError, O as DelegationPort, P as DelegationTarget, Q as DelegationTimeoutError, T as DoneEvent, U as EphemeralAgent, V as ErrorEvent, W as FileEditEvent, X as IterationEvent, Y as LLMCallContext, Z as LoopFinishReason, _ as LoopOutcome, $ as LoopStrategyConfig, a0 as McpApprovalSpec, a1 as McpFileError, a2 as McpRegistryConfig, a3 as McpRequestContext, a4 as McpSelection, a5 as PartialToolCallEvent, a6 as ProcessInputContext, a7 as ReflectionContext, a8 as ReflectionResult, a9 as ReflectionStrategyConfig, aa as RunStartedEvent, ab as ScoreVerdict, ac as ScoredDelegation, ad as Scorer, ae as SdkAgentHandle, af as SdkMessage, ag as SdkSendOptions, ah as SdkTurnHandle, ai as Segment, aj as StateUpdateEvent, ak as TextDeltaEvent, al as ThinkingEvent, am as ToolCallEvent, an as ToolCallVeto, ao as ToolHooks, ap as ToolHooksPlugin, aq as ToolResultEvent, ar as agentsPlugin, as as buildModelSelection, at as compileAgentModule, au as compileContextWindow, av as compileProjectContext, aw as compileSkills, ax as createAgentExecutionContext, ay as createApiErrorHandler, az as createSdkAgentStream, aA as createThinkTagExtractor, aB as createToolHooksPlugin, aC as delegate, aD as delegateBackground, aE as delegateWithScoring, 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 ladderReflectionStrategy, aR as loadMcpJson, aS as loopStrategyConfigSchema, aT as mcpRegistry, aU as mcpToolApprovals, aV as noopReflectionStrategy, aW as presentUIMessageStream, aX as projectContextMetadataOnlyKnobs, aY as reasoningEffortOf, aZ as reflectionStrategyConfigSchema, a_ as resolveLoopStrategy, a$ as resolveMcpServers, b0 as runWithApiErrorHandling, b1 as streamAgentResponse, b2 as toAgentFactory, b3 as translateSdkEvent, b4 as withClockCap, b5 as withEphemeralAgent } from './bridge-entry-BEniSXWE.js';
5
7
  import { TheokitAgentError } from '@theokit/sdk/errors';
6
8
  export * from '@theokit/sdk/errors';
7
9
  export { ConfigurationError, BudgetExceededError as WindowBudgetExceededError } from '@theokit/sdk/errors';
@@ -15,9 +17,14 @@ export { assertNoSymlinkEscape, isForbiddenPath, safePathJoin } from '@theokit/s
15
17
  export * from '@theokit/sdk/concurrency';
16
18
  export * from '@theokit/sdk/messages';
17
19
  export * from '@theokit/sdk/models';
20
+ import { DiscoverSubagentsOptions } from '@theokit/sdk/subagents-loader';
18
21
  export { AgentDefinition as SubagentDefinition, discoverSubagents, loadSubagentDefinition } from '@theokit/sdk/subagents-loader';
22
+ export { H as HookHandlers } from './hook-handlers-Cw2FsnE5.js';
19
23
  import { WireChunk } from '@theokit/presenter/wire';
24
+ export { WireChunk, WireDataPart } from '@theokit/presenter/wire';
25
+ export { ContentChunk, LifecycleItem, LifecycleVocabulary, TurnLifecycle, TurnOutcome, foldTurnLifecycle } from '@theokit/presenter';
20
26
  import '@theokit/http';
27
+ import '@theokit/sdk/sandbox';
21
28
 
22
29
  /**
23
30
  * M9 (theokit-ai-first) — built-in guardrail detectors.
@@ -470,6 +477,36 @@ declare class GoalRunner {
470
477
  run(goal: string, options?: GoalOptions, deps?: GoalRunnerDeps): AsyncGenerator<GoalEvent, GoalResult, void>;
471
478
  }
472
479
 
480
+ /**
481
+ * M69 — render one {@link GoalEvent} as a line, exhaustively and safely.
482
+ *
483
+ * ## Why this exists
484
+ *
485
+ * `GoalEvent` is a closed discriminated union of five variants. Every consumer that renders a goal
486
+ * run switched on it, and TypeScript made that switch exhaustive against the types they had
487
+ * installed — which is precisely the problem: the day the SDK adds a sixth variant in a minor, each
488
+ * of those switches is silently non-exhaustive at runtime while still compiling.
489
+ *
490
+ * So every consumer wrote the same default branch for an event it could not name. This function is
491
+ * that branch, written once, where the knowledge belongs.
492
+ *
493
+ * ## Exhaustive-safe means both halves
494
+ *
495
+ * **Compile time:** the `never` assignment at the end of the switch fails the build if a variant is
496
+ * added to the union — here, in the one file that claims to know them all, rather than in every
497
+ * consumer.
498
+ *
499
+ * **Run time:** an event whose `type` this build does not recognise is still formatted, and the line
500
+ * says so. A render path that throws on a forward-compatible event turns an SDK minor into a
501
+ * crashed UI; a line that pretends to understand it is worse, because nobody notices. The honest
502
+ * output names the type and marks it unrecognised.
503
+ *
504
+ * The milestone allowed marking the published union OPEN instead. That was rejected: an open union
505
+ * makes the default branch *required*, which is the opposite of the stated goal — the consumer
506
+ * stops writing it.
507
+ */
508
+ declare function formatGoalEvent(event: GoalEvent): string;
509
+
473
510
  /**
474
511
  * M52 — the capability layer: object-oriented, composable authoring that produces the EXISTING narrow
475
512
  * waist (`CompiledAgentOptions`), which `assembleM8CreateOptions` already turns into `Agent.create`
@@ -497,7 +534,15 @@ interface Capability {
497
534
  apply(draft: CompiledAgentOptionsDraft): void;
498
535
  }
499
536
  /** Two capabilities set the same scalar field to different values — a composition bug, never last-wins. */
500
- declare class CapabilityConflictError extends Error {
537
+ /**
538
+ * M80 — extends {@link TheokitAgentError}, not plain `Error`.
539
+ *
540
+ * `isTransientError` is defined over `TheokitAgentError`, so a class outside that hierarchy is
541
+ * INVISIBLE to it and the only recourse left to a consumer is matching on message text. `code` is
542
+ * stable across a rename; `isRetryable` is DECLARED, because a default would be a retry policy
543
+ * nobody chose.
544
+ */
545
+ declare class CapabilityConflictError extends TheokitAgentError {
501
546
  readonly name = "CapabilityConflictError";
502
547
  constructor(field: string, previous: unknown, next: unknown, capability: string);
503
548
  }
@@ -548,7 +593,15 @@ declare class SkillsCapability implements Capability {
548
593
  * capability names): resolving name → capability without a switch that grows per feature (OCP).
549
594
  */
550
595
  /** Fail-fast with the known set — never `undefined` leaking into the pipeline. */
551
- declare class UnknownCapabilityError extends Error {
596
+ /**
597
+ * M80 — extends {@link TheokitAgentError}, not plain `Error`.
598
+ *
599
+ * `isTransientError` is defined over `TheokitAgentError`, so a class outside that hierarchy is
600
+ * INVISIBLE to it and the only recourse left to a consumer is matching on message text. `code` is
601
+ * stable across a rename; `isRetryable` is DECLARED, because a default would be a retry policy
602
+ * nobody chose.
603
+ */
604
+ declare class UnknownCapabilityError extends TheokitAgentError {
552
605
  readonly name = "UnknownCapabilityError";
553
606
  constructor(requested: string, known: readonly string[]);
554
607
  }
@@ -670,10 +723,22 @@ declare class SkillsOptionsCapability implements Capability {
670
723
  constructor(options: SkillsOptions);
671
724
  apply(draft: CompiledAgentOptionsDraft): void;
672
725
  }
673
- /** Functional-path fields that had no decorator source — closing the gap list, not adding surface. */
674
- declare class SettingSourcesCapability extends FieldCapability<'settingSources'> {
726
+ /**
727
+ * `.settingSources({ user, project })` → the resolved SDK roots.
728
+ *
729
+ * NOT a `FieldCapability` (M68). A raw pass-through here would let a bare `'project'` string reach
730
+ * `CompiledAgentOptions` — and `project` reads `<cwd>/.theokit/`, **including `hooks.json`, which
731
+ * executes shell**. Resolving through the gate is what makes the compiled value unable to express a
732
+ * root that no posture authorized.
733
+ *
734
+ * The refusal happens at `apply()` — build time — rather than at run assembly, per
735
+ * `error-handling.md` § 3: validate at the entry, fail before the value travels.
736
+ */
737
+ declare class SettingSourcesCapability implements Capability {
738
+ private readonly selection;
675
739
  readonly name = "setting-sources";
676
- protected readonly field: "settingSources";
740
+ constructor(selection: SettingSourcesSelection);
741
+ apply(draft: CompiledAgentOptionsDraft): void;
677
742
  }
678
743
  declare class PluginsCapability extends FieldCapability<'plugins'> {
679
744
  readonly name = "plugins";
@@ -727,6 +792,64 @@ declare class MainLoopCapability implements Capability {
727
792
  apply(draft: CompiledAgentOptionsDraft): void;
728
793
  }
729
794
 
795
+ /**
796
+ * M69 — the composed shape of an agent, as a value the construction sites can consume.
797
+ *
798
+ * ## What this replaces
799
+ *
800
+ * `applyCapabilities` returns a `FinalizedDraft`: `Partial<CompiledAgentOptions>` plus a MUTABLE
801
+ * `provenance` array. That is the compiler's working surface — exactly right for capabilities,
802
+ * which enrich it in place — and it was also the only thing the capability layer handed back.
803
+ *
804
+ * So a caller that wanted the small answer ("which tools does this agent have, on which model, and
805
+ * who declared them?") had to depend on the entire compiled-options shape and receive an array it
806
+ * could push into. The three construction sites — the `AgentBuilder`, `Agent.create`, and roles
807
+ * loaded from disk — all need that same answer, and none of them should be handed the draft to get
808
+ * it.
809
+ *
810
+ * ## Why four fields
811
+ *
812
+ * `{ tools, model, reasoningEffort, provenance }` is what a caller composes and reasons about: what
813
+ * the agent can do, on which model, at what effort, and where each of those came from. Everything
814
+ * else in the compiled options is downstream projection. Publishing the narrow value is what keeps
815
+ * the wide internal one free to change — the reason it was internal in the first place.
816
+ *
817
+ * `provenance` is what makes the shape auditable rather than merely descriptive: two capabilities
818
+ * may both touch `tools`, and without it a reader cannot tell which one to go edit.
819
+ */
820
+ interface AgentShape {
821
+ /** Identity of the agent this shape describes. */
822
+ readonly name: string;
823
+ /**
824
+ * Tools the composed capabilities contributed, in declaration order.
825
+ *
826
+ * `readonly CompiledTool[]`, not the draft's own `CompiledTool[]`: inheriting the draft's type
827
+ * would publish a MUTABLE array, which is the half of the problem this value exists to fix. The
828
+ * draft is mutable because capabilities enrich it in place; what the construction sites receive
829
+ * must not be.
830
+ */
831
+ readonly tools: readonly CompiledTool[];
832
+ /** Model id, when some capability declared one. */
833
+ readonly model?: string;
834
+ /** Extended-thinking effort, when declared. */
835
+ readonly reasoningEffort?: ReasoningEffort;
836
+ /** Which capability contributed which field. */
837
+ readonly provenance: readonly ProvenanceEntry[];
838
+ }
839
+ /**
840
+ * Compose `members` into a published {@link AgentShape}.
841
+ *
842
+ * A projection of `applyCapabilities`, never a second implementation — so it inherits the set-once
843
+ * discipline: a conflicting redeclaration still throws `CapabilityConflictError` rather than
844
+ * resolving silently. A narrower return type that swallowed the conflict would be a downgrade
845
+ * disguised as ergonomics.
846
+ *
847
+ * The result is frozen, including its arrays. The draft is mutable by design; the published value
848
+ * must not be, or the shape becomes a shared mutable and the next reader cannot tell whether what
849
+ * they hold is what was declared.
850
+ */
851
+ declare function declareAgentShape(name: string, members: readonly Capability[]): AgentShape;
852
+
730
853
  /**
731
854
  * M53 — tools without `@Toolbox`/`@Tool`.
732
855
  *
@@ -1062,26 +1185,22 @@ declare class AcpClient {
1062
1185
  }
1063
1186
 
1064
1187
  /**
1065
- * M35 (multi-surface) — the in-process agent-turn seam (Model A).
1188
+ * M81 — the names of the subagents defined under `<cwd>/.theokit/agents/*.md`.
1066
1189
  *
1067
- * The FRAMEWORK-owned sibling of the HTTP `mountAgent` and the stdout `runAgentInTerminal`: it runs a
1068
- * compiled agent with the SAME `compileAgentModule` + SAME `streamAgentUIMessages` (G2 — reuses the
1069
- * SDK runtime, reimplements nothing), but returns the raw `UIMessageChunk` generator so ANY consumer
1070
- * drives it directly — the Ink TUI (M35), a Tauri window (M36), or a test — in a SINGLE process with
1071
- * NO HTTP loopback, NO port, and NO CSRF (there is no network boundary to defend).
1190
+ * ## Why one line deserves to exist
1072
1191
  *
1073
- * The ONLY difference from the HTTP mount is HITL resolution: the mount pauses the run and resolves
1074
- * the approval via a SECOND HTTP request to `/approve/:id` (the approval registry). In-process there
1075
- * is no second request — the caller resolves the approval INLINE via `awaitApproval` (e.g. the Ink
1076
- * TUI's y/n prompt). The gated-tool map is `compiled.hitl` verbatim, so the pause semantics are
1077
- * byte-identical to the HTTP path; only the resolver differs. Parity with the mount is by
1078
- * construction: both compile the module, resolve function-form skills, and call `streamAgentUIMessages`
1079
- * with the same `{ message, sessionId, hitl }`.
1192
+ * It is a SELECTOR over `discoverSubagents`, exactly as `loadSubagentDefinition` already is and
1193
+ * that module says why in its own words: *"one parser is the whole point"*.
1080
1194
  *
1081
- * Consumers WILL still receive `tool-approval-request` chunks from the returned generator they are
1082
- * INFORMATIONAL (render them or ignore them). The authoritative human gate is `awaitApproval`, which
1083
- * the SDK awaits BEFORE the gated tool runs; the chunk is not the gate.
1195
+ * What was missing is not the logic; it is the REACH. A product that wants an inventory of
1196
+ * subagents for a `/agents` command had no name-shaped answer to reach for, so it wrote a second
1197
+ * reader over the same directory. Two readers of one convention disagree eventually about
1198
+ * frontmatter, about which files count, about what an absent directory means — and the disagreement
1199
+ * shows up as a command that lists an agent the runtime cannot find.
1200
+ *
1201
+ * Sorted, because an inventory whose order changes per filesystem is an inventory nobody can diff.
1084
1202
  */
1203
+ declare function listSubagentNames(cwd: string, options?: DiscoverSubagentsOptions): Promise<readonly string[]>;
1085
1204
 
1086
1205
  /** An inline approval request handed to the caller's `awaitApproval` (the Ink/Tauri prompt). */
1087
1206
  interface InProcessApprovalRequest {
@@ -1144,7 +1263,16 @@ interface StreamAgentTurnDeps {
1144
1263
  * the correct posture: silently running a `@HumanInTheLoop`-gated tool with no human gate is exactly
1145
1264
  * the #99 class of bug. Typed so callers can catch it distinctly.
1146
1265
  */
1147
- declare class InProcessApprovalRequiredError extends Error {
1266
+ /**
1267
+ * M80 — extends {@link TheokitAgentError}, not plain `Error`.
1268
+ *
1269
+ * `isTransientError` is defined over `TheokitAgentError`, so a class outside that hierarchy is
1270
+ * INVISIBLE to it and the only recourse left to a consumer is matching on message text. `code` is
1271
+ * stable across a rename; `isRetryable` is DECLARED, because a default would be a retry policy
1272
+ * nobody chose.
1273
+ */
1274
+ declare class InProcessApprovalRequiredError extends TheokitAgentError {
1275
+ readonly name = "InProcessApprovalRequiredError";
1148
1276
  constructor(toolNames: readonly string[]);
1149
1277
  }
1150
1278
  /**
@@ -1164,6 +1292,22 @@ type ListOptionsWithoutPagination = ListAgentsOptions & {
1164
1292
  * the previous minor keeps compiling; it will be removed in the next major.
1165
1293
  */
1166
1294
  type ListOptionsWithoutPaginationAlias = ListOptionsWithoutPagination;
1295
+ /**
1296
+ * M71 — `Agent.delete` clears the REGISTRY ENTRY and never touches the transcript on disk.
1297
+ *
1298
+ * That asymmetry is not visible from the name, and the consumer that hit it had to discover it by
1299
+ * measuring: it called `delete`, believed the session was gone, and found the `.jsonl` still there.
1300
+ * A method whose name promises removal and delivers half of it is the kind of thing this layer is
1301
+ * supposed to say out loud — the same reason the `list` narrowing above carries its own note.
1302
+ *
1303
+ * The whole answer is `deleteSession` in `@theokit/agents/session`, which returns
1304
+ * `{ registryRemoved, transcriptRemoved }` precisely so the two stores are impossible to confuse,
1305
+ * and refuses by default when the session is protected. Reach for that unless you specifically want
1306
+ * the registry alone.
1307
+ *
1308
+ * Kept reachable rather than removed: narrowing it away would break a consumer that legitimately
1309
+ * wants only the registry entry gone, and this layer's rule is that enriching never reduces.
1310
+ */
1167
1311
  type AgentWithNarrowedList = Omit<typeof Agent$1, 'list'> & {
1168
1312
  list(options?: ListOptionsWithoutPagination): Promise<Omit<ListResult<SDKAgentInfo>, 'nextCursor'>>;
1169
1313
  };
@@ -1174,4 +1318,4 @@ type AgentWithNarrowedList = Omit<typeof Agent$1, 'list'> & {
1174
1318
  type AgentWithNarrowedListAlias = AgentWithNarrowedList;
1175
1319
  declare const Agent: AgentWithNarrowedList;
1176
1320
 
1177
- export { type A2AAuth, type A2ACapabilities, type A2ASkill, type A2AToolConfig, AcpClient, AcpMessageDecoder, type AcpTransport, Agent, type AgentCard, type AgentConfig, AgentConfigCapability, AgentManifestEntry, AgentRunner, AgentRunnerBuilder, type AgentRunnerRunOptions, type AgentWithNarrowedListAlias, ApprovalOptions, ApprovalPosture, type BuildAgentCardOptions, type Capability, CapabilityConflictError, CapabilityPreset, CapabilityRegistry, CheckpointCapability, type CompactionCallOptions, type CompactionStrategyConfig, CompiledAgentOptions, type CompiledAgentOptionsDraft, CompiledTool, ContextWindowCapability, type CostGuardOptions, DEFAULT_KEEP_TOKENS, DelegationResult, FieldCapability, type FinalizedDraft, GoalRunner, type GoalRunnerDeps, Guardrail, GuardrailsCapability, HitlDecision, HumanInTheLoopCapability, HumanInTheLoopOptions, type InProcessApprovalRequest, InProcessApprovalRequiredError, type InProcessAwaitApproval, type ListOptionsWithoutPaginationAlias, LoopStrategy, MCP_PROTOCOL_VERSION, MainLoopCapability, MainLoopMeta, type McpJsonSchema, type McpServerInfo, McpServersCapability, type McpToolDescriptor, MemoryCapability, ModelCapability, type NamedTool, type OutputModerationOptions, type PiiOptions, PluginsCapability, ProjectContextCapability, type PromptInjectionOptions, type ProvenanceEntry, ReasoningEffort, ReflectionStrategy, RoundStreamFactory, RunContextCapability, SettingSourcesCapability, SkillsCapability, SkillsOptionsCapability, SkillsResolverCapability, type StreamAgentTurnDeps, type StreamAgentTurnInProcessInput, StreamEvent, SubAgentsCapability, type Summarize, type ToolComNome, type ToolDeclaration, ToolOptions, ToolboxCapability, type ToolboxSource, ToolsCapability, Toolset, ToolsetError, type TranscriptCompactionStrategy, UnknownCapabilityError, applyCapabilities, buildAgentCard, buildMcpToolDescriptors, compactionStrategyConfigSchema, costGuard, createA2ATool, createDraft, deriveConversationId, encodeAcpMessage, estimateTokens, mcpServerInfo, moderateOutputStream, outputModeration, parseConversationId, piiDetector, promptInjectionDetector, resolveCompactionStrategy, runInputGuards, runOutputGuards, setOnce, streamAgentTurnInProcess, streamAgentUIMessages, tokenBudgetCompactionStrategy, unicodeNormalizer, wellKnownCardPath };
1321
+ export { type A2AAuth, type A2ACapabilities, type A2ASkill, type A2AToolConfig, AcpClient, AcpMessageDecoder, type AcpTransport, Agent, type AgentCard, type AgentConfig, AgentConfigCapability, AgentManifestEntry, AgentRunner, AgentRunnerBuilder, type AgentRunnerRunOptions, type AgentShape, type AgentWithNarrowedListAlias, ApprovalOptions, ApprovalPosture, type BuildAgentCardOptions, type Capability, CapabilityConflictError, CapabilityPreset, CapabilityRegistry, CheckpointCapability, type CompactionCallOptions, type CompactionStrategyConfig, CompiledAgentOptions, type CompiledAgentOptionsDraft, CompiledTool, ContextWindowCapability, type CostGuardOptions, DEFAULT_KEEP_TOKENS, DelegationResult, FieldCapability, type FinalizedDraft, GoalRunner, type GoalRunnerDeps, Guardrail, GuardrailsCapability, HitlDecision, HumanInTheLoopCapability, HumanInTheLoopOptions, type InProcessApprovalRequest, InProcessApprovalRequiredError, type InProcessAwaitApproval, type ListOptionsWithoutPaginationAlias, LoopStrategy, MCP_PROTOCOL_VERSION, MainLoopCapability, MainLoopMeta, type McpJsonSchema, type McpServerInfo, McpServersCapability, type McpToolDescriptor, MemoryCapability, ModelCapability, type NamedTool, type OutputModerationOptions, type PiiOptions, PluginsCapability, ProjectContextCapability, type PromptInjectionOptions, type ProvenanceEntry, ReasoningEffort, ReflectionStrategy, RoundStreamFactory, RunContextCapability, SettingSourcesCapability, SettingSourcesSelection, SkillsCapability, SkillsOptionsCapability, SkillsResolverCapability, type StreamAgentTurnDeps, type StreamAgentTurnInProcessInput, StreamEvent, SubAgentsCapability, type Summarize, type ToolComNome, type ToolDeclaration, ToolOptions, ToolboxCapability, type ToolboxSource, ToolsCapability, Toolset, ToolsetError, type TranscriptCompactionStrategy, UnknownCapabilityError, applyCapabilities, buildAgentCard, buildMcpToolDescriptors, compactionStrategyConfigSchema, costGuard, createA2ATool, createDraft, declareAgentShape, deriveConversationId, encodeAcpMessage, estimateTokens, formatGoalEvent, listSubagentNames, mcpServerInfo, moderateOutputStream, outputModeration, parseConversationId, piiDetector, promptInjectionDetector, resolveCompactionStrategy, runInputGuards, runOutputGuards, setOnce, streamAgentTurnInProcess, streamAgentUIMessages, tokenBudgetCompactionStrategy, unicodeNormalizer, wellKnownCardPath };