@theokit/agents 9.3.0 → 10.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.
@@ -3,138 +3,12 @@ import {
3
3
  inheritHooks
4
4
  } from "./chunk-RKWCXVYG.js";
5
5
  import {
6
- compileAgentDefinition,
7
- defineAgent,
8
- isAgentDefinition
6
+ compileAgentDefinition
9
7
  } from "./chunk-4VHCH6IZ.js";
10
8
  import {
11
9
  __name
12
10
  } from "./chunk-Z4QWC7IK.js";
13
11
 
14
- // src/errors.ts
15
- import { ConfigurationError } from "@theokit/sdk/errors";
16
-
17
- // src/bridge/compile-context-window.ts
18
- var STRATEGY_KNOBS = [
19
- "compactionStrategy",
20
- "preserveLastN",
21
- "preserveToolResults",
22
- "preserveSystemPrompt"
23
- ];
24
- function compileContextWindow(options) {
25
- const context = {};
26
- if (typeof options.maxTokens === "number") {
27
- context.maxTokens = options.maxTokens;
28
- }
29
- const opts = options;
30
- const metadataOnlyKnobs = STRATEGY_KNOBS.filter((knob) => opts[knob] !== void 0);
31
- return {
32
- context,
33
- metadataOnlyKnobs
34
- };
35
- }
36
- __name(compileContextWindow, "compileContextWindow");
37
-
38
- // src/bridge/compile-skills.ts
39
- function compileSkills(options) {
40
- if (options.autoDiscover) {
41
- return {
42
- autoInject: true
43
- };
44
- }
45
- return {
46
- enabled: options.include,
47
- autoInject: true
48
- };
49
- }
50
- __name(compileSkills, "compileSkills");
51
-
52
- // src/bridge/agent-compiler.ts
53
- var SDK_TOOL_NAME = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
54
- var SDK_TOOL_NAME_MAX_LENGTH = 64;
55
- var SDK_TOOL_NAME_CHARSET = /^[a-zA-Z][a-zA-Z0-9_-]*$/;
56
- var SDK_RESERVED_TOOL_NAMES = /* @__PURE__ */ new Set([
57
- "shell",
58
- "memory_search",
59
- "memory_get"
60
- ]);
61
- var SDK_RESERVED_TOOL_PREFIX = "mcp_";
62
- function toolRuntimeName(namespace, toolName) {
63
- if (toolName.trim().length === 0) {
64
- const where = namespace ? ` in namespace "${namespace}"` : "";
65
- throw new ConfigurationError(`tool: empty name${where} \u2014 declare a non-empty name for the tool`);
66
- }
67
- const name = namespace ? `${namespace}_${toolName}` : toolName;
68
- if (!SDK_TOOL_NAME.test(name)) {
69
- if (SDK_TOOL_NAME_CHARSET.test(name)) {
70
- throw new ConfigurationError(`tool: name "${name}" has length ${name.length} \u2014 the composition namespace + "_" + tool exceeds the maximum of ${SDK_TOOL_NAME_MAX_LENGTH} the SDK accepts`);
71
- }
72
- throw new ConfigurationError(`tool: invalid name "${name}" \u2014 it must match ${String(SDK_TOOL_NAME)} (the SDK rejects the rest; check the namespace and the tool name)`);
73
- }
74
- if (SDK_RESERVED_TOOL_NAMES.has(name) || name.startsWith(SDK_RESERVED_TOOL_PREFIX)) {
75
- throw new ConfigurationError(`tool: reserved name "${name}" \u2014 the SDK reserves ${[
76
- ...SDK_RESERVED_TOOL_NAMES
77
- ].join(", ")} and the prefix "${SDK_RESERVED_TOOL_PREFIX}"`);
78
- }
79
- return name;
80
- }
81
- __name(toolRuntimeName, "toolRuntimeName");
82
- function compileHitlGates(toolboxes) {
83
- const gates = /* @__PURE__ */ new Map();
84
- for (const tb of toolboxes) {
85
- for (const tool of tb.tools) {
86
- if (tool.hitl) {
87
- gates.set(toolRuntimeName(tb.namespace, tool.config.name), tool.hitl);
88
- }
89
- }
90
- }
91
- return gates;
92
- }
93
- __name(compileHitlGates, "compileHitlGates");
94
- function compileTools(toolboxes, toolboxInstances) {
95
- const tools = [];
96
- for (const tb of toolboxes) {
97
- const instance = toolboxInstances.get(tb.class);
98
- if (!instance) {
99
- throw new ConfigurationError(`toolbox: ${tb.class.name} was not instantiated \u2014 pass the instance in \`toolboxInstances\``);
100
- }
101
- for (const tool of tb.tools) {
102
- const handler = instance[tool.propertyKey];
103
- if (typeof handler !== "function") {
104
- throw new ConfigurationError(`toolbox: ${tb.class.name}.${String(tool.propertyKey)} is not a method (tool "${tool.config.name}")`);
105
- }
106
- const name = toolRuntimeName(tb.namespace, tool.config.name);
107
- tools.push({
108
- name,
109
- description: tool.config.description,
110
- inputSchema: tool.config.input,
111
- handler: /* @__PURE__ */ __name((input) => handler.call(instance, input), "handler")
112
- });
113
- }
114
- }
115
- return tools;
116
- }
117
- __name(compileTools, "compileTools");
118
-
119
- // src/bridge/agent-execution-context.ts
120
- function createAgentExecutionContext(base, agent, run, toolCall) {
121
- return {
122
- getRequest: /* @__PURE__ */ __name(() => base.getRequest(), "getRequest"),
123
- getUrl: /* @__PURE__ */ __name(() => base.getUrl(), "getUrl"),
124
- getClass: /* @__PURE__ */ __name(() => base.getClass(), "getClass"),
125
- getMethodName: /* @__PURE__ */ __name(() => base.getMethodName(), "getMethodName"),
126
- getAgent: /* @__PURE__ */ __name(() => agent, "getAgent"),
127
- getRun: /* @__PURE__ */ __name(() => run, "getRun"),
128
- getToolCall: /* @__PURE__ */ __name(() => toolCall ?? null, "getToolCall"),
129
- isAgentContext: /* @__PURE__ */ __name(() => true, "isAgentContext")
130
- };
131
- }
132
- __name(createAgentExecutionContext, "createAgentExecutionContext");
133
- function isAgentContext(ctx) {
134
- return "isAgentContext" in ctx && ctx.isAgentContext();
135
- }
136
- __name(isAgentContext, "isAgentContext");
137
-
138
12
  // src/bridge/compile-project-context.ts
