@theokit/agents 7.3.1 → 7.4.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,30 +1,21 @@
1
- import {
2
- __name
3
- } from "./chunk-Z4QWC7IK.js";
4
-
5
1
  // src/errors.ts
6
2
  import { ConfigurationError } from "@theokit/sdk/errors";
7
3
 
8
4
  // src/bridge/define-agent.ts
9
5
  var AGENT_BRAND = /* @__PURE__ */ Symbol.for("theokit.agent.definition");
10
6
  function defineAgent(config) {
11
- return {
12
- ...config,
13
- [AGENT_BRAND]: true
14
- };
7
+ return { ...config, [AGENT_BRAND]: true };
15
8
  }
16
- __name(defineAgent, "defineAgent");
17
9
  function isAgentDefinition(value) {
18
10
  return typeof value === "object" && value !== null && value[AGENT_BRAND] === true;
19
11
  }
20
- __name(isAgentDefinition, "isAgentDefinition");
21
12
  function toCompiledTool(tool) {
22
13
  const handler = tool.handler;
23
14
  const compiled = {
24
15
  name: tool.name,
25
16
  description: tool.description,
26
17
  inputSchema: tool.inputSchema,
27
- handler: /* @__PURE__ */ __name((input, ctx) => handler(input, ctx), "handler")
18
+ handler: (input, ctx) => handler(input, ctx)
28
19
  };
29
20
  for (const sym of Object.getOwnPropertySymbols(tool)) {
30
21
  ;
@@ -32,7 +23,6 @@ function toCompiledTool(tool) {
32
23
  }
33
24
  return compiled;
34
25
  }
35
- __name(toCompiledTool, "toCompiledTool");
36
26
  function compileAgentDefinition(def) {
37
27
  return {
38
28
  model: def.model,
@@ -43,48 +33,33 @@ function compileAgentDefinition(def) {
43
33
  stream: true,
44
34
  // M7 — run-context flows to CompiledAgentOptions.runContext (distinct from the
45
35
  // context-window `context` field the decorator path uses); absent ⇒ no key.
46
- ...def.context !== void 0 ? {
47
- runContext: def.context
48
- } : {},
36
+ ...def.context !== void 0 ? { runContext: def.context } : {},
49
37
  // M9 — guardrails flow through unchanged; the runner applies them at the input boundary.
50
- ...def.guardrails !== void 0 ? {
51
- guardrails: def.guardrails
52
- } : {},
38
+ ...def.guardrails !== void 0 ? { guardrails: def.guardrails } : {},
53
39
  // M14 — HITL approvals compile into the same `hitl` map the decorator path produces.
54
- ...def.approvals !== void 0 ? {
55
- hitl: compileApprovals(def)
56
- } : {},
40
+ ...def.approvals !== void 0 ? { hitl: compileApprovals(def) } : {},
57
41
  // M13 — skills: a static list → SDK skills.enabled; a resolver → carried for the request path.
58
42
  ...compileSkillsSelection(def.skills),
59
43
  // theokit-file-based-config — the declared `.theokit/` sources flow to the run path, which
60
44
  // projects them into `Agent.create({ local.settingSources })`; absent ⇒ inline config only.
61
- ...def.settingSources !== void 0 ? {
62
- settingSources: def.settingSources
63
- } : {},
45
+ ...def.settingSources !== void 0 ? { settingSources: def.settingSources } : {},
64
46
  // M49 — memory flows to the projection layer; `assembleM8CreateOptions` forwards it to Agent.create.
65
- ...def.memory !== void 0 ? {
66
- memory: def.memory
67
- } : {},
47
+ ...def.memory !== void 0 ? { memory: def.memory } : {},
68
48
  // Hooks are converted here — the layer EVERY path converges on — rather than on the builder, so
69
49
  // `defineAgent({ hooks })` cannot type-check and silently no-op. A lifecycle hook that is
70
50
  // declared but never registered is a security gate that does not gate.
71
51
  ...compileHooksAndPlugins(def),
72
52
  // MCP — builder/`defineAgent` servers converge on the same `mcpServers` field the `@MCP`
73
53
  // decorator path populates; the SDK adapter forwards it to `Agent.create({ mcpServers })`.
74
- ...def.mcpServers !== void 0 ? {
75
- mcpServers: def.mcpServers
76
- } : {}
54
+ ...def.mcpServers !== void 0 ? { mcpServers: def.mcpServers } : {}
77
55
  };
78
56
  }
79
- __name(compileAgentDefinition, "compileAgentDefinition");
80
57
  function compileHooksAndPlugins(def) {
81
58
  const map = def.hooks;
82
59
  const entries = Object.entries(map ?? {}).filter(([, h]) => typeof h === "function");
83
60
  const explicit = def.plugins ?? [];
84
61
  if (entries.length === 0) {
85
- return def.plugins !== void 0 ? {
86
- plugins: def.plugins
87
- } : {};
62
+ return def.plugins !== void 0 ? { plugins: def.plugins } : {};
88
63
  }
89
64
  const plugin = {
90
65
  name: "theokit-builder-hooks",
@@ -96,19 +71,11 @@ function compileHooksAndPlugins(def) {
96
71
  }
97
72
  }
98
73
  };
99
- return {
100
- plugins: [
101
- ...explicit,
102
- plugin
103
- ]
104
- };
74
+ return { plugins: [...explicit, plugin] };
105
75
  }
106
- __name(compileHooksAndPlugins, "compileHooksAndPlugins");
107
76
  function compileSkillsSelection(skills) {
108
77
  if (skills === void 0) return {};
109
- if (typeof skills === "function") return {
110
- skillsResolver: skills
111
- };
78
+ if (typeof skills === "function") return { skillsResolver: skills };
112
79
  const enabled = [];
113
80
  const inline = [];
114
81
  for (const entry of skills) {
@@ -116,30 +83,22 @@ function compileSkillsSelection(skills) {
116
83
  else inline.push(entry);
117
84
  }
118
85
  return {
119
- skills: {
120
- enabled,
121
- autoInject: true,
122
- ...inline.length > 0 ? {
123
- inline
124
- } : {}
125
- }
86
+ skills: { enabled, autoInject: true, ...inline.length > 0 ? { inline } : {} }
126
87
  };
127
88
  }
128
- __name(compileSkillsSelection, "compileSkillsSelection");
129
89
  function compileApprovals(def) {
130
90
  const toolNames = new Set((def.tools ?? []).map((t) => t.name));
131
91
  const gates = /* @__PURE__ */ new Map();
132
92
  for (const [toolName, options] of Object.entries(def.approvals ?? {})) {
133
93
  if (!toolNames.has(toolName)) {
134
- throw new Error(`[@theokit/agents] defineAgent approval references unknown tool "${toolName}". Declared tools: ${[
135
- ...toolNames
136
- ].join(", ") || "(none)"}.`);
94
+ throw new Error(
95
+ `[@theokit/agents] defineAgent approval references unknown tool "${toolName}". Declared tools: ${[...toolNames].join(", ") || "(none)"}.`
96
+ );
137
97
  }
138
98
  gates.set(toolName, options);
139
99
  }
140
100
  return gates;
141
101
  }
142
- __name(compileApprovals, "compileApprovals");
143
102
 
144
103
  // src/bridge/compile-context-window.ts
145
104
  var STRATEGY_KNOBS = [
@@ -155,26 +114,16 @@ function compileContextWindow(options) {
155
114
  }
156
115
  const opts = options;
157
116
  const metadataOnlyKnobs = STRATEGY_KNOBS.filter((knob) => opts[knob] !== void 0);
158
- return {
159
- context,
160
- metadataOnlyKnobs
161
- };
117
+ return { context, metadataOnlyKnobs };
162
118
  }
163
- __name(compileContextWindow, "compileContextWindow");
164
119
 
165
120
  // src/bridge/compile-skills.ts
166
121
  function compileSkills(options) {
167
122
  if (options.autoDiscover) {
168
- return {
169
- autoInject: true
170
- };
123
+ return { autoInject: true };
171
124
  }
172
- return {
173
- enabled: options.include,
174
- autoInject: true
175
- };
125
+ return { enabled: options.include, autoInject: true };
176
126
  }
177
- __name(compileSkills, "compileSkills");
178
127
 
179
128
  // src/bridge/agent-compiler.ts
180
129
  var SDK_TOOL_NAME = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
@@ -194,18 +143,21 @@ function toolRuntimeName(namespace, toolName) {
194
143
  const name = namespace ? `${namespace}_${toolName}` : toolName;
195
144
  if (!SDK_TOOL_NAME.test(name)) {
196
145
  if (SDK_TOOL_NAME_CHARSET.test(name)) {
197
- throw new ConfigurationError(`tool: nome "${name}" tem comprimento ${name.length} \u2014 a composi\xE7\xE3o namespace + "_" + tool excede o m\xE1ximo de ${SDK_TOOL_NAME_MAX_LENGTH} que o SDK aceita`);
146
+ throw new ConfigurationError(
147
+ `tool: nome "${name}" tem comprimento ${name.length} \u2014 a composi\xE7\xE3o namespace + "_" + tool excede o m\xE1ximo de ${SDK_TOOL_NAME_MAX_LENGTH} que o SDK aceita`
148
+ );
198
149
  }
199
- throw new ConfigurationError(`tool: nome inv\xE1lido "${name}" \u2014 deve casar ${String(SDK_TOOL_NAME)} (o SDK rejeita o resto; verifique o namespace e o nome da tool)`);
150
+ throw new ConfigurationError(
151
+ `tool: nome inv\xE1lido "${name}" \u2014 deve casar ${String(SDK_TOOL_NAME)} (o SDK rejeita o resto; verifique o namespace e o nome da tool)`
152
+ );
200
153
  }
201
154
  if (SDK_RESERVED_TOOL_NAMES.has(name) || name.startsWith(SDK_RESERVED_TOOL_PREFIX)) {
202
- throw new ConfigurationError(`tool: nome reservado "${name}" \u2014 o SDK reserva ${[
203
- ...SDK_RESERVED_TOOL_NAMES
204
- ].join(", ")} e o prefixo "${SDK_RESERVED_TOOL_PREFIX}"`);
155
+ throw new ConfigurationError(
156
+ `tool: nome reservado "${name}" \u2014 o SDK reserva ${[...SDK_RESERVED_TOOL_NAMES].join(", ")} e o prefixo "${SDK_RESERVED_TOOL_PREFIX}"`
157
+ );
205
158
  }
206
159
  return name;
207
160
  }
208
- __name(toolRuntimeName, "toolRuntimeName");
209
161
  function compileHitlGates(toolboxes) {
210
162
  const gates = /* @__PURE__ */ new Map();
211
163
  for (const tb of toolboxes) {
@@ -217,50 +169,50 @@ function compileHitlGates(toolboxes) {
217
169
  }
218
170
  return gates;
219
171
  }
220
- __name(compileHitlGates, "compileHitlGates");
221
172
  function compileTools(toolboxes, toolboxInstances) {
222
173
  const tools = [];
223
174
  for (const tb of toolboxes) {
224
175
  const instance = toolboxInstances.get(tb.class);
225
176
  if (!instance) {
226
- throw new ConfigurationError(`toolbox: ${tb.class.name} n\xE3o foi instanciado \u2014 passe a inst\xE2ncia em \`toolboxInstances\``);
177
+ throw new ConfigurationError(
178
+ `toolbox: ${tb.class.name} n\xE3o foi instanciado \u2014 passe a inst\xE2ncia em \`toolboxInstances\``
179
+ );
227
180
  }
228
181
  for (const tool of tb.tools) {
229
182
  const handler = instance[tool.propertyKey];
230
183
  if (typeof handler !== "function") {
231
- throw new ConfigurationError(`toolbox: ${tb.class.name}.${String(tool.propertyKey)} n\xE3o \xE9 um m\xE9todo (tool "${tool.config.name}")`);
184
+ throw new ConfigurationError(
185
+ `toolbox: ${tb.class.name}.${String(tool.propertyKey)} n\xE3o \xE9 um m\xE9todo (tool "${tool.config.name}")`
186
+ );
232
187
  }
233
188
  const name = toolRuntimeName(tb.namespace, tool.config.name);
234
189
  tools.push({
235
190
  name,
236
191
  description: tool.config.description,
237
192
  inputSchema: tool.config.input,
238
- handler: /* @__PURE__ */ __name((input) => handler.call(instance, input), "handler")
193
+ handler: (input) => handler.call(instance, input)
239
194
  });
240
195
  }
241
196
  }
242
197
  return tools;
243
198
  }
244
- __name(compileTools, "compileTools");
245
199
 
246
200
  // src/bridge/agent-execution-context.ts
247
201
  function createAgentExecutionContext(base, agent, run, toolCall) {
248
202
  return {
249
- getRequest: /* @__PURE__ */ __name(() => base.getRequest(), "getRequest"),
250
- getUrl: /* @__PURE__ */ __name(() => base.getUrl(), "getUrl"),
251
- getClass: /* @__PURE__ */ __name(() => base.getClass(), "getClass"),
252
- getMethodName: /* @__PURE__ */ __name(() => base.getMethodName(), "getMethodName"),
253
- getAgent: /* @__PURE__ */ __name(() => agent, "getAgent"),
254
- getRun: /* @__PURE__ */ __name(() => run, "getRun"),
255
- getToolCall: /* @__PURE__ */ __name(() => toolCall ?? null, "getToolCall"),
256
- isAgentContext: /* @__PURE__ */ __name(() => true, "isAgentContext")
203
+ getRequest: () => base.getRequest(),
204
+ getUrl: () => base.getUrl(),
205
+ getClass: () => base.getClass(),
206
+ getMethodName: () => base.getMethodName(),
207
+ getAgent: () => agent,
208
+ getRun: () => run,
209
+ getToolCall: () => toolCall ?? null,
210
+ isAgentContext: () => true
257
211
  };
258
212
  }
259
- __name(createAgentExecutionContext, "createAgentExecutionContext");
260
213
  function isAgentContext(ctx) {
261
214
  return "isAgentContext" in ctx && ctx.isAgentContext();
262
215
  }
263
- __name(isAgentContext, "isAgentContext");
264
216
 
265
217
  // src/bridge/compile-project-context.ts
266
218
  var UNMAPPED_KNOBS = [
@@ -274,7 +226,6 @@ function projectContextMetadataOnlyKnobs(options) {
274
226
  const opts = options;
275
227
  return UNMAPPED_KNOBS.filter((knob) => opts[knob] !== void 0);
276
228
  }
277
- __name(projectContextMetadataOnlyKnobs, "projectContextMetadataOnlyKnobs");
278
229
  function compileProjectContext(options, base) {
279
230
  return async (promptCtx) => {
280
231
  const resolvedBase = typeof base === "function" ? await base(promptCtx) : base;
@@ -285,24 +236,16 @@ function compileProjectContext(options, base) {
285
236
  const { buildEnvContext, buildRepoMap } = await import("@theokit/sdk-tools");
286
237
  const { readProjectInstructions } = await import("@theokit/sdk/project");
287
238
  const env = buildEnvContext(cwd);
288
- const repoMap = buildRepoMap(cwd, {
289
- ignore: options.ignorePatterns
290
- });
239
+ const repoMap = buildRepoMap(cwd, { ignore: options.ignorePatterns });
291
240
  let instructions = "";
292
241
  try {
293
242
  instructions = (await readProjectInstructions(cwd)).content ?? "";
294
243
  } catch {
295
244
  instructions = "";
296
245
  }
297
- return [
298
- env,
299
- repoMap,
300
- instructions,
301
- resolvedBase
302
- ].filter(Boolean).join("\n\n");
246
+ return [env, repoMap, instructions, resolvedBase].filter(Boolean).join("\n\n");
303
247
  };
304
248
  }
305
- __name(compileProjectContext, "compileProjectContext");
306
249
 
307
250
  // src/bridge/agent-sse-handler.ts
308
251
  var encoder = new TextEncoder();
@@ -310,14 +253,14 @@ function streamAgentResponse(eventStream) {
310
253
  const stream = new ReadableStream({
311
254
  async start(controller) {
312
255
  let closed = false;
313
- const safeEnqueue = /* @__PURE__ */ __name((chunk) => {
256
+ const safeEnqueue = (chunk) => {
314
257
  if (closed) return;
315
258
  try {
316
259
  controller.enqueue(chunk);
317
260
  } catch {
318
261
  closed = true;
319
262
  }
320
- }, "safeEnqueue");
263
+ };
321
264
  try {
322
265
  for await (const event of eventStream) {
323
266
  if (closed) break;
@@ -332,9 +275,7 @@ data: ${data}
332
275
  if (!closed) {
333
276
  const errorEvent = {
334
277
  type: "error",
335
- error: {
336
- message: err instanceof Error ? err.message : "Internal agent error"
337
- }
278
+ error: { message: err instanceof Error ? err.message : "Internal agent error" }
338
279
  };
339
280
  const frame = `event: error
340
281
  data: ${JSON.stringify(errorEvent)}
@@ -356,37 +297,29 @@ data: ${JSON.stringify(errorEvent)}
356
297
  }
357
298
  });
358
299
  }
359
- __name(streamAgentResponse, "streamAgentResponse");
360
300
 
361
301
  // src/bridge/agent-stream-events.ts
362
302
  function isTextDelta(e) {
363
303
  return e.type === "text_delta";
364
304
  }
365
- __name(isTextDelta, "isTextDelta");
366
305
  function isToolCall(e) {
367
306
  return e.type === "tool_call";
368
307
  }
369
- __name(isToolCall, "isToolCall");
370
308
  function isPartialToolCall(e) {
371
309
  return e.type === "partial_tool_call";
372
310
  }
373
- __name(isPartialToolCall, "isPartialToolCall");
374
311
  function isToolResult(e) {
375
312
  return e.type === "tool_result";
376
313
  }
377
- __name(isToolResult, "isToolResult");
378
314
  function isDone(e) {
379
315
  return e.type === "done";
380
316
  }
381
- __name(isDone, "isDone");
382
317
  function isError(e) {
383
318
  return e.type === "error";
384
319
  }
385
- __name(isError, "isError");
386
320
  function isApprovalRequired(e) {
387
321
  return e.type === "approval_required";
388
322
  }
389
- __name(isApprovalRequired, "isApprovalRequired");
390
323
 
391
324
  // src/bridge/agent-route-generator.ts
392
325
  function generateAgentRoutes(ctx) {
@@ -396,7 +329,7 @@ function generateAgentRoutes(ctx) {
396
329
  routes.push({
397
330
  method: "POST",
398
331
  path: `${basePath}/chat`,
399
- handler: /* @__PURE__ */ __name(async (request) => {
332
+ handler: async (request) => {
400
333
  let body = null;
401
334
  try {
402
335
  body = await request.json();
@@ -404,92 +337,75 @@ function generateAgentRoutes(ctx) {
404
337
  }
405
338
  const message = body?.message;
406
339
  if (typeof message !== "string" || message.length === 0) {
407
- return new Response(JSON.stringify({
408
- error: {
409
- code: "BAD_REQUEST",
410
- message: "message field required"
411
- }
412
- }), {
413
- status: 400,
414
- headers: {
415
- "content-type": "application/json"
416
- }
417
- });
340
+ return new Response(
341
+ JSON.stringify({ error: { code: "BAD_REQUEST", message: "message field required" } }),
342
+ { status: 400, headers: { "content-type": "application/json" } }
343
+ );
418
344
  }
419
345
  const rawSessionId = body?.sessionId;
420
346
  const sessionId = typeof rawSessionId === "string" ? rawSessionId : `session-${Date.now()}`;
421
347
  return streamAgentResponse(createRun(message, sessionId));
422
- }, "handler")
348
+ }
423
349
  });
424
350
  if (getRun) {
425
351
  routes.push({
426
352
  method: "GET",
427
353
  path: `${basePath}/runs/:runId`,
428
- handler: /* @__PURE__ */ __name(async (request) => {
354
+ handler: async (request) => {
429
355
  const url = new URL(request.url);
430
356
  const runId = url.pathname.split("/").pop() ?? "";
431
357
  const run = await getRun(runId);
432
358
  if (!run) {
433
- return new Response(JSON.stringify({
434
- error: {
435
- code: "NOT_FOUND",
436
- message: `Run ${runId} not found`
437
- }
438
- }), {
439
- status: 404,
440
- headers: {
441
- "content-type": "application/json"
442
- }
443
- });
359
+ return new Response(
360
+ JSON.stringify({ error: { code: "NOT_FOUND", message: `Run ${runId} not found` } }),
361
+ { status: 404, headers: { "content-type": "application/json" } }
362
+ );
444
363
  }
445
364
  return new Response(JSON.stringify(run), {
446
365
  status: 200,
447
- headers: {
448
- "content-type": "application/json"
449
- }
366
+ headers: { "content-type": "application/json" }
450
367
  });
451
- }, "handler")
368
+ }
452
369
  });
453
370
  }
454
371
  return routes;
455
372
  }
456
- __name(generateAgentRoutes, "generateAgentRoutes");
457
373
 
458
374
  // src/guardrails/types.ts
459
375
  var GuardrailViolationError = class extends Error {
460
- static {
461
- __name(this, "GuardrailViolationError");
376
+ constructor(guardName, phase, reason) {
377
+ super(`Guardrail "${guardName}" blocked ${phase}: ${reason}`);
378
+ this.guardName = guardName;
379
+ this.phase = phase;
380
+ this.reason = reason;
381
+ this.name = "GuardrailViolationError";
462
382
  }
463
383
  guardName;
464
384
  phase;
465
385
  reason;
466
- constructor(guardName, phase, reason) {
467
- super(`Guardrail "${guardName}" blocked ${phase}: ${reason}`), this.guardName = guardName, this.phase = phase, this.reason = reason;
468
- this.name = "GuardrailViolationError";
469
- }
470
386
  };
471
387
  var CostBudgetExceededError = class extends Error {
472
- static {
473
- __name(this, "CostBudgetExceededError");
474
- }
475
- usedTokens;
476
- maxTokens;
477
388
  constructor(usedTokens, maxTokens) {
478
- super(`Cost budget exceeded: ${usedTokens} > ${maxTokens} tokens`), this.usedTokens = usedTokens, this.maxTokens = maxTokens;
389
+ super(`Cost budget exceeded: ${usedTokens} > ${maxTokens} tokens`);
390
+ this.usedTokens = usedTokens;
391
+ this.maxTokens = maxTokens;
479
392
  this.name = "CostBudgetExceededError";
480
393
  }
394
+ usedTokens;
395
+ maxTokens;
481
396
  };
482
397
 
483
398
  // src/guardrails/detectors.ts
484
399
  function estimateTokens(text) {
485
400
  return Math.ceil(text.length / 4);
486
401
  }
487
- __name(estimateTokens, "estimateTokens");
488
402
  var INJECTION_PHRASES = [
489
403
  "previous instructions",
404
+ // "ignore/disregard [all|the] previous instructions"
490
405
  "disregard the above",
491
406
  "you are now dan",
492
407
  "system prompt",
408
+ // "reveal your/the system prompt"
493
409
  "no restrictions",
494
410
  "without restrictions",
495
411
  "no rules",
@@ -498,31 +414,21 @@ var INJECTION_PHRASES = [
498
414
  function normalizeForMatch(text) {
499
415
  return text.toLowerCase().replace(/\s+/g, " ");
500
416
  }
501
- __name(normalizeForMatch, "normalizeForMatch");
502
417
  function promptInjectionDetector(options = {}) {
503
- const phrases = [
504
- ...INJECTION_PHRASES,
505
- ...(options.extra ?? []).map((p) => p.toLowerCase())
506
- ];
418
+ const phrases = [...INJECTION_PHRASES, ...(options.extra ?? []).map((p) => p.toLowerCase())];
507
419
  return {
508
420
  name: "prompt-injection",
509
421
  checkInput(text) {
510
422
  const normalized = normalizeForMatch(text);
511
423
  for (const phrase of phrases) {
512
424
  if (normalized.includes(phrase)) {
513
- return {
514
- action: "block",
515
- reason: `prompt injection phrase matched: "${phrase}"`
516
- };
425
+ return { action: "block", reason: `prompt injection phrase matched: "${phrase}"` };
517
426
  }
518
427
  }
519
- return {
520
- action: "allow"
521
- };
428
+ return { action: "allow" };
522
429
  }
523
430
  };
524
431
  }
525
- __name(promptInjectionDetector, "promptInjectionDetector");
526
432
  var CPF = /\b\d{3}\.?\d{3}\.?\d{3}-?\d{2}\b/g;
527
433
  var EMAIL = /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g;
528
434
  var PHONE = /\+?\d[\d\s()-]{7,13}\d/g;
@@ -535,36 +441,22 @@ function piiDetector(options = {}) {
535
441
  redacted = redacted.replace(EMAIL, placeholder);
536
442
  redacted = redacted.replace(CPF, placeholder);
537
443
  redacted = redacted.replace(PHONE, placeholder);
538
- if (redacted === text) return {
539
- action: "allow"
540
- };
541
- return {
542
- action: "redact",
543
- text: redacted,
544
- reason: "PII detected and redacted"
545
- };
444
+ if (redacted === text) return { action: "allow" };
445
+ return { action: "redact", text: redacted, reason: "PII detected and redacted" };
546
446
  }
547
447
  };
548
448
  }
549
- __name(piiDetector, "piiDetector");
550
449
  var OBFUSCATION_CHARS = /[\u200B-\u200D\uFEFF\u202A-\u202E\u2066-\u2069]/g;
551
450
  function unicodeNormalizer() {
552
451
  return {
553
452
  name: "unicode-normalizer",
554
453
  checkInput(text) {
555
454
  const cleaned = text.normalize("NFKC").replace(OBFUSCATION_CHARS, "");
556
- if (cleaned === text) return {
557
- action: "allow"
558
- };
559
- return {
560
- action: "redact",
561
- text: cleaned,
562
- reason: "obfuscation characters normalized"
563
- };
455
+ if (cleaned === text) return { action: "allow" };
456
+ return { action: "redact", text: cleaned, reason: "obfuscation characters normalized" };
564
457
  }
565
458
  };
566
459
  }
567
- __name(unicodeNormalizer, "unicodeNormalizer");
568
460
  function costGuard(options) {
569
461
  let used = 0;
570
462
  return {
@@ -576,28 +468,19 @@ function costGuard(options) {
576
468
  if (used > options.maxTokens) {
577
469
  return Promise.reject(new CostBudgetExceededError(used, options.maxTokens));
578
470
  }
579
- return Promise.resolve({
580
- action: "allow"
581
- });
471
+ return Promise.resolve({ action: "allow" });
582
472
  }
583
473
  };
584
474
  }
585
- __name(costGuard, "costGuard");
586
475
  function outputModeration(options) {
587
476
  return {
588
477
  name: "output-moderation",
589
478
  async checkOutput(text) {
590
479
  const flagged = await options.moderate(text);
591
- return flagged ? {
592
- action: "block",
593
- reason: "output flagged by moderation predicate"
594
- } : {
595
- action: "allow"
596
- };
480
+ return flagged ? { action: "block", reason: "output flagged by moderation predicate" } : { action: "allow" };
597
481
  }
598
482
  };
599
483
  }
600
- __name(outputModeration, "outputModeration");
601
484
 
602
485
  // src/guardrails/pipeline.ts
603
486
  async function runInputGuards(text, guards) {
@@ -612,7 +495,6 @@ async function runInputGuards(text, guards) {
612
495
  }
613
496
  return current;
614
497
  }
615
- __name(runInputGuards, "runInputGuards");
616
498
  async function runOutputGuards(text, guards) {
617
499
  let current = text;
618
500
  for (const g of guards) {
@@ -625,7 +507,6 @@ async function runOutputGuards(text, guards) {
625
507
  }
626
508
  return current;
627
509
  }
628
- __name(runOutputGuards, "runOutputGuards");
629
510
 
630
511
  // src/guardrails/stream.ts
631
512
  async function* moderateOutputStream(inner, guards, extractText) {
@@ -645,7 +526,6 @@ async function* moderateOutputStream(inner, guards, extractText) {
645
526
  for (const event of buffered) yield event;
646
527
  return step.value;
647
528
  }
648
- __name(moderateOutputStream, "moderateOutputStream");
649
529
 
650
530
  // src/bridge/tool-hooks-plugin.ts
651
531
  function createToolHooksPlugin(hooks) {
@@ -658,30 +538,22 @@ function createToolHooksPlugin(hooks) {
658
538
  register(ctx) {
659
539
  const { beforeToolCall, afterToolCall, beforeLLMCall, afterLLMCall, processInput } = hooks;
660
540
  if (beforeToolCall) {
661
- ctx.on("pre_tool_call", (c) => beforeToolCall({
662
- name: c.name ?? "",
663
- args: c.args ?? {}
664
- }));
541
+ ctx.on("pre_tool_call", (c) => beforeToolCall({ name: c.name ?? "", args: c.args ?? {} }));
665
542
  }
666
543
  if (afterToolCall) {
667
- ctx.on("post_tool_call", (c) => afterToolCall({
668
- name: c.name ?? "",
669
- result: c.result
670
- }));
544
+ ctx.on("post_tool_call", (c) => afterToolCall({ name: c.name ?? "", result: c.result }));
671
545
  }
672
546
  if (beforeLLMCall) {
673
- ctx.on("pre_llm_call", (c) => beforeLLMCall({
674
- agentId: c.agentId,
675
- runId: c.runId,
676
- iteration: c.iteration
677
- }));
547
+ ctx.on(
548
+ "pre_llm_call",
549
+ (c) => beforeLLMCall({ agentId: c.agentId, runId: c.runId, iteration: c.iteration })
550
+ );
678
551
  }
679
552
  if (afterLLMCall) {
680
- ctx.on("post_llm_call", (c) => afterLLMCall({
681
- agentId: c.agentId,
682
- runId: c.runId,
683
- iteration: c.iteration
684
- }));
553
+ ctx.on(
554
+ "post_llm_call",
555
+ (c) => afterLLMCall({ agentId: c.agentId, runId: c.runId, iteration: c.iteration })
556
+ );
685
557
  }
686
558
  if (processInput) {
687
559
  ctx.on("pre_user_send", async (c) => {
@@ -690,49 +562,30 @@ function createToolHooksPlugin(hooks) {
690
562
  agentId: c.agentId,
691
563
  runId: c.runId
692
564
  });
693
- return injected !== void 0 && injected.length > 0 ? {
694
- recalledContext: injected
695
- } : void 0;
565
+ return injected !== void 0 && injected.length > 0 ? { recalledContext: injected } : void 0;
696
566
  });
697
567
  }
698
568
  }
699
569
  };
700
570
  }
701
- __name(createToolHooksPlugin, "createToolHooksPlugin");
702
571
 
703
572
  // src/bridge/model-selection.ts
704
573
  var PARAM_THINKING = "thinking";
705
574
  function buildModelSelection(model, effort) {
706
- const base = typeof model === "string" ? {
707
- id: model
708
- } : {
709
- ...model
710
- };
575
+ const base = typeof model === "string" ? { id: model } : { ...model };
711
576
  if (!effort) return base;
712
- return {
713
- ...base,
714
- params: [
715
- ...base.params ?? [],
716
- {
717
- id: PARAM_THINKING,
718
- value: effort
719
- }
720
- ]
721
- };
577
+ return { ...base, params: [...base.params ?? [], { id: PARAM_THINKING, value: effort }] };
722
578
  }
723
- __name(buildModelSelection, "buildModelSelection");
724
579
  function reasoningEffortOf(model) {
725
580
  const params = typeof model === "string" ? void 0 : model.params;
726
581
  return params?.find((p) => p.id === PARAM_THINKING)?.value;
727
582
  }
728
- __name(reasoningEffortOf, "reasoningEffortOf");
729
583
 
730
584
  // src/bridge/event-translator.ts
731
585
  function asString(value, fallback) {
732
586
  if (typeof value === "string") return value;
733
587
  return fallback;
734
588
  }
735
- __name(asString, "asString");
736
589
  function serializeToolOutput(value, fallback) {
737
590
  if (typeof value === "string") return value;
738
591
  if (value === void 0 || value === null) return fallback;
@@ -742,7 +595,6 @@ function serializeToolOutput(value, fallback) {
742
595
  return typeof value === "bigint" ? value.toString() : fallback;
743
596
  }
744
597
  }
745
- __name(serializeToolOutput, "serializeToolOutput");
746
598
  function translateSystemEvent(msg, runId) {
747
599
  return [
748
600
  {
@@ -753,7 +605,6 @@ function translateSystemEvent(msg, runId) {
753
605
  }
754
606
  ];
755
607
  }
756
- __name(translateSystemEvent, "translateSystemEvent");
757
608
  function translateAssistantEvent(msg) {
758
609
  const events = [];
759
610
  const message = msg.message;
@@ -762,10 +613,7 @@ function translateAssistantEvent(msg) {
762
613
  for (const block of content) {
763
614
  const b = block;
764
615
  if (b.type === "text" && b.text) {
765
- events.push({
766
- type: "text_delta",
767
- content: b.text
768
- });
616
+ events.push({ type: "text_delta", content: b.text });
769
617
  }
770
618
  if (b.type === "tool_use") {
771
619
  events.push({
@@ -782,7 +630,6 @@ function translateAssistantEvent(msg) {
782
630
  }
783
631
  return events;
784
632
  }
785
- __name(translateAssistantEvent, "translateAssistantEvent");
786
633
  function translateToolCallEvent(msg) {
787
634
  const status = msg.status;
788
635
  const callId = asString(msg.call_id, "");
@@ -813,17 +660,11 @@ function translateToolCallEvent(msg) {
813
660
  }
814
661
  if (status === "running") {
815
662
  return [
816
- {
817
- type: "tool_call",
818
- callId,
819
- toolName,
820
- input: msg.args ?? msg.input ?? msg.arguments ?? {}
821
- }
663
+ { type: "tool_call", callId, toolName, input: msg.args ?? msg.input ?? msg.arguments ?? {} }
822
664
  ];
823
665
  }
824
666
  return [];
825
667
  }
826
- __name(translateToolCallEvent, "translateToolCallEvent");
827
668
  function translateStatusEvent(msg) {
828
669
  const s = msg.status;
829
670
  if (s === "FINISHED" || s === "CANCELLED") {
@@ -831,11 +672,7 @@ function translateStatusEvent(msg) {
831
672
  {
832
673
  type: "done",
833
674
  result: "",
834
- usage: {
835
- inputTokens: 0,
836
- outputTokens: 0,
837
- totalTokens: 0
838
- },
675
+ usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
839
676
  durationMs: 0,
840
677
  cost: 0
841
678
  }
@@ -853,17 +690,15 @@ function translateStatusEvent(msg) {
853
690
  }
854
691
  return [];
855
692
  }
856
- __name(translateStatusEvent, "translateStatusEvent");
857
693
  var jaAvisados = /* @__PURE__ */ new Set();
858
694
  function avisarSeDesconhecido(tipo, ignoradosDeProposito) {
859
695
  if (ignoradosDeProposito.has(tipo) || jaAvisados.has(tipo)) return;
860
696
  jaAvisados.add(tipo);
861
- console.warn(`[theokit] agents.bridge: evento "${tipo}" do SDK n\xE3o \xE9 traduzido e foi descartado. Se ele carrega informa\xE7\xE3o que a UI precisa, o tradutor precisa de um caso para ele (#141).`);
697
+ console.warn(
698
+ `[theokit] agents.bridge: evento "${tipo}" do SDK n\xE3o \xE9 traduzido e foi descartado. Se ele carrega informa\xE7\xE3o que a UI precisa, o tradutor precisa de um caso para ele (#141).`
699
+ );
862
700
  }
863
- __name(avisarSeDesconhecido, "avisarSeDesconhecido");
864
- var SDK_MESSAGE_IGNORADOS = /* @__PURE__ */ new Set([
865
- "user"
866
- ]);
701
+ var SDK_MESSAGE_IGNORADOS = /* @__PURE__ */ new Set(["user"]);
867
702
  var INTERACTION_UPDATE_IGNORADOS = /* @__PURE__ */ new Set([
868
703
  "thinking-completed",
869
704
  "token-delta",
@@ -879,21 +714,11 @@ function translateSdkEvent(msg, runId) {
879
714
  case "tool_call":
880
715
  return translateToolCallEvent(msg);
881
716
  case "thinking":
882
- return [
883
- {
884
- type: "thinking",
885
- content: asString(msg.text, "")
886
- }
887
- ];
717
+ return [{ type: "thinking", content: asString(msg.text, "") }];
888
718
  case "status":
889
719
  return translateStatusEvent(msg);
890
720
  case "request":
891
- return [
892
- {
893
- type: "input_requested",
894
- requestId: asString(msg.request_id, "")
895
- }
896
- ];
721
+ return [{ type: "input_requested", requestId: asString(msg.request_id, "") }];
897
722
  case "task": {
898
723
  const status = typeof msg.status === "string" ? msg.status : void 0;
899
724
  const text = typeof msg.text === "string" ? msg.text : void 0;
@@ -901,12 +726,8 @@ function translateSdkEvent(msg, runId) {
901
726
  return [
902
727
  {
903
728
  type: "task_progress",
904
- ...status !== void 0 ? {
905
- status
906
- } : {},
907
- ...text !== void 0 ? {
908
- text
909
- } : {}
729
+ ...status !== void 0 ? { status } : {},
730
+ ...text !== void 0 ? { text } : {}
910
731
  }
911
732
  ];
912
733
  }
@@ -915,23 +736,12 @@ function translateSdkEvent(msg, runId) {
915
736
  return [];
916
737
  }
917
738
  }
918
- __name(translateSdkEvent, "translateSdkEvent");
919
739
  function translateInteractionUpdate(update) {
920
740
  switch (update.type) {
921
741
  case "text-delta":
922
- return update.text ? [
923
- {
924
- type: "text_delta",
925
- content: update.text
926
- }
927
- ] : [];
742
+ return update.text ? [{ type: "text_delta", content: update.text }] : [];
928
743
  case "thinking-delta":
929
- return update.text ? [
930
- {
931
- type: "thinking",
932
- content: update.text
933
- }
934
- ] : [];
744
+ return update.text ? [{ type: "thinking", content: update.text }] : [];
935
745
  case "tool-call-started":
936
746
  return [
937
747
  {
@@ -962,18 +772,12 @@ function translateInteractionUpdate(update) {
962
772
  }
963
773
  ];
964
774
  case "shell-output-delta":
965
- return [
966
- {
967
- type: "shell_output",
968
- event: update.event
969
- }
970
- ];
775
+ return [{ type: "shell_output", event: update.event }];
971
776
  default:
972
777
  avisarSeDesconhecido(update.type, INTERACTION_UPDATE_IGNORADOS);
973
778
  return [];
974
779
  }
975
780
  }
976
- __name(translateInteractionUpdate, "translateInteractionUpdate");
977
781
 
978
782
  // src/bridge/think-tag-extractor.ts
979
783
  var TAG = "think";
@@ -986,11 +790,10 @@ function heldPrefixLength(s, delim) {
986
790
  }
987
791
  return 0;
988
792
  }
989
- __name(heldPrefixLength, "heldPrefixLength");
990
793
  function createThinkTagExtractor() {
991
794
  let mode = "text";
992
795
  let buffer = "";
993
- const write = /* @__PURE__ */ __name((chunk) => {
796
+ const write = (chunk) => {
994
797
  buffer += chunk;
995
798
  const out = [];
996
799
  for (; ; ) {
@@ -998,52 +801,30 @@ function createThinkTagExtractor() {
998
801
  const idx = buffer.indexOf(delim);
999
802
  if (idx !== -1) {
1000
803
  const content = buffer.slice(0, idx);
1001
- if (content) out.push({
1002
- kind: mode,
1003
- content
1004
- });
804
+ if (content) out.push({ kind: mode, content });
1005
805
  buffer = buffer.slice(idx + delim.length);
1006
806
  mode = mode === "text" ? "thinking" : "text";
1007
807
  continue;
1008
808
  }
1009
809
  const keep = heldPrefixLength(buffer, delim);
1010
810
  const emit = buffer.slice(0, buffer.length - keep);
1011
- if (emit) out.push({
1012
- kind: mode,
1013
- content: emit
1014
- });
811
+ if (emit) out.push({ kind: mode, content: emit });
1015
812
  buffer = buffer.slice(buffer.length - keep);
1016
813
  break;
1017
814
  }
1018
815
  return out;
1019
- }, "write");
1020
- const end = /* @__PURE__ */ __name(() => {
816
+ };
817
+ const end = () => {
1021
818
  if (!buffer) return [];
1022
- const seg = {
1023
- kind: mode,
1024
- content: buffer
1025
- };
819
+ const seg = { kind: mode, content: buffer };
1026
820
  buffer = "";
1027
- return [
1028
- seg
1029
- ];
1030
- }, "end");
1031
- return {
1032
- write,
1033
- end
821
+ return [seg];
1034
822
  };
823
+ return { write, end };
1035
824
  }
1036
- __name(createThinkTagExtractor, "createThinkTagExtractor");
1037
825
  function segmentToEvent(seg) {
1038
- return seg.kind === "thinking" ? {
1039
- type: "thinking",
1040
- content: seg.content
1041
- } : {
1042
- type: "text_delta",
1043
- content: seg.content
1044
- };
826
+ return seg.kind === "thinking" ? { type: "thinking", content: seg.content } : { type: "text_delta", content: seg.content };
1045
827
  }
1046
- __name(segmentToEvent, "segmentToEvent");
1047
828
  async function* extractThinkTagStream(source) {
1048
829
  const extractor = createThinkTagExtractor();
1049
830
  try {
@@ -1058,7 +839,6 @@ async function* extractThinkTagStream(source) {
1058
839
  for (const seg of extractor.end()) yield segmentToEvent(seg);
1059
840
  }
1060
841
  }
1061
- __name(extractThinkTagStream, "extractThinkTagStream");
1062
842
 
1063
843
  // src/debug-log.ts
1064
844
  function debugLog(marker, data) {
@@ -1067,7 +847,6 @@ function debugLog(marker, data) {
1067
847
  console.debug(marker, data);
1068
848
  }
1069
849
  }
1070
- __name(debugLog, "debugLog");
1071
850
 
1072
851
  // src/bridge/hitl-plugin.ts
1073
852
  function createHitlPlugin(wiring) {
@@ -1091,53 +870,39 @@ function createHitlPlugin(wiring) {
1091
870
  callbackUrl: `approve/${approvalId}`,
1092
871
  timeoutMs: opts.timeout ?? 3e5,
1093
872
  // M20 — carry the declared custom-payload schema so the UI knows what to collect.
1094
- ...opts.payloadSchema !== void 0 ? {
1095
- payloadSchema: opts.payloadSchema
1096
- } : {}
873
+ ...opts.payloadSchema !== void 0 ? { payloadSchema: opts.payloadSchema } : {}
1097
874
  });
1098
875
  const raw = await wiring.awaitApproval(approvalId, opts, c.name);
1099
- const decision = typeof raw === "boolean" ? {
1100
- approved: raw
1101
- } : raw;
876
+ const decision = typeof raw === "boolean" ? { approved: raw } : raw;
1102
877
  if (decision.approved) return void 0;
1103
878
  let message = `Tool '${c.name}' denied by human approver`;
1104
879
  if (decision.reason) message += `: ${decision.reason}`;
1105
880
  if (decision.payload !== void 0) {
1106
881
  message += ` (payload: ${JSON.stringify(decision.payload)})`;
1107
882
  }
1108
- return {
1109
- block: true,
1110
- message
1111
- };
883
+ return { block: true, message };
1112
884
  });
1113
885
  }
1114
886
  };
1115
887
  }
1116
- __name(createHitlPlugin, "createHitlPlugin");
1117
888
 
1118
889
  // src/bridge/approval-posture.ts
1119
890
  function razaoDe(postura) {
1120
891
  return postura.kind === "interactive" ? "human approver on this surface" : postura.reason;
1121
892
  }
1122
- __name(razaoDe, "razaoDe");
1123
893
  function aplicarPostura(extra, m8, postura, gated) {
1124
894
  const daPostura = pluginsDaPostura(postura, gated);
1125
895
  if (daPostura.length === 0) return;
1126
896
  const atuais = extra.plugins ?? m8.plugins;
1127
897
  if (atuais !== void 0 && !Array.isArray(atuais)) {
1128
- throw new Error(`[@theokit/agents] approval posture "${postura.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.`);
898
+ throw new Error(
899
+ `[@theokit/agents] approval posture "${postura.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.`
900
+ );
1129
901
  }
1130
- extra.plugins = [
1131
- ...atuais ?? [],
1132
- ...daPostura
1133
- ];
902
+ extra.plugins = [...atuais ?? [], ...daPostura];
1134
903
  }
1135
- __name(aplicarPostura, "aplicarPostura");
1136
904
  function pluginsDaPostura(postura, gated) {
1137
- debugLog("[theokit] approval posture", {
1138
- kind: postura.kind,
1139
- reason: razaoDe(postura)
1140
- });
905
+ debugLog("[theokit] approval posture", { kind: postura.kind, reason: razaoDe(postura) });
1141
906
  if (gated === void 0 || gated.size === 0) return [];
1142
907
  switch (postura.kind) {
1143
908
  case "interactive":
@@ -1151,7 +916,7 @@ function pluginsDaPostura(postura, gated) {
1151
916
  case "auto-approve":
1152
917
  return [
1153
918
  createToolHooksPlugin({
1154
- beforeToolCall: /* @__PURE__ */ __name((ctx) => {
919
+ beforeToolCall: (ctx) => {
1155
920
  if (gated.has(ctx.name)) {
1156
921
  debugLog("[theokit] gated tool auto-approved", {
1157
922
  tool: ctx.name,
@@ -1159,7 +924,7 @@ function pluginsDaPostura(postura, gated) {
1159
924
  });
1160
925
  }
1161
926
  return void 0;
1162
- }, "beforeToolCall")
927
+ }
1163
928
  })
1164
929
  ];
1165
930
  case "auto-reject":
@@ -1167,17 +932,16 @@ function pluginsDaPostura(postura, gated) {
1167
932
  createToolHooksPlugin({
1168
933
  // Só as tools GATEADAS são recusadas: a postura descreve o gate, não um bloqueio universal.
1169
934
  // Recusar tudo quebraria todo agente que tem uma tool livre ao lado de uma gateada.
1170
- beforeToolCall: /* @__PURE__ */ __name((ctx) => gated.has(ctx.name) ? {
935
+ beforeToolCall: (ctx) => gated.has(ctx.name) ? {
1171
936
  block: true,
1172
937
  message: `Tool '${ctx.name}' requires human approval, and this surface has no approver (approval posture: auto-reject \u2014 ${postura.reason}). Refused (fail-closed).`
1173
- } : void 0, "beforeToolCall")
938
+ } : void 0
1174
939
  })
1175
940
  ];
1176
941
  case "owned-by-surface":
1177
942
  return [];
1178
943
  }
1179
944
  }
1180
- __name(pluginsDaPostura, "pluginsDaPostura");
1181
945
 
1182
946
  // src/bridge/definicao-ou-thunk.ts
1183
947
  function projetar(def, overrides) {
@@ -1189,7 +953,6 @@ function projetar(def, overrides) {
1189
953
  runContext: overrides.runContext ?? compiled.runContext
1190
954
  };
1191
955
  }
1192
- __name(projetar, "projetar");
1193
956
  function resolverProjecao(def, overrides) {
1194
957
  if (typeof def === "function") {
1195
958
  return async (sessionId) => projetar(await def(sessionId), overrides);
@@ -1197,7 +960,6 @@ function resolverProjecao(def, overrides) {
1197
960
  const eager = projetar(def, overrides);
1198
961
  return () => Promise.resolve(eager);
1199
962
  }
1200
- __name(resolverProjecao, "resolverProjecao");
1201
963
 
1202
964
  // src/bridge/erro-do-sdk.ts
1203
965
  function eventoDeErroDoSdk(err) {
@@ -1211,7 +973,6 @@ function eventoDeErroDoSdk(err) {
1211
973
  retryable: sdkErr.isRetryable === true
1212
974
  };
1213
975
  }
1214
- __name(eventoDeErroDoSdk, "eventoDeErroDoSdk");
1215
976
 
1216
977
  // src/bridge/sdk-adapter-create-options.ts
1217
978
  function assembleM8CreateOptions(compiled) {
@@ -1228,10 +989,7 @@ function assembleM8CreateOptions(compiled) {
1228
989
  }
1229
990
  const settingSources = resolveSettingSources(compiled);
1230
991
  if (settingSources) {
1231
- options.local = {
1232
- ...options.local,
1233
- settingSources
1234
- };
992
+ options.local = { ...options.local, settingSources };
1235
993
  applied.push("settingSources");
1236
994
  }
1237
995
  if (compiled.context) {
@@ -1254,32 +1012,23 @@ function assembleM8CreateOptions(compiled) {
1254
1012
  } else {
1255
1013
  const dropped = Object.keys(compiled.memory);
1256
1014
  if (dropped.length > 0) {
1257
- process.stderr.write(`[theokit-agents] @Memory decorator options not yet mapped to the SDK (${dropped.join(", ")}) \u2014 memory enabled with defaults
1258
- `);
1015
+ process.stderr.write(
1016
+ `[theokit-agents] @Memory decorator options not yet mapped to the SDK (${dropped.join(", ")}) \u2014 memory enabled with defaults
1017
+ `
1018
+ );
1259
1019
  }
1260
- options.memory = {
1261
- enabled: true
1262
- };
1020
+ options.memory = { enabled: true };
1263
1021
  }
1264
1022
  applied.push("memory");
1265
1023
  }
1266
- return {
1267
- options,
1268
- applied
1269
- };
1024
+ return { options, applied };
1270
1025
  }
1271
- __name(assembleM8CreateOptions, "assembleM8CreateOptions");
1272
1026
  function resolveSettingSources(compiled) {
1273
1027
  const explicit = compiled.settingSources;
1274
- if (explicit && explicit.length > 0) return [
1275
- ...explicit
1276
- ];
1277
- if (compiled.skills) return [
1278
- "project"
1279
- ];
1028
+ if (explicit && explicit.length > 0) return [...explicit];
1029
+ if (compiled.skills) return ["project"];
1280
1030
  return void 0;
1281
1031
  }
1282
- __name(resolveSettingSources, "resolveSettingSources");
1283
1032
  function realUsageDone(result, t0) {
1284
1033
  const u = result.usage;
1285
1034
  const inputTokens = u?.inputTokens ?? 0;
@@ -1301,7 +1050,6 @@ function realUsageDone(result, t0) {
1301
1050
  cost: result.cost?.amount ?? 0
1302
1051
  };
1303
1052
  }
1304
- __name(realUsageDone, "realUsageDone");
1305
1053
 
1306
1054
  // src/bridge/sdk-timeline.ts
1307
1055
  function idsOf(e, raw) {
@@ -1312,13 +1060,11 @@ function idsOf(e, raw) {
1312
1060
  if (typeof model === "string" && model !== "" && model !== callId) ids.push(model);
1313
1061
  return ids;
1314
1062
  }
1315
- __name(idsOf, "idsOf");
1316
1063
  function bucketFor(e, seen) {
1317
1064
  if (e.type === "tool_call") return seen.started;
1318
1065
  if (e.type === "tool_result") return seen.completed;
1319
1066
  return void 0;
1320
1067
  }
1321
- __name(bucketFor, "bucketFor");
1322
1068
  function dedupeTools(events, raw, seen) {
1323
1069
  return events.filter((e) => {
1324
1070
  if (e.type === "thinking") {
@@ -1335,19 +1081,15 @@ function dedupeTools(events, raw, seen) {
1335
1081
  return true;
1336
1082
  });
1337
1083
  }
1338
- __name(dedupeTools, "dedupeTools");
1339
1084
  function createToolSeen() {
1340
- return {
1341
- started: /* @__PURE__ */ new Set(),
1342
- completed: /* @__PURE__ */ new Set(),
1343
- sawThinkingDelta: false
1344
- };
1085
+ return { started: /* @__PURE__ */ new Set(), completed: /* @__PURE__ */ new Set(), sawThinkingDelta: false };
1345
1086
  }
1346
- __name(createToolSeen, "createToolSeen");
1347
1087
  function translateTimelineEvent(ev, runId, seen) {
1348
1088
  if (ev.kind === "delta") {
1349
1089
  if (ev.update === void 0) return [];
1350
- const events2 = translateInteractionUpdate(ev.update);
1090
+ const events2 = translateInteractionUpdate(
1091
+ ev.update
1092
+ );
1351
1093
  return dedupeTools(events2, ev.update, seen);
1352
1094
  }
1353
1095
  if (ev.message === void 0) return [];
@@ -1355,7 +1097,6 @@ function translateTimelineEvent(ev, runId, seen) {
1355
1097
  const kept = ev.textAlreadyStreamed === true ? events.filter((e) => e.type !== "text_delta") : events;
1356
1098
  return dedupeTools(kept, ev.message, seen);
1357
1099
  }
1358
- __name(translateTimelineEvent, "translateTimelineEvent");
1359
1100
 
1360
1101
  // src/bridge/tool-dialect-stripper.ts
1361
1102
  var OPEN2 = "<function=";
@@ -1367,12 +1108,11 @@ function heldPrefixLength2(s, delim) {
1367
1108
  }
1368
1109
  return 0;
1369
1110
  }
1370
- __name(heldPrefixLength2, "heldPrefixLength");
1371
1111
  function createToolDialectStripper() {
1372
1112
  let mode = "text";
1373
1113
  let buffer = "";
1374
1114
  let pendingLeak = "";
1375
- const write = /* @__PURE__ */ __name((chunk) => {
1115
+ const write = (chunk) => {
1376
1116
  buffer += chunk;
1377
1117
  const out = [];
1378
1118
  for (; ; ) {
@@ -1380,10 +1120,7 @@ function createToolDialectStripper() {
1380
1120
  const idx2 = buffer.indexOf(OPEN2);
1381
1121
  if (idx2 !== -1) {
1382
1122
  const content = buffer.slice(0, idx2);
1383
- if (content) out.push({
1384
- kind: "text",
1385
- content
1386
- });
1123
+ if (content) out.push({ kind: "text", content });
1387
1124
  pendingLeak = OPEN2;
1388
1125
  buffer = buffer.slice(idx2 + OPEN2.length);
1389
1126
  mode = "stripping";
@@ -1391,10 +1128,7 @@ function createToolDialectStripper() {
1391
1128
  }
1392
1129
  const keep2 = heldPrefixLength2(buffer, OPEN2);
1393
1130
  const emit = buffer.slice(0, buffer.length - keep2);
1394
- if (emit) out.push({
1395
- kind: "text",
1396
- content: emit
1397
- });
1131
+ if (emit) out.push({ kind: "text", content: emit });
1398
1132
  buffer = buffer.slice(buffer.length - keep2);
1399
1133
  break;
1400
1134
  }
@@ -1411,34 +1145,22 @@ function createToolDialectStripper() {
1411
1145
  break;
1412
1146
  }
1413
1147
  return out;
1414
- }, "write");
1415
- const end = /* @__PURE__ */ __name(() => {
1148
+ };
1149
+ const end = () => {
1416
1150
  const leftover = mode === "stripping" ? pendingLeak + buffer : buffer;
1417
1151
  buffer = "";
1418
1152
  pendingLeak = "";
1419
- return leftover ? [
1420
- {
1421
- kind: "text",
1422
- content: leftover
1423
- }
1424
- ] : [];
1425
- }, "end");
1426
- return {
1427
- write,
1428
- end
1153
+ return leftover ? [{ kind: "text", content: leftover }] : [];
1429
1154
  };
1155
+ return { write, end };
1430
1156
  }
1431
- __name(createToolDialectStripper, "createToolDialectStripper");
1432
1157
  async function* stripToolDialectStream(source) {
1433
1158
  const stripper = createToolDialectStripper();
1434
1159
  try {
1435
1160
  for await (const event of source) {
1436
1161
  if (event.type === "text_delta" && typeof event.content === "string") {
1437
1162
  for (const seg of stripper.write(event.content)) {
1438
- yield {
1439
- type: "text_delta",
1440
- content: seg.content
1441
- };
1163
+ yield { type: "text_delta", content: seg.content };
1442
1164
  }
1443
1165
  } else {
1444
1166
  yield event;
@@ -1446,37 +1168,26 @@ async function* stripToolDialectStream(source) {
1446
1168
  }
1447
1169
  } finally {
1448
1170
  for (const seg of stripper.end()) {
1449
- yield {
1450
- type: "text_delta",
1451
- content: seg.content
1452
- };
1171
+ yield { type: "text_delta", content: seg.content };
1453
1172
  }
1454
1173
  }
1455
1174
  }
1456
- __name(stripToolDialectStream, "stripToolDialectStream");
1457
1175
 
1458
1176
  // src/bridge/sdk-adapter.ts
1459
1177
  function withLeakedDialectRecovery(providers) {
1460
1178
  return {
1461
1179
  ...providers,
1462
- routes: providers.routes.map((route) => ({
1463
- ...route,
1464
- extractToolCallsFromContent: true
1465
- }))
1180
+ routes: providers.routes.map((route) => ({ ...route, extractToolCallsFromContent: true }))
1466
1181
  };
1467
1182
  }
1468
- __name(withLeakedDialectRecovery, "withLeakedDialectRecovery");
1469
1183
  function buildExtraCreateOptions(overrides, compiled) {
1470
1184
  const recoverLeakedToolCalls = overrides.recoverLeakedToolCalls ?? compiled.recoverLeakedToolCalls ?? false;
1471
1185
  const extra = {};
1472
1186
  if (overrides.plugins !== void 0) {
1473
- const asArray = /* @__PURE__ */ __name((v) => Array.isArray(v) ? v : void 0, "asArray");
1187
+ const asArray = (v) => Array.isArray(v) ? v : void 0;
1474
1188
  const overrideList = asArray(overrides.plugins);
1475
1189
  const compiledList = asArray(compiled.plugins);
1476
- extra.plugins = overrideList !== void 0 && compiledList !== void 0 ? [
1477
- ...compiledList,
1478
- ...overrideList
1479
- ] : overrides.plugins;
1190
+ extra.plugins = overrideList !== void 0 && compiledList !== void 0 ? [...compiledList, ...overrideList] : overrides.plugins;
1480
1191
  }
1481
1192
  if (overrides.providers !== void 0) {
1482
1193
  extra.providers = recoverLeakedToolCalls ? withLeakedDialectRecovery(overrides.providers) : overrides.providers;
@@ -1485,7 +1196,6 @@ function buildExtraCreateOptions(overrides, compiled) {
1485
1196
  if (overrides.budgetTracker !== void 0) extra.budgetTracker = overrides.budgetTracker;
1486
1197
  return extra;
1487
1198
  }
1488
- __name(buildExtraCreateOptions, "buildExtraCreateOptions");
1489
1199
  async function loadSdkRuntime() {
1490
1200
  try {
1491
1201
  const sdk = await import("@theokit/sdk");
@@ -1495,40 +1205,30 @@ async function loadSdkRuntime() {
1495
1205
  // `.bind` keeps the static factory callable when detached from `sdk.Tool` (it takes no `this`,
1496
1206
  // but binding is explicit + satisfies unbound-method rather than relying on that).
1497
1207
  defineTool: sdk.Tool.create.bind(sdk.Tool),
1498
- ...skillReadTool ? {
1499
- defineSkillReadTool: /* @__PURE__ */ __name((skills) => skillReadTool.create(skills), "defineSkillReadTool")
1500
- } : {}
1208
+ ...skillReadTool ? { defineSkillReadTool: (skills) => skillReadTool.create(skills) } : {}
1501
1209
  };
1502
1210
  } catch (err) {
1503
1211
  console.warn("[theokit] @theokit/sdk import failed:", err);
1504
1212
  return null;
1505
1213
  }
1506
1214
  }
1507
- __name(loadSdkRuntime, "loadSdkRuntime");
1508
1215
  function resolveTextTransformFlags(compiled, overrides) {
1509
1216
  return {
1510
1217
  parseThinkTags: overrides.parseThinkTags ?? compiled.parseThinkTags ?? false,
1511
1218
  stripToolDialect: overrides.stripToolDialect ?? compiled.stripToolDialect ?? false
1512
1219
  };
1513
1220
  }
1514
- __name(resolveTextTransformFlags, "resolveTextTransformFlags");
1515
1221
  function applyTextTransforms(events, opts) {
1516
1222
  let out = opts.parseThinkTags ? extractThinkTagStream(events) : events;
1517
1223
  if (opts.stripToolDialect) out = stripToolDialectStream(out);
1518
1224
  return out;
1519
1225
  }
1520
- __name(applyTextTransforms, "applyTextTransforms");
1521
1226
  function hasZodInputSchema(schema) {
1522
1227
  return typeof schema?.parse === "function";
1523
1228
  }
1524
- __name(hasZodInputSchema, "hasZodInputSchema");
1525
1229
  function withRunContext(handler, runContext) {
1526
- return (input, ctx) => handler(input, {
1527
- ...ctx,
1528
- context: runContext
1529
- });
1230
+ return (input, ctx) => handler(input, { ...ctx, context: runContext });
1530
1231
  }
1531
- __name(withRunContext, "withRunContext");
1532
1232
  function buildSdkTools(compiledTools, defineTool, extraSdkTools = [], runContext) {
1533
1233
  const has = runContext !== void 0;
1534
1234
  return [
@@ -1541,25 +1241,20 @@ function buildSdkTools(compiledTools, defineTool, extraSdkTools = [], runContext
1541
1241
  handler: has ? withRunContext(t.handler, runContext) : t.handler
1542
1242
  });
1543
1243
  }
1544
- return has ? {
1545
- ...t,
1546
- handler: withRunContext(t.handler, runContext)
1547
- } : t;
1244
+ return has ? { ...t, handler: withRunContext(t.handler, runContext) } : t;
1548
1245
  }),
1549
- ...extraSdkTools.map((t) => has ? {
1550
- ...t,
1551
- handler: withRunContext(t.handler, runContext)
1552
- } : t)
1246
+ ...extraSdkTools.map(
1247
+ (t) => has ? { ...t, handler: withRunContext(t.handler, runContext) } : t
1248
+ )
1553
1249
  ];
1554
1250
  }
1555
- __name(buildSdkTools, "buildSdkTools");
1556
- var resolverApiKey = /* @__PURE__ */ __name(async (k) => typeof k === "function" ? await k() : k, "resolverApiKey");
1251
+ var resolverApiKey = async (k) => typeof k === "function" ? await k() : k;
1557
1252
  function createSdkAgentStream(compiled, compiledTools, apiKey, overrides = {}) {
1558
1253
  const model = overrides.model ?? compiled.model ?? "openai/gpt-4o-mini";
1559
1254
  const reasoningEffort = overrides.reasoningEffort ?? compiled.reasoningEffort;
1560
1255
  const { parseThinkTags, stripToolDialect } = resolveTextTransformFlags(compiled, overrides);
1561
1256
  const runContext = overrides.runContext ?? compiled.runContext;
1562
- const factory = /* @__PURE__ */ __name((message, sessionId, factoryOpts) => ({
1257
+ const factory = (message, sessionId, factoryOpts) => ({
1563
1258
  async *[Symbol.asyncIterator]() {
1564
1259
  const runId = `run-${Date.now()}`;
1565
1260
  const t0 = Date.now();
@@ -1608,24 +1303,27 @@ function createSdkAgentStream(compiled, compiledTools, apiKey, overrides = {}) {
1608
1303
  yield eventoDeErroDoSdk(err);
1609
1304
  }
1610
1305
  }
1611
- }), "factory");
1612
- return Object.assign(factory, {
1613
- resolvedModel: model
1614
1306
  });
1307
+ return Object.assign(factory, { resolvedModel: model });
1615
1308
  }
1616
- __name(createSdkAgentStream, "createSdkAgentStream");
1617
1309
  async function* streamSdkAgent(rt, compiled, sdkTools, opts) {
1618
1310
  const { Agent } = rt;
1619
- const { apiKey, model, reasoningEffort, overrides, parseThinkTags, stripToolDialect, sessionId, message, factoryOpts, runId, t0 } = opts;
1311
+ const {
1312
+ apiKey,
1313
+ model,
1314
+ reasoningEffort,
1315
+ overrides,
1316
+ parseThinkTags,
1317
+ stripToolDialect,
1318
+ sessionId,
1319
+ message,
1320
+ factoryOpts,
1321
+ runId,
1322
+ t0
1323
+ } = opts;
1620
1324
  const { options: m8, applied } = assembleM8CreateOptions(compiled);
1621
- if (overrides.cwd !== void 0) m8.local = {
1622
- ...m8.local,
1623
- cwd: overrides.cwd
1624
- };
1625
- if (overrides.baseDir !== void 0) m8.local = {
1626
- ...m8.local,
1627
- baseDir: overrides.baseDir
1628
- };
1325
+ if (overrides.cwd !== void 0) m8.local = { ...m8.local, cwd: overrides.cwd };
1326
+ if (overrides.baseDir !== void 0) m8.local = { ...m8.local, baseDir: overrides.baseDir };
1629
1327
  const extra = buildExtraCreateOptions(overrides, compiled);
1630
1328
  if (applied.length > 0) {
1631
1329
  debugLog("[THEO_AGENT_M8_RUNTIME_APPLIED]", {
@@ -1642,19 +1340,13 @@ async function* streamSdkAgent(rt, compiled, sdkTools, opts) {
1642
1340
  ...extra
1643
1341
  });
1644
1342
  try {
1645
- const state = {
1646
- sawError: false,
1647
- lastEventType: ""
1648
- };
1343
+ const state = { sawError: false, lastEventType: "" };
1649
1344
  const sendOptions = {};
1650
1345
  if (factoryOpts?.disableTools === true) sendOptions.toolChoice = "none";
1651
1346
  if (overrides.onRunEvent !== void 0) sendOptions.onRunEvent = overrides.onRunEvent;
1652
- const sendInput = overrides.images && overrides.images.length > 0 ? {
1653
- text: message,
1654
- images: overrides.images
1655
- } : message;
1347
+ const sendInput = overrides.images && overrides.images.length > 0 ? { text: message, images: overrides.images } : message;
1656
1348
  const sendPromise = agent.send(sendInput, sendOptions);
1657
- const timeline = /* @__PURE__ */ __name(async function* () {
1349
+ const timeline = async function* () {
1658
1350
  const run = await sendPromise;
1659
1351
  const seen = createToolSeen();
1660
1352
  for await (const ev of run.events()) {
@@ -1665,7 +1357,7 @@ async function* streamSdkAgent(rt, compiled, sdkTools, opts) {
1665
1357
  yield event;
1666
1358
  }
1667
1359
  }
1668
- }, "timeline");
1360
+ };
1669
1361
  for await (const event of applyTextTransforms(timeline(), {
1670
1362
  parseThinkTags,
1671
1363
  stripToolDialect
@@ -1688,7 +1380,6 @@ async function* streamSdkAgent(rt, compiled, sdkTools, opts) {
1688
1380
  await agent.dispose();
1689
1381
  }
1690
1382
  }
1691
- __name(streamSdkAgent, "streamSdkAgent");
1692
1383
  function toAgentFactory(def, opts) {
1693
1384
  const overrides = opts.overrides ?? {};
1694
1385
  const projetarPorSessao = resolverProjecao(def, overrides);
@@ -1696,7 +1387,9 @@ function toAgentFactory(def, opts) {
1696
1387
  const { compiled, model, reasoningEffort, runContext } = await projetarPorSessao(sessionId);
1697
1388
  const rt = await loadSdkRuntime();
1698
1389
  if (!rt) {
1699
- throw new Error("[@theokit/agents] @theokit/sdk is not installed \u2014 run: pnpm add @theokit/sdk");
1390
+ throw new Error(
1391
+ "[@theokit/agents] @theokit/sdk is not installed \u2014 run: pnpm add @theokit/sdk"
1392
+ );
1700
1393
  }
1701
1394
  const sdkTools = buildSdkTools(compiled.tools, rt.defineTool, overrides.sdkTools, runContext);
1702
1395
  const inlineSkills = compiled.skills?.inline;
@@ -1704,14 +1397,8 @@ function toAgentFactory(def, opts) {
1704
1397
  sdkTools.push(rt.defineSkillReadTool(inlineSkills));
1705
1398
  }
1706
1399
  const { options: m8 } = assembleM8CreateOptions(compiled);
1707
- if (overrides.cwd !== void 0) m8.local = {
1708
- ...m8.local,
1709
- cwd: overrides.cwd
1710
- };
1711
- if (overrides.baseDir !== void 0) m8.local = {
1712
- ...m8.local,
1713
- baseDir: overrides.baseDir
1714
- };
1400
+ if (overrides.cwd !== void 0) m8.local = { ...m8.local, cwd: overrides.cwd };
1401
+ if (overrides.baseDir !== void 0) m8.local = { ...m8.local, baseDir: overrides.baseDir };
1715
1402
  const extra = buildExtraCreateOptions(overrides, compiled);
1716
1403
  aplicarPostura(extra, m8, opts.approvals, compiled.hitl);
1717
1404
  const agent = await rt.Agent.getOrCreate(sessionId, {
@@ -1724,53 +1411,37 @@ function toAgentFactory(def, opts) {
1724
1411
  return withGuardrails(agent, compiled.guardrails);
1725
1412
  };
1726
1413
  }
1727
- __name(toAgentFactory, "toAgentFactory");
1728
1414
  function withGuardrails(handle, guardrails) {
1729
1415
  if (guardrails === void 0 || guardrails.length === 0) return handle;
1730
1416
  return {
1731
1417
  get agentId() {
1732
1418
  return handle.agentId;
1733
1419
  },
1734
- dispose: /* @__PURE__ */ __name(() => handle.dispose(), "dispose"),
1735
- send: /* @__PURE__ */ __name(async (msg, sendOpts) => {
1420
+ dispose: () => handle.dispose(),
1421
+ send: async (msg, sendOpts) => {
1736
1422
  const guarded = await runInputGuards(msg, guardrails);
1737
1423
  const turn = await handle.send(guarded, sendOpts);
1738
1424
  return {
1739
- wait: /* @__PURE__ */ __name(async () => {
1425
+ wait: async () => {
1740
1426
  const out = await turn.wait();
1741
1427
  if (out.result === void 0) return out;
1742
- return {
1743
- ...out,
1744
- result: await runOutputGuards(out.result, guardrails)
1745
- };
1746
- }, "wait")
1428
+ return { ...out, result: await runOutputGuards(out.result, guardrails) };
1429
+ }
1747
1430
  };
1748
- }, "send")
1431
+ }
1749
1432
  };
1750
1433
  }
1751
- __name(withGuardrails, "withGuardrails");
1752
1434
 
1753
1435
  // src/bridge/present-ui-message-stream.ts
1754
1436
  import { UIMessageStreamPresenter } from "@theokit/presenter";
1755
1437
  function toAgentOutputEvent(e) {
1756
1438
  switch (e.type) {
1757
1439
  case "text_delta":
1758
- return {
1759
- type: "text",
1760
- text: e.content
1761
- };
1440
+ return { type: "text", text: e.content };
1762
1441
  case "thinking":
1763
- return {
1764
- type: "reasoning",
1765
- text: e.content
1766
- };
1442
+ return { type: "reasoning", text: e.content };
1767
1443
  case "tool_call":
1768
- return {
1769
- type: "tool-call",
1770
- callId: e.callId,
1771
- name: e.toolName,
1772
- input: e.input
1773
- };
1444
+ return { type: "tool-call", callId: e.callId, name: e.toolName, input: e.input };
1774
1445
  case "tool_result":
1775
1446
  return {
1776
1447
  type: "tool-result",
@@ -1783,40 +1454,20 @@ function toAgentOutputEvent(e) {
1783
1454
  return null;
1784
1455
  }
1785
1456
  }
1786
- __name(toAgentOutputEvent, "toAgentOutputEvent");
1787
1457
  function doneToMetadata(event) {
1788
- return event.cost === void 0 ? {
1789
- usage: event.usage,
1790
- durationMs: event.durationMs
1791
- } : {
1792
- usage: event.usage,
1793
- durationMs: event.durationMs,
1794
- cost: event.cost
1795
- };
1458
+ return event.cost === void 0 ? { usage: event.usage, durationMs: event.durationMs } : { usage: event.usage, durationMs: event.durationMs, cost: event.cost };
1796
1459
  }
1797
- __name(doneToMetadata, "doneToMetadata");
1798
1460
  var ERROR_CODE_DATA_PART = "data-error-code";
1799
1461
  var INPUT_REQUESTED_DATA_PART = "data-input-requested";
1800
1462
  var TASK_PROGRESS_DATA_PART = "data-task-progress";
1801
1463
  var SHELL_OUTPUT_DATA_PART = "data-shell-output";
1802
1464
  function dataPart(type, data) {
1803
- return {
1804
- type,
1805
- data,
1806
- transient: true
1807
- };
1465
+ return { type, data, transient: true };
1808
1466
  }
1809
- __name(dataPart, "dataPart");
1810
1467
  function* errorChunks(errorText, code) {
1811
- if (code !== void 0) yield dataPart(ERROR_CODE_DATA_PART, {
1812
- code
1813
- });
1814
- yield {
1815
- type: "error",
1816
- errorText
1817
- };
1468
+ if (code !== void 0) yield dataPart(ERROR_CODE_DATA_PART, { code });
1469
+ yield { type: "error", errorText };
1818
1470
  }
1819
- __name(errorChunks, "errorChunks");
1820
1471
  function diagnosticDataPart(event) {
1821
1472
  switch (event.type) {
1822
1473
  case "checkpoint_saved":
@@ -1829,34 +1480,21 @@ function diagnosticDataPart(event) {
1829
1480
  // catch-all, which is the reported defect one layer down: translating an event and never
1830
1481
  // presenting it leaves the consumer just as blind, minus even the warning.
1831
1482
  case "input_requested":
1832
- return dataPart(INPUT_REQUESTED_DATA_PART, {
1833
- requestId: event.requestId
1834
- });
1483
+ return dataPart(INPUT_REQUESTED_DATA_PART, { requestId: event.requestId });
1835
1484
  case "task_progress":
1836
1485
  return dataPart(TASK_PROGRESS_DATA_PART, {
1837
- ...event.status !== void 0 ? {
1838
- status: event.status
1839
- } : {},
1840
- ...event.text !== void 0 ? {
1841
- text: event.text
1842
- } : {}
1486
+ ...event.status !== void 0 ? { status: event.status } : {},
1487
+ ...event.text !== void 0 ? { text: event.text } : {}
1843
1488
  });
1844
1489
  case "shell_output":
1845
- return dataPart(SHELL_OUTPUT_DATA_PART, {
1846
- event: event.event
1847
- });
1490
+ return dataPart(SHELL_OUTPUT_DATA_PART, { event: event.event });
1848
1491
  default:
1849
1492
  return null;
1850
1493
  }
1851
1494
  }
1852
- __name(diagnosticDataPart, "diagnosticDataPart");
1853
1495
  async function* presentUIMessageStream(events, opts) {
1854
- const presenter = new UIMessageStreamPresenter({
1855
- textId: opts.textId
1856
- });
1857
- yield {
1858
- type: "start"
1859
- };
1496
+ const presenter = new UIMessageStreamPresenter({ textId: opts.textId });
1497
+ yield { type: "start" };
1860
1498
  let turnMetadata;
1861
1499
  try {
1862
1500
  for await (const event of events) {
@@ -1877,11 +1515,7 @@ async function* presentUIMessageStream(events, opts) {
1877
1515
  dynamic: true
1878
1516
  };
1879
1517
  }
1880
- yield {
1881
- type: "tool-approval-request",
1882
- approvalId: event.callId,
1883
- toolCallId: event.callId
1884
- };
1518
+ yield { type: "tool-approval-request", approvalId: event.callId, toolCallId: event.callId };
1885
1519
  continue;
1886
1520
  }
1887
1521
  const diagnostic = diagnosticDataPart(event);
@@ -1905,105 +1539,46 @@ async function* presentUIMessageStream(events, opts) {
1905
1539
  }
1906
1540
  yield* presenter.finish(turnMetadata);
1907
1541
  }
1908
- __name(presentUIMessageStream, "presentUIMessageStream");
1909
1542
 
1910
1543
  // src/bridge/agent-builder.ts
1911
1544
  var ContextualTool = {
1912
1545
  /**
1913
- * Tag a {@link CustomTool} with a literal name (so `.tool()` can accumulate the tool-name union)
1914
- * and, optionally, a required run-context type. The `requiredContext` argument is a type-only
1915
- * witness — pass `undefined as C` or a sample value; it is never read at runtime.
1916
- */
1546
+ * Tag a {@link CustomTool} with a literal name (so `.tool()` can accumulate the tool-name union)
1547
+ * and, optionally, a required run-context type. The `requiredContext` argument is a type-only
1548
+ * witness — pass `undefined as C` or a sample value; it is never read at runtime.
1549
+ */
1917
1550
  of(tool, _requiredContext) {
1918
1551
  return tool;
1919
1552
  }
1920
1553
  };
1921
1554
  function makeBuilder(config) {
1922
1555
  const runtime = {
1923
- input: /* @__PURE__ */ __name((schema) => makeBuilder({
1924
- ...config,
1925
- input: schema
1926
- }), "input"),
1927
- model: /* @__PURE__ */ __name((id) => makeBuilder({
1928
- ...config,
1929
- model: id
1930
- }), "model"),
1931
- system: /* @__PURE__ */ __name((prompt) => makeBuilder({
1932
- ...config,
1933
- system: prompt
1934
- }), "system"),
1935
- reasoningEffort: /* @__PURE__ */ __name((effort) => makeBuilder({
1936
- ...config,
1937
- reasoningEffort: effort
1938
- }), "reasoningEffort"),
1939
- context: /* @__PURE__ */ __name((value) => makeBuilder({
1940
- ...config,
1941
- context: value
1942
- }), "context"),
1943
- tool: /* @__PURE__ */ __name((tool) => makeBuilder({
1944
- ...config,
1945
- tools: [
1946
- ...config.tools ?? [],
1947
- tool
1948
- ]
1949
- }), "tool"),
1950
- guardrail: /* @__PURE__ */ __name((g) => makeBuilder({
1951
- ...config,
1952
- guardrails: [
1953
- ...config.guardrails ?? [],
1954
- g
1955
- ]
1956
- }), "guardrail"),
1957
- guardrails: /* @__PURE__ */ __name((gs) => makeBuilder({
1958
- ...config,
1959
- guardrails: gs
1960
- }), "guardrails"),
1961
- approval: /* @__PURE__ */ __name((toolName, options) => makeBuilder({
1962
- ...config,
1963
- approvals: {
1964
- ...config.approvals ?? {},
1965
- [toolName]: options
1966
- }
1967
- }), "approval"),
1968
- approvals: /* @__PURE__ */ __name((map) => makeBuilder({
1969
- ...config,
1970
- approvals: map
1971
- }), "approvals"),
1972
- skills: /* @__PURE__ */ __name((selection) => makeBuilder({
1973
- ...config,
1974
- skills: selection
1975
- }), "skills"),
1976
- settingSources: /* @__PURE__ */ __name((sources) => makeBuilder({
1977
- ...config,
1978
- settingSources: sources
1979
- }), "settingSources"),
1980
- memory: /* @__PURE__ */ __name((settings) => makeBuilder({
1981
- ...config,
1982
- memory: settings
1983
- }), "memory"),
1984
- hooks: /* @__PURE__ */ __name((map) => makeBuilder({
1985
- ...config,
1986
- hooks: map
1987
- }), "hooks"),
1988
- plugins: /* @__PURE__ */ __name((list) => makeBuilder({
1989
- ...config,
1990
- plugins: list
1991
- }), "plugins"),
1992
- mcp: /* @__PURE__ */ __name((servers) => makeBuilder({
1993
- ...config,
1994
- mcpServers: servers
1995
- }), "mcp"),
1996
- use: /* @__PURE__ */ __name((preset) => preset(runtime), "use"),
1997
- build: /* @__PURE__ */ __name(() => defineAgent(config), "build")
1556
+ input: (schema) => makeBuilder({ ...config, input: schema }),
1557
+ model: (id) => makeBuilder({ ...config, model: id }),
1558
+ system: (prompt) => makeBuilder({ ...config, system: prompt }),
1559
+ reasoningEffort: (effort) => makeBuilder({ ...config, reasoningEffort: effort }),
1560
+ context: (value) => makeBuilder({ ...config, context: value }),
1561
+ tool: (tool) => makeBuilder({ ...config, tools: [...config.tools ?? [], tool] }),
1562
+ guardrail: (g) => makeBuilder({ ...config, guardrails: [...config.guardrails ?? [], g] }),
1563
+ guardrails: (gs) => makeBuilder({ ...config, guardrails: gs }),
1564
+ approval: (toolName, options) => makeBuilder({ ...config, approvals: { ...config.approvals ?? {}, [toolName]: options } }),
1565
+ approvals: (map) => makeBuilder({ ...config, approvals: map }),
1566
+ skills: (selection) => makeBuilder({ ...config, skills: selection }),
1567
+ settingSources: (sources) => makeBuilder({ ...config, settingSources: sources }),
1568
+ memory: (settings) => makeBuilder({ ...config, memory: settings }),
1569
+ hooks: (map) => makeBuilder({ ...config, hooks: map }),
1570
+ plugins: (list) => makeBuilder({ ...config, plugins: list }),
1571
+ mcp: (servers) => makeBuilder({ ...config, mcpServers: servers }),
1572
+ use: (preset) => preset(runtime),
1573
+ build: () => defineAgent(config)
1998
1574
  };
1999
1575
  return runtime;
2000
1576
  }
2001
- __name(makeBuilder, "makeBuilder");
2002
1577
  var AgentBuilder = {
2003
1578
  /**
2004
- * Start a fluent agent definition. Chain `.model()` (required) + `.context()` / `.system()` /
2005
- * `.input()` / `.tool()` / `.use()`, then `.build()` to get the branded {@link AgentDefinition}.
2006
- */
1579
+ * Start a fluent agent definition. Chain `.model()` (required) + `.context()` / `.system()` /
1580
+ * `.input()` / `.tool()` / `.use()`, then `.build()` to get the branded {@link AgentDefinition}.
1581
+ */
2007
1582
  create() {
2008
1583
  return makeBuilder({});
2009
1584
  }
@@ -2011,11 +1586,10 @@ var AgentBuilder = {
2011
1586
 
2012
1587
  // src/bridge/agent-endpoint.ts
2013
1588
  var AgentDefinitionError = class extends Error {
2014
- static {
2015
- __name(this, "AgentDefinitionError");
2016
- }
2017
1589
  constructor(source) {
2018
- super(`[@theokit/agents] ${source}: an agents/ file must default-export a defineAgent(...) value or an @Agent-decorated class.`);
1590
+ super(
1591
+ `[@theokit/agents] ${source}: an agents/ file must default-export a defineAgent(...) value or an @Agent-decorated class.`
1592
+ );
2019
1593
  this.name = "AgentDefinitionError";
2020
1594
  }
2021
1595
  };
@@ -2025,13 +1599,11 @@ function extractDefaultExport(mod) {
2025
1599
  }
2026
1600
  return mod;
2027
1601
  }
2028
- __name(extractDefaultExport, "extractDefaultExport");
2029
1602
  function isCompiledAgentOptions(value) {
2030
1603
  if (typeof value !== "object" || value === null) return false;
2031
1604
  const v = value;
2032
1605
  return Array.isArray(v.tools) && typeof v.agents === "object" && v.agents !== null;
2033
1606
  }
2034
- __name(isCompiledAgentOptions, "isCompiledAgentOptions");
2035
1607
  function compileAgentModule(mod, source = "agent module") {
2036
1608
  const def = extractDefaultExport(mod);
2037
1609
  if (isAgentDefinition(def)) {
@@ -2040,33 +1612,22 @@ function compileAgentModule(mod, source = "agent module") {
2040
1612
  if (isCompiledAgentOptions(def)) return def;
2041
1613
  throw new AgentDefinitionError(source);
2042
1614
  }
2043
- __name(compileAgentModule, "compileAgentModule");
2044
1615
  async function* asAgentStream(events) {
2045
1616
  for await (const e of events) yield e;
2046
1617
  }
2047
- __name(asAgentStream, "asAgentStream");
2048
- var EventQueue = class EventQueue2 {
2049
- static {
2050
- __name(this, "EventQueue");
2051
- }
1618
+ var EventQueue = class {
2052
1619
  #items = [];
2053
1620
  #resolvers = [];
2054
1621
  #closed = false;
2055
1622
  push(item) {
2056
1623
  if (this.#closed) return;
2057
1624
  const r = this.#resolvers.shift();
2058
- if (r) r({
2059
- value: item,
2060
- done: false
2061
- });
1625
+ if (r) r({ value: item, done: false });
2062
1626
  else this.#items.push(item);
2063
1627
  }
2064
1628
  close() {
2065
1629
  this.#closed = true;
2066
- for (const r of this.#resolvers.splice(0)) r({
2067
- value: void 0,
2068
- done: true
2069
- });
1630
+ for (const r of this.#resolvers.splice(0)) r({ value: void 0, done: true });
2070
1631
  }
2071
1632
  async *drain() {
2072
1633
  for (; ; ) {
@@ -2083,12 +1644,12 @@ var EventQueue = class EventQueue2 {
2083
1644
  };
2084
1645
  async function* appendCheckpointSaved(source, sessionId) {
2085
1646
  let emitted = false;
2086
- const checkpoint = /* @__PURE__ */ __name(() => ({
1647
+ const checkpoint = () => ({
2087
1648
  type: "checkpoint_saved",
2088
1649
  checkpointId: crypto.randomUUID(),
2089
1650
  step: 0,
2090
1651
  resumeToken: sessionId
2091
- }), "checkpoint");
1652
+ });
2092
1653
  for await (const ev of source) {
2093
1654
  if (ev.type === "done" && !emitted) {
2094
1655
  emitted = true;
@@ -2098,7 +1659,6 @@ async function* appendCheckpointSaved(source, sessionId) {
2098
1659
  }
2099
1660
  if (!emitted) yield checkpoint();
2100
1661
  }
2101
- __name(appendCheckpointSaved, "appendCheckpointSaved");
2102
1662
  function streamAgentUIMessages(compiled, apiKey, input) {
2103
1663
  const textId = crypto.randomUUID();
2104
1664
  const overrides = {};
@@ -2108,29 +1668,34 @@ function streamAgentUIMessages(compiled, apiKey, input) {
2108
1668
  if (input.onRunEvent !== void 0) overrides.onRunEvent = input.onRunEvent;
2109
1669
  let source;
2110
1670
  if (!input.hitl || input.hitl.gated.size === 0) {
2111
- const events2 = createSdkAgentStream(compiled, compiled.tools, apiKey, overrides)(input.message, input.sessionId);
1671
+ const events2 = createSdkAgentStream(
1672
+ compiled,
1673
+ compiled.tools,
1674
+ apiKey,
1675
+ overrides
1676
+ )(input.message, input.sessionId);
2112
1677
  source = asAgentStream(events2);
2113
1678
  } else {
2114
1679
  const queue = new EventQueue();
2115
- input.signal?.addEventListener("abort", () => {
2116
- queue.close();
2117
- }, {
2118
- once: true
2119
- });
1680
+ input.signal?.addEventListener(
1681
+ "abort",
1682
+ () => {
1683
+ queue.close();
1684
+ },
1685
+ { once: true }
1686
+ );
2120
1687
  const plugin = createHitlPlugin({
2121
1688
  gated: input.hitl.gated,
2122
- emit: /* @__PURE__ */ __name((e) => {
1689
+ emit: (e) => {
2123
1690
  queue.push(e);
2124
- }, "emit"),
1691
+ },
2125
1692
  awaitApproval: input.hitl.awaitApproval
2126
1693
  });
2127
1694
  const sdkStream = createSdkAgentStream(compiled, compiled.tools, apiKey, {
2128
1695
  ...overrides,
2129
1696
  // The HITL plugin is a structural @theokit/sdk Plugin (createHitlPlugin returns the
2130
1697
  // { name, register } shape); the RuntimeOverrides.plugins union is widened at the SDK edge.
2131
- plugins: [
2132
- plugin
2133
- ]
1698
+ plugins: [plugin]
2134
1699
  })(input.message, input.sessionId);
2135
1700
  void (async () => {
2136
1701
  try {
@@ -2150,11 +1715,8 @@ function streamAgentUIMessages(compiled, apiKey, input) {
2150
1715
  }
2151
1716
  const durableCheckpoint = compiled.checkpoint?.storage === "filesystem";
2152
1717
  const events = durableCheckpoint ? appendCheckpointSaved(source, input.sessionId) : source;
2153
- return presentUIMessageStream(events, {
2154
- textId
2155
- });
1718
+ return presentUIMessageStream(events, { textId });
2156
1719
  }
2157
- __name(streamAgentUIMessages, "streamAgentUIMessages");
2158
1720
 
2159
1721
  // src/loop/compaction-strategy.ts
2160
1722
  import { compactTranscript } from "@theokit/sdk/compaction";
@@ -2165,73 +1727,56 @@ var compactionStrategyConfigSchema = z.object({
2165
1727
  keepTokens: z.number().int().positive()
2166
1728
  });
2167
1729
  function resolveCompactionStrategy(name, config) {
2168
- const cfg = compactionStrategyConfigSchema.parse({
2169
- name,
2170
- keepTokens: config.keepTokens
2171
- });
1730
+ const cfg = compactionStrategyConfigSchema.parse({ name, keepTokens: config.keepTokens });
2172
1731
  return {
2173
1732
  name: cfg.name,
2174
1733
  keepTokens: cfg.keepTokens,
2175
- compact: /* @__PURE__ */ __name((messages, options) => compactTranscript(messages, {
1734
+ compact: (messages, options) => compactTranscript(messages, {
2176
1735
  keepTokens: options?.keepTokens ?? cfg.keepTokens,
2177
1736
  summarize: options?.summarize,
2178
1737
  marker: options?.marker,
2179
1738
  summaryTemplate: options?.summaryTemplate,
2180
1739
  // Default-safe: a thrown summarize keeps the transcript (app opts out via failSafe:false).
2181
1740
  failSafe: options?.failSafe ?? true
2182
- }), "compact")
1741
+ })
2183
1742
  };
2184
1743
  }
2185
- __name(resolveCompactionStrategy, "resolveCompactionStrategy");
2186
- var tokenBudgetCompactionStrategy = resolveCompactionStrategy("token-budget", {
2187
- keepTokens: DEFAULT_KEEP_TOKENS
2188
- });
1744
+ var tokenBudgetCompactionStrategy = resolveCompactionStrategy("token-budget", { keepTokens: DEFAULT_KEEP_TOKENS });
2189
1745
 
2190
1746
  // src/loop/loop-strategy.ts
2191
1747
  import { z as z2 } from "zod";
2192
1748
  var DEFAULT_MAX_ITERATIONS = 8;
2193
1749
  var maxIterationsSchema = z2.number().int().min(1);
2194
1750
  var loopStrategyConfigSchema = z2.object({
2195
- name: z2.enum([
2196
- "simple-chat",
2197
- "plan-act-reflect",
2198
- "react"
2199
- ]),
1751
+ name: z2.enum(["simple-chat", "plan-act-reflect", "react"]),
2200
1752
  maxIterations: maxIterationsSchema
2201
1753
  });
2202
1754
  function assertValidCustomLoopStrategy(strategy) {
2203
1755
  const result = maxIterationsSchema.safeParse(strategy.maxIterations);
2204
1756
  if (!result.success) {
2205
- throw new Error(`loopStrategy: maxIterations inv\xE1lido (${String(strategy.maxIterations)}) \u2014 deve ser um inteiro finito \u2265 1 (sen\xE3o o teto round < maxIterations nunca termina)`);
1757
+ throw new Error(
1758
+ `loopStrategy: maxIterations inv\xE1lido (${String(strategy.maxIterations)}) \u2014 deve ser um inteiro finito \u2265 1 (sen\xE3o o teto round < maxIterations nunca termina)`
1759
+ );
2206
1760
  }
2207
1761
  }
2208
- __name(assertValidCustomLoopStrategy, "assertValidCustomLoopStrategy");
2209
1762
  function resolveLoopStrategy(strategy, maxIterations = DEFAULT_MAX_ITERATIONS) {
2210
- const cfg = loopStrategyConfigSchema.parse({
2211
- name: strategy,
2212
- maxIterations
2213
- });
1763
+ const cfg = loopStrategyConfigSchema.parse({ name: strategy, maxIterations });
2214
1764
  if (cfg.name === "simple-chat") {
2215
- return {
2216
- name: cfg.name,
2217
- maxIterations: cfg.maxIterations,
2218
- shouldContinue: /* @__PURE__ */ __name(() => false, "shouldContinue")
2219
- };
1765
+ return { name: cfg.name, maxIterations: cfg.maxIterations, shouldContinue: () => false };
2220
1766
  }
2221
1767
  if (cfg.name === "plan-act-reflect") {
2222
1768
  return {
2223
1769
  name: cfg.name,
2224
1770
  maxIterations: cfg.maxIterations,
2225
- shouldContinue: /* @__PURE__ */ __name((outcome) => outcome.round < cfg.maxIterations, "shouldContinue")
1771
+ shouldContinue: (outcome) => outcome.round < cfg.maxIterations
2226
1772
  };
2227
1773
  }
2228
1774
  return {
2229
1775
  name: cfg.name,
2230
1776
  maxIterations: cfg.maxIterations,
2231
- shouldContinue: /* @__PURE__ */ __name((outcome) => outcome.finishReason === "tool-calls" && outcome.round < cfg.maxIterations, "shouldContinue")
1777
+ shouldContinue: (outcome) => outcome.finishReason === "tool-calls" && outcome.round < cfg.maxIterations
2232
1778
  };
2233
1779
  }
2234
- __name(resolveLoopStrategy, "resolveLoopStrategy");
2235
1780
 
2236
1781
  // src/loop/reflection-strategy.ts
2237
1782
  import { z as z3 } from "zod";
@@ -2247,55 +1792,52 @@ var ladderReflectionStrategy = {
2247
1792
  continue: true
2248
1793
  };
2249
1794
  }
2250
- return {
2251
- continue: false
2252
- };
1795
+ return { continue: false };
2253
1796
  }
2254
1797
  };
2255
1798
  var noopReflectionStrategy = {
2256
1799
  name: "noop",
2257
1800
  reflect() {
2258
- return {
2259
- continue: true
2260
- };
1801
+ return { continue: true };
2261
1802
  }
2262
1803
  };
2263
1804
 
2264
1805
  // src/bridge/delegation-types.ts
2265
1806
  var DelegationBudgetExceededError = class extends Error {
2266
- static {
2267
- __name(this, "DelegationBudgetExceededError");
1807
+ constructor(agentName, actualCost, budgetLimit) {
1808
+ super(
1809
+ `Agent "${agentName}" exceeded budget: $${actualCost.toFixed(4)} > $${budgetLimit.toFixed(4)}`
1810
+ );
1811
+ this.agentName = agentName;
1812
+ this.actualCost = actualCost;
1813
+ this.budgetLimit = budgetLimit;
1814
+ this.name = "DelegationBudgetExceededError";
2268
1815
  }
2269
1816
  agentName;
2270
1817
  actualCost;
2271
1818
  budgetLimit;
2272
- constructor(agentName, actualCost, budgetLimit) {
2273
- super(`Agent "${agentName}" exceeded budget: $${actualCost.toFixed(4)} > $${budgetLimit.toFixed(4)}`), this.agentName = agentName, this.actualCost = actualCost, this.budgetLimit = budgetLimit;
2274
- this.name = "DelegationBudgetExceededError";
2275
- }
2276
1819
  };
2277
1820
  var BudgetExceededError = DelegationBudgetExceededError;
2278
1821
  var DelegationError = class extends Error {
2279
- static {
2280
- __name(this, "DelegationError");
2281
- }
2282
- agentName;
2283
- cause;
2284
1822
  constructor(agentName, cause) {
2285
- super(`Delegation to agent "${agentName}" failed: ${cause instanceof Error ? cause.message : String(cause)}`), this.agentName = agentName, this.cause = cause;
1823
+ super(
1824
+ `Delegation to agent "${agentName}" failed: ${cause instanceof Error ? cause.message : String(cause)}`
1825
+ );
1826
+ this.agentName = agentName;
1827
+ this.cause = cause;
2286
1828
  this.name = "DelegationError";
2287
1829
  }
1830
+ agentName;
1831
+ cause;
2288
1832
  };
2289
1833
 
2290
1834
  // src/loop/run-reflective-loop.ts
2291
1835
  function asString2(value, fallback) {
2292
1836
  return typeof value === "string" ? value : fallback;
2293
1837
  }
2294
- __name(asString2, "asString");
2295
1838
  function asNumber(value, fallback) {
2296
1839
  return typeof value === "number" ? value : fallback;
2297
1840
  }
2298
- __name(asNumber, "asNumber");
2299
1841
  var NO_PROGRESS_THRESHOLD = 2;
2300
1842
  var MAINLOOP_METRIC = "[THEO_AGENT_MAINLOOP_RUNTIME_APPLIED]";
2301
1843
  var TOOL_CALLS = "tool-calls";
@@ -2308,17 +1850,15 @@ function stableStringify(value) {
2308
1850
  const entries = Object.keys(obj).sort((a, b) => a.localeCompare(b)).map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`);
2309
1851
  return `{${entries.join(",")}}`;
2310
1852
  }
2311
- __name(stableStringify, "stableStringify");
2312
1853
  function roundSignature(toolCalls) {
2313
1854
  return toolCalls.map((tc) => `${tc.name}:${stableStringify(tc.input)}`).sort((a, b) => a.localeCompare(b)).join(",");
2314
1855
  }
2315
- __name(roundSignature, "roundSignature");
2316
1856
  function terminalReason(reflectionContinue, roundReason, round, maxIterations) {
2317
- if (reflectionContinue && roundReason === TOOL_CALLS && round >= maxIterations) return "step_limit";
1857
+ if (reflectionContinue && roundReason === TOOL_CALLS && round >= maxIterations)
1858
+ return "step_limit";
2318
1859
  if (roundReason === TOOL_CALLS) return "stop";
2319
1860
  return roundReason;
2320
1861
  }
2321
- __name(terminalReason, "terminalReason");
2322
1862
  var CONTINUE_PROMPT = "Continue from the prior turns above; finish the task and give a final answer.";
2323
1863
  function buildPrompt(round, maxIterations, message, feedback) {
2324
1864
  const hint = round === maxIterations ? `${STEP_LIMIT_HINT}
@@ -2328,16 +1868,20 @@ function buildPrompt(round, maxIterations, message, feedback) {
2328
1868
  const body = round === 1 ? message : continuation;
2329
1869
  return hint + body;
2330
1870
  }
2331
- __name(buildPrompt, "buildPrompt");
2332
1871
  async function* consumeRoundOrThrow(inputs, agentName) {
2333
1872
  try {
2334
- return yield* consumeOneRound(inputs.factory, inputs.prompt, inputs.sessionId, inputs.signal, inputs.retry);
1873
+ return yield* consumeOneRound(
1874
+ inputs.factory,
1875
+ inputs.prompt,
1876
+ inputs.sessionId,
1877
+ inputs.signal,
1878
+ inputs.retry
1879
+ );
2335
1880
  } catch (err) {
2336
1881
  if (err instanceof DelegationBudgetExceededError || err instanceof DelegationError) throw err;
2337
1882
  throw new DelegationError(agentName, err);
2338
1883
  }
2339
1884
  }
2340
- __name(consumeRoundOrThrow, "consumeRoundOrThrow");
2341
1885
  function accumulateUsage(acc, r) {
2342
1886
  acc.cost += r.cost;
2343
1887
  acc.tokens += r.tokens;
@@ -2347,25 +1891,18 @@ function accumulateUsage(acc, r) {
2347
1891
  acc.cacheReadTokens = (acc.cacheReadTokens ?? 0) + r.cacheReadTokens;
2348
1892
  acc.cacheWriteTokens = (acc.cacheWriteTokens ?? 0) + r.cacheWriteTokens;
2349
1893
  }
2350
- __name(accumulateUsage, "accumulateUsage");
2351
1894
  function finalize(acc, round, reason, strategyName) {
2352
1895
  acc.rounds = round;
2353
1896
  acc.finishReason = reason;
2354
- debugLog(MAINLOOP_METRIC, {
2355
- strategy: strategyName,
2356
- rounds: round,
2357
- terminal: reason
2358
- });
1897
+ debugLog(MAINLOOP_METRIC, { strategy: strategyName, rounds: round, terminal: reason });
2359
1898
  return acc;
2360
1899
  }
2361
- __name(finalize, "finalize");
2362
1900
  function deriveFinishReason(signals) {
2363
1901
  if (signals.sawError) return "error";
2364
1902
  if (signals.sawDone && signals.doneFinishReason === TOOL_CALLS) return TOOL_CALLS;
2365
1903
  if (signals.sawToolResult) return TOOL_CALLS;
2366
1904
  return "stop";
2367
1905
  }
2368
- __name(deriveFinishReason, "deriveFinishReason");
2369
1906
  function pushToolResult(event, r, callInputs) {
2370
1907
  const id = asString2(event.callId, "");
2371
1908
  const call = callInputs.get(id);
@@ -2378,7 +1915,6 @@ function pushToolResult(event, r, callInputs) {
2378
1915
  output: asString2(event.output, "")
2379
1916
  });
2380
1917
  }
2381
- __name(pushToolResult, "pushToolResult");
2382
1918
  function applyDone(event, r) {
2383
1919
  r.cost = asNumber(event.cost, 0);
2384
1920
  const usage = event.usage;
@@ -2389,7 +1925,6 @@ function applyDone(event, r) {
2389
1925
  r.cacheReadTokens = usage?.cacheReadTokens ?? 0;
2390
1926
  r.cacheWriteTokens = usage?.cacheWriteTokens ?? 0;
2391
1927
  }
2392
- __name(applyDone, "applyDone");
2393
1928
  function accumulateEvent(event, r, signals, callInputs) {
2394
1929
  if (event.type === "text_delta" && typeof event.content === "string") {
2395
1930
  r.responseText += event.content;
@@ -2410,28 +1945,20 @@ function accumulateEvent(event, r, signals, callInputs) {
2410
1945
  r.errorMessage = asString2(event.message, "Unknown agent error");
2411
1946
  }
2412
1947
  }
2413
- __name(accumulateEvent, "accumulateEvent");
2414
1948
  async function startRound(factory, prompt, sessionId, signal, retry) {
2415
- const open = /* @__PURE__ */ __name(async () => {
1949
+ const open = async () => {
2416
1950
  const it = factory(prompt, sessionId)[Symbol.asyncIterator]();
2417
1951
  try {
2418
- return {
2419
- it,
2420
- first: await it.next()
2421
- };
1952
+ return { it, first: await it.next() };
2422
1953
  } catch (err) {
2423
1954
  await it.return?.(void 0);
2424
1955
  throw err;
2425
1956
  }
2426
- }, "open");
1957
+ };
2427
1958
  if (!retry) return open();
2428
1959
  const { Retry } = await import("@theokit/sdk/retry");
2429
- return Retry.create(open, {
2430
- ...retry,
2431
- signal: retry.signal ?? signal
2432
- });
1960
+ return Retry.create(open, { ...retry, signal: retry.signal ?? signal });
2433
1961
  }
2434
- __name(startRound, "startRound");
2435
1962
  async function* consumeOneRound(factory, prompt, sessionId, signal, retry) {
2436
1963
  const r = {
2437
1964
  responseText: "",
@@ -2467,16 +1994,19 @@ async function* consumeOneRound(factory, prompt, sessionId, signal, retry) {
2467
1994
  r.finishReason = deriveFinishReason(signals);
2468
1995
  return r;
2469
1996
  }
2470
- __name(consumeOneRound, "consumeOneRound");
2471
1997
  function ceilingRoundFactory(factory, round, maxIterations) {
2472
1998
  if (round !== maxIterations) return factory;
2473
- return (m, s) => factory(m, s, {
2474
- disableTools: true
2475
- });
1999
+ return (m, s) => factory(m, s, { disableTools: true });
2476
2000
  }
2477
- __name(ceilingRoundFactory, "ceilingRoundFactory");
2478
2001
  async function* runReflectiveLoopStream(factory, message, sessionId, config) {
2479
- const { loop, reflection, budget = Number.POSITIVE_INFINITY, signal, agentName = loop.name, retry } = config;
2002
+ const {
2003
+ loop,
2004
+ reflection,
2005
+ budget = Number.POSITIVE_INFINITY,
2006
+ signal,
2007
+ agentName = loop.name,
2008
+ retry
2009
+ } = config;
2480
2010
  const acc = {
2481
2011
  response: "",
2482
2012
  toolCalls: [],
@@ -2497,13 +2027,10 @@ async function* runReflectiveLoopStream(factory, message, sessionId, config) {
2497
2027
  while (!signal?.aborted) {
2498
2028
  const prompt = buildPrompt(round, loop.maxIterations, message, feedback);
2499
2029
  const roundFactory = ceilingRoundFactory(factory, round, loop.maxIterations);
2500
- const r = yield* consumeRoundOrThrow({
2501
- factory: roundFactory,
2502
- prompt,
2503
- sessionId,
2504
- signal,
2505
- retry
2506
- }, agentName);
2030
+ const r = yield* consumeRoundOrThrow(
2031
+ { factory: roundFactory, prompt, sessionId, signal, retry },
2032
+ agentName
2033
+ );
2507
2034
  acc.response += r.responseText;
2508
2035
  acc.toolCalls.push(...r.toolCalls);
2509
2036
  accumulateUsage(acc, r);
@@ -2525,7 +2052,12 @@ async function* runReflectiveLoopStream(factory, message, sessionId, config) {
2525
2052
  };
2526
2053
  const reflectionResult = reflection.reflect(outcome, reflectionContext);
2527
2054
  if (!(reflectionResult.continue && loop.shouldContinue(outcome) && round < loop.maxIterations)) {
2528
- const reason = terminalReason(reflectionResult.continue, r.finishReason, round, loop.maxIterations);
2055
+ const reason = terminalReason(
2056
+ reflectionResult.continue,
2057
+ r.finishReason,
2058
+ round,
2059
+ loop.maxIterations
2060
+ );
2529
2061
  return finalize(acc, round, reason, loop.name);
2530
2062
  }
2531
2063
  feedback = reflectionResult.feedback;
@@ -2534,20 +2066,15 @@ async function* runReflectiveLoopStream(factory, message, sessionId, config) {
2534
2066
  acc.rounds = round - 1;
2535
2067
  return acc;
2536
2068
  }
2537
- __name(runReflectiveLoopStream, "runReflectiveLoopStream");
2538
2069
  async function runReflectiveLoop(factory, message, sessionId, config) {
2539
2070
  const gen = runReflectiveLoopStream(factory, message, sessionId, config);
2540
2071
  let res = await gen.next();
2541
2072
  while (!res.done) res = await gen.next();
2542
2073
  return res.value;
2543
2074
  }
2544
- __name(runReflectiveLoop, "runReflectiveLoop");
2545
2075
 
2546
2076
  // src/loop/agent-runner.ts
2547
2077
  var AgentRunner = class {
2548
- static {
2549
- __name(this, "AgentRunner");
2550
- }
2551
2078
  compiled;
2552
2079
  agentName;
2553
2080
  /** The resolved terminal-decision strategy (parity with `delegate()`). */
@@ -2557,18 +2084,18 @@ var AgentRunner = class {
2557
2084
  /** The resolved between-round reflection (default or `.reflection(custom)` override). */
2558
2085
  reflectionStrategy;
2559
2086
  /**
2560
- * Recorded streaming preference. The reflective loop currently always streams via
2561
- * the SDK `Run.stream()`; a non-streaming collect mode is future work — the flag is
2562
- * captured + exposed here, not yet branched on (honest per G10: documented, not a
2563
- * silent no-op).
2564
- */
2087
+ * Recorded streaming preference. The reflective loop currently always streams via
2088
+ * the SDK `Run.stream()`; a non-streaming collect mode is future work — the flag is
2089
+ * captured + exposed here, not yet branched on (honest per G10: documented, not a
2090
+ * silent no-op).
2091
+ */
2565
2092
  streamEnabled;
2566
2093
  /**
2567
- * V4-F: the resolved compaction strategy (from `@Compaction` or `.compaction()`),
2568
- * or `undefined` when neither is declared — compaction is opt-in (EC-4). CALLABLE
2569
- * by the app (ADR D1: `runner.compaction?.compact(messages, { summarize })`); the
2570
- * reflective loop does NOT auto-invoke it (the SDK owns per-turn context).
2571
- */
2094
+ * V4-F: the resolved compaction strategy (from `@Compaction` or `.compaction()`),
2095
+ * or `undefined` when neither is declared — compaction is opt-in (EC-4). CALLABLE
2096
+ * by the app (ADR D1: `runner.compaction?.compact(messages, { summarize })`); the
2097
+ * reflective loop does NOT auto-invoke it (the SDK owns per-turn context).
2098
+ */
2572
2099
  compaction;
2573
2100
  constructor(state) {
2574
2101
  this.compiled = state.compiled;
@@ -2584,35 +2111,41 @@ var AgentRunner = class {
2584
2111
  return new AgentRunnerBuilder(spec);
2585
2112
  }
2586
2113
  /**
2587
- * V4-D-stream: stream the agent's events LIVE across the reflective loop, returning
2588
- * the aggregated {@link DelegationResult} as the generator's return value. This is the
2589
- * on-ramp for streaming-first apps (SSE) — `runReflectiveLoopStream` yields every
2590
- * round's events before the loop terminates. `streamEnabled` is honored: when the
2591
- * builder set `.stream(false)`, callers should use {@link run} instead.
2592
- */
2114
+ * V4-D-stream: stream the agent's events LIVE across the reflective loop, returning
2115
+ * the aggregated {@link DelegationResult} as the generator's return value. This is the
2116
+ * on-ramp for streaming-first apps (SSE) — `runReflectiveLoopStream` yields every
2117
+ * round's events before the loop terminates. `streamEnabled` is honored: when the
2118
+ * builder set `.stream(false)`, callers should use {@link run} instead.
2119
+ */
2593
2120
  stream(message, opts) {
2594
2121
  const guardrails = this.compiled.guardrails;
2595
2122
  if (guardrails && guardrails.length > 0) {
2596
- const runUnguarded = /* @__PURE__ */ __name((m) => this.streamUnguarded(m, opts), "runUnguarded");
2597
- return (/* @__PURE__ */ __name(async function* guarded() {
2123
+ const runUnguarded = (m) => this.streamUnguarded(m, opts);
2124
+ return (async function* guarded() {
2598
2125
  const safe = await runInputGuards(message, guardrails);
2599
- return yield* moderateOutputStream(runUnguarded(safe), guardrails, (e) => e.type === "text_delta" && typeof e.content === "string" ? e.content : void 0);
2600
- }, "guarded"))();
2126
+ return yield* moderateOutputStream(
2127
+ runUnguarded(safe),
2128
+ guardrails,
2129
+ (e) => e.type === "text_delta" && typeof e.content === "string" ? e.content : void 0
2130
+ );
2131
+ })();
2601
2132
  }
2602
2133
  return this.streamUnguarded(message, opts);
2603
2134
  }
2604
2135
  /** The core stream path, after input guardrails have run (M9). */
2605
2136
  streamUnguarded(message, opts) {
2606
- const tools = opts.tools ? [
2607
- ...opts.tools
2608
- ] : this.compiled.tools;
2137
+ const tools = opts.tools ? [...opts.tools] : this.compiled.tools;
2609
2138
  const loop = this.resolvePerRunLoop(opts.maxIterations);
2610
2139
  const streamFactory = opts.streamFactory ?? createSdkAgentStream(this.compiled, tools, opts.apiKey, {
2611
2140
  model: opts.model,
2612
2141
  reasoningEffort: opts.reasoningEffort,
2142
+ // M1: per-run extended-thinking effort
2613
2143
  parseThinkTags: opts.parseThinkTags,
2144
+ // M2: per-run <think>-tag extraction opt-in
2614
2145
  stripToolDialect: opts.stripToolDialect,
2146
+ // theocode#32: per-run tool-dialect strip opt-in
2615
2147
  recoverLeakedToolCalls: opts.recoverLeakedToolCalls,
2148
+ // theokit#58: per-run leaked-dialect recovery opt-in
2616
2149
  cwd: opts.cwd,
2617
2150
  baseDir: opts.baseDir,
2618
2151
  plugins: opts.plugins,
@@ -2620,6 +2153,7 @@ var AgentRunner = class {
2620
2153
  agents: opts.agents,
2621
2154
  budgetTracker: opts.budgetTracker,
2622
2155
  sdkTools: opts.sdkTools
2156
+ // V4-Q: pre-built SDK tools forwarded raw
2623
2157
  });
2624
2158
  const sessionId = opts.sessionId ?? `runner-${crypto.randomUUID()}`;
2625
2159
  return runReflectiveLoopStream(streamFactory, message, sessionId, {
@@ -2629,16 +2163,17 @@ var AgentRunner = class {
2629
2163
  agentName: this.agentName,
2630
2164
  signal: opts.signal,
2631
2165
  retry: opts.retry
2166
+ // V4-P: per-round transient retry (opt-in)
2632
2167
  });
2633
2168
  }
2634
2169
  /** Run the agent to a terminal result via the shared reflective loop (collect mode). */
2635
2170
  /**
2636
- * Apply a per-call `maxIterations` override (M54 D4). A custom strategy must NOT be re-resolved by
2637
- * name — its name is outside the `z.enum`, which would throw — and its `shouldContinue` closure
2638
- * must survive; since the runner enforces the ceiling via `round < loop.maxIterations` (T1.1),
2639
- * overriding just that field bounds a custom without touching its logic. A built-in keeps the
2640
- * by-name re-resolution (zod fail-loud on `< 1`) — unchanged, zero-behavior.
2641
- */
2171
+ * Apply a per-call `maxIterations` override (M54 D4). A custom strategy must NOT be re-resolved by
2172
+ * name — its name is outside the `z.enum`, which would throw — and its `shouldContinue` closure
2173
+ * must survive; since the runner enforces the ceiling via `round < loop.maxIterations` (T1.1),
2174
+ * overriding just that field bounds a custom without touching its logic. A built-in keeps the
2175
+ * by-name re-resolution (zod fail-loud on `< 1`) — unchanged, zero-behavior.
2176
+ */
2642
2177
  resolvePerRunLoop(maxIterations) {
2643
2178
  if (maxIterations == null) return this.loopStrategy;
2644
2179
  if (this.loopStrategyIsCustom) {
@@ -2657,40 +2192,37 @@ var AgentRunner = class {
2657
2192
  }
2658
2193
  };
2659
2194
  var AgentRunnerBuilder = class {
2660
- static {
2661
- __name(this, "AgentRunnerBuilder");
2195
+ constructor(spec) {
2196
+ this.spec = spec;
2662
2197
  }
2663
2198
  spec;
2664
2199
  reflectionOverride;
2665
2200
  streamEnabled = true;
2666
2201
  compactionOverride;
2667
2202
  loopStrategyOverride;
2668
- constructor(spec) {
2669
- this.spec = spec;
2670
- }
2671
2203
  /** Override the default reflection strategy (OCP — plan Drawback #2). No arg ⇒ keep default. */
2672
2204
  reflection(strategy) {
2673
2205
  if (strategy) this.reflectionOverride = strategy;
2674
2206
  return this;
2675
2207
  }
2676
2208
  /**
2677
- * M54 — inject a custom terminal-decision strategy (the fourth OCP axis, alongside
2678
- * `.reflection()`/`.compaction()`/`streamFactory`). WINS over the strategy the spec's name would
2679
- * resolve to, exactly as `.compaction()` outranks the spec. The runner caps ANY strategy at
2680
- * `custom.maxIterations` (T1.1), so a `shouldContinue: () => true` still terminates — never an
2681
- * infinite loop.
2682
- *
2683
- * @example
2684
- * ```ts
2685
- * // Stop as soon as the confidence in the last round crosses 0.9, else run to the ceiling.
2686
- * const stopWhenConfident: LoopStrategy = {
2687
- * name: 'confident',
2688
- * maxIterations: 8,
2689
- * shouldContinue: (o) => !o.responseText.includes('confidence: high'),
2690
- * }
2691
- * AgentRunner.fromSpec(spec).loopStrategy(stopWhenConfident).build()
2692
- * ```
2693
- */
2209
+ * M54 — inject a custom terminal-decision strategy (the fourth OCP axis, alongside
2210
+ * `.reflection()`/`.compaction()`/`streamFactory`). WINS over the strategy the spec's name would
2211
+ * resolve to, exactly as `.compaction()` outranks the spec. The runner caps ANY strategy at
2212
+ * `custom.maxIterations` (T1.1), so a `shouldContinue: () => true` still terminates — never an
2213
+ * infinite loop.
2214
+ *
2215
+ * @example
2216
+ * ```ts
2217
+ * // Stop as soon as the confidence in the last round crosses 0.9, else run to the ceiling.
2218
+ * const stopWhenConfident: LoopStrategy = {
2219
+ * name: 'confident',
2220
+ * maxIterations: 8,
2221
+ * shouldContinue: (o) => !o.responseText.includes('confidence: high'),
2222
+ * }
2223
+ * AgentRunner.fromSpec(spec).loopStrategy(stopWhenConfident).build()
2224
+ * ```
2225
+ */
2694
2226
  loopStrategy(custom) {
2695
2227
  assertValidCustomLoopStrategy(custom);
2696
2228
  this.loopStrategyOverride = custom;
@@ -2702,15 +2234,12 @@ var AgentRunnerBuilder = class {
2702
2234
  return this;
2703
2235
  }
2704
2236
  /**
2705
- * V4-F: declare the compaction strategy (e.g. `.compaction('token-budget', { keepTokens: 8000 })`).
2706
- * Resolved + validated at {@link build} (EC-5 — fail-fast there, not here). This builder
2707
- * call WINS over a `@Compaction` decorator on the same agent (EC-1 — explicit override).
2708
- */
2237
+ * V4-F: declare the compaction strategy (e.g. `.compaction('token-budget', { keepTokens: 8000 })`).
2238
+ * Resolved + validated at {@link build} (EC-5 — fail-fast there, not here). This builder
2239
+ * call WINS over a `@Compaction` decorator on the same agent (EC-1 — explicit override).
2240
+ */
2709
2241
  compaction(name, options = {}) {
2710
- this.compactionOverride = {
2711
- name,
2712
- keepTokens: options.keepTokens
2713
- };
2242
+ this.compactionOverride = { name, keepTokens: options.keepTokens };
2714
2243
  return this;
2715
2244
  }
2716
2245
  /** Resolve strategies from the spec — the compile→execute boundary (no I/O). */
@@ -2721,9 +2250,7 @@ var AgentRunnerBuilder = class {
2721
2250
  const loopStrategy = this.loopStrategyOverride ?? resolveLoopStrategy(strategy, spec.maxIterations);
2722
2251
  const reflectionStrategy = this.reflectionOverride ?? (strategy === "plan-act-reflect" ? ladderReflectionStrategy : noopReflectionStrategy);
2723
2252
  const compactionDecl = this.compactionOverride ?? spec.compaction;
2724
- const compaction = compactionDecl ? resolveCompactionStrategy(compactionDecl.name, {
2725
- keepTokens: compactionDecl.keepTokens
2726
- }) : void 0;
2253
+ const compaction = compactionDecl ? resolveCompactionStrategy(compactionDecl.name, { keepTokens: compactionDecl.keepTokens }) : void 0;
2727
2254
  return new AgentRunner({
2728
2255
  compiled: spec.compiled,
2729
2256
  agentName: spec.name,
@@ -2740,18 +2267,15 @@ var AgentRunnerBuilder = class {
2740
2267
  import { runGoalLoop } from "@theokit/sdk";
2741
2268
  import { JudgeCredentialError } from "@theokit/sdk";
2742
2269
  var GoalRunner = class {
2743
- static {
2744
- __name(this, "GoalRunner");
2745
- }
2746
- agent;
2747
2270
  constructor(agent) {
2748
2271
  this.agent = agent;
2749
2272
  }
2273
+ agent;
2750
2274
  /**
2751
- * Drive `goal` to completion against the bound agent. Returns the SAME async generator `runGoalLoop`
2752
- * returns — yielding `GoalEvent`s, resolving a `GoalResult`. `deps` (judge/clock overrides) threads
2753
- * straight through; a test seam for the judge lives there, exactly as on the free function.
2754
- */
2275
+ * Drive `goal` to completion against the bound agent. Returns the SAME async generator `runGoalLoop`
2276
+ * returns — yielding `GoalEvent`s, resolving a `GoalResult`. `deps` (judge/clock overrides) threads
2277
+ * straight through; a test seam for the judge lives there, exactly as on the free function.
2278
+ */
2755
2279
  run(goal, options, deps) {
2756
2280
  return runGoalLoop(this.agent, goal, options, deps);
2757
2281
  }
@@ -2765,22 +2289,14 @@ function requireApiKey(opts, agentName) {
2765
2289
  }
2766
2290
  return apiKey;
2767
2291
  }
2768
- __name(requireApiKey, "requireApiKey");
2769
2292
  function mergeTools(parentTools, subTools) {
2770
2293
  const subToolNames = new Set(subTools.map((t) => t.name));
2771
2294
  const inherited = parentTools.filter((t) => !subToolNames.has(t.name));
2772
- return [
2773
- ...inherited,
2774
- ...subTools
2775
- ];
2295
+ return [...inherited, ...subTools];
2776
2296
  }
2777
- __name(mergeTools, "mergeTools");
2778
2297
  async function delegate(spec, message, opts = {}) {
2779
2298
  const apiKey = requireApiKey(opts, spec.name);
2780
- const effectiveMessage = opts.onDelegationStart ? await opts.onDelegationStart({
2781
- subAgent: spec.name,
2782
- input: message
2783
- }) : message;
2299
+ const effectiveMessage = opts.onDelegationStart ? await opts.onDelegationStart({ subAgent: spec.name, input: message }) : message;
2784
2300
  const { compiled } = spec;
2785
2301
  const allTools = mergeTools(opts.parentTools ?? [], compiled.tools);
2786
2302
  const budget = Math.min(opts.budget ?? Infinity, opts.parentBudgetRemaining ?? Infinity);
@@ -2794,7 +2310,10 @@ async function delegate(spec, message, opts = {}) {
2794
2310
  sdkTools: opts.sdkTools
2795
2311
  });
2796
2312
  const sessionId = opts.sessionId ?? `sub-${crypto.randomUUID()}`;
2797
- const loopStrategy = resolveLoopStrategy(spec.strategy ?? "simple-chat", opts.maxIterations ?? spec.maxIterations);
2313
+ const loopStrategy = resolveLoopStrategy(
2314
+ spec.strategy ?? "simple-chat",
2315
+ opts.maxIterations ?? spec.maxIterations
2316
+ );
2798
2317
  const reflection = opts.reflection ?? (loopStrategy.name === "plan-act-reflect" ? ladderReflectionStrategy : noopReflectionStrategy);
2799
2318
  const result = await runReflectiveLoop(streamFactory, effectiveMessage, sessionId, {
2800
2319
  loop: loopStrategy,
@@ -2803,16 +2322,13 @@ async function delegate(spec, message, opts = {}) {
2803
2322
  agentName: spec.name,
2804
2323
  signal: opts.signal,
2805
2324
  retry: opts.retry
2325
+ // V4-T: per-round transient retry (V4-P) on the delegate path
2806
2326
  });
2807
2327
  if (opts.onDelegationComplete) {
2808
- return await opts.onDelegationComplete({
2809
- subAgent: spec.name,
2810
- result
2811
- });
2328
+ return await opts.onDelegationComplete({ subAgent: spec.name, result });
2812
2329
  }
2813
2330
  return result;
2814
2331
  }
2815
- __name(delegate, "delegate");
2816
2332
 
2817
2333
  // src/bridge/api-error-handler.ts
2818
2334
  var DEFAULT_MAX_ATTEMPTS = 3;
@@ -2824,10 +2340,7 @@ async function runWithApiErrorHandling(thunk, policy) {
2824
2340
  try {
2825
2341
  return await thunk();
2826
2342
  } catch (error) {
2827
- const decision = await policy.processApiError({
2828
- error,
2829
- attempt
2830
- });
2343
+ const decision = await policy.processApiError({ error, attempt });
2831
2344
  if (decision.retry && attempt < maxAttempts) continue;
2832
2345
  if (!decision.retry && "fallback" in decision && decision.fallback !== void 0) {
2833
2346
  return decision.fallback;
@@ -2836,11 +2349,9 @@ async function runWithApiErrorHandling(thunk, policy) {
2836
2349
  }
2837
2350
  }
2838
2351
  }
2839
- __name(runWithApiErrorHandling, "runWithApiErrorHandling");
2840
2352
  function createApiErrorHandler(policy) {
2841
2353
  return (thunk) => runWithApiErrorHandling(thunk, policy);
2842
2354
  }
2843
- __name(createApiErrorHandler, "createApiErrorHandler");
2844
2355
 
2845
2356
  // src/bridge/delegation-scoring.ts
2846
2357
  function delegateBackground(subAgent, message, opts = {}) {
@@ -2851,20 +2362,24 @@ function delegateBackground(subAgent, message, opts = {}) {
2851
2362
  });
2852
2363
  promise.catch(() => void 0);
2853
2364
  return {
2854
- wait: /* @__PURE__ */ __name(() => promise, "wait"),
2855
- settled: /* @__PURE__ */ __name(() => isSettled, "settled")
2365
+ wait: () => promise,
2366
+ settled: () => isSettled
2856
2367
  };
2857
2368
  }
2858
- __name(delegateBackground, "delegateBackground");
2859
2369
  var DEFAULT_MAX_ROUNDS = 3;
2860
2370
  function defaultFeedbackTemplate(message, feedback) {
2861
2371
  return `${message}
2862
2372
 
2863
2373
  Feedback from the reviewer (address this): ${feedback}`;
2864
2374
  }
2865
- __name(defaultFeedbackTemplate, "defaultFeedbackTemplate");
2866
2375
  async function delegateWithScoring(subAgent, message, opts) {
2867
- const { scorer, maxRounds: maxRoundsOpt = DEFAULT_MAX_ROUNDS, delegateFn = delegate, feedbackTemplate = defaultFeedbackTemplate, ...delegateOpts } = opts;
2376
+ const {
2377
+ scorer,
2378
+ maxRounds: maxRoundsOpt = DEFAULT_MAX_ROUNDS,
2379
+ delegateFn = delegate,
2380
+ feedbackTemplate = defaultFeedbackTemplate,
2381
+ ...delegateOpts
2382
+ } = opts;
2868
2383
  const maxRounds = Math.max(1, maxRoundsOpt);
2869
2384
  const verdicts = [];
2870
2385
  let currentMessage = message;
@@ -2875,12 +2390,7 @@ async function delegateWithScoring(subAgent, message, opts) {
2875
2390
  const verdict = await scorer(result);
2876
2391
  verdicts.push(verdict);
2877
2392
  if (verdict.pass) {
2878
- return {
2879
- result,
2880
- rounds: round,
2881
- passed: true,
2882
- verdicts
2883
- };
2393
+ return { result, rounds: round, passed: true, verdicts };
2884
2394
  }
2885
2395
  if (verdict.feedback) currentMessage = feedbackTemplate(message, verdict.feedback);
2886
2396
  }
@@ -2894,7 +2404,6 @@ async function delegateWithScoring(subAgent, message, opts) {
2894
2404
  verdicts
2895
2405
  };
2896
2406
  }
2897
- __name(delegateWithScoring, "delegateWithScoring");
2898
2407
 
2899
2408
  // src/bridge/mcp-resolver.ts
2900
2409
  async function resolveMcpServers(selection, ctx) {
@@ -2906,7 +2415,6 @@ async function resolveMcpServers(selection, ctx) {
2906
2415
  }
2907
2416
  return resolved;
2908
2417
  }
2909
- __name(resolveMcpServers, "resolveMcpServers");
2910
2418
  function mcpRegistry(config) {
2911
2419
  const registry = config.registry;
2912
2420
  if (registry === "composio") {
@@ -2914,17 +2422,8 @@ function mcpRegistry(config) {
2914
2422
  return {
2915
2423
  composio: {
2916
2424
  command: "npx",
2917
- args: [
2918
- "-y",
2919
- "@composio/mcp",
2920
- ...apps.length > 0 ? [
2921
- "--apps",
2922
- apps.join(",")
2923
- ] : []
2924
- ],
2925
- env: {
2926
- COMPOSIO_API_KEY: config.apiKey
2927
- }
2425
+ args: ["-y", "@composio/mcp", ...apps.length > 0 ? ["--apps", apps.join(",")] : []],
2426
+ env: { COMPOSIO_API_KEY: config.apiKey }
2928
2427
  }
2929
2428
  };
2930
2429
  }
@@ -2936,30 +2435,23 @@ function mcpRegistry(config) {
2936
2435
  "-y",
2937
2436
  "@mcp.run/cli",
2938
2437
  "serve",
2939
- ...config.profile ? [
2940
- "--profile",
2941
- config.profile
2942
- ] : []
2438
+ ...config.profile ? ["--profile", config.profile] : []
2943
2439
  ],
2944
- env: {
2945
- MCP_RUN_API_KEY: config.apiKey
2946
- }
2440
+ env: { MCP_RUN_API_KEY: config.apiKey }
2947
2441
  }
2948
2442
  };
2949
2443
  }
2950
- throw new Error(`mcpRegistry: unknown registry ${JSON.stringify(registry)} (supported: 'composio', 'mcp.run').`);
2444
+ throw new Error(
2445
+ `mcpRegistry: unknown registry ${JSON.stringify(registry)} (supported: 'composio', 'mcp.run').`
2446
+ );
2951
2447
  }
2952
- __name(mcpRegistry, "mcpRegistry");
2953
2448
  function mcpToolApprovals(specs) {
2954
2449
  const out = {};
2955
2450
  for (const [tool, spec] of Object.entries(specs)) {
2956
- out[tool] = typeof spec === "string" ? {
2957
- question: spec
2958
- } : spec;
2451
+ out[tool] = typeof spec === "string" ? { question: spec } : spec;
2959
2452
  }
2960
2453
  return out;
2961
2454
  }
2962
- __name(mcpToolApprovals, "mcpToolApprovals");
2963
2455
 
2964
2456
  // src/bridge/mcp-file.ts
2965
2457
  import { existsSync, readFileSync } from "fs";
@@ -2971,11 +2463,7 @@ function warningChannel(opts) {
2971
2463
  `);
2972
2464
  });
2973
2465
  }
2974
- __name(warningChannel, "warningChannel");
2975
2466
  var McpFileError = class extends TheokitAgentError {
2976
- static {
2977
- __name(this, "McpFileError");
2978
- }
2979
2467
  name = "McpFileError";
2980
2468
  constructor(message) {
2981
2469
  super(`[@theokit/agents] ${message}`);
@@ -2999,7 +2487,6 @@ function loadMcpJson(cwd, opts = {}) {
2999
2487
  }
3000
2488
  return parseMcpJson(parsed, path, warningChannel(opts));
3001
2489
  }
3002
- __name(loadMcpJson, "loadMcpJson");
3003
2490
  function parseMcpJson(raw, source, onWarn) {
3004
2491
  if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {
3005
2492
  throw new McpFileError(`${source}: root must be a JSON object with an "mcpServers" key.`);
@@ -3020,7 +2507,6 @@ function parseMcpJson(raw, source, onWarn) {
3020
2507
  }
3021
2508
  return out;
3022
2509
  }
3023
- __name(parseMcpJson, "parseMcpJson");
3024
2510
  function validarEntrada(name, entryRaw) {
3025
2511
  if (typeof entryRaw !== "object" || entryRaw === null || Array.isArray(entryRaw)) {
3026
2512
  return "a entrada deve ser um objeto.";
@@ -3028,21 +2514,23 @@ function validarEntrada(name, entryRaw) {
3028
2514
  const entry = entryRaw;
3029
2515
  const temUrl = entry.url !== void 0;
3030
2516
  const temCommand = entry.command !== void 0;
3031
- if (temUrl && temCommand) return 'declara "command" e "url" ao mesmo tempo \u2014 escolha um transporte.';
2517
+ if (temUrl && temCommand)
2518
+ return 'declara "command" e "url" ao mesmo tempo \u2014 escolha um transporte.';
3032
2519
  if (!temUrl && !temCommand) return 'requer "command" (stdio) ou "url" (http/sse).';
3033
2520
  return temUrl ? validarRemoto(entry) : validarStdio(entry);
3034
2521
  }
3035
- __name(validarEntrada, "validarEntrada");
3036
2522
  function validarStdio(entry) {
3037
2523
  if (typeof entry.command !== "string" || entry.command.length === 0) {
3038
2524
  return 'campo "command" deve ser uma string n\xE3o vazia.';
3039
2525
  }
3040
- if (entry.args !== void 0 && !isStringArray(entry.args)) return 'campo "args" deve ser array de strings.';
3041
- if (entry.env !== void 0 && !isStringRecord(entry.env)) return 'campo "env" deve ser um mapa de strings.';
3042
- if (entry.cwd !== void 0 && typeof entry.cwd !== "string") return 'campo "cwd" deve ser string.';
2526
+ if (entry.args !== void 0 && !isStringArray(entry.args))
2527
+ return 'campo "args" deve ser array de strings.';
2528
+ if (entry.env !== void 0 && !isStringRecord(entry.env))
2529
+ return 'campo "env" deve ser um mapa de strings.';
2530
+ if (entry.cwd !== void 0 && typeof entry.cwd !== "string")
2531
+ return 'campo "cwd" deve ser string.';
3043
2532
  return void 0;
3044
2533
  }
3045
- __name(validarStdio, "validarStdio");
3046
2534
  function validarRemoto(entry) {
3047
2535
  if (typeof entry.url !== "string" || entry.url.length === 0) {
3048
2536
  return 'campo "url" deve ser uma string n\xE3o vazia.';
@@ -3063,39 +2551,30 @@ function validarRemoto(entry) {
3063
2551
  }
3064
2552
  return void 0;
3065
2553
  }
3066
- __name(validarRemoto, "validarRemoto");
3067
2554
  function buildEntry(entry) {
3068
2555
  if (entry.url !== void 0) {
3069
- const remote = {
3070
- url: entry.url
3071
- };
2556
+ const remote = { url: entry.url };
3072
2557
  if (entry.type !== void 0) remote.type = entry.type;
3073
2558
  if (entry.headers !== void 0) remote.headers = entry.headers;
3074
2559
  if (entry.auth !== void 0) remote.auth = entry.auth;
3075
2560
  if (entry.requestTimeoutMs !== void 0) remote.requestTimeoutMs = entry.requestTimeoutMs;
3076
2561
  return remote;
3077
2562
  }
3078
- const stdio = {
3079
- command: entry.command
3080
- };
2563
+ const stdio = { command: entry.command };
3081
2564
  if (entry.args !== void 0) stdio.args = entry.args;
3082
2565
  if (entry.env !== void 0) stdio.env = entry.env;
3083
2566
  if (entry.cwd !== void 0) stdio.cwd = entry.cwd;
3084
2567
  return stdio;
3085
2568
  }
3086
- __name(buildEntry, "buildEntry");
3087
2569
  function descrever(err) {
3088
2570
  return err instanceof Error ? err.message : String(err);
3089
2571
  }
3090
- __name(descrever, "descrever");
3091
2572
  function isStringArray(v) {
3092
2573
  return Array.isArray(v) && v.every((x) => typeof x === "string");
3093
2574
  }
3094
- __name(isStringArray, "isStringArray");
3095
2575
  function isStringRecord(v) {
3096
2576
  return typeof v === "object" && v !== null && !Array.isArray(v) && Object.values(v).every((x) => typeof x === "string");
3097
2577
  }
3098
- __name(isStringRecord, "isStringRecord");
3099
2578
 
3100
2579
  // src/manifest/agent-manifest.ts
3101
2580
  function generateAgentManifest(sources) {
@@ -3113,15 +2592,17 @@ function generateAgentManifest(sources) {
3113
2592
  },
3114
2593
  guards: r.guards.map((g) => g.name),
3115
2594
  interceptors: r.interceptors.map((i) => i.name),
3116
- tools: r.toolboxes.flatMap((tb) => tb.tools.map((t) => ({
3117
- name: tb.namespace ? `${tb.namespace}.${t.config.name}` : t.config.name,
3118
- description: t.config.description,
3119
- risk: t.config.risk,
3120
- approval: t.approval !== void 0,
3121
- capabilities: t.capabilities,
3122
- trace: t.trace,
3123
- audit: t.audit
3124
- }))),
2595
+ tools: r.toolboxes.flatMap(
2596
+ (tb) => tb.tools.map((t) => ({
2597
+ name: tb.namespace ? `${tb.namespace}.${t.config.name}` : t.config.name,
2598
+ description: t.config.description,
2599
+ risk: t.config.risk,
2600
+ approval: t.approval !== void 0,
2601
+ capabilities: t.capabilities,
2602
+ trace: t.trace,
2603
+ audit: t.audit
2604
+ }))
2605
+ ),
3125
2606
  gateway: r.gateway ? {
3126
2607
  platforms: r.gateway.platforms,
3127
2608
  sessionStrategy: r.gateway.sessionStrategy ?? "per-user"
@@ -3138,7 +2619,6 @@ function generateAgentManifest(sources) {
3138
2619
  }))
3139
2620
  };
3140
2621
  }
3141
- __name(generateAgentManifest, "generateAgentManifest");
3142
2622
 
3143
2623
  // src/theokit-plugin.ts
3144
2624
  function validateUniqueRoutes(results) {
@@ -3146,12 +2626,13 @@ function validateUniqueRoutes(results) {
3146
2626
  for (const r of results) {
3147
2627
  const existing = seen.get(r.route);
3148
2628
  if (existing !== void 0) {
3149
- throw new Error(`[@theokit/agents] Duplicate agent route '${r.route}': both '${existing}' and '${r.agentConfig.name}' declare it.`);
2629
+ throw new Error(
2630
+ `[@theokit/agents] Duplicate agent route '${r.route}': both '${existing}' and '${r.agentConfig.name}' declare it.`
2631
+ );
3150
2632
  }
3151
2633
  seen.set(r.route, r.agentConfig.name);
3152
2634
  }
3153
2635
  }
3154
- __name(validateUniqueRoutes, "validateUniqueRoutes");
3155
2636
  function agentsPlugin(opts) {
3156
2637
  let routes = null;
3157
2638
  return {
@@ -3169,30 +2650,23 @@ function agentsPlugin(opts) {
3169
2650
  }
3170
2651
  };
3171
2652
  }
3172
- __name(agentsPlugin, "agentsPlugin");
3173
2653
  function initRoutes(opts) {
3174
2654
  const allRoutes = [];
3175
2655
  const routeIdentities = [];
3176
2656
  for (const entry of opts.agents) {
3177
- routeIdentities.push({
3178
- route: entry.route,
3179
- agentConfig: {
3180
- name: entry.name
3181
- }
3182
- });
2657
+ routeIdentities.push({ route: entry.route, agentConfig: { name: entry.name } });
3183
2658
  const createRun = opts.createRunFactory ? opts.createRunFactory(entry.compiled) : defaultCreateRun(entry.compiled);
3184
- allRoutes.push(...generateAgentRoutes({
3185
- walkResult: {
3186
- route: entry.route
3187
- },
3188
- compiledOptions: entry.compiled,
3189
- createRun
3190
- }));
2659
+ allRoutes.push(
2660
+ ...generateAgentRoutes({
2661
+ walkResult: { route: entry.route },
2662
+ compiledOptions: entry.compiled,
2663
+ createRun
2664
+ })
2665
+ );
3191
2666
  }
3192
2667
  validateUniqueRoutes(routeIdentities);
3193
2668
  return compileRoutePatterns(allRoutes);
3194
2669
  }
3195
- __name(initRoutes, "initRoutes");
3196
2670
  function defaultCreateRun(compiled) {
3197
2671
  return async function* (_message, _sessionId) {
3198
2672
  await Promise.resolve();
@@ -3209,18 +2683,13 @@ function defaultCreateRun(compiled) {
3209
2683
  };
3210
2684
  };
3211
2685
  }
3212
- __name(defaultCreateRun, "defaultCreateRun");
3213
2686
  function compileRoutePatterns(routes) {
3214
2687
  return routes.map((r) => {
3215
2688
  if (!r.path.includes(":")) return r;
3216
2689
  const regexSource = r.path.replace(/:[^/]+/g, "[^/]+");
3217
- return {
3218
- ...r,
3219
- regex: RegExp(`^${regexSource}$`)
3220
- };
2690
+ return { ...r, regex: RegExp(`^${regexSource}$`) };
3221
2691
  });
3222
2692
  }
3223
- __name(compileRoutePatterns, "compileRoutePatterns");
3224
2693
  function matchRoute(routes, method, pathname) {
3225
2694
  return routes.find((r) => {
3226
2695
  if (r.method !== method) return false;
@@ -3228,7 +2697,6 @@ function matchRoute(routes, method, pathname) {
3228
2697
  return r.path === pathname;
3229
2698
  });
3230
2699
  }
3231
- __name(matchRoute, "matchRoute");
3232
2700
 
3233
2701
  export {
3234
2702
  ConfigurationError,
@@ -3309,4 +2777,4 @@ export {
3309
2777
  generateAgentManifest,
3310
2778
  agentsPlugin
3311
2779
  };
3312
- //# sourceMappingURL=chunk-7ECCHM4N.js.map
2780
+ //# sourceMappingURL=chunk-NSJDG6XE.js.map