@bastani/atomic 0.9.73-alpha.1 → 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 (194) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/dist/builtin/intercom/CHANGELOG.md +10 -0
  3. package/dist/builtin/intercom/package.json +1 -1
  4. package/dist/builtin/mcp/package.json +1 -1
  5. package/dist/builtin/subagents/package.json +1 -1
  6. package/dist/builtin/web-access/package.json +1 -1
  7. package/dist/builtin/workflows/CHANGELOG.md +16 -0
  8. package/dist/builtin/workflows/README.md +2 -2
  9. package/dist/builtin/workflows/builtin/adversarial-verification.js +2 -2
  10. package/dist/builtin/workflows/builtin/{chunk-2377r57g.js → chunk-8kdrnrpa.js} +1 -1
  11. package/dist/builtin/workflows/builtin/{chunk-t8y25z1j.js → chunk-8ycbc76t.js} +1 -1
  12. package/dist/builtin/workflows/builtin/{chunk-vbrmytm5.js → chunk-a4fdm2cw.js} +1 -1
  13. package/dist/builtin/workflows/builtin/{chunk-9pjdp2td.js → chunk-d5cxskkp.js} +3 -3
  14. package/dist/builtin/workflows/builtin/{chunk-tpsw128z.js → chunk-d9pz64yp.js} +3 -3
  15. package/dist/builtin/workflows/builtin/{chunk-z0d03ktm.js → chunk-gp0s6m45.js} +1 -1
  16. package/dist/builtin/workflows/builtin/{chunk-4kygv34g.js → chunk-m8eg152f.js} +1 -1
  17. package/dist/builtin/workflows/builtin/{chunk-mswg7kc7.js → chunk-r39ypw6b.js} +1 -1
  18. package/dist/builtin/workflows/builtin/{chunk-q7dry6km.js → chunk-va2h64a6.js} +3 -3
  19. package/dist/builtin/workflows/builtin/generate-and-filter.js +2 -2
  20. package/dist/builtin/workflows/builtin/goal.js +4 -4
  21. package/dist/builtin/workflows/builtin/index.js +9 -9
  22. package/dist/builtin/workflows/builtin/loop-until-done.js +2 -2
  23. package/dist/builtin/workflows/builtin/ralph.js +4 -4
  24. package/dist/builtin/workflows/builtin/tournament.js +2 -2
  25. package/dist/builtin/workflows/package.json +1 -1
  26. package/dist/builtin/workflows/src/authoring.d.ts +2 -0
  27. package/dist/builtin/workflows/src/extension/index.bundle.mjs +403 -76
  28. package/dist/builtin/workflows/src/extension/local-worker-entry.mjs +387 -60
  29. package/dist/builtin/workflows/src/index.js +393 -62
  30. package/dist/builtin/workflows/src/local-worker-entry.mjs +387 -60
  31. package/dist/builtin/workflows/src/shared/serializable-error-families.d.ts +1 -0
  32. package/dist/builtin/workflows/src/shared/structured-output-errors.d.ts +50 -0
  33. package/dist/config.d.ts +2 -0
  34. package/dist/config.d.ts.map +1 -1
  35. package/dist/config.js +4 -0
  36. package/dist/config.js.map +1 -1
  37. package/dist/core/agent-session-background-compaction.d.ts.map +1 -1
  38. package/dist/core/agent-session-background-compaction.js +2 -1
  39. package/dist/core/agent-session-background-compaction.js.map +1 -1
  40. package/dist/core/agent-session-compaction.d.ts.map +1 -1
  41. package/dist/core/agent-session-compaction.js +98 -4
  42. package/dist/core/agent-session-compaction.js.map +1 -1
  43. package/dist/core/agent-session-detached-tools.d.ts +20 -5
  44. package/dist/core/agent-session-detached-tools.d.ts.map +1 -1
  45. package/dist/core/agent-session-detached-tools.js +97 -21
  46. package/dist/core/agent-session-detached-tools.js.map +1 -1
  47. package/dist/core/agent-session-message-queue.d.ts.map +1 -1
  48. package/dist/core/agent-session-message-queue.js +2 -1
  49. package/dist/core/agent-session-message-queue.js.map +1 -1
  50. package/dist/core/agent-session-methods.d.ts +3 -1
  51. package/dist/core/agent-session-methods.d.ts.map +1 -1
  52. package/dist/core/agent-session-methods.js.map +1 -1
  53. package/dist/core/agent-session-persistent-custom-messages.d.ts.map +1 -1
  54. package/dist/core/agent-session-persistent-custom-messages.js +12 -4
  55. package/dist/core/agent-session-persistent-custom-messages.js.map +1 -1
  56. package/dist/core/agent-session-prompt.d.ts.map +1 -1
  57. package/dist/core/agent-session-prompt.js +33 -0
  58. package/dist/core/agent-session-prompt.js.map +1 -1
  59. package/dist/core/compaction/background-compaction.d.ts +11 -5
  60. package/dist/core/compaction/background-compaction.d.ts.map +1 -1
  61. package/dist/core/compaction/background-compaction.js +19 -10
  62. package/dist/core/compaction/background-compaction.js.map +1 -1
  63. package/dist/core/compaction/compaction-boundary.d.ts +10 -0
  64. package/dist/core/compaction/compaction-boundary.d.ts.map +1 -1
  65. package/dist/core/compaction/compaction-boundary.js +30 -2
  66. package/dist/core/compaction/compaction-boundary.js.map +1 -1
  67. package/dist/core/compaction/compaction-runner.d.ts +7 -0
  68. package/dist/core/compaction/compaction-runner.d.ts.map +1 -1
  69. package/dist/core/compaction/compaction-runner.js +13 -5
  70. package/dist/core/compaction/compaction-runner.js.map +1 -1
  71. package/dist/core/compaction/compaction-types.d.ts +1 -1
  72. package/dist/core/compaction/compaction-types.js +1 -1
  73. package/dist/core/compaction/compaction-types.js.map +1 -1
  74. package/dist/core/compaction/deleted-ranges.d.ts +17 -2
  75. package/dist/core/compaction/deleted-ranges.d.ts.map +1 -1
  76. package/dist/core/compaction/deleted-ranges.js +44 -5
  77. package/dist/core/compaction/deleted-ranges.js.map +1 -1
  78. package/dist/core/compaction/history-recall.d.ts +32 -0
  79. package/dist/core/compaction/history-recall.d.ts.map +1 -0
  80. package/dist/core/compaction/history-recall.js +275 -0
  81. package/dist/core/compaction/history-recall.js.map +1 -0
  82. package/dist/core/compaction/index.d.ts +2 -0
  83. package/dist/core/compaction/index.d.ts.map +1 -1
  84. package/dist/core/compaction/index.js +2 -0
  85. package/dist/core/compaction/index.js.map +1 -1
  86. package/dist/core/compaction/pi-summary-fallback.d.ts.map +1 -1
  87. package/dist/core/compaction/pi-summary-fallback.js +1 -0
  88. package/dist/core/compaction/pi-summary-fallback.js.map +1 -1
  89. package/dist/core/compaction/planner-outcome.d.ts +14 -0
  90. package/dist/core/compaction/planner-outcome.d.ts.map +1 -1
  91. package/dist/core/compaction/planner-outcome.js +8 -0
  92. package/dist/core/compaction/planner-outcome.js.map +1 -1
  93. package/dist/core/compaction/range-planner-diagnostics.d.ts +35 -10
  94. package/dist/core/compaction/range-planner-diagnostics.d.ts.map +1 -1
  95. package/dist/core/compaction/range-planner-diagnostics.js +67 -24
  96. package/dist/core/compaction/range-planner-diagnostics.js.map +1 -1
  97. package/dist/core/compaction/range-planner.d.ts +7 -4
  98. package/dist/core/compaction/range-planner.d.ts.map +1 -1
  99. package/dist/core/compaction/range-planner.js +43 -19
  100. package/dist/core/compaction/range-planner.js.map +1 -1
  101. package/dist/core/compaction/refusal-recovery.d.ts +27 -0
  102. package/dist/core/compaction/refusal-recovery.d.ts.map +1 -0
  103. package/dist/core/compaction/refusal-recovery.js +65 -0
  104. package/dist/core/compaction/refusal-recovery.js.map +1 -0
  105. package/dist/core/compaction/region-trimming.d.ts +23 -0
  106. package/dist/core/compaction/region-trimming.d.ts.map +1 -1
  107. package/dist/core/compaction/region-trimming.js +59 -15
  108. package/dist/core/compaction/region-trimming.js.map +1 -1
  109. package/dist/core/compaction/structured-compaction-input.d.ts +19 -1
  110. package/dist/core/compaction/structured-compaction-input.d.ts.map +1 -1
  111. package/dist/core/compaction/structured-compaction-input.js +30 -17
  112. package/dist/core/compaction/structured-compaction-input.js.map +1 -1
  113. package/dist/core/compaction/transcript-serialization.d.ts +9 -3
  114. package/dist/core/compaction/transcript-serialization.d.ts.map +1 -1
  115. package/dist/core/compaction/transcript-serialization.js +18 -10
  116. package/dist/core/compaction/transcript-serialization.js.map +1 -1
  117. package/dist/core/messages.d.ts +5 -1
  118. package/dist/core/messages.d.ts.map +1 -1
  119. package/dist/core/messages.js +21 -3
  120. package/dist/core/messages.js.map +1 -1
  121. package/dist/core/session-manager-core.js +1 -1
  122. package/dist/core/session-manager-core.js.map +1 -1
  123. package/dist/core/session-manager-history.d.ts +1 -1
  124. package/dist/core/session-manager-history.d.ts.map +1 -1
  125. package/dist/core/session-manager-history.js +2 -5
  126. package/dist/core/session-manager-history.js.map +1 -1
  127. package/dist/core/settings-defaults.d.ts +2 -0
  128. package/dist/core/settings-defaults.d.ts.map +1 -1
  129. package/dist/core/settings-defaults.js +2 -0
  130. package/dist/core/settings-defaults.js.map +1 -1
  131. package/dist/core/settings-manager-basic-accessors.d.ts +2 -0
  132. package/dist/core/settings-manager-basic-accessors.d.ts.map +1 -1
  133. package/dist/core/settings-manager-basic-accessors.js +3 -0
  134. package/dist/core/settings-manager-basic-accessors.js.map +1 -1
  135. package/dist/core/settings-schema.d.ts +2 -0
  136. package/dist/core/settings-schema.d.ts.map +1 -1
  137. package/dist/core/settings-schema.js +4 -0
  138. package/dist/core/settings-schema.js.map +1 -1
  139. package/dist/core/storage/session/conformance.d.ts.map +1 -1
  140. package/dist/core/storage/session/conformance.js +12 -0
  141. package/dist/core/storage/session/conformance.js.map +1 -1
  142. package/dist/core/storage/session/jsonl-session-store.d.ts.map +1 -1
  143. package/dist/core/storage/session/jsonl-session-store.js +3 -0
  144. package/dist/core/storage/session/jsonl-session-store.js.map +1 -1
  145. package/dist/core/storage/session/legacy-session-store.d.ts.map +1 -1
  146. package/dist/core/storage/session/legacy-session-store.js +3 -0
  147. package/dist/core/storage/session/legacy-session-store.js.map +1 -1
  148. package/dist/core/storage/session/memory-session-store.d.ts.map +1 -1
  149. package/dist/core/storage/session/memory-session-store.js +3 -0
  150. package/dist/core/storage/session/memory-session-store.js.map +1 -1
  151. package/dist/core/storage/session/sql-session-store.d.ts.map +1 -1
  152. package/dist/core/storage/session/sql-session-store.js +12 -3
  153. package/dist/core/storage/session/sql-session-store.js.map +1 -1
  154. package/dist/core/storage/session/types.d.ts +3 -0
  155. package/dist/core/storage/session/types.d.ts.map +1 -1
  156. package/dist/core/storage/session/types.js +3 -0
  157. package/dist/core/storage/session/types.js.map +1 -1
  158. package/dist/core/tools/history-protocol.d.ts +3 -0
  159. package/dist/core/tools/history-protocol.d.ts.map +1 -1
  160. package/dist/core/tools/history-protocol.js +7 -87
  161. package/dist/core/tools/history-protocol.js.map +1 -1
  162. package/dist/core/tools/history-transcript.d.ts +24 -0
  163. package/dist/core/tools/history-transcript.d.ts.map +1 -0
  164. package/dist/core/tools/history-transcript.js +110 -0
  165. package/dist/core/tools/history-transcript.js.map +1 -0
  166. package/dist/index.d.ts +1 -1
  167. package/dist/index.d.ts.map +1 -1
  168. package/dist/index.js.map +1 -1
  169. package/dist/main-session.d.ts.map +1 -1
  170. package/dist/main-session.js +21 -5
  171. package/dist/main-session.js.map +1 -1
  172. package/dist/modes/interactive/components/compaction-boundary-message.d.ts.map +1 -1
  173. package/dist/modes/interactive/components/compaction-boundary-message.js +7 -3
  174. package/dist/modes/interactive/components/compaction-boundary-message.js.map +1 -1
  175. package/dist/modes/interactive/interactive-render-chat.js +2 -2
  176. package/dist/modes/interactive/interactive-render-chat.js.map +1 -1
  177. package/dist/session-id-target.d.ts +1 -0
  178. package/dist/session-id-target.d.ts.map +1 -1
  179. package/dist/session-id-target.js +3 -0
  180. package/dist/session-id-target.js.map +1 -1
  181. package/docs/compaction/reference.md +3 -2
  182. package/docs/compaction.md +35 -7
  183. package/docs/development.md +1 -1
  184. package/docs/sdk/reference.md +6 -5
  185. package/docs/sessions.md +3 -3
  186. package/docs/settings.md +3 -0
  187. package/docs/storage.md +2 -0
  188. package/docs/workflows/api-reference.md +15 -3
  189. package/docs/workflows/authoring.md +2 -2
  190. package/docs/workflows/operations.md +1 -0
  191. package/docs/workflows/reliable-design.md +1 -1
  192. package/npm-shrinkwrap.json +32 -32
  193. package/package.json +3 -3
  194. package/schemas/settings.schema.json +5 -0
