@bastani/atomic 0.9.73 → 0.9.74-alpha.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 (193) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/dist/builtin/intercom/package.json +1 -1
  3. package/dist/builtin/mcp/package.json +1 -1
  4. package/dist/builtin/subagents/package.json +1 -1
  5. package/dist/builtin/web-access/package.json +1 -1
  6. package/dist/builtin/workflows/CHANGELOG.md +16 -0
  7. package/dist/builtin/workflows/README.md +2 -2
  8. package/dist/builtin/workflows/builtin/adversarial-verification.js +2 -2
  9. package/dist/builtin/workflows/builtin/{chunk-2377r57g.js → chunk-8kdrnrpa.js} +1 -1
  10. package/dist/builtin/workflows/builtin/{chunk-t8y25z1j.js → chunk-8ycbc76t.js} +1 -1
  11. package/dist/builtin/workflows/builtin/{chunk-vbrmytm5.js → chunk-a4fdm2cw.js} +1 -1
  12. package/dist/builtin/workflows/builtin/{chunk-9pjdp2td.js → chunk-d5cxskkp.js} +3 -3
  13. package/dist/builtin/workflows/builtin/{chunk-tpsw128z.js → chunk-d9pz64yp.js} +3 -3
  14. package/dist/builtin/workflows/builtin/{chunk-z0d03ktm.js → chunk-gp0s6m45.js} +1 -1
  15. package/dist/builtin/workflows/builtin/{chunk-4kygv34g.js → chunk-m8eg152f.js} +1 -1
  16. package/dist/builtin/workflows/builtin/{chunk-mswg7kc7.js → chunk-r39ypw6b.js} +1 -1
  17. package/dist/builtin/workflows/builtin/{chunk-q7dry6km.js → chunk-va2h64a6.js} +3 -3
  18. package/dist/builtin/workflows/builtin/generate-and-filter.js +2 -2
  19. package/dist/builtin/workflows/builtin/goal.js +4 -4
  20. package/dist/builtin/workflows/builtin/index.js +9 -9
  21. package/dist/builtin/workflows/builtin/loop-until-done.js +2 -2
  22. package/dist/builtin/workflows/builtin/ralph.js +4 -4
  23. package/dist/builtin/workflows/builtin/tournament.js +2 -2
  24. package/dist/builtin/workflows/package.json +1 -1
  25. package/dist/builtin/workflows/src/authoring.d.ts +2 -0
  26. package/dist/builtin/workflows/src/extension/index.bundle.mjs +403 -76
  27. package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +387 -60
  28. package/dist/builtin/workflows/src/index.js +393 -62
  29. package/dist/builtin/workflows/src/local-worker-entry.mjs +387 -60
  30. package/dist/builtin/workflows/src/shared/serializable-error-families.d.ts +1 -0
  31. package/dist/builtin/workflows/src/shared/structured-output-errors.d.ts +50 -0
  32. package/dist/config.d.ts +2 -0
  33. package/dist/config.d.ts.map +1 -1
  34. package/dist/config.js +4 -0
  35. package/dist/config.js.map +1 -1
  36. package/dist/core/agent-session-background-compaction.d.ts.map +1 -1
  37. package/dist/core/agent-session-background-compaction.js +2 -1
  38. package/dist/core/agent-session-background-compaction.js.map +1 -1
  39. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  40. package/dist/core/agent-session-compaction.js +98 -4
  41. package/dist/core/agent-session-compaction.js.map +1 -1
  42. package/dist/core/agent-session-detached-tools.d.ts +20 -5
  43. package/dist/core/agent-session-detached-tools.d.ts.map +1 -1
  44. package/dist/core/agent-session-detached-tools.js +97 -21
  45. package/dist/core/agent-session-detached-tools.js.map +1 -1
  46. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  47. package/dist/core/agent-session-message-queue.js +2 -1
  48. package/dist/core/agent-session-message-queue.js.map +1 -1
  49. package/dist/core/agent-session-methods.d.ts +3 -1
  50. package/dist/core/agent-session-methods.d.ts.map +1 -1
  51. package/dist/core/agent-session-methods.js.map +1 -1
  52. package/dist/core/agent-session-persistent-custom-messages.d.ts.map +1 -1
  53. package/dist/core/agent-session-persistent-custom-messages.js +12 -4
  54. package/dist/core/agent-session-persistent-custom-messages.js.map +1 -1
  55. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  56. package/dist/core/agent-session-prompt.js +33 -0
  57. package/dist/core/agent-session-prompt.js.map +1 -1
  58. package/dist/core/compaction/background-compaction.d.ts +11 -5
  59. package/dist/core/compaction/background-compaction.d.ts.map +1 -1
  60. package/dist/core/compaction/background-compaction.js +19 -10
  61. package/dist/core/compaction/background-compaction.js.map +1 -1
  62. package/dist/core/compaction/compaction-boundary.d.ts +10 -0
  63. package/dist/core/compaction/compaction-boundary.d.ts.map +1 -1
  64. package/dist/core/compaction/compaction-boundary.js +30 -2
  65. package/dist/core/compaction/compaction-boundary.js.map +1 -1
  66. package/dist/core/compaction/compaction-runner.d.ts +7 -0
  67. package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
  68. package/dist/core/compaction/compaction-runner.js +13 -5
  69. package/dist/core/compaction/compaction-runner.js.map +1 -1
  70. package/dist/core/compaction/compaction-types.d.ts +1 -1
  71. package/dist/core/compaction/compaction-types.js +1 -1
  72. package/dist/core/compaction/compaction-types.js.map +1 -1
  73. package/dist/core/compaction/deleted-ranges.d.ts +17 -2
  74. package/dist/core/compaction/deleted-ranges.d.ts.map +1 -1
  75. package/dist/core/compaction/deleted-ranges.js +44 -5
  76. package/dist/core/compaction/deleted-ranges.js.map +1 -1
  77. package/dist/core/compaction/history-recall.d.ts +32 -0
  78. package/dist/core/compaction/history-recall.d.ts.map +1 -0
  79. package/dist/core/compaction/history-recall.js +275 -0
  80. package/dist/core/compaction/history-recall.js.map +1 -0
  81. package/dist/core/compaction/index.d.ts +2 -0
  82. package/dist/core/compaction/index.d.ts.map +1 -1
  83. package/dist/core/compaction/index.js +2 -0
  84. package/dist/core/compaction/index.js.map +1 -1
  85. package/dist/core/compaction/pi-summary-fallback.d.ts.map +1 -1
  86. package/dist/core/compaction/pi-summary-fallback.js +1 -0
  87. package/dist/core/compaction/pi-summary-fallback.js.map +1 -1
  88. package/dist/core/compaction/planner-outcome.d.ts +14 -0
  89. package/dist/core/compaction/planner-outcome.d.ts.map +1 -1
  90. package/dist/core/compaction/planner-outcome.js +8 -0
  91. package/dist/core/compaction/planner-outcome.js.map +1 -1
  92. package/dist/core/compaction/range-planner-diagnostics.d.ts +35 -10
  93. package/dist/core/compaction/range-planner-diagnostics.d.ts.map +1 -1
  94. package/dist/core/compaction/range-planner-diagnostics.js +67 -24
  95. package/dist/core/compaction/range-planner-diagnostics.js.map +1 -1
  96. package/dist/core/compaction/range-planner.d.ts +7 -4
  97. package/dist/core/compaction/range-planner.d.ts.map +1 -1
  98. package/dist/core/compaction/range-planner.js +43 -19
  99. package/dist/core/compaction/range-planner.js.map +1 -1
  100. package/dist/core/compaction/refusal-recovery.d.ts +27 -0
  101. package/dist/core/compaction/refusal-recovery.d.ts.map +1 -0
  102. package/dist/core/compaction/refusal-recovery.js +65 -0
  103. package/dist/core/compaction/refusal-recovery.js.map +1 -0
  104. package/dist/core/compaction/region-trimming.d.ts +23 -0
  105. package/dist/core/compaction/region-trimming.d.ts.map +1 -1
  106. package/dist/core/compaction/region-trimming.js +59 -15
  107. package/dist/core/compaction/region-trimming.js.map +1 -1
  108. package/dist/core/compaction/structured-compaction-input.d.ts +19 -1
  109. package/dist/core/compaction/structured-compaction-input.d.ts.map +1 -1
  110. package/dist/core/compaction/structured-compaction-input.js +30 -17
  111. package/dist/core/compaction/structured-compaction-input.js.map +1 -1
  112. package/dist/core/compaction/transcript-serialization.d.ts +9 -3
  113. package/dist/core/compaction/transcript-serialization.d.ts.map +1 -1
  114. package/dist/core/compaction/transcript-serialization.js +18 -10
  115. package/dist/core/compaction/transcript-serialization.js.map +1 -1
  116. package/dist/core/messages.d.ts +5 -1
  117. package/dist/core/messages.d.ts.map +1 -1
  118. package/dist/core/messages.js +21 -3
  119. package/dist/core/messages.js.map +1 -1
  120. package/dist/core/session-manager-core.js +1 -1
  121. package/dist/core/session-manager-core.js.map +1 -1
  122. package/dist/core/session-manager-history.d.ts +1 -1
  123. package/dist/core/session-manager-history.d.ts.map +1 -1
  124. package/dist/core/session-manager-history.js +2 -5
  125. package/dist/core/session-manager-history.js.map +1 -1
  126. package/dist/core/settings-defaults.d.ts +2 -0
  127. package/dist/core/settings-defaults.d.ts.map +1 -1
  128. package/dist/core/settings-defaults.js +2 -0
  129. package/dist/core/settings-defaults.js.map +1 -1
  130. package/dist/core/settings-manager-basic-accessors.d.ts +2 -0
  131. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  132. package/dist/core/settings-manager-basic-accessors.js +3 -0
  133. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  134. package/dist/core/settings-schema.d.ts +2 -0
  135. package/dist/core/settings-schema.d.ts.map +1 -1
  136. package/dist/core/settings-schema.js +4 -0
  137. package/dist/core/settings-schema.js.map +1 -1
  138. package/dist/core/storage/session/conformance.d.ts.map +1 -1
  139. package/dist/core/storage/session/conformance.js +12 -0
  140. package/dist/core/storage/session/conformance.js.map +1 -1
  141. package/dist/core/storage/session/jsonl-session-store.d.ts.map +1 -1
  142. package/dist/core/storage/session/jsonl-session-store.js +3 -0
  143. package/dist/core/storage/session/jsonl-session-store.js.map +1 -1
  144. package/dist/core/storage/session/legacy-session-store.d.ts.map +1 -1
  145. package/dist/core/storage/session/legacy-session-store.js +3 -0
  146. package/dist/core/storage/session/legacy-session-store.js.map +1 -1
  147. package/dist/core/storage/session/memory-session-store.d.ts.map +1 -1
  148. package/dist/core/storage/session/memory-session-store.js +3 -0
  149. package/dist/core/storage/session/memory-session-store.js.map +1 -1
  150. package/dist/core/storage/session/sql-session-store.d.ts.map +1 -1
  151. package/dist/core/storage/session/sql-session-store.js +12 -3
  152. package/dist/core/storage/session/sql-session-store.js.map +1 -1
  153. package/dist/core/storage/session/types.d.ts +3 -0
  154. package/dist/core/storage/session/types.d.ts.map +1 -1
  155. package/dist/core/storage/session/types.js +3 -0
  156. package/dist/core/storage/session/types.js.map +1 -1
  157. package/dist/core/tools/history-protocol.d.ts +3 -0
  158. package/dist/core/tools/history-protocol.d.ts.map +1 -1
  159. package/dist/core/tools/history-protocol.js +7 -87
  160. package/dist/core/tools/history-protocol.js.map +1 -1
  161. package/dist/core/tools/history-transcript.d.ts +24 -0
  162. package/dist/core/tools/history-transcript.d.ts.map +1 -0
  163. package/dist/core/tools/history-transcript.js +110 -0
  164. package/dist/core/tools/history-transcript.js.map +1 -0
  165. package/dist/index.d.ts +1 -1
  166. package/dist/index.d.ts.map +1 -1
  167. package/dist/index.js.map +1 -1
  168. package/dist/main-session.d.ts.map +1 -1
  169. package/dist/main-session.js +21 -5
  170. package/dist/main-session.js.map +1 -1
  171. package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
  172. package/dist/modes/interactive/components/compaction-boundary-message.js +7 -3
  173. package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
  174. package/dist/modes/interactive/interactive-render-chat.js +2 -2
  175. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  176. package/dist/session-id-target.d.ts +1 -0
  177. package/dist/session-id-target.d.ts.map +1 -1
  178. package/dist/session-id-target.js +3 -0
  179. package/dist/session-id-target.js.map +1 -1
  180. package/docs/compaction/reference.md +3 -2
  181. package/docs/compaction.md +35 -7
  182. package/docs/development.md +1 -1
  183. package/docs/sdk/reference.md +6 -5
  184. package/docs/sessions.md +3 -3
  185. package/docs/settings.md +3 -0
  186. package/docs/storage.md +2 -0
  187. package/docs/workflows/api-reference.md +15 -3
  188. package/docs/workflows/authoring.md +2 -2
  189. package/docs/workflows/operations.md +1 -0
  190. package/docs/workflows/reliable-design.md +1 -1
  191. package/npm-shrinkwrap.json +32 -32
  192. package/package.json +3 -3
  193. package/schemas/settings.schema.json +5 -0
