@theokit/agents 16.0.0 → 16.1.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.
Files changed (37) hide show
  1. package/CHANGELOG.md +26 -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-3TE4PJZL.js} +62 -1137
  11. package/dist/chunk-3TE4PJZL.js.map +1 -0
  12. package/dist/{chunk-FIGLHWR2.js → chunk-4SXVNI5O.js} +7 -7
  13. package/dist/chunk-A2UVVEB3.js +799 -0
  14. package/dist/chunk-A2UVVEB3.js.map +1 -0
  15. package/dist/chunk-Z5SYU6Z6.js +353 -0
  16. package/dist/chunk-Z5SYU6Z6.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-4SXVNI5O.js.map} +0 -0
@@ -1,16 +1,12 @@
1
- import {
2
- hooksPlugin,
3
- inheritHooks
4
- } from "./chunk-MJ6FRILJ.js";
5
- import {
6
- compileAgentDefinition
7
- } from "./chunk-NIQJ4GZX.js";
8
1
  import {
9
2
  debugLog
10
3
  } from "./chunk-M5J3Q6YC.js";
11
4
  import {
12
5
  ConfigurationError
13
6
  } from "./chunk-Q65ZIFNK.js";
7
+ import {
8
+ compileAgentDefinition
9
+ } from "./chunk-NIQJ4GZX.js";
14
10
  import {
15
11
  createRunUsageMeter
16
12
  } from "./chunk-OXNDJSAJ.js";
@@ -1273,10 +1269,7 @@ function withStepCeiling(handle, maxIterations) {
1273
1269
  return handle.agentId;
1274
1270
  },
1275
1271
  dispose: /* @__PURE__ */ __name(() => handle.dispose(), "dispose"),
