@tangle-network/agent-runtime 0.313.2 → 0.314.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 (51) hide show
  1. package/dist/{activation-B_dUMaW8.js → activation-feDZcn-R.js} +2 -2
  2. package/dist/{activation-B_dUMaW8.js.map → activation-feDZcn-R.js.map} +1 -1
  3. package/dist/{activation-yAlZTwYG.d.ts → activation-qaeBges3.d.ts} +2 -2
  4. package/dist/agent.d.ts +1 -1
  5. package/dist/agent.js +2 -2
  6. package/dist/{coordination-driver-26qkTbVh.js → coordination-driver-Bzrkge9N.js} +2 -2
  7. package/dist/{coordination-driver-26qkTbVh.js.map → coordination-driver-Bzrkge9N.js.map} +1 -1
  8. package/dist/{delegate-C0ZXShbu.js → delegate-BYJ8DfDq.js} +2 -2
  9. package/dist/{delegate-C0ZXShbu.js.map → delegate-BYJ8DfDq.js.map} +1 -1
  10. package/dist/durable.d.ts +1 -1
  11. package/dist/durable.js +2 -2
  12. package/dist/{graph-BF6LYqON.js → graph-CtzVgJhO.js} +4 -4
  13. package/dist/{graph-BF6LYqON.js.map → graph-CtzVgJhO.js.map} +1 -1
  14. package/dist/{improvement-cycle-C-F2WKKO.js → improvement-cycle-B5S_Z2dn.js} +3 -3
  15. package/dist/{improvement-cycle-C-F2WKKO.js.map → improvement-cycle-B5S_Z2dn.js.map} +1 -1
  16. package/dist/{index-Lm_RjfXs.d.ts → index-BqKSQheO.d.ts} +4 -2
  17. package/dist/index.d.ts +4 -4
  18. package/dist/index.js +7 -7
  19. package/dist/intelligence.d.ts +2 -2
  20. package/dist/intelligence.js +3 -3
  21. package/dist/kernel.d.ts +1 -1
  22. package/dist/kernel.js +8 -8
  23. package/dist/{loop-runner-bin-CliCf9sW.d.ts → loop-runner-bin-BFNIBkkr.d.ts} +2 -2
  24. package/dist/{loop-runner-bin-CreO-bam.js → loop-runner-bin-BV3DTvLk.js} +3 -3
  25. package/dist/{loop-runner-bin-CreO-bam.js.map → loop-runner-bin-BV3DTvLk.js.map} +1 -1
  26. package/dist/loop-runner-bin.d.ts +1 -1
  27. package/dist/loop-runner-bin.js +1 -1
  28. package/dist/mcp/bin.js +3 -3
  29. package/dist/mcp/index.d.ts +2 -2
  30. package/dist/mcp/index.js +4 -4
  31. package/dist/model-policy-DhvyZ8-O.js.map +1 -1
  32. package/dist/{openai-tools-BrOgOw66.d.ts → openai-tools-CzU4e76d.d.ts} +2 -2
  33. package/dist/profiles.d.ts +1 -1
  34. package/dist/{provision-supervisor-nV0XW_vi.js → provision-supervisor-BIwTaa6O.js} +3 -3
  35. package/dist/{provision-supervisor-nV0XW_vi.js.map → provision-supervisor-BIwTaa6O.js.map} +1 -1
  36. package/dist/{runtime-sx7Qtw4g.js → runtime-66oKOxeF.js} +8 -8
  37. package/dist/{runtime-sx7Qtw4g.js.map → runtime-66oKOxeF.js.map} +1 -1
  38. package/dist/{search-executor-emDfPe_k.js → search-executor-HUVofl1c.js} +2 -2
  39. package/dist/{search-executor-emDfPe_k.js.map → search-executor-HUVofl1c.js.map} +1 -1
  40. package/dist/{server-DgdTtcch.js → server-cRxGXPyr.js} +3 -3
  41. package/dist/{server-DgdTtcch.js.map → server-cRxGXPyr.js.map} +1 -1
  42. package/dist/{supervise-pxhnrGsA.js → supervise-DmpAprU1.js} +3 -3
  43. package/dist/{supervise-pxhnrGsA.js.map → supervise-DmpAprU1.js.map} +1 -1
  44. package/dist/{supervisor-yX008JOQ.js → supervisor-Bnjo-yDg.js} +180 -84
  45. package/dist/supervisor-Bnjo-yDg.js.map +1 -0
  46. package/dist/testing.d.ts +1 -1
  47. package/dist/testing.js +12 -12
  48. package/dist/tui/index.d.ts +1 -1
  49. package/dist/tui/index.js +1 -1
  50. package/package.json +1 -1
  51. package/dist/supervisor-yX008JOQ.js.map +0 -1