@@ -13359,6 +13359,10 @@ function stageSessionExtensionRunner(current) {
13359
13359
  }
13360
13360
  return;
13361
13361
  }
13362
+ function stageSessionToolContext(session, toolCallId, signal) {
13363
+ const runner = session?.extensionRunner;
13364
+ return typeof runner?.createToolContext === "function" ? runner.createToolContext(toolCallId, signal) : undefined;
13365
+ }
13362
13366
  function shutdownStageSession(current) {
13363
13367
  if (!current)
13364
13368
  return Promise.resolve();
@@ -13899,7 +13903,7 @@ async function createTestAgentSession(_options) {
13899
13903
  compactedText: "[User]: retained",
13900
13904
  firstKeptEntryId: "kept",
13901
13905
  tokensBefore: 0,
13902
- promptVersion: 5,
13906
+ promptVersion: 6,
13903
13907
  parameters: { compression_ratio: 0.5, preserve_recent: 2, query: "auto-detected" },
13904
13908
  rung: "planned",
13905
13909
  stats: {
@@ -23186,6 +23190,82 @@ var init_run_eviction_errors = __esm(() => {
23186
23190
  };
23187
23191
  });
23188
23192
 
23193
+ // dist/builtin/workflows/src/shared/structured-output-errors.ts
23194
+ function isWorkflowStructuredOutputInferenceError(error) {
23195
+ return error instanceof WorkflowStructuredOutputInferenceError || hasIdentity(error, NAMES, CODES2);
23196
+ }
23197
+ function findWorkflowStructuredOutputInferenceError(error) {
23198
+ return causeChain(error).find(isWorkflowStructuredOutputInferenceError);
23199
+ }
23200
+ function deserializeWorkflowStructuredOutputInferenceError(serialized, cause) {
23201
+ if (!CODES2.has(serialized.code))
23202
+ return;
23203
+ const rebuilt = cause ?? (serialized.cause === undefined ? undefined : deserializeCause3(serialized.cause, 0));
23204
+ const error = new WorkflowStructuredOutputInferenceError(serialized.code, serialized.fields, rebuilt === undefined ? undefined : { cause: rebuilt });
23205
+ Object.defineProperty(error, "message", { value: serialized.message });
23206
+ return error;
23207
+ }
23208
+ function serializeCause5(cause, depth) {
23209
+ if (!(cause instanceof Error) || depth >= MAX_CAUSE_DEPTH4)
23210
+ return { name: "Error", message: cause instanceof Error ? cause.message : String(cause) };
23211
+ const code = cause.code;
23212
+ return {
23213
+ name: cause.name,
23214
+ message: cause.message,
23215
+ ...typeof code === "string" ? { code } : {},
23216
+ ...cause.cause === undefined ? {} : { cause: serializeCause5(cause.cause, depth + 1) }
23217
+ };
23218
+ }
23219
+ function deserializeCause3(cause, depth) {
23220
+ const nested = cause.cause === undefined || depth >= MAX_CAUSE_DEPTH4 ? undefined : deserializeCause3(cause.cause, depth + 1);
23221
+ const error = new Error(cause.message, nested === undefined ? undefined : { cause: nested });
23222
+ error.name = cause.name;
23223
+ if (cause.code !== undefined)
23224
+ Object.assign(error, { code: cause.code });
23225
+ return error;
23226
+ }
23227
+ var NAME = "WorkflowStructuredOutputInferenceError", CODES2, NAMES, SUBJECTS, HINTS3, WorkflowStructuredOutputInferenceError;
23228
+ var init_structured_output_errors = __esm(() => {
23229
+ CODES2 = new Set([
23230
+ "auto-inference-failed",
23231
+ "tool-context-unavailable"
23232
+ ]);
23233
+ NAMES = new Set([NAME]);
23234
+ SUBJECTS = {
23235
+ "auto-inference-failed": "The automatic structured_output inference failed",
23236
+ "tool-context-unavailable": "The automatic structured_output inference could not start"
23237
+ };
23238
+ HINTS3 = {
23239
+ "auto-inference-failed": "The runtime falls back to corrective prompts. Check the decision model and its credentials (the decisionModel setting), raise the stage's schemaTimeoutMs for a slow model, or end the stage with the final answer its schema needs; the cause says what failed.",
23240
+ "tool-context-unavailable": "The runtime falls back to corrective prompts. Create the stage's session with the Atomic SDK, whose sessions expose the tool context the inference runs in."
23241
+ };
23242
+ WorkflowStructuredOutputInferenceError = class WorkflowStructuredOutputInferenceError extends Error {
23243
+ name = NAME;
23244
+ code;
23245
+ hint;
23246
+ retryable = false;
23247
+ fields;
23248
+ constructor(code, fields, options) {
23249
+ const hint = HINTS3[code];
23250
+ super(failureMessage(SUBJECTS[code], `stage "${fields.stageName}"`, code, hint), options);
23251
+ this.code = code;
23252
+ this.hint = hint;
23253
+ this.fields = fields;
23254
+ }
23255
+ toJSON() {
23256
+ return {
23257
+ name: this.name,
23258
+ code: this.code,
23259
+ message: this.message,
23260
+ hint: this.hint,
23261
+ retryable: this.retryable,
23262
+ fields: this.fields,
23263
+ ...this.cause === undefined ? {} : { cause: serializeCause5(this.cause, 0) }
23264
+ };
23265
+ }
23266
+ };
23267
+ });
23268
+
23189
23269
  // dist/builtin/workflows/src/shared/serializable-error-families.ts
23190
23270
  import {
23191
23271
  AgentRehydrateError,
@@ -23278,6 +23358,7 @@ var SERIALIZABLE_ERROR_FAMILIES, FAMILY_NAMES5;
23278
23358
  var init_serializable_error_families = __esm(() => {
23279
23359
  init_run_eviction_errors();
23280
23360
  init_stage_wait_errors();
23361
+ init_structured_output_errors();
23281
23362
  init_workflow_git_required_error();
23282
23363
  SERIALIZABLE_ERROR_FAMILIES = {
23283
23364
  "stage-wait": family({
@@ -23407,6 +23488,11 @@ var init_serializable_error_families = __esm(() => {
23407
23488
  return form;
23408
23489
  },
23409
23490
  rehydrate: rehydrateResumeError
23491
+ }),
23492
+ "structured-output": family({
23493
+ is: instanceOf(WorkflowStructuredOutputInferenceError),
23494
+ serialize: (error) => error.toJSON(),
23495
+ rehydrate: deserializeWorkflowStructuredOutputInferenceError
23410
23496
  })
23411
23497
  };
23412
23498
  FAMILY_NAMES5 = Object.keys(SERIALIZABLE_ERROR_FAMILIES);
@@ -66601,7 +66687,7 @@ Preserve every confirmed veto or blocking finding in remaining_work verbatim. Ex
66601
66687
  </decision_rules>
66602
66688
 
66603
66689
  <output_format>
66604
- Call structured_output with repair_guidance (a concise actionable repair plan) and remaining_work (the unresolved findings as strings). Never emit an approval or rejection decision. ${READABLE_REPORT}
66690
+ Report repair_guidance (a concise actionable repair plan) and remaining_work (the unresolved findings as strings). Never emit an approval or rejection decision. ${READABLE_REPORT}
66605
66691
  ${GROUNDED_REPORTING}
66606
66692
  </output_format>
66607
66693
 
@@ -66963,7 +67049,7 @@ async function warm_first_fan_out(ctx, steps, prefixKeyOf, options = {}) {
66963
67049
  throw warmFailure;
66964
67050
  return steps.map((_, index) => resultsByIndex.get(index)).filter((result) => result !== undefined);
66965
67051
  }
66966
- var MAX_INLINE_CANDIDATE_BYTES, DEFAULT_WARM_CONCURRENCY = 4, DEFAULT_OUTPUT_FORMAT = "Call structured_output with criterion_id, score (1–20), evidence, and findings containing finding and severity.";
67052
+ var MAX_INLINE_CANDIDATE_BYTES, DEFAULT_WARM_CONCURRENCY = 4, DEFAULT_OUTPUT_FORMAT = "Report criterion_id, score (1–20), evidence, and findings containing finding and severity.";
66967
67053
  var init_verification_prompts = __esm(() => {
66968
67054
  init_verification_criteria();
66969
67055
  MAX_INLINE_CANDIDATE_BYTES = 32 * 1024;
@@ -67056,7 +67142,7 @@ function stageName(cell, reaskWave) {
67056
67142
  return reaskWave === 0 ? cell.name : `${cell.name}-reask-${reaskWave}`;
67057
67143
  }
67058
67144
  function verifierOutputFormat(criterionId) {
67059
- return `Call structured_output with criterion_id (set to ${criterionId}), score (1–20), evidence (string array), and findings containing finding and severity (veto, blocking, or note).`;
67145
+ return `Report criterion_id (set to ${criterionId}), score (1–20), evidence (string array), and findings containing finding and severity (veto, blocking, or note).`;
67060
67146
  }
67061
67147
  function scoreStep(cell, reaskWave, head, criteriaPath) {
67062
67148
  const promptHead = {
@@ -67696,7 +67782,7 @@ Stop after every candidate is shortlisted once or recorded as discarded.
67696
67782
  </stop_rules>
67697
67783
 
67698
67784
  <output_format>
67699
- Call structured_output with shortlist (candidate artifact paths in ranked order) and discarded entries containing path and a concise, criteria-based reason.
67785
+ Report shortlist (candidate artifact paths in ranked order) and discarded entries containing path and a concise, criteria-based reason.
67700
67786
  </output_format>
67701
67787
 
67702
67788
  <objective>
@@ -67708,7 +67794,7 @@ function renderJudgePrompt(task, filterPath, shortlistSize, candidates = []) {
67708
67794
  task: `Rank at most ${shortlistSize} distinct candidate paths for: ${task}.`,
67709
67795
  groundTruthNote: `Read the filter report at ${filterPath} and every candidate path it references before judging.`,
67710
67796
  candidates,
67711
- outputFormat: "Call structured_output with shortlist (candidate paths in ranked order) and rationale (a concise, criteria-based explanation)."
67797
+ outputFormat: "Report shortlist (candidate paths in ranked order) and rationale (a concise, criteria-based explanation)."
67712
67798
  };
67713
67799
  const prompt = build_scoring_prompt(head, {
67714
67800
  id: "filtered_shortlist",
@@ -67918,16 +68004,14 @@ function stringifyStructuredOutputValue(value2) {
67918
68004
  throw new Error(`atomic-workflows: structured_output returned a non-serializable value: ${error instanceof Error ? error.message : String(error)}`);
67919
68005
  }
67920
68006
  }
67921
- function stageOptionsWithStructuredOutput(options, capture, executionCapture) {
67922
- if (!options?.schema || !capture)
67923
- return options;
68007
+ function createStageStructuredOutputTool(options, capture, executionCapture) {
67924
68008
  const structuredOutputTool = createStructuredOutputTool({
67925
68009
  schema: options.schema,
67926
68010
  capture,
67927
68011
  ...options.schemaTimeoutMs === undefined ? {} : { timeoutMs: options.schemaTimeoutMs }
67928
68012
  });
67929
68013
  const executeStructuredOutput = structuredOutputTool.execute;
67930
- const capturedStructuredOutputTool = {
68014
+ return {
67931
68015
  ...structuredOutputTool,
67932
68016
  async execute(...args) {
67933
68017
  const result = await executeStructuredOutput(...args);
@@ -67940,21 +68024,25 @@ function stageOptionsWithStructuredOutput(options, capture, executionCapture) {
67940
68024
  return result;
67941
68025
  }
67942
68026
  };
68027
+ }
68028
+ function stageOptionsWithStructuredOutput(options, structuredOutputTool) {
68029
+ if (!options?.schema || !structuredOutputTool)
68030
+ return options;
67943
68031
  const tools = options.tools === undefined ? options.noTools === "all" ? [STRUCTURED_OUTPUT_TOOL_NAME] : undefined : Array.from(new Set([...options.tools, STRUCTURED_OUTPUT_TOOL_NAME]));
67944
68032
  const excludedTools = options.excludedTools?.filter((toolName) => toolName !== STRUCTURED_OUTPUT_TOOL_NAME);
67945
68033
  return {
67946
68034
  ...options,
67947
68035
  ...tools !== undefined ? { tools } : {},
67948
68036
  ...excludedTools !== undefined ? { excludedTools } : {},
67949
- customTools: [...options.customTools ?? [], capturedStructuredOutputTool]
68037
+ customTools: [...options.customTools ?? [], structuredOutputTool]
67950
68038
  };
67951
68039
  }
67952
68040
  var STRUCTURED_OUTPUT_MAX_CORRECTIVE_PROMPTS = 3, STRUCTURED_OUTPUT_MISSING_ERROR = "atomic-workflows: stage configured with schema must finish by calling structured_output.", WorkflowStructuredOutputContractError, STRUCTURED_OUTPUT_TOOL_NAME = "structured_output";
67953
68041
  var init_stage_runner_structured_output = __esm(() => {
67954
68042
  WorkflowStructuredOutputContractError = class WorkflowStructuredOutputContractError extends Error {
67955
68043
  code = "ATOMIC_WORKFLOW_STRUCTURED_OUTPUT_CONTRACT";
67956
- constructor(message) {
67957
- super(message);
68044
+ constructor(message, options) {
68045
+ super(message, options);
67958
68046
  this.name = "WorkflowStructuredOutputContractError";
67959
68047
  }
67960
68048
  };
@@ -68063,7 +68151,7 @@ function build_progress_prompt(input) {
68063
68151
  ...input.checkpoints.map((checkpoint) => `- ${checkpoint}`),
68064
68152
  "</checkpoints>",
68065
68153
  "<output_format>",
68066
- `Return structured_output with scores: [{ checkpoint, score }], using integer scores from ${VERIFICATION_SCALE.min} through ${VERIFICATION_SCALE.max}.`,
68154
+ `Report scores: [{ checkpoint, score }], using integer scores from ${VERIFICATION_SCALE.min} through ${VERIFICATION_SCALE.max}.`,
68067
68155
  "</output_format>"
68068
68156
  ].join(`
68069
68157
  `);
@@ -68863,7 +68951,7 @@ Objective:
68863
68951
  ${context.objective}`,
68864
68952
  groundTruthNote: `The objective is the contract. Verify the finding against observed code, not reviewer narration.`,
68865
68953
  candidates: [candidate],
68866
- outputFormat: "Call structured_output with score (an integer from 1 to 20) and evidence (an array of observed, concise reasons)."
68954
+ outputFormat: "Report score (an integer from 1 to 20) and evidence (an array of observed, concise reasons)."
68867
68955
  };
68868
68956
  const prompt = build_scoring_prompt(head, {
68869
68957
  id: "finding_reverification",
@@ -74761,7 +74849,7 @@ var init_delivery_failure_reason = __esm(() => {
74761
74849
 
74762
74850
  // dist/builtin/intercom/broker/released-child-errors.ts
74763
74851
  function isReleasedChildErrorCode(value2) {
74764
- return CODES2.has(value2);
74852
+ return CODES3.has(value2);
74765
74853
  }
74766
74854
  function releasedChildErrorFor(refusal, options) {
74767
74855
  return refusal.code === "unknown_released_child" ? new UnknownReleasedChildError(refusal, options) : new ReleasedChildReservationError(refusal, options);
@@ -74772,7 +74860,7 @@ function rehydrateCause3(serialized, depth) {
74772
74860
  cause.name = serialized.name;
74773
74861
  return cause;
74774
74862
  }
74775
- var RELEASED_CHILD_ERROR_CODES, CODES2, HINTS3, BASE_NAME = "IntercomReleasedChildError", RESERVATION_NAME = "ReleasedChildReservationError", UNKNOWN_NAME = "UnknownReleasedChildError", IntercomReleasedChildError, ReleasedChildReservationError, UnknownReleasedChildError, NAMES, RESERVATION_NAMES, UNKNOWN_NAMES, MAX_CAUSE_DEPTH11 = 4;
74863
+ var RELEASED_CHILD_ERROR_CODES, CODES3, HINTS4, BASE_NAME = "IntercomReleasedChildError", RESERVATION_NAME = "ReleasedChildReservationError", UNKNOWN_NAME = "UnknownReleasedChildError", IntercomReleasedChildError, ReleasedChildReservationError, UnknownReleasedChildError, NAMES2, RESERVATION_NAMES, UNKNOWN_NAMES, MAX_CAUSE_DEPTH11 = 4;
74776
74864
  var init_released_child_errors = __esm(() => {
74777
74865
  RELEASED_CHILD_ERROR_CODES = [
74778
74866
  "invalid_frame",
@@ -74784,8 +74872,8 @@ var init_released_child_errors = __esm(() => {
74784
74872
  "not_owner",
74785
74873
  "group_not_allowed"
74786
74874
  ];
74787
- CODES2 = new Set(RELEASED_CHILD_ERROR_CODES);
74788
- HINTS3 = {
74875
+ CODES3 = new Set(RELEASED_CHILD_ERROR_CODES);
74876
+ HINTS4 = {
74789
74877
  invalid_frame: "Send between 1 and 500 children per frame, each with a child name and a boolean wake flag.",
74790
74878
  invalid_child_name: "Use the child's exact, non-empty name; the wildcard `*` names no child.",
74791
74879
  invalid_alias: "Reserve extra targets only as session ids, never as names.",
@@ -74803,11 +74891,11 @@ var init_released_child_errors = __esm(() => {
74803
74891
  retryable = false;
74804
74892
  constructor(refusal, options) {
74805
74893
  const subject = refusal.childName === undefined ? "request" : `child ${JSON.stringify(refusal.childName)}`;
74806
- super(`Released-child request refused: ${subject} (${refusal.code}). ${HINTS3[refusal.code]}`, options);
74894
+ super(`Released-child request refused: ${subject} (${refusal.code}). ${HINTS4[refusal.code]}`, options);
74807
74895
  this.code = refusal.code;
74808
74896
  if (refusal.childName !== undefined)
74809
74897
  this.childName = refusal.childName;
74810
- this.hint = HINTS3[refusal.code];
74898
+ this.hint = HINTS4[refusal.code];
74811
74899
  }
74812
74900
  };
74813
74901
  ReleasedChildReservationError = class ReleasedChildReservationError extends IntercomReleasedChildError {
@@ -74816,14 +74904,14 @@ var init_released_child_errors = __esm(() => {
74816
74904
  UnknownReleasedChildError = class UnknownReleasedChildError extends IntercomReleasedChildError {
74817
74905
  name = UNKNOWN_NAME;
74818
74906
  };
74819
- NAMES = new Set([BASE_NAME, RESERVATION_NAME, UNKNOWN_NAME]);
74907
+ NAMES2 = new Set([BASE_NAME, RESERVATION_NAME, UNKNOWN_NAME]);
74820
74908
  RESERVATION_NAMES = new Set([RESERVATION_NAME]);
74821
74909
  UNKNOWN_NAMES = new Set([UNKNOWN_NAME]);
74822
74910
  });
74823
74911
 
74824
74912
  // dist/builtin/intercom/broker/released-reply-errors.ts
74825
74913
  function isReleasedReplyErrorCode(value2) {
74826
- return CODES3.has(value2);
74914
+ return CODES4.has(value2);
74827
74915
  }
74828
74916
  function rehydrateIntercomReleasedReplyError(serialized) {
74829
74917
  const options = serialized.cause === undefined ? undefined : { cause: rehydrateCause3(serialized.cause, 1) };
@@ -74871,15 +74959,15 @@ function readSerializedIntercomReleasedReplyError(value2) {
74871
74959
  ...cause === undefined ? {} : { cause }
74872
74960
  };
74873
74961
  }
74874
- var RELEASED_REPLY_ERROR_CODES, CODES3, HINTS4, RETRYABLE, BASE_NAME2 = "IntercomReleasedReplyError", ANSWERED_NAME = "ReleasedReplyAnsweredError", IN_FLIGHT_NAME = "ReleasedReplyInFlightError", IntercomReleasedReplyError, ReleasedReplyAnsweredError, ReleasedReplyInFlightError, NAMES2, ANSWERED_NAMES, IN_FLIGHT_NAMES, MAX_CAUSE_DEPTH12 = 4, isWireObject = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
74962
+ var RELEASED_REPLY_ERROR_CODES, CODES4, HINTS5, RETRYABLE, BASE_NAME2 = "IntercomReleasedReplyError", ANSWERED_NAME = "ReleasedReplyAnsweredError", IN_FLIGHT_NAME = "ReleasedReplyInFlightError", IntercomReleasedReplyError, ReleasedReplyAnsweredError, ReleasedReplyInFlightError, NAMES3, ANSWERED_NAMES, IN_FLIGHT_NAMES, MAX_CAUSE_DEPTH12 = 4, isWireObject = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
74875
74963
  var init_released_reply_errors = __esm(() => {
74876
74964
  init_released_child_errors();
74877
74965
  RELEASED_REPLY_ERROR_CODES = [
74878
74966
  "released_reply_answered",
74879
74967
  "released_reply_in_flight"
74880
74968
  ];
74881
- CODES3 = new Set(RELEASED_REPLY_ERROR_CODES);
74882
- HINTS4 = {
74969
+ CODES4 = new Set(RELEASED_REPLY_ERROR_CODES);
74970
+ HINTS5 = {
74883
74971
  released_reply_answered: "The subagent's owner already took another reply to this question; do not send this one again, and send a new message if the subagent needs more.",
74884
74972
  released_reply_in_flight: "Another reply to this question is still being handed to the subagent's owner; wait, then reply again if the subagent still waits for an answer."
74885
74973
  };
@@ -74896,9 +74984,9 @@ var init_released_reply_errors = __esm(() => {
74896
74984
  questionId;
74897
74985
  childName;
74898
74986
  constructor(code, fields, options) {
74899
- super(`Reply to a released subagent refused: question ${JSON.stringify(fields.questionId)} of ${JSON.stringify(fields.childName)} (${code}). ${HINTS4[code]}`, options);
74987
+ super(`Reply to a released subagent refused: question ${JSON.stringify(fields.questionId)} of ${JSON.stringify(fields.childName)} (${code}). ${HINTS5[code]}`, options);
74900
74988
  this.code = code;
74901
- this.hint = HINTS4[code];
74989
+ this.hint = HINTS5[code];
74902
74990
  this.retryable = RETRYABLE[code];
74903
74991
  this.messageId = fields.messageId;
74904
74992
  this.questionId = fields.questionId;
@@ -74917,7 +75005,7 @@ var init_released_reply_errors = __esm(() => {
74917
75005
  super("released_reply_in_flight", fields, options);
74918
75006
  }
74919
75007
  };
74920
- NAMES2 = new Set([BASE_NAME2, ANSWERED_NAME, IN_FLIGHT_NAME]);
75008
+ NAMES3 = new Set([BASE_NAME2, ANSWERED_NAME, IN_FLIGHT_NAME]);
74921
75009
  ANSWERED_NAMES = new Set([ANSWERED_NAME]);
74922
75010
  IN_FLIGHT_NAMES = new Set([IN_FLIGHT_NAME]);
74923
75011
  });
@@ -87528,6 +87616,18 @@ class StageSessionPause {
87528
87616
  function storedTranscript(session) {
87529
87617
  return asAgentSession(session)?.sessionManager.buildSessionProjection().messages ?? session.messages;
87530
87618
  }
87619
+ function storedEntryCount(session) {
87620
+ return storedEntries(session)?.length;
87621
+ }
87622
+ function storedAssistantMessageSince(session, entryCount) {
87623
+ if (entryCount === undefined)
87624
+ return false;
87625
+ return storedEntries(session)?.slice(entryCount).some((entry) => entry.type === "message" && entry.message.role === "assistant") === true;
87626
+ }
87627
+ function storedEntries(session) {
87628
+ const manager = asAgentSession(session)?.sessionManager;
87629
+ return typeof manager?.getEntries === "function" ? manager.getEntries() : undefined;
87630
+ }
87531
87631
  function unansweredToolCallIds(messages) {
87532
87632
  let index = messages.length - 1;
87533
87633
  while (index >= 0 && messages[index]?.role !== "assistant")
@@ -87808,6 +87908,7 @@ import {
87808
87908
  AutoRoutingInferenceError,
87809
87909
  convertToLlm,
87810
87910
  currentWorktreeRootMappings,
87911
+ findToolDetachmentError,
87811
87912
  isExtensionStartupFailure,
87812
87913
  isTaskCleanupError as isTaskCleanupError2,
87813
87914
  isTransientExtensionStartupFailure as isTransientExtensionStartupFailure2,
@@ -87859,7 +87960,9 @@ function isSessionCreationPauseResult(value2) {
87859
87960
  return "kind" in value2 && value2.kind === "paused";
87860
87961
  }
87861
87962
  function resumeMessageOptions(sdkOptions) {
87862
- return { ...sdkOptions, expandPromptTemplates: false };
87963
+ const options = { ...sdkOptions, expandPromptTemplates: false };
87964
+ operatorMessageOptions.add(options);
87965
+ return options;
87863
87966
  }
87864
87967
  function stageUserMessageText(message) {
87865
87968
  if (message.role !== "user")
@@ -88038,6 +88141,16 @@ class StageSessionController {
88038
88141
  structuredOutputExecutionFailure() {
88039
88142
  return this.structuredOutputExecutionFailureValue;
88040
88143
  }
88144
+ stageCancellationSignal() {
88145
+ return this.residency.startupWait.signal;
88146
+ }
88147
+ stageToolContext(toolCallId, signal) {
88148
+ return stageSessionToolContext(this.session, toolCallId, signal);
88149
+ }
88150
+ recordStructuredOutputWarning(warning) {
88151
+ this.modelWarnings.push(warning);
88152
+ this.notifyModelFallbackMetaChange();
88153
+ }
88041
88154
  beginStructuredOutputCandidateCycle() {
88042
88155
  this.structuredOutputCycleAttemptMark = this.modelAttempts.length;
88043
88156
  }
@@ -88434,12 +88547,19 @@ class StageSessionController {
88434
88547
  const unanswered = new Set(unansweredToolCallIds(storedTranscript(session)));
88435
88548
  return awaited.filter((toolCallId) => unanswered.has(toolCallId));
88436
88549
  };
88437
- try {
88438
- await resume.call(session, results);
88439
- } catch (error) {
88440
- if (stageReopenFailureCause(error) === "transient" && unsaved().length > 0)
88441
- throw new DetachedResultsNotSaved(error);
88442
- throw error;
88550
+ for (;; ) {
88551
+ try {
88552
+ await resume.call(session, results);
88553
+ break;
88554
+ } catch (error) {
88555
+ if (findToolDetachmentError(error)?.code === "session-busy") {
88556
+ await this.untilSessionSettles(session);
88557
+ continue;
88558
+ }
88559
+ if (stageReopenFailureCause(error) === "transient" && unsaved().length > 0)
88560
+ throw new DetachedResultsNotSaved(error);
88561
+ throw error;
88562
+ }
88443
88563
  }
88444
88564
  const missing = asAgentSession(session) === undefined ? [] : unsaved();
88445
88565
  if (missing.length > 0)
@@ -88453,6 +88573,25 @@ class StageSessionController {
88453
88573
  }, { code: "results-not-saved" });
88454
88574
  this.opts.waiting?.resultsInTranscript();
88455
88575
  }
88576
+ async untilSessionSettles(session) {
88577
+ const settled = Promise.withResolvers();
88578
+ const unsubscribe = session.subscribe((event) => {
88579
+ if (event.type === "agent_settled")
88580
+ settled.resolve();
88581
+ });
88582
+ let timer;
88583
+ try {
88584
+ await raceAbort2(Promise.race([
88585
+ settled.promise,
88586
+ new Promise((resolve) => {
88587
+ timer = setTimeout(resolve, SESSION_SETTLE_POLL_MS);
88588
+ })
88589
+ ]), this.opts.signal);
88590
+ } finally {
88591
+ clearTimeout(timer);
88592
+ unsubscribe();
88593
+ }
88594
+ }
88456
88595
  throwUnlessResultsSaveRetries(failure, attempt, startedAt) {
88457
88596
  const { signal } = this.opts;
88458
88597
  if (signal?.aborted)
@@ -89496,6 +89635,10 @@ class StageSessionController {
89496
89635
  const continuationSession = retryableAgentSession(activeSession);
89497
89636
  const admittedMessages = activeSession.messages.length > messagesBeforeAttempt.length;
89498
89637
  const willRetry = decision !== undefined && !this.disposed && this.opts.signal?.aborted !== true && !this.capturedStructuredOutputForAttempt();
89638
+ if (willRetry && activeSession.isWaitingOnDetachedResults?.() === true) {
89639
+ this.reportHeldForDetachedResults(activeSession, "retry", error);
89640
+ return { terminalScanStartIndex: terminalScanStartIndex ?? messagesBeforeAttempt.length };
89641
+ }
89499
89642
  const willContinue = continuationSession !== undefined && admittedMessages;
89500
89643
  if (retryableFailure && willRetry) {
89501
89644
  this.artifactCapture.settleAttempt(false);
@@ -89546,6 +89689,18 @@ class StageSessionController {
89546
89689
  }
89547
89690
  }
89548
89691
  }
89692
+ reportHeldForDetachedResults(session, held, error) {
89693
+ const code = error?.code;
89694
+ reportDebug3("workflow", "stage-input-held-for-detached-results", {
89695
+ runId: this.opts.runId,
89696
+ stageId: this.opts.stageId,
89697
+ stageName: this.opts.stageName,
89698
+ sessionId: session.sessionId,
89699
+ held,
89700
+ ...error instanceof Error ? { errorName: error.name } : {},
89701
+ ...typeof code === "string" ? { errorCode: code } : {}
89702
+ });
89703
+ }
89549
89704
  workflowAbortReason() {
89550
89705
  const reason = this.opts.signal?.reason;
89551
89706
  if (reason instanceof Error || reason instanceof DOMException || typeof reason === "string")
@@ -90043,6 +90198,7 @@ class StageSessionController {
90043
90198
  continue;
90044
90199
  }
90045
90200
  const promptStartIndex = activeSession.messages.length;
90201
+ const promptStartEntries = storedEntryCount(activeSession);
90046
90202
  this.lastPromptStartIndex = promptStartIndex;
90047
90203
  this.unresolvedContextOverflowMessage = undefined;
90048
90204
  try {
@@ -90055,6 +90211,11 @@ class StageSessionController {
90055
90211
  if (nextText !== initialText)
90056
90212
  await activeSession.steer(nextText, undefined, { expandPromptTemplates: false });
90057
90213
  await this.continueFromResults(activeSession, activeSession.resumeDetachedTurn, detachedResults);
90214
+ } else if (activeSession.isWaitingOnDetachedResults?.() === true) {
90215
+ this.reportHeldForDetachedResults(activeSession, "prompt");
90216
+ if (nextOptions !== undefined && operatorMessageOptions.has(nextOptions))
90217
+ await activeSession.steer(nextText, undefined, { expandPromptTemplates: false });
90218
+ return { terminalScanStartIndex: promptStartIndex };
90058
90219
  } else
90059
90220
  await activeSession.prompt(nextText, nextOptions);
90060
90221
  const pendingPauseAfterPrompt = this.pauseControl.currentResume();
@@ -90069,7 +90230,7 @@ class StageSessionController {
90069
90230
  continue;
90070
90231
  }
90071
90232
  this.throwUnresolvedContextOverflowIfPresent();
90072
- this.throwIfEmptyCompletion(activeSession, promptStartIndex);
90233
+ this.throwIfEmptyCompletion(activeSession, promptStartIndex, promptStartEntries);
90073
90234
  return { terminalScanStartIndex: promptStartIndex };
90074
90235
  } catch (err) {
90075
90236
  if (err instanceof DetachedResultsNotSaved)
@@ -90285,11 +90446,13 @@ class StageSessionController {
90285
90446
  if (message !== undefined)
90286
90447
  throw unresolvedContextOverflowFailure(message);
90287
90448
  }
90288
- throwIfEmptyCompletion(activeSession, promptStartIndex) {
90449
+ throwIfEmptyCompletion(activeSession, promptStartIndex, promptStartEntries) {
90289
90450
  if (this.structuredOutputCapture === undefined || this.structuredOutputCapture.called)
90290
90451
  return;
90291
90452
  if (this.disposed || hasAssistantMessageSince(activeSession.messages, promptStartIndex))
90292
90453
  return;
90454
+ if (storedAssistantMessageSince(activeSession, promptStartEntries))
90455
+ return;
90293
90456
  if (this.opts.signal?.aborted)
90294
90457
  throw this.workflowAbortReason();
90295
90458
  if (this.residency.startupWait.signal.aborted)
@@ -90297,7 +90460,7 @@ class StageSessionController {
90297
90460
  throw new WorkflowPromptEmptyCompletionFailure;
90298
90461
  }
90299
90462
  }
90300
- var WORKFLOW_STAGE_CLOSED_FOR_GOOD_STATE = "atomic:workflow-stage-closed-for-good", WORKFLOW_STAGE_END_CHILDREN_STATE = "atomic:workflow-stage-end-children", StageSessionCreationCancelled, ThrownErrorRetryPaused, NO_TERMINATING_TOOL_CALLS;
90463
+ var WORKFLOW_STAGE_CLOSED_FOR_GOOD_STATE = "atomic:workflow-stage-closed-for-good", WORKFLOW_STAGE_END_CHILDREN_STATE = "atomic:workflow-stage-end-children", SESSION_SETTLE_POLL_MS = 50, StageSessionCreationCancelled, operatorMessageOptions, ThrownErrorRetryPaused, NO_TERMINATING_TOOL_CALLS;
90301
90464
  var init_stage_runner_controller = __esm(() => {
90302
90465
  init_stage_wait();
90303
90466
  init_stage_wait_errors();
@@ -90324,6 +90487,7 @@ var init_stage_runner_controller = __esm(() => {
90324
90487
  this.name = "StageSessionCreationCancelled";
90325
90488
  }
90326
90489
  };
90490
+ operatorMessageOptions = new WeakSet;
90327
90491
  ThrownErrorRetryPaused = class ThrownErrorRetryPaused extends Error {
90328
90492
  resume;
90329
90493
  constructor(resume) {
@@ -90501,12 +90665,13 @@ function validatePromptOutputOptions(outputOptions) {
90501
90665
  }
90502
90666
  }
90503
90667
  function stageOutputInstruction(outputOptions, hasStructuredOutput = false) {
90668
+ const closing = hasStructuredOutput ? STRUCTURED_OUTPUT_CLOSING_INSTRUCTION : "";
90504
90669
  if (typeof outputOptions.output !== "string" || outputOptions.output.length === 0)
90505
- return "";
90670
+ return closing;
90506
90671
  if (hasStructuredOutput) {
90507
90672
  return `
90508
90673
 
90509
- [This stage has two final output channels. In the same final assistant message, write the complete human-readable artifact as ordinary assistant text before calling structured_output. That text is saved verbatim as the artifact and is what later stages read; the structured_output tool infers the separate machine-readable result for workflow logic from its instructions and state. Do not replace the artifact text with JSON or a pointer to another file. Files you write yourself are not the artifact.]`;
90674
+ [This stage has two final output channels. In the same final assistant message, write the complete human-readable artifact as ordinary assistant text before calling structured_output. That text is saved verbatim as the artifact and is what later stages read; the structured_output tool infers the separate machine-readable result for workflow logic from its instructions and state. Do not replace the artifact text with JSON or a pointer to another file. Files you write yourself are not the artifact.]${closing}`;
90510
90675
  }
90511
90676
  return `
90512
90677
 
@@ -90549,12 +90714,135 @@ ${err instanceof Error ? err.message : String(err)}`;
90549
90714
 
90550
90715
  ${reference}`;
90551
90716
  }
90552
- var DEFAULT_MAX_OUTPUT_BYTES, DEFAULT_MAX_OUTPUT_LINES = 5000;
90717
+ var DEFAULT_MAX_OUTPUT_BYTES, DEFAULT_MAX_OUTPUT_LINES = 5000, STRUCTURED_OUTPUT_CLOSING_INSTRUCTION = `
90718
+
90719
+ [When your work is done, finish by calling the structured_output tool exactly once, with complete instructions and nonempty named state for this stage's result. Do not answer with plain JSON text.]`;
90553
90720
  var init_stage_runner_output = __esm(() => {
90554
90721
  init_workflow_artifacts();
90555
90722
  DEFAULT_MAX_OUTPUT_BYTES = 200 * 1024;
90556
90723
  });
90557
90724
 
90725
+ // dist/builtin/workflows/src/runs/foreground/stage-runner-structured-output-auto.ts
90726
+ import {
90727
+ findDecisionError as findDecisionError2,
90728
+ isDecisionOutputError
90729
+ } from "@bastani/atomic";
90730
+ function boundedText(text, limit) {
90731
+ if (text.length <= limit)
90732
+ return text;
90733
+ const head = Math.ceil(limit / 2);
90734
+ return `${text.slice(0, head)}
90735
+ [… ${text.length - limit} characters omitted …]
90736
+ ${text.slice(text.length - (limit - head))}`;
90737
+ }
90738
+ function conversationText(message) {
90739
+ if (message.role !== "user" && message.role !== "assistant")
90740
+ return;
90741
+ const text = extractMessageText2(message).trim();
90742
+ return text.length === 0 ? undefined : { role: message.role, text };
90743
+ }
90744
+ function finalAssistantAnswer(messages, promptStartIndex) {
90745
+ for (let index = messages.length - 1;index >= promptStartIndex; index -= 1) {
90746
+ const message = messages[index];
90747
+ if (message.role !== "assistant")
90748
+ continue;
90749
+ const rawText = extractMessageText2(message);
90750
+ if (rawText.trim().length > 0)
90751
+ return { index, rawText };
90752
+ }
90753
+ return;
90754
+ }
90755
+ function automaticStructuredOutputInput(input) {
90756
+ const { messages, promptStartIndex } = input;
90757
+ const final = finalAssistantAnswer(messages, promptStartIndex);
90758
+ if (final === undefined)
90759
+ return;
90760
+ const recent = [];
90761
+ for (let index = final.index - 1;index >= 0 && recent.length < AUTOMATIC_STRUCTURED_OUTPUT_TRANSCRIPT_MESSAGES; index -= 1) {
90762
+ const message = conversationText(messages[index]);
90763
+ if (message !== undefined)
90764
+ recent.unshift({
90765
+ role: message.role,
90766
+ text: boundedText(message.text, AUTOMATIC_STRUCTURED_OUTPUT_TEXT_CHARS)
90767
+ });
90768
+ }
90769
+ return {
90770
+ finalText: final.rawText,
90771
+ evidence: {
90772
+ stageTask: boundedText(input.stagePrompt, AUTOMATIC_STRUCTURED_OUTPUT_TEXT_CHARS),
90773
+ finalAssistantText: boundedText(final.rawText.trim(), AUTOMATIC_STRUCTURED_OUTPUT_TEXT_CHARS),
90774
+ recentTranscript: recent
90775
+ }
90776
+ };
90777
+ }
90778
+ function automaticStructuredOutputInstructions(schema) {
90779
+ const { title, description } = schema;
90780
+ const contract = [title, description].filter((part) => part !== undefined && part.trim().length > 0).join(": ");
90781
+ return [
90782
+ "Produce the machine-readable result this workflow stage was asked to return, as the registered result schema defines it.",
90783
+ "state.stageTask is the stage's task, state.finalAssistantText is the agent's final answer to it, and state.recentTranscript is the exchange that led to that answer.",
90784
+ "Report what the agent concluded. Do not redo the task, and do not invent facts the state does not contain.",
90785
+ ...contract.length === 0 ? [] : [`Result schema: ${contract}`]
90786
+ ].join(`
90787
+ `);
90788
+ }
90789
+ function failure3(code, fields, cause) {
90790
+ return {
90791
+ kind: "failed",
90792
+ error: new WorkflowStructuredOutputInferenceError(code, fields, cause === undefined ? undefined : { cause })
90793
+ };
90794
+ }
90795
+ async function runAutomaticStructuredOutput(input) {
90796
+ const { fields, signal } = input;
90797
+ const built = automaticStructuredOutputInput(input);
90798
+ if (built === undefined)
90799
+ return { kind: "skipped" };
90800
+ const { evidence, finalText } = built;
90801
+ let context;
90802
+ try {
90803
+ context = input.toolContext(fields.toolCallId, signal);
90804
+ } catch (error) {
90805
+ signal.throwIfAborted();
90806
+ return failure3("tool-context-unavailable", fields, error);
90807
+ }
90808
+ if (context === undefined)
90809
+ return failure3("tool-context-unavailable", fields);
90810
+ const params = {
90811
+ instructions: automaticStructuredOutputInstructions(input.schema),
90812
+ state: evidence
90813
+ };
90814
+ try {
90815
+ await input.tool.execute(fields.toolCallId, params, signal, undefined, context);
90816
+ } catch (error) {
90817
+ signal.throwIfAborted();
90818
+ return failure3("auto-inference-failed", fields, error);
90819
+ }
90820
+ return { kind: "captured", finalAssistantText: finalText };
90821
+ }
90822
+ function automaticInferenceExecutionFailure(error) {
90823
+ if (error.cause === undefined)
90824
+ return;
90825
+ const decision = findDecisionError2(error.cause);
90826
+ if (decision !== undefined)
90827
+ return isDecisionOutputError(decision) ? undefined : errorMessage4(error.cause);
90828
+ const detail = errorMessage4(error.cause);
90829
+ return isStructuredOutputContractFailure(detail) ? undefined : detail;
90830
+ }
90831
+ function automaticInferenceWarning(error) {
90832
+ const cause = error.cause;
90833
+ const code = typeof cause === "object" && cause !== null ? cause.code : undefined;
90834
+ const name = cause instanceof Error ? cause.name : undefined;
90835
+ const reason = name === undefined ? "" : ` Cause: ${name}${typeof code === "string" ? ` (${code})` : ""}.`;
90836
+ return `[structured-output] ${error.message}${reason}`;
90837
+ }
90838
+ var AUTOMATIC_STRUCTURED_OUTPUT_TRANSCRIPT_MESSAGES = 6, AUTOMATIC_STRUCTURED_OUTPUT_TEXT_CHARS = 16000;
90839
+ var init_stage_runner_structured_output_auto = __esm(() => {
90840
+ init_structured_output_errors();
90841
+ init_model_fallback();
90842
+ init_stage_runner_messages();
90843
+ init_stage_runner_structured_output();
90844
+ });
90845
+
90558
90846
  // dist/builtin/workflows/src/runs/foreground/stage-runner-context.ts
90559
90847
  import { createStructuredOutputCapture, runCallback as runCallback2 } from "@bastani/atomic";
90560
90848
  function createStageContext(opts) {
@@ -90562,7 +90850,8 @@ function createStageContext(opts) {
90562
90850
  const stageCwd = stageOptions?.cwd ?? stageOptions?.sessionManager?.getCwd() ?? agentSessionAdapterDefaultCwd(adapters.agentSession) ?? opts.defaultCwd ?? process.cwd();
90563
90851
  const structuredOutputCapture = stageOptions?.schema ? createStructuredOutputCapture() : undefined;
90564
90852
  const structuredOutputExecutionCapture = stageOptions?.schema ? {} : undefined;
90565
- const effectiveStageOptions = stageOptionsWithStructuredOutput(adapters.sessionStore === undefined || stageOptions?.sessionStore !== undefined || stageOptions?.sessionDir !== undefined || stageOptions?.sessionManager !== undefined ? stageOptions : { ...stageOptions, sessionStore: adapters.sessionStore }, structuredOutputCapture, structuredOutputExecutionCapture);
90853
+ const structuredOutputTool = stageOptions?.schema ? createStageStructuredOutputTool({ schema: stageOptions.schema, schemaTimeoutMs: stageOptions.schemaTimeoutMs }, structuredOutputCapture, structuredOutputExecutionCapture) : undefined;
90854
+ const effectiveStageOptions = stageOptionsWithStructuredOutput(adapters.sessionStore === undefined || stageOptions?.sessionStore !== undefined || stageOptions?.sessionDir !== undefined || stageOptions?.sessionManager !== undefined ? stageOptions : { ...stageOptions, sessionStore: adapters.sessionStore }, structuredOutputTool);
90566
90855
  const meta = {
90567
90856
  runId,
90568
90857
  stageId,
@@ -90582,6 +90871,23 @@ function createStageContext(opts) {
90582
90871
  let artifactClosed = false;
90583
90872
  let artifactText;
90584
90873
  let continuing = false;
90874
+ let automaticInferences = 0;
90875
+ let automaticArtifactText;
90876
+ let warnedInference = false;
90877
+ async function inferStructuredOutputAutomatically(stagePrompt) {
90878
+ automaticInferences += 1;
90879
+ return runAutomaticStructuredOutput({
90880
+ tool: structuredOutputTool,
90881
+ schema: stageOptions.schema,
90882
+ capture: structuredOutputCapture,
90883
+ stagePrompt,
90884
+ messages: controller.currentSession?.messages ?? [],
90885
+ promptStartIndex: controller.currentPromptStartIndex ?? 0,
90886
+ toolContext: (toolCallId, signal) => controller.stageToolContext(toolCallId, signal),
90887
+ signal: controller.stageCancellationSignal(),
90888
+ fields: { runId, stageId, stageName, toolCallId: `workflow-auto-structured-output-${automaticInferences}` }
90889
+ });
90890
+ }
90585
90891
  async function exportArtifact() {
90586
90892
  const text = assistantArtifactTextForGeneration(controller.outputGenerationMessages());
90587
90893
  if (text !== artifactText || lastFinalizedOutput === undefined) {
@@ -90641,6 +90947,7 @@ function createStageContext(opts) {
90641
90947
  if (structuredOutputCapture) {
90642
90948
  let structuredOutputError = STRUCTURED_OUTPUT_MISSING_ERROR;
90643
90949
  let executionFailure;
90950
+ let automaticInferenceFailure;
90644
90951
  while (!structuredOutputCapture.called) {
90645
90952
  let nextPrompt = promptText;
90646
90953
  let newSessionPrompt;
@@ -90649,12 +90956,25 @@ function createStageContext(opts) {
90649
90956
  while (!structuredOutputCapture.called) {
90650
90957
  controller.resetStructuredOutputToolError();
90651
90958
  await controller.promptWithFallback(nextPrompt, sdkOptions, undefined, newSessionPrompt, continuationText);
90959
+ if (structuredOutputCapture.called)
90960
+ break;
90961
+ const automatic = await inferStructuredOutputAutomatically(text);
90962
+ if (automatic.kind === "captured")
90963
+ automaticArtifactText = automatic.finalAssistantText;
90652
90964
  if (structuredOutputCapture.called)
90653
90965
  break;
90654
90966
  structuredOutputError = controller.structuredOutputFailureReason();
90655
90967
  executionFailure ??= controller.structuredOutputExecutionFailure();
90656
90968
  if (!isStructuredOutputContractFailure(structuredOutputError))
90657
90969
  executionFailure ??= structuredOutputError;
90970
+ if (automatic.kind === "failed") {
90971
+ automaticInferenceFailure = automatic.error;
90972
+ executionFailure ??= automaticInferenceExecutionFailure(automatic.error);
90973
+ if (automatic.error.code === "auto-inference-failed" && !warnedInference) {
90974
+ warnedInference = true;
90975
+ controller.recordStructuredOutputWarning(automaticInferenceWarning(automatic.error));
90976
+ }
90977
+ }
90658
90978
  if (correctiveAttempts >= STRUCTURED_OUTPUT_MAX_CORRECTIVE_PROMPTS)
90659
90979
  break;
90660
90980
  correctiveAttempts += 1;
@@ -90666,7 +90986,8 @@ ${nextPrompt}`;
90666
90986
  if (structuredOutputCapture.called)
90667
90987
  break;
90668
90988
  if (!await controller.failCandidateForStructuredOutputExhaustion(structuredOutputError)) {
90669
- throw executionFailure === undefined ? new WorkflowStructuredOutputContractError(structuredOutputError) : new Error(executionFailure);
90989
+ const failureOptions = automaticInferenceFailure === undefined ? undefined : { cause: automaticInferenceFailure };
90990
+ throw executionFailure === undefined ? new WorkflowStructuredOutputContractError(structuredOutputError, failureOptions) : new Error(executionFailure, failureOptions);
90670
90991
  }
90671
90992
  }
90672
90993
  const sessionMessages = controller.currentSession?.messages;
@@ -90674,7 +90995,7 @@ ${nextPrompt}`;
90674
90995
  if (executionSnapshot === undefined) {
90675
90996
  throw new Error("atomic-workflows: structured_output completed without an execution snapshot; the successful tool call could not be paired with its result.");
90676
90997
  }
90677
- const rawOutputText = hasOutputArtifact ? assistantArtifactTextForToolCall(sessionMessages ?? [], executionSnapshot.toolCallId) ?? "" : stringifyStructuredOutputValue(executionSnapshot.value);
90998
+ const rawOutputText = hasOutputArtifact ? automaticArtifactText ?? assistantArtifactTextForToolCall(sessionMessages ?? [], executionSnapshot.toolCallId) ?? "" : stringifyStructuredOutputValue(executionSnapshot.value);
90678
90999
  lastAssistantText = await finalizePromptOutput(rawOutputText, outputOptions, stageCwd, runId, sessionMessages);
90679
91000
  lastFinalizedOutput = lastAssistantText;
90680
91001
  lastFinalizedMessageCount = controller.currentSession?.messages.length;
@@ -90936,6 +91257,7 @@ var init_stage_runner_context = __esm(() => {
90936
91257
  init_stage_runner_output();
90937
91258
  init_stage_runner_session_options();
90938
91259
  init_stage_runner_structured_output();
91260
+ init_stage_runner_structured_output_auto();
90939
91261
  });
90940
91262
 
90941
91263
  // dist/builtin/workflows/src/runs/foreground/stage-runner.ts
@@ -98541,7 +98863,7 @@ import {
98541
98863
  resolveGitSync as resolveGitSync2,
98542
98864
  restoreRunWorktree
98543
98865
  } from "@bastani/atomic";
98544
- function failure3(error) {
98866
+ function failure4(error) {
98545
98867
  return error instanceof WorkerPlacementError ? serializeWorkerPlacementError(error) : { name: error.name, message: error.message };
98546
98868
  }
98547
98869
  function active(status) {
@@ -98662,7 +98984,7 @@ class WorkerHost {
98662
98984
  this.options = options;
98663
98985
  this.timer = setInterval(() => {
98664
98986
  this.polling ??= this.poll().catch((error) => {
98665
- this.lastDetach = failure3(error);
98987
+ this.lastDetach = failure4(error);
98666
98988
  }).finally(() => {
98667
98989
  this.polling = undefined;
98668
98990
  });
@@ -98708,7 +99030,7 @@ class WorkerHost {
98708
99030
  continue;
98709
99031
  this.satellites.delete(root);
98710
99032
  await satellite.coordinator.stopSatellite().catch((error) => {
98711
- this.lastDetach = failure3(error);
99033
+ this.lastDetach = failure4(error);
98712
99034
  });
98713
99035
  await satellite.coordinator.shutdown();
98714
99036
  }
@@ -98753,7 +99075,7 @@ class WorkerHost {
98753
99075
  satellite.yielding = true;
98754
99076
  this.yielded.set(root, now);
98755
99077
  satellite.attached.then(() => satellite.coordinator.drain()).catch((error) => {
98756
- this.lastDetach = failure3(error);
99078
+ this.lastDetach = failure4(error);
98757
99079
  }).finally(() => {
98758
99080
  satellite.detached = true;
98759
99081
  });
@@ -98798,15 +99120,15 @@ class WorkerHost {
98798
99120
  detached: (reason) => {
98799
99121
  satellite.detached = true;
98800
99122
  if (reason !== undefined)
98801
- this.lastDetach = failure3(reason);
99123
+ this.lastDetach = failure4(reason);
98802
99124
  },
98803
99125
  placementFailed: (error) => {
98804
- this.lastPlacementFailure = failure3(error);
99126
+ this.lastPlacementFailure = failure4(error);
98805
99127
  }
98806
99128
  }
98807
99129
  }).catch((error) => {
98808
99130
  satellite.detached = true;
98809
- this.lastDetach = failure3(error);
99131
+ this.lastDetach = failure4(error);
98810
99132
  });
98811
99133
  this.satellites.set(root.root, satellite);
98812
99134
  }
@@ -98838,7 +99160,7 @@ class WorkerHost {
98838
99160
  else if (this.draining && !this.stoppingNow)
98839
99161
  for (const satellite of this.satellites.values())
98840
99162
  satellite.coordinator.stopSatellite().catch((error) => {
98841
- this.lastDetach = failure3(error);
99163
+ this.lastDetach = failure4(error);
98842
99164
  });
98843
99165
  this.stoppingNow = true;
98844
99166
  return this.stopping;
@@ -99039,6 +99361,7 @@ __export(exports_sdk_surface, {
99039
99361
  WorkflowAdmissionError: () => WorkflowAdmissionError,
99040
99362
  WorkflowGitRequiredError: () => WorkflowGitRequiredError,
99041
99363
  WorkflowInfrastructureError: () => WorkflowInfrastructureError,
99364
+ WorkflowStructuredOutputInferenceError: () => WorkflowStructuredOutputInferenceError,
99042
99365
  WorkspaceBindingError: () => WorkspaceBindingError3,
99043
99366
  WorkspaceCollectionError: () => WorkspaceCollectionError,
99044
99367
  WorkspaceConfigError: () => WorkspaceConfigError,
@@ -99064,7 +99387,8 @@ __export(exports_sdk_surface, {
99064
99387
  deserializeRunEvictionError: () => deserializeRunEvictionError,
99065
99388
  deserializeStageWaitError: () => deserializeStageWaitError,
99066
99389
  deserializeSubscriptionError: () => deserializeSubscriptionError2,
99067
- findDecisionError: () => findDecisionError2,
99390
+ deserializeWorkflowStructuredOutputInferenceError: () => deserializeWorkflowStructuredOutputInferenceError,
99391
+ findDecisionError: () => findDecisionError3,
99068
99392
  findForkError: () => findForkError,
99069
99393
  findLocalWorkerPoolError: () => findLocalWorkerPoolError,
99070
99394
  findPossibleStagePredictionError: () => findPossibleStagePredictionError,
@@ -99072,6 +99396,7 @@ __export(exports_sdk_surface, {
99072
99396
  findStageWaitError: () => findStageWaitError,
99073
99397
  findSubscriptionError: () => findSubscriptionError,
99074
99398
  findWorkflowAdmissionError: () => findWorkflowAdmissionError,
99399
+ findWorkflowStructuredOutputInferenceError: () => findWorkflowStructuredOutputInferenceError,
99075
99400
  findWorkspaceError: () => findWorkspaceError,
99076
99401
  forkRun: () => forkRun,
99077
99402
  githubChecks: () => githubChecks,
@@ -99082,7 +99407,7 @@ __export(exports_sdk_surface, {
99082
99407
  isDecisionConfigError: () => isDecisionConfigError,
99083
99408
  isDecisionError: () => isDecisionError,
99084
99409
  isDecisionModelUnavailableError: () => isDecisionModelUnavailableError2,
99085
- isDecisionOutputError: () => isDecisionOutputError,
99410
+ isDecisionOutputError: () => isDecisionOutputError2,
99086
99411
  isDecisionProviderError: () => isDecisionProviderError,
99087
99412
  isDecisionRequestError: () => isDecisionRequestError,
99088
99413
  isDecisionTimeoutError: () => isDecisionTimeoutError,
@@ -99165,6 +99490,7 @@ __export(exports_sdk_surface, {
99165
99490
  isWorkflowAdmissionError: () => isWorkflowAdmissionError,
99166
99491
  isWorkflowGitRequiredError: () => isWorkflowGitRequiredError,
99167
99492
  isWorkflowInfrastructureError: () => isWorkflowInfrastructureError,
99493
+ isWorkflowStructuredOutputInferenceError: () => isWorkflowStructuredOutputInferenceError,
99168
99494
  isWorkspace: () => isWorkspace2,
99169
99495
  isWorkspaceBindingError: () => isWorkspaceBindingError,
99170
99496
  isWorkspaceCollectionError: () => isWorkspaceCollectionError,
@@ -99236,7 +99562,7 @@ import {
99236
99562
  decide,
99237
99563
  deserializeSubscriptionError as deserializeSubscriptionError2,
99238
99564
  EventSourceError,
99239
- findDecisionError as findDecisionError2,
99565
+ findDecisionError as findDecisionError3,
99240
99566
  findSubscriptionError,
99241
99567
  findWorkspaceError,
99242
99568
  GitUnavailableError,
@@ -99247,7 +99573,7 @@ import {
99247
99573
  isDecisionConfigError,
99248
99574
  isDecisionError,
99249
99575
  isDecisionModelUnavailableError as isDecisionModelUnavailableError2,
99250
- isDecisionOutputError,
99576
+ isDecisionOutputError as isDecisionOutputError2,
99251
99577
  isDecisionProviderError,
99252
99578
  isDecisionRequestError,
99253
99579
  isDecisionTimeoutError,
@@ -99341,6 +99667,7 @@ var init_sdk_surface = __esm(() => {
99341
99667
  init_stage_wait_errors();
99342
99668
  init_stage_wake();
99343
99669
  init_store();
99670
+ init_structured_output_errors();
99344
99671
  init_types2();
99345
99672
  init_worker_pool_errors();
99346
99673
  init_workflow_git_required_error();
@@ -116293,17 +116620,17 @@ async function openCompletedDurableWorkflow(workflowId, deps, catalog) {
116293
116620
  const selectedStore = await stageSessionStore({ sessionStore: deps.sessionStore ?? deps.adapters?.sessionStore, cwd: deps.cwd }, deps.defaultSessionDir);
116294
116621
  const resolved = await resolveCompletedWorkflow(workflowId, deps.durableBackend, catalog, selectedStore);
116295
116622
  if (resolved.kind === "not_found") {
116296
- return failure4("not_found", `No completed durable workflow found for id: ${workflowId}`);
116623
+ return failure5("not_found", `No completed durable workflow found for id: ${workflowId}`);
116297
116624
  }
116298
116625
  if (resolved.kind === "malformed") {
116299
- return failure4("malformed", resolved.message);
116626
+ return failure5("malformed", resolved.message);
116300
116627
  }
116301
116628
  if (resolved.kind === "stale") {
116302
- return failure4("stale", `Completed workflow ${resolved.entry.workflowId} is stale or missing durable checkpoint/session data and cannot be opened.`);
116629
+ return failure5("stale", `Completed workflow ${resolved.entry.workflowId} is stale or missing durable checkpoint/session data and cannot be opened.`);
116303
116630
  }
116304
116631
  const existing = deps.store.run(resolved.snapshot.id);
116305
116632
  if (existing !== undefined && existing.status !== "completed") {
116306
- return failure4("active", `Workflow ${resolved.snapshot.id} is already active in this session; attach with /workflow connect ${resolved.snapshot.id} instead.`);
116633
+ return failure5("active", `Workflow ${resolved.snapshot.id} is already active in this session; attach with /workflow connect ${resolved.snapshot.id} instead.`);
116307
116634
  }
116308
116635
  const snapshots = await completedWorkflowRunSnapshots(deps.durableBackend, resolved.entry, selectedStore);
116309
116636
  const snapshot = snapshots.find((run) => run.id === resolved.snapshot.id) ?? resolved.snapshot;
@@ -116324,7 +116651,7 @@ async function openCompletedDurableWorkflow(workflowId, deps, catalog) {
116324
116651
  message: `Opened completed durable workflow "${snapshot.name}" (${snapshot.id}) for read-only inspection${hasReopenableStage ? " and follow-up chat" : ""}.`
116325
116652
  };
116326
116653
  }
116327
- function failure4(reason, message) {
116654
+ function failure5(reason, message) {
116328
116655
  return { ok: false, reason, message };
116329
116656
  }
116330
116657
  function registerCompletedChatHandles(snapshot, deps, sessionStore) {
@@ -117280,7 +117607,7 @@ init_possible_stage_prediction();
117280
117607
  init_possible_stage_prediction_errors();
117281
117608
  init_store_internal();
117282
117609
  import {
117283
- findDecisionError as findDecisionError3,
117610
+ findDecisionError as findDecisionError4,
117284
117611
  isDecisionModelUnavailableError as isDecisionModelUnavailableError3,
117285
117612
  isDecisionTimeoutError as isDecisionTimeoutError2
117286
117613
  } from "@bastani/atomic";
@@ -117499,7 +117826,7 @@ class StagePredictor {
117499
117826
  }
117500
117827
  }
117501
117828
  function decisionModelGivesNoProbabilities2(error) {
117502
- const decision = findDecisionError3(error);
117829
+ const decision = findDecisionError4(error);
117503
117830
  return isDecisionModelUnavailableError3(decision) && decision.reason === "no-probabilities";
117504
117831
  }
117505
117832
  function stageDecisionPortFromModels(models) {
@@ -122111,7 +122438,7 @@ function errorOptions(runId, cause, failedRuns) {
122111
122438
  ...failedRuns === undefined ? {} : { failedRuns }
122112
122439
  };
122113
122440
  }
122114
- function failure5(code, message, runId, cause, failedRuns) {
122441
+ function failure6(code, message, runId, cause, failedRuns) {
122115
122442
  const options = errorOptions(runId, cause, failedRuns);
122116
122443
  switch (code) {
122117
122444
  case "run_not_found":
@@ -122134,7 +122461,7 @@ function failure5(code, message, runId, cause, failedRuns) {
122134
122461
  }
122135
122462
  function translateThrown(error, runId) {
122136
122463
  const code = classifyControlError(error);
122137
- return code === "owned_elsewhere" || code === "storage_unavailable" ? failure5(code, error.message, runId, error) : error;
122464
+ return code === "owned_elsewhere" || code === "storage_unavailable" ? failure6(code, error.message, runId, error) : error;
122138
122465
  }
122139
122466
  function controlStatus(status, runId) {
122140
122467
  switch (status) {
@@ -122146,15 +122473,15 @@ function controlStatus(status, runId) {
122146
122473
  case "cancelled":
122147
122474
  return status;
122148
122475
  default:
122149
- throw failure5("control_failed", `Unexpected workflow control status: ${status}`, runId);
122476
+ throw failure6("control_failed", `Unexpected workflow control status: ${status}`, runId);
122150
122477
  }
122151
122478
  }
122152
122479
  function controlOutcome(result) {
122153
122480
  if (result.action !== "pause" && result.action !== "quit" && result.action !== "resume") {
122154
- throw failure5("control_failed", `Unexpected workflow result: ${result.action}`, undefined);
122481
+ throw failure6("control_failed", `Unexpected workflow result: ${result.action}`, undefined);
122155
122482
  }
122156
122483
  if ("code" in result && result.code !== undefined) {
122157
- throw failure5(result.code, result.message, result.runId, "failure" in result ? rehydrateJournalStoreError2(result.failure) : undefined, "failedRuns" in result ? result.failedRuns : undefined);
122484
+ throw failure6(result.code, result.message, result.runId, "failure" in result ? rehydrateJournalStoreError2(result.failure) : undefined, "failedRuns" in result ? result.failedRuns : undefined);
122158
122485
  }
122159
122486
  return { ...result, status: controlStatus(result.status, result.runId) };
122160
122487
  }
@@ -122164,7 +122491,7 @@ function rejectUnknownRunPrefix(store, runId) {
122164
122491
  return;
122165
122492
  const resolution = resolveRunIdTarget(target, store.runs().map((run) => run.id));
122166
122493
  if (resolution.kind === "not_found") {
122167
- throw failure5("run_not_found", `Run not found: ${target} (no run in this session has that prefix; pass the full run id for a run recorded elsewhere).`, runId);
122494
+ throw failure6("run_not_found", `Run not found: ${target} (no run in this session has that prefix; pass the full run id for a run recorded elsewhere).`, runId);
122168
122495
  }
122169
122496
  }
122170
122497
  function createSessionRunControl(host) {
@@ -122185,7 +122512,7 @@ function createSessionRunControl(host) {
122185
122512
  ...filter?.status === undefined ? {} : { statusFilter: filter.status }
122186
122513
  });
122187
122514
  if (result.action !== "status")
122188
- throw failure5("control_failed", `Unexpected workflow result: ${result.action}`, undefined);
122515
+ throw failure6("control_failed", `Unexpected workflow result: ${result.action}`, undefined);
122189
122516
  const catalog = filter?.includeDurable ? await host.catalog?.() : undefined;
122190
122517
  const cwd = host.context()?.cwd;
122191
122518
  const canonicalPaths = new Map;
@@ -122242,9 +122569,9 @@ function createSessionRunControl(host) {
122242
122569
  async getRun(runId) {
122243
122570
  const result = await request({ action: "status", runId });
122244
122571
  if (result.action !== "statusDetail")
122245
- throw failure5("control_failed", `Unexpected workflow result: ${result.action}`, runId);
122572
+ throw failure6("control_failed", `Unexpected workflow result: ${result.action}`, runId);
122246
122573
  if ("error" in result)
122247
- throw failure5("run_not_found", result.error, runId);
122574
+ throw failure6("run_not_found", result.error, runId);
122248
122575
  return result.detail;
122249
122576
  },
122250
122577
  async getStages(runId, filter) {
@@ -122254,9 +122581,9 @@ function createSessionRunControl(host) {
122254
122581
  ...filter?.status === undefined ? {} : { statusFilter: filter.status }
122255
122582
  });
122256
122583
  if (result.action !== "stages")
122257
- throw failure5("control_failed", `Unexpected workflow result: ${result.action}`, runId);
122584
+ throw failure6("control_failed", `Unexpected workflow result: ${result.action}`, runId);
122258
122585
  if (result.error !== undefined)
122259
- throw failure5("run_not_found", result.error, runId);
122586
+ throw failure6("run_not_found", result.error, runId);
122260
122587
  return result.stages;
122261
122588
  },
122262
122589
  async pause(runId, options) {
@@ -122279,7 +122606,7 @@ function createSessionRunControl(host) {
122279
122606
  } catch (error) {
122280
122607
  const cause = error instanceof Error ? error : new Error(String(error));
122281
122608
  const code = error instanceof JournalError ? "storage_unavailable" : classifyControlError(error);
122282
- throw failure5(code, `Run ${runId} did not settle cleanly: ${describeErrorWithCauses(error)}`, runId, cause);
122609
+ throw failure6(code, `Run ${runId} did not settle cleanly: ${describeErrorWithCauses(error)}`, runId, cause);
122283
122610
  }
122284
122611
  },
122285
122612
  async resume(runId, options) {