@theokit/agents 16.0.0 → 16.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/README.md +47 -1
  3. package/dist/{agent-compiler-BMpuJFAI.d.ts → agent-compiler-JSYkHpa7.d.ts} +2 -2
  4. package/dist/{delegation-scoring-CURe4oSL.d.ts → agent-orchestrator-BFWg2URC.d.ts} +11 -426
  5. package/dist/agent-runner-BUJKNNuI.d.ts +364 -0
  6. package/dist/agent-sse-handler-BRp9vHrb.d.ts +348 -0
  7. package/dist/{bridge-entry-BxJWDpQP.d.ts → bridge-entry-BNWDrPzg.d.ts} +8 -422
  8. package/dist/bridge.d.ts +8 -5
  9. package/dist/bridge.js +19 -15
  10. package/dist/{chunk-4PHZ25JN.js → chunk-A7RXWJZE.js} +62 -1137
  11. package/dist/chunk-A7RXWJZE.js.map +1 -0
  12. package/dist/{chunk-FIGLHWR2.js → chunk-CJMYZKUL.js} +7 -7
  13. package/dist/chunk-MB23MSOK.js +353 -0
  14. package/dist/chunk-MB23MSOK.js.map +1 -0
  15. package/dist/chunk-SAKSZKVK.js +799 -0
  16. package/dist/chunk-SAKSZKVK.js.map +1 -0
  17. package/dist/delegation-scoring-Cn5eM4lQ.d.ts +79 -0
  18. package/dist/evals.d.ts +84 -0
  19. package/dist/evals.js +191 -0
  20. package/dist/evals.js.map +1 -0
  21. package/dist/handoff.d.ts +91 -0
  22. package/dist/handoff.js +268 -0
  23. package/dist/handoff.js.map +1 -0
  24. package/dist/index.d.ts +19 -369
  25. package/dist/index.js +36 -32
  26. package/dist/index.js.map +1 -1
  27. package/dist/mcp-health.d.ts +1 -1
  28. package/dist/sdk-adapter-DQnKx7bA.d.ts +435 -0
  29. package/dist/testing.d.ts +2 -2
  30. package/dist/tools.d.ts +5 -3
  31. package/dist/tools.js +10 -6
  32. package/dist/tools.js.map +1 -1
  33. package/dist/{types-DdltPCj2.d.ts → types-D5cHmSLi.d.ts} +1 -1
  34. package/docs/capability-map.md +31 -1
  35. package/package.json +12 -2
  36. package/dist/chunk-4PHZ25JN.js.map +0 -1
  37. /package/dist/{chunk-FIGLHWR2.js.map → chunk-CJMYZKUL.js.map} +0 -0
