@theokit/agents 0.46.0 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,50 +1,142 @@
1
- import {
2
- AGENT_CONFIG,
3
- AGENT_MAIN_LOOP,
4
- Audit,
5
- Budget,
6
- RequiresApproval,
7
- TOOLBOX_CONFIG,
8
- TOOL_CONFIG,
9
- TOOL_METHODS,
10
- Trace,
11
- getAgentConfig,
12
- getCheckpointConfig,
13
- getCompactionConfig,
14
- getContextWindowConfig,
15
- getGatewayConfig,
16
- getGuardrailsConfig,
17
- getHumanInTheLoopConfig,
18
- getMcpConfig,
19
- getMemoryConfig,
20
- getMeta,
21
- getMixins,
22
- getProjectContextConfig,
23
- getSkillsConfig,
24
- getSubAgents
25
- } from "./chunk-NERDIS45.js";
26
1
  import {
27
2
  __name
28
3
  } from "./chunk-7QVYU63E.js";
29
4
 
30
- // src/bridge/agent-execution-context.ts
31
- function createAgentExecutionContext(base, agent2, run, toolCall) {
5
+ // src/bridge/define-agent.ts
6
+ var AGENT_BRAND = /* @__PURE__ */ Symbol.for("theokit.agent.definition");
7
+ function defineAgent(config) {
32
8
  return {
33
- getRequest: /* @__PURE__ */ __name(() => base.getRequest(), "getRequest"),
34
- getUrl: /* @__PURE__ */ __name(() => base.getUrl(), "getUrl"),
35
- getClass: /* @__PURE__ */ __name(() => base.getClass(), "getClass"),
36
- getMethodName: /* @__PURE__ */ __name(() => base.getMethodName(), "getMethodName"),
37
- getAgent: /* @__PURE__ */ __name(() => agent2, "getAgent"),
38
- getRun: /* @__PURE__ */ __name(() => run, "getRun"),
39
- getToolCall: /* @__PURE__ */ __name(() => toolCall ?? null, "getToolCall"),
40
- isAgentContext: /* @__PURE__ */ __name(() => true, "isAgentContext")
9
+ ...config,
10
+ [AGENT_BRAND]: true
41
11
  };
42
12
  }
43
- __name(createAgentExecutionContext, "createAgentExecutionContext");
44
- function isAgentContext(ctx) {
45
- return "isAgentContext" in ctx && ctx.isAgentContext();
13
+ __name(defineAgent, "defineAgent");
14
+ function isAgentDefinition(value) {
15
+ return typeof value === "object" && value !== null && value[AGENT_BRAND] === true;
46
16
  }
47
- __name(isAgentContext, "isAgentContext");
17
+ __name(isAgentDefinition, "isAgentDefinition");
18
+ function toCompiledTool(tool) {
19
+ const handler = tool.handler;
20
+ const compiled = {
21
+ name: tool.name,
22
+ description: tool.description,
23
+ inputSchema: tool.inputSchema,
24
+ handler: /* @__PURE__ */ __name((input, ctx) => handler(input, ctx), "handler")
25
+ };
26
+ for (const sym of Object.getOwnPropertySymbols(tool)) {
27
+ ;
28
+ compiled[sym] = tool[sym];
29
+ }
30
+ return compiled;
31
+ }
32
+ __name(toCompiledTool, "toCompiledTool");
33
+ function compileAgentDefinition(def) {
34
+ return {
35
+ model: def.model,
36
+ reasoningEffort: def.reasoningEffort,
37
+ systemPrompt: def.system,
38
+ tools: (def.tools ?? []).map(toCompiledTool),
39
+ agents: {},
40
+ stream: true,
41
+ // M7 — run-context flows to CompiledAgentOptions.runContext (distinct from the
42
+ // context-window `context` field the decorator path uses); absent ⇒ no key.
43
+ ...def.context !== void 0 ? {
44
+ runContext: def.context
45
+ } : {},
46
+ // M9 — guardrails flow through unchanged; the runner applies them at the input boundary.
47
+ ...def.guardrails !== void 0 ? {
48
+ guardrails: def.guardrails
49
+ } : {},
50
+ // M14 — HITL approvals compile into the same `hitl` map the decorator path produces.
51
+ ...def.approvals !== void 0 ? {
52
+ hitl: compileApprovals(def)
53
+ } : {},
54
+ // M13 — skills: a static list → SDK skills.enabled; a resolver → carried for the request path.
55
+ ...compileSkillsSelection(def.skills),
56
+ // theokit-file-based-config — the declared `.theokit/` sources flow to the run path, which
57
+ // projects them into `Agent.create({ local.settingSources })`; absent ⇒ inline config only.
58
+ ...def.settingSources !== void 0 ? {
59
+ settingSources: def.settingSources
60
+ } : {},
61
+ // M49 — memory flows to the projection layer; `assembleM8CreateOptions` forwards it to Agent.create.
62
+ ...def.memory !== void 0 ? {
63
+ memory: def.memory
64
+ } : {},
65
+ // Hooks are converted here — the layer EVERY path converges on — rather than on the builder, so
66
+ // `defineAgent({ hooks })` cannot type-check and silently no-op. A lifecycle hook that is
67
+ // declared but never registered is a security gate that does not gate.
68
+ ...compileHooksAndPlugins(def),
69
+ // MCP — builder/`defineAgent` servers converge on the same `mcpServers` field the `@MCP`
70
+ // decorator path populates; the SDK adapter forwards it to `Agent.create({ mcpServers })`.
71
+ ...def.mcpServers !== void 0 ? {
72
+ mcpServers: def.mcpServers
73
+ } : {}
74
+ };
75
+ }
76
+ __name(compileAgentDefinition, "compileAgentDefinition");
77
+ function compileHooksAndPlugins(def) {
78
+ const map = def.hooks;
79
+ const entries = Object.entries(map ?? {}).filter(([, h]) => typeof h === "function");
80
+ const explicit = def.plugins ?? [];
81
+ if (entries.length === 0) {
82
+ return def.plugins !== void 0 ? {
83
+ plugins: def.plugins
84
+ } : {};
85
+ }
86
+ const plugin = {
87
+ name: "theokit-builder-hooks",
88
+ version: "1.0.0",
89
+ kind: "general",
90
+ register(ctx) {
91
+ for (const [hookName, handler] of entries) {
92
+ ctx.on(hookName, handler);
93
+ }
94
+ }
95
+ };
96
+ return {
97
+ plugins: [
98
+ ...explicit,
99
+ plugin
100
+ ]
101
+ };
102
+ }
103
+ __name(compileHooksAndPlugins, "compileHooksAndPlugins");
104
+ function compileSkillsSelection(skills) {
105
+ if (skills === void 0) return {};
106
+ if (typeof skills === "function") return {
107
+ skillsResolver: skills
108
+ };
109
+ const enabled = [];
110
+ const inline = [];
111
+ for (const entry of skills) {
112
+ if (typeof entry === "string") enabled.push(entry);
113
+ else inline.push(entry);
114
+ }
115
+ return {
116
+ skills: {
117
+ enabled,
118
+ autoInject: true,
119
+ ...inline.length > 0 ? {
120
+ inline
121
+ } : {}
122
+ }
123
+ };
124
+ }
125
+ __name(compileSkillsSelection, "compileSkillsSelection");
126
+ function compileApprovals(def) {
127
+ const toolNames = new Set((def.tools ?? []).map((t) => t.name));
128
+ const gates = /* @__PURE__ */ new Map();
129
+ for (const [toolName, options] of Object.entries(def.approvals ?? {})) {
130
+ if (!toolNames.has(toolName)) {
131
+ throw new Error(`[@theokit/agents] defineAgent approval references unknown tool "${toolName}". Declared tools: ${[
132
+ ...toolNames
133
+ ].join(", ") || "(none)"}.`);
134
+ }
135
+ gates.set(toolName, options);
136
+ }
137
+ return gates;
138
+ }
139
+ __name(compileApprovals, "compileApprovals");
48
140
 
49
141
  // src/bridge/compile-context-window.ts
50
142
  var STRATEGY_KNOBS = [
@@ -67,198 +159,6 @@ function compileContextWindow(options) {
67
159
  }
68
160
  __name(compileContextWindow, "compileContextWindow");
69
161
 
70
- // src/bridge/compile-project-context.ts
71
- var UNMAPPED_KNOBS = [
72
- "indexStrategy",
73
- "relevanceStrategy",
74
- "maxFilesInContext",
75
- "includeExtensions",
76
- "rootMarkers"
77
- ];
78
- function projectContextMetadataOnlyKnobs(options) {
79
- const opts = options;
80
- return UNMAPPED_KNOBS.filter((knob) => opts[knob] !== void 0);
81
- }
82
- __name(projectContextMetadataOnlyKnobs, "projectContextMetadataOnlyKnobs");
83
- function compileProjectContext(options, base) {
84
- return async (promptCtx) => {
85
- const resolvedBase = typeof base === "function" ? await base(promptCtx) : base;
86
- const cwd = promptCtx.cwd;
87
- if (!cwd) {
88
- return resolvedBase ?? "";
89
- }
90
- const { buildEnvContext, buildRepoMap } = await import("@theokit/sdk-tools");
91
- const { readProjectInstructions } = await import("@theokit/sdk/project");
92
- const env = buildEnvContext(cwd);
93
- const repoMap = buildRepoMap(cwd, {
94
- ignore: options.ignorePatterns
95
- });
96
- let instructions = "";
97
- try {
98
- instructions = (await readProjectInstructions(cwd)).content ?? "";
99
- } catch {
100
- instructions = "";
101
- }
102
- return [
103
- env,
104
- repoMap,
105
- instructions,
106
- resolvedBase
107
- ].filter(Boolean).join("\n\n");
108
- };
109
- }
110
- __name(compileProjectContext, "compileProjectContext");
111
-
112
- // src/bridge/walk-agent-metadata.ts
113
- import "reflect-metadata";
114
- import { Reflector } from "@theokit/http";
115
- var USE_GUARDS = /* @__PURE__ */ Symbol.for("theokit:http-decorators:use-guards");
116
- var USE_INTERCEPTORS = /* @__PURE__ */ Symbol.for("theokit:http-decorators:use-interceptors");
117
- var USE_FILTERS = /* @__PURE__ */ Symbol.for("theokit:http-decorators:use-filters");
118
- var AgentWarningCode = {
119
- INTERCEPTOR_METADATA_ONLY: "THEO_AGENT_INTERCEPTOR_METADATA_ONLY",
120
- FILTER_METADATA_ONLY: "THEO_AGENT_FILTER_METADATA_ONLY",
121
- BUDGET_TOP_LEVEL_METADATA_ONLY: "THEO_AGENT_BUDGET_TOP_LEVEL_METADATA_ONLY",
122
- CONTEXT_STRATEGY_METADATA_ONLY: "THEO_AGENT_CONTEXT_STRATEGY_METADATA_ONLY",
123
- PROJECT_CONTEXT_KNOB_METADATA_ONLY: "THEO_AGENT_PROJECT_CONTEXT_KNOB_METADATA_ONLY",
124
- CHECKPOINT_STORAGE_METADATA_ONLY: "THEO_AGENT_CHECKPOINT_STORAGE_METADATA_ONLY"
125
- };
126
- var reflectorInstance = new Reflector();
127
- function walkToolbox(ToolboxClass) {
128
- const config = getMeta(TOOLBOX_CONFIG, ToolboxClass) ?? {};
129
- const methods = getMeta(TOOL_METHODS, ToolboxClass) ?? [];
130
- const classGuards = getMeta(USE_GUARDS, ToolboxClass) ?? [];
131
- const tools = methods.map((propertyKey) => {
132
- const toolConfig = getMeta(TOOL_CONFIG, ToolboxClass, propertyKey);
133
- if (!toolConfig) {
134
- throw new Error(`[@theokit/agents] Toolbox ${ToolboxClass.name}: method '${String(propertyKey)}' is in TOOL_METHODS but has no @Tool() config.`);
135
- }
136
- const methodGuards = getMeta(USE_GUARDS, ToolboxClass, propertyKey) ?? [];
137
- const ref = reflectorInstance;
138
- const approvalVal = ref.get(RequiresApproval, ToolboxClass, propertyKey);
139
- const traceVal = ref.get(Trace, ToolboxClass, propertyKey);
140
- const auditVal = ref.get(Audit, ToolboxClass, propertyKey);
141
- return {
142
- propertyKey,
143
- config: toolConfig,
144
- guards: [
145
- ...classGuards,
146
- ...methodGuards
147
- ],
148
- approval: approvalVal && typeof approvalVal === "object" && "reason" in approvalVal ? approvalVal : void 0,
149
- capabilities: void 0,
150
- budget: void 0,
151
- trace: traceVal ?? false,
152
- audit: auditVal ?? false,
153
- hitl: getHumanInTheLoopConfig(ToolboxClass, propertyKey)
154
- };
155
- });
156
- return {
157
- class: ToolboxClass,
158
- namespace: config.namespace ?? "",
159
- tools,
160
- guards: classGuards
161
- };
162
- }
163
- __name(walkToolbox, "walkToolbox");
164
- function warnUnmappedDecoratorKnobs(agentName, contextWindow, projectContext) {
165
- if (contextWindow) {
166
- const { metadataOnlyKnobs } = compileContextWindow(contextWindow);
167
- if (metadataOnlyKnobs.length > 0) {
168
- console.warn(`[${AgentWarningCode.CONTEXT_STRATEGY_METADATA_ONLY}] Agent ${agentName}: @ContextWindow knob(s) ${metadataOnlyKnobs.join(", ")} are metadata-only \u2014 the SDK manages transcript compaction internally. Only maxTokens is forwarded to Agent.create({ context }).`);
169
- }
170
- }
171
- if (projectContext) {
172
- const unmapped = projectContextMetadataOnlyKnobs(projectContext);
173
- if (unmapped.length > 0) {
174
- console.warn(`[${AgentWarningCode.PROJECT_CONTEXT_KNOB_METADATA_ONLY}] Agent ${agentName}: @ProjectContext knob(s) ${unmapped.join(", ")} are metadata-only \u2014 the repo map is composed via buildRepoMap/buildEnvContext/readProjectInstructions; only ignorePatterns is forwarded.`);
175
- }
176
- }
177
- }
178
- __name(warnUnmappedDecoratorKnobs, "warnUnmappedDecoratorKnobs");
179
- function warnNonDurableCheckpoint(agentName, checkpoint) {
180
- if (checkpoint && checkpoint.storage !== "filesystem") {
181
- console.warn(`[${AgentWarningCode.CHECKPOINT_STORAGE_METADATA_ONLY}] Agent ${agentName}: @Checkpoint({ storage: '${checkpoint.storage ?? "memory"}' }) does NOT resume across requests \u2014 only 'filesystem' selects the SDK's durable conversation store. Use @Checkpoint({ storage: 'filesystem' }) for cross-request resume.`);
182
- }
183
- }
184
- __name(warnNonDurableCheckpoint, "warnNonDurableCheckpoint");
185
- var agentWalkCache = /* @__PURE__ */ new WeakMap();
186
- function walkAgentMetadata(AgentClass, toolboxClasses = []) {
187
- if (toolboxClasses.length === 0) {
188
- const cached = agentWalkCache.get(AgentClass);
189
- if (cached) return cached;
190
- }
191
- const agentConfig = getMeta(AGENT_CONFIG, AgentClass);
192
- if (!agentConfig) {
193
- throw new Error(`[@theokit/agents] Class ${AgentClass.name} is missing @Agent() decorator.`);
194
- }
195
- const mainLoop = getMeta(AGENT_MAIN_LOOP, AgentClass);
196
- if (!mainLoop) {
197
- throw new Error(`[@theokit/agents] Agent ${AgentClass.name} is missing @MainLoop() decorator. Decorate exactly one method with @MainLoop().`);
198
- }
199
- const guards = getMeta(USE_GUARDS, AgentClass) ?? [];
200
- const interceptors = getMeta(USE_INTERCEPTORS, AgentClass) ?? [];
201
- if (interceptors.length > 0) {
202
- console.warn(`[${AgentWarningCode.INTERCEPTOR_METADATA_ONLY}] Agent ${AgentClass.name}: @UseInterceptors is metadata-only on agents and will not execute. Agent pipeline shares guards with HTTP but uses a distinct execution model. Interceptors are reserved for future agent-specific lifecycle hooks.`);
203
- }
204
- const filters = getMeta(USE_FILTERS, AgentClass) ?? [];
205
- if (filters.length > 0) {
206
- console.warn(`[${AgentWarningCode.FILTER_METADATA_ONLY}] Agent ${AgentClass.name}: @UseFilters is metadata-only on agents and will not catch agent runtime errors. Agent errors flow through SSE error events, not HTTP exception filters. Filters are reserved for future agent-specific error handling.`);
207
- }
208
- const agentBudget = reflectorInstance.get(Budget, AgentClass);
209
- if (agentBudget) {
210
- console.warn(`[${AgentWarningCode.BUDGET_TOP_LEVEL_METADATA_ONLY}] Agent ${AgentClass.name}: @Budget on top-level agents is metadata-only in this version. Budget enforcement currently applies to delegate() calls only. Top-level run enforcement will be wired through SDK cost tracking in a future release.`);
211
- }
212
- const toolboxes = toolboxClasses.map(walkToolbox);
213
- const gateway = getGatewayConfig(AgentClass);
214
- const subAgentClasses = getSubAgents(AgentClass);
215
- const memory = getMemoryConfig(AgentClass);
216
- const skills = getSkillsConfig(AgentClass);
217
- const mcpServers = getMcpConfig(AgentClass);
218
- const guardrails = getGuardrailsConfig(AgentClass);
219
- const contextWindow = getContextWindowConfig(AgentClass);
220
- const projectContext = getProjectContextConfig(AgentClass);
221
- warnUnmappedDecoratorKnobs(AgentClass.name, contextWindow, projectContext);
222
- const compaction = getCompactionConfig(AgentClass);
223
- const checkpoint = getCheckpointConfig(AgentClass);
224
- warnNonDurableCheckpoint(AgentClass.name, checkpoint);
225
- const result = {
226
- agentConfig,
227
- mainLoop,
228
- toolboxes,
229
- guards,
230
- interceptors,
231
- filters,
232
- route: agentConfig.route,
233
- gateway,
234
- subAgentClasses,
235
- memory,
236
- skills,
237
- contextWindow,
238
- projectContext,
239
- mcpServers,
240
- guardrails,
241
- compaction,
242
- checkpoint
243
- };
244
- if (toolboxClasses.length === 0) {
245
- agentWalkCache.set(AgentClass, result);
246
- }
247
- return result;
248
- }
249
- __name(walkAgentMetadata, "walkAgentMetadata");
250
- function validateUniqueRoutes(results) {
251
- const seen = /* @__PURE__ */ new Map();
252
- for (const r of results) {
253
- const existing = seen.get(r.route);
254
- if (existing) {
255
- throw new Error(`[@theokit/agents] Duplicate agent route '${r.route}': both '${existing}' and '${r.agentConfig.name}' declare it.`);
256
- }
257
- seen.set(r.route, r.agentConfig.name);
258
- }
259
- }
260
- __name(validateUniqueRoutes, "validateUniqueRoutes");
261
-
262
162
  // src/bridge/compile-skills.ts
263
163
  function compileSkills(options) {
264
164
  if (options.autoDiscover) {
@@ -278,18 +178,6 @@ function toolRuntimeName(namespace, toolName) {
278
178
  return namespace ? `${namespace}.${toolName}` : toolName;
279
179
  }
280
180
  __name(toolRuntimeName, "toolRuntimeName");
281
- function compileHitlGates(toolboxes) {
282
- const gates = /* @__PURE__ */ new Map();
283
- for (const tb of toolboxes) {
284
- for (const tool of tb.tools) {
285
- if (tool.hitl) {
286
- gates.set(toolRuntimeName(tb.namespace, tool.config.name), tool.hitl);
287
- }
288
- }
289
- }
290
- return gates;
291
- }
292
- __name(compileHitlGates, "compileHitlGates");
293
181
  function compileTools(toolboxes, toolboxInstances) {
294
182
  const tools = [];
295
183
  for (const tb of toolboxes) {
@@ -314,46 +202,67 @@ function compileTools(toolboxes, toolboxInstances) {
314
202
  return tools;
315
203
  }
316
204
  __name(compileTools, "compileTools");
317
- function compileSubAgents(subAgentClasses) {
318
- const agents = {};
319
- for (const cls of subAgentClasses) {
320
- const config = getAgentConfig(cls);
321
- if (!config) continue;
322
- agents[config.name] = {
323
- model: config.model,
324
- systemPrompt: config.systemPrompt
325
- };
326
- }
327
- return agents;
328
- }
329
- __name(compileSubAgents, "compileSubAgents");
330
- function compileAgent(walkResult, toolboxInstances = /* @__PURE__ */ new Map()) {
331
- const tools = compileTools(walkResult.toolboxes, toolboxInstances);
332
- const agents = compileSubAgents(walkResult.subAgentClasses);
333
- const hitl = compileHitlGates(walkResult.toolboxes);
205
+
206
+ // src/bridge/agent-execution-context.ts
207
+ function createAgentExecutionContext(base, agent2, run, toolCall) {
334
208
  return {
335
- model: walkResult.agentConfig.model,
336
- reasoningEffort: walkResult.agentConfig.reasoningEffort,
337
- parseThinkTags: walkResult.agentConfig.parseThinkTags,
338
- stripToolDialect: walkResult.agentConfig.stripToolDialect,
339
- recoverLeakedToolCalls: walkResult.agentConfig.recoverLeakedToolCalls,
340
- systemPrompt: walkResult.agentConfig.systemPrompt,
341
- tools,
342
- agents,
343
- memory: walkResult.memory,
344
- skills: walkResult.skills ? compileSkills(walkResult.skills) : void 0,
345
- context: walkResult.contextWindow ? compileContextWindow(walkResult.contextWindow).context : void 0,
346
- projectContext: walkResult.projectContext,
347
- mcpServers: walkResult.mcpServers,
348
- guardrails: walkResult.guardrails,
349
- maxIterations: walkResult.mainLoop.maxIterations ?? walkResult.agentConfig.maxIterations,
350
- timeoutMs: walkResult.mainLoop.timeoutMs ?? walkResult.agentConfig.timeoutMs,
351
- stream: walkResult.agentConfig.stream ?? true,
352
- hitl: hitl.size > 0 ? hitl : void 0,
353
- checkpoint: walkResult.checkpoint
209
+ getRequest: /* @__PURE__ */ __name(() => base.getRequest(), "getRequest"),
210
+ getUrl: /* @__PURE__ */ __name(() => base.getUrl(), "getUrl"),
211
+ getClass: /* @__PURE__ */ __name(() => base.getClass(), "getClass"),
212
+ getMethodName: /* @__PURE__ */ __name(() => base.getMethodName(), "getMethodName"),
213
+ getAgent: /* @__PURE__ */ __name(() => agent2, "getAgent"),
214
+ getRun: /* @__PURE__ */ __name(() => run, "getRun"),
215
+ getToolCall: /* @__PURE__ */ __name(() => toolCall ?? null, "getToolCall"),
216
+ isAgentContext: /* @__PURE__ */ __name(() => true, "isAgentContext")
217
+ };
218
+ }
219
+ __name(createAgentExecutionContext, "createAgentExecutionContext");
220
+ function isAgentContext(ctx) {
221
+ return "isAgentContext" in ctx && ctx.isAgentContext();
222
+ }
223
+ __name(isAgentContext, "isAgentContext");
224
+
225
+ // src/bridge/compile-project-context.ts
226
+ var UNMAPPED_KNOBS = [
227
+ "indexStrategy",
228
+ "relevanceStrategy",
229
+ "maxFilesInContext",
230
+ "includeExtensions",
231
+ "rootMarkers"
232
+ ];
233
+ function projectContextMetadataOnlyKnobs(options) {
234
+ const opts = options;
235
+ return UNMAPPED_KNOBS.filter((knob) => opts[knob] !== void 0);
236
+ }
237
+ __name(projectContextMetadataOnlyKnobs, "projectContextMetadataOnlyKnobs");
238
+ function compileProjectContext(options, base) {
239
+ return async (promptCtx) => {
240
+ const resolvedBase = typeof base === "function" ? await base(promptCtx) : base;
241
+ const cwd = promptCtx.cwd;
242
+ if (!cwd) {
243
+ return resolvedBase ?? "";
244
+ }
245
+ const { buildEnvContext, buildRepoMap } = await import("@theokit/sdk-tools");
246
+ const { readProjectInstructions } = await import("@theokit/sdk/project");
247
+ const env = buildEnvContext(cwd);
248
+ const repoMap = buildRepoMap(cwd, {
249
+ ignore: options.ignorePatterns
250
+ });
251
+ let instructions = "";
252
+ try {
253
+ instructions = (await readProjectInstructions(cwd)).content ?? "";
254
+ } catch {
255
+ instructions = "";
256
+ }
257
+ return [
258
+ env,
259
+ repoMap,
260
+ instructions,
261
+ resolvedBase
262
+ ].filter(Boolean).join("\n\n");
354
263
  };
355
264
  }
356
- __name(compileAgent, "compileAgent");
265
+ __name(compileProjectContext, "compileProjectContext");
357
266
 
358
267
  // src/bridge/agent-sse-handler.ts
359
268
  var encoder = new TextEncoder();
@@ -506,142 +415,6 @@ function generateAgentRoutes(ctx) {
506
415
  }
507
416
  __name(generateAgentRoutes, "generateAgentRoutes");
508
417
 
509
- // src/bridge/define-agent.ts
510
- var AGENT_BRAND = /* @__PURE__ */ Symbol.for("theokit.agent.definition");
511
- function defineAgent(config) {
512
- return {
513
- ...config,
514
- [AGENT_BRAND]: true
515
- };
516
- }
517
- __name(defineAgent, "defineAgent");
518
- function isAgentDefinition(value) {
519
- return typeof value === "object" && value !== null && value[AGENT_BRAND] === true;
520
- }
521
- __name(isAgentDefinition, "isAgentDefinition");
522
- function toCompiledTool(tool) {
523
- const handler = tool.handler;
524
- const compiled = {
525
- name: tool.name,
526
- description: tool.description,
527
- inputSchema: tool.inputSchema,
528
- handler: /* @__PURE__ */ __name((input, ctx) => handler(input, ctx), "handler")
529
- };
530
- for (const sym of Object.getOwnPropertySymbols(tool)) {
531
- ;
532
- compiled[sym] = tool[sym];
533
- }
534
- return compiled;
535
- }
536
- __name(toCompiledTool, "toCompiledTool");
537
- function compileAgentDefinition(def) {
538
- return {
539
- model: def.model,
540
- reasoningEffort: def.reasoningEffort,
541
- systemPrompt: def.system,
542
- tools: (def.tools ?? []).map(toCompiledTool),
543
- agents: {},
544
- stream: true,
545
- // M7 — run-context flows to CompiledAgentOptions.runContext (distinct from the
546
- // context-window `context` field the decorator path uses); absent ⇒ no key.
547
- ...def.context !== void 0 ? {
548
- runContext: def.context
549
- } : {},
550
- // M9 — guardrails flow through unchanged; the runner applies them at the input boundary.
551
- ...def.guardrails !== void 0 ? {
552
- guardrails: def.guardrails
553
- } : {},
554
- // M14 — HITL approvals compile into the same `hitl` map the decorator path produces.
555
- ...def.approvals !== void 0 ? {
556
- hitl: compileApprovals(def)
557
- } : {},
558
- // M13 — skills: a static list → SDK skills.enabled; a resolver → carried for the request path.
559
- ...compileSkillsSelection(def.skills),
560
- // theokit-file-based-config — the declared `.theokit/` sources flow to the run path, which
561
- // projects them into `Agent.create({ local.settingSources })`; absent ⇒ inline config only.
562
- ...def.settingSources !== void 0 ? {
563
- settingSources: def.settingSources
564
- } : {},
565
- // M49 — memory flows to the projection layer; `assembleM8CreateOptions` forwards it to Agent.create.
566
- ...def.memory !== void 0 ? {
567
- memory: def.memory
568
- } : {},
569
- // Hooks are converted here — the layer EVERY path converges on — rather than on the builder, so
570
- // `defineAgent({ hooks })` cannot type-check and silently no-op. A lifecycle hook that is
571
- // declared but never registered is a security gate that does not gate.
572
- ...compileHooksAndPlugins(def),
573
- // MCP — builder/`defineAgent` servers converge on the same `mcpServers` field the `@MCP`
574
- // decorator path populates; the SDK adapter forwards it to `Agent.create({ mcpServers })`.
575
- ...def.mcpServers !== void 0 ? {
576
- mcpServers: def.mcpServers
577
- } : {}
578
- };
579
- }
580
- __name(compileAgentDefinition, "compileAgentDefinition");
581
- function compileHooksAndPlugins(def) {
582
- const map = def.hooks;
583
- const entries = Object.entries(map ?? {}).filter(([, h]) => typeof h === "function");
584
- const explicit = def.plugins ?? [];
585
- if (entries.length === 0) {
586
- return def.plugins !== void 0 ? {
587
- plugins: def.plugins
588
- } : {};
589
- }
590
- const plugin = {
591
- name: "theokit-builder-hooks",
592
- version: "1.0.0",
593
- kind: "general",
594
- register(ctx) {
595
- for (const [hookName, handler] of entries) {
596
- ctx.on(hookName, handler);
597
- }
598
- }
599
- };
600
- return {
601
- plugins: [
602
- ...explicit,
603
- plugin
604
- ]
605
- };
606
- }
607
- __name(compileHooksAndPlugins, "compileHooksAndPlugins");
608
- function compileSkillsSelection(skills) {
609
- if (skills === void 0) return {};
610
- if (typeof skills === "function") return {
611
- skillsResolver: skills
612
- };
613
- const enabled = [];
614
- const inline = [];
615
- for (const entry of skills) {
616
- if (typeof entry === "string") enabled.push(entry);
617
- else inline.push(entry);
618
- }
619
- return {
620
- skills: {
621
- enabled,
622
- autoInject: true,
623
- ...inline.length > 0 ? {
624
- inline
625
- } : {}
626
- }
627
- };
628
- }
629
- __name(compileSkillsSelection, "compileSkillsSelection");
630
- function compileApprovals(def) {
631
- const toolNames = new Set((def.tools ?? []).map((t) => t.name));
632
- const gates = /* @__PURE__ */ new Map();
633
- for (const [toolName, options] of Object.entries(def.approvals ?? {})) {
634
- if (!toolNames.has(toolName)) {
635
- throw new Error(`[@theokit/agents] defineAgent approval references unknown tool "${toolName}". Declared tools: ${[
636
- ...toolNames
637
- ].join(", ") || "(none)"}.`);
638
- }
639
- gates.set(toolName, options);
640
- }
641
- return gates;
642
- }
643
- __name(compileApprovals, "compileApprovals");
644
-
645
418
  // src/bridge/event-translator.ts
646
419
  function asString(value, fallback) {
647
420
  if (typeof value === "string") return value;
@@ -1152,9 +925,12 @@ function buildExtraCreateOptions(overrides, compiled) {
1152
925
  const recoverLeakedToolCalls = overrides.recoverLeakedToolCalls ?? compiled.recoverLeakedToolCalls ?? false;
1153
926
  const extra = {};
1154
927
  if (overrides.plugins !== void 0) {
1155
- extra.plugins = Array.isArray(overrides.plugins) && Array.isArray(compiled.plugins) ? [
1156
- ...compiled.plugins,
1157
- ...overrides.plugins
928
+ const asArray = /* @__PURE__ */ __name((v) => Array.isArray(v) ? v : void 0, "asArray");
929
+ const overrideList = asArray(overrides.plugins);
930
+ const compiledList = asArray(compiled.plugins);
931
+ extra.plugins = overrideList !== void 0 && compiledList !== void 0 ? [
932
+ ...compiledList,
933
+ ...overrideList
1158
934
  ] : overrides.plugins;
1159
935
  }
1160
936
  if (overrides.providers !== void 0) {
@@ -1353,7 +1129,7 @@ function createSdkAgentStream(compiled, compiledTools, apiKey, overrides = {}) {
1353
1129
  const reasoningEffort = overrides.reasoningEffort ?? compiled.reasoningEffort;
1354
1130
  const { parseThinkTags, stripToolDialect } = resolveTextTransformFlags(compiled, overrides);
1355
1131
  const runContext = overrides.runContext ?? compiled.runContext;
1356
- return (message, sessionId, factoryOpts) => ({
1132
+ const factory = /* @__PURE__ */ __name((message, sessionId, factoryOpts) => ({
1357
1133
  async *[Symbol.asyncIterator]() {
1358
1134
  const runId = `run-${Date.now()}`;
1359
1135
  const t0 = Date.now();
@@ -1407,6 +1183,9 @@ function createSdkAgentStream(compiled, compiledTools, apiKey, overrides = {}) {
1407
1183
  };
1408
1184
  }
1409
1185
  }
1186
+ }), "factory");
1187
+ return Object.assign(factory, {
1188
+ resolvedModel: model
1410
1189
  });
1411
1190
  }
1412
1191
  __name(createSdkAgentStream, "createSdkAgentStream");
@@ -1904,6 +1683,125 @@ var UIMessageStreamPresenter = class {
1904
1683
  return out;
1905
1684
  }
1906
1685
  };
1686
+ var ANSI = {
1687
+ text: "",
1688
+ reasoning: "\x1B[2m",
1689
+ tool: "\x1B[36m",
1690
+ "tool-result": "\x1B[2m",
1691
+ "tool-error": "\x1B[31m",
1692
+ error: "\x1B[31m",
1693
+ status: "\x1B[35m",
1694
+ finish: "\x1B[2m"
1695
+ };
1696
+ var RESET = "\x1B[0m";
1697
+ function preview(value, max) {
1698
+ const raw = typeof value === "string" ? value : safeJson(value);
1699
+ const flat = raw.replace(/\s+/g, " ").trim();
1700
+ return flat.length > max ? `${flat.slice(0, max - 1)}\u2026` : flat;
1701
+ }
1702
+ __name(preview, "preview");
1703
+ __name2(preview, "preview");
1704
+ function safeJson(value) {
1705
+ if (value === void 0 || value === null) return "";
1706
+ try {
1707
+ return JSON.stringify(value);
1708
+ } catch {
1709
+ return typeof value === "bigint" ? value.toString() : "";
1710
+ }
1711
+ }
1712
+ __name(safeJson, "safeJson");
1713
+ __name2(safeJson, "safeJson");
1714
+ function suffix(open, value, close) {
1715
+ return value === void 0 ? "" : open + value + close;
1716
+ }
1717
+ __name(suffix, "suffix");
1718
+ __name2(suffix, "suffix");
1719
+ var TerminalPresenter = class {
1720
+ static {
1721
+ __name(this, "TerminalPresenter");
1722
+ }
1723
+ static {
1724
+ __name2(this, "TerminalPresenter");
1725
+ }
1726
+ surface = "terminal";
1727
+ #ansi;
1728
+ #max;
1729
+ constructor(options = {}) {
1730
+ this.#ansi = options.ansi ?? false;
1731
+ this.#max = options.maxPreview ?? 88;
1732
+ }
1733
+ present(event) {
1734
+ switch (event.type) {
1735
+ case "text":
1736
+ return event.text.length > 0 ? [
1737
+ this.#row("text", event.text)
1738
+ ] : [];
1739
+ case "reasoning":
1740
+ return event.text.length > 0 ? [
1741
+ this.#row("reasoning", `\xB7 ${event.text}`)
1742
+ ] : [];
1743
+ case "tool-call":
1744
+ return [
1745
+ this.#row("tool", `\u23FA ${event.name}(${preview(event.input, this.#max)})`)
1746
+ ];
1747
+ case "tool-result":
1748
+ return [
1749
+ this.#toolResult(event.isError === true, preview(event.result, this.#max))
1750
+ ];
1751
+ case "error":
1752
+ return [
1753
+ this.#row("error", `\u2716 ${event.message}${suffix(" (", event.code, ")")}`)
1754
+ ];
1755
+ case "status":
1756
+ return [
1757
+ this.#row("status", `\u25CF ${event.status}${suffix(" \u2014 ", event.detail, "")}`)
1758
+ ];
1759
+ case "finish":
1760
+ return [
1761
+ this.#row("finish", this.#finishText(event.reason, event.usage?.totalTokens))
1762
+ ];
1763
+ // `partial-tool-call` streams incremental args — the committed `tool-call` renders them.
1764
+ default:
1765
+ return [];
1766
+ }
1767
+ }
1768
+ #toolResult(isError2, body) {
1769
+ return this.#row(isError2 ? "tool-error" : "tool-result", ` \u23BF ${body}`);
1770
+ }
1771
+ #finishText(reason, tokens) {
1772
+ const r = suffix(" ", reason, "");
1773
+ const t = tokens === void 0 ? "" : ` \xB7 ${tokens} tokens`;
1774
+ return `<<${r}${t} >>`;
1775
+ }
1776
+ #row(kind, text) {
1777
+ return {
1778
+ kind,
1779
+ text: this.#ansi && ANSI[kind] !== "" ? `${ANSI[kind]}${text}${RESET}` : text
1780
+ };
1781
+ }
1782
+ };
1783
+ var JsonPresenter = class {
1784
+ static {
1785
+ __name(this, "JsonPresenter");
1786
+ }
1787
+ static {
1788
+ __name2(this, "JsonPresenter");
1789
+ }
1790
+ surface = "json";
1791
+ #ns;
1792
+ constructor(options = {}) {
1793
+ this.#ns = options.namespace ?? "agent.";
1794
+ }
1795
+ present(event) {
1796
+ const { type, ...payload } = event;
1797
+ return [
1798
+ {
1799
+ type: `${this.#ns}${type}`,
1800
+ ...payload
1801
+ }
1802
+ ];
1803
+ }
1804
+ };
1907
1805
 
1908
1806
  // src/bridge/present-ui-message-stream.ts
1909
1807
  function toAgentOutputEvent(e) {
@@ -2172,19 +2070,18 @@ function extractDefaultExport(mod) {
2172
2070
  return mod;
2173
2071
  }
2174
2072
  __name(extractDefaultExport, "extractDefaultExport");
2073
+ function isCompiledAgentOptions(value) {
2074
+ if (typeof value !== "object" || value === null) return false;
2075
+ const v = value;
2076
+ return Array.isArray(v.tools) && typeof v.agents === "object" && v.agents !== null;
2077
+ }
2078
+ __name(isCompiledAgentOptions, "isCompiledAgentOptions");
2175
2079
  function compileAgentModule(mod, source = "agent module") {
2176
2080
  const def = extractDefaultExport(mod);
2177
2081
  if (isAgentDefinition(def)) {
2178
2082
  return compileAgentDefinition(def);
2179
2083
  }
2180
- if (typeof def === "function" && getAgentConfig(def) !== void 0) {
2181
- const walk = walkAgentMetadata(def, getMixins(def));
2182
- const instances = /* @__PURE__ */ new Map();
2183
- for (const tb of walk.toolboxes) {
2184
- instances.set(tb.class, new tb.class());
2185
- }
2186
- return compileAgent(walk, instances);
2187
- }
2084
+ if (isCompiledAgentOptions(def)) return def;
2188
2085
  throw new AgentDefinitionError(source);
2189
2086
  }
2190
2087
  __name(compileAgentModule, "compileAgentModule");
@@ -2258,12 +2155,16 @@ function streamAgentUIMessages(compiled, apiKey, input) {
2258
2155
  source = asAgentStream(events2);
2259
2156
  } else {
2260
2157
  const queue = new EventQueue();
2261
- input.signal?.addEventListener("abort", () => queue.close(), {
2158
+ input.signal?.addEventListener("abort", () => {
2159
+ queue.close();
2160
+ }, {
2262
2161
  once: true
2263
2162
  });
2264
2163
  const plugin = createHitlPlugin({
2265
2164
  gated: input.hitl.gated,
2266
- emit: /* @__PURE__ */ __name((e) => queue.push(e), "emit"),
2165
+ emit: /* @__PURE__ */ __name((e) => {
2166
+ queue.push(e);
2167
+ }, "emit"),
2267
2168
  awaitApproval: input.hitl.awaitApproval
2268
2169
  });
2269
2170
  const sdkStream = createSdkAgentStream(compiled, compiled.tools, apiKey, {
@@ -2901,9 +2802,9 @@ var AgentRunner = class {
2901
2802
  this.streamEnabled = state.streamEnabled;
2902
2803
  this.compaction = state.compaction;
2903
2804
  }
2904
- /** Start a fluent builder for `AgentClass`. */
2905
- static builder(AgentClass) {
2906
- return new AgentRunnerBuilder(AgentClass);
2805
+ /** Start a fluent builder from an already-compiled spec. */
2806
+ static fromSpec(spec) {
2807
+ return new AgentRunnerBuilder(spec);
2907
2808
  }
2908
2809
  /**
2909
2810
  * V4-D-stream: stream the agent's events LIVE across the reflective loop, returning
@@ -2965,12 +2866,12 @@ var AgentRunnerBuilder = class {
2965
2866
  static {
2966
2867
  __name(this, "AgentRunnerBuilder");
2967
2868
  }
2968
- AgentClass;
2869
+ spec;
2969
2870
  reflectionOverride;
2970
2871
  streamEnabled = true;
2971
2872
  compactionOverride;
2972
- constructor(AgentClass) {
2973
- this.AgentClass = AgentClass;
2873
+ constructor(spec) {
2874
+ this.spec = spec;
2974
2875
  }
2975
2876
  /** Override the default reflection strategy (OCP — plan Drawback #2). No arg ⇒ keep default. */
2976
2877
  reflection(strategy) {
@@ -2994,23 +2895,19 @@ var AgentRunnerBuilder = class {
2994
2895
  };
2995
2896
  return this;
2996
2897
  }
2997
- /** Walk + compile + resolve strategies — the compile→execute boundary (no I/O). */
2898
+ /** Resolve strategies from the spec — the compile→execute boundary (no I/O). */
2998
2899
  build() {
2999
- const walk = walkAgentMetadata(this.AgentClass, []);
3000
- const toolboxInstances = new Map(walk.toolboxes.map((tb) => [
3001
- tb.class,
3002
- new tb.class()
3003
- ]));
3004
- const compiled = compileAgent(walk, toolboxInstances);
3005
- const loopStrategy = resolveLoopStrategy(walk.mainLoop.strategy, walk.mainLoop.maxIterations);
3006
- const reflectionStrategy = this.reflectionOverride ?? (walk.mainLoop.strategy === "plan-act-reflect" ? ladderReflectionStrategy : noopReflectionStrategy);
3007
- const compactionDecl = this.compactionOverride ?? walk.compaction;
2900
+ const { spec } = this;
2901
+ const strategy = spec.strategy ?? "simple-chat";
2902
+ const loopStrategy = resolveLoopStrategy(strategy, spec.maxIterations);
2903
+ const reflectionStrategy = this.reflectionOverride ?? (strategy === "plan-act-reflect" ? ladderReflectionStrategy : noopReflectionStrategy);
2904
+ const compactionDecl = this.compactionOverride ?? spec.compaction;
3008
2905
  const compaction = compactionDecl ? resolveCompactionStrategy(compactionDecl.name, {
3009
2906
  keepTokens: compactionDecl.keepTokens
3010
2907
  }) : void 0;
3011
2908
  return new AgentRunner({
3012
- compiled,
3013
- agentName: walk.agentConfig.name,
2909
+ compiled: spec.compiled,
2910
+ agentName: spec.name,
3014
2911
  loopStrategy,
3015
2912
  reflectionStrategy,
3016
2913
  streamEnabled: this.streamEnabled,
@@ -3037,22 +2934,17 @@ function mergeTools(parentTools, subTools) {
3037
2934
  ];
3038
2935
  }
3039
2936
  __name(mergeTools, "mergeTools");
3040
- async function delegate(SubAgentClass, message, opts = {}) {
3041
- const apiKey = requireApiKey(opts, SubAgentClass.name);
2937
+ async function delegate(spec, message, opts = {}) {
2938
+ const apiKey = requireApiKey(opts, spec.name);
3042
2939
  const effectiveMessage = opts.onDelegationStart ? await opts.onDelegationStart({
3043
- subAgent: SubAgentClass.name,
2940
+ subAgent: spec.name,
3044
2941
  input: message
3045
2942
  }) : message;
3046
- const walk = walkAgentMetadata(SubAgentClass, []);
3047
- const toolboxInstances = new Map(walk.toolboxes.map((tb) => [
3048
- tb.class,
3049
- new tb.class()
3050
- ]));
3051
- const compiled = compileAgent(walk, toolboxInstances);
2943
+ const { compiled } = spec;
3052
2944
  const allTools = mergeTools(opts.parentTools ?? [], compiled.tools);
3053
2945
  const budget = Math.min(opts.budget ?? Infinity, opts.parentBudgetRemaining ?? Infinity);
3054
2946
  const streamFactory = opts.streamFactory ?? createSdkAgentStream(compiled, allTools, apiKey, {
3055
- model: opts.model ?? walk.agentConfig.model,
2947
+ model: opts.model ?? compiled.model,
3056
2948
  cwd: opts.cwd,
3057
2949
  plugins: opts.plugins,
3058
2950
  providers: opts.providers,
@@ -3061,19 +2953,19 @@ async function delegate(SubAgentClass, message, opts = {}) {
3061
2953
  sdkTools: opts.sdkTools
3062
2954
  });
3063
2955
  const sessionId = opts.sessionId ?? `sub-${crypto.randomUUID()}`;
3064
- const loopStrategy = resolveLoopStrategy(walk.mainLoop.strategy, opts.maxIterations ?? walk.mainLoop.maxIterations);
2956
+ const loopStrategy = resolveLoopStrategy(spec.strategy ?? "simple-chat", opts.maxIterations ?? spec.maxIterations);
3065
2957
  const reflection = opts.reflection ?? (loopStrategy.name === "plan-act-reflect" ? ladderReflectionStrategy : noopReflectionStrategy);
3066
2958
  const result = await runReflectiveLoop(streamFactory, effectiveMessage, sessionId, {
3067
2959
  loop: loopStrategy,
3068
2960
  reflection,
3069
2961
  budget,
3070
- agentName: SubAgentClass.name,
2962
+ agentName: spec.name,
3071
2963
  signal: opts.signal,
3072
2964
  retry: opts.retry
3073
2965
  });
3074
2966
  if (opts.onDelegationComplete) {
3075
2967
  return await opts.onDelegationComplete({
3076
- subAgent: SubAgentClass.name,
2968
+ subAgent: spec.name,
3077
2969
  result
3078
2970
  });
3079
2971
  }
@@ -3204,6 +3096,9 @@ async function delegateWithScoring(subAgent, message, opts) {
3204
3096
  }
3205
3097
  if (verdict.feedback) currentMessage = feedbackTemplate(message, verdict.feedback);
3206
3098
  }
3099
+ if (lastResult === void 0) {
3100
+ throw new Error("[@theokit/agents] delegateWithScoring: no round ran (maxRounds < 1)");
3101
+ }
3207
3102
  return {
3208
3103
  result: lastResult,
3209
3104
  rounds: maxRounds,
@@ -3279,11 +3174,11 @@ function mcpToolApprovals(specs) {
3279
3174
  __name(mcpToolApprovals, "mcpToolApprovals");
3280
3175
 
3281
3176
  // src/manifest/agent-manifest.ts
3282
- function generateAgentManifest(walkResults) {
3177
+ function generateAgentManifest(sources) {
3283
3178
  return {
3284
3179
  version: "1.0",
3285
3180
  generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
3286
- agents: walkResults.map((r) => ({
3181
+ agents: sources.map((r) => ({
3287
3182
  name: r.agentConfig.name,
3288
3183
  route: r.route,
3289
3184
  model: r.agentConfig.model,
@@ -3322,7 +3217,17 @@ function generateAgentManifest(walkResults) {
3322
3217
  __name(generateAgentManifest, "generateAgentManifest");
3323
3218
 
3324
3219
  // src/theokit-plugin.ts
3325
- import "reflect-metadata";
3220
+ function validateUniqueRoutes(results) {
3221
+ const seen = /* @__PURE__ */ new Map();
3222
+ for (const r of results) {
3223
+ const existing = seen.get(r.route);
3224
+ if (existing !== void 0) {
3225
+ throw new Error(`[@theokit/agents] Duplicate agent route '${r.route}': both '${existing}' and '${r.agentConfig.name}' declare it.`);
3226
+ }
3227
+ seen.set(r.route, r.agentConfig.name);
3228
+ }
3229
+ }
3230
+ __name(validateUniqueRoutes, "validateUniqueRoutes");
3326
3231
  function agentsPlugin(opts) {
3327
3232
  let routes = null;
3328
3233
  return {
@@ -3343,25 +3248,24 @@ function agentsPlugin(opts) {
3343
3248
  __name(agentsPlugin, "agentsPlugin");
3344
3249
  function initRoutes(opts) {
3345
3250
  const allRoutes = [];
3346
- const walkResults = [];
3347
- for (const AgentClass of opts.agents) {
3348
- const mixins = getMixins(AgentClass);
3349
- const toolboxes = [
3350
- ...opts.toolboxes ?? [],
3351
- ...mixins
3352
- ];
3353
- const walkResult = walkAgentMetadata(AgentClass, toolboxes);
3354
- walkResults.push(walkResult);
3355
- const compiled = compileAgent(walkResult, /* @__PURE__ */ new Map());
3356
- const createRun = opts.createRunFactory ? opts.createRunFactory(compiled, walkResult) : defaultCreateRun(compiled);
3357
- const agentRoutes = generateAgentRoutes({
3358
- walkResult,
3359
- compiledOptions: compiled,
3360
- createRun
3251
+ const routeIdentities = [];
3252
+ for (const entry of opts.agents) {
3253
+ routeIdentities.push({
3254
+ route: entry.route,
3255
+ agentConfig: {
3256
+ name: entry.name
3257
+ }
3361
3258
  });
3362
- allRoutes.push(...agentRoutes);
3259
+ const createRun = opts.createRunFactory ? opts.createRunFactory(entry.compiled) : defaultCreateRun(entry.compiled);
3260
+ allRoutes.push(...generateAgentRoutes({
3261
+ walkResult: {
3262
+ route: entry.route
3263
+ },
3264
+ compiledOptions: entry.compiled,
3265
+ createRun
3266
+ }));
3363
3267
  }
3364
- validateUniqueRoutes(walkResults);
3268
+ validateUniqueRoutes(routeIdentities);
3365
3269
  return compileRoutePatterns(allRoutes);
3366
3270
  }
3367
3271
  __name(initRoutes, "initRoutes");
@@ -3403,17 +3307,17 @@ function matchRoute(routes, method, pathname) {
3403
3307
  __name(matchRoute, "matchRoute");
3404
3308
 
3405
3309
  export {
3310
+ AGENT_BRAND,
3311
+ isAgentDefinition,
3312
+ compileAgentDefinition,
3313
+ compileSkillsSelection,
3314
+ compileContextWindow,
3315
+ compileSkills,
3316
+ compileTools,
3406
3317
  createAgentExecutionContext,
3407
3318
  isAgentContext,
3408
- compileContextWindow,
3409
3319
  projectContextMetadataOnlyKnobs,
3410
3320
  compileProjectContext,
3411
- AgentWarningCode,
3412
- walkAgentMetadata,
3413
- validateUniqueRoutes,
3414
- compileSkills,
3415
- compileTools,
3416
- compileAgent,
3417
3321
  streamAgentResponse,
3418
3322
  isTextDelta,
3419
3323
  isToolCall,
@@ -3423,9 +3327,6 @@ export {
3423
3327
  isError,
3424
3328
  isApprovalRequired,
3425
3329
  generateAgentRoutes,
3426
- AGENT_BRAND,
3427
- isAgentDefinition,
3428
- compileAgentDefinition,
3429
3330
  translateSdkEvent,
3430
3331
  buildModelSelection,
3431
3332
  createThinkTagExtractor,
@@ -3475,4 +3376,4 @@ export {
3475
3376
  generateAgentManifest,
3476
3377
  agentsPlugin
3477
3378
  };
3478
- //# sourceMappingURL=chunk-YBNKD5UM.js.map
3379
+ //# sourceMappingURL=chunk-7KRJJX7W.js.map