@@ -7105,22 +7105,24 @@ function checkpointSlots(port) {
7105
7105
  * holds every file of the returned tree and, when the checkpoint took a marker, that the tree
7106
7106
  * holds the marker's exact bytes, which proves it read this checkpoint and no other state.
7107
7107
  */
7108
- async function captureProviderCheckpointWorkspace(port, context, marker) {
7108
+ async function captureProviderCheckpointWorkspace(port, prepare, marker, parent) {
7109
7109
  assertProviderWorkspaceRetentionPort(port, "provider workspace retention");
7110
7110
  const capture = port.captureCheckpoint;
7111
7111
  if (capture === void 0) throw new ValidationError$1("provider workspace retention: the port has no captureCheckpoint");
7112
7112
  const controller = new AbortController();
7113
7113
  const clearDeadline = armDeadlineTimer(port.timeoutMs, () => controller.abort(/* @__PURE__ */ new Error(`checkpoint capture timed out after ${port.timeoutMs}ms`)), true);
7114
+ const signal = parent === void 0 ? controller.signal : AbortSignal.any([controller.signal, parent]);
7114
7115
  try {
7115
- return await runAbortable(() => withCaptureSlot(checkpointSlots(port), controller.signal, async () => {
7116
+ return await runAbortable(() => withCaptureSlot(checkpointSlots(port), signal, async () => {
7117
+ const context = await prepare(signal);
7116
7118
  const tree = detachedSnapshot(await capture.call(port, {
7117
7119
  ...context,
7118
- signal: controller.signal
7120
+ signal
7119
7121
  }), "checkpoint capture tree");
7120
7122
  if (tree?.kind !== "agent-candidate-workspace-tree") throw new Error("checkpoint capture returned no workspace tree");
7121
7123
  const material = await verifyAgentCandidateWorkspaceTree(tree, port.artifacts, {
7122
7124
  ...port.limits === void 0 ? {} : { limits: port.limits },
7123
- signal: controller.signal
7125
+ signal
7124
7126
  });
7125
7127
  if (material.files.length !== tree.files) throw new Error("checkpoint capture tree misstates its file count");
7126
7128
  if (marker !== void 0) {
@@ -7129,7 +7131,7 @@ async function captureProviderCheckpointWorkspace(port, context, marker) {
7129
7131
  if (held === void 0 || held.byteLength !== bytes.byteLength || held.sha256 !== `sha256:${createHash("sha256").update(bytes).digest("hex")}`) throw new Error(`checkpoint capture does not hold the checkpoint's marker ${marker.path}`);
7130
7132
  }
7131
7133
  return tree;
7132
- }), controller.signal, `checkpoint capture timed out after ${port.timeoutMs}ms`);
7134
+ }), signal, `checkpoint capture timed out after ${port.timeoutMs}ms`);
7133
7135
  } finally {
7134
7136
  clearDeadline();
7135
7137
  }
@@ -13570,10 +13572,30 @@ async function runBrainLoop(opts) {
13570
13572
  async function routerChatWithUsage(cfg, messages, opts) {
13571
13573
  const url = `${cfg.routerBaseUrl.replace(/\/$/, "")}/chat/completions`;
13572
13574
  const headers = routerRequestHeaders(cfg, opts);
13575
+ const body = () => chatCompletionBody(cfg, messages, opts);
13576
+ const retry = resolveRouterRetryPolicy(cfg.retry, "RouterConfig.retry");
13577
+ const complete = cfg.complete;
13578
+ if (complete) {
13579
+ const { value, attempts } = await retryRouterOperation(retry, opts?.signal, (signal) => complete(body(), {
13580
+ headers,
13581
+ signal
13582
+ }));
13583
+ return parseChatResult(value, cfg.model, attempts);
13584
+ }
13585
+ const { response, attempts } = await fetchRouterResponse(url, {
13586
+ method: "POST",
13587
+ headers,
13588
+ body: JSON.stringify(body())
13589
+ }, opts?.signal, retry);
13590
+ return parseChatResult(await routerResponseJson(response, attempts), cfg.model, attempts);
13591
+ }
13592
+ /** The OpenAI-shape request body both plain-chat transports send. One builder so the streamed
13593
+ * completion cannot drift from the buffered one on model, ceilings, seed, or reasoning effort. */
13594
+ function chatCompletionBody(cfg, messages, opts) {
13573
13595
  const temperature = opts?.temperature;
13574
13596
  const maxTokens = opts?.maxTokens ?? cfg.maxTokens;
13575
13597
  const maxCompletionTokens = opts?.maxCompletionTokens ?? cfg.maxCompletionTokens;
13576
- const body = () => ({
13598
+ return {
13577
13599
  ...providerRequestExtras(opts?.extraBody, [
13578
13600
  "model",
13579
13601
  "messages",
@@ -13592,22 +13614,7 @@ async function routerChatWithUsage(cfg, messages, opts) {
13592
13614
  ...maxCompletionTokens !== void 0 ? { max_completion_tokens: maxCompletionTokens } : {},
13593
13615
  ...opts?.seed !== void 0 ? { seed: opts.seed } : {},
13594
13616
  ...opts?.reasoningEffort ? { reasoning_effort: opts.reasoningEffort } : {}
13595
- });
13596
- const retry = resolveRouterRetryPolicy(cfg.retry, "RouterConfig.retry");
13597
- const complete = cfg.complete;
13598
- if (complete) {
13599
- const { value, attempts } = await retryRouterOperation(retry, opts?.signal, (signal) => complete(body(), {
13600
- headers,
13601
- signal
13602
- }));
13603
- return parseChatResult(value, cfg.model, attempts);
13604
- }
13605
- const { response, attempts } = await fetchRouterResponse(url, {
13606
- method: "POST",
13607
- headers,
13608
- body: JSON.stringify(body())
13609
- }, opts?.signal, retry);
13610
- return parseChatResult(await routerResponseJson(response, attempts), cfg.model, attempts);
13617
+ };
13611
13618
  }
13612
13619
  function parseChatResult(json, model, transportAttempts) {
13613
13620
  const data = json;
@@ -13831,10 +13838,76 @@ function readPromptCache(raw) {
13831
13838
  * why the streamed transport says so explicitly and the buffered one has no equivalent claim to make.
13832
13839
  */
13833
13840
  async function streamRouterChatWithTools(cfg, messages, tools, opts) {
13841
+ const streamed = await streamChatCompletion("streamRouterChatWithTools", cfg, toolCompletionBody(cfg, messages, tools, opts), opts);
13842
+ const toolCalls = [...streamed.calls.entries()].sort((a, b) => a[0] - b[0]).map(([index, call]) => ({
13843
+ id: call.id ?? `call_${index}`,
13844
+ name: call.name ?? "",
13845
+ arguments: call.arguments || "{}"
13846
+ }));
13847
+ const { usage, resources, costUsd, costProvenance, billedCostUsd, cache } = meterTurn(streamed.rawUsage, cfg.model, streamed.transportAttempts);
13848
+ return {
13849
+ content: streamed.sawContent ? streamed.content : null,
13850
+ toolCalls,
13851
+ transportAttempts: streamed.transportAttempts,
13852
+ ...streamed.model !== void 0 ? { model: streamed.model } : {},
13853
+ ...streamed.reasoning ? { reasoning: streamed.reasoning } : {},
13854
+ ...streamed.finishReason !== void 0 ? { finishReason: streamed.finishReason } : {},
13855
+ ...usage ? { usage } : {},
13856
+ ...resources ? { resources } : {},
13857
+ ...costUsd !== void 0 ? { costUsd } : {},
13858
+ ...costProvenance ? { costProvenance } : {},
13859
+ ...billedCostUsd !== void 0 ? { billedCostUsd } : {},
13860
+ ...cache ? { cache } : {},
13861
+ ...usage ? {} : { usageUnknown: true }
13862
+ };
13863
+ }
13864
+ /**
13865
+ * The SAME completion as `routerChatWithUsage`, taken over SSE (`stream: true`) and reassembled
13866
+ * into the identical `RouterChatResult`: content with any inline `<think>` split out, reasoning,
13867
+ * finish reason, reported model, usage, catalog estimate, billed cost, and prompt cache.
13868
+ *
13869
+ * What it buys: the Tangle Router bounds a request by a deadline that ends when response headers
13870
+ * are committed. A buffered completion commits headers only after the whole generation, so a long
13871
+ * thinking-model answer outlives that deadline and fails with `request_deadline_exceeded`. A
13872
+ * streamed response commits headers at the first byte, so generation length is no longer bounded
13873
+ * by the Router's request deadline.
13874
+ *
13875
+ * Usage that never arrives stays `undefined` (never a fabricated 0), which the executor records as
13876
+ * unknown tokens. A stream that ends without a single choice is refused, matching the buffered
13877
+ * path's refusal of a completion with no `choices[0].message`.
13878
+ */
13879
+ async function streamRouterChatWithUsage(cfg, messages, opts) {
13880
+ const streamed = await streamChatCompletion("streamRouterChatWithUsage", cfg, chatCompletionBody(cfg, messages, opts), opts);
13881
+ if (!streamed.sawChoice) throwRouterFailureWithAttempts(new ValidationError$1("router stream: completion carried no choices"), streamed.transportAttempts);
13882
+ const { usage, resources, costUsd, costProvenance, billedCostUsd, cache } = meterTurn(streamed.rawUsage, cfg.model, streamed.transportAttempts);
13883
+ return {
13884
+ content: streamed.content,
13885
+ transportAttempts: streamed.transportAttempts,
13886
+ ...streamed.model !== void 0 ? { model: streamed.model } : {},
13887
+ ...streamed.reasoning ? { reasoning: streamed.reasoning } : {},
13888
+ ...usage ? { usage } : {},
13889
+ ...resources ? { resources } : {},
13890
+ ...costUsd !== void 0 ? { costUsd } : {},
13891
+ ...costProvenance ? { costProvenance } : {},
13892
+ ...billedCostUsd !== void 0 ? { billedCostUsd } : {},
13893
+ ...cache ? { cache } : {},
13894
+ ...streamed.finishReason !== void 0 ? { finishReason: streamed.finishReason } : {}
13895
+ };
13896
+ }
13897
+ /**
13898
+ * POST `body` with `stream: true` and fold the SSE chunks into one completion. Both streamed
13899
+ * transports share this reader so content, reasoning, model identity, finish reason, usage, and
13900
+ * tool-call assembly cannot drift between them.
13901
+ *
13902
+ * The caller signal stays attached through the body read: the retry layer's request deadline
13903
+ * covers only response headers, and cancelling the caller must still stop a completion that is
13904
+ * mid-stream rather than leave it reading until the provider finishes.
13905
+ */
13906
+ async function streamChatCompletion(context, cfg, requestBody, opts) {
13834
13907
  const retry = resolveRouterRetryPolicy(cfg.retry, "RouterConfig.retry");
13835
- if (cfg.complete) throw new ValidationError$1("streamRouterChatWithTools: RouterConfig.complete is a BUFFERED transport (it returns one parsed completion body) and cannot serve a stream. Drop `stream` to use the injected transport, or drop `complete` to stream from the router.");
13908
+ if (cfg.complete) throw new ValidationError$1(`${context}: RouterConfig.complete is a BUFFERED transport (it returns one parsed completion body) and cannot serve a stream. Drop \`stream\` to use the injected transport, or drop \`complete\` to stream from the router.`);
13836
13909
  const body = {
13837
- ...toolCompletionBody(cfg, messages, tools, opts),
13910
+ ...requestBody,
13838
13911
  stream: true,
13839
13912
  stream_options: { include_usage: true }
13840
13913
  };
@@ -13846,25 +13919,27 @@ async function streamRouterChatWithTools(cfg, messages, tools, opts) {
13846
13919
  },
13847
13920
  body: JSON.stringify(body)
13848
13921
  }, opts?.signal, retry);
13849
- if (!res.body) throw new ValidationError$1(`router ${res.status}: streamed completion returned no response body to read`);
13922
+ if (!res.body) throwRouterFailureWithAttempts(new ValidationError$1(`router ${res.status}: streamed completion returned no response body to read`), transportAttempts);
13850
13923
  let content = "";
13851
13924
  let sawContent = false;
13925
+ let sawChoice = false;
13852
13926
  let fieldReasoning = "";
13853
13927
  let finishReason;
13854
13928
  let rawUsage;
13855
13929
  let observedModel;
13856
13930
  const calls = /* @__PURE__ */ new Map();
13857
13931
  let lastCallIndex = -1;
13858
- for await (const chunk of readChatCompletionChunksWithAttempts(res.body, transportAttempts)) {
13859
- if (chunk.error) throw new ValidationError$1(`router stream error: ${chunk.error.message ?? chunk.error.type ?? "unknown"}`);
13932
+ for await (const chunk of readChatCompletionChunksWithAttempts(res.body, transportAttempts, opts?.signal)) {
13933
+ if (chunk.error) throwRouterFailureWithAttempts(new ValidationError$1(`router stream error: ${chunk.error.message ?? chunk.error.type ?? "unknown"}`), transportAttempts);
13860
13934
  const chunkModel = reportedModel(chunk.model);
13861
13935
  if (chunkModel !== void 0) {
13862
- if (observedModel !== void 0 && observedModel !== chunkModel) throw new ValidationError$1(`router stream changed reported model from ${JSON.stringify(observedModel)} to ${JSON.stringify(chunkModel)}`);
13936
+ if (observedModel !== void 0 && observedModel !== chunkModel) throwRouterFailureWithAttempts(new ValidationError$1(`router stream changed reported model from ${JSON.stringify(observedModel)} to ${JSON.stringify(chunkModel)}`), transportAttempts);
13863
13937
  observedModel = chunkModel;
13864
13938
  }
13865
13939
  if (chunk.usage) rawUsage = chunk.usage;
13866
13940
  const choice = chunk.choices?.[0];
13867
13941
  if (!choice) continue;
13942
+ sawChoice = true;
13868
13943
  if (typeof choice.finish_reason === "string") finishReason = choice.finish_reason;
13869
13944
  const delta = choice.delta;
13870
13945
  if (!delta) continue;
@@ -13885,26 +13960,16 @@ async function streamRouterChatWithTools(cfg, messages, tools, opts) {
13885
13960
  }
13886
13961
  }
13887
13962
  const split = splitReasoning(content, fieldReasoning.length > 0 ? fieldReasoning : void 0);
13888
- const toolCalls = [...calls.entries()].sort((a, b) => a[0] - b[0]).map(([index, call]) => ({
13889
- id: call.id ?? `call_${index}`,
13890
- name: call.name ?? "",
13891
- arguments: call.arguments || "{}"
13892
- }));
13893
- const { usage, resources, costUsd, costProvenance, billedCostUsd, cache } = meterTurn(rawUsage, cfg.model, transportAttempts);
13894
13963
  return {
13895
- content: sawContent ? split.content : null,
13896
- toolCalls,
13897
- transportAttempts,
13898
- ...observedModel !== void 0 ? { model: observedModel } : {},
13964
+ content: split.content,
13965
+ sawContent,
13966
+ sawChoice,
13899
13967
  ...split.reasoning ? { reasoning: split.reasoning } : {},
13900
13968
  ...finishReason !== void 0 ? { finishReason } : {},
13901
- ...usage ? { usage } : {},
13902
- ...resources ? { resources } : {},
13903
- ...costUsd !== void 0 ? { costUsd } : {},
13904
- ...costProvenance ? { costProvenance } : {},
13905
- ...billedCostUsd !== void 0 ? { billedCostUsd } : {},
13906
- ...cache ? { cache } : {},
13907
- ...usage ? {} : { usageUnknown: true }
13969
+ ...rawUsage ? { rawUsage } : {},
13970
+ ...observedModel !== void 0 ? { model: observedModel } : {},
13971
+ calls,
13972
+ transportAttempts
13908
13973
  };
13909
13974
  }
13910
13975
  function routerRequestHeaders(cfg, opts) {
@@ -14121,14 +14186,20 @@ function idAlreadyOpen(calls, id) {
14121
14186
  * body is CANCELLED rather than merely unlocked: releasing the lock alone leaves the connection
14122
14187
  * held open until the socket times out, which under a connection pool starves later turns.
14123
14188
  */
14124
- async function* readChatCompletionChunks(body) {
14189
+ async function* readChatCompletionChunks(body, signal) {
14190
+ signal?.throwIfAborted();
14125
14191
  const reader = body.getReader();
14126
14192
  const decoder = new TextDecoder();
14127
14193
  let buf = "";
14128
14194
  let drained = false;
14195
+ const onAbort = () => {
14196
+ reader.cancel(signal?.reason).catch(() => void 0);
14197
+ };
14198
+ signal?.addEventListener("abort", onAbort, { once: true });
14129
14199
  try {
14130
14200
  for (;;) {
14131
14201
  const { done, value } = await reader.read();
14202
+ signal?.throwIfAborted();
14132
14203
  buf = normalizeSseLineEndings(done ? buf : buf + decoder.decode(value, { stream: true }), !done);
14133
14204
  let sep = buf.indexOf("\n\n");
14134
14205
  while (sep !== -1) {
@@ -14144,13 +14215,14 @@ async function* readChatCompletionChunks(body) {
14144
14215
  const tail = parseChunkFrame(buf);
14145
14216
  if (tail && tail !== "done") yield tail;
14146
14217
  } finally {
14218
+ signal?.removeEventListener("abort", onAbort);
14147
14219
  if (!drained) await reader.cancel().catch(() => void 0);
14148
14220
  reader.releaseLock();
14149
14221
  }
14150
14222
  }
14151
- async function* readChatCompletionChunksWithAttempts(body, attempts) {
14223
+ async function* readChatCompletionChunksWithAttempts(body, attempts, signal) {
14152
14224
  try {
14153
- yield* readChatCompletionChunks(body);
14225
+ yield* readChatCompletionChunks(body, signal);
14154
14226
  } catch (error) {
14155
14227
  throwRouterFailureWithAttempts(error, attempts);
14156
14228
  }
@@ -19774,10 +19846,6 @@ const routerInlineExecutor = (spec, ctx) => {
19774
19846
  transcript.observe(messages);
19775
19847
  const started = Date.now();
19776
19848
  const linked = linkAbort(signal, controller.signal).signal;
19777
- const extraBody = {
19778
- ...profileExecution.extraBody ?? {},
19779
- ...profileExecution.reasoningEffort ? { reasoning_effort: profileExecution.reasoningEffort } : {}
19780
- };
19781
19849
  recordRuntimeOwnedProviderAttemptStart(executor);
19782
19850
  const r = await runRouterTransport("routerInlineExecutor", () => seam.tools ? (profileExecution.stream === true ? streamRouterChatWithTools : routerChatWithTools)({
19783
19851
  routerBaseUrl: seam.routerBaseUrl,
@@ -19791,9 +19859,10 @@ const routerInlineExecutor = (spec, ctx) => {
19791
19859
  ...profileExecution.toolChoice ? { toolChoice: profileExecution.toolChoice } : {},
19792
19860
  ...profileExecution.tokenLimits.applied,
19793
19861
  ...profileExecution.seed !== void 0 ? { seed: profileExecution.seed } : {},
19794
- ...Object.keys(extraBody).length > 0 ? { extraBody } : {},
19862
+ ...profileExecution.reasoningEffort ? { reasoningEffort: profileExecution.reasoningEffort } : {},
19863
+ ...profileExecution.extraBody ? { extraBody: profileExecution.extraBody } : {},
19795
19864
  ...requestIdentity
19796
- }) : routerChatWithUsage({
19865
+ }) : (profileExecution.stream === true ? streamRouterChatWithUsage : routerChatWithUsage)({
19797
19866
  routerBaseUrl: seam.routerBaseUrl,
19798
19867
  routerKey: seam.routerKey,
19799
19868
  model,
@@ -19941,6 +20010,7 @@ const routerToolsInlineExecutor = (spec, ctx) => {
19941
20010
  const profileExecution = routerProfileExecution(spec.profile, {
19942
20011
  routerBaseUrl: seam.routerBaseUrl,
19943
20012
  routerKey: seam.routerKey,
20013
+ ...seam.complete ? { complete: seam.complete } : {},
19944
20014
  tools: seam.tools
19945
20015
  }, { multiTurn: true });
19946
20016
  if (model === "tangle/auto") assertRouterAutoDeclaration(profileExecution.extraBody?.auto, profileExecution.stream);
@@ -21397,7 +21467,7 @@ function routerProfileExecution(profile, seam, mode) {
21397
21467
  const profileEffort = profile.model?.reasoningEffort;
21398
21468
  const settings = profileModelExecutionSettings(profile, "routerInlineExecutor");
21399
21469
  if (!mode.multiTurn && settings.maxTurns !== void 0) throw new ValidationError$1("routerInlineExecutor: AgentProfile.model.metadata.maxTurns requires the router-tools backend");
21400
- if (settings.stream === true && seam.tools === void 0) throw new ValidationError$1("routerInlineExecutor: streamed chat without tool schemas is not supported; omit stream or use a harness executor");
21470
+ if (settings.stream === true && seam.complete !== void 0) throw new ValidationError$1("routerInlineExecutor: AgentProfile.model.metadata.stream requires the HTTP Router transport; RouterSeam.complete returns one buffered completion and cannot serve a stream");
21401
21471
  const declaredTools = profile.tools ?? {};
21402
21472
  const suppliedTools = seam.tools ?? [];
21403
21473
  if (settings.toolChoice !== void 0 && suppliedTools.length === 0) throw new ValidationError$1("routerInlineExecutor: AgentProfile.model.metadata.toolChoice requires at least one enabled tool");
@@ -24448,6 +24518,7 @@ async function captureBeforeCleanup(state, branching, event, events, parent) {
24448
24518
  if (capture?.port.captureCheckpoint === void 0) return refuse("no checkpoint capture: the owner backend has no captureCheckpoint", false);
24449
24519
  const provider = state.provider;
24450
24520
  if (provider?.get === void 0) return refuse("the provider cannot reconstruct a fork of the checkpoint", false);
24521
+ const get = provider.get.bind(provider);
24451
24522
  if (branching === void 0) return refuse("source-scoped checkpoint handle unavailable", true);
24452
24523
  const material = {
24453
24524
  checkpoint: event.checkpoint,
@@ -24458,34 +24529,56 @@ async function captureBeforeCleanup(state, branching, event, events, parent) {
24458
24529
  idempotencyKey: `${event.checkpoint.idempotencyKey}:capture:${state.nextSequence()}`,
24459
24530
  requestDigest: workspaceForkRequestDigest(material)
24460
24531
  };
24461
- const forkSignal = AbortSignal.any([...parent === void 0 ? [] : [parent], AbortSignal.timeout(WORKSPACE_CHECKPOINT_FORK_TIMEOUT_MS)]);
24462
24532
  let forkEnvironmentId;
24533
+ let captureEnded = false;
24463
24534
  try {
24464
- await args.journal.appendEvent(args.rootId, {
24465
- kind: "workspace-checkpoint-fork-requested",
24466
- id: args.nodeId,
24467
- provider: event.provider,
24468
- environmentId: event.environmentId,
24469
- checkpointId,
24470
- idempotencyKey: request.idempotencyKey,
24471
- requestDigest: request.requestDigest,
24472
- seq: state.nextSequence(),
24473
- at: new Date(args.now()).toISOString()
24474
- });
24475
- const result = await runAbortable(() => branching.fork(request, { signal: forkSignal }), forkSignal, "checkpoint fork timed out");
24476
- if (result.status === "created" || result.status === "replayed") forkEnvironmentId = result.environment.environmentId;
24477
- if (result.status !== "created" && result.status !== "replayed" || !workspaceForkResultMatchesRequest(request, result)) return refuse(`fork ${result.status}${"message" in result ? `: ${result.message}` : ""}`, true);
24478
- const forkId = result.environment.environmentId;
24479
- const get = provider.get.bind(provider);
24480
- const environment = await runAbortable(() => get(forkId), forkSignal, "checkpoint fork lookup timed out");
24481
- if (environment === null || environment.id !== forkId || environment.provider !== provider.name) return refuse(`fork ${forkId} could not be reconstructed`, true);
24482
- parent?.throwIfAborted();
24483
- const tree = await captureProviderCheckpointWorkspace(capture.port, {
24484
- environment,
24485
- checkpoint: event.checkpoint,
24486
- executionId: `${args.nodeId}:checkpoint:${checkpointId}`,
24487
- profile: capture.profile
24488
- }, event.marker);
24535
+ const tree = await captureProviderCheckpointWorkspace(capture.port, async (captureSignal) => {
24536
+ const forkSignal = AbortSignal.any([
24537
+ captureSignal,
24538
+ ...parent === void 0 ? [] : [parent],
24539
+ AbortSignal.timeout(WORKSPACE_CHECKPOINT_FORK_TIMEOUT_MS)
24540
+ ]);
24541
+ await args.journal.appendEvent(args.rootId, {
24542
+ kind: "workspace-checkpoint-fork-requested",
24543
+ id: args.nodeId,
24544
+ provider: event.provider,
24545
+ environmentId: event.environmentId,
24546
+ checkpointId,
24547
+ idempotencyKey: request.idempotencyKey,
24548
+ requestDigest: request.requestDigest,
24549
+ seq: state.nextSequence(),
24550
+ at: new Date(args.now()).toISOString()
24551
+ });
24552
+ const result = await runAbortable(() => branching.fork(request, { signal: forkSignal }).then(async (result) => {
24553
+ if (result.status === "created" || result.status === "replayed") {
24554
+ const forkId = result.environment.environmentId;
24555
+ if (captureEnded) await destroyCaptureFork(state, branching, {
24556
+ provider: event.provider,
24557
+ environmentId: event.environmentId,
24558
+ checkpointId,
24559
+ fork: {
24560
+ idempotencyKey: request.idempotencyKey,
24561
+ environmentId: forkId
24562
+ }
24563
+ });
24564
+ else forkEnvironmentId = forkId;
24565
+ }
24566
+ return result;
24567
+ }), forkSignal, "checkpoint fork timed out");
24568
+ if (result.status !== "created" && result.status !== "replayed" || !workspaceForkResultMatchesRequest(request, result)) throw new Error(`fork ${result.status}${"message" in result ? `: ${result.message}` : ""}`);
24569
+ const forkId = result.environment.environmentId;
24570
+ const environment = await runAbortable(() => get(forkId), forkSignal, "checkpoint fork lookup timed out");
24571
+ if (environment === null || environment.id !== forkId || environment.provider !== provider.name) throw new Error(`fork ${forkId} could not be reconstructed`);
24572
+ parent?.throwIfAborted();
24573
+ return {
24574
+ environment,
24575
+ checkpoint: event.checkpoint,
24576
+ executionId: `${args.nodeId}:checkpoint:${checkpointId}`,
24577
+ profile: capture.profile
24578
+ };
24579
+ }, event.marker, parent);
24580
+ const forkId = forkEnvironmentId;
24581
+ if (forkId === void 0) throw new Error("checkpoint capture fork identity missing");
24489
24582
  await args.journal.appendEvent(args.rootId, {
24490
24583
  kind: "workspace-checkpoint-capture",
24491
24584
  id: args.nodeId,
@@ -24510,6 +24603,7 @@ async function captureBeforeCleanup(state, branching, event, events, parent) {
24510
24603
  } catch (error) {
24511
24604
  return refuse(`capture failed: ${errorText(error instanceof Error ? error.message : error)}`, true);
24512
24605
  } finally {
24606
+ captureEnded = true;
24513
24607
  if (forkEnvironmentId !== void 0) await destroyCaptureFork(state, branching, {
24514
24608
  provider: event.provider,
24515
24609
  environmentId: event.environmentId,
@@ -28850,7 +28944,8 @@ async function runDriverWithRetry(run) {
28850
28944
  outageSince = void 0;
28851
28945
  }
28852
28946
  }
28853
- const retryStop = abandoned ? void 0 : stop;
28947
+ const unresolved = !abandoned && !progressed && pending !== void 0 && samePending !== void 0 && run.resolvePending !== void 0 && abandonments >= maxConsecutive && samePending.count >= SAME_PENDING_LIMIT && (stop === void 0 || stop === "no-progress");
28948
+ const retryStop = abandoned ? void 0 : unresolved ? "pending-unresolved" : stop;
28854
28949
  if (progressed) barrenReentries = 0;
28855
28950
  if (retryStop !== void 0) {
28856
28951
  await emit({
@@ -28859,7 +28954,8 @@ async function runDriverWithRetry(run) {
28859
28954
  error: errMessage(error),
28860
28955
  classification,
28861
28956
  madeProgress: progressed,
28862
- stop: retryStop
28957
+ stop: retryStop,
28958
+ ...unresolved ? { pendingCause: pending.pendingCause } : {}
28863
28959
  });
28864
28960
  throw new DriverAttemptsExhaustedError(error, attempts, retryStop);
28865
28961
  }
@@ -30110,4 +30206,4 @@ function isNonEmptySpend(s) {
30110
30206
  //#endregion
30111
30207
  export { environmentReader as $, executableAgentSpecSnapshot as $i, parseWorkerToolTraceArtifact as $n, toOtelAttributes as $r, PEER_MAIL_WIRE_KEY as $t, scopeOwnerExecutorNodeContext as A, sandboxActProfileMaterialization as Ai, resolveAgentEnvironmentProvider as An, resolveHarnessTranscriptCapture as Ar, captureReusableExecutorConfig as At, consumeScopeRetainedOwnerResult as B, knownMaterializationReceipt as Bi, InMemoryResultBlobStore as Bn, defaultRedactor as Br, createInPlaceCliExecutor as Bt, deriveNodeExecutionIdentity as C, profileMaterializationAxes$1 as Ci, readPromptOptions as Cn, abortError as Cr, createContinuationKeeper as Ct, recordScopeOwnerMaterialization as D, promptResourceProfileMaterialization as Di, createAgentEnvironmentProviderRegistry as Dn, harnessTranscriptArtifact as Dr, passedItems as Dt, recordScopeOwnerDriverAttempt as E, promptOnlyProfileMaterialization as Ei, LEAF_CONTINUATION_TASK as En, captureHarnessTranscript as Er, failedItems as Et, seatExecutionProfile as F, attestRuntimeOwnedScopeOwner as Fi, retainedExecutorSeamKey as Fn, ROUTER_PRICE_SOURCE as Fr, snapshotExecutorConfig as Ft, scopeRetainedOwnerContext as G, runtimeOwnedExecutorExecutionBinding as Gi, replaySpawnTree as Gn, buildRuntimeEventOtelSpans as Gr, workerTraceSeamKey as Gt, prepareScopeRetainedOwnerSeatSwitch as H, providerAttemptEvidence as Hi, insideCursorNamespace as Hn, resolveRedactor as Hr, readWorkerTraceContext as Ht, abandonScopeRetainedOwnerInvocation as I, authoredProfileDigest as Ii, unavailablePauseMs as In, createPropagatingTraceEmitter as Ir, createWorktreeCliExecutor as It, scopeRetainedOwnerResourceReader as J, runtimeOwnedPendingExecutorMaterialization as Ji, readCommittedJsonLines as Jn, flatOtelSpan as Jr, createActivityLog as Jt, scopeRetainedOwnerJournalRoot as K, runtimeOwnedExecutorMaterialization as Ki, isNoEntError as Kn, createOpenInferenceFileExporter as Kr, taskToPrompt as Kt, beginScopeRetainedOwnerDrive as L, finalizeRuntimeOwnedPendingExecutor as Li, unavailableSignalOfFailure as Ln, mergeTraceEnv as Lr, DEFAULT_SANDBOX_STEERING_MAX_TURNS as Lt, SeatChain as M, validateProfileMaterialization as Mi, decodeToolPart as Mn, contentAddress as Mr, cliWorktreeExecutor as Mt, SeatChainExhaustedError as N, worktreeCliProfileMaterialization as Ni, sandboxSessionTraceSource as Nn, priceTokens as Nr, createExecutor as Nt, recordScopeOwnerPause as O, renderProfileMaterializationIssues as Oi, providerAsExecutor as On, persistHarnessTranscript as Or, verdictFromJudgeScore as Ot, authoredSeatStages as P, attestRuntimeOwnedPendingExecutor as Pi, registerRetainedExecutorPreparation as Pn, routerTokenPrice as Pr, createExecutorRegistry as Pt, SPAWN_RESOURCE_PATH_MAX_BYTES as Q, executableAgentProfileSnapshot as Qi, isTraceAnalysisStore as Qn, padTraceId as Qr, DEFAULT_PEER_MAIL_LIMITS as Qt, bindScopeRetainedOwnerEnvironmentId as R, inheritRuntimeOwnedExecutorAttestation as Ri, FileResultBlobStore as Rn, readTraceContextFromEnv as Rr, createSteerableSandboxSession as Rt, createScope as S, fullProfileMaterialization as Si, assertBoxlessPromptOptions as Sn, RunCancellationReason as Sr, checkVerdictOf as St, meterRuntimeOwnedProviderAttempt as T, promptModelProfileMaterialization as Ti, runBrainLoop as Tn, runAbortable as Tr, expandQuestions as Tt, prepareScopeRetainedOwnerTask as U, recordRuntimeOwnedDriveHarnessProviderEvidence as Ui, loadSpawnForest as Un, buildLoopOtelSpans as Ur, workerTraceEnv as Ut, noteScopeRetainedOwnerCoordination as V, newExecutionAttemptId as Vi, InMemorySpawnJournal as Vn, defaultRedactorIdentityMaterial as Vr, WORKER_TRACE_PROPAGATION as Vt, reconcileScopeRetainedOwnerEnvironment as W, runtimeOwnedDriveHarnessProviderEvidence as Wi, materializeTreeView as Wn, buildLoopSpanNodes as Wr, workerTraceHeaders as Wt, scopeRetainedOwnerResult as X, unknownExecutionBindingReceipt as Xi, WORKER_TOOL_TRACE_SCHEMA_VERSION as Xn, loopEventToOtelSpan as Xr, createInbox as Xt, scopeRetainedOwnerRestorePoint as Y, runtimeOwnedScopeOwnerRuntime as Yi, writeAllBytes as Yn, generateSpanId as Yr, readWorkerProgress as Yt, scopeRetainedOwnerTurnEnded as Z, unknownMaterializationReceipt as Zi, captureWorkerTraceEvidence as Zn, padSpanId as Zr, AUTHORITY_MARKERS as Zt, isDriverSpec as _, abortError$1 as _a, terminateProcessTreeAndConfirm as _i, runAgentRounds as _n, retainedCreateMaterial as _r, CONTINUATION_FACTS as _t, collectDelivered as a, canonicalStreamEventFromSandboxEvent as aa, runSettledCommand as ai, isLiveNodeStatus as an, createBudgetPool as ar, interactiveAdmissionSeamKey as at, assertRecursiveReservationPolicy as b, promptOptionsFromAgentTurnInput as ba, controlProfileMaterialization as bi, SandboxEvidenceRetentionError as bn, createWorkerSlots as br, admitFinding as bt, runTree as c, extractLlmCallEvent as ca, createWorktree as ci, bridgeModelRouteRefusal as cn, spendFromUsageEvents as cr, reconnectRetainedInteractiveRun as ct, classifyDriverFailure as d, mapSandboxToolEvent as da, LOCAL_HARNESSES as di, harnessUsageIsEmpty as dn, bridgeStopSignalKey as dr, freeSlots as dt, detachedFrozen as ea, createRuntimeEventCollector as ei, claimsAuthority as en, workerTraceAnalysisStore as er, hostDirectoryReader as et, runDriverWithRetry as f, notifySandboxEventObserver as fa, harnessInvocation as fi, readCodexRolloutSession as fn, errMessage as fr, queueOf as ft, driverExecutorFactory as g, decodeHarnessUsage as ga, CodexExecutionDiagnosticError as gi, isTerminalDecision as gn, startRetainedRunInEnvironment as gr, CONTINUATIONS_DIR as gt, driverChild as h, sumSandboxUsage as ha, parseCodexTokenUsage as hi, defaultSelectWinner as hn, startRetainedRun as hr, mapExecutorResult as ht, bestDelivered as i, assertSandboxServedModel as ia, sanitizeRuntimeStreamEvent as ii, peerMailVerbNames as in, assertValidBudget as ir, providerVisibleProfile as it, settledToIteration as j, unsupportedProfileDimensions as ji, createPushTraceSource as jn, retainHarnessTranscript as jr, cliInPlaceExecutor as jt, restoreScopeOwnerAcceptedExecution as k, renderUnsupported as ki, providerAsSandboxClient as kn, readHarnessTranscript as kr, bindReusableExecutorExecutionId as kt, DriverAttemptsExhaustedError as l, isSandboxTerminalEvent as la, removeWorktree as li, addHarnessUsage as ln, spendFromUsageTotals as lr, recoverRetainedInteractiveRun as lt, upstreamUnavailableSignal as m, sandboxProgressEvents as ma, localHarnessExecutable as mi, createSandboxForSpec as mn, recoverRetainedRun as mr, gateOnDeliverable as mt, createRootHandle as n, projectSandboxOutcome as na, sanitizeAgentRuntimeEvent as ni, isPeerMailEnvelope as nn, BudgetReconcileFault as nr, coordinationMcpAlias as nt, pickBestDelivered as o, createSandboxToolPartState as oa, runWorktreeHarness as oi, isTerminalNodeStatus as on, meterUsageEvent as or, attachWorker as ot, summarizeDriverAttempts as p, sandboxEventServedBackend as pa, harnessSupportsReasoningEffort as pi, TERMINAL_DECISIONS as pn, reconnectRetainedRun as pr, rollingDispatch as pt, scopeRetainedOwnerPriorSpend as q, runtimeOwnedExecutorProviderEvidence as qi, prepareJsonlAppend as qn, createOtelExporter as qr, DEFAULT_STALL_AFTER_MS as qt, createSupervisor as r, readSandboxOutcome as ra, sanitizeKnowledgeReadinessReport as ri, peerMailTools as rn, ReservationWaitRefused as rr, coordinationProfileToolPrefix as rt, runFinalizer as s, createSandboxUsageLedger as sa, captureWorktreeDiff as si, bridgeAdmissionRefusal as sn, newUsageTotals as sr, readWorkerInteractiveBinding as st, DEFAULT_MAX_DEPTH as t, detachedSnapshot as ta, createRuntimeStreamEventCollector as ti, createPeerMailbox as tn, executorFailure as tr, resolveSpawnResourcePaths as tt, HarnessTurnFailedError as u, mapSandboxEvent as ua, DEFAULT_LOCAL_HARNESS as ui, createCodexRolloutStoreReader as un, bridgeRuntimeAttachmentsKey as ur, startRetainedInteractiveRun as ut, withDriverExecutor as v, awaitAbortable$1 as va, AGENT_PROFILE_MATERIALIZATION_AXES as vi, createSandboxLineage as vn, destroyInteractiveEnvironment as vr, CheckUnavailableError as vt, meterRuntimeOwnedAccounting as w, promptControlProfileMaterialization as wi, routerBrain as wn, linkAbort as wr, distillFindings as wt, beginScopeOwnerAttempt as x, providerMessageText as xa, defineProfileMaterializationContract as xi, captureBeforeDestroy as xn, openSlotGroup as xr, bestComposite as xt, SUBTREE_RESULT_LIMIT as y, promptFromAgentTurnInput as ya, assertProfileMaterialization as yi, acquireSandbox as yn, environmentGone as yr, admitContinuationPolicy as yt, bindScopeRetainedOwnerProvider as z, knownExecutionBindingReceipt as zi, FileSpawnJournal as zn, traceContextToEnv as zr, createRouterTranscript as zt };
30112
30208
 
30113
- //# sourceMappingURL=supervisor-yX008JOQ.js.map
30209
+ //# sourceMappingURL=supervisor-Bnjo-yDg.js.map