@theokit/agents 0.47.0 → 1.0.1

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,28 +1,3 @@
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";
@@ -163,25 +138,6 @@ function compileApprovals(def) {
163
138
  }
164
139
  __name(compileApprovals, "compileApprovals");
165
140
 
166
- // src/bridge/agent-execution-context.ts
167
- function createAgentExecutionContext(base, agent2, run, toolCall) {
168
- return {
169
- getRequest: /* @__PURE__ */ __name(() => base.getRequest(), "getRequest"),
170
- getUrl: /* @__PURE__ */ __name(() => base.getUrl(), "getUrl"),
171
- getClass: /* @__PURE__ */ __name(() => base.getClass(), "getClass"),
172
- getMethodName: /* @__PURE__ */ __name(() => base.getMethodName(), "getMethodName"),
173
- getAgent: /* @__PURE__ */ __name(() => agent2, "getAgent"),
174
- getRun: /* @__PURE__ */ __name(() => run, "getRun"),
175
- getToolCall: /* @__PURE__ */ __name(() => toolCall ?? null, "getToolCall"),
176
- isAgentContext: /* @__PURE__ */ __name(() => true, "isAgentContext")
177
- };
178
- }
179
- __name(createAgentExecutionContext, "createAgentExecutionContext");
180
- function isAgentContext(ctx) {
181
- return "isAgentContext" in ctx && ctx.isAgentContext();
182
- }
183
- __name(isAgentContext, "isAgentContext");
184
-
185
141
  // src/bridge/compile-context-window.ts