@@ -0,0 +1,799 @@
1
+ import {
2
+ GuardrailError,
3
+ createSdkAgentStream,
4
+ moderateOutputStream,
5
+ runInputGuards,
6
+ textPayloadExtractor
7
+ } from "./chunk-A7RXWJZE.js";
8
+ import {
9
+ debugLog
10
+ } from "./chunk-M5J3Q6YC.js";
11
+ import {
12
+ __name
13
+ } from "./chunk-Z4QWC7IK.js";
14
+
15
+ // src/loop/compaction-strategy.ts
16
+ import { compactTranscript } from "@theokit/sdk/compaction";
17
+ import { z } from "zod";
18
+ var DEFAULT_KEEP_TOKENS = 8e3;
19
+ var compactionStrategyConfigSchema = z.object({
20
+ name: z.literal("token-budget"),
21
+ keepTokens: z.number().int().positive()
22
+ });
23
+ function resolveCompactionStrategy(name, config) {
24
+ const cfg = compactionStrategyConfigSchema.parse({
25
+ name,
26
+ keepTokens: config.keepTokens
27
+ });
28
+ return {
29
+ name: cfg.name,
30
+ keepTokens: cfg.keepTokens,
31
+ compact: /* @__PURE__ */ __name((messages, options) => compactTranscript(messages, {
32
+ keepTokens: options?.keepTokens ?? cfg.keepTokens,
33
+ summarize: options?.summarize,
34
+ marker: options?.marker,
35
+ summaryTemplate: options?.summaryTemplate,
36
+ // Default-safe: a thrown summarize keeps the transcript (app opts out via failSafe:false).
37
+ failSafe: options?.failSafe ?? true
38
+ }), "compact")
39
+ };
40
+ }
41
+ __name(resolveCompactionStrategy, "resolveCompactionStrategy");
42
+ var tokenBudgetCompactionStrategy = resolveCompactionStrategy("token-budget", {
43
+ keepTokens: DEFAULT_KEEP_TOKENS
44
+ });
45
+
46
+ // src/loop/loop-strategy.ts
47
+ import { z as z2 } from "zod";
48
+ var DEFAULT_MAX_ITERATIONS = 8;
49
+ var maxIterationsSchema = z2.number().int().min(1);
50
+ var loopStrategyConfigSchema = z2.object({
51
+ name: z2.enum([
52
+ "simple-chat",
53
+ "plan-act-reflect",
54
+ "react"
55
+ ]),
56
+ maxIterations: maxIterationsSchema
57
+ });
58
+ function assertValidCustomLoopStrategy(strategy) {
59
+ const result = maxIterationsSchema.safeParse(strategy.maxIterations);
60
+ if (!result.success) {
61
+ throw new Error(`loopStrategy: invalid maxIterations (${String(strategy.maxIterations)}) \u2014 must be a finite integer \u2265 1 (otherwise the round < maxIterations ceiling never terminates)`);
62
+ }
63
+ }
64
+ __name(assertValidCustomLoopStrategy, "assertValidCustomLoopStrategy");
65
+ function resolveLoopStrategy(strategy, maxIterations = DEFAULT_MAX_ITERATIONS) {
66
+ const cfg = loopStrategyConfigSchema.parse({
67
+ name: strategy,
68
+ maxIterations
69
+ });
70
+ if (cfg.name === "simple-chat") {
71
+ return {
72
+ name: cfg.name,
73
+ maxIterations: cfg.maxIterations,
74
+ shouldContinue: /* @__PURE__ */ __name(() => false, "shouldContinue")
75
+ };
76
+ }
77
+ if (cfg.name === "plan-act-reflect") {
78
+ return {
79
+ name: cfg.name,
80
+ maxIterations: cfg.maxIterations,
81
+ shouldContinue: /* @__PURE__ */ __name((outcome) => outcome.round < cfg.maxIterations, "shouldContinue")
82
+ };
83
+ }
84
+ return {
85
+ name: cfg.name,
86
+ maxIterations: cfg.maxIterations,
87
+ shouldContinue: /* @__PURE__ */ __name((outcome) => outcome.finishReason === "tool-calls" && outcome.round < cfg.maxIterations, "shouldContinue")
88
+ };
89
+ }
90
+ __name(resolveLoopStrategy, "resolveLoopStrategy");
91
+
92
+ // src/loop/reflection-strategy.ts
93
+ import { z as z3 } from "zod";
94
+ var reflectionStrategyConfigSchema = z3.object({
95
+ name: z3.string().min(1)
96
+ });
97
+ var ladderReflectionStrategy = {
98
+ name: "ladder",
99
+ reflect(outcome) {
100
+ if (outcome.finishReason === "tool-calls") {
101
+ return {
102
+ feedback: `Tool results received (round ${outcome.round}). Reflect on whether the goal is met; if not, refine the approach and continue.`,
103
+ continue: true
104
+ };
105
+ }
106
+ return {
107
+ continue: false
108
+ };
109
+ }
110
+ };
111
+ var noopReflectionStrategy = {
112
+ name: "noop",
113
+ reflect() {
114
+ return {
115
+ continue: true
116
+ };
117
+ }
118
+ };
119
+
120
+ // src/bridge/delegation-types.ts
121
+ import { TheokitAgentError } from "@theokit/sdk/errors";
122
+ function budgetMessage(agentName, actualCost, budgetLimit, refusal) {
123
+ const limit = `$${budgetLimit.toFixed(4)}`;
124
+ if (refusal === void 0) {
125
+ return `Agent "${agentName}" exceeded budget: $${actualCost.toFixed(4)} > ${limit}`;
126
+ }
127
+ if ("nothingToSpend" in refusal) {
128
+ return `Agent "${agentName}" stopped before its first round: its ${limit} limit leaves nothing to spend`;
129
+ }
130
+ if ("costUnknown" in refusal) {
131
+ return `Agent "${agentName}" stopped before its next round: the cost of its last round is not known, so the ${limit} limit cannot be enforced (known spend $${actualCost.toFixed(4)})`;
132
+ }
133
+ return `Agent "${agentName}" stopped before its next round: spent $${actualCost.toFixed(4)}, next round projected at $${refusal.projectedRoundCost.toFixed(4)}, which would pass the ${limit} limit`;
134
+ }
135
+ __name(budgetMessage, "budgetMessage");
136
+ var DelegationBudgetExceededError = class extends TheokitAgentError {
137
+ static {
138
+ __name(this, "DelegationBudgetExceededError");
139
+ }
140
+ agentName;
141
+ actualCost;
142
+ budgetLimit;
143
+ name = "DelegationBudgetExceededError";
144
+ /** The cost the refused round was projected at; absent when the spend already passed the limit. */
145
+ projectedRoundCost;
146
+ constructor(agentName, actualCost, budgetLimit, refusal) {
147
+ super(budgetMessage(agentName, actualCost, budgetLimit, refusal), {
148
+ code: "DELEGATION_BUDGET_EXCEEDED",
149
+ // The budget does not refill on retry.
150
+ isRetryable: false
151
+ }), this.agentName = agentName, this.actualCost = actualCost, this.budgetLimit = budgetLimit;
152
+ this.projectedRoundCost = refusal !== void 0 && "projectedRoundCost" in refusal ? refusal.projectedRoundCost : void 0;
153
+ }
154
+ };
155
+ var DelegationBudgetCostUnknownError = class extends DelegationBudgetExceededError {
156
+ static {
157
+ __name(this, "DelegationBudgetCostUnknownError");
158
+ }
159
+ constructor(agentName, knownSpend, budgetLimit) {
160
+ super(agentName, knownSpend, budgetLimit, {
161
+ costUnknown: true
162
+ });
163
+ }
164
+ };
165
+ var BudgetExceededError = DelegationBudgetExceededError;
166
+ var DelegationError = class extends TheokitAgentError {
167
+ static {
168
+ __name(this, "DelegationError");
169
+ }
170
+ agentName;
171
+ cause;
172
+ name = "DelegationError";
173
+ constructor(agentName, cause) {
174
+ super(`Delegation to agent "${agentName}" failed: ${cause instanceof Error ? cause.message : String(cause)}`, {
175
+ code: "DELEGATION_FAILED",
176
+ // Not retryable AT THIS LEVEL: whether the underlying cause is transient is the cause's own
177
+ // answer, and `cause` is carried so a caller can ask it rather than guess from the wrapper.
178
+ isRetryable: false,
179
+ cause
180
+ }), this.agentName = agentName, this.cause = cause;
181
+ }
182
+ };
183
+
184
+ // src/guardrails/terminal-frame.ts
185
+ async function* mirrorModeratedText(inner) {
186
+ let round = "";
187
+ let sawText = false;
188
+ let step = await inner.next();
189
+ while (!step.done) {
190
+ const event = step.value;
191
+ if (event.type === "text_delta" && typeof event.content === "string") {
192
+ round += event.content;
193
+ sawText = true;
194
+ }
195
+ if (event.type === "done") {
196
+ yield sawText ? {
197
+ ...event,
198
+ result: round
199
+ } : event;
200
+ round = "";
201
+ sawText = false;
202
+ } else {
203
+ yield event;
204
+ }
205
+ step = await inner.next();
206
+ }
207
+ return step.value;
208
+ }
209
+ __name(mirrorModeratedText, "mirrorModeratedText");
210
+
211
+ // src/loop/run-budget.ts
212
+ function refuseNextRound(spent, lastRound, ceiling, agentName) {
213
+ if (!Number.isFinite(ceiling)) return void 0;
214
+ if (!lastRound.costKnown) return new DelegationBudgetCostUnknownError(agentName, spent, ceiling);
215
+ if (spent + lastRound.cost > ceiling) {
216
+ return new DelegationBudgetExceededError(agentName, spent, ceiling, {
217
+ projectedRoundCost: lastRound.cost
218
+ });
219
+ }
220
+ return void 0;
221
+ }
222
+ __name(refuseNextRound, "refuseNextRound");
223
+ function throwIfNextRoundRefused(spent, lastRound, ceiling, agentName, signal) {
224
+ if (signal?.aborted) return;
225
+ const refusal = refuseNextRound(spent, lastRound, ceiling, agentName);
226
+ if (refusal) throw refusal;
227
+ }
228
+ __name(throwIfNextRoundRefused, "throwIfNextRoundRefused");
229
+ function resolveRunBudget(budget, agentName, name = "budget") {
230
+ if (budget == null) return void 0;
231
+ let field = name;
232
+ let ceiling = budget;
233
+ if (typeof budget !== "number") {
234
+ if (budget.window !== void 0) {
235
+ throw new DelegationError(agentName, new Error(`${name}.window is not supported: a rolling budget needs spend persisted across runs`));
236
+ }
237
+ field = `${name}.maxCostUsd`;
238
+ ceiling = budget.maxCostUsd;
239
+ }
240
+ if (typeof ceiling !== "number" || Number.isNaN(ceiling)) {
241
+ throw new DelegationError(agentName, new Error(`${field} must be a number, got ${String(ceiling)}`));
242
+ }
243
+ if (ceiling <= 0) {
244
+ throw new DelegationBudgetExceededError(agentName, 0, ceiling, {
245
+ nothingToSpend: true
246
+ });
247
+ }
248
+ return ceiling;
249
+ }
250
+ __name(resolveRunBudget, "resolveRunBudget");
251
+
252
+ // src/loop/round-usage.ts
253
+ var TOKEN_BUCKETS = [
254
+ "tokensInput",
255
+ "tokensOutput",
256
+ "reasoningTokens",
257
+ "cacheReadTokens",
258
+ "cacheWriteTokens"
259
+ ];
260
+ var DONE_USAGE_FIELDS = [
261
+ [
262
+ "tokens",
263
+ "totalTokens"
264
+ ],
265
+ [
266
+ "tokensInput",
267
+ "inputTokens"
268
+ ],
269
+ [
270
+ "tokensOutput",
271
+ "outputTokens"
272
+ ],
273
+ [
274
+ "reasoningTokens",
275
+ "reasoningTokens"
276
+ ],
277
+ [
278
+ "cacheReadTokens",
279
+ "cacheReadTokens"
280
+ ],
281
+ [
282
+ "cacheWriteTokens",
283
+ "cacheWriteTokens"
284
+ ]
285
+ ];
286
+ function applyDone(event, r) {
287
+ r.costKnown = typeof event.cost === "number" && Number.isFinite(event.cost);
288
+ r.cost = r.costKnown ? event.cost : 0;
289
+ const usage = event.usage ?? {};
290
+ for (const [field, key] of DONE_USAGE_FIELDS) r[field] = usage[key] ?? 0;
291
+ }
292
+ __name(applyDone, "applyDone");
293
+ function accumulateUsage(acc, r) {
294
+ acc.cost += r.cost;
295
+ if (!r.costKnown) acc.costUnknown = true;
296
+ acc.tokens += r.tokens;
297
+ for (const bucket of TOKEN_BUCKETS) acc[bucket] = (acc[bucket] ?? 0) + r[bucket];
298
+ }
299
+ __name(accumulateUsage, "accumulateUsage");
300
+
301
+ // src/loop/run-reflective-loop.ts
302
+ function asString(value, fallback) {
303
+ return typeof value === "string" ? value : fallback;
304
+ }
305
+ __name(asString, "asString");
306
+ var NO_PROGRESS_THRESHOLD = 2;
307
+ var MAINLOOP_METRIC = "[THEO_AGENT_MAINLOOP_RUNTIME_APPLIED]";
308
+ var TOOL_CALLS = "tool-calls";
309
+ var STEP_LIMIT_HINT = "This is your final round \u2014 do not call any more tools; summarize the work done so far and list any remaining tasks.";
310
+ function stableStringify(value) {
311
+ if (value === void 0) return "undefined";
312
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
313
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
314
+ const obj = value;
315
+ const entries = Object.keys(obj).sort((a, b) => a.localeCompare(b)).map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`);
316
+ return `{${entries.join(",")}}`;
317
+ }
318
+ __name(stableStringify, "stableStringify");
319
+ function roundSignature(toolCalls) {
320
+ return toolCalls.map((tc) => `${tc.name}:${stableStringify(tc.input)}`).sort((a, b) => a.localeCompare(b)).join(",");
321
+ }
322
+ __name(roundSignature, "roundSignature");
323
+ function terminalReason(reflectionContinue, roundReason, round, maxIterations) {
324
+ if (reflectionContinue && roundReason === TOOL_CALLS && round >= maxIterations) return "step_limit";
325
+ if (roundReason === TOOL_CALLS) return "stop";
326
+ return roundReason;
327
+ }
328
+ __name(terminalReason, "terminalReason");
329
+ var CONTINUE_PROMPT = "Continue from the prior turns above; finish the task and give a final answer.";
330
+ function buildPrompt(round, maxIterations, message, feedback) {
331
+ const hint = round === maxIterations ? `${STEP_LIMIT_HINT}
332
+
333
+ ` : "";
334
+ const continuation = feedback ? `[reflection] ${feedback}` : CONTINUE_PROMPT;
335
+ const body = round === 1 ? message : continuation;
336
+ return hint + body;
337
+ }
338
+ __name(buildPrompt, "buildPrompt");
339
+ async function* consumeRoundOrThrow(inputs, agentName) {
340
+ try {
341
+ return yield* consumeOneRound(inputs.factory, inputs.prompt, inputs.sessionId, inputs.signal, inputs.retry);
342
+ } catch (err) {
343
+ if (err instanceof DelegationBudgetExceededError || err instanceof DelegationError || err instanceof GuardrailError) {
344
+ throw err;
345
+ }
346
+ throw new DelegationError(agentName, err);
347
+ }
348
+ }
349
+ __name(consumeRoundOrThrow, "consumeRoundOrThrow");
350
+ function finalize(acc, round, reason, strategyName) {
351
+ acc.rounds = round;
352
+ acc.finishReason = reason;
353
+ debugLog(MAINLOOP_METRIC, {
354
+ strategy: strategyName,
355
+ rounds: round,
356
+ terminal: reason
357
+ });
358
+ return acc;
359
+ }
360
+ __name(finalize, "finalize");
361
+ function deriveFinishReason(signals) {
362
+ if (signals.sawError) return "error";
363
+ if (signals.sawDone && signals.doneFinishReason === TOOL_CALLS) return TOOL_CALLS;
364
+ if (signals.sawToolResult) return TOOL_CALLS;
365
+ return "stop";
366
+ }
367
+ __name(deriveFinishReason, "deriveFinishReason");
368
+ function pushToolResult(event, r, callInputs) {
369
+ const id = asString(event.callId, "");
370
+ const call = callInputs.get(id);
371
+ r.toolCalls.push({
372
+ id,
373
+ name: call?.name ?? asString(event.toolName, "unknown"),
374
+ // Prefer the correlated tool_call input (real SDK shape); fall back to an input on the
375
+ // result event itself (some streams/tests carry it there), else {}.
376
+ input: call?.input ?? event.input ?? {},
377
+ output: asString(event.output, "")
378
+ });
379
+ }
380
+ __name(pushToolResult, "pushToolResult");
381
+ function accumulateEvent(event, r, signals, callInputs) {
382
+ if (event.type === "text_delta" && typeof event.content === "string") {
383
+ r.responseText += event.content;
384
+ } else if (event.type === "tool_call") {
385
+ callInputs.set(asString(event.callId, ""), {
386
+ name: asString(event.toolName, "unknown"),
387
+ input: event.input ?? {}
388
+ });
389
+ } else if (event.type === "tool_result") {
390
+ signals.sawToolResult = true;
391
+ pushToolResult(event, r, callInputs);
392
+ } else if (event.type === "done") {
393
+ signals.sawDone = true;
394
+ signals.doneFinishReason = asString(event.finishReason, "");
395
+ applyDone(event, r);
396
+ } else if (event.type === "error") {
397
+ signals.sawError = true;
398
+ r.errorMessage = asString(event.message, "Unknown agent error");
399
+ }
400
+ }
401
+ __name(accumulateEvent, "accumulateEvent");
402
+ async function startRound(factory, prompt, sessionId, signal, retry) {
403
+ const open = /* @__PURE__ */ __name(async () => {
404
+ const it = factory(prompt, sessionId)[Symbol.asyncIterator]();
405
+ try {
406
+ return {
407
+ it,
408
+ first: await it.next()
409
+ };
410
+ } catch (err) {
411
+ await it.return?.(void 0);
412
+ throw err;
413
+ }
414
+ }, "open");
415
+ if (!retry) return open();
416
+ const { Retry } = await import("@theokit/sdk/retry");
417
+ return Retry.run(open, {
418
+ ...retry,
419
+ signal: retry.signal ?? signal
420
+ });
421
+ }
422
+ __name(startRound, "startRound");
423
+ async function* consumeOneRound(factory, prompt, sessionId, signal, retry) {
424
+ const r = {
425
+ responseText: "",
426
+ toolCalls: [],
427
+ cost: 0,
428
+ costKnown: false,
429
+ tokens: 0,
430
+ tokensInput: 0,
431
+ tokensOutput: 0,
432
+ reasoningTokens: 0,
433
+ cacheReadTokens: 0,
434
+ cacheWriteTokens: 0,
435
+ finishReason: "stop",
436
+ errorMessage: ""
437
+ };
438
+ const signals = {
439
+ sawError: false,
440
+ sawDone: false,
441
+ doneFinishReason: "",
442
+ sawToolResult: false
443
+ };
444
+ const callInputs = /* @__PURE__ */ new Map();
445
+ const { it, first } = await startRound(factory, prompt, sessionId, signal, retry);
446
+ let next = first;
447
+ while (!next.done) {
448
+ if (signal?.aborted) {
449
+ await it.return?.(void 0);
450
+ break;
451
+ }
452
+ yield next.value;
453
+ accumulateEvent(next.value, r, signals, callInputs);
454
+ next = await it.next();
455
+ }
456
+ r.finishReason = deriveFinishReason(signals);
457
+ return r;
458
+ }
459
+ __name(consumeOneRound, "consumeOneRound");
460
+ function ceilingRoundFactory(factory, round, maxIterations) {
461
+ if (round !== maxIterations) return factory;
462
+ return (m, s) => factory(m, s, {
463
+ disableTools: true
464
+ });
465
+ }
466
+ __name(ceilingRoundFactory, "ceilingRoundFactory");
467
+ async function* runReflectiveLoopStream(factory, message, sessionId, config) {
468
+ const { loop, reflection, budget = Number.POSITIVE_INFINITY, signal, agentName = loop.name, retry } = config;
469
+ const acc = {
470
+ response: "",
471
+ toolCalls: [],
472
+ cost: 0,
473
+ tokens: 0,
474
+ tokensInput: 0,
475
+ tokensOutput: 0,
476
+ reasoningTokens: 0,
477
+ cacheReadTokens: 0,
478
+ cacheWriteTokens: 0,
479
+ rounds: 0
480
+ };
481
+ const reflectionContext = {};
482
+ let round = 1;
483
+ let feedback;
484
+ let prevSig;
485
+ let stuck = 0;
486
+ while (!signal?.aborted) {
487
+ const prompt = buildPrompt(round, loop.maxIterations, message, feedback);
488
+ const roundFactory = ceilingRoundFactory(factory, round, loop.maxIterations);
489
+ const r = yield* consumeRoundOrThrow({
490
+ factory: roundFactory,
491
+ prompt,
492
+ sessionId,
493
+ signal,
494
+ retry
495
+ }, agentName);
496
+ acc.response += r.responseText;
497
+ acc.toolCalls.push(...r.toolCalls);
498
+ accumulateUsage(acc, r);
499
+ if (r.finishReason === "error") throw new DelegationError(agentName, r.errorMessage);
500
+ if (Number.isFinite(budget) && acc.cost > budget) {
501
+ throw new DelegationBudgetExceededError(agentName, acc.cost, budget);
502
+ }
503
+ if (r.finishReason === TOOL_CALLS && r.toolCalls.length > 0) {
504
+ const sig = roundSignature(r.toolCalls);
505
+ stuck = sig === prevSig ? stuck + 1 : 0;
506
+ if (stuck >= NO_PROGRESS_THRESHOLD) return finalize(acc, round, "no_progress", loop.name);
507
+ prevSig = sig;
508
+ }
509
+ const outcome = {
510
+ finishReason: r.finishReason,
511
+ round,
512
+ toolCalls: r.toolCalls,
513
+ responseText: r.responseText
514
+ };
515
+ const reflectionResult = reflection.reflect(outcome, reflectionContext);
516
+ if (!(reflectionResult.continue && loop.shouldContinue(outcome) && round < loop.maxIterations)) {
517
+ const reason = terminalReason(reflectionResult.continue, r.finishReason, round, loop.maxIterations);
518
+ return finalize(acc, round, reason, loop.name);
519
+ }
520
+ throwIfNextRoundRefused(acc.cost, r, budget, agentName, signal);
521
+ feedback = reflectionResult.feedback;
522
+ round += 1;
523
+ }
524
+ acc.rounds = round - 1;
525
+ return acc;
526
+ }
527
+ __name(runReflectiveLoopStream, "runReflectiveLoopStream");
528
+ async function runReflectiveLoop(factory, message, sessionId, config) {
529
+ const gen = runReflectiveLoopStream(factory, message, sessionId, config);
530
+ let res = await gen.next();
531
+ while (!res.done) res = await gen.next();
532
+ return res.value;
533
+ }
534
+ __name(runReflectiveLoop, "runReflectiveLoop");
535
+
536
+ // src/loop/agent-runner.ts
537
+ var AgentRunner = class {
538
+ static {
539
+ __name(this, "AgentRunner");
540
+ }
541
+ compiled;
542
+ agentName;
543
+ /** The resolved terminal-decision strategy (parity with `delegate()`). */
544
+ loopStrategy;
545
+ /** M54 — whether {@link loopStrategy} is a caller-injected custom (see {@link AgentRunnerState}). */
546
+ loopStrategyIsCustom;
547
+ /** The resolved between-round reflection (default or `.reflection(custom)` override). */
548
+ reflectionStrategy;
549
+ /**
550
+ * Recorded streaming preference. The reflective loop currently always streams via
551
+ * the SDK `Run.stream()`; a non-streaming collect mode is future work — the flag is
552
+ * captured + exposed here, not yet branched on (honest per G10: documented, not a
553
+ * silent no-op).
554
+ */
555
+ streamEnabled;
556
+ /**
557
+ * V4-F: the resolved compaction strategy (from `@Compaction` or `.compaction()`),
558
+ * or `undefined` when neither is declared — compaction is opt-in (EC-4). CALLABLE
559
+ * by the app (ADR D1: `runner.compaction?.compact(messages, { summarize })`); the
560
+ * reflective loop does NOT auto-invoke it (the SDK owns per-turn context).
561
+ */
562
+ compaction;
563
+ constructor(state) {
564
+ this.compiled = state.compiled;
565
+ this.agentName = state.agentName;
566
+ this.loopStrategy = state.loopStrategy;
567
+ this.loopStrategyIsCustom = state.loopStrategyIsCustom ?? false;
568
+ this.reflectionStrategy = state.reflectionStrategy;
569
+ this.streamEnabled = state.streamEnabled;
570
+ this.compaction = state.compaction;
571
+ }
572
+ /** Start a fluent builder from an already-compiled spec. */
573
+ static fromSpec(spec) {
574
+ return new AgentRunnerBuilder(spec);
575
+ }
576
+ /**
577
+ * V4-D-stream: stream the agent's events LIVE across the reflective loop, returning
578
+ * the aggregated {@link DelegationResult} as the generator's return value. This is the
579
+ * on-ramp for streaming-first apps (SSE) — `runReflectiveLoopStream` yields every
580
+ * round's events before the loop terminates. `streamEnabled` is honored: when the
581
+ * builder set `.stream(false)`, callers should use {@link run} instead.
582
+ */
583
+ stream(message, opts) {
584
+ const runOpts = {
585
+ ...opts,
586
+ budget: resolveRunBudget(opts.budget, this.agentName)
587
+ };
588
+ const guardrails = this.compiled.guardrails;
589
+ if (guardrails && guardrails.length > 0) {
590
+ const runUnguarded = /* @__PURE__ */ __name((m) => this.streamUnguarded(m, runOpts), "runUnguarded");
591
+ return (/* @__PURE__ */ __name(async function* guarded() {
592
+ const safe = await runInputGuards(message, guardrails);
593
+ return yield* mirrorModeratedText(
594
+ // #732 — the fourth channel, and the one the `done` fix cannot reach. A milestone is not
595
+ // a mirror of anything: it carries text the model writes through `task-tools`, so it gets
596
+ // its own pass like the two below. One pass per kind, because two kinds under one
597
+ // extractor collapse into a single event.
598
+ //
599
+ // `task-tools.ts` claimed B-018 had already shipped this. It had not — `agent-endpoint.ts`
600
+ // said in the same tree that the channel was NOT covered, and the claim is corrected there
601
+ // rather than deleted.
602
+ moderateOutputStream(
603
+ moderateOutputStream(
604
+ moderateOutputStream(
605
+ runUnguarded(safe),
606
+ guardrails,
607
+ // B-021 — the shared extractor, so "this kind, content unreadable" throws instead of
608
+ // sharing a return value with "not this kind". The hand-written form here returned
609
+ // `undefined` for a non-string, which reads as "carries no text": the payload was
610
+ // never shown to a guard and was yielded verbatim.
611
+ textPayloadExtractor("text_delta", (e) => e.content),
612
+ (content) => ({
613
+ type: "text_delta",
614
+ content
615
+ }),
616
+ (content, result) => ({
617
+ ...result,
618
+ response: content
619
+ })
620
+ ),
621
+ guardrails,
622
+ textPayloadExtractor("thinking", (e) => e.content),
623
+ (content) => ({
624
+ type: "thinking",
625
+ content
626
+ }),
627
+ // The reasoning pass does NOT touch the aggregate — the visible pass already did.
628
+ (_content, result) => result
629
+ ),
630
+ guardrails,
631
+ textPayloadExtractor("task_progress", (e) => e.text),
632
+ (text) => ({
633
+ type: "task_progress",
634
+ text
635
+ }),
636
+ // A milestone is not the answer — the visible pass owns the aggregate.
637
+ (_text, result) => result
638
+ )
639
+ );
640
+ }, "guarded"))();
641
+ }
642
+ return this.streamUnguarded(message, runOpts);
643
+ }
644
+ /** The core stream path, after input guardrails have run (M9). */
645
+ streamUnguarded(message, opts) {
646
+ const tools = opts.tools ? [
647
+ ...opts.tools
648
+ ] : this.compiled.tools;
649
+ const loop = this.resolvePerRunLoop(opts.maxIterations);
650
+ const streamFactory = opts.streamFactory ?? createSdkAgentStream(this.compiled, tools, opts.apiKey, {
651
+ model: opts.model,
652
+ reasoningEffort: opts.reasoningEffort,
653
+ parseThinkTags: opts.parseThinkTags,
654
+ stripToolDialect: opts.stripToolDialect,
655
+ recoverLeakedToolCalls: opts.recoverLeakedToolCalls,
656
+ cwd: opts.cwd,
657
+ baseDir: opts.baseDir,
658
+ plugins: opts.plugins,
659
+ providers: opts.providers,
660
+ agents: opts.agents,
661
+ budgetTracker: opts.budgetTracker,
662
+ sdkTools: opts.sdkTools
663
+ });
664
+ const sessionId = opts.sessionId ?? `runner-${crypto.randomUUID()}`;
665
+ return runReflectiveLoopStream(streamFactory, message, sessionId, {
666
+ loop,
667
+ reflection: this.reflectionStrategy,
668
+ budget: opts.budget,
669
+ agentName: this.agentName,
670
+ signal: opts.signal,
671
+ retry: opts.retry
672
+ });
673
+ }
674
+ /** Run the agent to a terminal result via the shared reflective loop (collect mode). */
675
+ /**
676
+ * Apply a per-call `maxIterations` override (M54 D4). A custom strategy must NOT be re-resolved by
677
+ * name — its name is outside the `z.enum`, which would throw — and its `shouldContinue` closure
678
+ * must survive; since the runner enforces the ceiling via `round < loop.maxIterations` (T1.1),
679
+ * overriding just that field bounds a custom without touching its logic. A built-in keeps the
680
+ * by-name re-resolution (zod fail-loud on `< 1`) — unchanged, zero-behavior.
681
+ */
682
+ resolvePerRunLoop(maxIterations) {
683
+ if (maxIterations == null) return this.loopStrategy;
684
+ if (this.loopStrategyIsCustom) {
685
+ const base = this.loopStrategy;
686
+ return Object.assign(Object.create(Object.getPrototypeOf(base)), base, {
687
+ maxIterations
688
+ });
689
+ }
690
+ return resolveLoopStrategy(this.loopStrategy.name, maxIterations);
691
+ }
692
+ async run(message, opts) {
693
+ const gen = this.stream(message, opts);
694
+ let res = await gen.next();
695
+ while (!res.done) res = await gen.next();
696
+ return res.value;
697
+ }
698
+ };
699
+ var AgentRunnerBuilder = class {
700
+ static {
701
+ __name(this, "AgentRunnerBuilder");
702
+ }
703
+ spec;
704
+ reflectionOverride;
705
+ streamEnabled = true;
706
+ compactionOverride;
707
+ loopStrategyOverride;
708
+ constructor(spec) {
709
+ this.spec = spec;
710
+ }
711
+ /** Override the default reflection strategy (OCP — plan Drawback #2). No arg ⇒ keep default. */
712
+ reflection(strategy) {
713
+ if (strategy) this.reflectionOverride = strategy;
714
+ return this;
715
+ }
716
+ /**
717
+ * M54 — inject a custom terminal-decision strategy (the fourth OCP axis, alongside
718
+ * `.reflection()`/`.compaction()`/`streamFactory`). WINS over the strategy the spec's name would
719
+ * resolve to, exactly as `.compaction()` outranks the spec. The runner caps ANY strategy at
720
+ * `custom.maxIterations` (T1.1), so a `shouldContinue: () => true` still terminates — never an
721
+ * infinite loop.
722
+ *
723
+ * @example
724
+ * ```ts
725
+ * // Stop as soon as the confidence in the last round crosses 0.9, else run to the ceiling.
726
+ * const stopWhenConfident: LoopStrategy = {
727
+ * name: 'confident',
728
+ * maxIterations: 8,
729
+ * shouldContinue: (o) => !o.responseText.includes('confidence: high'),
730
+ * }
731
+ * AgentRunner.fromSpec(spec).loopStrategy(stopWhenConfident).build()
732
+ * ```
733
+ */
734
+ loopStrategy(custom) {
735
+ assertValidCustomLoopStrategy(custom);
736
+ this.loopStrategyOverride = custom;
737
+ return this;
738
+ }
739
+ /** Record the streaming preference (see {@link AgentRunner.streamEnabled}). */
740
+ stream(enabled = true) {
741
+ this.streamEnabled = enabled;
742
+ return this;
743
+ }
744
+ /**
745
+ * V4-F: declare the compaction strategy (e.g. `.compaction('token-budget', { keepTokens: 8000 })`).
746
+ * Resolved + validated at {@link build} (EC-5 — fail-fast there, not here). This builder
747
+ * call WINS over a `@Compaction` decorator on the same agent (EC-1 — explicit override).
748
+ */
749
+ compaction(name, options = {}) {
750
+ this.compactionOverride = {
751
+ name,
752
+ keepTokens: options.keepTokens
753
+ };
754
+ return this;
755
+ }
756
+ /** Resolve strategies from the spec — the compile→execute boundary (no I/O). */
757
+ build() {
758
+ const { spec } = this;
759
+ const strategy = spec.strategy ?? "simple-chat";
760
+ const loopStrategyIsCustom = this.loopStrategyOverride !== void 0;
761
+ const loopStrategy = this.loopStrategyOverride ?? resolveLoopStrategy(strategy, spec.maxIterations);
762
+ const reflectionStrategy = this.reflectionOverride ?? (strategy === "plan-act-reflect" ? ladderReflectionStrategy : noopReflectionStrategy);
763
+ const compactionDecl = this.compactionOverride ?? spec.compaction;
764
+ const compaction = compactionDecl ? resolveCompactionStrategy(compactionDecl.name, {
765
+ keepTokens: compactionDecl.keepTokens
766
+ }) : void 0;
767
+ return new AgentRunner({
768
+ compiled: spec.compiled,
769
+ agentName: spec.name,
770
+ loopStrategy,
771
+ loopStrategyIsCustom,
772
+ reflectionStrategy,
773
+ streamEnabled: this.streamEnabled,
774
+ compaction
775
+ });
776
+ }
777
+ };
778
+
779
+ export {
780
+ DEFAULT_KEEP_TOKENS,
781
+ compactionStrategyConfigSchema,
782
+ resolveCompactionStrategy,
783
+ tokenBudgetCompactionStrategy,
784
+ DEFAULT_MAX_ITERATIONS,
785
+ loopStrategyConfigSchema,
786
+ resolveLoopStrategy,
787
+ reflectionStrategyConfigSchema,
788
+ ladderReflectionStrategy,
789
+ noopReflectionStrategy,
790
+ DelegationBudgetExceededError,
791
+ DelegationBudgetCostUnknownError,
792
+ BudgetExceededError,
793
+ DelegationError,
794
+ resolveRunBudget,
795
+ runReflectiveLoop,
796
+ AgentRunner,
797
+ AgentRunnerBuilder
798
+ };
799
+ //# sourceMappingURL=chunk-SAKSZKVK.js.map