1276
- // Forwarded — see {@link SdkAgentHandle.generate} for why, and why it is not guarded.
1277
- ...handle.generate === void 0 ? {} : {
1278
- generate: handle.generate.bind(handle)
1279
- },
1272
+ ...forwardedMembers(handle),
1280
1273
  send: /* @__PURE__ */ __name((msg, sendOpts) => handle.send(msg, {
1281
1274
  maxIterations,
1282
1275
  ...sendOpts
@@ -1291,27 +1284,68 @@ function withGuardrails(handle, guardrails) {
1291
1284
  return handle.agentId;
1292
1285
  },
1293
1286
  dispose: /* @__PURE__ */ __name(() => handle.dispose(), "dispose"),
1294
- // Forwarded — see {@link SdkAgentHandle.generate} for why, and why it is not guarded.
1295
- ...handle.generate === void 0 ? {} : {
1296
- generate: handle.generate.bind(handle)
1297
- },
1287
+ ...forwardedMembers(handle),
1298
1288
  send: /* @__PURE__ */ __name(async (msg, sendOpts) => {
1299
1289
  const guarded = await runInputGuards(msg, guardrails);
1300
- const turn = await handle.send(guarded, sendOpts);
1301
- return {
1302
- wait: /* @__PURE__ */ __name(async () => {
1303
- const out = await turn.wait();
1304
- if (out.result === void 0) return out;
1305
- return {
1306
- ...out,
1307
- result: await runOutputGuards(out.result, guardrails)
1308
- };
1309
- }, "wait")
1310
- };
1290
+ return guardTurn(await handle.send(guarded, sendOpts), guardrails);
1311
1291
  }, "send")
1312
1292
  };
1313
1293
  }
1314
1294
  __name(withGuardrails, "withGuardrails");
1295
+ function forwardedMembers(handle) {
1296
+ return {
1297
+ ...handle.generate === void 0 ? {} : {
1298
+ generate: handle.generate.bind(handle)
1299
+ },
1300
+ ...handle.pluginManager === void 0 ? {} : {
1301
+ pluginManager: handle.pluginManager.bind(handle)
1302
+ }
1303
+ };
1304
+ }
1305
+ __name(forwardedMembers, "forwardedMembers");
1306
+ function guardTurn(turn, guardrails) {
1307
+ let outcome;
1308
+ const guardedOutcome = /* @__PURE__ */ __name(() => outcome ??= turn.wait().then(async (out) => out.result === void 0 ? out : {
1309
+ ...out,
1310
+ result: await runOutputGuards(out.result, guardrails)
1311
+ }), "guardedOutcome");
1312
+ return {
1313
+ wait: guardedOutcome,
1314
+ async *stream() {
1315
+ let out;
1316
+ try {
1317
+ out = await guardedOutcome();
1318
+ } catch (err) {
1319
+ if (!(err instanceof GuardrailError)) throw err;
1320
+ yield errorStatus(err.message);
1321
+ return;
1322
+ }
1323
+ if (out.result !== void 0) {
1324
+ yield {
1325
+ type: "assistant",
1326
+ message: {
1327
+ content: [
1328
+ {
1329
+ type: "text",
1330
+ text: out.result
1331
+ }
1332
+ ]
1333
+ }
1334
+ };
1335
+ }
1336
+ if (out.status === "error") yield errorStatus(out.error?.message ?? "run error");
1337
+ }
1338
+ };
1339
+ }
1340
+ __name(guardTurn, "guardTurn");
1341
+ function errorStatus(message) {
1342
+ return {
1343
+ type: "status",
1344
+ status: "ERROR",
1345
+ message
1346
+ };
1347
+ }
1348
+ __name(errorStatus, "errorStatus");
1315
1349
 
1316
1350
  // src/bridge/sdk-error.ts
1317
1351
  function sdkErrorEvent(err) {
@@ -1899,1085 +1933,6 @@ function toAgentFactory(def, opts) {
1899
1933
  }
1900
1934
  __name(toAgentFactory, "toAgentFactory");
1901
1935
 
1902
- // src/loop/compaction-strategy.ts
1903
- import { compactTranscript } from "@theokit/sdk/compaction";
1904
- import { z } from "zod";
1905
- var DEFAULT_KEEP_TOKENS = 8e3;
1906
- var compactionStrategyConfigSchema = z.object({
1907
- name: z.literal("token-budget"),
1908
- keepTokens: z.number().int().positive()
1909
- });
1910
- function resolveCompactionStrategy(name, config) {
1911
- const cfg = compactionStrategyConfigSchema.parse({
1912
- name,
1913
- keepTokens: config.keepTokens
1914
- });
1915
- return {
1916
- name: cfg.name,
1917
- keepTokens: cfg.keepTokens,
1918
- compact: /* @__PURE__ */ __name((messages, options) => compactTranscript(messages, {
1919
- keepTokens: options?.keepTokens ?? cfg.keepTokens,
1920
- summarize: options?.summarize,
1921
- marker: options?.marker,
1922
- summaryTemplate: options?.summaryTemplate,
1923
- // Default-safe: a thrown summarize keeps the transcript (app opts out via failSafe:false).
1924
- failSafe: options?.failSafe ?? true
1925
- }), "compact")
1926
- };
1927
- }
1928
- __name(resolveCompactionStrategy, "resolveCompactionStrategy");
1929
- var tokenBudgetCompactionStrategy = resolveCompactionStrategy("token-budget", {
1930
- keepTokens: DEFAULT_KEEP_TOKENS
1931
- });
1932
-
1933
- // src/loop/loop-strategy.ts
1934
- import { z as z2 } from "zod";
1935
- var DEFAULT_MAX_ITERATIONS = 8;
1936
- var maxIterationsSchema = z2.number().int().min(1);
1937
- var loopStrategyConfigSchema = z2.object({
1938
- name: z2.enum([
1939
- "simple-chat",
1940
- "plan-act-reflect",
1941
- "react"
1942
- ]),
1943
- maxIterations: maxIterationsSchema
1944
- });
1945
- function assertValidCustomLoopStrategy(strategy) {
1946
- const result = maxIterationsSchema.safeParse(strategy.maxIterations);
1947
- if (!result.success) {
1948
- throw new Error(`loopStrategy: invalid maxIterations (${String(strategy.maxIterations)}) \u2014 must be a finite integer \u2265 1 (otherwise the round < maxIterations ceiling never terminates)`);
1949
- }
1950
- }
1951
- __name(assertValidCustomLoopStrategy, "assertValidCustomLoopStrategy");
1952
- function resolveLoopStrategy(strategy, maxIterations = DEFAULT_MAX_ITERATIONS) {
1953
- const cfg = loopStrategyConfigSchema.parse({
1954
- name: strategy,
1955
- maxIterations
1956
- });
1957
- if (cfg.name === "simple-chat") {
1958
- return {
1959
- name: cfg.name,
1960
- maxIterations: cfg.maxIterations,
1961
- shouldContinue: /* @__PURE__ */ __name(() => false, "shouldContinue")
1962
- };
1963
- }
1964
- if (cfg.name === "plan-act-reflect") {
1965
- return {
1966
- name: cfg.name,
1967
- maxIterations: cfg.maxIterations,
1968
- shouldContinue: /* @__PURE__ */ __name((outcome) => outcome.round < cfg.maxIterations, "shouldContinue")
1969
- };
1970
- }
1971
- return {
1972
- name: cfg.name,
1973
- maxIterations: cfg.maxIterations,
1974
- shouldContinue: /* @__PURE__ */ __name((outcome) => outcome.finishReason === "tool-calls" && outcome.round < cfg.maxIterations, "shouldContinue")
1975
- };
1976
- }
1977
- __name(resolveLoopStrategy, "resolveLoopStrategy");
1978
-
1979
- // src/loop/reflection-strategy.ts
1980
- import { z as z3 } from "zod";
1981
- var reflectionStrategyConfigSchema = z3.object({
1982
- name: z3.string().min(1)
1983
- });
1984
- var ladderReflectionStrategy = {
1985
- name: "ladder",
1986
- reflect(outcome) {
1987
- if (outcome.finishReason === "tool-calls") {
1988
- return {
1989
- feedback: `Tool results received (round ${outcome.round}). Reflect on whether the goal is met; if not, refine the approach and continue.`,
1990
- continue: true
1991
- };
1992
- }
1993
- return {
1994
- continue: false
1995
- };
1996
- }
1997
- };
1998
- var noopReflectionStrategy = {
1999
- name: "noop",
2000
- reflect() {
2001
- return {
2002
- continue: true
2003
- };
2004
- }
2005
- };
2006
-
2007
- // src/bridge/delegation-types.ts
2008
- import { TheokitAgentError as TheokitAgentError4 } from "@theokit/sdk/errors";
2009
- function budgetMessage(agentName, actualCost, budgetLimit, refusal) {
2010
- const limit = `$${budgetLimit.toFixed(4)}`;
2011
- if (refusal === void 0) {
2012
- return `Agent "${agentName}" exceeded budget: $${actualCost.toFixed(4)} > ${limit}`;
2013
- }
2014
- if ("nothingToSpend" in refusal) {
2015
- return `Agent "${agentName}" stopped before its first round: its ${limit} limit leaves nothing to spend`;
2016
- }
2017
- if ("costUnknown" in refusal) {
2018
- 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)})`;
2019
- }
2020
- 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`;
2021
- }
2022
- __name(budgetMessage, "budgetMessage");
2023
- var DelegationBudgetExceededError = class extends TheokitAgentError4 {
2024
- static {
2025
- __name(this, "DelegationBudgetExceededError");
2026
- }
2027
- agentName;
2028
- actualCost;
2029
- budgetLimit;
2030
- name = "DelegationBudgetExceededError";
2031
- /** The cost the refused round was projected at; absent when the spend already passed the limit. */
2032
- projectedRoundCost;
2033
- constructor(agentName, actualCost, budgetLimit, refusal) {
2034
- super(budgetMessage(agentName, actualCost, budgetLimit, refusal), {
2035
- code: "DELEGATION_BUDGET_EXCEEDED",
2036
- // The budget does not refill on retry.
2037
- isRetryable: false
2038
- }), this.agentName = agentName, this.actualCost = actualCost, this.budgetLimit = budgetLimit;
2039
- this.projectedRoundCost = refusal !== void 0 && "projectedRoundCost" in refusal ? refusal.projectedRoundCost : void 0;
2040
- }
2041
- };
2042
- var DelegationBudgetCostUnknownError = class extends DelegationBudgetExceededError {
2043
- static {
2044
- __name(this, "DelegationBudgetCostUnknownError");
2045
- }
2046
- constructor(agentName, knownSpend, budgetLimit) {
2047
- super(agentName, knownSpend, budgetLimit, {
2048
- costUnknown: true
2049
- });
2050
- }
2051
- };
2052
- var BudgetExceededError = DelegationBudgetExceededError;
2053
- var DelegationError = class extends TheokitAgentError4 {
2054
- static {
2055
- __name(this, "DelegationError");
2056
- }
2057
- agentName;
2058
- cause;
2059
- name = "DelegationError";
2060
- constructor(agentName, cause) {
2061
- super(`Delegation to agent "${agentName}" failed: ${cause instanceof Error ? cause.message : String(cause)}`, {
2062
- code: "DELEGATION_FAILED",
2063
- // Not retryable AT THIS LEVEL: whether the underlying cause is transient is the cause's own
2064
- // answer, and `cause` is carried so a caller can ask it rather than guess from the wrapper.
2065
- isRetryable: false,
2066
- cause
2067
- }), this.agentName = agentName, this.cause = cause;
2068
- }
2069
- };
2070
-
2071
- // src/guardrails/terminal-frame.ts
2072
- async function* mirrorModeratedText(inner) {
2073
- let round = "";
2074
- let sawText = false;
2075
- let step = await inner.next();
2076
- while (!step.done) {
2077
- const event = step.value;
2078
- if (event.type === "text_delta" && typeof event.content === "string") {
2079
- round += event.content;
2080
- sawText = true;
2081
- }
2082
- if (event.type === "done") {
2083
- yield sawText ? {
2084
- ...event,
2085
- result: round
2086
- } : event;
2087
- round = "";
2088
- sawText = false;
2089
- } else {
2090
- yield event;
2091
- }
2092
- step = await inner.next();
2093
- }
2094
- return step.value;
2095
- }
2096
- __name(mirrorModeratedText, "mirrorModeratedText");
2097
-
2098
- // src/loop/run-budget.ts
2099
- function refuseNextRound(spent, lastRound, ceiling, agentName) {
2100
- if (!Number.isFinite(ceiling)) return void 0;
2101
- if (!lastRound.costKnown) return new DelegationBudgetCostUnknownError(agentName, spent, ceiling);
2102
- if (spent + lastRound.cost > ceiling) {
2103
- return new DelegationBudgetExceededError(agentName, spent, ceiling, {
2104
- projectedRoundCost: lastRound.cost
2105
- });
2106
- }
2107
- return void 0;
2108
- }
2109
- __name(refuseNextRound, "refuseNextRound");
2110
- function throwIfNextRoundRefused(spent, lastRound, ceiling, agentName, signal) {
2111
- if (signal?.aborted) return;
2112
- const refusal = refuseNextRound(spent, lastRound, ceiling, agentName);
2113
- if (refusal) throw refusal;
2114
- }
2115
- __name(throwIfNextRoundRefused, "throwIfNextRoundRefused");
2116
- function resolveRunBudget(budget, agentName, name = "budget") {
2117
- if (budget == null) return void 0;
2118
- let field = name;
2119
- let ceiling = budget;
2120
- if (typeof budget !== "number") {
2121
- if (budget.window !== void 0) {
2122
- throw new DelegationError(agentName, new Error(`${name}.window is not supported: a rolling budget needs spend persisted across runs`));
2123
- }
2124
- field = `${name}.maxCostUsd`;
2125
- ceiling = budget.maxCostUsd;
2126
- }
2127
- if (typeof ceiling !== "number" || Number.isNaN(ceiling)) {
2128
- throw new DelegationError(agentName, new Error(`${field} must be a number, got ${String(ceiling)}`));
2129
- }
2130
- if (ceiling <= 0) {
2131
- throw new DelegationBudgetExceededError(agentName, 0, ceiling, {
2132
- nothingToSpend: true
2133
- });
2134
- }
2135
- return ceiling;
2136
- }
2137
- __name(resolveRunBudget, "resolveRunBudget");
2138
-
2139
- // src/loop/round-usage.ts
2140
- var TOKEN_BUCKETS = [
2141
- "tokensInput",
2142
- "tokensOutput",
2143
- "reasoningTokens",
2144
- "cacheReadTokens",
2145
- "cacheWriteTokens"
2146
- ];
2147
- var DONE_USAGE_FIELDS = [
2148
- [
2149
- "tokens",
2150
- "totalTokens"
2151
- ],
2152
- [
2153
- "tokensInput",
2154
- "inputTokens"
2155
- ],
2156
- [
2157
- "tokensOutput",
2158
- "outputTokens"
2159
- ],
2160
- [
2161
- "reasoningTokens",
2162
- "reasoningTokens"
2163
- ],
2164
- [
2165
- "cacheReadTokens",
2166
- "cacheReadTokens"
2167
- ],
2168
- [
2169
- "cacheWriteTokens",
2170
- "cacheWriteTokens"
2171
- ]
2172
- ];
2173
- function applyDone(event, r) {
2174
- r.costKnown = typeof event.cost === "number" && Number.isFinite(event.cost);
2175
- r.cost = r.costKnown ? event.cost : 0;
2176
- const usage = event.usage ?? {};
2177
- for (const [field, key] of DONE_USAGE_FIELDS) r[field] = usage[key] ?? 0;
2178
- }
2179
- __name(applyDone, "applyDone");
2180
- function accumulateUsage(acc, r) {
2181
- acc.cost += r.cost;
2182
- if (!r.costKnown) acc.costUnknown = true;
2183
- acc.tokens += r.tokens;
2184
- for (const bucket of TOKEN_BUCKETS) acc[bucket] = (acc[bucket] ?? 0) + r[bucket];
2185
- }
2186
- __name(accumulateUsage, "accumulateUsage");
2187
-
2188
- // src/loop/run-reflective-loop.ts
2189
- function asString2(value, fallback) {
2190
- return typeof value === "string" ? value : fallback;
2191
- }
2192
- __name(asString2, "asString");
2193
- var NO_PROGRESS_THRESHOLD = 2;
2194
- var MAINLOOP_METRIC = "[THEO_AGENT_MAINLOOP_RUNTIME_APPLIED]";
2195
- var TOOL_CALLS = "tool-calls";
2196
- 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.";
2197
- function stableStringify(value) {
2198
- if (value === void 0) return "undefined";
2199
- if (value === null || typeof value !== "object") return JSON.stringify(value);
2200
- if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
2201
- const obj = value;
2202
- const entries = Object.keys(obj).sort((a, b) => a.localeCompare(b)).map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`);
2203
- return `{${entries.join(",")}}`;
2204
- }
2205
- __name(stableStringify, "stableStringify");
2206
- function roundSignature(toolCalls) {
2207
- return toolCalls.map((tc) => `${tc.name}:${stableStringify(tc.input)}`).sort((a, b) => a.localeCompare(b)).join(",");
2208
- }
2209
- __name(roundSignature, "roundSignature");
2210
- function terminalReason(reflectionContinue, roundReason, round, maxIterations) {
2211
- if (reflectionContinue && roundReason === TOOL_CALLS && round >= maxIterations) return "step_limit";
2212
- if (roundReason === TOOL_CALLS) return "stop";
2213
- return roundReason;
2214
- }
2215
- __name(terminalReason, "terminalReason");
2216
- var CONTINUE_PROMPT = "Continue from the prior turns above; finish the task and give a final answer.";
2217
- function buildPrompt(round, maxIterations, message, feedback) {
2218
- const hint = round === maxIterations ? `${STEP_LIMIT_HINT}
2219
-
2220
- ` : "";
2221
- const continuation = feedback ? `[reflection] ${feedback}` : CONTINUE_PROMPT;
2222
- const body = round === 1 ? message : continuation;
2223
- return hint + body;
2224
- }
2225
- __name(buildPrompt, "buildPrompt");
2226
- async function* consumeRoundOrThrow(inputs, agentName) {
2227
- try {
2228
- return yield* consumeOneRound(inputs.factory, inputs.prompt, inputs.sessionId, inputs.signal, inputs.retry);
2229
- } catch (err) {
2230
- if (err instanceof DelegationBudgetExceededError || err instanceof DelegationError || err instanceof GuardrailError) {
2231
- throw err;
2232
- }
2233
- throw new DelegationError(agentName, err);
2234
- }
2235
- }
2236
- __name(consumeRoundOrThrow, "consumeRoundOrThrow");
2237
- function finalize(acc, round, reason, strategyName) {
2238
- acc.rounds = round;
2239
- acc.finishReason = reason;
2240
- debugLog(MAINLOOP_METRIC, {
2241
- strategy: strategyName,
2242
- rounds: round,
2243
- terminal: reason
2244
- });
2245
- return acc;
2246
- }
2247
- __name(finalize, "finalize");
2248
- function deriveFinishReason(signals) {
2249
- if (signals.sawError) return "error";
2250
- if (signals.sawDone && signals.doneFinishReason === TOOL_CALLS) return TOOL_CALLS;
2251
- if (signals.sawToolResult) return TOOL_CALLS;
2252
- return "stop";
2253
- }
2254
- __name(deriveFinishReason, "deriveFinishReason");
2255
- function pushToolResult(event, r, callInputs) {
2256
- const id = asString2(event.callId, "");
2257
- const call = callInputs.get(id);
2258
- r.toolCalls.push({
2259
- id,
2260
- name: call?.name ?? asString2(event.toolName, "unknown"),
2261
- // Prefer the correlated tool_call input (real SDK shape); fall back to an input on the
2262
- // result event itself (some streams/tests carry it there), else {}.
2263
- input: call?.input ?? event.input ?? {},
2264
- output: asString2(event.output, "")
2265
- });
2266
- }
2267
- __name(pushToolResult, "pushToolResult");
2268
- function accumulateEvent(event, r, signals, callInputs) {
2269
- if (event.type === "text_delta" && typeof event.content === "string") {
2270
- r.responseText += event.content;
2271
- } else if (event.type === "tool_call") {
2272
- callInputs.set(asString2(event.callId, ""), {
2273
- name: asString2(event.toolName, "unknown"),
2274
- input: event.input ?? {}
2275
- });
2276
- } else if (event.type === "tool_result") {
2277
- signals.sawToolResult = true;
2278
- pushToolResult(event, r, callInputs);
2279
- } else if (event.type === "done") {
2280
- signals.sawDone = true;
2281
- signals.doneFinishReason = asString2(event.finishReason, "");
2282
- applyDone(event, r);
2283
- } else if (event.type === "error") {
2284
- signals.sawError = true;
2285
- r.errorMessage = asString2(event.message, "Unknown agent error");
2286
- }
2287
- }
2288
- __name(accumulateEvent, "accumulateEvent");
2289
- async function startRound(factory, prompt, sessionId, signal, retry) {
2290
- const open = /* @__PURE__ */ __name(async () => {
2291
- const it = factory(prompt, sessionId)[Symbol.asyncIterator]();
2292
- try {
2293
- return {
2294
- it,
2295
- first: await it.next()
2296
- };
2297
- } catch (err) {
2298
- await it.return?.(void 0);
2299
- throw err;
2300
- }
2301
- }, "open");
2302
- if (!retry) return open();
2303
- const { Retry } = await import("@theokit/sdk/retry");
2304
- return Retry.run(open, {
2305
- ...retry,
2306
- signal: retry.signal ?? signal
2307
- });
2308
- }
2309
- __name(startRound, "startRound");
2310
- async function* consumeOneRound(factory, prompt, sessionId, signal, retry) {
2311
- const r = {
2312
- responseText: "",
2313
- toolCalls: [],
2314
- cost: 0,
2315
- costKnown: false,
2316
- tokens: 0,
2317
- tokensInput: 0,
2318
- tokensOutput: 0,
2319
- reasoningTokens: 0,
2320
- cacheReadTokens: 0,
2321
- cacheWriteTokens: 0,
2322
- finishReason: "stop",
2323
- errorMessage: ""
2324
- };
2325
- const signals = {
2326
- sawError: false,
2327
- sawDone: false,
2328
- doneFinishReason: "",
2329
- sawToolResult: false
2330
- };
2331
- const callInputs = /* @__PURE__ */ new Map();
2332
- const { it, first } = await startRound(factory, prompt, sessionId, signal, retry);
2333
- let next = first;
2334
- while (!next.done) {
2335
- if (signal?.aborted) {
2336
- await it.return?.(void 0);
2337
- break;
2338
- }
2339
- yield next.value;
2340
- accumulateEvent(next.value, r, signals, callInputs);
2341
- next = await it.next();
2342
- }
2343
- r.finishReason = deriveFinishReason(signals);
2344
- return r;
2345
- }
2346
- __name(consumeOneRound, "consumeOneRound");
2347
- function ceilingRoundFactory(factory, round, maxIterations) {
2348
- if (round !== maxIterations) return factory;
2349
- return (m, s) => factory(m, s, {
2350
- disableTools: true
2351
- });
2352
- }
2353
- __name(ceilingRoundFactory, "ceilingRoundFactory");
2354
- async function* runReflectiveLoopStream(factory, message, sessionId, config) {
2355
- const { loop, reflection, budget = Number.POSITIVE_INFINITY, signal, agentName = loop.name, retry } = config;
2356
- const acc = {
2357
- response: "",
2358
- toolCalls: [],
2359
- cost: 0,
2360
- tokens: 0,
2361
- tokensInput: 0,
2362
- tokensOutput: 0,
2363
- reasoningTokens: 0,
2364
- cacheReadTokens: 0,
2365
- cacheWriteTokens: 0,
2366
- rounds: 0
2367
- };
2368
- const reflectionContext = {};
2369
- let round = 1;
2370
- let feedback;
2371
- let prevSig;
2372
- let stuck = 0;
2373
- while (!signal?.aborted) {
2374
- const prompt = buildPrompt(round, loop.maxIterations, message, feedback);
2375
- const roundFactory = ceilingRoundFactory(factory, round, loop.maxIterations);
2376
- const r = yield* consumeRoundOrThrow({
2377
- factory: roundFactory,
2378
- prompt,
2379
- sessionId,
2380
- signal,
2381
- retry
2382
- }, agentName);
2383
- acc.response += r.responseText;
2384
- acc.toolCalls.push(...r.toolCalls);
2385
- accumulateUsage(acc, r);
2386
- if (r.finishReason === "error") throw new DelegationError(agentName, r.errorMessage);
2387
- if (Number.isFinite(budget) && acc.cost > budget) {
2388
- throw new DelegationBudgetExceededError(agentName, acc.cost, budget);
2389
- }
2390
- if (r.finishReason === TOOL_CALLS && r.toolCalls.length > 0) {
2391
- const sig = roundSignature(r.toolCalls);
2392
- stuck = sig === prevSig ? stuck + 1 : 0;
2393
- if (stuck >= NO_PROGRESS_THRESHOLD) return finalize(acc, round, "no_progress", loop.name);
2394
- prevSig = sig;
2395
- }
2396
- const outcome = {
2397
- finishReason: r.finishReason,
2398
- round,
2399
- toolCalls: r.toolCalls,
2400
- responseText: r.responseText
2401
- };
2402
- const reflectionResult = reflection.reflect(outcome, reflectionContext);
2403
- if (!(reflectionResult.continue && loop.shouldContinue(outcome) && round < loop.maxIterations)) {
2404
- const reason = terminalReason(reflectionResult.continue, r.finishReason, round, loop.maxIterations);
2405
- return finalize(acc, round, reason, loop.name);
2406
- }
2407
- throwIfNextRoundRefused(acc.cost, r, budget, agentName, signal);
2408
- feedback = reflectionResult.feedback;
2409
- round += 1;
2410
- }
2411
- acc.rounds = round - 1;
2412
- return acc;
2413
- }
2414
- __name(runReflectiveLoopStream, "runReflectiveLoopStream");
2415
- async function runReflectiveLoop(factory, message, sessionId, config) {
2416
- const gen = runReflectiveLoopStream(factory, message, sessionId, config);
2417
- let res = await gen.next();
2418
- while (!res.done) res = await gen.next();
2419
- return res.value;
2420
- }
2421
- __name(runReflectiveLoop, "runReflectiveLoop");
2422
-
2423
- // src/loop/agent-runner.ts
2424
- var AgentRunner = class {
2425
- static {
2426
- __name(this, "AgentRunner");
2427
- }
2428
- compiled;
2429
- agentName;
2430
- /** The resolved terminal-decision strategy (parity with `delegate()`). */
2431
- loopStrategy;
2432
- /** M54 — whether {@link loopStrategy} is a caller-injected custom (see {@link AgentRunnerState}). */
2433
- loopStrategyIsCustom;
2434
- /** The resolved between-round reflection (default or `.reflection(custom)` override). */
2435
- reflectionStrategy;
2436
- /**
2437
- * Recorded streaming preference. The reflective loop currently always streams via
2438
- * the SDK `Run.stream()`; a non-streaming collect mode is future work — the flag is
2439
- * captured + exposed here, not yet branched on (honest per G10: documented, not a
2440
- * silent no-op).
2441
- */
2442
- streamEnabled;
2443
- /**
2444
- * V4-F: the resolved compaction strategy (from `@Compaction` or `.compaction()`),
2445
- * or `undefined` when neither is declared — compaction is opt-in (EC-4). CALLABLE
2446
- * by the app (ADR D1: `runner.compaction?.compact(messages, { summarize })`); the
2447
- * reflective loop does NOT auto-invoke it (the SDK owns per-turn context).
2448
- */
2449
- compaction;
2450
- constructor(state) {
2451
- this.compiled = state.compiled;
2452
- this.agentName = state.agentName;
2453
- this.loopStrategy = state.loopStrategy;
2454
- this.loopStrategyIsCustom = state.loopStrategyIsCustom ?? false;
2455
- this.reflectionStrategy = state.reflectionStrategy;
2456
- this.streamEnabled = state.streamEnabled;
2457
- this.compaction = state.compaction;
2458
- }
2459
- /** Start a fluent builder from an already-compiled spec. */
2460
- static fromSpec(spec) {
2461
- return new AgentRunnerBuilder(spec);
2462
- }
2463
- /**
2464
- * V4-D-stream: stream the agent's events LIVE across the reflective loop, returning
2465
- * the aggregated {@link DelegationResult} as the generator's return value. This is the
2466
- * on-ramp for streaming-first apps (SSE) — `runReflectiveLoopStream` yields every
2467
- * round's events before the loop terminates. `streamEnabled` is honored: when the
2468
- * builder set `.stream(false)`, callers should use {@link run} instead.
2469
- */
2470
- stream(message, opts) {
2471
- const runOpts = {
2472
- ...opts,
2473
- budget: resolveRunBudget(opts.budget, this.agentName)
2474
- };
2475
- const guardrails = this.compiled.guardrails;
2476
- if (guardrails && guardrails.length > 0) {
2477
- const runUnguarded = /* @__PURE__ */ __name((m) => this.streamUnguarded(m, runOpts), "runUnguarded");
2478
- return (/* @__PURE__ */ __name(async function* guarded() {
2479
- const safe = await runInputGuards(message, guardrails);
2480
- return yield* mirrorModeratedText(
2481
- // #732 — the fourth channel, and the one the `done` fix cannot reach. A milestone is not
2482
- // a mirror of anything: it carries text the model writes through `task-tools`, so it gets
2483
- // its own pass like the two below. One pass per kind, because two kinds under one
2484
- // extractor collapse into a single event.
2485
- //
2486
- // `task-tools.ts` claimed B-018 had already shipped this. It had not — `agent-endpoint.ts`
2487
- // said in the same tree that the channel was NOT covered, and the claim is corrected there
2488
- // rather than deleted.
2489
- moderateOutputStream(
2490
- moderateOutputStream(
2491
- moderateOutputStream(
2492
- runUnguarded(safe),
2493
- guardrails,
2494
- // B-021 — the shared extractor, so "this kind, content unreadable" throws instead of
2495
- // sharing a return value with "not this kind". The hand-written form here returned
2496
- // `undefined` for a non-string, which reads as "carries no text": the payload was
2497
- // never shown to a guard and was yielded verbatim.
2498
- textPayloadExtractor("text_delta", (e) => e.content),
2499
- (content) => ({
2500
- type: "text_delta",
2501
- content
2502
- }),
2503
- (content, result) => ({
2504
- ...result,
2505
- response: content
2506
- })
2507
- ),
2508
- guardrails,
2509
- textPayloadExtractor("thinking", (e) => e.content),
2510
- (content) => ({
2511
- type: "thinking",
2512
- content
2513
- }),
2514
- // The reasoning pass does NOT touch the aggregate — the visible pass already did.
2515
- (_content, result) => result
2516
- ),
2517
- guardrails,
2518
- textPayloadExtractor("task_progress", (e) => e.text),
2519
- (text) => ({
2520
- type: "task_progress",
2521
- text
2522
- }),
2523
- // A milestone is not the answer — the visible pass owns the aggregate.
2524
- (_text, result) => result
2525
- )
2526
- );
2527
- }, "guarded"))();
2528
- }
2529
- return this.streamUnguarded(message, runOpts);
2530
- }
2531
- /** The core stream path, after input guardrails have run (M9). */
2532
- streamUnguarded(message, opts) {
2533
- const tools = opts.tools ? [
2534
- ...opts.tools
2535
- ] : this.compiled.tools;
2536
- const loop = this.resolvePerRunLoop(opts.maxIterations);
2537
- const streamFactory = opts.streamFactory ?? createSdkAgentStream(this.compiled, tools, opts.apiKey, {
2538
- model: opts.model,
2539
- reasoningEffort: opts.reasoningEffort,
2540
- parseThinkTags: opts.parseThinkTags,
2541
- stripToolDialect: opts.stripToolDialect,
2542
- recoverLeakedToolCalls: opts.recoverLeakedToolCalls,
2543
- cwd: opts.cwd,
2544
- baseDir: opts.baseDir,
2545
- plugins: opts.plugins,
2546
- providers: opts.providers,
2547
- agents: opts.agents,
2548
- budgetTracker: opts.budgetTracker,
2549
- sdkTools: opts.sdkTools
2550
- });
2551
- const sessionId = opts.sessionId ?? `runner-${crypto.randomUUID()}`;
2552
- return runReflectiveLoopStream(streamFactory, message, sessionId, {
2553
- loop,
2554
- reflection: this.reflectionStrategy,
2555
- budget: opts.budget,
2556
- agentName: this.agentName,
2557
- signal: opts.signal,
2558
- retry: opts.retry
2559
- });
2560
- }
2561
- /** Run the agent to a terminal result via the shared reflective loop (collect mode). */
2562
- /**
2563
- * Apply a per-call `maxIterations` override (M54 D4). A custom strategy must NOT be re-resolved by
2564
- * name — its name is outside the `z.enum`, which would throw — and its `shouldContinue` closure
2565
- * must survive; since the runner enforces the ceiling via `round < loop.maxIterations` (T1.1),
2566
- * overriding just that field bounds a custom without touching its logic. A built-in keeps the
2567
- * by-name re-resolution (zod fail-loud on `< 1`) — unchanged, zero-behavior.
2568
- */
2569
- resolvePerRunLoop(maxIterations) {
2570
- if (maxIterations == null) return this.loopStrategy;
2571
- if (this.loopStrategyIsCustom) {
2572
- const base = this.loopStrategy;
2573
- return Object.assign(Object.create(Object.getPrototypeOf(base)), base, {
2574
- maxIterations
2575
- });
2576
- }
2577
- return resolveLoopStrategy(this.loopStrategy.name, maxIterations);
2578
- }
2579
- async run(message, opts) {
2580
- const gen = this.stream(message, opts);
2581
- let res = await gen.next();
2582
- while (!res.done) res = await gen.next();
2583
- return res.value;
2584
- }
2585
- };
2586
- var AgentRunnerBuilder = class {
2587
- static {
2588
- __name(this, "AgentRunnerBuilder");
2589
- }
2590
- spec;
2591
- reflectionOverride;
2592
- streamEnabled = true;
2593
- compactionOverride;
2594
- loopStrategyOverride;
2595
- constructor(spec) {
2596
- this.spec = spec;
2597
- }
2598
- /** Override the default reflection strategy (OCP — plan Drawback #2). No arg ⇒ keep default. */
2599
- reflection(strategy) {
2600
- if (strategy) this.reflectionOverride = strategy;
2601
- return this;
2602
- }
2603
- /**
2604
- * M54 — inject a custom terminal-decision strategy (the fourth OCP axis, alongside
2605
- * `.reflection()`/`.compaction()`/`streamFactory`). WINS over the strategy the spec's name would
2606
- * resolve to, exactly as `.compaction()` outranks the spec. The runner caps ANY strategy at
2607
- * `custom.maxIterations` (T1.1), so a `shouldContinue: () => true` still terminates — never an
2608
- * infinite loop.
2609
- *
2610
- * @example
2611
- * ```ts
2612
- * // Stop as soon as the confidence in the last round crosses 0.9, else run to the ceiling.
2613
- * const stopWhenConfident: LoopStrategy = {
2614
- * name: 'confident',
2615
- * maxIterations: 8,
2616
- * shouldContinue: (o) => !o.responseText.includes('confidence: high'),
2617
- * }
2618
- * AgentRunner.fromSpec(spec).loopStrategy(stopWhenConfident).build()
2619
- * ```
2620
- */
2621
- loopStrategy(custom) {
2622
- assertValidCustomLoopStrategy(custom);
2623
- this.loopStrategyOverride = custom;
2624
- return this;
2625
- }
2626
- /** Record the streaming preference (see {@link AgentRunner.streamEnabled}). */
2627
- stream(enabled = true) {
2628
- this.streamEnabled = enabled;
2629
- return this;
2630
- }
2631
- /**
2632
- * V4-F: declare the compaction strategy (e.g. `.compaction('token-budget', { keepTokens: 8000 })`).
2633
- * Resolved + validated at {@link build} (EC-5 — fail-fast there, not here). This builder
2634
- * call WINS over a `@Compaction` decorator on the same agent (EC-1 — explicit override).
2635
- */
2636
- compaction(name, options = {}) {
2637
- this.compactionOverride = {
2638
- name,
2639
- keepTokens: options.keepTokens
2640
- };
2641
- return this;
2642
- }
2643
- /** Resolve strategies from the spec — the compile→execute boundary (no I/O). */
2644
- build() {
2645
- const { spec } = this;
2646
- const strategy = spec.strategy ?? "simple-chat";
2647
- const loopStrategyIsCustom = this.loopStrategyOverride !== void 0;
2648
- const loopStrategy = this.loopStrategyOverride ?? resolveLoopStrategy(strategy, spec.maxIterations);
2649
- const reflectionStrategy = this.reflectionOverride ?? (strategy === "plan-act-reflect" ? ladderReflectionStrategy : noopReflectionStrategy);
2650
- const compactionDecl = this.compactionOverride ?? spec.compaction;
2651
- const compaction = compactionDecl ? resolveCompactionStrategy(compactionDecl.name, {
2652
- keepTokens: compactionDecl.keepTokens
2653
- }) : void 0;
2654
- return new AgentRunner({
2655
- compiled: spec.compiled,
2656
- agentName: spec.name,
2657
- loopStrategy,
2658
- loopStrategyIsCustom,
2659
- reflectionStrategy,
2660
- streamEnabled: this.streamEnabled,
2661
- compaction
2662
- });
2663
- }
2664
- };
2665
-
2666
- // src/loop/goal-runner.ts
2667
- import { runGoalLoop } from "@theokit/sdk";
2668
- import { JudgeCredentialError } from "@theokit/sdk";
2669
- var GoalRunner = class {
2670
- static {
2671
- __name(this, "GoalRunner");
2672
- }
2673
- agent;
2674
- constructor(agent) {
2675
- this.agent = agent;
2676
- }
2677
- /**
2678
- * Drive `goal` to completion against the bound agent. Returns the SAME async generator `runGoalLoop`
2679
- * returns — yielding `GoalEvent`s, resolving a `GoalResult`. `deps` (judge/clock overrides) threads
2680
- * straight through; a test seam for the judge lives there, exactly as on the free function.
2681
- */
2682
- run(goal, options, deps) {
2683
- return runGoalLoop(this.agent, goal, options, deps);
2684
- }
2685
- };
2686
-
2687
- // src/loop/format-goal-event.ts
2688
- function formatGoalEvent(event) {
2689
- const candidate = event;
2690
- if (candidate === null || typeof candidate !== "object" || typeof candidate.type !== "string") {
2691
- return "[goal] unrecognised event (malformed)";
2692
- }
2693
- switch (event.type) {
2694
- case "turn_start":
2695
- return `[goal] turn ${event.turn} started \u2014 ${event.goal}`;
2696
- case "agent_response":
2697
- return `[goal] turn ${event.turn} response: ${event.content}`;
2698
- case "judge_verdict":
2699
- return `[goal] turn ${event.turn} judged ${event.verdict}: ${event.reason}` + // Surfaced rather than hidden: a verdict the judge could not parse reached a decision by
2700
- // fallback, and an operator reading the log needs to know which of the two happened.
2701
- (event.parseFailed ? " (verdict could not be parsed)" : "");
2702
- case "continuation":
2703
- return `[goal] turn ${event.turn} continuing: ${event.prompt}`;
2704
- case "status_change":
2705
- return `[goal] status ${event.status}: ${event.reason}`;
2706
- default:
2707
- return formatUnrecognised(event);
2708
- }
2709
- }
2710
- __name(formatGoalEvent, "formatGoalEvent");
2711
- function formatUnrecognised(event) {
2712
- const { type } = event;
2713
- return `[goal] unrecognised event: ${String(type)}`;
2714
- }
2715
- __name(formatUnrecognised, "formatUnrecognised");
2716
-
2717
- // src/loop/pre-compaction.ts
2718
- import { TheokitAgentError as TheokitAgentError5 } from "@theokit/sdk/errors";
2719
- var DEFAULT_HANDLER_TIMEOUT_MS = 3e4;
2720
- var PreCompactionHandlerError = class extends TheokitAgentError5 {
2721
- static {
2722
- __name(this, "PreCompactionHandlerError");
2723
- }
2724
- name = "PreCompactionHandlerError";
2725
- /** `'timeout'` when the bound was exceeded, `'threw'` when the handler failed on its own. */
2726
- reason;
2727
- constructor(message, reason, options) {
2728
- super(message, {
2729
- code: "PRE_COMPACTION_HANDLER_FAILED",
2730
- ...options ?? {}
2731
- });
2732
- this.reason = reason;
2733
- }
2734
- };
2735
- function assertUsableTimeout(timeoutMs) {
2736
- if (!Number.isFinite(timeoutMs) || timeoutMs <= 0) {
2737
- throw new TypeError(`withPreCompaction: timeoutMs must be a finite number greater than 0, received ${String(timeoutMs)}`);
2738
- }
2739
- }
2740
- __name(assertUsableTimeout, "assertUsableTimeout");
2741
- async function runHandlerBounded(handler, messages, timeoutMs, onError) {
2742
- let timer;
2743
- const controller = new AbortController();
2744
- try {
2745
- await Promise.race([
2746
- Promise.resolve(handler(messages, controller.signal)),
2747
- new Promise((_resolve, reject) => {
2748
- timer = setTimeout(() => {
2749
- controller.abort();
2750
- reject(new PreCompactionHandlerError(`pre-compaction handler exceeded its ${String(timeoutMs)}ms bound; compaction proceeded without it`, "timeout"));
2751
- }, timeoutMs);
2752
- })
2753
- ]);
2754
- } catch (cause) {
2755
- const detail = cause instanceof Error ? cause.message : String(cause);
2756
- const reported = cause instanceof PreCompactionHandlerError ? cause : new PreCompactionHandlerError(`pre-compaction handler failed: ${detail}`, "threw", {
2757
- cause
2758
- });
2759
- onError?.(reported);
2760
- } finally {
2761
- if (timer !== void 0) clearTimeout(timer);
2762
- }
2763
- }
2764
- __name(runHandlerBounded, "runHandlerBounded");
2765
- function withPreCompaction(strategy, handler, options) {
2766
- const timeoutMs = options?.timeoutMs ?? DEFAULT_HANDLER_TIMEOUT_MS;
2767
- assertUsableTimeout(timeoutMs);
2768
- const onError = options?.onError;
2769
- return {
2770
- name: strategy.name,
2771
- keepTokens: strategy.keepTokens,
2772
- compact: /* @__PURE__ */ __name(async (messages, callOptions) => {
2773
- await runHandlerBounded(handler, [
2774
- ...messages
2775
- ], timeoutMs, onError);
2776
- return strategy.compact(messages, callOptions);
2777
- }, "compact")
2778
- };
2779
- }
2780
- __name(withPreCompaction, "withPreCompaction");
2781
-
2782
- // src/loop/decomposition.ts
2783
- function resolveDecomposition(callerSubgoals, declared) {
2784
- if (declared.length > 0) return declared;
2785
- return callerSubgoals;
2786
- }
2787
- __name(resolveDecomposition, "resolveDecomposition");
2788
-
2789
- // src/bridge/agent-orchestrator.ts
2790
- function requireApiKey(opts, agentName) {
2791
- if (opts.apiKey === null) return "";
2792
- const apiKey = opts.apiKey ?? "";
2793
- if (!apiKey) {
2794
- throw new DelegationError(agentName, "No API key provided. Pass apiKey in DelegateOptions, or `apiKey: null` when the provider takes no credential (a local model).");
2795
- }
2796
- return apiKey;
2797
- }
2798
- __name(requireApiKey, "requireApiKey");
2799
- function withInheritedHooks(compiled, parentHooks) {
2800
- const plugin = hooksPlugin(inheritHooks(parentHooks, void 0));
2801
- if (plugin === void 0) return compiled;
2802
- return {
2803
- ...compiled,
2804
- plugins: [
2805
- ...compiled.plugins ?? [],
2806
- plugin
2807
- ]
2808
- };
2809
- }
2810
- __name(withInheritedHooks, "withInheritedHooks");
2811
- function mergeTools(parentTools, subTools) {
2812
- const subToolNames = new Set(subTools.map((t) => t.name));
2813
- const inherited = parentTools.filter((t) => !subToolNames.has(t.name));
2814
- return [
2815
- ...inherited,
2816
- ...subTools
2817
- ];
2818
- }
2819
- __name(mergeTools, "mergeTools");
2820
- async function delegate(spec, message, opts = {}) {
2821
- const apiKey = requireApiKey(opts, spec.name);
2822
- const budget = Math.min(resolveRunBudget(opts.budget, spec.name) ?? Infinity, resolveRunBudget(opts.parentBudgetRemaining, spec.name, "parentBudgetRemaining") ?? Infinity);
2823
- const rewritten = opts.onDelegationStart ? await opts.onDelegationStart({
2824
- subAgent: spec.name,
2825
- input: message
2826
- }) : message;
2827
- const { compiled } = spec;
2828
- const guardrails = compiled.guardrails ?? [];
2829
- const effectiveMessage = await runInputGuards(rewritten, guardrails);
2830
- const allTools = mergeTools(opts.parentTools ?? [], compiled.tools);
2831
- const compiledForMember = withInheritedHooks(compiled, opts.parentHooks);
2832
- const streamFactory = opts.streamFactory ?? createSdkAgentStream(compiledForMember, allTools, apiKey, {
2833
- model: opts.model ?? compiled.model,
2834
- cwd: opts.cwd,
2835
- plugins: opts.plugins,
2836
- providers: opts.providers,
2837
- agents: opts.agents,
2838
- budgetTracker: opts.budgetTracker,
2839
- sdkTools: opts.sdkTools
2840
- });
2841
- const sessionId = opts.sessionId ?? `sub-${crypto.randomUUID()}`;
2842
- const loopStrategy = resolveLoopStrategy(spec.strategy ?? "simple-chat", opts.maxIterations ?? spec.maxIterations);
2843
- const reflection = opts.reflection ?? (loopStrategy.name === "plan-act-reflect" ? ladderReflectionStrategy : noopReflectionStrategy);
2844
- const result = await runReflectiveLoop(streamFactory, effectiveMessage, sessionId, {
2845
- loop: loopStrategy,
2846
- reflection,
2847
- budget,
2848
- agentName: spec.name,
2849
- signal: opts.signal,
2850
- retry: opts.retry
2851
- });
2852
- const transformed = opts.onDelegationComplete ? await opts.onDelegationComplete({
2853
- subAgent: spec.name,
2854
- result
2855
- }) : result;
2856
- return await moderateDelegationResult(transformed, guardrails);
2857
- }
2858
- __name(delegate, "delegate");
2859
- async function moderateDelegationResult(result, guardrails) {
2860
- if (guardrails.length === 0) return result;
2861
- return {
2862
- ...result,
2863
- response: await runOutputGuards(result.response, guardrails)
2864
- };
2865
- }
2866
- __name(moderateDelegationResult, "moderateDelegationResult");
2867
-
2868
- // src/bridge/delegation-lifecycle.ts
2869
- import { TheokitAgentError as TheokitAgentError6 } from "@theokit/sdk/errors";
2870
- var DelegationTimeoutError = class extends TheokitAgentError6 {
2871
- static {
2872
- __name(this, "DelegationTimeoutError");
2873
- }
2874
- name = "DelegationTimeoutError";
2875
- constructor(subAgent, timeoutMs) {
2876
- super(`delegation to "${subAgent}" exceeded its ${String(timeoutMs)} ms clock cap. This is a WALL CLOCK limit, not a budget: the run may have been progressing and simply slow, or hung. Raise \`timeoutMs\` if the work legitimately takes longer.`, {
2877
- code: "DELEGATION_TIMEOUT",
2878
- // A hang is often transient — the model, a tool or a network call. Unlike the budget errors,
2879
- // this one is worth another attempt, which is exactly why it is a separate class.
2880
- isRetryable: true
2881
- });
2882
- }
2883
- };
2884
- async function withClockCap(promise, timeoutMs, subAgent) {
2885
- let timer;
2886
- const clock = new Promise((_resolve, reject) => {
2887
- timer = setTimeout(() => {
2888
- reject(new DelegationTimeoutError(subAgent, timeoutMs));
2889
- }, timeoutMs);
2890
- });
2891
- try {
2892
- return await Promise.race([
2893
- promise,
2894
- clock
2895
- ]);
2896
- } finally {
2897
- if (timer !== void 0) clearTimeout(timer);
2898
- }
2899
- }
2900
- __name(withClockCap, "withClockCap");
2901
- async function withEphemeralAgent(create, body, options = {}) {
2902
- const { agent, dispose } = await create();
2903
- try {
2904
- return await body(agent);
2905
- } finally {
2906
- try {
2907
- await dispose();
2908
- } catch (error) {
2909
- options.onDisposeError?.(error);
2910
- }
2911
- }
2912
- }
2913
- __name(withEphemeralAgent, "withEphemeralAgent");
2914
-
2915
- // src/bridge/delegation-scoring.ts
2916
- function isPort(target) {
2917
- if ("compiled" in target) return false;
2918
- return typeof target.run === "function";
2919
- }
2920
- __name(isPort, "isPort");
2921
- async function runOnce(target, message, delegateFn, opts) {
2922
- const port = isPort(target);
2923
- const started = port ? target.run(message) : delegateFn(target, message, opts);
2924
- if (opts.timeoutMs === void 0) return started;
2925
- return withClockCap(started, opts.timeoutMs, port ? "port" : target.name);
2926
- }
2927
- __name(runOnce, "runOnce");
2928
- function delegateBackground(subAgent, message, opts = {}) {
2929
- const { delegateFn = delegate, ...delegateOpts } = opts;
2930
- let isSettled = false;
2931
- const promise = runOnce(subAgent, message, delegateFn, delegateOpts).finally(() => {
2932
- isSettled = true;
2933
- });
2934
- promise.catch(() => void 0);
2935
- return {
2936
- wait: /* @__PURE__ */ __name(() => promise, "wait"),
2937
- settled: /* @__PURE__ */ __name(() => isSettled, "settled")
2938
- };
2939
- }
2940
- __name(delegateBackground, "delegateBackground");
2941
- var DEFAULT_MAX_ROUNDS = 3;
2942
- function defaultFeedbackTemplate(message, feedback) {
2943
- return `${message}
2944
-
2945
- Feedback from the reviewer (address this): ${feedback}`;
2946
- }
2947
- __name(defaultFeedbackTemplate, "defaultFeedbackTemplate");
2948
- async function delegateWithScoring(subAgent, message, opts) {
2949
- const { scorer, maxRounds: maxRoundsOpt = DEFAULT_MAX_ROUNDS, delegateFn = delegate, feedbackTemplate = defaultFeedbackTemplate, ...delegateOpts } = opts;
2950
- const maxRounds = Math.max(1, maxRoundsOpt);
2951
- const verdicts = [];
2952
- let currentMessage = message;
2953
- let lastResult;
2954
- for (let round = 1; round <= maxRounds; round++) {
2955
- const result = await runOnce(subAgent, currentMessage, delegateFn, delegateOpts);
2956
- lastResult = result;
2957
- const verdict = await scorer(result);
2958
- verdicts.push(verdict);
2959
- if (verdict.pass) {
2960
- return {
2961
- result,
2962
- rounds: round,
2963
- passed: true,
2964
- verdicts
2965
- };
2966
- }
2967
- if (verdict.feedback) currentMessage = feedbackTemplate(message, verdict.feedback);
2968
- }
2969
- if (lastResult === void 0) {
2970
- throw new Error("[@theokit/agents] delegateWithScoring: no round ran (maxRounds < 1)");
2971
- }
2972
- return {
2973
- result: lastResult,
2974
- rounds: maxRounds,
2975
- passed: false,
2976
- verdicts
2977
- };
2978
- }
2979
- __name(delegateWithScoring, "delegateWithScoring");
2980
-
2981
1936
  export {
2982
1937
  projectContextMetadataOnlyKnobs,
2983
1938
  compileProjectContext,
@@ -3010,36 +1965,6 @@ export {
3010
1965
  createThinkTagExtractor,
3011
1966
  extractThinkTagStream,
3012
1967
  createSdkAgentStream,
3013
- toAgentFactory,
3014
- DEFAULT_KEEP_TOKENS,
3015
- compactionStrategyConfigSchema,
3016
- resolveCompactionStrategy,
3017
- tokenBudgetCompactionStrategy,
3018
- DEFAULT_MAX_ITERATIONS,
3019
- loopStrategyConfigSchema,
3020
- resolveLoopStrategy,
3021
- reflectionStrategyConfigSchema,
3022
- ladderReflectionStrategy,
3023
- noopReflectionStrategy,
3024
- DelegationBudgetExceededError,
3025
- DelegationBudgetCostUnknownError,
3026
- BudgetExceededError,
3027
- DelegationError,
3028
- AgentRunner,
3029
- AgentRunnerBuilder,
3030
- GoalRunner,
3031
- JudgeCredentialError,
3032
- formatGoalEvent,
3033
- DEFAULT_HANDLER_TIMEOUT_MS,
3034
- PreCompactionHandlerError,
3035
- withPreCompaction,
3036
- resolveDecomposition,
3037
- delegate,
3038
- DelegationTimeoutError,
3039
- withClockCap,
3040
- withEphemeralAgent,
3041
- isPort,
3042
- delegateBackground,
3043
- delegateWithScoring
1968
+ toAgentFactory
3044
1969
  };
3045
- //# sourceMappingURL=chunk-4PHZ25JN.js.map
1970
+ //# sourceMappingURL=chunk-3TE4PJZL.js.map