186
142
  var STRATEGY_KNOBS = [
187
143
  "compactionStrategy",
@@ -203,198 +159,6 @@ function compileContextWindow(options) {
203
159
  }
204
160
  __name(compileContextWindow, "compileContextWindow");
205
161
 
206
- // src/bridge/compile-project-context.ts
207
- var UNMAPPED_KNOBS = [
208
- "indexStrategy",
209
- "relevanceStrategy",
210
- "maxFilesInContext",
211
- "includeExtensions",
212
- "rootMarkers"
213
- ];
214
- function projectContextMetadataOnlyKnobs(options) {
215
- const opts = options;
216
- return UNMAPPED_KNOBS.filter((knob) => opts[knob] !== void 0);
217
- }
218
- __name(projectContextMetadataOnlyKnobs, "projectContextMetadataOnlyKnobs");
219
- function compileProjectContext(options, base) {
220
- return async (promptCtx) => {
221
- const resolvedBase = typeof base === "function" ? await base(promptCtx) : base;
222
- const cwd = promptCtx.cwd;
223
- if (!cwd) {
224
- return resolvedBase ?? "";
225
- }
226
- const { buildEnvContext, buildRepoMap } = await import("@theokit/sdk-tools");
227
- const { readProjectInstructions } = await import("@theokit/sdk/project");
228
- const env = buildEnvContext(cwd);
229
- const repoMap = buildRepoMap(cwd, {
230
- ignore: options.ignorePatterns
231
- });
232
- let instructions = "";
233
- try {
234
- instructions = (await readProjectInstructions(cwd)).content ?? "";
235
- } catch {
236
- instructions = "";
237
- }
238
- return [
239
- env,
240
- repoMap,
241
- instructions,
242
- resolvedBase
243
- ].filter(Boolean).join("\n\n");
244
- };
245
- }
246
- __name(compileProjectContext, "compileProjectContext");
247
-
248
- // src/bridge/walk-agent-metadata.ts
249
- import "reflect-metadata";
250
- import { Reflector } from "@theokit/http";
251
- var USE_GUARDS = /* @__PURE__ */ Symbol.for("theokit:http-decorators:use-guards");
252
- var USE_INTERCEPTORS = /* @__PURE__ */ Symbol.for("theokit:http-decorators:use-interceptors");
253
- var USE_FILTERS = /* @__PURE__ */ Symbol.for("theokit:http-decorators:use-filters");
254
- var AgentWarningCode = {
255
- INTERCEPTOR_METADATA_ONLY: "THEO_AGENT_INTERCEPTOR_METADATA_ONLY",
256
- FILTER_METADATA_ONLY: "THEO_AGENT_FILTER_METADATA_ONLY",
257
- BUDGET_TOP_LEVEL_METADATA_ONLY: "THEO_AGENT_BUDGET_TOP_LEVEL_METADATA_ONLY",
258
- CONTEXT_STRATEGY_METADATA_ONLY: "THEO_AGENT_CONTEXT_STRATEGY_METADATA_ONLY",
259
- PROJECT_CONTEXT_KNOB_METADATA_ONLY: "THEO_AGENT_PROJECT_CONTEXT_KNOB_METADATA_ONLY",
260
- CHECKPOINT_STORAGE_METADATA_ONLY: "THEO_AGENT_CHECKPOINT_STORAGE_METADATA_ONLY"
261
- };
262
- var reflectorInstance = new Reflector();
263
- function walkToolbox(ToolboxClass) {
264
- const config = getMeta(TOOLBOX_CONFIG, ToolboxClass) ?? {};
265
- const methods = getMeta(TOOL_METHODS, ToolboxClass) ?? [];
266
- const classGuards = getMeta(USE_GUARDS, ToolboxClass) ?? [];
267
- const tools = methods.map((propertyKey) => {
268
- const toolConfig = getMeta(TOOL_CONFIG, ToolboxClass, propertyKey);
269
- if (!toolConfig) {
270
- throw new Error(`[@theokit/agents] Toolbox ${ToolboxClass.name}: method '${String(propertyKey)}' is in TOOL_METHODS but has no @Tool() config.`);
271
- }
272
- const methodGuards = getMeta(USE_GUARDS, ToolboxClass, propertyKey) ?? [];
273
- const ref = reflectorInstance;
274
- const approvalVal = ref.get(RequiresApproval, ToolboxClass, propertyKey);
275
- const traceVal = ref.get(Trace, ToolboxClass, propertyKey);
276
- const auditVal = ref.get(Audit, ToolboxClass, propertyKey);
277
- return {
278
- propertyKey,
279
- config: toolConfig,
280
- guards: [
281
- ...classGuards,
282
- ...methodGuards
283
- ],
284
- approval: approvalVal && typeof approvalVal === "object" && "reason" in approvalVal ? approvalVal : void 0,
285
- capabilities: void 0,
286
- budget: void 0,
287
- trace: traceVal ?? false,
288
- audit: auditVal ?? false,
289
- hitl: getHumanInTheLoopConfig(ToolboxClass, propertyKey)
290
- };
291
- });
292
- return {
293
- class: ToolboxClass,
294
- namespace: config.namespace ?? "",
295
- tools,
296
- guards: classGuards
297
- };
298
- }
299
- __name(walkToolbox, "walkToolbox");
300
- function warnUnmappedDecoratorKnobs(agentName, contextWindow, projectContext) {
301
- if (contextWindow) {
302
- const { metadataOnlyKnobs } = compileContextWindow(contextWindow);
303
- if (metadataOnlyKnobs.length > 0) {
304
- 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 }).`);
305
- }
306
- }
307
- if (projectContext) {
308
- const unmapped = projectContextMetadataOnlyKnobs(projectContext);
309
- if (unmapped.length > 0) {
310
- 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.`);
311
- }
312
- }
313
- }
314
- __name(warnUnmappedDecoratorKnobs, "warnUnmappedDecoratorKnobs");
315
- function warnNonDurableCheckpoint(agentName, checkpoint) {
316
- if (checkpoint && checkpoint.storage !== "filesystem") {
317
- 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.`);
318
- }
319
- }
320
- __name(warnNonDurableCheckpoint, "warnNonDurableCheckpoint");
321
- var agentWalkCache = /* @__PURE__ */ new WeakMap();
322
- function walkAgentMetadata(AgentClass, toolboxClasses = []) {
323
- if (toolboxClasses.length === 0) {
324
- const cached = agentWalkCache.get(AgentClass);
325
- if (cached) return cached;
326
- }
327
- const agentConfig = getMeta(AGENT_CONFIG, AgentClass);
328
- if (!agentConfig) {
329
- throw new Error(`[@theokit/agents] Class ${AgentClass.name} is missing @Agent() decorator.`);
330
- }
331
- const mainLoop = getMeta(AGENT_MAIN_LOOP, AgentClass);
332
- if (!mainLoop) {
333
- throw new Error(`[@theokit/agents] Agent ${AgentClass.name} is missing @MainLoop() decorator. Decorate exactly one method with @MainLoop().`);
334
- }
335
- const guards = getMeta(USE_GUARDS, AgentClass) ?? [];
336
- const interceptors = getMeta(USE_INTERCEPTORS, AgentClass) ?? [];
337
- if (interceptors.length > 0) {
338
- 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.`);
339
- }
340
- const filters = getMeta(USE_FILTERS, AgentClass) ?? [];
341
- if (filters.length > 0) {
342
- 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.`);
343
- }
344
- const agentBudget = reflectorInstance.get(Budget, AgentClass);
345
- if (agentBudget) {
346
- 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.`);
347
- }
348
- const toolboxes = toolboxClasses.map(walkToolbox);
349
- const gateway = getGatewayConfig(AgentClass);
350
- const subAgentClasses = getSubAgents(AgentClass);
351
- const memory = getMemoryConfig(AgentClass);
352
- const skills = getSkillsConfig(AgentClass);
353
- const mcpServers = getMcpConfig(AgentClass);
354
- const guardrails = getGuardrailsConfig(AgentClass);
355
- const contextWindow = getContextWindowConfig(AgentClass);
356
- const projectContext = getProjectContextConfig(AgentClass);
357
- warnUnmappedDecoratorKnobs(AgentClass.name, contextWindow, projectContext);
358
- const compaction = getCompactionConfig(AgentClass);
359
- const checkpoint = getCheckpointConfig(AgentClass);
360
- warnNonDurableCheckpoint(AgentClass.name, checkpoint);
361
- const result = {
362
- agentConfig,
363
- mainLoop,
364
- toolboxes,
365
- guards,
366
- interceptors,
367
- filters,
368
- route: agentConfig.route,
369
- gateway,
370
- subAgentClasses,
371
- memory,
372
- skills,
373
- contextWindow,
374
- projectContext,
375
- mcpServers,
376
- guardrails,
377
- compaction,
378
- checkpoint
379
- };
380
- if (toolboxClasses.length === 0) {
381
- agentWalkCache.set(AgentClass, result);
382
- }
383
- return result;
384
- }
385
- __name(walkAgentMetadata, "walkAgentMetadata");
386
- function validateUniqueRoutes(results) {
387
- const seen = /* @__PURE__ */ new Map();
388
- for (const r of results) {
389
- const existing = seen.get(r.route);
390
- if (existing) {
391
- throw new Error(`[@theokit/agents] Duplicate agent route '${r.route}': both '${existing}' and '${r.agentConfig.name}' declare it.`);
392
- }
393
- seen.set(r.route, r.agentConfig.name);
394
- }
395
- }
396
- __name(validateUniqueRoutes, "validateUniqueRoutes");
397
-
398
162
  // src/bridge/compile-skills.ts