139
13
  var UNMAPPED_KNOBS = [
140
14
  "indexStrategy",
@@ -177,157 +51,6 @@ function compileProjectContext(options, base) {
177
51
  }
178
52
  __name(compileProjectContext, "compileProjectContext");
179
53
 
180
- // src/bridge/agent-sse-handler.ts
181
- var encoder = new TextEncoder();
182
- function streamAgentResponse(eventStream) {
183
- const stream = new ReadableStream({
184
- async start(controller) {
185
- let closed = false;
186
- const safeEnqueue = /* @__PURE__ */ __name((chunk) => {
187
- if (closed) return;
188
- try {
189
- controller.enqueue(chunk);
190
- } catch {
191
- closed = true;
192
- }
193
- }, "safeEnqueue");
194
- try {
195
- for await (const event of eventStream) {
196
- if (closed) break;
197
- const data = JSON.stringify(event);
198
- const frame = `event: ${event.type}
199
- data: ${data}
200
-
201
- `;
202
- safeEnqueue(encoder.encode(frame));
203
- }
204
- } catch (err) {
205
- if (!closed) {
206
- const errorEvent = {
207
- type: "error",
208
- error: {
209
- message: err instanceof Error ? err.message : "Internal agent error"
210
- }
211
- };
212
- const frame = `event: error
213
- data: ${JSON.stringify(errorEvent)}
214
-
215
- `;
216
- safeEnqueue(encoder.encode(frame));
217
- }
218
- } finally {
219
- controller.close();
220
- }
221
- }
222
- });
223
- return new Response(stream, {
224
- status: 200,
225
- headers: {
226
- "content-type": "text/event-stream",
227
- "cache-control": "no-cache",
228
- connection: "keep-alive"
229
- }
230
- });
231
- }
232
- __name(streamAgentResponse, "streamAgentResponse");
233
-
234
- // src/bridge/agent-stream-events.ts
235
- function isTextDelta(e) {
236
- return e.type === "text_delta";
237
- }
238
- __name(isTextDelta, "isTextDelta");
239
- function isToolCall(e) {
240
- return e.type === "tool_call";
241
- }
242
- __name(isToolCall, "isToolCall");
243
- function isPartialToolCall(e) {
244
- return e.type === "partial_tool_call";
245
- }
246
- __name(isPartialToolCall, "isPartialToolCall");
247
- function isToolResult(e) {
248
- return e.type === "tool_result";
249
- }
250
- __name(isToolResult, "isToolResult");
251
- function isDone(e) {
252
- return e.type === "done";
253
- }
254
- __name(isDone, "isDone");
255
- function isError(e) {
256
- return e.type === "error";
257
- }
258
- __name(isError, "isError");
259
- function isApprovalRequired(e) {
260
- return e.type === "approval_required";
261
- }
262
- __name(isApprovalRequired, "isApprovalRequired");
263
-
264
- // src/bridge/agent-route-generator.ts
265
- function generateAgentRoutes(ctx) {
266
- const { walkResult, createRun, getRun } = ctx;
267
- const basePath = walkResult.route.replace(/\/$/, "");
268
- const routes = [];
269
- routes.push({
270
- method: "POST",
271
- path: `${basePath}/chat`,
272
- handler: /* @__PURE__ */ __name(async (request) => {
273
- let body = null;
274
- try {
275
- body = await request.json();
276
- } catch {
277
- }
278
- const message = body?.message;
279
- if (typeof message !== "string" || message.length === 0) {
280
- return new Response(JSON.stringify({
281
- error: {
282
- code: "BAD_REQUEST",
283
- message: "message field required"
284
- }
285
- }), {
286
- status: 400,
287
- headers: {
288
- "content-type": "application/json"
289
- }
290
- });
291
- }
292
- const rawSessionId = body?.sessionId;
293
- const sessionId = typeof rawSessionId === "string" ? rawSessionId : `session-${Date.now()}`;
294
- return streamAgentResponse(createRun(message, sessionId));
295
- }, "handler")
296
- });
297
- if (getRun) {
298
- routes.push({
299
- method: "GET",
300
- path: `${basePath}/runs/:runId`,
301
- handler: /* @__PURE__ */ __name(async (request) => {
302
- const url = new URL(request.url);
303
- const runId = url.pathname.split("/").pop() ?? "";
304
- const run = await getRun(runId);
305
- if (!run) {
306
- return new Response(JSON.stringify({
307
- error: {
308
- code: "NOT_FOUND",
309
- message: `Run ${runId} not found`
310
- }
311
- }), {
312
- status: 404,
313
- headers: {
314
- "content-type": "application/json"
315
- }
316
- });
317
- }
318
- return new Response(JSON.stringify(run), {
319
- status: 200,
320
- headers: {
321
- "content-type": "application/json"
322
- }
323
- });
324
- }, "handler")
325
- });
326
- }
327
- return routes;
328
- }
329
- __name(generateAgentRoutes, "generateAgentRoutes");
330
-
331
54
  // src/guardrails/types.ts
332
55
  import { TheokitAgentError } from "@theokit/sdk/errors";
333
56
  var GuardrailViolationError = class extends TheokitAgentError {
@@ -531,6 +254,41 @@ async function* moderateOutputStream(inner, guards, extractText) {
531
254
  }
532
255
  __name(moderateOutputStream, "moderateOutputStream");
533
256
 
257
+ // src/bridge/approval-decision.ts
258
+ var APPROVAL_MODES = [
259
+ "suggest",
260
+ "auto-edit",
261
+ "full-auto"
262
+ ];
263
+ var WRITE_SCOPED_TOOLS = immutableSet([
264
+ "apply_patch",
265
+ "edit_file",
266
+ "write_file"
267
+ ]);
268
+ function immutableSet(values) {
269
+ const set = new Set(values);
270
+ const refuse = /* @__PURE__ */ __name((op) => () => {
271
+ throw new TypeError(`${op} on an immutable set: this is an approval catalog, and widening it at runtime would change what auto-approves for every consumer of this package. Pass your own set via \`writeScopedTools\` instead.`);
272
+ }, "refuse");
273
+ return Object.freeze(Object.assign(set, {
274
+ add: refuse("add"),
275
+ delete: refuse("delete"),
276
+ clear: refuse("clear")
277
+ }));
278
+ }
279
+ __name(immutableSet, "immutableSet");
280
+ function shouldAutoApprove(mode, toolName, posture, options) {
281
+ switch (mode) {
282
+ case "suggest":
283
+ return false;
284
+ case "auto-edit":
285
+ return options?.writeScopedTools?.has(toolName) ?? false;
286
+ case "full-auto":
287
+ return posture?.enforced === true;
288
+ }
289
+ }
290
+ __name(shouldAutoApprove, "shouldAutoApprove");
291
+
534
292
  // src/bridge/tool-hooks-plugin.ts
535
293
  function createToolHooksPlugin(hooks) {
536
294
  return {
@@ -584,6 +342,128 @@ function createToolHooksPlugin(hooks) {
584
342
  }
585
343
  __name(createToolHooksPlugin, "createToolHooksPlugin");
586
344
 
345
+ // src/debug-log.ts
346
+ function debugLog(marker, data) {
347
+ const flag = process.env.THEOKIT_DEBUG;
348
+ if (flag !== void 0 && flag !== "" && flag !== "0" && flag !== "false") {
349
+ console.debug(marker, data);
350
+ }
351
+ }
352
+ __name(debugLog, "debugLog");
353
+
354
+ // src/bridge/hitl-plugin.ts
355
+ function createHitlPlugin(wiring) {
356
+ return {
357
+ name: "theokit-hitl",
358
+ version: "1.0.0",
359
+ // `kind: 'general'` is load-bearing — without it the SDK's isCodePlugin() drops this plugin and
360
+ // the HITL veto never fires (the run would proceed WITHOUT waiting for human approval).
361
+ kind: "general",
362
+ register(ctx) {
363
+ ctx.on("pre_tool_call", async (c) => {
364
+ const opts = wiring.gated.get(c.name);
365
+ if (!opts) return void 0;
366
+ const approvalId = crypto.randomUUID();
367
+ wiring.emit({
368
+ type: "approval_required",
369
+ callId: approvalId,
370
+ toolName: c.name,
371
+ question: opts.question,
372
+ input: c.args,
373
+ callbackUrl: `approve/${approvalId}`,
374
+ timeoutMs: opts.timeout ?? 3e5,
375
+ // M20 — carry the declared custom-payload schema so the UI knows what to collect.
376
+ ...opts.payloadSchema !== void 0 ? {
377
+ payloadSchema: opts.payloadSchema
378
+ } : {}
379
+ });
380
+ const raw = await wiring.awaitApproval(approvalId, opts, c.name);
381
+ const decision = typeof raw === "boolean" ? {
382
+ approved: raw
383
+ } : raw;
384
+ if (decision.approved) return void 0;
385
+ let message = `Tool '${c.name}' denied by human approver`;
386
+ if (decision.reason) message += `: ${decision.reason}`;
387
+ if (decision.payload !== void 0) {
388
+ message += ` (payload: ${JSON.stringify(decision.payload)})`;
389
+ }
390
+ return {
391
+ block: true,
392
+ message
393
+ };
394
+ });
395
+ }
396
+ };
397
+ }
398
+ __name(createHitlPlugin, "createHitlPlugin");
399
+
400
+ // src/bridge/approval-posture.ts
401
+ function reasonOf(posturePolicy) {
402
+ return posturePolicy.kind === "interactive" ? "human approver on this surface" : posturePolicy.reason;
403
+ }
404
+ __name(reasonOf, "reasonOf");
405
+ function applyPosture(extra, m8, posturePolicy, gated) {
406
+ const ofThePosture = posturePlugins(posturePolicy, gated);
407
+ if (ofThePosture.length === 0) return;
408
+ const currentOnes = extra.plugins ?? m8.plugins;
409
+ if (currentOnes !== void 0 && !Array.isArray(currentOnes)) {
410
+ throw new Error(`[@theokit/agents] approval posture "${posturePolicy.kind}" needs to install a plugin, but \`plugins\` was supplied in the legacy object form, which cannot carry both. Pass \`plugins\` as an array so the approval gate is not dropped.`);
411
+ }
412
+ extra.plugins = [
413
+ ...currentOnes ?? [],
414
+ ...ofThePosture
415
+ ];
416
+ }
417
+ __name(applyPosture, "applyPosture");
418
+ function posturePlugins(posturePolicy, gated) {
419
+ debugLog("[theokit] approval posture", {
420
+ kind: posturePolicy.kind,
421
+ reason: reasonOf(posturePolicy)
422
+ });
423
+ if (gated === void 0 || gated.size === 0) return [];
424
+ switch (posturePolicy.kind) {
425
+ case "interactive":
426
+ return [
427
+ createHitlPlugin({
428
+ gated,
429
+ emit: posturePolicy.emit,
430
+ awaitApproval: posturePolicy.awaitApproval
431
+ })
432
+ ];
433
+ case "auto-approve":
434
+ if (!shouldAutoApprove("full-auto", "*", posturePolicy.confinedBy)) {
435
+ throw new Error(`[@theokit/agents] approval posture "auto-approve" claims confinement ("${posturePolicy.reason}"), but the sandbox reports it is NOT enforced: ${posturePolicy.confinedBy.detail} (mode: ${posturePolicy.confinedBy.mode}). Auto-approving gated tools without enforced confinement runs arbitrary commands with no human and no sandbox. Use "interactive" (a human decides) or "auto-reject" (fail-closed) until the sandbox reports enforced.`);
436
+ }
437
+ return [
438
+ createToolHooksPlugin({
439
+ beforeToolCall: /* @__PURE__ */ __name((ctx) => {
440
+ if (gated.has(ctx.name)) {
441
+ debugLog("[theokit] gated tool auto-approved", {
442
+ tool: ctx.name,
443
+ reason: posturePolicy.reason
444
+ });
445
+ }
446
+ return void 0;
447
+ }, "beforeToolCall")
448
+ })
449
+ ];
450
+ case "auto-reject":
451
+ return [
452
+ createToolHooksPlugin({
453
+ // Only GATED tools are refused: the posture describes the gate, not a universal block.
454
+ // Refusing everything would break every agent with a free tool next to a gated one.
455
+ beforeToolCall: /* @__PURE__ */ __name((ctx) => gated.has(ctx.name) ? {
456
+ block: true,
457
+ message: `Tool '${ctx.name}' requires human approval, and this surface has no approver (approval posture: auto-reject \u2014 ${posturePolicy.reason}). Refused (fail-closed).`
458
+ } : void 0, "beforeToolCall")
459
+ })
460
+ ];
461
+ case "owned-by-surface":
462
+ return [];
463
+ }
464
+ }
465
+ __name(posturePlugins, "posturePlugins");
466
+
587
467
  // src/bridge/model-selection.ts
588
468
  var PARAM_THINKING = "thinking";
589
469
  function buildModelSelection(model, effort) {
@@ -944,128 +824,6 @@ async function* extractThinkTagStream(source) {
944
824
  }
945
825
  __name(extractThinkTagStream, "extractThinkTagStream");
946
826
 
947
- // src/debug-log.ts
948
- function debugLog(marker, data) {
949
- const flag = process.env.THEOKIT_DEBUG;
950
- if (flag !== void 0 && flag !== "" && flag !== "0" && flag !== "false") {
951
- console.debug(marker, data);
952
- }
953
- }
954
- __name(debugLog, "debugLog");
955
-
956
- // src/bridge/hitl-plugin.ts
957
- function createHitlPlugin(wiring) {
958
- return {
959
- name: "theokit-hitl",
960
- version: "1.0.0",
961
- // `kind: 'general'` is load-bearing — without it the SDK's isCodePlugin() drops this plugin and
962
- // the HITL veto never fires (the run would proceed WITHOUT waiting for human approval).
963
- kind: "general",
964
- register(ctx) {
965
- ctx.on("pre_tool_call", async (c) => {
966
- const opts = wiring.gated.get(c.name);
967
- if (!opts) return void 0;
968
- const approvalId = crypto.randomUUID();
969
- wiring.emit({
970
- type: "approval_required",
971
- callId: approvalId,
972
- toolName: c.name,
973
- question: opts.question,
974
- input: c.args,
975
- callbackUrl: `approve/${approvalId}`,
976
- timeoutMs: opts.timeout ?? 3e5,
977
- // M20 — carry the declared custom-payload schema so the UI knows what to collect.
978
- ...opts.payloadSchema !== void 0 ? {
979
- payloadSchema: opts.payloadSchema
980
- } : {}
981
- });
982
- const raw = await wiring.awaitApproval(approvalId, opts, c.name);
983
- const decision = typeof raw === "boolean" ? {
984
- approved: raw
985
- } : raw;
986
- if (decision.approved) return void 0;
987
- let message = `Tool '${c.name}' denied by human approver`;
988
- if (decision.reason) message += `: ${decision.reason}`;
989
- if (decision.payload !== void 0) {
990
- message += ` (payload: ${JSON.stringify(decision.payload)})`;
991
- }
992
- return {
993
- block: true,
994
- message
995
- };
996
- });
997
- }
998
- };
999
- }
1000
- __name(createHitlPlugin, "createHitlPlugin");
1001
-
1002
- // src/bridge/approval-posture.ts
1003
- function reasonOf(posturePolicy) {
1004
- return posturePolicy.kind === "interactive" ? "human approver on this surface" : posturePolicy.reason;
1005
- }
1006
- __name(reasonOf, "reasonOf");
1007
- function applyPosture(extra, m8, posturePolicy, gated) {
1008
- const ofThePosture = posturePlugins(posturePolicy, gated);
1009
- if (ofThePosture.length === 0) return;
1010
- const currentOnes = extra.plugins ?? m8.plugins;
1011
- if (currentOnes !== void 0 && !Array.isArray(currentOnes)) {
1012
- throw new Error(`[@theokit/agents] approval posture "${posturePolicy.kind}" needs to install a plugin, but \`plugins\` was supplied in the legacy object form, which cannot carry both. Pass \`plugins\` as an array so the approval gate is not dropped.`);
1013
- }
1014
- extra.plugins = [
1015
- ...currentOnes ?? [],
1016
- ...ofThePosture
1017
- ];
1018
- }
1019
- __name(applyPosture, "applyPosture");
1020
- function posturePlugins(posturePolicy, gated) {
1021
- debugLog("[theokit] approval posture", {
1022
- kind: posturePolicy.kind,
1023
- reason: reasonOf(posturePolicy)
1024
- });
1025
- if (gated === void 0 || gated.size === 0) return [];
1026
- switch (posturePolicy.kind) {
1027
- case "interactive":
1028
- return [
1029
- createHitlPlugin({
1030
- gated,
1031
- emit: posturePolicy.emit,
1032
- awaitApproval: posturePolicy.awaitApproval
1033
- })
1034
- ];
1035
- case "auto-approve":
1036
- if (!posturePolicy.confinedBy.enforced) {
1037
- throw new Error(`[@theokit/agents] approval posture "auto-approve" claims confinement ("${posturePolicy.reason}"), but the sandbox reports it is NOT enforced: ${posturePolicy.confinedBy.detail} (mode: ${posturePolicy.confinedBy.mode}). Auto-approving gated tools without enforced confinement runs arbitrary commands with no human and no sandbox. Use "interactive" (a human decides) or "auto-reject" (fail-closed) until the sandbox reports enforced.`);
1038
- }
1039
- return [
1040
- createToolHooksPlugin({
1041
- beforeToolCall: /* @__PURE__ */ __name((ctx) => {
1042
- if (gated.has(ctx.name)) {
1043
- debugLog("[theokit] gated tool auto-approved", {
1044
- tool: ctx.name,
1045
- reason: posturePolicy.reason
1046
- });
1047
- }
1048
- return void 0;
1049
- }, "beforeToolCall")
1050
- })
1051
- ];
1052
- case "auto-reject":
1053
- return [
1054
- createToolHooksPlugin({
1055
- // Only GATED tools are refused: the posture describes the gate, not a universal block.
1056
- // Refusing everything would break every agent with a free tool next to a gated one.
1057
- beforeToolCall: /* @__PURE__ */ __name((ctx) => gated.has(ctx.name) ? {
1058
- block: true,
1059
- message: `Tool '${ctx.name}' requires human approval, and this surface has no approver (approval posture: auto-reject \u2014 ${posturePolicy.reason}). Refused (fail-closed).`
1060
- } : void 0, "beforeToolCall")
1061
- })
1062
- ];
1063
- case "owned-by-surface":
1064
- return [];
1065
- }
1066
- }
1067
- __name(posturePlugins, "posturePlugins");
1068
-
1069
827
  // src/bridge/definition-or-thunk.ts
1070
828
  function project(def, overrides) {
1071
829
  const compiled = compileAgentDefinition(def);
@@ -1627,431 +1385,6 @@ function withGuardrails(handle, guardrails) {
1627
1385
  }
1628
1386
  __name(withGuardrails, "withGuardrails");
1629
1387
 
1630
- // src/bridge/present-ui-message-stream.ts
1631
- import { UIMessageStreamPresenter } from "@theokit/presenter";
1632
- function toAgentOutputEvent(e) {
1633
- switch (e.type) {
1634
- case "text_delta":
1635
- return {
1636
- type: "text",
1637
- text: e.content
1638
- };
1639
- case "thinking":
1640
- return {
1641
- type: "reasoning",
1642
- text: e.content
1643
- };
1644
- case "tool_call":
1645
- return {
1646
- type: "tool-call",
1647
- callId: e.callId,
1648
- name: e.toolName,
1649
- input: e.input
1650
- };
1651
- case "tool_result":
1652
- return {
1653
- type: "tool-result",
1654
- callId: e.callId,
1655
- name: e.toolName,
1656
- result: e.output,
1657
- isError: e.isError
1658
- };
1659
- default:
1660
- return null;
1661
- }
1662
- }
1663
- __name(toAgentOutputEvent, "toAgentOutputEvent");
1664
- function doneToMetadata(event) {
1665
- return event.cost === void 0 ? {
1666
- usage: event.usage,
1667
- durationMs: event.durationMs
1668
- } : {
1669
- usage: event.usage,
1670
- durationMs: event.durationMs,
1671
- cost: event.cost
1672
- };
1673
- }
1674
- __name(doneToMetadata, "doneToMetadata");
1675
- var ERROR_CODE_DATA_PART = "data-error-code";
1676
- var INPUT_REQUESTED_DATA_PART = "data-input-requested";
1677
- var TASK_PROGRESS_DATA_PART = "data-task-progress";
1678
- var SHELL_OUTPUT_DATA_PART = "data-shell-output";
1679
- function dataPart(type, data) {
1680
- return {
1681
- type,
1682
- data,
1683
- transient: true
1684
- };
1685
- }
1686
- __name(dataPart, "dataPart");
1687
- function* errorChunks(errorText, code) {
1688
- if (code !== void 0) yield dataPart(ERROR_CODE_DATA_PART, {
1689
- code
1690
- });
1691
- yield {
1692
- type: "error",
1693
- errorText
1694
- };
1695
- }
1696
- __name(errorChunks, "errorChunks");
1697
- function diagnosticDataPart(event) {
1698
- switch (event.type) {
1699
- case "checkpoint_saved":
1700
- return dataPart("data-checkpoint", {
1701
- checkpointId: event.checkpointId,
1702
- resumeToken: event.resumeToken,
1703
- step: event.step
1704
- });
1705
- // theokit#141 — without these cases the three restored events would be dropped by the loop's
1706
- // catch-all, which is the reported defect one layer down: translating an event and never
1707
- // presenting it leaves the consumer just as blind, minus even the warning.
1708
- case "input_requested":
1709
- return dataPart(INPUT_REQUESTED_DATA_PART, {
1710
- requestId: event.requestId
1711
- });
1712
- case "task_progress":
1713
- return dataPart(TASK_PROGRESS_DATA_PART, {
1714
- ...event.status !== void 0 ? {
1715
- status: event.status
1716
- } : {},
1717
- ...event.text !== void 0 ? {
1718
- text: event.text
1719
- } : {}
1720
- });
1721
- case "shell_output":
1722
- return dataPart(SHELL_OUTPUT_DATA_PART, {
1723
- event: event.event
1724
- });
1725
- default:
1726
- return null;
1727
- }
1728
- }
1729
- __name(diagnosticDataPart, "diagnosticDataPart");
1730
- async function* presentUIMessageStream(events, opts) {
1731
- const presenter = new UIMessageStreamPresenter({
1732
- textId: opts.textId
1733
- });
1734
- yield {
1735
- type: "start"
1736
- };
1737
- let turnMetadata;
1738
- try {
1739
- for await (const event of events) {
1740
- const output = toAgentOutputEvent(event);
1741
- if (output !== null) {
1742
- yield* presenter.present(output);
1743
- continue;
1744
- }
1745
- if (event.type === "approval_required") {
1746
- yield* presenter.closeBlock();
1747
- if (!presenter.hasSeen(event.callId)) {
1748
- presenter.markSeen(event.callId);
1749
- yield {
1750
- type: "tool-input-available",
1751
- toolCallId: event.callId,
1752
- toolName: event.toolName,
1753
- input: event.input ?? {},
1754
- dynamic: true
1755
- };
1756
- }
1757
- yield {
1758
- type: "tool-approval-request",
1759
- approvalId: event.callId,
1760
- toolCallId: event.callId
1761
- };
1762
- continue;
1763
- }
1764
- const diagnostic = diagnosticDataPart(event);
1765
- if (diagnostic !== null) {
1766
- yield* presenter.closeBlock();
1767
- yield diagnostic;
1768
- continue;
1769
- }
1770
- if (event.type === "error") {
1771
- yield* errorChunks(event.message, event.code);
1772
- break;
1773
- }
1774
- if (event.type === "done") {
1775
- turnMetadata = doneToMetadata(event);
1776
- break;
1777
- }
1778
- }
1779
- } catch (err) {
1780
- const code = err.code;
1781
- yield* errorChunks(String(err), typeof code === "string" ? code : void 0);
1782
- }
1783
- yield* presenter.finish(turnMetadata);
1784
- }
1785
- __name(presentUIMessageStream, "presentUIMessageStream");
1786
-
1787
- // src/bridge/agent-builder.ts
1788
- var ContextualTool = {
1789
- /**
1790
- * Tag a {@link CustomTool} with a literal name (so `.tool()` can accumulate the tool-name union)
1791
- * and, optionally, a required run-context type. The `requiredContext` argument is a type-only
1792
- * witness — pass `undefined as C` or a sample value; it is never read at runtime.
1793
- */
1794
- of(tool, _requiredContext) {
1795
- return tool;
1796
- }
1797
- };
1798
- function makeBuilder(config) {
1799
- const runtime = {
1800
- input: /* @__PURE__ */ __name((schema) => makeBuilder({
1801
- ...config,
1802
- input: schema
1803
- }), "input"),
1804
- model: /* @__PURE__ */ __name((id) => makeBuilder({
1805
- ...config,
1806
- model: id
1807
- }), "model"),
1808
- system: /* @__PURE__ */ __name((prompt) => makeBuilder({
1809
- ...config,
1810
- system: prompt
1811
- }), "system"),
1812
- reasoningEffort: /* @__PURE__ */ __name((effort) => makeBuilder({
1813
- ...config,
1814
- reasoningEffort: effort
1815
- }), "reasoningEffort"),
1816
- context: /* @__PURE__ */ __name((value) => makeBuilder({
1817
- ...config,
1818
- context: value
1819
- }), "context"),
1820
- tool: /* @__PURE__ */ __name((tool) => makeBuilder({
1821
- ...config,
1822
- tools: [
1823
- ...config.tools ?? [],
1824
- tool
1825
- ]
1826
- }), "tool"),
1827
- tools: /* @__PURE__ */ __name((list) => makeBuilder({
1828
- ...config,
1829
- tools: [
1830
- ...config.tools ?? [],
1831
- ...list
1832
- ]
1833
- }), "tools"),
1834
- // `when` is deliberately not a conditional-typed return: the branch runs or it does not, and
1835
- // either way the caller gets a builder carrying the same accumulated state. Returning `builder`
1836
- // unchanged on `false` is what makes it a true no-op rather than a reset.
1837
- when: /* @__PURE__ */ __name((condition, apply) => {
1838
- const builder = makeBuilder(config);
1839
- return condition ? apply(builder) : builder;
1840
- }, "when"),
1841
- guardrail: /* @__PURE__ */ __name((g) => makeBuilder({
1842
- ...config,
1843
- guardrails: [
1844
- ...config.guardrails ?? [],
1845
- g
1846
- ]
1847
- }), "guardrail"),
1848
- guardrails: /* @__PURE__ */ __name((gs) => makeBuilder({
1849
- ...config,
1850
- guardrails: gs
1851
- }), "guardrails"),
1852
- approval: /* @__PURE__ */ __name((toolName, options) => makeBuilder({
1853
- ...config,
1854
- approvals: {
1855
- ...config.approvals ?? {},
1856
- [toolName]: options
1857
- }
1858
- }), "approval"),
1859
- approvals: /* @__PURE__ */ __name((map) => makeBuilder({
1860
- ...config,
1861
- approvals: map
1862
- }), "approvals"),
1863
- skills: /* @__PURE__ */ __name((selection) => makeBuilder({
1864
- ...config,
1865
- skills: selection
1866
- }), "skills"),
1867
- settingSources: /* @__PURE__ */ __name((selection) => makeBuilder({
1868
- ...config,
1869
- settingSources: selection
1870
- }), "settingSources"),
1871
- memory: /* @__PURE__ */ __name((settings) => makeBuilder({
1872
- ...config,
1873
- memory: settings
1874
- }), "memory"),
1875
- hooks: /* @__PURE__ */ __name((map) => makeBuilder({
1876
- ...config,
1877
- hooks: map
1878
- }), "hooks"),
1879
- plugins: /* @__PURE__ */ __name((list) => makeBuilder({
1880
- ...config,
1881
- plugins: list
1882
- }), "plugins"),
1883
- mcp: /* @__PURE__ */ __name((servers) => makeBuilder({
1884
- ...config,
1885
- mcpServers: servers
1886
- }), "mcp"),
1887
- use: /* @__PURE__ */ __name((preset) => preset(runtime), "use"),
1888
- build: /* @__PURE__ */ __name(() => defineAgent(config), "build")
1889
- };
1890
- return runtime;
1891
- }
1892
- __name(makeBuilder, "makeBuilder");
1893
- var AgentBuilder = {
1894
- /**
1895
- * Start a fluent agent definition. Chain `.model()` (required) + `.context()` / `.system()` /
1896
- * `.input()` / `.tool()` / `.use()`, then `.build()` to get the branded {@link AgentDefinition}.
1897
- */
1898
- create() {
1899
- return makeBuilder({});
1900
- }
1901
- };
1902
-
1903
- // src/bridge/agent-endpoint.ts
1904
- import { TheokitAgentError as TheokitAgentError2 } from "@theokit/sdk/errors";
1905
- var AgentDefinitionError = class extends TheokitAgentError2 {
1906
- static {
1907
- __name(this, "AgentDefinitionError");
1908
- }
1909
- name = "AgentDefinitionError";
1910
- constructor(source) {
1911
- super(`[@theokit/agents] ${source}: an agents/ file must default-export a defineAgent(...) value or an @Agent-decorated class.`, {
1912
- code: "AGENT_DEFINITION_INVALID",
1913
- // a malformed module does not become well-formed by being loaded twice.
1914
- isRetryable: false
1915
- });
1916
- }
1917
- };
1918
- function extractDefaultExport(mod) {
1919
- if (typeof mod === "object" && mod !== null && "default" in mod) {
1920
- return mod.default;
1921
- }
1922
- return mod;
1923
- }
1924
- __name(extractDefaultExport, "extractDefaultExport");
1925
- function isCompiledAgentOptions(value) {
1926
- if (typeof value !== "object" || value === null) return false;
1927
- const v = value;
1928
- return Array.isArray(v.tools) && typeof v.agents === "object" && v.agents !== null;
1929
- }
1930
- __name(isCompiledAgentOptions, "isCompiledAgentOptions");
1931
- function compileAgentModule(mod, source = "agent module") {
1932
- const def = extractDefaultExport(mod);
1933
- if (isAgentDefinition(def)) {
1934
- return compileAgentDefinition(def);
1935
- }
1936
- if (isCompiledAgentOptions(def)) return def;
1937
- throw new AgentDefinitionError(source);
1938
- }
1939
- __name(compileAgentModule, "compileAgentModule");
1940
- async function* asAgentStream(events) {
1941
- for await (const e of events) yield e;
1942
- }
1943
- __name(asAgentStream, "asAgentStream");
1944
- var EventQueue = class EventQueue2 {
1945
- static {
1946
- __name(this, "EventQueue");
1947
- }
1948
- #items = [];
1949
- #resolvers = [];
1950
- #closed = false;
1951
- push(item) {
1952
- if (this.#closed) return;
1953
- const r = this.#resolvers.shift();
1954
- if (r) r({
1955
- value: item,
1956
- done: false
1957
- });
1958
- else this.#items.push(item);
1959
- }
1960
- close() {
1961
- this.#closed = true;
1962
- for (const r of this.#resolvers.splice(0)) r({
1963
- value: void 0,
1964
- done: true
1965
- });
1966
- }
1967
- async *drain() {
1968
- for (; ; ) {
1969
- if (this.#items.length > 0) {
1970
- yield this.#items.shift();
1971
- continue;
1972
- }
1973
- if (this.#closed) return;
1974
- const next = await new Promise((resolve) => this.#resolvers.push(resolve));
1975
- if (next.done) return;
1976
- yield next.value;
1977
- }
1978
- }
1979
- };
1980
- async function* appendCheckpointSaved(source, sessionId) {
1981
- let emitted = false;
1982
- const checkpoint = /* @__PURE__ */ __name(() => ({
1983
- type: "checkpoint_saved",
1984
- checkpointId: crypto.randomUUID(),
1985
- step: 0,
1986
- resumeToken: sessionId
1987
- }), "checkpoint");
1988
- for await (const ev of source) {
1989
- if (ev.type === "done" && !emitted) {
1990
- emitted = true;
1991
- yield checkpoint();
1992
- }
1993
- yield ev;
1994
- }
1995
- if (!emitted) yield checkpoint();
1996
- }
1997
- __name(appendCheckpointSaved, "appendCheckpointSaved");
1998
- function streamAgentUIMessages(compiled, apiKey, input) {
1999
- const textId = crypto.randomUUID();
2000
- const overrides = {};
2001
- if (input.cwd !== void 0) overrides.cwd = input.cwd;
2002
- if (input.baseDir !== void 0) overrides.baseDir = input.baseDir;
2003
- if (input.images !== void 0) overrides.images = input.images;
2004
- if (input.onRunEvent !== void 0) overrides.onRunEvent = input.onRunEvent;
2005
- let source;
2006
- if (!input.hitl || input.hitl.gated.size === 0) {
2007
- const events2 = createSdkAgentStream(compiled, compiled.tools, apiKey, overrides)(input.message, input.sessionId);
2008
- source = asAgentStream(events2);
2009
- } else {
2010
- const queue = new EventQueue();
2011
- input.signal?.addEventListener("abort", () => {
2012
- queue.close();
2013
- }, {
2014
- once: true
2015
- });
2016
- const plugin = createHitlPlugin({
2017
- gated: input.hitl.gated,
2018
- emit: /* @__PURE__ */ __name((e) => {
2019
- queue.push(e);
2020
- }, "emit"),
2021
- awaitApproval: input.hitl.awaitApproval
2022
- });
2023
- const sdkStream = createSdkAgentStream(compiled, compiled.tools, apiKey, {
2024
- ...overrides,
2025
- // The HITL plugin is a structural @theokit/sdk Plugin (createHitlPlugin returns the
2026
- // { name, register } shape); the RuntimeOverrides.plugins union is widened at the SDK edge.
2027
- plugins: [
2028
- plugin
2029
- ]
2030
- })(input.message, input.sessionId);
2031
- void (async () => {
2032
- try {
2033
- for await (const e of sdkStream) queue.push(e);
2034
- } catch (err) {
2035
- queue.push({
2036
- type: "error",
2037
- code: "SDK_STREAM_ERROR",
2038
- message: err instanceof Error ? err.message : String(err),
2039
- retryable: false
2040
- });
2041
- } finally {
2042
- queue.close();
2043
- }
2044
- })();
2045
- source = queue.drain();
2046
- }
2047
- const durableCheckpoint = compiled.checkpoint?.storage === "filesystem";
2048
- const events = durableCheckpoint ? appendCheckpointSaved(source, input.sessionId) : source;
2049
- return presentUIMessageStream(events, {
2050
- textId
2051
- });
2052
- }
2053
- __name(streamAgentUIMessages, "streamAgentUIMessages");
2054
-
2055
1388
  // src/loop/compaction-strategy.ts
2056
1389
  import { compactTranscript } from "@theokit/sdk/compaction";
2057
1390
  import { z } from "zod";
@@ -2158,8 +1491,8 @@ var noopReflectionStrategy = {
2158
1491
  };
2159
1492
 
2160
1493
  // src/bridge/delegation-types.ts
2161
- import { TheokitAgentError as TheokitAgentError3 } from "@theokit/sdk/errors";
2162
- var DelegationBudgetExceededError = class extends TheokitAgentError3 {
1494
+ import { TheokitAgentError as TheokitAgentError2 } from "@theokit/sdk/errors";
1495
+ var DelegationBudgetExceededError = class extends TheokitAgentError2 {
2163
1496
  static {
2164
1497
  __name(this, "DelegationBudgetExceededError");
2165
1498
  }
@@ -2176,7 +1509,7 @@ var DelegationBudgetExceededError = class extends TheokitAgentError3 {
2176
1509
  }
2177
1510
  };
2178
1511
  var BudgetExceededError = DelegationBudgetExceededError;
2179
- var DelegationError = class extends TheokitAgentError3 {
1512
+ var DelegationError = class extends TheokitAgentError2 {
2180
1513
  static {
2181
1514
  __name(this, "DelegationError");
2182
1515
  }
@@ -2764,37 +2097,9 @@ async function delegate(spec, message, opts = {}) {
2764
2097
  }
2765
2098
  __name(delegate, "delegate");
2766
2099
 
2767
- // src/bridge/api-error-handler.ts
2768
- var DEFAULT_MAX_ATTEMPTS = 3;
2769
- async function runWithApiErrorHandling(thunk, policy) {
2770
- const maxAttempts = policy.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;
2771
- let attempt = 0;
2772
- for (; ; ) {
2773
- attempt += 1;
2774
- try {
2775
- return await thunk();
2776
- } catch (error) {
2777
- const decision = await policy.processApiError({
2778
- error,
2779
- attempt
2780
- });
2781
- if (decision.retry && attempt < maxAttempts) continue;
2782
- if (!decision.retry && "fallback" in decision && decision.fallback !== void 0) {
2783
- return decision.fallback;
2784
- }
2785
- throw error;
2786
- }
2787
- }
2788
- }
2789
- __name(runWithApiErrorHandling, "runWithApiErrorHandling");
2790
- function createApiErrorHandler(policy) {
2791
- return (thunk) => runWithApiErrorHandling(thunk, policy);
2792
- }
2793
- __name(createApiErrorHandler, "createApiErrorHandler");
2794
-
2795
2100
  // src/bridge/delegation-lifecycle.ts
2796
- import { TheokitAgentError as TheokitAgentError4 } from "@theokit/sdk/errors";
2797
- var DelegationTimeoutError = class extends TheokitAgentError4 {
2101
+ import { TheokitAgentError as TheokitAgentError3 } from "@theokit/sdk/errors";
2102
+ var DelegationTimeoutError = class extends TheokitAgentError3 {
2798
2103
  static {
2799
2104
  __name(this, "DelegationTimeoutError");
2800
2105
  }
@@ -2841,7 +2146,7 @@ __name(withEphemeralAgent, "withEphemeralAgent");
2841
2146
 
2842
2147
  // src/bridge/delegation-scoring.ts
2843
2148
  function isPort(target) {
2844
- return typeof target.run === "function";
2149
+ return "run" in target;
2845
2150
  }
2846
2151
  __name(isPort, "isPort");
2847
2152
  async function runOnce(target, message, delegateFn, opts) {
@@ -2904,360 +2209,9 @@ async function delegateWithScoring(subAgent, message, opts) {
2904
2209
  }
2905
2210
  __name(delegateWithScoring, "delegateWithScoring");
2906
2211
 
2907
- // src/bridge/mcp-resolver.ts
2908
- async function resolveMcpServers(selection, ctx) {
2909
- if (selection === void 0) return void 0;
2910
- if (typeof selection !== "function") return selection;
2911
- const resolved = await selection(ctx);
2912
- if (typeof resolved !== "object" || resolved === null) {
2913
- throw new Error("[@theokit/agents] MCP resolver must return an McpServersMap object");
2914
- }
2915
- return resolved;
2916
- }
2917
- __name(resolveMcpServers, "resolveMcpServers");
2918
- function mcpRegistry(config) {
2919
- const registry = config.registry;
2920
- if (registry === "composio") {
2921
- const apps = config.apps ?? [];
2922
- return {
2923
- composio: {
2924
- command: "npx",
2925
- args: [
2926
- "-y",
2927
- "@composio/mcp",
2928
- ...apps.length > 0 ? [
2929
- "--apps",
2930
- apps.join(",")
2931
- ] : []
2932
- ],
2933
- env: {
2934
- COMPOSIO_API_KEY: config.apiKey
2935
- }
2936
- }
2937
- };
2938
- }
2939
- if (registry === "mcp.run") {
2940
- return {
2941
- "mcp.run": {
2942
- command: "npx",
2943
- args: [
2944
- "-y",
2945
- "@mcp.run/cli",
2946
- "serve",
2947
- ...config.profile ? [
2948
- "--profile",
2949
- config.profile
2950
- ] : []
2951
- ],
2952
- env: {
2953
- MCP_RUN_API_KEY: config.apiKey
2954
- }
2955
- }
2956
- };
2957
- }
2958
- throw new Error(`mcpRegistry: unknown registry ${JSON.stringify(registry)} (supported: 'composio', 'mcp.run').`);
2959
- }
2960
- __name(mcpRegistry, "mcpRegistry");
2961
- function mcpToolApprovals(specs) {
2962
- const out = {};
2963
- for (const [tool, spec] of Object.entries(specs)) {
2964
- out[tool] = typeof spec === "string" ? {
2965
- question: spec
2966
- } : spec;
2967
- }
2968
- return out;
2969
- }
2970
- __name(mcpToolApprovals, "mcpToolApprovals");
2971
-
2972
- // src/bridge/mcp-file.ts
2973
- import { existsSync, readFileSync } from "fs";
2974
- import { join } from "path";
2975
- import { TheokitAgentError as TheokitAgentError5 } from "@theokit/sdk/errors";
2976
- function warningChannel(opts) {
2977
- return opts.onWarn ?? ((warning) => {
2978
- process.stderr.write(`[@theokit/agents] ${warning}
2979
- `);
2980
- });
2981
- }
2982
- __name(warningChannel, "warningChannel");
2983
- var McpFileError = class extends TheokitAgentError5 {
2984
- static {
2985
- __name(this, "McpFileError");
2986
- }
2987
- name = "McpFileError";
2988
- constructor(message) {
2989
- super(`[@theokit/agents] ${message}`);
2990
- }
2991
- };
2992
- var MCP_FILENAME = ".mcp.json";
2993
- function loadMcpJson(cwd, opts = {}) {
2994
- const path = join(cwd, MCP_FILENAME);
2995
- if (!existsSync(path)) return {};
2996
- let text;
2997
- try {
2998
- text = readFileSync(path, "utf8");
2999
- } catch (err) {
3000
- throw new McpFileError(`failed to read ${path}: ${describeIt(err)}`);
3001
- }
3002
- let parsed;
3003
- try {
3004
- parsed = JSON.parse(text);
3005
- } catch (err) {
3006
- throw new McpFileError(`${path} is not valid JSON: ${describeIt(err)}`);
3007
- }
3008
- return parseMcpJson(parsed, path, warningChannel(opts));
3009
- }
3010
- __name(loadMcpJson, "loadMcpJson");
3011
- function parseMcpJson(raw, source, onWarn) {
3012
- if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
3013
- throw new McpFileError(`${source}: root must be a JSON object with an "mcpServers" key.`);
3014
- }
3015
- const serversRaw = raw.mcpServers;
3016
- if (serversRaw === void 0) return {};
3017
- if (typeof serversRaw !== "object" || serversRaw === null || Array.isArray(serversRaw)) {
3018
- throw new McpFileError(`${source}: "mcpServers" must be an object keyed by server name.`);
3019
- }
3020
- const out = {};
3021
- for (const [name, entryRaw] of Object.entries(serversRaw)) {
3022
- const reason = validateEntry(name, entryRaw);
3023
- if (reason !== void 0) {
3024
- onWarn(`${source}: server "${name}" ignored \u2014 ${reason}`);
3025
- continue;
3026
- }
3027
- out[name] = buildEntry(entryRaw);
3028
- }
3029
- return out;
3030
- }
3031
- __name(parseMcpJson, "parseMcpJson");
3032
- function validateEntry(name, entryRaw) {
3033
- if (typeof entryRaw !== "object" || entryRaw === null || Array.isArray(entryRaw)) {
3034
- return "the entry must be an object.";
3035
- }
3036
- const entry = entryRaw;
3037
- const hasUrl = entry.url !== void 0;
3038
- const hasCommand = entry.command !== void 0;
3039
- if (hasUrl && hasCommand) return 'declares both "command" and "url" \u2014 pick one transport.';
3040
- if (!hasUrl && !hasCommand) return 'requires "command" (stdio) or "url" (http/sse).';
3041
- return hasUrl ? validateRemote(entry) : validateStdio(entry);
3042
- }
3043
- __name(validateEntry, "validateEntry");
3044
- function validateStdio(entry) {
3045
- if (typeof entry.command !== "string" || entry.command.length === 0) {
3046
- return 'field "command" must be a non-empty string.';
3047
- }
3048
- if (entry.args !== void 0 && !isStringArray(entry.args)) return 'field "args" must be an array of strings.';
3049
- if (entry.env !== void 0 && !isStringRecord(entry.env)) return 'field "env" must be a map of strings.';
3050
- if (entry.cwd !== void 0 && typeof entry.cwd !== "string") return 'field "cwd" must be a string.';
3051
- return void 0;
3052
- }
3053
- __name(validateStdio, "validateStdio");
3054
- function validateRemote(entry) {
3055
- if (typeof entry.url !== "string" || entry.url.length === 0) {
3056
- return 'field "url" must be a non-empty string.';
3057
- }
3058
- try {
3059
- new URL(entry.url);
3060
- } catch {
3061
- return 'field "url" is not a valid URL.';
3062
- }
3063
- if (entry.type !== void 0 && entry.type !== "http" && entry.type !== "sse") {
3064
- return 'field "type" must be "http" or "sse".';
3065
- }
3066
- if (entry.headers !== void 0 && !isStringRecord(entry.headers)) {
3067
- return 'field "headers" must be a map of strings.';
3068
- }
3069
- if (entry.requestTimeoutMs !== void 0 && typeof entry.requestTimeoutMs !== "number") {
3070
- return 'field "requestTimeoutMs" must be a number.';
3071
- }
3072
- return void 0;
3073
- }
3074
- __name(validateRemote, "validateRemote");
3075
- function buildEntry(entry) {
3076
- if (entry.url !== void 0) {
3077
- const remote = {
3078
- url: entry.url
3079
- };
3080
- if (entry.type !== void 0) remote.type = entry.type;
3081
- if (entry.headers !== void 0) remote.headers = entry.headers;
3082
- if (entry.auth !== void 0) remote.auth = entry.auth;
3083
- if (entry.requestTimeoutMs !== void 0) remote.requestTimeoutMs = entry.requestTimeoutMs;
3084
- return remote;
3085
- }
3086
- const stdio = {
3087
- command: entry.command
3088
- };
3089
- if (entry.args !== void 0) stdio.args = entry.args;
3090
- if (entry.env !== void 0) stdio.env = entry.env;
3091
- if (entry.cwd !== void 0) stdio.cwd = entry.cwd;
3092
- return stdio;
3093
- }
3094
- __name(buildEntry, "buildEntry");
3095
- function describeIt(err) {
3096
- return err instanceof Error ? err.message : String(err);
3097
- }
3098
- __name(describeIt, "describeIt");
3099
- function isStringArray(v) {
3100
- return Array.isArray(v) && v.every((x) => typeof x === "string");
3101
- }
3102
- __name(isStringArray, "isStringArray");
3103
- function isStringRecord(v) {
3104
- return typeof v === "object" && v !== null && !Array.isArray(v) && Object.values(v).every((x) => typeof x === "string");
3105
- }
3106
- __name(isStringRecord, "isStringRecord");
3107
-
3108
- // src/manifest/agent-manifest.ts
3109
- function generateAgentManifest(sources) {
3110
- return {
3111
- version: "1.0",
3112
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
3113
- agents: sources.map((r) => ({
3114
- name: r.agentConfig.name,
3115
- route: r.route,
3116
- model: r.agentConfig.model,
3117
- stream: r.agentConfig.stream ?? true,
3118
- mainLoop: {
3119
- method: String(r.mainLoop.propertyKey),
3120
- strategy: r.mainLoop.strategy
3121
- },
3122
- guards: r.guards.map((g) => g.name),
3123
- interceptors: r.interceptors.map((i) => i.name),
3124
- tools: r.toolboxes.flatMap((tb) => tb.tools.map((t) => ({
3125
- name: tb.namespace ? `${tb.namespace}.${t.config.name}` : t.config.name,
3126
- description: t.config.description,
3127
- risk: t.config.risk,
3128
- approval: t.approval !== void 0,
3129
- capabilities: t.capabilities,
3130
- trace: t.trace,
3131
- audit: t.audit
3132
- }))),
3133
- gateway: r.gateway ? {
3134
- platforms: r.gateway.platforms,
3135
- sessionStrategy: r.gateway.sessionStrategy ?? "per-user"
3136
- } : void 0,
3137
- subAgents: r.subAgentClasses.map((cls) => cls.name),
3138
- memory: r.memory ? {
3139
- provider: r.memory.provider ?? "built-in",
3140
- embeddings: r.memory.embeddings ?? false,
3141
- fts: r.memory.fts ?? false,
3142
- scope: r.memory.scope ?? "per-user"
3143
- } : void 0,
3144
- skills: r.skills?.include,
3145
- mcpServers: r.mcpServers ? Object.keys(r.mcpServers) : void 0
3146
- }))
3147
- };
3148
- }
3149
- __name(generateAgentManifest, "generateAgentManifest");
3150
-
3151
- // src/theokit-plugin.ts
3152
- function validateUniqueRoutes(results) {
3153
- const seen = /* @__PURE__ */ new Map();
3154
- for (const r of results) {
3155
- const existing = seen.get(r.route);
3156
- if (existing !== void 0) {
3157
- throw new Error(`[@theokit/agents] Duplicate agent route '${r.route}': both '${existing}' and '${r.agentConfig.name}' declare it.`);
3158
- }
3159
- seen.set(r.route, r.agentConfig.name);
3160
- }
3161
- }
3162
- __name(validateUniqueRoutes, "validateUniqueRoutes");
3163
- function agentsPlugin(opts) {
3164
- let routes = null;
3165
- return {
3166
- name: "@theokit/agents",
3167
- register(app) {
3168
- app.addHook("onRequest", async (pluginCtx) => {
3169
- routes ??= initRoutes(opts);
3170
- const request = pluginCtx.request;
3171
- const url = new URL(request.url);
3172
- const method = request.method.toUpperCase();
3173
- const matched = matchRoute(routes, method, url.pathname);
3174
- if (!matched) return;
3175
- return matched.handler(request);
3176
- });
3177
- }
3178
- };
3179
- }
3180
- __name(agentsPlugin, "agentsPlugin");
3181
- function initRoutes(opts) {
3182
- const allRoutes = [];
3183
- const routeIdentities = [];
3184
- for (const entry of opts.agents) {
3185
- routeIdentities.push({
3186
- route: entry.route,
3187
- agentConfig: {
3188
- name: entry.name
3189
- }
3190
- });
3191
- const createRun = opts.createRunFactory ? opts.createRunFactory(entry.compiled) : defaultCreateRun(entry.compiled);
3192
- allRoutes.push(...generateAgentRoutes({
3193
- walkResult: {
3194
- route: entry.route
3195
- },
3196
- compiledOptions: entry.compiled,
3197
- createRun
3198
- }));
3199
- }
3200
- validateUniqueRoutes(routeIdentities);
3201
- return compileRoutePatterns(allRoutes);
3202
- }
3203
- __name(initRoutes, "initRoutes");
3204
- function defaultCreateRun(compiled) {
3205
- return async function* (_message, _sessionId) {
3206
- await Promise.resolve();
3207
- yield {
3208
- type: "run_started",
3209
- runId: `run-${Date.now()}`,
3210
- agentName: compiled.model ?? "unknown"
3211
- };
3212
- yield {
3213
- type: "error",
3214
- code: "SDK_NOT_WIRED",
3215
- message: "No createRunFactory provided \u2014 wire @theokit/sdk Agent.create() to enable real agent execution.",
3216
- retryable: false
3217
- };
3218
- };
3219
- }
3220
- __name(defaultCreateRun, "defaultCreateRun");
3221
- function compileRoutePatterns(routes) {
3222
- return routes.map((r) => {
3223
- if (!r.path.includes(":")) return r;
3224
- const regexSource = r.path.replace(/:[^/]+/g, "[^/]+");
3225
- return {
3226
- ...r,
3227
- regex: RegExp(`^${regexSource}$`)
3228
- };
3229
- });
3230
- }
3231
- __name(compileRoutePatterns, "compileRoutePatterns");
3232
- function matchRoute(routes, method, pathname) {
3233
- return routes.find((r) => {
3234
- if (r.method !== method) return false;
3235
- if (r.regex) return r.regex.test(pathname);
3236
- return r.path === pathname;
3237
- });
3238
- }
3239
- __name(matchRoute, "matchRoute");
3240
-
3241
2212
  export {
3242
- ConfigurationError,
3243
- compileContextWindow,
3244
- compileSkills,
3245
- toolRuntimeName,
3246
- compileHitlGates,
3247
- compileTools,
3248
- createAgentExecutionContext,
3249
- isAgentContext,
3250
2213
  projectContextMetadataOnlyKnobs,
3251
2214
  compileProjectContext,
3252
- streamAgentResponse,
3253
- isTextDelta,
3254
- isToolCall,
3255
- isPartialToolCall,
3256
- isToolResult,
3257
- isDone,
3258
- isError,
3259
- isApprovalRequired,
3260
- generateAgentRoutes,
3261
2215
  GuardrailViolationError,
3262
2216
  CostBudgetExceededError,
3263
2217
  estimateTokens,
@@ -3269,7 +2223,12 @@ export {
3269
2223
  runInputGuards,
3270
2224
  runOutputGuards,
3271
2225
  moderateOutputStream,
2226
+ APPROVAL_MODES,
2227
+ WRITE_SCOPED_TOOLS,
2228
+ shouldAutoApprove,
2229
+ createHitlPlugin,
3272
2230
  createToolHooksPlugin,
2231
+ applyPosture,
3273
2232
  buildModelSelection,
3274
2233
  reasoningEffortOf,
3275
2234
  translateSdkEvent,
@@ -3277,12 +2236,6 @@ export {
3277
2236
  extractThinkTagStream,
3278
2237
  createSdkAgentStream,
3279
2238
  toAgentFactory,
3280
- presentUIMessageStream,
3281
- ContextualTool,
3282
- AgentBuilder,
3283
- AgentDefinitionError,
3284
- compileAgentModule,
3285
- streamAgentUIMessages,
3286
2239
  DEFAULT_KEEP_TOKENS,
3287
2240
  compactionStrategyConfigSchema,
3288
2241
  resolveCompactionStrategy,
@@ -3302,19 +2255,11 @@ export {
3302
2255
  JudgeCredentialError,
3303
2256
  formatGoalEvent,
3304
2257
  delegate,
3305
- runWithApiErrorHandling,
3306
- createApiErrorHandler,
3307
2258
  DelegationTimeoutError,
3308
2259
  withClockCap,
3309
2260
  withEphemeralAgent,
2261
+ isPort,
3310
2262
  delegateBackground,
3311
- delegateWithScoring,
3312
- resolveMcpServers,
3313
- mcpRegistry,
3314
- mcpToolApprovals,
3315
- McpFileError,
3316
- loadMcpJson,
3317
- generateAgentManifest,
3318
- agentsPlugin
2263
+ delegateWithScoring
3319
2264
  };
3320
- //# sourceMappingURL=chunk-RZCNKKOG.js.map
2265
+ //# sourceMappingURL=chunk-CKRM5Q2K.js.map