@draht/coding-agent 2026.10.16 → 2026.10.19

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 (133) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/README.md +1 -0
  3. package/dist/bundle/chunks/{chunk-OWGSPJPZ.js → chunk-7TYCZN4Z.js} +4 -4
  4. package/dist/bundle/chunks/{chunk-TJ3AW62W.js → chunk-KEUN2Y6B.js} +1 -1
  5. package/dist/bundle/chunks/{chunk-JFDPOIUH.js → chunk-MO3SCGBN.js} +1 -1
  6. package/dist/bundle/chunks/{chunk-6APPDDHH.js → chunk-N2QZNJT6.js} +3 -3
  7. package/dist/bundle/chunks/{chunk-MIUVNYYW.js → chunk-VOODMGI3.js} +103 -91
  8. package/dist/bundle/chunks/{chunk-NHTOADU6.js → chunk-ZA4QNPJY.js} +1 -1
  9. package/dist/bundle/chunks/{cli-U7Y4VNNI.js → cli-PYJB6AQ3.js} +1 -1
  10. package/dist/bundle/chunks/{execute-ZWB4PIQQ.js → execute-6N7T7VLY.js} +1 -1
  11. package/dist/bundle/chunks/{runtime-PXJK4L7Y.js → runtime-D3KV73AE.js} +1 -1
  12. package/dist/bundle/chunks/{virtual-modules-BEJ4ZJ3D.js → virtual-modules-GSNL3MCU.js} +1 -1
  13. package/dist/bundle/cli-runtime.js +1 -1
  14. package/dist/bundle/index.js +1 -1
  15. package/dist/bundle/rpc-entry.js +1 -1
  16. package/dist/core/agent-session.d.ts.map +1 -1
  17. package/dist/core/agent-session.js +4 -0
  18. package/dist/core/agent-session.js.map +1 -1
  19. package/dist/core/builtins/duet.d.ts +7 -1
  20. package/dist/core/builtins/duet.d.ts.map +1 -1
  21. package/dist/core/builtins/duet.js +83 -14
  22. package/dist/core/builtins/duet.js.map +1 -1
  23. package/dist/core/builtins/polyphase.d.ts.map +1 -1
  24. package/dist/core/builtins/polyphase.js +21 -2
  25. package/dist/core/builtins/polyphase.js.map +1 -1
  26. package/dist/core/builtins/subagent.d.ts +59 -2
  27. package/dist/core/builtins/subagent.d.ts.map +1 -1
  28. package/dist/core/builtins/subagent.js +258 -62
  29. package/dist/core/builtins/subagent.js.map +1 -1
  30. package/dist/core/extensions/loader.d.ts.map +1 -1
  31. package/dist/core/extensions/loader.js +23 -0
  32. package/dist/core/extensions/loader.js.map +1 -1
  33. package/dist/core/extensions/runner.d.ts.map +1 -1
  34. package/dist/core/extensions/runner.js +2 -0
  35. package/dist/core/extensions/runner.js.map +1 -1
  36. package/dist/core/extensions/types.d.ts +12 -0
  37. package/dist/core/extensions/types.d.ts.map +1 -1
  38. package/dist/core/extensions/types.js.map +1 -1
  39. package/dist/core/keybindings.d.ts +5 -0
  40. package/dist/core/keybindings.d.ts.map +1 -1
  41. package/dist/core/keybindings.js +4 -0
  42. package/dist/core/keybindings.js.map +1 -1
  43. package/dist/core/multi-agent/permission-gate.d.ts +18 -6
  44. package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
  45. package/dist/core/multi-agent/permission-gate.js +867 -59
  46. package/dist/core/multi-agent/permission-gate.js.map +1 -1
  47. package/dist/core/polyphase/approval.d.ts +6 -2
  48. package/dist/core/polyphase/approval.d.ts.map +1 -1
  49. package/dist/core/polyphase/approval.js +23 -35
  50. package/dist/core/polyphase/approval.js.map +1 -1
  51. package/dist/core/polyphase/child-events.js +1 -1
  52. package/dist/core/polyphase/child-events.js.map +1 -1
  53. package/dist/core/polyphase/child-process.d.ts.map +1 -1
  54. package/dist/core/polyphase/child-process.js +65 -7
  55. package/dist/core/polyphase/child-process.js.map +1 -1
  56. package/dist/core/polyphase/commands.d.ts.map +1 -1
  57. package/dist/core/polyphase/commands.js +46 -5
  58. package/dist/core/polyphase/commands.js.map +1 -1
  59. package/dist/core/polyphase/details.d.ts.map +1 -1
  60. package/dist/core/polyphase/details.js +5 -0
  61. package/dist/core/polyphase/details.js.map +1 -1
  62. package/dist/core/polyphase/permission-bridge.d.ts +128 -0
  63. package/dist/core/polyphase/permission-bridge.d.ts.map +1 -0
  64. package/dist/core/polyphase/permission-bridge.js +357 -0
  65. package/dist/core/polyphase/permission-bridge.js.map +1 -0
  66. package/dist/core/polyphase/render/run-block.d.ts.map +1 -1
  67. package/dist/core/polyphase/render/run-block.js +13 -4
  68. package/dist/core/polyphase/render/run-block.js.map +1 -1
  69. package/dist/core/polyphase/render/snapshot.d.ts +4 -0
  70. package/dist/core/polyphase/render/snapshot.d.ts.map +1 -1
  71. package/dist/core/polyphase/render/snapshot.js +4 -0
  72. package/dist/core/polyphase/render/snapshot.js.map +1 -1
  73. package/dist/core/polyphase/result-text.d.ts.map +1 -1
  74. package/dist/core/polyphase/result-text.js +23 -3
  75. package/dist/core/polyphase/result-text.js.map +1 -1
  76. package/dist/core/polyphase/session.d.ts +15 -1
  77. package/dist/core/polyphase/session.d.ts.map +1 -1
  78. package/dist/core/polyphase/session.js +36 -1
  79. package/dist/core/polyphase/session.js.map +1 -1
  80. package/dist/core/polyphase/settings.d.ts +1 -0
  81. package/dist/core/polyphase/settings.d.ts.map +1 -1
  82. package/dist/core/polyphase/settings.js +1 -1
  83. package/dist/core/polyphase/settings.js.map +1 -1
  84. package/dist/core/polyphase/store.d.ts +18 -0
  85. package/dist/core/polyphase/store.d.ts.map +1 -1
  86. package/dist/core/polyphase/store.js +38 -0
  87. package/dist/core/polyphase/store.js.map +1 -1
  88. package/dist/core/polyphase/types.d.ts +60 -3
  89. package/dist/core/polyphase/types.d.ts.map +1 -1
  90. package/dist/core/polyphase/types.js.map +1 -1
  91. package/dist/core/polyphase/ui/inspector.js +1 -1
  92. package/dist/core/polyphase/ui/inspector.js.map +1 -1
  93. package/dist/core/polyphase/workflow/agent-host.d.ts.map +1 -1
  94. package/dist/core/polyphase/workflow/agent-host.js +17 -3
  95. package/dist/core/polyphase/workflow/agent-host.js.map +1 -1
  96. package/dist/core/polyphase/workflow/guidance.d.ts.map +1 -1
  97. package/dist/core/polyphase/workflow/guidance.js +16 -5
  98. package/dist/core/polyphase/workflow/guidance.js.map +1 -1
  99. package/dist/core/polyphase/workflow/launch.d.ts +2 -1
  100. package/dist/core/polyphase/workflow/launch.d.ts.map +1 -1
  101. package/dist/core/polyphase/workflow/launch.js +22 -3
  102. package/dist/core/polyphase/workflow/launch.js.map +1 -1
  103. package/dist/core/polyphase/workflow/limits.d.ts +80 -0
  104. package/dist/core/polyphase/workflow/limits.d.ts.map +1 -0
  105. package/dist/core/polyphase/workflow/limits.js +234 -0
  106. package/dist/core/polyphase/workflow/limits.js.map +1 -0
  107. package/dist/core/polyphase/workflow/runtime.d.ts +1 -1
  108. package/dist/core/polyphase/workflow/runtime.d.ts.map +1 -1
  109. package/dist/core/polyphase/workflow/runtime.js.map +1 -1
  110. package/dist/core/polyphase/workflow/tool.d.ts +1 -0
  111. package/dist/core/polyphase/workflow/tool.d.ts.map +1 -1
  112. package/dist/core/polyphase/workflow/tool.js +23 -2
  113. package/dist/core/polyphase/workflow/tool.js.map +1 -1
  114. package/dist/core/usage-totals.d.ts +5 -0
  115. package/dist/core/usage-totals.d.ts.map +1 -1
  116. package/dist/core/usage-totals.js +16 -0
  117. package/dist/core/usage-totals.js.map +1 -1
  118. package/dist/main.d.ts.map +1 -1
  119. package/dist/main.js +4 -0
  120. package/dist/main.js.map +1 -1
  121. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  122. package/dist/modes/interactive/interactive-mode.js +2 -0
  123. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  124. package/dist/utils/shell.d.ts.map +1 -1
  125. package/dist/utils/shell.js +3 -0
  126. package/dist/utils/shell.js.map +1 -1
  127. package/docs/duet.md +1 -1
  128. package/docs/environment-variables.md +3 -1
  129. package/docs/extensions.md +2 -1
  130. package/docs/keybindings.md +1 -0
  131. package/docs/polyphase.md +97 -33
  132. package/docs/settings.md +2 -2
  133. package/package.json +10 -10
@@ -2,7 +2,7 @@
2
2
  * Bridges a workflow script's `agent()`/`phase()`/`log()` calls to real subagent runs (§14.3): one
3
3
  * `WorkflowHost` per run, created by `launch.ts` and handed to `runWorkflowScript`.
4
4
  */
5
- import { discoverAgents, runSingleTask } from "../../builtins/subagent.js";
5
+ import { childPermissionContext, discoverAgents, runSingleTask } from "../../builtins/subagent.js";
6
6
  import { ModelSelectionError, resolveChildModel } from "../model-selection.js";
7
7
  import { currentPolyphaseDepth, POLYPHASE_RESULT_TOOL_NAME, } from "../types.js";
8
8
  import { prepareResultSchema, STRUCTURED_OUTPUT_INSTRUCTION } from "./structured-output.js";
@@ -25,13 +25,19 @@ function failureDetail(stderr, errorMessage, exitCode) {
25
25
  }
26
26
  return `exit code ${exitCode}`;
27
27
  }
28
- /** `cancelReason "user"` reads as "you" in the log line; every other reason reads verbatim. */
28
+ /** `cancelReason "user"` reads as "you", "time" reads as "time limit" (matching the §D-B wording
29
+ * used elsewhere), every other reason reads verbatim. */
29
30
  function cancelReasonText(reason) {
30
- return reason === "user" ? "you" : (reason ?? "run");
31
+ if (reason === "user")
32
+ return "you";
33
+ if (reason === "time")
34
+ return "time limit";
35
+ return reason ?? "run";
31
36
  }
32
37
  export function createWorkflowAgentHost(deps) {
33
38
  let cachedAgents;
34
39
  let budgetNoticeLogged = false;
40
+ let timeLimitNoticeLogged = false;
35
41
  const agentTypeCounts = new Map();
36
42
  const usedLabels = new Set();
37
43
  const inFlight = new Set();
@@ -76,6 +82,13 @@ export function createWorkflowAgentHost(deps) {
76
82
  }
77
83
  return { kind: "null", reason: "budget" };
78
84
  }
85
+ if (deps.run.timeLimit.reached) {
86
+ if (!timeLimitNoticeLogged) {
87
+ timeLimitNoticeLogged = true;
88
+ deps.run.appendLog("time limit reached; agent(...) returns null", "warning");
89
+ }
90
+ return { kind: "null", reason: "time" };
91
+ }
79
92
  let agentTypeDisplay;
80
93
  let config;
81
94
  if (request.agentType) {
@@ -147,6 +160,7 @@ export function createWorkflowAgentHost(deps) {
147
160
  schema: schemaPrep?.toolSchema,
148
161
  extraTools: schemaPrep ? [POLYPHASE_RESULT_TOOL_NAME] : undefined,
149
162
  extraSystemPrompt: schemaPrep ? STRUCTURED_OUTPUT_INSTRUCTION : undefined,
163
+ ...childPermissionContext(deps.ctx, deps.session, label),
150
164
  }),
151
165
  });
152
166
  inFlight.add(resultPromise);