@@ -9324,6 +9324,10 @@ function stageSessionExtensionRunner(current) {
9324
9324
  }
9325
9325
  return;
9326
9326
  }
9327
+ function stageSessionToolContext(session, toolCallId, signal) {
9328
+ const runner = session?.extensionRunner;
9329
+ return typeof runner?.createToolContext === "function" ? runner.createToolContext(toolCallId, signal) : undefined;
9330
+ }
9327
9331
  function shutdownStageSession(current) {
9328
9332
  if (!current)
9329
9333
  return Promise.resolve();
@@ -13520,7 +13524,7 @@ async function createTestAgentSession(_options) {
13520
13524
  compactedText: "[User]: retained",
13521
13525
  firstKeptEntryId: "kept",
13522
13526
  tokensBefore: 0,
13523
- promptVersion: 5,
13527
+ promptVersion: 6,
13524
13528
  parameters: { compression_ratio: 0.5, preserve_recent: 2, query: "auto-detected" },
13525
13529
  rung: "planned",
13526
13530
  stats: {
@@ -20206,6 +20210,82 @@ var init_run_eviction_errors = __esm(() => {
20206
20210
  };
20207
20211
  });
20208
20212
 
20213
+ // dist/builtin/workflows/src/shared/structured-output-errors.ts
20214
+ function isWorkflowStructuredOutputInferenceError(error) {
20215
+ return error instanceof WorkflowStructuredOutputInferenceError || hasIdentity(error, NAMES, CODES2);
20216
+ }
20217
+ function findWorkflowStructuredOutputInferenceError(error) {
20218
+ return causeChain(error).find(isWorkflowStructuredOutputInferenceError);
20219
+ }
20220
+ function deserializeWorkflowStructuredOutputInferenceError(serialized, cause) {
20221
+ if (!CODES2.has(serialized.code))
20222
+ return;
20223
+ const rebuilt = cause ?? (serialized.cause === undefined ? undefined : deserializeCause3(serialized.cause, 0));
20224
+ const error = new WorkflowStructuredOutputInferenceError(serialized.code, serialized.fields, rebuilt === undefined ? undefined : { cause: rebuilt });
20225
+ Object.defineProperty(error, "message", { value: serialized.message });
20226
+ return error;
20227
+ }
20228
+ function serializeCause5(cause, depth) {
20229
+ if (!(cause instanceof Error) || depth >= MAX_CAUSE_DEPTH2)
20230
+ return { name: "Error", message: cause instanceof Error ? cause.message : String(cause) };
20231
+ const code = cause.code;
20232
+ return {
20233
+ name: cause.name,
20234
+ message: cause.message,
20235
+ ...typeof code === "string" ? { code } : {},
20236
+ ...cause.cause === undefined ? {} : { cause: serializeCause5(cause.cause, depth + 1) }
20237
+ };
20238
+ }
20239
+ function deserializeCause3(cause, depth) {
20240
+ const nested = cause.cause === undefined || depth >= MAX_CAUSE_DEPTH2 ? undefined : deserializeCause3(cause.cause, depth + 1);
20241
+ const error = new Error(cause.message, nested === undefined ? undefined : { cause: nested });
20242
+ error.name = cause.name;
20243
+ if (cause.code !== undefined)
20244
+ Object.assign(error, { code: cause.code });
20245
+ return error;
20246
+ }
20247
+ var NAME = "WorkflowStructuredOutputInferenceError", CODES2, NAMES, SUBJECTS, HINTS3, WorkflowStructuredOutputInferenceError;
20248
+ var init_structured_output_errors = __esm(() => {
20249
+ CODES2 = new Set([
20250
+ "auto-inference-failed",
20251
+ "tool-context-unavailable"
20252
+ ]);
20253
+ NAMES = new Set([NAME]);
20254
+ SUBJECTS = {
20255
+ "auto-inference-failed": "The automatic structured_output inference failed",
20256
+ "tool-context-unavailable": "The automatic structured_output inference could not start"
20257
+ };
20258
+ HINTS3 = {
20259
+ "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.",
20260
+ "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."
20261
+ };
20262
+ WorkflowStructuredOutputInferenceError = class WorkflowStructuredOutputInferenceError extends Error {
20263
+ name = NAME;
20264
+ code;
20265
+ hint;
20266
+ retryable = false;
20267
+ fields;
20268
+ constructor(code, fields, options) {
20269
+ const hint = HINTS3[code];
20270
+ super(failureMessage(SUBJECTS[code], `stage "${fields.stageName}"`, code, hint), options);
20271
+ this.code = code;
20272
+ this.hint = hint;
20273
+ this.fields = fields;
20274
+ }
20275
+ toJSON() {
20276
+ return {
20277
+ name: this.name,
20278
+ code: this.code,
20279
+ message: this.message,
20280
+ hint: this.hint,
20281
+ retryable: this.retryable,
20282
+ fields: this.fields,
20283
+ ...this.cause === undefined ? {} : { cause: serializeCause5(this.cause, 0) }
20284
+ };
20285
+ }
20286
+ };
20287
+ });
20288
+
20209
20289
  // dist/builtin/workflows/src/shared/serializable-error-families.ts
20210
20290
  import {
20211
20291
  AgentRehydrateError,
@@ -20298,6 +20378,7 @@ var SERIALIZABLE_ERROR_FAMILIES, FAMILY_NAMES4;
20298
20378
  var init_serializable_error_families = __esm(() => {
20299
20379
  init_run_eviction_errors();
20300
20380
  init_stage_wait_errors();
20381
+ init_structured_output_errors();
20301
20382
  init_workflow_git_required_error();
20302
20383
  SERIALIZABLE_ERROR_FAMILIES = {
20303
20384
  "stage-wait": family({
@@ -20427,6 +20508,11 @@ var init_serializable_error_families = __esm(() => {
20427
20508
  return form;
20428
20509
  },
20429
20510
  rehydrate: rehydrateResumeError
20511
+ }),
20512
+ "structured-output": family({
20513
+ is: instanceOf(WorkflowStructuredOutputInferenceError),
20514
+ serialize: (error) => error.toJSON(),
20515
+ rehydrate: deserializeWorkflowStructuredOutputInferenceError
20430
20516
  })
20431
20517
  };
20432
20518
  FAMILY_NAMES4 = Object.keys(SERIALIZABLE_ERROR_FAMILIES);
@@ -63953,7 +64039,7 @@ Preserve every confirmed veto or blocking finding in remaining_work verbatim. Ex
63953
64039
  </decision_rules>
63954
64040
 
63955
64041
  <output_format>
63956
- 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}
64042
+ 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}
63957
64043
  ${GROUNDED_REPORTING}
63958
64044
  </output_format>
63959
64045
 
@@ -64315,7 +64401,7 @@ async function warm_first_fan_out(ctx, steps, prefixKeyOf, options = {}) {
64315
64401
  throw warmFailure;
64316
64402
  return steps.map((_, index) => resultsByIndex.get(index)).filter((result) => result !== undefined);
64317
64403
  }
64318
- 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.";
64404
+ 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.";
64319
64405
  var init_verification_prompts = __esm(() => {
64320
64406
  init_verification_criteria();
64321
64407
  MAX_INLINE_CANDIDATE_BYTES = 32 * 1024;
@@ -64408,7 +64494,7 @@ function stageName(cell, reaskWave) {
64408
64494
  return reaskWave === 0 ? cell.name : `${cell.name}-reask-${reaskWave}`;
64409
64495
  }
64410
64496
  function verifierOutputFormat(criterionId) {
64411
- 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).`;
64497
+ return `Report criterion_id (set to ${criterionId}), score (1–20), evidence (string array), and findings containing finding and severity (veto, blocking, or note).`;
64412
64498
  }
64413
64499
  function scoreStep(cell, reaskWave, head, criteriaPath) {
64414
64500
  const promptHead = {
@@ -65048,7 +65134,7 @@ Stop after every candidate is shortlisted once or recorded as discarded.
65048
65134
  </stop_rules>
65049
65135
 
65050
65136
  <output_format>
65051
- Call structured_output with shortlist (candidate artifact paths in ranked order) and discarded entries containing path and a concise, criteria-based reason.
65137
+ Report shortlist (candidate artifact paths in ranked order) and discarded entries containing path and a concise, criteria-based reason.
65052
65138
  </output_format>
65053
65139
 
65054
65140
  <objective>
@@ -65060,7 +65146,7 @@ function renderJudgePrompt(task, filterPath, shortlistSize, candidates = []) {
65060
65146
  task: `Rank at most ${shortlistSize} distinct candidate paths for: ${task}.`,
65061
65147
  groundTruthNote: `Read the filter report at ${filterPath} and every candidate path it references before judging.`,
65062
65148
  candidates,
65063
- outputFormat: "Call structured_output with shortlist (candidate paths in ranked order) and rationale (a concise, criteria-based explanation)."
65149
+ outputFormat: "Report shortlist (candidate paths in ranked order) and rationale (a concise, criteria-based explanation)."
65064
65150
  };
65065
65151
  const prompt = build_scoring_prompt(head, {
65066
65152
  id: "filtered_shortlist",
@@ -65270,16 +65356,14 @@ function stringifyStructuredOutputValue(value2) {
65270
65356
  throw new Error(`atomic-workflows: structured_output returned a non-serializable value: ${error instanceof Error ? error.message : String(error)}`);
65271
65357
  }
65272
65358
  }
65273
- function stageOptionsWithStructuredOutput(options, capture, executionCapture) {
65274
- if (!options?.schema || !capture)
65275
- return options;
65359
+ function createStageStructuredOutputTool(options, capture, executionCapture) {
65276
65360
  const structuredOutputTool = createStructuredOutputTool({
65277
65361
  schema: options.schema,
65278
65362
  capture,
65279
65363
  ...options.schemaTimeoutMs === undefined ? {} : { timeoutMs: options.schemaTimeoutMs }
65280
65364
  });
65281
65365
  const executeStructuredOutput = structuredOutputTool.execute;
65282
- const capturedStructuredOutputTool = {
65366
+ return {
65283
65367
  ...structuredOutputTool,
65284
65368
  async execute(...args) {
65285
65369
  const result = await executeStructuredOutput(...args);
@@ -65292,21 +65376,25 @@ function stageOptionsWithStructuredOutput(options, capture, executionCapture) {
65292
65376
  return result;
65293
65377
  }
65294
65378
  };
65379
+ }
65380
+ function stageOptionsWithStructuredOutput(options, structuredOutputTool) {
65381
+ if (!options?.schema || !structuredOutputTool)
65382
+ return options;
65295
65383
  const tools = options.tools === undefined ? options.noTools === "all" ? [STRUCTURED_OUTPUT_TOOL_NAME] : undefined : Array.from(new Set([...options.tools, STRUCTURED_OUTPUT_TOOL_NAME]));
65296
65384
  const excludedTools = options.excludedTools?.filter((toolName) => toolName !== STRUCTURED_OUTPUT_TOOL_NAME);
65297
65385
  return {
65298
65386
  ...options,
65299
65387
  ...tools !== undefined ? { tools } : {},
65300
65388
  ...excludedTools !== undefined ? { excludedTools } : {},
65301
- customTools: [...options.customTools ?? [], capturedStructuredOutputTool]
65389
+ customTools: [...options.customTools ?? [], structuredOutputTool]
65302
65390
  };
65303
65391
  }
65304
65392
  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";
65305
65393
  var init_stage_runner_structured_output = __esm(() => {
65306
65394
  WorkflowStructuredOutputContractError = class WorkflowStructuredOutputContractError extends Error {
65307
65395
  code = "ATOMIC_WORKFLOW_STRUCTURED_OUTPUT_CONTRACT";
65308
- constructor(message) {
65309
- super(message);
65396
+ constructor(message, options) {
65397
+ super(message, options);
65310
65398
  this.name = "WorkflowStructuredOutputContractError";
65311
65399
  }
65312
65400
  };
@@ -65415,7 +65503,7 @@ function build_progress_prompt(input) {
65415
65503
  ...input.checkpoints.map((checkpoint) => `- ${checkpoint}`),
65416
65504
  "</checkpoints>",
65417
65505
  "<output_format>",
65418
- `Return structured_output with scores: [{ checkpoint, score }], using integer scores from ${VERIFICATION_SCALE.min} through ${VERIFICATION_SCALE.max}.`,
65506
+ `Report scores: [{ checkpoint, score }], using integer scores from ${VERIFICATION_SCALE.min} through ${VERIFICATION_SCALE.max}.`,
65419
65507
  "</output_format>"
65420
65508
  ].join(`
65421
65509
  `);
@@ -66215,7 +66303,7 @@ Objective:
66215
66303
  ${context.objective}`,
66216
66304
  groundTruthNote: `The objective is the contract. Verify the finding against observed code, not reviewer narration.`,
66217
66305
  candidates: [candidate],
66218
- outputFormat: "Call structured_output with score (an integer from 1 to 20) and evidence (an array of observed, concise reasons)."
66306
+ outputFormat: "Report score (an integer from 1 to 20) and evidence (an array of observed, concise reasons)."
66219
66307
  };
66220
66308
  const prompt = build_scoring_prompt(head, {
66221
66309
  id: "finding_reverification",
@@ -72477,7 +72565,7 @@ var init_delivery_failure_reason = __esm(() => {
72477
72565
 
72478
72566
  // dist/builtin/intercom/broker/released-child-errors.ts
72479
72567
  function isReleasedChildErrorCode(value2) {
72480
- return CODES2.has(value2);
72568
+ return CODES3.has(value2);
72481
72569
  }
72482
72570
  function releasedChildErrorFor(refusal, options) {
72483
72571
  return refusal.code === "unknown_released_child" ? new UnknownReleasedChildError(refusal, options) : new ReleasedChildReservationError(refusal, options);
@@ -72488,7 +72576,7 @@ function rehydrateCause3(serialized, depth) {
72488
72576
  cause.name = serialized.name;
72489
72577
  return cause;
72490
72578
  }
72491
- 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_DEPTH9 = 4;
72579
+ 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_DEPTH9 = 4;
72492
72580
  var init_released_child_errors = __esm(() => {
72493
72581
  RELEASED_CHILD_ERROR_CODES = [
72494
72582
  "invalid_frame",
@@ -72500,8 +72588,8 @@ var init_released_child_errors = __esm(() => {
72500
72588
  "not_owner",
72501
72589
  "group_not_allowed"
72502
72590
  ];
72503
- CODES2 = new Set(RELEASED_CHILD_ERROR_CODES);
72504
- HINTS3 = {
72591
+ CODES3 = new Set(RELEASED_CHILD_ERROR_CODES);
72592
+ HINTS4 = {
72505
72593
  invalid_frame: "Send between 1 and 500 children per frame, each with a child name and a boolean wake flag.",
72506
72594
  invalid_child_name: "Use the child's exact, non-empty name; the wildcard `*` names no child.",
72507
72595
  invalid_alias: "Reserve extra targets only as session ids, never as names.",
@@ -72519,11 +72607,11 @@ var init_released_child_errors = __esm(() => {
72519
72607
  retryable = false;
72520
72608
  constructor(refusal, options) {
72521
72609
  const subject = refusal.childName === undefined ? "request" : `child ${JSON.stringify(refusal.childName)}`;
72522
- super(`Released-child request refused: ${subject} (${refusal.code}). ${HINTS3[refusal.code]}`, options);
72610
+ super(`Released-child request refused: ${subject} (${refusal.code}). ${HINTS4[refusal.code]}`, options);
72523
72611
  this.code = refusal.code;
72524
72612
  if (refusal.childName !== undefined)
72525
72613
  this.childName = refusal.childName;
72526
- this.hint = HINTS3[refusal.code];
72614
+ this.hint = HINTS4[refusal.code];
72527
72615
  }
72528
72616
  };
72529
72617
  ReleasedChildReservationError = class ReleasedChildReservationError extends IntercomReleasedChildError {
@@ -72532,14 +72620,14 @@ var init_released_child_errors = __esm(() => {
72532
72620
  UnknownReleasedChildError = class UnknownReleasedChildError extends IntercomReleasedChildError {
72533
72621
  name = UNKNOWN_NAME;
72534
72622
  };
72535
- NAMES = new Set([BASE_NAME, RESERVATION_NAME, UNKNOWN_NAME]);
72623
+ NAMES2 = new Set([BASE_NAME, RESERVATION_NAME, UNKNOWN_NAME]);
72536
72624
  RESERVATION_NAMES = new Set([RESERVATION_NAME]);
72537
72625
  UNKNOWN_NAMES = new Set([UNKNOWN_NAME]);
72538
72626
  });
72539
72627
 
72540
72628
  // dist/builtin/intercom/broker/released-reply-errors.ts
72541
72629
  function isReleasedReplyErrorCode(value2) {
72542
- return CODES3.has(value2);
72630
+ return CODES4.has(value2);
72543
72631
  }
72544
72632
  function rehydrateIntercomReleasedReplyError(serialized) {
72545
72633
  const options = serialized.cause === undefined ? undefined : { cause: rehydrateCause3(serialized.cause, 1) };
@@ -72587,15 +72675,15 @@ function readSerializedIntercomReleasedReplyError(value2) {
72587
72675
  ...cause === undefined ? {} : { cause }
72588
72676
  };
72589
72677
  }
72590
- 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_DEPTH10 = 4, isWireObject = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
72678
+ 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_DEPTH10 = 4, isWireObject = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
72591
72679
  var init_released_reply_errors = __esm(() => {
72592
72680
  init_released_child_errors();
72593
72681
  RELEASED_REPLY_ERROR_CODES = [
72594
72682
  "released_reply_answered",
72595
72683
  "released_reply_in_flight"
72596
72684
  ];
72597
- CODES3 = new Set(RELEASED_REPLY_ERROR_CODES);
72598
- HINTS4 = {
72685
+ CODES4 = new Set(RELEASED_REPLY_ERROR_CODES);
72686
+ HINTS5 = {
72599
72687
  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.",
72600
72688
  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."
72601
72689
  };
@@ -72612,9 +72700,9 @@ var init_released_reply_errors = __esm(() => {
72612
72700
  questionId;
72613
72701
  childName;
72614
72702
  constructor(code, fields, options) {
72615
- super(`Reply to a released subagent refused: question ${JSON.stringify(fields.questionId)} of ${JSON.stringify(fields.childName)} (${code}). ${HINTS4[code]}`, options);
72703
+ super(`Reply to a released subagent refused: question ${JSON.stringify(fields.questionId)} of ${JSON.stringify(fields.childName)} (${code}). ${HINTS5[code]}`, options);
72616
72704
  this.code = code;
72617
- this.hint = HINTS4[code];
72705
+ this.hint = HINTS5[code];
72618
72706
  this.retryable = RETRYABLE[code];
72619
72707
  this.messageId = fields.messageId;
72620
72708
  this.questionId = fields.questionId;
@@ -72633,7 +72721,7 @@ var init_released_reply_errors = __esm(() => {
72633
72721
  super("released_reply_in_flight", fields, options);
72634
72722
  }
72635
72723
  };
72636
- NAMES2 = new Set([BASE_NAME2, ANSWERED_NAME, IN_FLIGHT_NAME]);
72724
+ NAMES3 = new Set([BASE_NAME2, ANSWERED_NAME, IN_FLIGHT_NAME]);
72637
72725
  ANSWERED_NAMES = new Set([ANSWERED_NAME]);
72638
72726
  IN_FLIGHT_NAMES = new Set([IN_FLIGHT_NAME]);
72639
72727
  });
@@ -85422,6 +85510,18 @@ class StageSessionPause {
85422
85510
  function storedTranscript(session) {
85423
85511
  return asAgentSession(session)?.sessionManager.buildSessionProjection().messages ?? session.messages;
85424
85512
  }
85513
+ function storedEntryCount(session) {
85514
+ return storedEntries(session)?.length;
85515
+ }
85516
+ function storedAssistantMessageSince(session, entryCount) {
85517
+ if (entryCount === undefined)
85518
+ return false;
85519
+ return storedEntries(session)?.slice(entryCount).some((entry) => entry.type === "message" && entry.message.role === "assistant") === true;
85520
+ }
85521
+ function storedEntries(session) {
85522
+ const manager = asAgentSession(session)?.sessionManager;
85523
+ return typeof manager?.getEntries === "function" ? manager.getEntries() : undefined;
85524
+ }
85425
85525
  function unansweredToolCallIds(messages) {
85426
85526
  let index = messages.length - 1;
85427
85527
  while (index >= 0 && messages[index]?.role !== "assistant")
@@ -85702,6 +85802,7 @@ import {
85702
85802
  AutoRoutingInferenceError,
85703
85803
  convertToLlm,
85704
85804
  currentWorktreeRootMappings,
85805
+ findToolDetachmentError,
85705
85806
  isExtensionStartupFailure,
85706
85807
  isTaskCleanupError as isTaskCleanupError2,
85707
85808
  isTransientExtensionStartupFailure as isTransientExtensionStartupFailure2,
@@ -85753,7 +85854,9 @@ function isSessionCreationPauseResult(value2) {
85753
85854
  return "kind" in value2 && value2.kind === "paused";
85754
85855
  }
85755
85856
  function resumeMessageOptions(sdkOptions) {
85756
- return { ...sdkOptions, expandPromptTemplates: false };
85857
+ const options = { ...sdkOptions, expandPromptTemplates: false };
85858
+ operatorMessageOptions.add(options);
85859
+ return options;
85757
85860
  }
85758
85861
  function stageUserMessageText(message) {
85759
85862
  if (message.role !== "user")
@@ -85932,6 +86035,16 @@ class StageSessionController {
85932
86035
  structuredOutputExecutionFailure() {
85933
86036
  return this.structuredOutputExecutionFailureValue;
85934
86037
  }
86038
+ stageCancellationSignal() {
86039
+ return this.residency.startupWait.signal;
86040
+ }
86041
+ stageToolContext(toolCallId, signal) {
86042
+ return stageSessionToolContext(this.session, toolCallId, signal);
86043
+ }
86044
+ recordStructuredOutputWarning(warning) {
86045
+ this.modelWarnings.push(warning);
86046
+ this.notifyModelFallbackMetaChange();
86047
+ }
85935
86048
  beginStructuredOutputCandidateCycle() {
85936
86049
  this.structuredOutputCycleAttemptMark = this.modelAttempts.length;
85937
86050
  }
@@ -86328,12 +86441,19 @@ class StageSessionController {
86328
86441
  const unanswered = new Set(unansweredToolCallIds(storedTranscript(session)));
86329
86442
  return awaited.filter((toolCallId) => unanswered.has(toolCallId));
86330
86443
  };
86331
- try {
86332
- await resume.call(session, results);
86333
- } catch (error) {
86334
- if (stageReopenFailureCause(error) === "transient" && unsaved().length > 0)
86335
- throw new DetachedResultsNotSaved(error);
86336
- throw error;
86444
+ for (;; ) {
86445
+ try {
86446
+ await resume.call(session, results);
86447
+ break;
86448
+ } catch (error) {
86449
+ if (findToolDetachmentError(error)?.code === "session-busy") {
86450
+ await this.untilSessionSettles(session);
86451
+ continue;
86452
+ }
86453
+ if (stageReopenFailureCause(error) === "transient" && unsaved().length > 0)
86454
+ throw new DetachedResultsNotSaved(error);
86455
+ throw error;
86456
+ }
86337
86457
  }
86338
86458
  const missing = asAgentSession(session) === undefined ? [] : unsaved();
86339
86459
  if (missing.length > 0)
@@ -86347,6 +86467,25 @@ class StageSessionController {
86347
86467
  }, { code: "results-not-saved" });
86348
86468
  this.opts.waiting?.resultsInTranscript();
86349
86469
  }
86470
+ async untilSessionSettles(session) {
86471
+ const settled = Promise.withResolvers();
86472
+ const unsubscribe = session.subscribe((event) => {
86473
+ if (event.type === "agent_settled")
86474
+ settled.resolve();
86475
+ });
86476
+ let timer;
86477
+ try {
86478
+ await raceAbort2(Promise.race([
86479
+ settled.promise,
86480
+ new Promise((resolve) => {
86481
+ timer = setTimeout(resolve, SESSION_SETTLE_POLL_MS);
86482
+ })
86483
+ ]), this.opts.signal);
86484
+ } finally {
86485
+ clearTimeout(timer);
86486
+ unsubscribe();
86487
+ }
86488
+ }
86350
86489
  throwUnlessResultsSaveRetries(failure, attempt, startedAt) {
86351
86490
  const { signal } = this.opts;
86352
86491
  if (signal?.aborted)
@@ -87390,6 +87529,10 @@ class StageSessionController {
87390
87529
  const continuationSession = retryableAgentSession(activeSession);
87391
87530
  const admittedMessages = activeSession.messages.length > messagesBeforeAttempt.length;
87392
87531
  const willRetry = decision !== undefined && !this.disposed && this.opts.signal?.aborted !== true && !this.capturedStructuredOutputForAttempt();
87532
+ if (willRetry && activeSession.isWaitingOnDetachedResults?.() === true) {
87533
+ this.reportHeldForDetachedResults(activeSession, "retry", error);
87534
+ return { terminalScanStartIndex: terminalScanStartIndex ?? messagesBeforeAttempt.length };
87535
+ }
87393
87536
  const willContinue = continuationSession !== undefined && admittedMessages;
87394
87537
  if (retryableFailure && willRetry) {
87395
87538
  this.artifactCapture.settleAttempt(false);
@@ -87440,6 +87583,18 @@ class StageSessionController {
87440
87583
  }
87441
87584
  }
87442
87585
  }
87586
+ reportHeldForDetachedResults(session, held, error) {
87587
+ const code = error?.code;
87588
+ reportDebug3("workflow", "stage-input-held-for-detached-results", {
87589
+ runId: this.opts.runId,
87590
+ stageId: this.opts.stageId,
87591
+ stageName: this.opts.stageName,
87592
+ sessionId: session.sessionId,
87593
+ held,
87594
+ ...error instanceof Error ? { errorName: error.name } : {},
87595
+ ...typeof code === "string" ? { errorCode: code } : {}
87596
+ });
87597
+ }
87443
87598
  workflowAbortReason() {
87444
87599
  const reason = this.opts.signal?.reason;
87445
87600
  if (reason instanceof Error || reason instanceof DOMException || typeof reason === "string")
@@ -87937,6 +88092,7 @@ class StageSessionController {
87937
88092
  continue;
87938
88093
  }
87939
88094
  const promptStartIndex = activeSession.messages.length;
88095
+ const promptStartEntries = storedEntryCount(activeSession);
87940
88096
  this.lastPromptStartIndex = promptStartIndex;
87941
88097
  this.unresolvedContextOverflowMessage = undefined;
87942
88098
  try {
@@ -87949,6 +88105,11 @@ class StageSessionController {
87949
88105
  if (nextText !== initialText)
87950
88106
  await activeSession.steer(nextText, undefined, { expandPromptTemplates: false });
87951
88107
  await this.continueFromResults(activeSession, activeSession.resumeDetachedTurn, detachedResults);
88108
+ } else if (activeSession.isWaitingOnDetachedResults?.() === true) {
88109
+ this.reportHeldForDetachedResults(activeSession, "prompt");
88110
+ if (nextOptions !== undefined && operatorMessageOptions.has(nextOptions))
88111
+ await activeSession.steer(nextText, undefined, { expandPromptTemplates: false });
88112
+ return { terminalScanStartIndex: promptStartIndex };
87952
88113
  } else
87953
88114
  await activeSession.prompt(nextText, nextOptions);
87954
88115
  const pendingPauseAfterPrompt = this.pauseControl.currentResume();
@@ -87963,7 +88124,7 @@ class StageSessionController {
87963
88124
  continue;
87964
88125
  }
87965
88126
  this.throwUnresolvedContextOverflowIfPresent();
87966
- this.throwIfEmptyCompletion(activeSession, promptStartIndex);
88127
+ this.throwIfEmptyCompletion(activeSession, promptStartIndex, promptStartEntries);
87967
88128
  return { terminalScanStartIndex: promptStartIndex };
87968
88129
  } catch (err) {
87969
88130
  if (err instanceof DetachedResultsNotSaved)
@@ -88179,11 +88340,13 @@ class StageSessionController {
88179
88340
  if (message !== undefined)
88180
88341
  throw unresolvedContextOverflowFailure(message);
88181
88342
  }
88182
- throwIfEmptyCompletion(activeSession, promptStartIndex) {
88343
+ throwIfEmptyCompletion(activeSession, promptStartIndex, promptStartEntries) {
88183
88344
  if (this.structuredOutputCapture === undefined || this.structuredOutputCapture.called)
88184
88345
  return;
88185
88346
  if (this.disposed || hasAssistantMessageSince(activeSession.messages, promptStartIndex))
88186
88347
  return;
88348
+ if (storedAssistantMessageSince(activeSession, promptStartEntries))
88349
+ return;
88187
88350
  if (this.opts.signal?.aborted)
88188
88351
  throw this.workflowAbortReason();
88189
88352
  if (this.residency.startupWait.signal.aborted)
@@ -88191,7 +88354,7 @@ class StageSessionController {
88191
88354
  throw new WorkflowPromptEmptyCompletionFailure;
88192
88355
  }
88193
88356
  }
88194
- 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;
88357
+ 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;
88195
88358
  var init_stage_runner_controller = __esm(() => {
88196
88359
  init_stage_wait();
88197
88360
  init_stage_wait_errors();
@@ -88218,6 +88381,7 @@ var init_stage_runner_controller = __esm(() => {
88218
88381
  this.name = "StageSessionCreationCancelled";
88219
88382
  }
88220
88383
  };
88384
+ operatorMessageOptions = new WeakSet;
88221
88385
  ThrownErrorRetryPaused = class ThrownErrorRetryPaused extends Error {
88222
88386
  resume;
88223
88387
  constructor(resume) {
@@ -88395,12 +88559,13 @@ function validatePromptOutputOptions(outputOptions) {
88395
88559
  }
88396
88560
  }
88397
88561
  function stageOutputInstruction(outputOptions, hasStructuredOutput = false) {
88562
+ const closing = hasStructuredOutput ? STRUCTURED_OUTPUT_CLOSING_INSTRUCTION : "";
88398
88563
  if (typeof outputOptions.output !== "string" || outputOptions.output.length === 0)
88399
- return "";
88564
+ return closing;
88400
88565
  if (hasStructuredOutput) {
88401
88566
  return `
88402
88567
 
88403
- [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.]`;
88568
+ [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}`;
88404
88569
  }
88405
88570
  return `
88406
88571
 
@@ -88443,12 +88608,135 @@ ${err instanceof Error ? err.message : String(err)}`;
88443
88608
 
88444
88609
  ${reference}`;
88445
88610
  }
88446
- var DEFAULT_MAX_OUTPUT_BYTES, DEFAULT_MAX_OUTPUT_LINES = 5000;
88611
+ var DEFAULT_MAX_OUTPUT_BYTES, DEFAULT_MAX_OUTPUT_LINES = 5000, STRUCTURED_OUTPUT_CLOSING_INSTRUCTION = `
88612
+
88613
+ [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.]`;
88447
88614
  var init_stage_runner_output = __esm(() => {
88448
88615
  init_workflow_artifacts();
88449
88616
  DEFAULT_MAX_OUTPUT_BYTES = 200 * 1024;
88450
88617
  });
88451
88618
 
88619
+ // dist/builtin/workflows/src/runs/foreground/stage-runner-structured-output-auto.ts
88620
+ import {
88621
+ findDecisionError,
88622
+ isDecisionOutputError
88623
+ } from "@bastani/atomic";
88624
+ function boundedText(text, limit) {
88625
+ if (text.length <= limit)
88626
+ return text;
88627
+ const head = Math.ceil(limit / 2);
88628
+ return `${text.slice(0, head)}
88629
+ [… ${text.length - limit} characters omitted …]
88630
+ ${text.slice(text.length - (limit - head))}`;
88631
+ }
88632
+ function conversationText(message) {
88633
+ if (message.role !== "user" && message.role !== "assistant")
88634
+ return;
88635
+ const text = extractMessageText(message).trim();
88636
+ return text.length === 0 ? undefined : { role: message.role, text };
88637
+ }
88638
+ function finalAssistantAnswer(messages, promptStartIndex) {
88639
+ for (let index = messages.length - 1;index >= promptStartIndex; index -= 1) {
88640
+ const message = messages[index];
88641
+ if (message.role !== "assistant")
88642
+ continue;
88643
+ const rawText = extractMessageText(message);
88644
+ if (rawText.trim().length > 0)
88645
+ return { index, rawText };
88646
+ }
88647
+ return;
88648
+ }
88649
+ function automaticStructuredOutputInput(input) {
88650
+ const { messages, promptStartIndex } = input;
88651
+ const final = finalAssistantAnswer(messages, promptStartIndex);
88652
+ if (final === undefined)
88653
+ return;
88654
+ const recent = [];
88655
+ for (let index = final.index - 1;index >= 0 && recent.length < AUTOMATIC_STRUCTURED_OUTPUT_TRANSCRIPT_MESSAGES; index -= 1) {
88656
+ const message = conversationText(messages[index]);
88657
+ if (message !== undefined)
88658
+ recent.unshift({
88659
+ role: message.role,
88660
+ text: boundedText(message.text, AUTOMATIC_STRUCTURED_OUTPUT_TEXT_CHARS)
88661
+ });
88662
+ }
88663
+ return {
88664
+ finalText: final.rawText,
88665
+ evidence: {
88666
+ stageTask: boundedText(input.stagePrompt, AUTOMATIC_STRUCTURED_OUTPUT_TEXT_CHARS),
88667
+ finalAssistantText: boundedText(final.rawText.trim(), AUTOMATIC_STRUCTURED_OUTPUT_TEXT_CHARS),
88668
+ recentTranscript: recent
88669
+ }
88670
+ };
88671
+ }
88672
+ function automaticStructuredOutputInstructions(schema) {
88673
+ const { title, description } = schema;
88674
+ const contract = [title, description].filter((part) => part !== undefined && part.trim().length > 0).join(": ");
88675
+ return [
88676
+ "Produce the machine-readable result this workflow stage was asked to return, as the registered result schema defines it.",
88677
+ "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.",
88678
+ "Report what the agent concluded. Do not redo the task, and do not invent facts the state does not contain.",
88679
+ ...contract.length === 0 ? [] : [`Result schema: ${contract}`]
88680
+ ].join(`
88681
+ `);
88682
+ }
88683
+ function failure3(code, fields, cause) {
88684
+ return {
88685
+ kind: "failed",
88686
+ error: new WorkflowStructuredOutputInferenceError(code, fields, cause === undefined ? undefined : { cause })
88687
+ };
88688
+ }
88689
+ async function runAutomaticStructuredOutput(input) {
88690
+ const { fields, signal } = input;
88691
+ const built = automaticStructuredOutputInput(input);
88692
+ if (built === undefined)
88693
+ return { kind: "skipped" };
88694
+ const { evidence, finalText } = built;
88695
+ let context;
88696
+ try {
88697
+ context = input.toolContext(fields.toolCallId, signal);
88698
+ } catch (error) {
88699
+ signal.throwIfAborted();
88700
+ return failure3("tool-context-unavailable", fields, error);
88701
+ }
88702
+ if (context === undefined)
88703
+ return failure3("tool-context-unavailable", fields);
88704
+ const params = {
88705
+ instructions: automaticStructuredOutputInstructions(input.schema),
88706
+ state: evidence
88707
+ };
88708
+ try {
88709
+ await input.tool.execute(fields.toolCallId, params, signal, undefined, context);
88710
+ } catch (error) {
88711
+ signal.throwIfAborted();
88712
+ return failure3("auto-inference-failed", fields, error);
88713
+ }
88714
+ return { kind: "captured", finalAssistantText: finalText };
88715
+ }
88716
+ function automaticInferenceExecutionFailure(error) {
88717
+ if (error.cause === undefined)
88718
+ return;
88719
+ const decision = findDecisionError(error.cause);
88720
+ if (decision !== undefined)
88721
+ return isDecisionOutputError(decision) ? undefined : errorMessage4(error.cause);
88722
+ const detail = errorMessage4(error.cause);
88723
+ return isStructuredOutputContractFailure(detail) ? undefined : detail;
88724
+ }
88725
+ function automaticInferenceWarning(error) {
88726
+ const cause = error.cause;
88727
+ const code = typeof cause === "object" && cause !== null ? cause.code : undefined;
88728
+ const name = cause instanceof Error ? cause.name : undefined;
88729
+ const reason = name === undefined ? "" : ` Cause: ${name}${typeof code === "string" ? ` (${code})` : ""}.`;
88730
+ return `[structured-output] ${error.message}${reason}`;
88731
+ }
88732
+ var AUTOMATIC_STRUCTURED_OUTPUT_TRANSCRIPT_MESSAGES = 6, AUTOMATIC_STRUCTURED_OUTPUT_TEXT_CHARS = 16000;
88733
+ var init_stage_runner_structured_output_auto = __esm(() => {
88734
+ init_structured_output_errors();
88735
+ init_model_fallback();
88736
+ init_stage_runner_messages();
88737
+ init_stage_runner_structured_output();
88738
+ });
88739
+
88452
88740
  // dist/builtin/workflows/src/runs/foreground/stage-runner-context.ts
88453
88741
  import { createStructuredOutputCapture, runCallback as runCallback2 } from "@bastani/atomic";
88454
88742
  function createStageContext(opts) {
@@ -88456,7 +88744,8 @@ function createStageContext(opts) {
88456
88744
  const stageCwd = stageOptions?.cwd ?? stageOptions?.sessionManager?.getCwd() ?? agentSessionAdapterDefaultCwd(adapters.agentSession) ?? opts.defaultCwd ?? process.cwd();
88457
88745
  const structuredOutputCapture = stageOptions?.schema ? createStructuredOutputCapture() : undefined;
88458
88746
  const structuredOutputExecutionCapture = stageOptions?.schema ? {} : undefined;
88459
- const effectiveStageOptions = stageOptionsWithStructuredOutput(adapters.sessionStore === undefined || stageOptions?.sessionStore !== undefined || stageOptions?.sessionDir !== undefined || stageOptions?.sessionManager !== undefined ? stageOptions : { ...stageOptions, sessionStore: adapters.sessionStore }, structuredOutputCapture, structuredOutputExecutionCapture);
88747
+ const structuredOutputTool = stageOptions?.schema ? createStageStructuredOutputTool({ schema: stageOptions.schema, schemaTimeoutMs: stageOptions.schemaTimeoutMs }, structuredOutputCapture, structuredOutputExecutionCapture) : undefined;
88748
+ const effectiveStageOptions = stageOptionsWithStructuredOutput(adapters.sessionStore === undefined || stageOptions?.sessionStore !== undefined || stageOptions?.sessionDir !== undefined || stageOptions?.sessionManager !== undefined ? stageOptions : { ...stageOptions, sessionStore: adapters.sessionStore }, structuredOutputTool);
88460
88749
  const meta = {
88461
88750
  runId,
88462
88751
  stageId,
@@ -88476,6 +88765,23 @@ function createStageContext(opts) {
88476
88765
  let artifactClosed = false;
88477
88766
  let artifactText;
88478
88767
  let continuing = false;
88768
+ let automaticInferences = 0;
88769
+ let automaticArtifactText;
88770
+ let warnedInference = false;
88771
+ async function inferStructuredOutputAutomatically(stagePrompt) {
88772
+ automaticInferences += 1;
88773
+ return runAutomaticStructuredOutput({
88774
+ tool: structuredOutputTool,
88775
+ schema: stageOptions.schema,
88776
+ capture: structuredOutputCapture,
88777
+ stagePrompt,
88778
+ messages: controller.currentSession?.messages ?? [],
88779
+ promptStartIndex: controller.currentPromptStartIndex ?? 0,
88780
+ toolContext: (toolCallId, signal) => controller.stageToolContext(toolCallId, signal),
88781
+ signal: controller.stageCancellationSignal(),
88782
+ fields: { runId, stageId, stageName, toolCallId: `workflow-auto-structured-output-${automaticInferences}` }
88783
+ });
88784
+ }
88479
88785
  async function exportArtifact() {
88480
88786
  const text = assistantArtifactTextForGeneration(controller.outputGenerationMessages());
88481
88787
  if (text !== artifactText || lastFinalizedOutput === undefined) {
@@ -88535,6 +88841,7 @@ function createStageContext(opts) {
88535
88841
  if (structuredOutputCapture) {
88536
88842
  let structuredOutputError = STRUCTURED_OUTPUT_MISSING_ERROR;
88537
88843
  let executionFailure;
88844
+ let automaticInferenceFailure;
88538
88845
  while (!structuredOutputCapture.called) {
88539
88846
  let nextPrompt = promptText;
88540
88847
  let newSessionPrompt;
@@ -88543,12 +88850,25 @@ function createStageContext(opts) {
88543
88850
  while (!structuredOutputCapture.called) {
88544
88851
  controller.resetStructuredOutputToolError();
88545
88852
  await controller.promptWithFallback(nextPrompt, sdkOptions, undefined, newSessionPrompt, continuationText);
88853
+ if (structuredOutputCapture.called)
88854
+ break;
88855
+ const automatic = await inferStructuredOutputAutomatically(text);
88856
+ if (automatic.kind === "captured")
88857
+ automaticArtifactText = automatic.finalAssistantText;
88546
88858
  if (structuredOutputCapture.called)
88547
88859
  break;
88548
88860
  structuredOutputError = controller.structuredOutputFailureReason();
88549
88861
  executionFailure ??= controller.structuredOutputExecutionFailure();
88550
88862
  if (!isStructuredOutputContractFailure(structuredOutputError))
88551
88863
  executionFailure ??= structuredOutputError;
88864
+ if (automatic.kind === "failed") {
88865
+ automaticInferenceFailure = automatic.error;
88866
+ executionFailure ??= automaticInferenceExecutionFailure(automatic.error);
88867
+ if (automatic.error.code === "auto-inference-failed" && !warnedInference) {
88868
+ warnedInference = true;
88869
+ controller.recordStructuredOutputWarning(automaticInferenceWarning(automatic.error));
88870
+ }
88871
+ }
88552
88872
  if (correctiveAttempts >= STRUCTURED_OUTPUT_MAX_CORRECTIVE_PROMPTS)
88553
88873
  break;
88554
88874
  correctiveAttempts += 1;
@@ -88560,7 +88880,8 @@ ${nextPrompt}`;
88560
88880
  if (structuredOutputCapture.called)
88561
88881
  break;
88562
88882
  if (!await controller.failCandidateForStructuredOutputExhaustion(structuredOutputError)) {
88563
- throw executionFailure === undefined ? new WorkflowStructuredOutputContractError(structuredOutputError) : new Error(executionFailure);
88883
+ const failureOptions = automaticInferenceFailure === undefined ? undefined : { cause: automaticInferenceFailure };
88884
+ throw executionFailure === undefined ? new WorkflowStructuredOutputContractError(structuredOutputError, failureOptions) : new Error(executionFailure, failureOptions);
88564
88885
  }
88565
88886
  }
88566
88887
  const sessionMessages = controller.currentSession?.messages;
@@ -88568,7 +88889,7 @@ ${nextPrompt}`;
88568
88889
  if (executionSnapshot === undefined) {
88569
88890
  throw new Error("atomic-workflows: structured_output completed without an execution snapshot; the successful tool call could not be paired with its result.");
88570
88891
  }
88571
- const rawOutputText = hasOutputArtifact ? assistantArtifactTextForToolCall(sessionMessages ?? [], executionSnapshot.toolCallId) ?? "" : stringifyStructuredOutputValue(executionSnapshot.value);
88892
+ const rawOutputText = hasOutputArtifact ? automaticArtifactText ?? assistantArtifactTextForToolCall(sessionMessages ?? [], executionSnapshot.toolCallId) ?? "" : stringifyStructuredOutputValue(executionSnapshot.value);
88572
88893
  lastAssistantText = await finalizePromptOutput(rawOutputText, outputOptions, stageCwd, runId, sessionMessages);
88573
88894
  lastFinalizedOutput = lastAssistantText;
88574
88895
  lastFinalizedMessageCount = controller.currentSession?.messages.length;
@@ -88830,6 +89151,7 @@ var init_stage_runner_context = __esm(() => {
88830
89151
  init_stage_runner_output();
88831
89152
  init_stage_runner_session_options();
88832
89153
  init_stage_runner_structured_output();
89154
+ init_stage_runner_structured_output_auto();
88833
89155
  });
88834
89156
 
88835
89157
  // dist/builtin/workflows/src/runs/foreground/stage-runner.ts
@@ -93610,7 +93932,7 @@ var init_blocked_stage_close = __esm(() => {
93610
93932
 
93611
93933
  // dist/builtin/workflows/src/runs/foreground/readiness-decision.ts
93612
93934
  import {
93613
- findDecisionError,
93935
+ findDecisionError as findDecisionError2,
93614
93936
  isDecisionModelUnavailableError
93615
93937
  } from "@bastani/atomic";
93616
93938
  function readinessVerdict(result, thresholds = READINESS_DECISION_THRESHOLDS) {
@@ -93635,11 +93957,11 @@ function readinessDecisionRecord(verdict, model, at = Date.now()) {
93635
93957
  });
93636
93958
  }
93637
93959
  function decisionModelGivesNoProbabilities(error) {
93638
- const typed = findDecisionError(error);
93960
+ const typed = findDecisionError2(error);
93639
93961
  return isDecisionModelUnavailableError(typed) && typed.reason === "no-probabilities";
93640
93962
  }
93641
93963
  function readinessFailureRecord(error, at = Date.now()) {
93642
- const typed = findDecisionError(error);
93964
+ const typed = findDecisionError2(error);
93643
93965
  const named = error instanceof Error ? error : undefined;
93644
93966
  return Object.freeze({
93645
93967
  outcome: "asked",
@@ -98097,7 +98419,7 @@ import {
98097
98419
  resolveGitSync as resolveGitSync2,
98098
98420
  restoreRunWorktree
98099
98421
  } from "@bastani/atomic";
98100
- function failure3(error) {
98422
+ function failure4(error) {
98101
98423
  return error instanceof WorkerPlacementError ? serializeWorkerPlacementError(error) : { name: error.name, message: error.message };
98102
98424
  }
98103
98425
  function active(status) {
@@ -98218,7 +98540,7 @@ class WorkerHost {
98218
98540
  this.options = options;
98219
98541
  this.timer = setInterval(() => {
98220
98542
  this.polling ??= this.poll().catch((error) => {
98221
- this.lastDetach = failure3(error);
98543
+ this.lastDetach = failure4(error);
98222
98544
  }).finally(() => {
98223
98545
  this.polling = undefined;
98224
98546
  });
@@ -98264,7 +98586,7 @@ class WorkerHost {
98264
98586
  continue;
98265
98587
  this.satellites.delete(root);
98266
98588
  await satellite.coordinator.stopSatellite().catch((error) => {
98267
- this.lastDetach = failure3(error);
98589
+ this.lastDetach = failure4(error);
98268
98590
  });
98269
98591
  await satellite.coordinator.shutdown();
98270
98592
  }
@@ -98309,7 +98631,7 @@ class WorkerHost {
98309
98631
  satellite.yielding = true;
98310
98632
  this.yielded.set(root, now);
98311
98633
  satellite.attached.then(() => satellite.coordinator.drain()).catch((error) => {
98312
- this.lastDetach = failure3(error);
98634
+ this.lastDetach = failure4(error);
98313
98635
  }).finally(() => {
98314
98636
  satellite.detached = true;
98315
98637
  });
@@ -98354,15 +98676,15 @@ class WorkerHost {
98354
98676
  detached: (reason) => {
98355
98677
  satellite.detached = true;
98356
98678
  if (reason !== undefined)
98357
- this.lastDetach = failure3(reason);
98679
+ this.lastDetach = failure4(reason);
98358
98680
  },
98359
98681
  placementFailed: (error) => {
98360
- this.lastPlacementFailure = failure3(error);
98682
+ this.lastPlacementFailure = failure4(error);
98361
98683
  }
98362
98684
  }
98363
98685
  }).catch((error) => {
98364
98686
  satellite.detached = true;
98365
- this.lastDetach = failure3(error);
98687
+ this.lastDetach = failure4(error);
98366
98688
  });
98367
98689
  this.satellites.set(root.root, satellite);
98368
98690
  }
@@ -98394,7 +98716,7 @@ class WorkerHost {
98394
98716
  else if (this.draining && !this.stoppingNow)
98395
98717
  for (const satellite of this.satellites.values())
98396
98718
  satellite.coordinator.stopSatellite().catch((error) => {
98397
- this.lastDetach = failure3(error);
98719
+ this.lastDetach = failure4(error);
98398
98720
  });
98399
98721
  this.stoppingNow = true;
98400
98722
  return this.stopping;
@@ -98595,6 +98917,7 @@ __export(exports_sdk_surface, {
98595
98917
  WorkflowAdmissionError: () => WorkflowAdmissionError,
98596
98918
  WorkflowGitRequiredError: () => WorkflowGitRequiredError,
98597
98919
  WorkflowInfrastructureError: () => WorkflowInfrastructureError,
98920
+ WorkflowStructuredOutputInferenceError: () => WorkflowStructuredOutputInferenceError,
98598
98921
  WorkspaceBindingError: () => WorkspaceBindingError3,
98599
98922
  WorkspaceCollectionError: () => WorkspaceCollectionError,
98600
98923
  WorkspaceConfigError: () => WorkspaceConfigError,
@@ -98620,7 +98943,8 @@ __export(exports_sdk_surface, {
98620
98943
  deserializeRunEvictionError: () => deserializeRunEvictionError,
98621
98944
  deserializeStageWaitError: () => deserializeStageWaitError,
98622
98945
  deserializeSubscriptionError: () => deserializeSubscriptionError2,
98623
- findDecisionError: () => findDecisionError2,
98946
+ deserializeWorkflowStructuredOutputInferenceError: () => deserializeWorkflowStructuredOutputInferenceError,
98947
+ findDecisionError: () => findDecisionError3,
98624
98948
  findForkError: () => findForkError,
98625
98949
  findLocalWorkerPoolError: () => findLocalWorkerPoolError,
98626
98950
  findPossibleStagePredictionError: () => findPossibleStagePredictionError,
@@ -98628,6 +98952,7 @@ __export(exports_sdk_surface, {
98628
98952
  findStageWaitError: () => findStageWaitError,
98629
98953
  findSubscriptionError: () => findSubscriptionError,
98630
98954
  findWorkflowAdmissionError: () => findWorkflowAdmissionError,
98955
+ findWorkflowStructuredOutputInferenceError: () => findWorkflowStructuredOutputInferenceError,
98631
98956
  findWorkspaceError: () => findWorkspaceError2,
98632
98957
  forkRun: () => forkRun,
98633
98958
  githubChecks: () => githubChecks,
@@ -98638,7 +98963,7 @@ __export(exports_sdk_surface, {
98638
98963
  isDecisionConfigError: () => isDecisionConfigError,
98639
98964
  isDecisionError: () => isDecisionError,
98640
98965
  isDecisionModelUnavailableError: () => isDecisionModelUnavailableError2,
98641
- isDecisionOutputError: () => isDecisionOutputError,
98966
+ isDecisionOutputError: () => isDecisionOutputError2,
98642
98967
  isDecisionProviderError: () => isDecisionProviderError,
98643
98968
  isDecisionRequestError: () => isDecisionRequestError,
98644
98969
  isDecisionTimeoutError: () => isDecisionTimeoutError,
@@ -98721,6 +99046,7 @@ __export(exports_sdk_surface, {
98721
99046
  isWorkflowAdmissionError: () => isWorkflowAdmissionError,
98722
99047
  isWorkflowGitRequiredError: () => isWorkflowGitRequiredError,
98723
99048
  isWorkflowInfrastructureError: () => isWorkflowInfrastructureError,
99049
+ isWorkflowStructuredOutputInferenceError: () => isWorkflowStructuredOutputInferenceError,
98724
99050
  isWorkspace: () => isWorkspace2,
98725
99051
  isWorkspaceBindingError: () => isWorkspaceBindingError,
98726
99052
  isWorkspaceCollectionError: () => isWorkspaceCollectionError,
@@ -98792,7 +99118,7 @@ import {
98792
99118
  decide,
98793
99119
  deserializeSubscriptionError as deserializeSubscriptionError2,
98794
99120
  EventSourceError,
98795
- findDecisionError as findDecisionError2,
99121
+ findDecisionError as findDecisionError3,
98796
99122
  findSubscriptionError,
98797
99123
  findWorkspaceError as findWorkspaceError2,
98798
99124
  GitUnavailableError,
@@ -98803,7 +99129,7 @@ import {
98803
99129
  isDecisionConfigError,
98804
99130
  isDecisionError,
98805
99131
  isDecisionModelUnavailableError as isDecisionModelUnavailableError2,
98806
- isDecisionOutputError,
99132
+ isDecisionOutputError as isDecisionOutputError2,
98807
99133
  isDecisionProviderError,
98808
99134
  isDecisionRequestError,
98809
99135
  isDecisionTimeoutError,
@@ -98897,6 +99223,7 @@ var init_sdk_surface = __esm(() => {
98897
99223
  init_stage_wait_errors();
98898
99224
  init_stage_wake();
98899
99225
  init_store();
99226
+ init_structured_output_errors();
98900
99227
  init_types2();
98901
99228
  init_worker_pool_errors();
98902
99229
  init_workflow_git_required_error();