399
163
  function compileSkills(options) {
400
164
  if (options.autoDiscover) {
@@ -410,22 +174,11 @@ function compileSkills(options) {
410
174
  __name(compileSkills, "compileSkills");
411
175
 
412
176
  // src/bridge/agent-compiler.ts
177
+ var SDK_TOOL_NAME = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
413
178
  function toolRuntimeName(namespace, toolName) {
414
- return namespace ? `${namespace}.${toolName}` : toolName;
179
+ return namespace ? `${namespace}_${toolName}` : toolName;
415
180
  }
416
181
  __name(toolRuntimeName, "toolRuntimeName");
417
- function compileHitlGates(toolboxes) {
418
- const gates = /* @__PURE__ */ new Map();
419
- for (const tb of toolboxes) {
420
- for (const tool of tb.tools) {
421
- if (tool.hitl) {
422
- gates.set(toolRuntimeName(tb.namespace, tool.config.name), tool.hitl);
423
- }
424
- }
425
- }
426
- return gates;
427
- }
428
- __name(compileHitlGates, "compileHitlGates");
429
182
  function compileTools(toolboxes, toolboxInstances) {
430
183
  const tools = [];
431
184
  for (const tb of toolboxes) {
@@ -450,46 +203,67 @@ function compileTools(toolboxes, toolboxInstances) {
450
203
  return tools;
451
204
  }
452
205
  __name(compileTools, "compileTools");
453
- function compileSubAgents(subAgentClasses) {
454
- const agents = {};
455
- for (const cls of subAgentClasses) {
456
- const config = getAgentConfig(cls);
457
- if (!config) continue;
458
- agents[config.name] = {
459
- model: config.model,
460
- systemPrompt: config.systemPrompt
461
- };
462
- }
463
- return agents;
464
- }
465
- __name(compileSubAgents, "compileSubAgents");
466
- function compileAgent(walkResult, toolboxInstances = /* @__PURE__ */ new Map()) {
467
- const tools = compileTools(walkResult.toolboxes, toolboxInstances);
468
- const agents = compileSubAgents(walkResult.subAgentClasses);
469
- const hitl = compileHitlGates(walkResult.toolboxes);
206
+
207
+ // src/bridge/agent-execution-context.ts
208
+ function createAgentExecutionContext(base, agent2, run, toolCall) {
470
209
  return {
471
- model: walkResult.agentConfig.model,
472
- reasoningEffort: walkResult.agentConfig.reasoningEffort,
473
- parseThinkTags: walkResult.agentConfig.parseThinkTags,
474
- stripToolDialect: walkResult.agentConfig.stripToolDialect,
475
- recoverLeakedToolCalls: walkResult.agentConfig.recoverLeakedToolCalls,
476
- systemPrompt: walkResult.agentConfig.systemPrompt,
477
- tools,
478
- agents,
479
- memory: walkResult.memory,
480
- skills: walkResult.skills ? compileSkills(walkResult.skills) : void 0,
481
- context: walkResult.contextWindow ? compileContextWindow(walkResult.contextWindow).context : void 0,
482
- projectContext: walkResult.projectContext,
483
- mcpServers: walkResult.mcpServers,
484
- guardrails: walkResult.guardrails,
485
- maxIterations: walkResult.mainLoop.maxIterations ?? walkResult.agentConfig.maxIterations,
486
- timeoutMs: walkResult.mainLoop.timeoutMs ?? walkResult.agentConfig.timeoutMs,
487
- stream: walkResult.agentConfig.stream ?? true,
488
- hitl: hitl.size > 0 ? hitl : void 0,
489
- checkpoint: walkResult.checkpoint
210
+ getRequest: /* @__PURE__ */ __name(() => base.getRequest(), "getRequest"),
211
+ getUrl: /* @__PURE__ */ __name(() => base.getUrl(), "getUrl"),
212
+ getClass: /* @__PURE__ */ __name(() => base.getClass(), "getClass"),
213
+ getMethodName: /* @__PURE__ */ __name(() => base.getMethodName(), "getMethodName"),
214
+ getAgent: /* @__PURE__ */ __name(() => agent2, "getAgent"),
215
+ getRun: /* @__PURE__ */ __name(() => run, "getRun"),
216
+ getToolCall: /* @__PURE__ */ __name(() => toolCall ?? null, "getToolCall"),
217
+ isAgentContext: /* @__PURE__ */ __name(() => true, "isAgentContext")
218
+ };
219
+ }
220
+ __name(createAgentExecutionContext, "createAgentExecutionContext");
221
+ function isAgentContext(ctx) {
222
+ return "isAgentContext" in ctx && ctx.isAgentContext();
223
+ }
224
+ __name(isAgentContext, "isAgentContext");
225
+
226
+ // src/bridge/compile-project-context.ts
227
+ var UNMAPPED_KNOBS = [
228
+ "indexStrategy",
229
+ "relevanceStrategy",
230
+ "maxFilesInContext",
231
+ "includeExtensions",
232
+ "rootMarkers"
233
+ ];
234
+ function projectContextMetadataOnlyKnobs(options) {
235
+ const opts = options;
236
+ return UNMAPPED_KNOBS.filter((knob) => opts[knob] !== void 0);
237
+ }
238
+ __name(projectContextMetadataOnlyKnobs, "projectContextMetadataOnlyKnobs");
239
+ function compileProjectContext(options, base) {
240
+ return async (promptCtx) => {
241
+ const resolvedBase = typeof base === "function" ? await base(promptCtx) : base;
242
+ const cwd = promptCtx.cwd;
243
+ if (!cwd) {
244
+ return resolvedBase ?? "";
245
+ }
246
+ const { buildEnvContext, buildRepoMap } = await import("@theokit/sdk-tools");
247
+ const { readProjectInstructions } = await import("@theokit/sdk/project");
248
+ const env = buildEnvContext(cwd);
249
+ const repoMap = buildRepoMap(cwd, {
250
+ ignore: options.ignorePatterns
251
+ });
252
+ let instructions = "";
253
+ try {
254
+ instructions = (await readProjectInstructions(cwd)).content ?? "";
255
+ } catch {
256
+ instructions = "";
257
+ }
258
+ return [
259
+ env,
260
+ repoMap,
261
+ instructions,
262
+ resolvedBase
263
+ ].filter(Boolean).join("\n\n");
490
264
  };
491
265
  }
492
- __name(compileAgent, "compileAgent");
266
+ __name(compileProjectContext, "compileProjectContext");
493
267
 
494
268
  // src/bridge/agent-sse-handler.ts
495
269
  var encoder = new TextEncoder();
@@ -1152,9 +926,12 @@ function buildExtraCreateOptions(overrides, compiled) {
1152
926
  const recoverLeakedToolCalls = overrides.recoverLeakedToolCalls ?? compiled.recoverLeakedToolCalls ?? false;
1153
927
  const extra = {};
1154
928
  if (overrides.plugins !== void 0) {
1155
- extra.plugins = Array.isArray(overrides.plugins) && Array.isArray(compiled.plugins) ? [
1156
- ...compiled.plugins,
1157
- ...overrides.plugins
929
+ const asArray = /* @__PURE__ */ __name((v) => Array.isArray(v) ? v : void 0, "asArray");
930
+ const overrideList = asArray(overrides.plugins);
931
+ const compiledList = asArray(compiled.plugins);
932
+ extra.plugins = overrideList !== void 0 && compiledList !== void 0 ? [
933
+ ...compiledList,
934
+ ...overrideList
1158
935
  ] : overrides.plugins;
1159
936
  }
1160
937
  if (overrides.providers !== void 0) {
@@ -1353,7 +1130,7 @@ function createSdkAgentStream(compiled, compiledTools, apiKey, overrides = {}) {
1353
1130
  const reasoningEffort = overrides.reasoningEffort ?? compiled.reasoningEffort;
1354
1131
  const { parseThinkTags, stripToolDialect } = resolveTextTransformFlags(compiled, overrides);
1355
1132
  const runContext = overrides.runContext ?? compiled.runContext;
1356
- return (message, sessionId, factoryOpts) => ({
1133
+ const factory = /* @__PURE__ */ __name((message, sessionId, factoryOpts) => ({
1357
1134
  async *[Symbol.asyncIterator]() {
1358
1135
  const runId = `run-${Date.now()}`;
1359
1136
  const t0 = Date.now();
@@ -1407,6 +1184,9 @@ function createSdkAgentStream(compiled, compiledTools, apiKey, overrides = {}) {
1407
1184
  };
1408
1185
  }
1409
1186
  }
1187
+ }), "factory");
1188
+ return Object.assign(factory, {
1189
+ resolvedModel: model
1410
1190
  });
1411
1191
  }
1412
1192
  __name(createSdkAgentStream, "createSdkAgentStream");
@@ -2291,19 +2071,18 @@ function extractDefaultExport(mod) {
2291
2071
  return mod;
2292
2072
  }
2293
2073
  __name(extractDefaultExport, "extractDefaultExport");
2074
+ function isCompiledAgentOptions(value) {
2075
+ if (typeof value !== "object" || value === null) return false;
2076
+ const v = value;
2077
+ return Array.isArray(v.tools) && typeof v.agents === "object" && v.agents !== null;
2078
+ }
2079
+ __name(isCompiledAgentOptions, "isCompiledAgentOptions");
2294
2080
  function compileAgentModule(mod, source = "agent module") {
2295
2081
  const def = extractDefaultExport(mod);
2296
2082
  if (isAgentDefinition(def)) {
2297
2083
  return compileAgentDefinition(def);
2298
2084
  }
2299
- if (typeof def === "function" && getAgentConfig(def) !== void 0) {
2300
- const walk = walkAgentMetadata(def, getMixins(def));
2301
- const instances = /* @__PURE__ */ new Map();
2302
- for (const tb of walk.toolboxes) {
2303
- instances.set(tb.class, new tb.class());
2304
- }
2305
- return compileAgent(walk, instances);
2306
- }
2085
+ if (isCompiledAgentOptions(def)) return def;
2307
2086
  throw new AgentDefinitionError(source);
2308
2087
  }
2309
2088
  __name(compileAgentModule, "compileAgentModule");
@@ -2377,12 +2156,16 @@ function streamAgentUIMessages(compiled, apiKey, input) {
2377
2156
  source = asAgentStream(events2);
2378
2157
  } else {
2379
2158
  const queue = new EventQueue();
2380
- input.signal?.addEventListener("abort", () => queue.close(), {
2159
+ input.signal?.addEventListener("abort", () => {
2160
+ queue.close();
2161
+ }, {
2381
2162
  once: true
2382
2163
  });
2383
2164
  const plugin = createHitlPlugin({
2384
2165
  gated: input.hitl.gated,
2385
- emit: /* @__PURE__ */ __name((e) => queue.push(e), "emit"),
2166
+ emit: /* @__PURE__ */ __name((e) => {
2167
+ queue.push(e);
2168
+ }, "emit"),
2386
2169
  awaitApproval: input.hitl.awaitApproval
2387
2170
  });
2388
2171
  const sdkStream = createSdkAgentStream(compiled, compiled.tools, apiKey, {
@@ -3020,9 +2803,9 @@ var AgentRunner = class {
3020
2803
  this.streamEnabled = state.streamEnabled;
3021
2804
  this.compaction = state.compaction;
3022
2805
  }
3023
- /** Start a fluent builder for `AgentClass`. */
3024
- static builder(AgentClass) {
3025
- return new AgentRunnerBuilder(AgentClass);
2806
+ /** Start a fluent builder from an already-compiled spec. */
2807
+ static fromSpec(spec) {
2808
+ return new AgentRunnerBuilder(spec);
3026
2809
  }
3027
2810
  /**
3028
2811
  * V4-D-stream: stream the agent's events LIVE across the reflective loop, returning
@@ -3084,12 +2867,12 @@ var AgentRunnerBuilder = class {
3084
2867
  static {
3085
2868
  __name(this, "AgentRunnerBuilder");
3086
2869
  }
3087
- AgentClass;
2870
+ spec;
3088
2871
  reflectionOverride;
3089
2872
  streamEnabled = true;
3090
2873
  compactionOverride;
3091
- constructor(AgentClass) {
3092
- this.AgentClass = AgentClass;
2874
+ constructor(spec) {
2875
+ this.spec = spec;
3093
2876
  }
3094
2877
  /** Override the default reflection strategy (OCP — plan Drawback #2). No arg ⇒ keep default. */
3095
2878
  reflection(strategy) {
@@ -3113,23 +2896,19 @@ var AgentRunnerBuilder = class {
3113
2896
  };
3114
2897
  return this;
3115
2898
  }
3116
- /** Walk + compile + resolve strategies — the compile→execute boundary (no I/O). */
2899
+ /** Resolve strategies from the spec — the compile→execute boundary (no I/O). */
3117
2900
  build() {
3118
- const walk = walkAgentMetadata(this.AgentClass, []);
3119
- const toolboxInstances = new Map(walk.toolboxes.map((tb) => [
3120
- tb.class,
3121
- new tb.class()
3122
- ]));
3123
- const compiled = compileAgent(walk, toolboxInstances);
3124
- const loopStrategy = resolveLoopStrategy(walk.mainLoop.strategy, walk.mainLoop.maxIterations);
3125
- const reflectionStrategy = this.reflectionOverride ?? (walk.mainLoop.strategy === "plan-act-reflect" ? ladderReflectionStrategy : noopReflectionStrategy);
3126
- const compactionDecl = this.compactionOverride ?? walk.compaction;
2901
+ const { spec } = this;
2902
+ const strategy = spec.strategy ?? "simple-chat";
2903
+ const loopStrategy = resolveLoopStrategy(strategy, spec.maxIterations);
2904
+ const reflectionStrategy = this.reflectionOverride ?? (strategy === "plan-act-reflect" ? ladderReflectionStrategy : noopReflectionStrategy);
2905
+ const compactionDecl = this.compactionOverride ?? spec.compaction;
3127
2906
  const compaction = compactionDecl ? resolveCompactionStrategy(compactionDecl.name, {
3128
2907
  keepTokens: compactionDecl.keepTokens
3129
2908
  }) : void 0;
3130
2909
  return new AgentRunner({
3131
- compiled,
3132
- agentName: walk.agentConfig.name,
2910
+ compiled: spec.compiled,
2911
+ agentName: spec.name,
3133
2912
  loopStrategy,
3134
2913
  reflectionStrategy,
3135
2914
  streamEnabled: this.streamEnabled,
@@ -3156,22 +2935,17 @@ function mergeTools(parentTools, subTools) {
3156
2935
  ];
3157
2936
  }
3158
2937
  __name(mergeTools, "mergeTools");
3159
- async function delegate(SubAgentClass, message, opts = {}) {
3160
- const apiKey = requireApiKey(opts, SubAgentClass.name);
2938
+ async function delegate(spec, message, opts = {}) {
2939
+ const apiKey = requireApiKey(opts, spec.name);
3161
2940
  const effectiveMessage = opts.onDelegationStart ? await opts.onDelegationStart({
3162
- subAgent: SubAgentClass.name,
2941
+ subAgent: spec.name,
3163
2942
  input: message
3164
2943
  }) : message;
3165
- const walk = walkAgentMetadata(SubAgentClass, []);
3166
- const toolboxInstances = new Map(walk.toolboxes.map((tb) => [
3167
- tb.class,
3168
- new tb.class()
3169
- ]));
3170
- const compiled = compileAgent(walk, toolboxInstances);
2944
+ const { compiled } = spec;
3171
2945
  const allTools = mergeTools(opts.parentTools ?? [], compiled.tools);
3172
2946
  const budget = Math.min(opts.budget ?? Infinity, opts.parentBudgetRemaining ?? Infinity);
3173
2947
  const streamFactory = opts.streamFactory ?? createSdkAgentStream(compiled, allTools, apiKey, {
3174
- model: opts.model ?? walk.agentConfig.model,
2948
+ model: opts.model ?? compiled.model,
3175
2949
  cwd: opts.cwd,
3176
2950
  plugins: opts.plugins,
3177
2951
  providers: opts.providers,
@@ -3180,19 +2954,19 @@ async function delegate(SubAgentClass, message, opts = {}) {
3180
2954
  sdkTools: opts.sdkTools
3181
2955
  });
3182
2956
  const sessionId = opts.sessionId ?? `sub-${crypto.randomUUID()}`;
3183
- const loopStrategy = resolveLoopStrategy(walk.mainLoop.strategy, opts.maxIterations ?? walk.mainLoop.maxIterations);
2957
+ const loopStrategy = resolveLoopStrategy(spec.strategy ?? "simple-chat", opts.maxIterations ?? spec.maxIterations);
3184
2958
  const reflection = opts.reflection ?? (loopStrategy.name === "plan-act-reflect" ? ladderReflectionStrategy : noopReflectionStrategy);
3185
2959
  const result = await runReflectiveLoop(streamFactory, effectiveMessage, sessionId, {
3186
2960
  loop: loopStrategy,
3187
2961
  reflection,
3188
2962
  budget,
3189
- agentName: SubAgentClass.name,
2963
+ agentName: spec.name,
3190
2964
  signal: opts.signal,
3191
2965
  retry: opts.retry
3192
2966
  });
3193
2967
  if (opts.onDelegationComplete) {
3194
2968
  return await opts.onDelegationComplete({
3195
- subAgent: SubAgentClass.name,
2969
+ subAgent: spec.name,
3196
2970
  result
3197
2971
  });
3198
2972
  }
@@ -3323,6 +3097,9 @@ async function delegateWithScoring(subAgent, message, opts) {
3323
3097
  }
3324
3098
  if (verdict.feedback) currentMessage = feedbackTemplate(message, verdict.feedback);
3325
3099
  }
3100
+ if (lastResult === void 0) {
3101
+ throw new Error("[@theokit/agents] delegateWithScoring: no round ran (maxRounds < 1)");
3102
+ }
3326
3103
  return {
3327
3104
  result: lastResult,
3328
3105
  rounds: maxRounds,
@@ -3398,11 +3175,11 @@ function mcpToolApprovals(specs) {
3398
3175
  __name(mcpToolApprovals, "mcpToolApprovals");
3399
3176
 
3400
3177
  // src/manifest/agent-manifest.ts
3401
- function generateAgentManifest(walkResults) {
3178
+ function generateAgentManifest(sources) {
3402
3179
  return {
3403
3180
  version: "1.0",
3404
3181
  generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
3405
- agents: walkResults.map((r) => ({
3182
+ agents: sources.map((r) => ({
3406
3183
  name: r.agentConfig.name,
3407
3184
  route: r.route,
3408
3185
  model: r.agentConfig.model,
@@ -3441,7 +3218,17 @@ function generateAgentManifest(walkResults) {
3441
3218
  __name(generateAgentManifest, "generateAgentManifest");
3442
3219
 
3443
3220
  // src/theokit-plugin.ts
3444
- import "reflect-metadata";
3221
+ function validateUniqueRoutes(results) {
3222
+ const seen = /* @__PURE__ */ new Map();
3223
+ for (const r of results) {
3224
+ const existing = seen.get(r.route);
3225
+ if (existing !== void 0) {
3226
+ throw new Error(`[@theokit/agents] Duplicate agent route '${r.route}': both '${existing}' and '${r.agentConfig.name}' declare it.`);
3227
+ }
3228
+ seen.set(r.route, r.agentConfig.name);
3229
+ }
3230
+ }
3231
+ __name(validateUniqueRoutes, "validateUniqueRoutes");
3445
3232
  function agentsPlugin(opts) {
3446
3233
  let routes = null;
3447
3234
  return {
@@ -3462,25 +3249,24 @@ function agentsPlugin(opts) {
3462
3249
  __name(agentsPlugin, "agentsPlugin");
3463
3250
  function initRoutes(opts) {
3464
3251
  const allRoutes = [];
3465
- const walkResults = [];
3466
- for (const AgentClass of opts.agents) {
3467
- const mixins = getMixins(AgentClass);
3468
- const toolboxes = [
3469
- ...opts.toolboxes ?? [],
3470
- ...mixins
3471
- ];
3472
- const walkResult = walkAgentMetadata(AgentClass, toolboxes);
3473
- walkResults.push(walkResult);
3474
- const compiled = compileAgent(walkResult, /* @__PURE__ */ new Map());
3475
- const createRun = opts.createRunFactory ? opts.createRunFactory(compiled, walkResult) : defaultCreateRun(compiled);
3476
- const agentRoutes = generateAgentRoutes({
3477
- walkResult,
3478
- compiledOptions: compiled,
3479
- createRun
3252
+ const routeIdentities = [];
3253
+ for (const entry of opts.agents) {
3254
+ routeIdentities.push({
3255
+ route: entry.route,
3256
+ agentConfig: {
3257
+ name: entry.name
3258
+ }
3480
3259
  });
3481
- allRoutes.push(...agentRoutes);
3260
+ const createRun = opts.createRunFactory ? opts.createRunFactory(entry.compiled) : defaultCreateRun(entry.compiled);
3261
+ allRoutes.push(...generateAgentRoutes({
3262
+ walkResult: {
3263
+ route: entry.route
3264
+ },
3265
+ compiledOptions: entry.compiled,
3266
+ createRun
3267
+ }));
3482
3268
  }
3483
- validateUniqueRoutes(walkResults);
3269
+ validateUniqueRoutes(routeIdentities);
3484
3270
  return compileRoutePatterns(allRoutes);
3485
3271
  }
3486
3272
  __name(initRoutes, "initRoutes");
@@ -3526,17 +3312,15 @@ export {
3526
3312
  isAgentDefinition,
3527
3313
  compileAgentDefinition,
3528
3314
  compileSkillsSelection,
3315
+ compileContextWindow,
3316
+ compileSkills,
3317
+ SDK_TOOL_NAME,
3318
+ toolRuntimeName,
3319
+ compileTools,
3529
3320
  createAgentExecutionContext,
3530
3321
  isAgentContext,
3531
- compileContextWindow,
3532
3322
  projectContextMetadataOnlyKnobs,
3533
3323
  compileProjectContext,
3534
- AgentWarningCode,
3535
- walkAgentMetadata,
3536
- validateUniqueRoutes,
3537
- compileSkills,
3538
- compileTools,
3539
- compileAgent,
3540
3324
  streamAgentResponse,
3541
3325
  isTextDelta,
3542
3326
  isToolCall,
@@ -3595,4 +3379,4 @@ export {
3595
3379
  generateAgentManifest,
3596
3380
  agentsPlugin
3597
3381
  };
3598
- //# sourceMappingURL=chunk-FEH7JFH7.js.map
3382
+ //# sourceMappingURL=chunk-PTHRG25K.js.map