@@ -1 +1 @@
1
- {"version":3,"file":"agent-host.js","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/agent-host.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAE3E,OAAO,EAAyB,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAGtG,OAAO,EAIN,qBAAqB,EACrB,0BAA0B,GAE1B,MAAM,aAAa,CAAC;AAGrB,OAAO,EAAE,mBAAmB,EAAE,6BAA6B,EAAE,MAAM,wBAAwB,CAAC;AAW5F,MAAM,6BAA6B,GAAgB;IAClD,IAAI,EAAE,gBAAgB;IACtB,WAAW,EAAE,0BAA0B;IACvC,YAAY,EACX,oHAAoH;IACrH,MAAM,EAAE,MAAM;CACd,CAAC;AAEF;;8EAE8E;AAC9E,SAAS,aAAa,CAAC,MAAc,EAAE,YAAgC,EAAE,QAAgB;IACxF,KAAK,MAAM,SAAS,IAAI,CAAC,MAAM,EAAE,YAAY,IAAI,EAAE,CAAC,EAAE,CAAC;QACtD,KAAK,MAAM,IAAI,IAAI,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,EAAE,CAAC;YAC1C,MAAM,OAAO,GAAG,IAAI,CAAC,IAAI,EAAE,CAAC;YAC5B,IAAI,OAAO;gBAAE,OAAO,OAAO,CAAC;QAC7B,CAAC;IACF,CAAC;IACD,OAAO,aAAa,QAAQ,EAAE,CAAC;AAChC,CAAC;AAED,+FAA+F;AAC/F,SAAS,gBAAgB,CAAC,MAAgC;IACzD,OAAO,MAAM,KAAK,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,MAAM,IAAI,KAAK,CAAC,CAAC;AACtD,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UAAU,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC;KACtE,CAAC;AACH,CAAC","sourcesContent":["/**\n * Bridges a workflow script's `agent()`/`phase()`/`log()` calls to real subagent runs (§14.3): one\n * `WorkflowHost` per run, created by `launch.ts` and handed to `runWorkflowScript`.\n */\n\nimport { discoverAgents, runSingleTask } from \"../../builtins/subagent.ts\";\nimport type { ExtensionContext } from \"../../extensions/types.ts\";\nimport { type ChildModelChoice, ModelSelectionError, resolveChildModel } from \"../model-selection.ts\";\nimport type { PolyphaseSession } from \"../session.ts\";\nimport type { PolyphaseRun } from \"../store.ts\";\nimport {\n\ttype AgentConfig,\n\ttype AgentRunner,\n\ttype CancelReason,\n\tcurrentPolyphaseDepth,\n\tPOLYPHASE_RESULT_TOOL_NAME,\n\ttype RunResult,\n} from \"../types.ts\";\nimport type { WorkflowMeta } from \"./meta.ts\";\nimport type { WorkflowAgentReply, WorkflowAgentRequest, WorkflowHost } from \"./runtime.ts\";\nimport { prepareResultSchema, STRUCTURED_OUTPUT_INSTRUCTION } from \"./structured-output.ts\";\n\nexport interface WorkflowAgentHostDeps {\n\tctx: ExtensionContext;\n\tsession: PolyphaseSession;\n\trun: PolyphaseRun;\n\tmeta: WorkflowMeta;\n\tmailbox: string;\n\trunner?: AgentRunner;\n}\n\nconst DEFAULT_WORKFLOW_AGENT_CONFIG: AgentConfig = {\n\tname: \"workflow-agent\",\n\tdescription: \"polyphase workflow agent\",\n\tsystemPrompt:\n\t\t\"You are an agent in a polyphase workflow. Do the task; your final message is returned to the orchestrating script.\",\n\tsource: \"user\",\n};\n\n/** First non-empty trimmed line of `stderr`, else `errorMessage`'s first non-empty trimmed line,\n * else `exit code N`: a stderr that is blank or starts with a bare newline (or a leading runtime\n * warning line) must not leave the failure log line with no detail at all. */\nfunction failureDetail(stderr: string, errorMessage: string | undefined, exitCode: number): string {\n\tfor (const candidate of [stderr, errorMessage ?? \"\"]) {\n\t\tfor (const line of candidate.split(\"\\n\")) {\n\t\t\tconst trimmed = line.trim();\n\t\t\tif (trimmed) return trimmed;\n\t\t}\n\t}\n\treturn `exit code ${exitCode}`;\n}\n\n/** `cancelReason \"user\"` reads as \"you\" in the log line; every other reason reads verbatim. */\nfunction cancelReasonText(reason: CancelReason | undefined): string {\n\treturn reason === \"user\" ? \"you\" : (reason ?? \"run\");\n}\n\nexport interface WorkflowAgentHost extends WorkflowHost {\n\t/** Resolves once every `runSingleTask` started by this host has settled; bounded by the child\n\t * kill grace period. Waiting on it after the script finishes (or throws) avoids returning while\n\t * an agent orphaned by a sandbox abort is still being torn down (DESIGN.md §13.3 \"Awaiting\"). */\n\tsettled(): Promise<void>;\n}\n\nexport function createWorkflowAgentHost(deps: WorkflowAgentHostDeps): WorkflowAgentHost {\n\tlet cachedAgents: Map<string, AgentConfig> | undefined;\n\tlet budgetNoticeLogged = false;\n\tconst agentTypeCounts = new Map<string, number>();\n\tconst usedLabels = new Set<string>();\n\tconst inFlight = new Set<Promise<unknown>>();\n\n\tfunction agentsByName(): Map<string, AgentConfig> {\n\t\tif (!cachedAgents) {\n\t\t\tcachedAgents = new Map(\n\t\t\t\tdiscoverAgents(deps.ctx.cwd, \"both\", deps.ctx.isProjectTrusted()).map((agent) => [agent.name, agent]),\n\t\t\t);\n\t\t}\n\t\treturn cachedAgents;\n\t}\n\n\t/** Dedupe within this run: an explicit label keeps its text until it collides, appending `#2`,\n\t * `#3`. A default label never collides by construction: its per-type counter advances past any\n\t * slot already in `usedLabels` (including one taken by an explicit label of the same text). */\n\tfunction nextLabel(explicit: string | undefined, agentTypeDisplay: string): string {\n\t\tconst text = explicit?.trim();\n\t\tif (!text) {\n\t\t\tlet n = agentTypeCounts.get(agentTypeDisplay) ?? 0;\n\t\t\tlet candidate: string;\n\t\t\tdo {\n\t\t\t\tn++;\n\t\t\t\tcandidate = `${agentTypeDisplay}#${n}`;\n\t\t\t} while (usedLabels.has(candidate));\n\t\t\tagentTypeCounts.set(agentTypeDisplay, n);\n\t\t\tusedLabels.add(candidate);\n\t\t\treturn candidate;\n\t\t}\n\t\tif (!usedLabels.has(text)) {\n\t\t\tusedLabels.add(text);\n\t\t\treturn text;\n\t\t}\n\t\tlet n = 2;\n\t\twhile (usedLabels.has(`${text}#${n}`)) n++;\n\t\tconst deduped = `${text}#${n}`;\n\t\tusedLabels.add(deduped);\n\t\treturn deduped;\n\t}\n\n\tasync function runAgent(request: WorkflowAgentRequest, signal: AbortSignal): Promise<WorkflowAgentReply> {\n\t\tif (deps.run.budget.exhausted) {\n\t\t\tif (!budgetNoticeLogged) {\n\t\t\t\tbudgetNoticeLogged = true;\n\t\t\t\tdeps.run.appendLog(\"budget exhausted; agent(...) returns null\", \"warning\");\n\t\t\t}\n\t\t\treturn { kind: \"null\", reason: \"budget\" };\n\t\t}\n\n\t\tlet agentTypeDisplay: string;\n\t\tlet config: AgentConfig;\n\t\tif (request.agentType) {\n\t\t\tconst found = agentsByName().get(request.agentType);\n\t\t\tif (!found) {\n\t\t\t\tconst available = [...agentsByName().keys()].sort().join(\", \");\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"error\",\n\t\t\t\t\tmessage: `unknown agentType \"${request.agentType}\"; available: ${available || \"(none)\"}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tagentTypeDisplay = request.agentType;\n\t\t\tconfig = found;\n\t\t} else {\n\t\t\tagentTypeDisplay = \"agent\";\n\t\t\tconfig = DEFAULT_WORKFLOW_AGENT_CONFIG;\n\t\t}\n\n\t\t// Side-effect-free lookup for the model step: declaring a phase permanently (and may log a\n\t\t// one-time warning) must wait until every other validation has passed, so a rejected agent()\n\t\t// call (bad agentType/model) never mutates the run as a side effect (DESIGN.md §14.3).\n\t\tconst declaredIndex =\n\t\t\trequest.phase === undefined\n\t\t\t\t? deps.run.currentPhase\n\t\t\t\t: deps.run.phases.findIndex((phase) => phase.title === request.phase);\n\t\tconst phaseModel =\n\t\t\tdeclaredIndex !== undefined && declaredIndex >= 0 ? deps.meta.phases[declaredIndex]?.model : undefined;\n\n\t\tlet choice: ChildModelChoice;\n\t\ttry {\n\t\t\tchoice = resolveChildModel({\n\t\t\t\toverride: request.model,\n\t\t\t\teffort: request.effort,\n\t\t\t\tphaseModel,\n\t\t\t\tagentModel: config.model,\n\t\t\t\tparentModel: deps.ctx.model,\n\t\t\t\tparentThinking: deps.ctx.thinkingLevel,\n\t\t\t\tavailable: deps.ctx.modelRegistry.getAvailable(),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof ModelSelectionError) return { kind: \"error\", message: error.message };\n\t\t\tthrow error;\n\t\t}\n\n\t\tconst schemaPrep = request.schema ? prepareResultSchema(request.schema) : undefined;\n\t\tconst label = nextLabel(request.label, agentTypeDisplay);\n\t\tconst phaseIndex = deps.run.resolvePhase(request.phase);\n\n\t\tconst live = deps.run.addAgent({\n\t\t\tlabel,\n\t\t\tagentType: agentTypeDisplay,\n\t\t\ttask: request.prompt,\n\t\t\tphase: phaseIndex,\n\t\t\tmodel: choice.info,\n\t\t});\n\n\t\tconst combined = AbortSignal.any([signal, live.signal]);\n\t\tsignal.addEventListener(\"abort\", () => live.cancel(\"run\"), { once: true });\n\n\t\tconst depth = currentPolyphaseDepth();\n\t\tconst maxDepth = deps.session.settings().maxDepth;\n\n\t\tconst resultPromise = runSingleTask(deps.ctx.cwd, config, request.prompt, {\n\t\t\tsignal: combined,\n\t\t\tworktree: request.isolation === \"worktree\",\n\t\t\trunner: deps.runner,\n\t\t\tresultMailbox: deps.mailbox,\n\t\t\tlimiter: deps.session.limiter,\n\t\t\trun: live.createRunContext({\n\t\t\t\tmodel: choice.modelArg,\n\t\t\t\tthinking: choice.thinking,\n\t\t\t\tmodelInfo: choice.info,\n\t\t\t\tfallbackToChildDefaultModel: choice.info.source === \"inherited\",\n\t\t\t\texcludeTools: depth + 1 >= maxDepth ? [\"subagent\"] : [],\n\t\t\t\tschema: schemaPrep?.toolSchema,\n\t\t\t\textraTools: schemaPrep ? [POLYPHASE_RESULT_TOOL_NAME] : undefined,\n\t\t\t\textraSystemPrompt: schemaPrep ? STRUCTURED_OUTPUT_INSTRUCTION : undefined,\n\t\t\t}),\n\t\t});\n\t\tinFlight.add(resultPromise);\n\t\tlet result: RunResult;\n\t\ttry {\n\t\t\tresult = await resultPromise;\n\t\t} finally {\n\t\t\tinFlight.delete(resultPromise);\n\t\t}\n\n\t\tif (result.merge && !result.merge.success) {\n\t\t\tdeps.run.appendLog(\n\t\t\t\t`${label} merge-back failed; work is on branch ${result.merge.branch ?? \"unknown\"}`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t}\n\n\t\tif (result.cancelled) {\n\t\t\tdeps.run.appendLog(`${label} skipped (cancelled by ${cancelReasonText(live.cancelReason)})`, \"info\");\n\t\t\treturn { kind: \"null\", reason: \"cancelled\" };\n\t\t}\n\t\tif (result.exitCode !== 0) {\n\t\t\tconst detail = failureDetail(result.stderr, live.state.errorMessage, result.exitCode);\n\t\t\tdeps.run.appendLog(`${label} failed: ${detail}`, \"warning\");\n\t\t\treturn { kind: \"null\", reason: \"failed\" };\n\t\t}\n\t\tif (request.schema && !result.structured) {\n\t\t\tdeps.run.appendLog(`${label} did not return structured output matching the schema`, \"warning\");\n\t\t\treturn { kind: \"null\", reason: \"no-structured-output\" };\n\t\t}\n\n\t\tconst value =\n\t\t\trequest.schema && schemaPrep && result.structured ? schemaPrep.unwrap(result.structured.value) : result.output;\n\t\treturn { kind: \"value\", value };\n\t}\n\n\treturn {\n\t\trunAgent,\n\t\tonPhase: (title) => deps.run.enterPhase(title),\n\t\tonLog: (text, level) => deps.run.appendLog(text, level),\n\t\tspentTokens: () => deps.run.spentTokens(),\n\t\tsettled: () => Promise.allSettled([...inFlight]).then(() => undefined),\n\t};\n}\n"]}
1
+ {"version":3,"file":"agent-host.js","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/agent-host.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,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,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC;QACvD,WAAW,EAAE,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,WAAW,EAAE;QACzC,OAAO,EAAE,GAAG,EAAE,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC;KACtE,CAAC;AACH,CAAC","sourcesContent":["/**\n * Bridges a workflow script's `agent()`/`phase()`/`log()` calls to real subagent runs (§14.3): one\n * `WorkflowHost` per run, created by `launch.ts` and handed to `runWorkflowScript`.\n */\n\nimport { childPermissionContext, discoverAgents, runSingleTask } from \"../../builtins/subagent.ts\";\nimport type { ExtensionContext } from \"../../extensions/types.ts\";\nimport { type ChildModelChoice, ModelSelectionError, resolveChildModel } from \"../model-selection.ts\";\nimport type { PolyphaseSession } from \"../session.ts\";\nimport type { PolyphaseRun } from \"../store.ts\";\nimport {\n\ttype AgentConfig,\n\ttype AgentRunner,\n\ttype CancelReason,\n\tcurrentPolyphaseDepth,\n\tPOLYPHASE_RESULT_TOOL_NAME,\n\ttype RunResult,\n} from \"../types.ts\";\nimport type { WorkflowMeta } from \"./meta.ts\";\nimport type { WorkflowAgentReply, WorkflowAgentRequest, WorkflowHost } from \"./runtime.ts\";\nimport { prepareResultSchema, STRUCTURED_OUTPUT_INSTRUCTION } from \"./structured-output.ts\";\n\nexport interface WorkflowAgentHostDeps {\n\tctx: ExtensionContext;\n\tsession: PolyphaseSession;\n\trun: PolyphaseRun;\n\tmeta: WorkflowMeta;\n\tmailbox: string;\n\trunner?: AgentRunner;\n}\n\nconst DEFAULT_WORKFLOW_AGENT_CONFIG: AgentConfig = {\n\tname: \"workflow-agent\",\n\tdescription: \"polyphase workflow agent\",\n\tsystemPrompt:\n\t\t\"You are an agent in a polyphase workflow. Do the task; your final message is returned to the orchestrating script.\",\n\tsource: \"user\",\n};\n\n/** First non-empty trimmed line of `stderr`, else `errorMessage`'s first non-empty trimmed line,\n * else `exit code N`: a stderr that is blank or starts with a bare newline (or a leading runtime\n * warning line) must not leave the failure log line with no detail at all. */\nfunction failureDetail(stderr: string, errorMessage: string | undefined, exitCode: number): string {\n\tfor (const candidate of [stderr, errorMessage ?? \"\"]) {\n\t\tfor (const line of candidate.split(\"\\n\")) {\n\t\t\tconst trimmed = line.trim();\n\t\t\tif (trimmed) return trimmed;\n\t\t}\n\t}\n\treturn `exit code ${exitCode}`;\n}\n\n/** `cancelReason \"user\"` reads as \"you\", \"time\" reads as \"time limit\" (matching the §D-B wording\n * used elsewhere), every other reason reads verbatim. */\nfunction cancelReasonText(reason: CancelReason | undefined): string {\n\tif (reason === \"user\") return \"you\";\n\tif (reason === \"time\") return \"time limit\";\n\treturn reason ?? \"run\";\n}\n\nexport interface WorkflowAgentHost extends WorkflowHost {\n\t/** Resolves once every `runSingleTask` started by this host has settled; bounded by the child\n\t * kill grace period. Waiting on it after the script finishes (or throws) avoids returning while\n\t * an agent orphaned by a sandbox abort is still being torn down (DESIGN.md §13.3 \"Awaiting\"). */\n\tsettled(): Promise<void>;\n}\n\nexport function createWorkflowAgentHost(deps: WorkflowAgentHostDeps): WorkflowAgentHost {\n\tlet cachedAgents: Map<string, AgentConfig> | undefined;\n\tlet budgetNoticeLogged = false;\n\tlet timeLimitNoticeLogged = false;\n\tconst agentTypeCounts = new Map<string, number>();\n\tconst usedLabels = new Set<string>();\n\tconst inFlight = new Set<Promise<unknown>>();\n\n\tfunction agentsByName(): Map<string, AgentConfig> {\n\t\tif (!cachedAgents) {\n\t\t\tcachedAgents = new Map(\n\t\t\t\tdiscoverAgents(deps.ctx.cwd, \"both\", deps.ctx.isProjectTrusted()).map((agent) => [agent.name, agent]),\n\t\t\t);\n\t\t}\n\t\treturn cachedAgents;\n\t}\n\n\t/** Dedupe within this run: an explicit label keeps its text until it collides, appending `#2`,\n\t * `#3`. A default label never collides by construction: its per-type counter advances past any\n\t * slot already in `usedLabels` (including one taken by an explicit label of the same text). */\n\tfunction nextLabel(explicit: string | undefined, agentTypeDisplay: string): string {\n\t\tconst text = explicit?.trim();\n\t\tif (!text) {\n\t\t\tlet n = agentTypeCounts.get(agentTypeDisplay) ?? 0;\n\t\t\tlet candidate: string;\n\t\t\tdo {\n\t\t\t\tn++;\n\t\t\t\tcandidate = `${agentTypeDisplay}#${n}`;\n\t\t\t} while (usedLabels.has(candidate));\n\t\t\tagentTypeCounts.set(agentTypeDisplay, n);\n\t\t\tusedLabels.add(candidate);\n\t\t\treturn candidate;\n\t\t}\n\t\tif (!usedLabels.has(text)) {\n\t\t\tusedLabels.add(text);\n\t\t\treturn text;\n\t\t}\n\t\tlet n = 2;\n\t\twhile (usedLabels.has(`${text}#${n}`)) n++;\n\t\tconst deduped = `${text}#${n}`;\n\t\tusedLabels.add(deduped);\n\t\treturn deduped;\n\t}\n\n\tasync function runAgent(request: WorkflowAgentRequest, signal: AbortSignal): Promise<WorkflowAgentReply> {\n\t\tif (deps.run.budget.exhausted) {\n\t\t\tif (!budgetNoticeLogged) {\n\t\t\t\tbudgetNoticeLogged = true;\n\t\t\t\tdeps.run.appendLog(\"budget exhausted; agent(...) returns null\", \"warning\");\n\t\t\t}\n\t\t\treturn { kind: \"null\", reason: \"budget\" };\n\t\t}\n\t\tif (deps.run.timeLimit.reached) {\n\t\t\tif (!timeLimitNoticeLogged) {\n\t\t\t\ttimeLimitNoticeLogged = true;\n\t\t\t\tdeps.run.appendLog(\"time limit reached; agent(...) returns null\", \"warning\");\n\t\t\t}\n\t\t\treturn { kind: \"null\", reason: \"time\" };\n\t\t}\n\n\t\tlet agentTypeDisplay: string;\n\t\tlet config: AgentConfig;\n\t\tif (request.agentType) {\n\t\t\tconst found = agentsByName().get(request.agentType);\n\t\t\tif (!found) {\n\t\t\t\tconst available = [...agentsByName().keys()].sort().join(\", \");\n\t\t\t\treturn {\n\t\t\t\t\tkind: \"error\",\n\t\t\t\t\tmessage: `unknown agentType \"${request.agentType}\"; available: ${available || \"(none)\"}`,\n\t\t\t\t};\n\t\t\t}\n\t\t\tagentTypeDisplay = request.agentType;\n\t\t\tconfig = found;\n\t\t} else {\n\t\t\tagentTypeDisplay = \"agent\";\n\t\t\tconfig = DEFAULT_WORKFLOW_AGENT_CONFIG;\n\t\t}\n\n\t\t// Side-effect-free lookup for the model step: declaring a phase permanently (and may log a\n\t\t// one-time warning) must wait until every other validation has passed, so a rejected agent()\n\t\t// call (bad agentType/model) never mutates the run as a side effect (DESIGN.md §14.3).\n\t\tconst declaredIndex =\n\t\t\trequest.phase === undefined\n\t\t\t\t? deps.run.currentPhase\n\t\t\t\t: deps.run.phases.findIndex((phase) => phase.title === request.phase);\n\t\tconst phaseModel =\n\t\t\tdeclaredIndex !== undefined && declaredIndex >= 0 ? deps.meta.phases[declaredIndex]?.model : undefined;\n\n\t\tlet choice: ChildModelChoice;\n\t\ttry {\n\t\t\tchoice = resolveChildModel({\n\t\t\t\toverride: request.model,\n\t\t\t\teffort: request.effort,\n\t\t\t\tphaseModel,\n\t\t\t\tagentModel: config.model,\n\t\t\t\tparentModel: deps.ctx.model,\n\t\t\t\tparentThinking: deps.ctx.thinkingLevel,\n\t\t\t\tavailable: deps.ctx.modelRegistry.getAvailable(),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tif (error instanceof ModelSelectionError) return { kind: \"error\", message: error.message };\n\t\t\tthrow error;\n\t\t}\n\n\t\tconst schemaPrep = request.schema ? prepareResultSchema(request.schema) : undefined;\n\t\tconst label = nextLabel(request.label, agentTypeDisplay);\n\t\tconst phaseIndex = deps.run.resolvePhase(request.phase);\n\n\t\tconst live = deps.run.addAgent({\n\t\t\tlabel,\n\t\t\tagentType: agentTypeDisplay,\n\t\t\ttask: request.prompt,\n\t\t\tphase: phaseIndex,\n\t\t\tmodel: choice.info,\n\t\t});\n\n\t\tconst combined = AbortSignal.any([signal, live.signal]);\n\t\tsignal.addEventListener(\"abort\", () => live.cancel(\"run\"), { once: true });\n\n\t\tconst depth = currentPolyphaseDepth();\n\t\tconst maxDepth = deps.session.settings().maxDepth;\n\n\t\tconst resultPromise = runSingleTask(deps.ctx.cwd, config, request.prompt, {\n\t\t\tsignal: combined,\n\t\t\tworktree: request.isolation === \"worktree\",\n\t\t\trunner: deps.runner,\n\t\t\tresultMailbox: deps.mailbox,\n\t\t\tlimiter: deps.session.limiter,\n\t\t\trun: live.createRunContext({\n\t\t\t\tmodel: choice.modelArg,\n\t\t\t\tthinking: choice.thinking,\n\t\t\t\tmodelInfo: choice.info,\n\t\t\t\tfallbackToChildDefaultModel: choice.info.source === \"inherited\",\n\t\t\t\texcludeTools: depth + 1 >= maxDepth ? [\"subagent\"] : [],\n\t\t\t\tschema: schemaPrep?.toolSchema,\n\t\t\t\textraTools: schemaPrep ? [POLYPHASE_RESULT_TOOL_NAME] : undefined,\n\t\t\t\textraSystemPrompt: schemaPrep ? STRUCTURED_OUTPUT_INSTRUCTION : undefined,\n\t\t\t\t...childPermissionContext(deps.ctx, deps.session, label),\n\t\t\t}),\n\t\t});\n\t\tinFlight.add(resultPromise);\n\t\tlet result: RunResult;\n\t\ttry {\n\t\t\tresult = await resultPromise;\n\t\t} finally {\n\t\t\tinFlight.delete(resultPromise);\n\t\t}\n\n\t\tif (result.merge && !result.merge.success) {\n\t\t\tdeps.run.appendLog(\n\t\t\t\t`${label} merge-back failed; work is on branch ${result.merge.branch ?? \"unknown\"}`,\n\t\t\t\t\"warning\",\n\t\t\t);\n\t\t}\n\n\t\tif (result.cancelled) {\n\t\t\tdeps.run.appendLog(`${label} skipped (cancelled by ${cancelReasonText(live.cancelReason)})`, \"info\");\n\t\t\treturn { kind: \"null\", reason: \"cancelled\" };\n\t\t}\n\t\tif (result.exitCode !== 0) {\n\t\t\tconst detail = failureDetail(result.stderr, live.state.errorMessage, result.exitCode);\n\t\t\tdeps.run.appendLog(`${label} failed: ${detail}`, \"warning\");\n\t\t\treturn { kind: \"null\", reason: \"failed\" };\n\t\t}\n\t\tif (request.schema && !result.structured) {\n\t\t\tdeps.run.appendLog(`${label} did not return structured output matching the schema`, \"warning\");\n\t\t\treturn { kind: \"null\", reason: \"no-structured-output\" };\n\t\t}\n\n\t\tconst value =\n\t\t\trequest.schema && schemaPrep && result.structured ? schemaPrep.unwrap(result.structured.value) : result.output;\n\t\treturn { kind: \"value\", value };\n\t}\n\n\treturn {\n\t\trunAgent,\n\t\tonPhase: (title) => deps.run.enterPhase(title),\n\t\tonLog: (text, level) => deps.run.appendLog(text, level),\n\t\tspentTokens: () => deps.run.spentTokens(),\n\t\tsettled: () => Promise.allSettled([...inFlight]).then(() => undefined),\n\t};\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"guidance.d.ts","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/guidance.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,eAAO,MAAM,yBAAyB,QAgB2C,CAAC;AAElF,eAAO,MAAM,uBAAuB,+FACyD,CAAC;AAE9F,eAAO,MAAM,0BAA0B,EAAE,SAAS,MAAM,EAKvD,CAAC;AAEF,MAAM,WAAW,mBAAmB;IACnC,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;IAC9B,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;IAC9B,MAAM,EAAE;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC;CACrE;AAED,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,mBAAmB,GAAG,MAAM,CA0FtE"}
1
+ {"version":3,"file":"guidance.d.ts","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/guidance.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,eAAO,MAAM,yBAAyB,QAmBqC,CAAC;AAE5E,eAAO,MAAM,uBAAuB,+FACyD,CAAC;AAE9F,eAAO,MAAM,0BAA0B,EAAE,SAAS,MAAM,EAKvD,CAAC;AAEF,MAAM,WAAW,mBAAmB;IACnC,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;IAC9B,UAAU,EAAE,SAAS,MAAM,EAAE,CAAC;IAC9B,MAAM,EAAE;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC;CACrE;AAED,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,mBAAmB,GAAG,MAAM,CAkGtE"}
@@ -18,12 +18,15 @@ export const WORKFLOW_TOOL_DESCRIPTION = "Runs a workflow script that orchestrat
18
18
  "args, budget, meta. Math.random, Date.now, Date() and new Date() throw; new Date(value) works. " +
19
19
  "No workflow can start another workflow.\n\n" +
20
20
  "Call this tool with either `script` (a new script) or `name` (a saved workflow). Set `args` " +
21
- "for the script's input string and `budgetTokens` to cap total billable tokens.";
21
+ "for the script's input string. Set `budgetTokens` (a token count) and/or `timeLimit` (a " +
22
+ 'duration string, e.g. "30min", "2h") ONLY when the user stated a limit in words (e.g. "at ' +
23
+ 'most 300k tokens", "stop after 20 minutes"); never invent one. Without a stated limit, leave ' +
24
+ "both unset and write the script to stop on its own once the goal is met.";
22
25
  export const WORKFLOW_PROMPT_SNIPPET = "Run a multi-agent workflow script (phases, parallel agents, pipelines) with live oversight";
23
26
  export const WORKFLOW_PROMPT_GUIDELINES = [
24
27
  "Use the workflow tool for multi-phase tasks that benefit from several subagents running in parallel or in a pipeline, with live oversight in the TUI.",
25
28
  "Write `export const meta = {...}` first, as a plain literal (no identifiers, calls, or template-literal interpolation), then an async body using agent, parallel, pipeline, phase, log, args and budget.",
26
- "Each agent() call is a separate paid model session that cannot ask for permissions; give it a self-contained task and ask it to end with a STATUS line.",
29
+ "Each agent() call is a separate paid model session that cannot see this conversation; give it a self-contained task and ask it to end with a STATUS line. Its tool calls run under this session's permission mode; one that still needs approval is asked in this session, or blocked when nobody can answer.",
27
30
  "agent() returns null on failure, cancellation, or budget exhaustion; always check for null before using the result.",
28
31
  ];
29
32
  export function buildAuthoringGuide(input) {
@@ -82,15 +85,23 @@ new Date(value) still works. Never redeclare: agent, parallel, pipeline, phase,
82
85
 
83
86
  ## 4. Each agent is a separate paid session
84
87
 
85
- Every agent() call spawns an independent subagent process. It cannot ask for permissions or see
86
- anything outside its own prompt, so give it a self-contained task and ask it to end with a
87
- STATUS: line you can look for in its output.
88
+ Every agent() call spawns an independent subagent process. It cannot see anything outside its own
89
+ prompt, so give it a self-contained task and ask it to end with a STATUS: line you can look for in
90
+ its output. Its tool calls run under this session's permission mode; one that still needs approval
91
+ is asked in this session (the agent waits for the answer), or blocked when nobody can answer.
88
92
 
89
93
  ## 5. Limits
90
94
 
91
95
  - Up to ${input.limits.concurrency} agents run at once in this session.
92
96
  - Up to ${input.limits.maxAgents} agent() calls total in one workflow run.
93
97
  - Up to ${input.limits.maxItems} items per parallel()/pipeline() call.
98
+ - The token budget and time limit come from the user's own prompt (e.g. "+500k", "+30min" as a
99
+ standalone word), else the tool's \`budgetTokens\`/\`timeLimit\` parameters (set these only when
100
+ the user stated a limit in words), else config, else no limit at all: the run keeps going until
101
+ the script returns. Design scripts with no stated limit to stop on their own once the goal is
102
+ met (e.g. loop until a verifier agent reports success), not on an arbitrary iteration count.
103
+ \`agent()\` also returns \`null\` once the time limit is reached (in addition to failure,
104
+ cancellation, and budget exhaustion) -- the same null check for all of them is enough.
94
105
 
95
106
  ## 6. Available agent types
96
107
 
@@ -1 +1 @@
1
- {"version":3,"file":"guidance.js","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/guidance.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,MAAM,CAAC,MAAM,yBAAyB,GACrC,6FAA6F;IAC7F,oFAAoF;IACpF,0FAA0F;IAC1F,0FAA0F;IAC1F,4GAA4G;IAC5G,mDAAmD;IACnD,sEAAsE;IACtE,qEAAqE;IACrE,iDAAiD;IACjD,6FAA6F;IAC7F,+FAA+F;IAC/F,8FAA8F;IAC9F,iGAAiG;IACjG,6CAA6C;IAC7C,8FAA8F;IAC9F,gFAAgF,CAAC;AAElF,MAAM,CAAC,MAAM,uBAAuB,GACnC,4FAA4F,CAAC;AAE9F,MAAM,CAAC,MAAM,0BAA0B,GAAsB;IAC5D,uJAAuJ;IACvJ,0MAA0M;IAC1M,yJAAyJ;IACzJ,qHAAqH;CACrH,CAAC;AAQF,MAAM,UAAU,mBAAmB,CAAC,KAA0B;IAC7D,MAAM,cAAc,GAAG,KAAK,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,mBAAmB,CAAC;IACvG,MAAM,cAAc,GAAG,KAAK,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC;IAElG,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA2DE,KAAK,CAAC,MAAM,CAAC,WAAW;UACxB,KAAK,CAAC,MAAM,CAAC,SAAS;UACtB,KAAK,CAAC,MAAM,CAAC,QAAQ;;;;EAI7B,cAAc;;;;EAId,cAAc;;;;;;;;;;;;;;;;CAgBf,CAAC;AACF,CAAC","sourcesContent":["/**\n * Model-facing text for the `workflow` tool (§14.5): the tool description, prompt snippet and\n * guidelines shown while the tool is active, and the longer authoring guide sent once when the\n * keyword first enables it.\n */\n\nexport const WORKFLOW_TOOL_DESCRIPTION =\n\t\"Runs a workflow script that orchestrates one or more subagents through a multi-phase task, \" +\n\t\"with live oversight in the TUI (a running-agents dock and an agent inspector).\\n\\n\" +\n\t\"The script is plain JavaScript with no imports. It must start with `export const meta = \" +\n\t\"{ name, description, phases: [{ title, detail?, model? }, ...] }` as a pure literal (no \" +\n\t\"identifiers, calls, spreads, computed keys or template-literal interpolation), then an async body using:\\n\" +\n\t\" agent(prompt, opts) -> string | object | null\\n\" +\n\t\" parallel(thunks) -> array (barrier; a failed thunk becomes null)\\n\" +\n\t\" pipeline(items, ...stages) -> array (no barrier between stages)\\n\" +\n\t\" phase(title), log(...parts), args, budget\\n\\n\" +\n\t\"agent() returns null when the agent failed, was cancelled, or produced no valid structured \" +\n\t\"output. It throws for invalid options, an unknown agentType/model, an invalid effort, or the \" +\n\t\"per-run agent cap. Reserved names (never redeclare): agent, parallel, pipeline, phase, log, \" +\n\t\"args, budget, meta. Math.random, Date.now, Date() and new Date() throw; new Date(value) works. \" +\n\t\"No workflow can start another workflow.\\n\\n\" +\n\t\"Call this tool with either `script` (a new script) or `name` (a saved workflow). Set `args` \" +\n\t\"for the script's input string and `budgetTokens` to cap total billable tokens.\";\n\nexport const WORKFLOW_PROMPT_SNIPPET =\n\t\"Run a multi-agent workflow script (phases, parallel agents, pipelines) with live oversight\";\n\nexport const WORKFLOW_PROMPT_GUIDELINES: readonly string[] = [\n\t\"Use the workflow tool for multi-phase tasks that benefit from several subagents running in parallel or in a pipeline, with live oversight in the TUI.\",\n\t\"Write `export const meta = {...}` first, as a plain literal (no identifiers, calls, or template-literal interpolation), then an async body using agent, parallel, pipeline, phase, log, args and budget.\",\n\t\"Each agent() call is a separate paid model session that cannot ask for permissions; give it a self-contained task and ask it to end with a STATUS line.\",\n\t\"agent() returns null on failure, cancellation, or budget exhaustion; always check for null before using the result.\",\n];\n\nexport interface AuthoringGuideInput {\n\tagentTypes: readonly string[];\n\tsavedNames: readonly string[];\n\tlimits: { concurrency: number; maxAgents: number; maxItems: number };\n}\n\nexport function buildAuthoringGuide(input: AuthoringGuideInput): string {\n\tconst agentTypesLine = input.agentTypes.length > 0 ? input.agentTypes.join(\", \") : \"(none discovered)\";\n\tconst savedNamesLine = input.savedNames.length > 0 ? input.savedNames.join(\", \") : \"(none saved)\";\n\n\treturn `# Writing a polyphase workflow\n\nA workflow script is plain JavaScript. It runs in a sandbox with no imports and no filesystem or\nnetwork access of its own -- all real work happens inside the subagents it starts with agent().\n\n## 1. The meta block comes first\n\n\\`\\`\\`js\nexport const meta = {\n name: \"review-pr\", // ^[a-z][a-z0-9-]{0,47}$, used for /review-pr if you save it\n description: \"Review a change in parallel and synthesize findings\", // 1-300 chars\n whenToUse: \"...\", // optional, <= 300 chars\n phases: [ // 1-20 entries\n { title: \"Scan\" },\n { title: \"Review\" },\n { title: \"Synthesize\", model: \"anthropic/claude-opus-5-5\" }, // optional per-phase model\n ],\n};\n\\`\\`\\`\n\nmeta must be a pure literal: no identifiers, function calls, spreads, computed keys, template\ninterpolation (\\${...}), or regex literals. Unknown keys are warnings, not errors.\n\n## 2. The API\n\n- \\`agent(prompt, opts)\\` starts one subagent and returns its final text, or the schema-validated\n object when \\`opts.schema\\` is set. It returns \\`null\\` when the agent failed, was cancelled (by\n the user or the token budget), the budget was already exhausted, or no valid structured output\n was produced -- always check for null. It throws for invalid options, an unknown model/agentType,\n an invalid effort, or hitting the per-run agent cap.\n opts: { label, phase, schema, model, effort, isolation: \"worktree\", agentType }\n- \\`parallel(thunks)\\` runs an array of zero-argument thunks (each should call agent()) and waits\n for all of them (a barrier). A thunk that throws becomes null in the result array, with a\n warning logged; parallel() itself never rejects.\n- \\`pipeline(items, ...stages)\\` runs each item through the same stages in sequence, with no\n barrier between stages: each stage \\`(prev, item, index)\\` receives the previous stage's result\n (or the item itself, for the first stage). A throwing stage makes that item null and skips its\n later stages for that item.\n- \\`phase(title)\\` groups the agents started after it under that phase for the live view. Titles\n not declared in meta.phases become dynamic phases, logged once.\n- \\`log(...parts)\\` writes a narrator line visible in the dock and inspector.\n- \\`args\\` is the verbatim string passed to this call (or to /<name>). \\`meta\\` is the frozen meta\n object.\n- \\`budget\\`: { total, spent(), remaining() }. spent() is this run's total billable tokens as of\n the latest agent() reply.\n\n## 3. Determinism and reserved names\n\nMath.random, Date.now, Date() and new Date() all throw -- workflows must be deterministic.\nnew Date(value) still works. Never redeclare: agent, parallel, pipeline, phase, log, args, budget, meta.\n\n## 4. Each agent is a separate paid session\n\nEvery agent() call spawns an independent subagent process. It cannot ask for permissions or see\nanything outside its own prompt, so give it a self-contained task and ask it to end with a\nSTATUS: line you can look for in its output.\n\n## 5. Limits\n\n- Up to ${input.limits.concurrency} agents run at once in this session.\n- Up to ${input.limits.maxAgents} agent() calls total in one workflow run.\n- Up to ${input.limits.maxItems} items per parallel()/pipeline() call.\n\n## 6. Available agent types\n\n${agentTypesLine}\n\n## 7. Saved workflows\n\n${savedNamesLine}\n\n## Example\n\n\\`\\`\\`js\nexport const meta = { name: \"review-pr\", description: \"Review a change in parallel and synthesize findings\",\n phases: [{ title: \"Scan\" }, { title: \"Review\" }, { title: \"Synthesize\", model: \"anthropic/claude-opus-5-5\" }] };\nphase(\"Scan\");\nconst scan = await agent(\\`List the areas touched by \\${args}\\`, { label: \"scan\",\n schema: { type: \"object\", properties: { areas: { type: \"array\", items: { type: \"string\" } } }, required: [\"areas\"] } });\nphase(\"Review\");\nconst reviews = await parallel((scan?.areas ?? []).map((area) => () =>\n agent(\\`Review \\${area} for \\${args}. End with a STATUS line.\\`, { label: \\`review:\\${area}\\`, agentType: \"reviewer\" })));\nphase(\"Synthesize\");\nreturn await agent(\\`Synthesize these reviews:\\\\n\\${reviews.filter(Boolean).join(\"\\\\n---\\\\n\")}\\`, { label: \"synthesize\" });\n\\`\\`\\`\n`;\n}\n"]}
1
+ {"version":3,"file":"guidance.js","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/guidance.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,MAAM,CAAC,MAAM,yBAAyB,GACrC,6FAA6F;IAC7F,oFAAoF;IACpF,0FAA0F;IAC1F,0FAA0F;IAC1F,4GAA4G;IAC5G,mDAAmD;IACnD,sEAAsE;IACtE,qEAAqE;IACrE,iDAAiD;IACjD,6FAA6F;IAC7F,+FAA+F;IAC/F,8FAA8F;IAC9F,iGAAiG;IACjG,6CAA6C;IAC7C,8FAA8F;IAC9F,0FAA0F;IAC1F,4FAA4F;IAC5F,+FAA+F;IAC/F,0EAA0E,CAAC;AAE5E,MAAM,CAAC,MAAM,uBAAuB,GACnC,4FAA4F,CAAC;AAE9F,MAAM,CAAC,MAAM,0BAA0B,GAAsB;IAC5D,uJAAuJ;IACvJ,0MAA0M;IAC1M,+SAA+S;IAC/S,qHAAqH;CACrH,CAAC;AAQF,MAAM,UAAU,mBAAmB,CAAC,KAA0B;IAC7D,MAAM,cAAc,GAAG,KAAK,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,mBAAmB,CAAC;IACvG,MAAM,cAAc,GAAG,KAAK,CAAC,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,cAAc,CAAC;IAElG,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA4DE,KAAK,CAAC,MAAM,CAAC,WAAW;UACxB,KAAK,CAAC,MAAM,CAAC,SAAS;UACtB,KAAK,CAAC,MAAM,CAAC,QAAQ;;;;;;;;;;;EAW7B,cAAc;;;;EAId,cAAc;;;;;;;;;;;;;;;;CAgBf,CAAC;AACF,CAAC","sourcesContent":["/**\n * Model-facing text for the `workflow` tool (§14.5): the tool description, prompt snippet and\n * guidelines shown while the tool is active, and the longer authoring guide sent once when the\n * keyword first enables it.\n */\n\nexport const WORKFLOW_TOOL_DESCRIPTION =\n\t\"Runs a workflow script that orchestrates one or more subagents through a multi-phase task, \" +\n\t\"with live oversight in the TUI (a running-agents dock and an agent inspector).\\n\\n\" +\n\t\"The script is plain JavaScript with no imports. It must start with `export const meta = \" +\n\t\"{ name, description, phases: [{ title, detail?, model? }, ...] }` as a pure literal (no \" +\n\t\"identifiers, calls, spreads, computed keys or template-literal interpolation), then an async body using:\\n\" +\n\t\" agent(prompt, opts) -> string | object | null\\n\" +\n\t\" parallel(thunks) -> array (barrier; a failed thunk becomes null)\\n\" +\n\t\" pipeline(items, ...stages) -> array (no barrier between stages)\\n\" +\n\t\" phase(title), log(...parts), args, budget\\n\\n\" +\n\t\"agent() returns null when the agent failed, was cancelled, or produced no valid structured \" +\n\t\"output. It throws for invalid options, an unknown agentType/model, an invalid effort, or the \" +\n\t\"per-run agent cap. Reserved names (never redeclare): agent, parallel, pipeline, phase, log, \" +\n\t\"args, budget, meta. Math.random, Date.now, Date() and new Date() throw; new Date(value) works. \" +\n\t\"No workflow can start another workflow.\\n\\n\" +\n\t\"Call this tool with either `script` (a new script) or `name` (a saved workflow). Set `args` \" +\n\t\"for the script's input string. Set `budgetTokens` (a token count) and/or `timeLimit` (a \" +\n\t'duration string, e.g. \"30min\", \"2h\") ONLY when the user stated a limit in words (e.g. \"at ' +\n\t'most 300k tokens\", \"stop after 20 minutes\"); never invent one. Without a stated limit, leave ' +\n\t\"both unset and write the script to stop on its own once the goal is met.\";\n\nexport const WORKFLOW_PROMPT_SNIPPET =\n\t\"Run a multi-agent workflow script (phases, parallel agents, pipelines) with live oversight\";\n\nexport const WORKFLOW_PROMPT_GUIDELINES: readonly string[] = [\n\t\"Use the workflow tool for multi-phase tasks that benefit from several subagents running in parallel or in a pipeline, with live oversight in the TUI.\",\n\t\"Write `export const meta = {...}` first, as a plain literal (no identifiers, calls, or template-literal interpolation), then an async body using agent, parallel, pipeline, phase, log, args and budget.\",\n\t\"Each agent() call is a separate paid model session that cannot see this conversation; give it a self-contained task and ask it to end with a STATUS line. Its tool calls run under this session's permission mode; one that still needs approval is asked in this session, or blocked when nobody can answer.\",\n\t\"agent() returns null on failure, cancellation, or budget exhaustion; always check for null before using the result.\",\n];\n\nexport interface AuthoringGuideInput {\n\tagentTypes: readonly string[];\n\tsavedNames: readonly string[];\n\tlimits: { concurrency: number; maxAgents: number; maxItems: number };\n}\n\nexport function buildAuthoringGuide(input: AuthoringGuideInput): string {\n\tconst agentTypesLine = input.agentTypes.length > 0 ? input.agentTypes.join(\", \") : \"(none discovered)\";\n\tconst savedNamesLine = input.savedNames.length > 0 ? input.savedNames.join(\", \") : \"(none saved)\";\n\n\treturn `# Writing a polyphase workflow\n\nA workflow script is plain JavaScript. It runs in a sandbox with no imports and no filesystem or\nnetwork access of its own -- all real work happens inside the subagents it starts with agent().\n\n## 1. The meta block comes first\n\n\\`\\`\\`js\nexport const meta = {\n name: \"review-pr\", // ^[a-z][a-z0-9-]{0,47}$, used for /review-pr if you save it\n description: \"Review a change in parallel and synthesize findings\", // 1-300 chars\n whenToUse: \"...\", // optional, <= 300 chars\n phases: [ // 1-20 entries\n { title: \"Scan\" },\n { title: \"Review\" },\n { title: \"Synthesize\", model: \"anthropic/claude-opus-5-5\" }, // optional per-phase model\n ],\n};\n\\`\\`\\`\n\nmeta must be a pure literal: no identifiers, function calls, spreads, computed keys, template\ninterpolation (\\${...}), or regex literals. Unknown keys are warnings, not errors.\n\n## 2. The API\n\n- \\`agent(prompt, opts)\\` starts one subagent and returns its final text, or the schema-validated\n object when \\`opts.schema\\` is set. It returns \\`null\\` when the agent failed, was cancelled (by\n the user or the token budget), the budget was already exhausted, or no valid structured output\n was produced -- always check for null. It throws for invalid options, an unknown model/agentType,\n an invalid effort, or hitting the per-run agent cap.\n opts: { label, phase, schema, model, effort, isolation: \"worktree\", agentType }\n- \\`parallel(thunks)\\` runs an array of zero-argument thunks (each should call agent()) and waits\n for all of them (a barrier). A thunk that throws becomes null in the result array, with a\n warning logged; parallel() itself never rejects.\n- \\`pipeline(items, ...stages)\\` runs each item through the same stages in sequence, with no\n barrier between stages: each stage \\`(prev, item, index)\\` receives the previous stage's result\n (or the item itself, for the first stage). A throwing stage makes that item null and skips its\n later stages for that item.\n- \\`phase(title)\\` groups the agents started after it under that phase for the live view. Titles\n not declared in meta.phases become dynamic phases, logged once.\n- \\`log(...parts)\\` writes a narrator line visible in the dock and inspector.\n- \\`args\\` is the verbatim string passed to this call (or to /<name>). \\`meta\\` is the frozen meta\n object.\n- \\`budget\\`: { total, spent(), remaining() }. spent() is this run's total billable tokens as of\n the latest agent() reply.\n\n## 3. Determinism and reserved names\n\nMath.random, Date.now, Date() and new Date() all throw -- workflows must be deterministic.\nnew Date(value) still works. Never redeclare: agent, parallel, pipeline, phase, log, args, budget, meta.\n\n## 4. Each agent is a separate paid session\n\nEvery agent() call spawns an independent subagent process. It cannot see anything outside its own\nprompt, so give it a self-contained task and ask it to end with a STATUS: line you can look for in\nits output. Its tool calls run under this session's permission mode; one that still needs approval\nis asked in this session (the agent waits for the answer), or blocked when nobody can answer.\n\n## 5. Limits\n\n- Up to ${input.limits.concurrency} agents run at once in this session.\n- Up to ${input.limits.maxAgents} agent() calls total in one workflow run.\n- Up to ${input.limits.maxItems} items per parallel()/pipeline() call.\n- The token budget and time limit come from the user's own prompt (e.g. \"+500k\", \"+30min\" as a\n standalone word), else the tool's \\`budgetTokens\\`/\\`timeLimit\\` parameters (set these only when\n the user stated a limit in words), else config, else no limit at all: the run keeps going until\n the script returns. Design scripts with no stated limit to stop on their own once the goal is\n met (e.g. loop until a verifier agent reports success), not on an arbitrary iteration count.\n \\`agent()\\` also returns \\`null\\` once the time limit is reached (in addition to failure,\n cancellation, and budget exhaustion) -- the same null check for all of them is enough.\n\n## 6. Available agent types\n\n${agentTypesLine}\n\n## 7. Saved workflows\n\n${savedNamesLine}\n\n## Example\n\n\\`\\`\\`js\nexport const meta = { name: \"review-pr\", description: \"Review a change in parallel and synthesize findings\",\n phases: [{ title: \"Scan\" }, { title: \"Review\" }, { title: \"Synthesize\", model: \"anthropic/claude-opus-5-5\" }] };\nphase(\"Scan\");\nconst scan = await agent(\\`List the areas touched by \\${args}\\`, { label: \"scan\",\n schema: { type: \"object\", properties: { areas: { type: \"array\", items: { type: \"string\" } } }, required: [\"areas\"] } });\nphase(\"Review\");\nconst reviews = await parallel((scan?.areas ?? []).map((area) => () =>\n agent(\\`Review \\${area} for \\${args}. End with a STATUS line.\\`, { label: \\`review:\\${area}\\`, agentType: \"reviewer\" })));\nphase(\"Synthesize\");\nreturn await agent(\\`Synthesize these reviews:\\\\n\\${reviews.filter(Boolean).join(\"\\\\n---\\\\n\")}\\`, { label: \"synthesize\" });\n\\`\\`\\`\n`;\n}\n"]}
@@ -7,6 +7,7 @@ import type { ExtensionContext } from "../../extensions/types.ts";
7
7
  import type { PolyphaseSession } from "../session.ts";
8
8
  import type { PolyphaseRun } from "../store.ts";
9
9
  import type { AgentRunner, PolyphaseDetails, RunOrigin, WorkflowSource } from "../types.ts";
10
+ import { type ResolvedWorkflowLimits } from "./limits.ts";
10
11
  import type { WorkflowMeta } from "./meta.ts";
11
12
  import type { WorkflowOutcome } from "./runtime.ts";
12
13
  export interface StartWorkflowRunOptions {
@@ -22,7 +23,7 @@ export interface StartWorkflowRunOptions {
22
23
  kind: WorkflowSource;
23
24
  path?: string;
24
25
  };
25
- budgetTokens: number | null;
26
+ limits: ResolvedWorkflowLimits;
26
27
  runner?: AgentRunner;
27
28
  }
28
29
  export interface WorkflowRunCompletion {
@@ -1 +1 @@
1
- {"version":3,"file":"launch.d.ts","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/launch.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,WAAW,CAAC;AAEvC,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,2BAA2B,CAAC;AAGlE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAChD,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,SAAS,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAE5F,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAE9C,OAAO,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unUsage } from "../details.js";
7
7
  import { formatWorkflowResultText } from "../result-text.js";
8
8
  import { createWorkflowAgentHost } from "./agent-host.js";
9
+ import { formatWorkflowLimitsLine, hardSandboxTimeoutMs } from "./limits.js";
9
10
  import { loadWorkflowRuntime } from "./runtime.lazy.js";
10
11
  const RESULT_PREVIEW_MAX_CHARS = 400;
11
12
  /** A one-line JSON preview of the value (DESIGN.md §14.2 step 4): `JSON.stringify` even for a
@@ -113,18 +114,33 @@ function minimalFailedCompletion(run, meta, message) {
113
114
  };
114
115
  }
115
116
  export function startWorkflowRun(options) {
116
- const { ctx, session, id, origin, parentSignal, meta, body, args, source, budgetTokens, runner } = options;
117
+ const { ctx, session, id, origin, parentSignal, meta, body, args, source, limits, runner } = options;
117
118
  const settings = session.settings();
119
+ const budgetTokens = limits.budgetTokens.value;
120
+ const timeLimitMs = limits.timeLimitMs.value;
118
121
  const run = session.store.createRun({
119
122
  id,
120
123
  kind: "workflow",
121
124
  origin,
122
125
  title: meta.name,
123
- workflow: { name: meta.name, description: meta.description, source: source.kind, path: source.path, args },
126
+ workflow: {
127
+ name: meta.name,
128
+ description: meta.description,
129
+ source: source.kind,
130
+ path: source.path,
131
+ args,
132
+ budgetSource: limits.budgetTokens.source,
133
+ timeLimitSource: limits.timeLimitMs.source,
134
+ },
124
135
  phases: meta.phases,
125
136
  budgetTokens,
137
+ timeLimitMs,
126
138
  parentSignal,
127
139
  });
140
+ // One narrator line at start naming every applied limit and its source, or the disclaimer when
141
+ // one or both are absent (D-B): shows in the tool row, dock and inspector, same wording as the
142
+ // approval prompt's `Limits:` line and the final result text's `Limits:` line.
143
+ run.appendLog(`Limits: ${formatWorkflowLimitsLine(limits)}`, "info");
128
144
  const mailbox = createRunMailbox("workflow-run");
129
145
  const done = (async () => {
130
146
  let host;
@@ -138,10 +154,13 @@ export function startWorkflowRun(options) {
138
154
  budgetTokens,
139
155
  maxAgents: settings.maxAgentsPerRun,
140
156
  maxItemsPerCall: settings.maxItemsPerCall,
141
- timeoutMs: settings.workflowTimeoutMs,
157
+ timeoutMs: hardSandboxTimeoutMs(timeLimitMs),
142
158
  signal: run.signal,
143
159
  host,
144
160
  });
161
+ // The script is done: its remaining agents are only being torn down from here on, so the
162
+ // limit elapsing now must not mark a run that finished in time as time-limited.
163
+ run.disarmTimeLimit();
145
164
  // The sandbox may finish (abort, timeout, script error, script return) while an agent it
146
165
  // abandoned mid-call is still being torn down (DESIGN.md §14.2 step 4); wait for every
147
166
  // `runSingleTask` this host started before snapshotting the run as final.
@@ -1 +1 @@
1
- {"version":3,"file":"launch.js","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/launch.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAE9D,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC1D,OAAO,EAAE,wBAAwB,EAA+B,MAAM,mBAAmB,CAAC;AAI1F,OAAO,EAAE,uBAAuB,EAAE,MAAM,iBAAiB,CAAC;AAE1D,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AA+BxD,MAAM,wBAAwB,GAAG,GAAG,CAAC;AAErC;;0DAE0D;AAC1D,SAAS,eAAe,CAAC,KAAc;IACtC,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAC1C,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IACnC,kGAAkG;IAClG,gGAAgG;IAChG,iGAAiG;IACjG,+FAA+F;IAC/F,MAAM,UAAU,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACpC,IAAI,UAAU,CAAC,MAAM,IAAI,wBAAwB;QAAE,OAAO,IAAI,CAAC;IAC/D,OAAO,GAAG,UAAU,CAAC,KAAK,CAAC,CAAC,EAAE,wBAAwB,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,GAAG,CAA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GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACvE,IAAI,CAAC;gBACJ,OAAO,gBAAgB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;YACvC,CAAC;YAAC,MAAM,CAAC;gBACR,wFAAwF;gBACxF,qEAAqE;gBACrE,OAAO,uBAAuB,CAAC,GAAG,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;YACpD,CAAC;QACF,CAAC;gBAAS,CAAC;YACV,OAAO,CAAC,OAAO,EAAE,CAAC;QACnB,CAAC;IACF,CAAC,CAAC,EAAE,CAAC;IAEL,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC;AACtB,CAAC","sourcesContent":["/**\n * Starts one workflow run (§14.2): creates the store run and mailbox synchronously, then runs the\n * script asynchronously via the lazily-loaded runtime. `done` never rejects.\n */\n\nimport type { Usage } from \"@draht/ai\";\nimport { createRunMailbox } from \"../../builtins/subagent.ts\";\nimport type { ExtensionContext } from \"../../extensions/types.ts\";\nimport { buildDetails, sumRunUsage } from \"../details.ts\";\nimport { formatWorkflowResultText, type WorkflowOutcomeSummary } from \"../result-text.ts\";\nimport type { PolyphaseSession } from \"../session.ts\";\nimport type { PolyphaseRun } from \"../store.ts\";\nimport type { AgentRunner, PolyphaseDetails, RunOrigin, WorkflowSource } from \"../types.ts\";\nimport { createWorkflowAgentHost } from \"./agent-host.ts\";\nimport type { WorkflowMeta } from \"./meta.ts\";\nimport { loadWorkflowRuntime } from \"./runtime.lazy.ts\";\nimport type { WorkflowOutcome, WorkflowScriptError } from \"./runtime.ts\";\n\nexport interface StartWorkflowRunOptions {\n\tctx: ExtensionContext;\n\tsession: PolyphaseSession;\n\tid: string;\n\torigin: RunOrigin;\n\tparentSignal?: AbortSignal;\n\tmeta: WorkflowMeta;\n\tbody: string;\n\targs: string;\n\tsource: { kind: WorkflowSource; path?: string };\n\tbudgetTokens: number | null;\n\trunner?: AgentRunner;\n}\n\nexport interface WorkflowRunCompletion {\n\toutcome: WorkflowOutcome;\n\ttext: string;\n\tdetails: PolyphaseDetails;\n\tusage: Usage | undefined;\n\tisError: boolean;\n}\n\nexport interface WorkflowRunHandle {\n\treadonly run: PolyphaseRun;\n\t/** Never rejects. */\n\treadonly done: Promise<WorkflowRunCompletion>;\n}\n\nconst RESULT_PREVIEW_MAX_CHARS = 400;\n\n/** A one-line JSON preview of the value (DESIGN.md §14.2 step 4): `JSON.stringify` even for a\n * string value, so embedded newlines are escaped instead of breaking the row onto several lines.\n * `undefined` (no return value) has no preview at all. */\nfunction resultPreviewOf(value: unknown): string | undefined {\n\tif (value === undefined) return undefined;\n\tconst text = JSON.stringify(value);\n\t// Measured and truncated by code point, not UTF-16 code unit, throughout: comparing `text.length`\n\t// (code units) against the cap but truncating by code point let a text over the unit cap but at\n\t// or under the code-point cap (e.g. ~300 non-BMP emoji) through untruncated, with a trailing \"…\"\n\t// that still marked it as truncated, and let the truncated preview reach ~2x the intended cap.\n\tconst codePoints = Array.from(text);\n\tif (codePoints.length <= RESULT_PREVIEW_MAX_CHARS) return text;\n\treturn `${codePoints.slice(0, RESULT_PREVIEW_MAX_CHARS - 1).join(\"\")}…`;\n}\n\n/** Folds the sandbox's redeclaration hint (runtime.ts) into the message so it survives into\n * `WorkflowOutcomeSummary`, which has no `hint` field of its own. */\nfunction errorMessageWithHint(error: WorkflowScriptError): string {\n\treturn error.hint ? `${error.message} (hint: ${error.hint})` : error.message;\n}\n\nfunction toSummary(outcome: WorkflowOutcome): WorkflowOutcomeSummary {\n\tif (outcome.ok) return { ok: true, value: outcome.value, consoleOutput: outcome.consoleOutput };\n\treturn {\n\t\tok: false,\n\t\terrorKind: outcome.error.kind,\n\t\terrorMessage: errorMessageWithHint(outcome.error),\n\t\terrorLine: outcome.error.line,\n\t\tconsoleOutput: outcome.consoleOutput,\n\t};\n}\n\nfunction finishRun(run: PolyphaseRun, outcome: WorkflowOutcome): WorkflowRunCompletion {\n\tif (outcome.ok) {\n\t\tconst preview = resultPreviewOf(outcome.value);\n\t\tif (preview !== undefined) run.setResultPreview(preview);\n\t\trun.finish(\"done\");\n\t} else if (outcome.error.kind === \"aborted\") {\n\t\trun.finish(\"cancelled\", outcome.error.message);\n\t} else {\n\t\tconst composed = errorMessageWithHint(outcome.error);\n\t\tconst message = outcome.error.line !== undefined ? `line ${outcome.error.line}: ${composed}` : composed;\n\t\trun.finish(\"failed\", message);\n\t}\n\n\tconst summary = toSummary(outcome);\n\treturn {\n\t\toutcome,\n\t\ttext: formatWorkflowResultText(run, summary),\n\t\tdetails: buildDetails(run, { final: true }),\n\t\tusage: sumRunUsage(run),\n\t\tisError: !outcome.ok,\n\t};\n}\n\nfunction failedCompletion(run: PolyphaseRun, message: string): WorkflowRunCompletion {\n\trun.finish(\"failed\", message);\n\tconst outcome: WorkflowOutcome = {\n\t\tok: false,\n\t\terror: { kind: \"sandbox\", message },\n\t\tconsoleOutput: [],\n\t\tagentCalls: 0,\n\t};\n\treturn {\n\t\toutcome,\n\t\ttext: formatWorkflowResultText(run, toSummary(outcome)),\n\t\tdetails: buildDetails(run, { final: true }),\n\t\tusage: sumRunUsage(run),\n\t\tisError: true,\n\t};\n}\n\n/** Built without `buildDetails`/`formatWorkflowResultText` so it can never itself throw; used only\n * when `failedCompletion` (which calls those) throws a second time (DESIGN.md §14.2 step 4: `done`\n * must never reject). */\nfunction minimalFailedCompletion(run: PolyphaseRun, meta: WorkflowMeta, message: string): WorkflowRunCompletion {\n\trun.finish(\"failed\", message);\n\tconst outcome: WorkflowOutcome = {\n\t\tok: false,\n\t\terror: { kind: \"sandbox\", message },\n\t\tconsoleOutput: [],\n\t\tagentCalls: 0,\n\t};\n\tconst details: PolyphaseDetails = {\n\t\tv: 1,\n\t\trunId: run.id,\n\t\tkind: run.kind,\n\t\torigin: run.origin,\n\t\ttitle: run.title,\n\t\tstatus: \"failed\",\n\t\tstartedAt: run.startedAt,\n\t\tendedAt: run.endedAt ?? Date.now(),\n\t\tagents: [],\n\t\ttotals: { agents: 0, tokens: 0, cost: 0, byStatus: {}, blockedToolCalls: 0 },\n\t\terror: message,\n\t};\n\treturn {\n\t\toutcome,\n\t\ttext: `Workflow ${meta.name} failed: ${message}`,\n\t\tdetails,\n\t\tusage: undefined,\n\t\tisError: true,\n\t};\n}\n\nexport function startWorkflowRun(options: StartWorkflowRunOptions): WorkflowRunHandle {\n\tconst { ctx, session, id, origin, parentSignal, meta, body, args, source, budgetTokens, runner } = options;\n\tconst settings = session.settings();\n\n\tconst run = session.store.createRun({\n\t\tid,\n\t\tkind: \"workflow\",\n\t\torigin,\n\t\ttitle: meta.name,\n\t\tworkflow: { name: meta.name, description: meta.description, source: source.kind, path: source.path, args },\n\t\tphases: meta.phases,\n\t\tbudgetTokens,\n\t\tparentSignal,\n\t});\n\n\tconst mailbox = createRunMailbox(\"workflow-run\");\n\n\tconst done = (async (): Promise<WorkflowRunCompletion> => {\n\t\tlet host: ReturnType<typeof createWorkflowAgentHost> | undefined;\n\t\ttry {\n\t\t\tconst runtime = await loadWorkflowRuntime();\n\t\t\thost = createWorkflowAgentHost({ ctx, session, run, meta, mailbox: mailbox.name, runner });\n\t\t\tconst outcome = await runtime.runWorkflowScript({\n\t\t\t\tmeta,\n\t\t\t\tbody,\n\t\t\t\targs,\n\t\t\t\tbudgetTokens,\n\t\t\t\tmaxAgents: settings.maxAgentsPerRun,\n\t\t\t\tmaxItemsPerCall: settings.maxItemsPerCall,\n\t\t\t\ttimeoutMs: settings.workflowTimeoutMs,\n\t\t\t\tsignal: run.signal,\n\t\t\t\thost,\n\t\t\t});\n\t\t\t// The sandbox may finish (abort, timeout, script error, script return) while an agent it\n\t\t\t// abandoned mid-call is still being torn down (DESIGN.md §14.2 step 4); wait for every\n\t\t\t// `runSingleTask` this host started before snapshotting the run as final.\n\t\t\tawait host.settled();\n\t\t\treturn finishRun(run, outcome);\n\t\t} catch (error) {\n\t\t\t// Defensive: `runWorkflowScript` never rejects while agents are in flight today\n\t\t\t// (`finish()` aborts every pending host call), but if it ever did, awaiting `settled()`\n\t\t\t// without cancelling first would let paid children run to completion unobserved.\n\t\t\trun.cancel(\"run\");\n\t\t\tawait host?.settled();\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\ttry {\n\t\t\t\treturn failedCompletion(run, message);\n\t\t\t} catch {\n\t\t\t\t// formatWorkflowResultText/buildDetails/sumRunUsage threw a second time; fall back to a\n\t\t\t\t// completion that can't itself throw, so `done` still never rejects.\n\t\t\t\treturn minimalFailedCompletion(run, meta, message);\n\t\t\t}\n\t\t} finally {\n\t\t\tmailbox.dispose();\n\t\t}\n\t})();\n\n\treturn { run, done };\n}\n"]}
1
+ {"version":3,"file":"launch.js","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/launch.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAE9D,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAC1D,OAAO,EAAE,wBAAwB,EAA+B,MAAM,mBAAmB,CAAC;AAI1F,OAAO,EAAE,uBAAuB,EAAE,MAAM,iBAAiB,CAAC;AAC1D,OAAO,EAAE,wBAAwB,EAAE,oBAAoB,EAA+B,MAAM,aAAa,CAAC;AAE1G,OAAO,EAAE,mBAAmB,EAAE,MAAM,mBAAmB,CAAC;AA+BxD,MAAM,wBAAwB,GAAG,GAAG,CAAC;AAErC;;0DAE0D;AAC1D,SAAS,eAAe,CAAC,KAAc;IACtC,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,SAAS,CAAC;IAC1C,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;IACnC,kGAAkG;IAClG,gGAAgG;IAChG,iGAAiG;IACjG,+FAA+F;IAC/F,MAAM,UAAU,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACpC,IAA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BACJ,IAAI;gBACJ,YAAY;gBACZ,SAAS,EAAE,QAAQ,CAAC,eAAe;gBACnC,eAAe,EAAE,QAAQ,CAAC,eAAe;gBACzC,SAAS,EAAE,oBAAoB,CAAC,WAAW,CAAC;gBAC5C,MAAM,EAAE,GAAG,CAAC,MAAM;gBAClB,IAAI;aACJ,CAAC,CAAC;YACH,yFAAyF;YACzF,gFAAgF;YAChF,GAAG,CAAC,eAAe,EAAE,CAAC;YACtB,yFAAyF;YACzF,uFAAuF;YACvF,0EAA0E;YAC1E,MAAM,IAAI,CAAC,OAAO,EAAE,CAAC;YACrB,OAAO,SAAS,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;QAChC,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,gFAAgF;YAChF,wFAAwF;YACxF,iFAAiF;YACjF,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YAClB,MAAM,IAAI,EAAE,OAAO,EAAE,CAAC;YACtB,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACvE,IAAI,CAAC;gBACJ,OAAO,gBAAgB,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;YACvC,CAAC;YAAC,MAAM,CAAC;gBACR,wFAAwF;gBACxF,qEAAqE;gBACrE,OAAO,uBAAuB,CAAC,GAAG,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC;YACpD,CAAC;QACF,CAAC;gBAAS,CAAC;YACV,OAAO,CAAC,OAAO,EAAE,CAAC;QACnB,CAAC;IACF,CAAC,CAAC,EAAE,CAAC;IAEL,OAAO,EAAE,GAAG,EAAE,IAAI,EAAE,CAAC;AACtB,CAAC","sourcesContent":["/**\n * Starts one workflow run (§14.2): creates the store run and mailbox synchronously, then runs the\n * script asynchronously via the lazily-loaded runtime. `done` never rejects.\n */\n\nimport type { Usage } from \"@draht/ai\";\nimport { createRunMailbox } from \"../../builtins/subagent.ts\";\nimport type { ExtensionContext } from \"../../extensions/types.ts\";\nimport { buildDetails, sumRunUsage } from \"../details.ts\";\nimport { formatWorkflowResultText, type WorkflowOutcomeSummary } from \"../result-text.ts\";\nimport type { PolyphaseSession } from \"../session.ts\";\nimport type { PolyphaseRun } from \"../store.ts\";\nimport type { AgentRunner, PolyphaseDetails, RunOrigin, WorkflowSource } from \"../types.ts\";\nimport { createWorkflowAgentHost } from \"./agent-host.ts\";\nimport { formatWorkflowLimitsLine, hardSandboxTimeoutMs, type ResolvedWorkflowLimits } from \"./limits.ts\";\nimport type { WorkflowMeta } from \"./meta.ts\";\nimport { loadWorkflowRuntime } from \"./runtime.lazy.ts\";\nimport type { WorkflowOutcome, WorkflowScriptError } from \"./runtime.ts\";\n\nexport interface StartWorkflowRunOptions {\n\tctx: ExtensionContext;\n\tsession: PolyphaseSession;\n\tid: string;\n\torigin: RunOrigin;\n\tparentSignal?: AbortSignal;\n\tmeta: WorkflowMeta;\n\tbody: string;\n\targs: string;\n\tsource: { kind: WorkflowSource; path?: string };\n\tlimits: ResolvedWorkflowLimits;\n\trunner?: AgentRunner;\n}\n\nexport interface WorkflowRunCompletion {\n\toutcome: WorkflowOutcome;\n\ttext: string;\n\tdetails: PolyphaseDetails;\n\tusage: Usage | undefined;\n\tisError: boolean;\n}\n\nexport interface WorkflowRunHandle {\n\treadonly run: PolyphaseRun;\n\t/** Never rejects. */\n\treadonly done: Promise<WorkflowRunCompletion>;\n}\n\nconst RESULT_PREVIEW_MAX_CHARS = 400;\n\n/** A one-line JSON preview of the value (DESIGN.md §14.2 step 4): `JSON.stringify` even for a\n * string value, so embedded newlines are escaped instead of breaking the row onto several lines.\n * `undefined` (no return value) has no preview at all. */\nfunction resultPreviewOf(value: unknown): string | undefined {\n\tif (value === undefined) return undefined;\n\tconst text = JSON.stringify(value);\n\t// Measured and truncated by code point, not UTF-16 code unit, throughout: comparing `text.length`\n\t// (code units) against the cap but truncating by code point let a text over the unit cap but at\n\t// or under the code-point cap (e.g. ~300 non-BMP emoji) through untruncated, with a trailing \"…\"\n\t// that still marked it as truncated, and let the truncated preview reach ~2x the intended cap.\n\tconst codePoints = Array.from(text);\n\tif (codePoints.length <= RESULT_PREVIEW_MAX_CHARS) return text;\n\treturn `${codePoints.slice(0, RESULT_PREVIEW_MAX_CHARS - 1).join(\"\")}…`;\n}\n\n/** Folds the sandbox's redeclaration hint (runtime.ts) into the message so it survives into\n * `WorkflowOutcomeSummary`, which has no `hint` field of its own. */\nfunction errorMessageWithHint(error: WorkflowScriptError): string {\n\treturn error.hint ? `${error.message} (hint: ${error.hint})` : error.message;\n}\n\nfunction toSummary(outcome: WorkflowOutcome): WorkflowOutcomeSummary {\n\tif (outcome.ok) return { ok: true, value: outcome.value, consoleOutput: outcome.consoleOutput };\n\treturn {\n\t\tok: false,\n\t\terrorKind: outcome.error.kind,\n\t\terrorMessage: errorMessageWithHint(outcome.error),\n\t\terrorLine: outcome.error.line,\n\t\tconsoleOutput: outcome.consoleOutput,\n\t};\n}\n\nfunction finishRun(run: PolyphaseRun, outcome: WorkflowOutcome): WorkflowRunCompletion {\n\tif (outcome.ok) {\n\t\tconst preview = resultPreviewOf(outcome.value);\n\t\tif (preview !== undefined) run.setResultPreview(preview);\n\t\trun.finish(\"done\");\n\t} else if (outcome.error.kind === \"aborted\") {\n\t\trun.finish(\"cancelled\", outcome.error.message);\n\t} else {\n\t\tconst composed = errorMessageWithHint(outcome.error);\n\t\tconst message = outcome.error.line !== undefined ? `line ${outcome.error.line}: ${composed}` : composed;\n\t\trun.finish(\"failed\", message);\n\t}\n\n\tconst summary = toSummary(outcome);\n\treturn {\n\t\toutcome,\n\t\ttext: formatWorkflowResultText(run, summary),\n\t\tdetails: buildDetails(run, { final: true }),\n\t\tusage: sumRunUsage(run),\n\t\tisError: !outcome.ok,\n\t};\n}\n\nfunction failedCompletion(run: PolyphaseRun, message: string): WorkflowRunCompletion {\n\trun.finish(\"failed\", message);\n\tconst outcome: WorkflowOutcome = {\n\t\tok: false,\n\t\terror: { kind: \"sandbox\", message },\n\t\tconsoleOutput: [],\n\t\tagentCalls: 0,\n\t};\n\treturn {\n\t\toutcome,\n\t\ttext: formatWorkflowResultText(run, toSummary(outcome)),\n\t\tdetails: buildDetails(run, { final: true }),\n\t\tusage: sumRunUsage(run),\n\t\tisError: true,\n\t};\n}\n\n/** Built without `buildDetails`/`formatWorkflowResultText` so it can never itself throw; used only\n * when `failedCompletion` (which calls those) throws a second time (DESIGN.md §14.2 step 4: `done`\n * must never reject). */\nfunction minimalFailedCompletion(run: PolyphaseRun, meta: WorkflowMeta, message: string): WorkflowRunCompletion {\n\trun.finish(\"failed\", message);\n\tconst outcome: WorkflowOutcome = {\n\t\tok: false,\n\t\terror: { kind: \"sandbox\", message },\n\t\tconsoleOutput: [],\n\t\tagentCalls: 0,\n\t};\n\tconst details: PolyphaseDetails = {\n\t\tv: 1,\n\t\trunId: run.id,\n\t\tkind: run.kind,\n\t\torigin: run.origin,\n\t\ttitle: run.title,\n\t\tstatus: \"failed\",\n\t\tstartedAt: run.startedAt,\n\t\tendedAt: run.endedAt ?? Date.now(),\n\t\tagents: [],\n\t\ttotals: { agents: 0, tokens: 0, cost: 0, byStatus: {}, blockedToolCalls: 0 },\n\t\terror: message,\n\t};\n\treturn {\n\t\toutcome,\n\t\ttext: `Workflow ${meta.name} failed: ${message}`,\n\t\tdetails,\n\t\tusage: undefined,\n\t\tisError: true,\n\t};\n}\n\nexport function startWorkflowRun(options: StartWorkflowRunOptions): WorkflowRunHandle {\n\tconst { ctx, session, id, origin, parentSignal, meta, body, args, source, limits, runner } = options;\n\tconst settings = session.settings();\n\tconst budgetTokens = limits.budgetTokens.value;\n\tconst timeLimitMs = limits.timeLimitMs.value;\n\n\tconst run = session.store.createRun({\n\t\tid,\n\t\tkind: \"workflow\",\n\t\torigin,\n\t\ttitle: meta.name,\n\t\tworkflow: {\n\t\t\tname: meta.name,\n\t\t\tdescription: meta.description,\n\t\t\tsource: source.kind,\n\t\t\tpath: source.path,\n\t\t\targs,\n\t\t\tbudgetSource: limits.budgetTokens.source,\n\t\t\ttimeLimitSource: limits.timeLimitMs.source,\n\t\t},\n\t\tphases: meta.phases,\n\t\tbudgetTokens,\n\t\ttimeLimitMs,\n\t\tparentSignal,\n\t});\n\n\t// One narrator line at start naming every applied limit and its source, or the disclaimer when\n\t// one or both are absent (D-B): shows in the tool row, dock and inspector, same wording as the\n\t// approval prompt's `Limits:` line and the final result text's `Limits:` line.\n\trun.appendLog(`Limits: ${formatWorkflowLimitsLine(limits)}`, \"info\");\n\n\tconst mailbox = createRunMailbox(\"workflow-run\");\n\n\tconst done = (async (): Promise<WorkflowRunCompletion> => {\n\t\tlet host: ReturnType<typeof createWorkflowAgentHost> | undefined;\n\t\ttry {\n\t\t\tconst runtime = await loadWorkflowRuntime();\n\t\t\thost = createWorkflowAgentHost({ ctx, session, run, meta, mailbox: mailbox.name, runner });\n\t\t\tconst outcome = await runtime.runWorkflowScript({\n\t\t\t\tmeta,\n\t\t\t\tbody,\n\t\t\t\targs,\n\t\t\t\tbudgetTokens,\n\t\t\t\tmaxAgents: settings.maxAgentsPerRun,\n\t\t\t\tmaxItemsPerCall: settings.maxItemsPerCall,\n\t\t\t\ttimeoutMs: hardSandboxTimeoutMs(timeLimitMs),\n\t\t\t\tsignal: run.signal,\n\t\t\t\thost,\n\t\t\t});\n\t\t\t// The script is done: its remaining agents are only being torn down from here on, so the\n\t\t\t// limit elapsing now must not mark a run that finished in time as time-limited.\n\t\t\trun.disarmTimeLimit();\n\t\t\t// The sandbox may finish (abort, timeout, script error, script return) while an agent it\n\t\t\t// abandoned mid-call is still being torn down (DESIGN.md §14.2 step 4); wait for every\n\t\t\t// `runSingleTask` this host started before snapshotting the run as final.\n\t\t\tawait host.settled();\n\t\t\treturn finishRun(run, outcome);\n\t\t} catch (error) {\n\t\t\t// Defensive: `runWorkflowScript` never rejects while agents are in flight today\n\t\t\t// (`finish()` aborts every pending host call), but if it ever did, awaiting `settled()`\n\t\t\t// without cancelling first would let paid children run to completion unobserved.\n\t\t\trun.cancel(\"run\");\n\t\t\tawait host?.settled();\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\ttry {\n\t\t\t\treturn failedCompletion(run, message);\n\t\t\t} catch {\n\t\t\t\t// formatWorkflowResultText/buildDetails/sumRunUsage threw a second time; fall back to a\n\t\t\t\t// completion that can't itself throw, so `done` still never rejects.\n\t\t\t\treturn minimalFailedCompletion(run, meta, message);\n\t\t\t}\n\t\t} finally {\n\t\t\tmailbox.dispose();\n\t\t}\n\t})();\n\n\treturn { run, done };\n}\n"]}
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Workflow token-budget and time-limit directives (D-B): a `+500k`/`+30min`-style token the user
3
+ * types in their own prompt, else a tool/command parameter, else config, else none. See
4
+ * docs/polyphase.md "Limits" for the full grammar and precedence.
5
+ */
6
+ import type { LimitSource } from "../types.ts";
7
+ /** Extra wall-clock time the hard sandbox deadline keeps past a resolved graceful time limit, so
8
+ * agents already in flight when the limit fires have a window to wind down before the sandbox
9
+ * itself is killed. */
10
+ export declare const TIME_LIMIT_BACKSTOP_MS = 60000;
11
+ /** The longest time limit that still fits one `setTimeout` together with its backstop. Node turns
12
+ * any longer delay into 1ms, so an over-long limit would cancel every agent the moment it started;
13
+ * longer requests are capped here instead. */
14
+ export declare const MAX_TIME_LIMIT_MS: number;
15
+ export interface ParsedDirectives {
16
+ budgetTokens: number | null;
17
+ timeLimitMs: number | null;
18
+ }
19
+ export interface ResolvedLimit {
20
+ value: number | null;
21
+ source: LimitSource;
22
+ }
23
+ export interface ResolvedWorkflowLimits {
24
+ budgetTokens: ResolvedLimit;
25
+ timeLimitMs: ResolvedLimit;
26
+ }
27
+ /** The first `+500k`/`+1.5M`/`+200000`-style token (min 1000 tokens) and the first
28
+ * `+30min`/`+2h`/`+90s`/`+1h30min`-style token anywhere in `text`, each independent of the other. */
29
+ export declare function parsePromptDirectives(text: string): ParsedDirectives;
30
+ /** Removes every recognized directive token from `text` (e.g. command args) by cutting out the
31
+ * matched positions, not by a substring replace: a glued, non-standalone occurrence (e.g. the
32
+ * `+500k` inside `v+500k`) was never matched by `findDirectives` and is left untouched, and a
33
+ * standalone token that happens to be a textual prefix of another standalone token (e.g. `+1000`
34
+ * inside `+10000`) only removes its own matched span. Collapses the whitespace immediately next to
35
+ * each removed span, not every run of whitespace in `text`. A `+`-token that didn't classify (too
36
+ * small, malformed unit) is left untouched — it was never a directive. */
37
+ export declare function stripPromptDirectives(text: string): string;
38
+ /** Same grammar as the budget/time directive bodies, without the leading `+`: used for the
39
+ * `timeLimit` tool parameter. `undefined` when `text` is not a valid duration. */
40
+ export declare function parseDurationMs(text: string): number | undefined;
41
+ /** A steer or follow-up typed while a turn runs (`streamingBehavior` set) only adds what it states:
42
+ * `update`'s limits over `base`'s, keeping `base`'s where `update` names none. A prompt that starts a
43
+ * turn replaces the directives instead (the caller decides which). */
44
+ export declare function mergePromptDirectives(base: ParsedDirectives | undefined, update: ParsedDirectives): ParsedDirectives;
45
+ export interface ResolveWorkflowLimitsOptions {
46
+ prompt?: ParsedDirectives;
47
+ tool?: {
48
+ budgetTokens?: number | null;
49
+ timeLimitMs?: number | null;
50
+ };
51
+ config: {
52
+ budgetTokens: number | null;
53
+ timeLimitMs: number | null;
54
+ };
55
+ }
56
+ /** Precedence, independently for the token budget and the time limit: prompt directive, else tool
57
+ * parameter, else config, else none. */
58
+ export declare function resolveWorkflowLimits(options: ResolveWorkflowLimitsOptions): ResolvedWorkflowLimits;
59
+ /** The sandbox's own hard deadline: `timeLimitMs + 60s` when a time limit resolved, else disabled
60
+ * (0). There is no separate "config" hard-timeout concept anymore — `polyphase.workflowTimeoutMs`
61
+ * is itself one of the possible sources of the graceful time limit above. Never past what one
62
+ * `setTimeout` can wait. */
63
+ export declare function hardSandboxTimeoutMs(resolvedTimeLimitMs: number | null): number;
64
+ /** `1h30min`, `30min`, `90s` → `1min30s`: the one spelling of a limit's duration, wherever it
65
+ * is shown (approval, log lines, result text, tool row). */
66
+ export declare function formatLimitDuration(ms: number): string;
67
+ /** `budget 500k tokens (from your prompt)`, or `no token budget` when absent. */
68
+ export declare function formatBudgetLimitText(limit: ResolvedLimit): string;
69
+ /** `time limit 30min (from your prompt)`, or `no time limit` when absent. */
70
+ export declare function formatTimeLimitText(limit: ResolvedLimit): string;
71
+ /** The disclaimer shown (in the approval prompt, the start narrator line, and the final result
72
+ * text) when one or both limits are absent, naming only the missing one(s) and how to add them.
73
+ * "Runs until the workflow reaches its goal" is only said with neither limit: a time limit alone
74
+ * still ends the run. `undefined` when both are set. */
75
+ export declare function formatMissingLimitsDisclaimer(limits: ResolvedWorkflowLimits): string | undefined;
76
+ /** One line summarizing both limits, used identically by the approval prompt, the start narrator
77
+ * log line, and the final result text's `Limits:` line. Each limit is named exactly once: by its
78
+ * value and source when set, by its disclaimer when not. */
79
+ export declare function formatWorkflowLimitsLine(limits: ResolvedWorkflowLimits): string;
80
+ //# sourceMappingURL=limits.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"limits.d.ts","sourceRoot":"","sources":["../../../../src/core/polyphase/workflow/limits.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE/C;;uBAEuB;AACvB,eAAO,MAAM,sBAAsB,QAAS,CAAC;AAE7C;;8CAE8C;AAC9C,eAAO,MAAM,iBAAiB,QAA8C,CAAC;AAE7E,MAAM,WAAW,gBAAgB;IAChC,YAAY,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5B,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B;AAED,MAAM,WAAW,aAAa;IAC7B,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,MAAM,EAAE,WAAW,CAAC;CACpB;AAED,MAAM,WAAW,sBAAsB;IACtC,YAAY,EAAE,aAAa,CAAC;IAC5B,WAAW,EAAE,aAAa,CAAC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