@fitchmultz/pi-subagents 0.44.7 → 0.45.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +258 -7
- package/LICENSE +1 -0
- package/README.md +58 -1483
- package/agents/context-builder.md +19 -1
- package/agents/debugger.md +10 -3
- package/agents/delegate.md +1 -0
- package/agents/fixer.md +4 -1
- package/agents/oracle.md +13 -2
- package/agents/planner.md +14 -3
- package/agents/researcher.md +11 -2
- package/agents/reviewer-claude.md +11 -2
- package/agents/reviewer-gpt.md +12 -2
- package/agents/reviewer-ponytail.md +11 -1
- package/agents/reviewer-security.md +13 -2
- package/agents/reviewer.md +12 -3
- package/agents/scout.md +12 -1
- package/agents/ui-designer.md +10 -3
- package/agents/watcher.md +1 -0
- package/agents/worker.md +8 -2
- package/agents/writer.md +6 -3
- package/dist/agents/agent-defaults.js +9 -0
- package/dist/agents/agent-definition.js +196 -0
- package/dist/agents/agent-management.js +64 -905
- package/dist/agents/agent-scope.js +4 -2
- package/dist/agents/agent-selection.js +10 -5
- package/dist/agents/agent-serializer.js +55 -67
- package/dist/agents/agents.js +75 -716
- package/dist/agents/builtin-overrides.js +218 -0
- package/dist/agents/chain-serializer.js +3 -367
- package/dist/agents/config-values.js +52 -0
- package/dist/agents/discovery-paths.js +91 -0
- package/dist/agents/frontmatter.js +15 -5
- package/dist/agents/identity.js +25 -8
- package/dist/agents/json-chain.js +254 -0
- package/dist/agents/management-config.js +332 -0
- package/dist/agents/management-format.js +231 -0
- package/dist/agents/management-persistence.js +287 -0
- package/dist/agents/management-targets.js +136 -0
- package/dist/agents/management-warnings.js +81 -0
- package/dist/agents/markdown-chain.js +210 -0
- package/dist/agents/package-agents.js +154 -0
- package/dist/agents/skill-files.js +157 -0
- package/dist/agents/skill-search-paths.js +246 -0
- package/dist/agents/skill-types.js +1 -0
- package/dist/agents/skills.js +54 -499
- package/dist/extension/acceptance-schema.js +55 -0
- package/dist/extension/build-info.js +1 -1
- package/dist/extension/chain-schema.js +196 -0
- package/dist/extension/child-runtime.js +237 -0
- package/dist/extension/compact-tools.js +122 -51
- package/dist/extension/config-schema.js +29 -0
- package/dist/extension/config.js +27 -11
- package/dist/extension/control-notice-schema.js +37 -0
- package/dist/extension/control-notices.js +13 -6
- package/dist/extension/delegation-bridges.js +43 -0
- package/dist/extension/doctor.js +48 -25
- package/dist/extension/everyday-schemas.js +207 -0
- package/dist/extension/fanout-child.js +18 -319
- package/dist/extension/index.js +8 -563
- package/dist/extension/message-renderers.js +225 -0
- package/dist/extension/nested-control-inbox.js +154 -0
- package/dist/extension/parent-runtime.js +339 -0
- package/dist/extension/primary-tool.js +69 -0
- package/dist/extension/result-snapshot.js +22 -0
- package/dist/extension/runtime-reload.js +62 -0
- package/dist/extension/runtime-storage.js +43 -0
- package/dist/extension/schema-overrides.js +75 -0
- package/dist/extension/schemas.js +265 -336
- package/dist/extension/tool-input.js +27 -12
- package/dist/extension/tool-result.js +19 -4
- package/dist/history/answer-texts.js +57 -0
- package/dist/history/canonical-result.js +76 -43
- package/dist/history/canonical-selection.js +40 -0
- package/dist/history/database-generation.js +82 -0
- package/dist/history/database.js +57 -33
- package/dist/history/entry-ingestion.js +61 -0
- package/dist/history/index.js +242 -97
- package/dist/history/ingest.js +168 -331
- package/dist/history/output-digests.js +40 -0
- package/dist/history/preview.js +210 -0
- package/dist/history/prune.js +33 -0
- package/dist/history/queries.js +60 -349
- package/dist/history/query-scope.js +190 -0
- package/dist/history/rows.js +77 -0
- package/dist/history/run-projection.js +137 -0
- package/dist/history/run-queries.js +153 -0
- package/dist/history/schema.js +31 -0
- package/dist/history/search-queries.js +163 -0
- package/dist/history/selected-record.js +108 -0
- package/dist/history/source-file.js +45 -0
- package/dist/history/source-watches.js +141 -0
- package/dist/history/store.js +164 -153
- package/dist/history/text-chunks.js +169 -0
- package/dist/history/text.js +35 -0
- package/dist/history/transcript-queries.js +177 -0
- package/dist/history/types.js +5 -1
- package/dist/history/values.js +36 -0
- package/dist/history/wire-inputs.js +122 -0
- package/dist/history/wire-models.js +38 -0
- package/dist/history/worker-runtime.js +441 -0
- package/dist/history/worker.js +66 -462
- package/dist/intercom/intercom-bridge.js +48 -20
- package/dist/intercom/live-intercom.js +80 -23
- package/dist/intercom/nested-result-tree.js +163 -0
- package/dist/intercom/result-delivery.js +40 -0
- package/dist/intercom/result-intercom.js +178 -261
- package/dist/pi-intercom/agent-dir.js +7 -3
- package/dist/pi-intercom/async.js +27 -0
- package/dist/pi-intercom/bridge-ask.js +57 -0
- package/dist/pi-intercom/bridge-config.js +79 -0
- package/dist/pi-intercom/bridge-http.js +86 -0
- package/dist/pi-intercom/bridge-protocol.js +106 -0
- package/dist/pi-intercom/bridge-routes.js +64 -0
- package/dist/pi-intercom/bridge-session.js +416 -0
- package/dist/pi-intercom/bridge.js +182 -603
- package/dist/pi-intercom/broker/broker.js +236 -244
- package/dist/pi-intercom/broker/client.js +189 -304
- package/dist/pi-intercom/broker/connection.js +165 -0
- package/dist/pi-intercom/broker/framing.js +5 -3
- package/dist/pi-intercom/broker/paths.js +4 -1
- package/dist/pi-intercom/broker/pid.js +53 -25
- package/dist/pi-intercom/broker/snapshot-reader.js +78 -0
- package/dist/pi-intercom/broker/snapshots.js +188 -0
- package/dist/pi-intercom/broker/spawn.js +36 -25
- package/dist/pi-intercom/config.js +85 -71
- package/dist/pi-intercom/connection.js +297 -0
- package/dist/pi-intercom/identity.js +58 -0
- package/dist/pi-intercom/inbound-delivery.js +356 -0
- package/dist/pi-intercom/inbound-journal.js +303 -0
- package/dist/pi-intercom/inbound-record.js +113 -0
- package/dist/pi-intercom/inbound.js +179 -0
- package/dist/pi-intercom/index.js +79 -2933
- package/dist/pi-intercom/inspection.js +62 -0
- package/dist/pi-intercom/interview.js +236 -0
- package/dist/pi-intercom/lifecycle.js +168 -0
- package/dist/pi-intercom/message-format.js +69 -0
- package/dist/pi-intercom/outbound.js +304 -0
- package/dist/pi-intercom/peer-awareness.js +66 -0
- package/dist/pi-intercom/reply-tracker.js +62 -43
- package/dist/pi-intercom/reply-wait.js +201 -0
- package/dist/pi-intercom/runtime-types.js +3 -0
- package/dist/pi-intercom/session-events.js +180 -0
- package/dist/pi-intercom/session-targets.js +42 -34
- package/dist/pi-intercom/subagent-events.js +238 -0
- package/dist/pi-intercom/subagent-live-events.js +129 -86
- package/dist/pi-intercom/supervisor.js +282 -0
- package/dist/pi-intercom/tool-arguments.js +74 -0
- package/dist/pi-intercom/tool-registration.js +95 -0
- package/dist/pi-intercom/tool-results.js +38 -0
- package/dist/pi-intercom/tool-schemas.js +82 -0
- package/dist/pi-intercom/tools.js +51 -0
- package/dist/pi-intercom/topic-actions.js +177 -0
- package/dist/pi-intercom/topics.js +177 -92
- package/dist/pi-intercom/transport.js +1 -0
- package/dist/pi-intercom/types.js +151 -114
- package/dist/pi-intercom/ui/compose-paste.js +93 -0
- package/dist/pi-intercom/ui/compose.js +121 -143
- package/dist/pi-intercom/ui/inline-message.js +59 -59
- package/dist/pi-intercom/ui/message-renderers.js +147 -0
- package/dist/pi-intercom/ui/overlay.js +181 -0
- package/dist/pi-intercom/ui/session-format.js +124 -0
- package/dist/pi-intercom/ui/session-list.js +76 -43
- package/dist/pi-intercom/ui/tool-renderers.js +110 -0
- package/dist/pi-intercom/ui/topic-view.js +88 -0
- package/dist/pi-intercom/validation.js +59 -0
- package/dist/runs/background/async-chain-plan.js +265 -0
- package/dist/runs/background/async-control.js +134 -58
- package/dist/runs/background/async-execution.js +136 -633
- package/dist/runs/background/async-job-admission.js +40 -0
- package/dist/runs/background/async-job-projection.js +169 -0
- package/dist/runs/background/async-job-tracker.js +297 -327
- package/dist/runs/background/async-launch.js +216 -0
- package/dist/runs/background/async-plan.js +116 -0
- package/dist/runs/background/async-result-file.js +47 -23
- package/dist/runs/background/async-resume.js +195 -253
- package/dist/runs/background/async-run-discovery.js +213 -0
- package/dist/runs/background/async-run-location.js +135 -0
- package/dist/runs/background/async-run-record.js +1 -0
- package/dist/runs/background/async-run-repair.js +223 -0
- package/dist/runs/background/async-run-summary.js +1 -0
- package/dist/runs/background/async-single-plan.js +105 -0
- package/dist/runs/background/async-status-projection.js +155 -0
- package/dist/runs/background/async-status-render.js +117 -0
- package/dist/runs/background/async-status-validation.js +181 -0
- package/dist/runs/background/async-status.js +3 -442
- package/dist/runs/background/async-value.js +21 -0
- package/dist/runs/background/completion-dedupe.js +36 -12
- package/dist/runs/background/completion-delivery.js +211 -205
- package/dist/runs/background/completion-receipts.js +237 -0
- package/dist/runs/background/legacy-status-acceptance.js +34 -0
- package/dist/runs/background/notify.js +96 -48
- package/dist/runs/background/parallel-groups.js +36 -19
- package/dist/runs/background/result-payload.js +178 -0
- package/dist/runs/background/result-watcher.js +348 -339
- package/dist/runs/background/run-id-resolver.js +53 -33
- package/dist/runs/background/run-schemas.js +189 -0
- package/dist/runs/background/run-status-contracts.js +14 -0
- package/dist/runs/background/run-status-render.js +270 -0
- package/dist/runs/background/run-status.js +231 -339
- package/dist/runs/background/runner-attempt-output.js +155 -0
- package/dist/runs/background/runner-attempt.js +263 -0
- package/dist/runs/background/runner-child-executor.js +166 -0
- package/dist/runs/background/runner-child-observer.js +192 -0
- package/dist/runs/background/runner-completion-summary.js +71 -0
- package/dist/runs/background/runner-completion.js +211 -0
- package/dist/runs/background/runner-config.js +1 -0
- package/dist/runs/background/runner-contract.js +1 -0
- package/dist/runs/background/runner-dynamic.js +121 -0
- package/dist/runs/background/runner-finalization.js +149 -0
- package/dist/runs/background/runner-graph.js +68 -0
- package/dist/runs/background/runner-initial-status.js +60 -0
- package/dist/runs/background/runner-lifecycle.js +142 -0
- package/dist/runs/background/runner-monitor.js +309 -0
- package/dist/runs/background/runner-parallel.js +204 -0
- package/dist/runs/background/runner-prepare-step.js +86 -0
- package/dist/runs/background/runner-reporting.js +153 -0
- package/dist/runs/background/runner-status.js +148 -0
- package/dist/runs/background/runner-step-output.js +92 -0
- package/dist/runs/background/runner-step-record.js +45 -0
- package/dist/runs/background/runner-step.js +112 -0
- package/dist/runs/background/runner-streaming.js +173 -0
- package/dist/runs/background/runner-workflow.js +213 -0
- package/dist/runs/background/stale-run-reconciler.js +155 -292
- package/dist/runs/background/subagent-runner-launcher.js +33 -13
- package/dist/runs/background/subagent-runner.js +51 -1842
- package/dist/runs/background/top-level-async.js +2 -1
- package/dist/runs/foreground/chain-clarify.js +293 -1017
- package/dist/runs/foreground/clarification-draft.js +87 -0
- package/dist/runs/foreground/clarify-contracts.js +1 -0
- package/dist/runs/foreground/clarify-invocation.js +129 -38
- package/dist/runs/foreground/clarify-text-editor.js +210 -0
- package/dist/runs/foreground/clarify-view.js +167 -0
- package/dist/runs/foreground/execution-input.js +226 -353
- package/dist/runs/foreground/execution-routing.js +33 -0
- package/dist/runs/foreground/execution-timeout.js +81 -0
- package/dist/runs/foreground/foreground-control.js +222 -763
- package/dist/runs/foreground/foreground-memory.js +99 -0
- package/dist/runs/foreground/invocation-context.js +55 -0
- package/dist/runs/foreground/invocation-execution.js +331 -0
- package/dist/runs/foreground/invocation-expansion.js +48 -0
- package/dist/runs/foreground/management-actions.js +295 -0
- package/dist/runs/foreground/nested-control.js +179 -0
- package/dist/runs/foreground/question-continuation.js +78 -0
- package/dist/runs/foreground/question-control.js +155 -50
- package/dist/runs/foreground/resume-target.js +221 -0
- package/dist/runs/foreground/revival-launch-policy.js +58 -0
- package/dist/runs/foreground/run-async-path.js +190 -178
- package/dist/runs/foreground/run-interrupt.js +164 -0
- package/dist/runs/foreground/run-nudge.js +278 -0
- package/dist/runs/foreground/saved-revival.js +251 -0
- package/dist/runs/foreground/subagent-executor.js +135 -424
- package/dist/runs/foreground/subagent-params.js +67 -30
- package/dist/runs/foreground/wait-observation.js +104 -0
- package/dist/runs/foreground/wait-registration.js +17 -0
- package/dist/runs/foreground/wait-run.js +283 -123
- package/dist/runs/shared/acceptance-contract.js +193 -99
- package/dist/runs/shared/acceptance-defaults.js +1 -0
- package/dist/runs/shared/acceptance-evaluation.js +201 -181
- package/dist/runs/shared/acceptance-finalization.js +256 -180
- package/dist/runs/shared/acceptance-outcome.js +53 -0
- package/dist/runs/shared/acceptance-reports.js +137 -72
- package/dist/runs/shared/acceptance-submission.js +167 -0
- package/dist/runs/shared/acceptance-verification.js +100 -0
- package/dist/runs/shared/chain-outputs.js +80 -52
- package/dist/runs/shared/child-attempt-types.js +1 -0
- package/dist/runs/shared/child-attempt.js +314 -667
- package/dist/runs/shared/child-boundaries.js +173 -0
- package/dist/runs/shared/child-context-filter.js +44 -0
- package/dist/runs/shared/child-event-observer.js +390 -0
- package/dist/runs/shared/child-execution-cwd.js +73 -43
- package/dist/runs/shared/child-execution-outcome.js +72 -0
- package/dist/runs/shared/child-invocation.js +54 -0
- package/dist/runs/shared/child-message-validation.js +215 -0
- package/dist/runs/shared/child-native-accounting.js +106 -0
- package/dist/runs/shared/child-native-observation.js +69 -0
- package/dist/runs/shared/child-observation-spool.js +164 -0
- package/dist/runs/shared/child-observations.js +157 -76
- package/dist/runs/shared/child-presence.js +3 -0
- package/dist/runs/shared/child-route-env.js +119 -0
- package/dist/runs/shared/child-stream-observer.js +221 -0
- package/dist/runs/shared/child-stream-projection.js +137 -0
- package/dist/runs/shared/child-structured-tool.js +27 -0
- package/dist/runs/shared/claude-code.js +121 -158
- package/dist/runs/shared/claude-model.js +42 -0
- package/dist/runs/shared/claude-session.js +83 -0
- package/dist/runs/shared/claude-types.js +1 -0
- package/dist/runs/shared/completion-guard.js +18 -18
- package/dist/runs/shared/control-event-policy.js +8 -0
- package/dist/runs/shared/control-notification-owner.js +13 -0
- package/dist/runs/shared/dynamic-fanout.js +188 -173
- package/dist/runs/shared/dynamic-item.js +102 -0
- package/dist/runs/shared/history-index.js +62 -36
- package/dist/runs/shared/legacy-async-recovery.js +114 -0
- package/dist/runs/shared/legacy-output-recovery.js +148 -0
- package/dist/runs/shared/mcp-config-schema.js +36 -0
- package/dist/runs/shared/mcp-direct-tool-allowlist.js +147 -116
- package/dist/runs/shared/model-fallback.js +97 -38
- package/dist/runs/shared/mutating-tool-guard.js +128 -88
- package/dist/runs/shared/native-finalization-types.js +1 -0
- package/dist/runs/shared/native-finalization.js +155 -76
- package/dist/runs/shared/native-usage.js +238 -98
- package/dist/runs/shared/nested-control-records.js +128 -0
- package/dist/runs/shared/nested-events.js +8 -700
- package/dist/runs/shared/nested-path.js +32 -28
- package/dist/runs/shared/nested-projection.js +155 -0
- package/dist/runs/shared/nested-protocol.js +18 -0
- package/dist/runs/shared/nested-registry.js +191 -0
- package/dist/runs/shared/nested-render.js +106 -58
- package/dist/runs/shared/nested-route.js +220 -0
- package/dist/runs/shared/nested-validation.js +216 -0
- package/dist/runs/shared/owned-child-evidence.js +125 -0
- package/dist/runs/shared/owned-run-list.js +146 -0
- package/dist/runs/shared/owned-run-observation.js +267 -0
- package/dist/runs/shared/owned-run-progress.js +109 -0
- package/dist/runs/shared/owned-run-read-state.js +1 -0
- package/dist/runs/shared/owned-run-results.js +202 -0
- package/dist/runs/shared/owned-run-status.js +180 -0
- package/dist/runs/shared/owned-run-view.js +51 -0
- package/dist/runs/shared/owned-workflow-details.js +17 -0
- package/dist/runs/shared/owner-output.js +43 -0
- package/dist/runs/shared/parallel-utils.js +36 -28
- package/dist/runs/shared/parent-receipts.js +90 -32
- package/dist/runs/shared/parent-usage.js +169 -57
- package/dist/runs/shared/pi-args.js +108 -201
- package/dist/runs/shared/pi-launch-input.js +1 -0
- package/dist/runs/shared/pi-session-launch.js +86 -0
- package/dist/runs/shared/pi-spawn.js +35 -21
- package/dist/runs/shared/run-history-queries.js +126 -35
- package/dist/runs/shared/run-history.js +101 -35
- package/dist/runs/shared/run-metadata-paths.js +14 -0
- package/dist/runs/shared/run-metadata.js +158 -0
- package/dist/runs/shared/run-persistence.js +131 -0
- package/dist/runs/shared/run-records.js +9 -679
- package/dist/runs/shared/run-restoration.js +338 -0
- package/dist/runs/shared/run-state-owner.js +26 -0
- package/dist/runs/shared/session-cwd-preload.js +27 -18
- package/dist/runs/shared/single-output.js +148 -70
- package/dist/runs/shared/stable-value.js +15 -0
- package/dist/runs/shared/streaming-text.js +23 -12
- package/dist/runs/shared/structured-output.js +25 -13
- package/dist/runs/shared/subagent-control.js +167 -100
- package/dist/runs/shared/subagent-prompt-runtime.js +27 -130
- package/dist/runs/shared/subagent-tool-loop-guard.js +81 -52
- package/dist/runs/shared/supervisor-question-state.js +145 -0
- package/dist/runs/shared/supervisor-questions.js +185 -254
- package/dist/runs/shared/workflow-graph.js +259 -167
- package/dist/runs/shared/workflow-policy.js +120 -48
- package/dist/runs/shared/worktree-contract.js +1 -0
- package/dist/runs/shared/worktree-hook.js +138 -0
- package/dist/runs/shared/worktree-location.js +47 -0
- package/dist/runs/shared/worktree-preservation.js +8 -0
- package/dist/runs/shared/worktree-process.js +107 -0
- package/dist/runs/shared/worktree.js +183 -322
- package/dist/shared/agent-context-policy.js +34 -44
- package/dist/shared/agent-dir.js +14 -0
- package/dist/shared/artifacts.js +30 -12
- package/dist/shared/atomic-json.js +4 -1
- package/dist/shared/chain-files.js +72 -0
- package/dist/shared/concurrency.js +18 -0
- package/dist/shared/content-preview.js +115 -0
- package/dist/shared/cooperative.js +5 -2
- package/dist/shared/execution-cwd.js +13 -5
- package/dist/shared/file-coalescer.js +2 -1
- package/dist/shared/fork-context.js +10 -12
- package/dist/shared/formatters.js +45 -19
- package/dist/shared/journal-frames.js +164 -0
- package/dist/shared/journal-projections.js +121 -0
- package/dist/shared/journal-reader.js +6 -407
- package/dist/shared/json-projection.js +191 -0
- package/dist/shared/lazy-tools.js +19 -8
- package/dist/shared/message-output.js +116 -0
- package/dist/shared/model-info.js +31 -14
- package/dist/shared/native-import.js +20 -0
- package/dist/shared/native-journal.js +140 -0
- package/dist/shared/native-session.js +5 -2
- package/dist/shared/native-tui.js +7 -2
- package/dist/shared/native-typebox.js +15 -3
- package/dist/shared/output-page.js +63 -0
- package/dist/shared/post-exit-stdio-guard.js +128 -88
- package/dist/shared/prompt-sections.js +2 -0
- package/dist/shared/session-entries.js +70 -35
- package/dist/shared/session-identity.js +5 -3
- package/dist/shared/settings.js +62 -192
- package/dist/shared/status-format.js +97 -37
- package/dist/shared/task-file-policy.js +24 -0
- package/dist/shared/temp-root.js +44 -15
- package/dist/shared/types/acceptance.js +1 -0
- package/dist/shared/types/async.js +1 -0
- package/dist/shared/types/config.js +1 -0
- package/dist/shared/types/details.js +1 -0
- package/dist/shared/types/history.js +1 -0
- package/dist/shared/types/inputs.js +1 -0
- package/dist/shared/types/intercom.js +1 -0
- package/dist/shared/types/launch.js +1 -0
- package/dist/shared/types/messages.js +1 -0
- package/dist/shared/types/nested.js +1 -0
- package/dist/shared/types/owned-runs.js +1 -0
- package/dist/shared/types/progress.js +1 -0
- package/dist/shared/types/questions.js +1 -0
- package/dist/shared/types/results.js +1 -0
- package/dist/shared/types/state.js +1 -0
- package/dist/shared/types/usage.js +1 -0
- package/dist/shared/types/workflow.js +1 -0
- package/dist/shared/types.js +75 -30
- package/dist/shared/unknown.js +52 -0
- package/dist/shared/utils.js +54 -260
- package/dist/slash/command-discovery.js +82 -0
- package/dist/slash/command-input.js +190 -0
- package/dist/slash/prompt-template-bridge.js +94 -270
- package/dist/slash/prompt-template-contract.js +77 -0
- package/dist/slash/prompt-template-results.js +125 -0
- package/dist/slash/request-protocol.js +68 -0
- package/dist/slash/result-delivery.js +237 -0
- package/dist/slash/saved-chain.js +78 -0
- package/dist/slash/slash-bridge.js +123 -89
- package/dist/slash/slash-commands.js +101 -572
- package/dist/slash/slash-live-state.js +68 -47
- package/dist/tui/action-hints.js +50 -22
- package/dist/tui/activity-lines.js +32 -0
- package/dist/tui/agent-browser.js +290 -0
- package/dist/tui/agent-controls.js +289 -0
- package/dist/tui/agent-conversation.js +444 -0
- package/dist/tui/agent-dock.js +171 -0
- package/dist/tui/agent-history.js +50 -183
- package/dist/tui/agent-model.js +62 -0
- package/dist/tui/agent-picker.js +262 -0
- package/dist/tui/agent-view.js +232 -1564
- package/dist/tui/compact-results.js +193 -0
- package/dist/tui/conversation-details.js +190 -0
- package/dist/tui/conversation-frame.js +135 -0
- package/dist/tui/conversation-history.js +201 -0
- package/dist/tui/conversation-menu.js +78 -0
- package/dist/tui/conversation-notices.js +79 -0
- package/dist/tui/conversation-selection.js +58 -0
- package/dist/tui/conversation-viewport.js +129 -0
- package/dist/tui/direction-message.js +27 -0
- package/dist/tui/display.js +282 -0
- package/dist/tui/editor-viewport.js +18 -0
- package/dist/tui/expanded-content.js +87 -0
- package/dist/tui/expanded-multi.js +170 -0
- package/dist/tui/expanded-single.js +65 -0
- package/dist/tui/history-cards.js +216 -0
- package/dist/tui/history-display.js +238 -0
- package/dist/tui/history-json.js +16 -0
- package/dist/tui/history-metadata.js +152 -0
- package/dist/tui/history-record.js +251 -0
- package/dist/tui/history-text.js +34 -0
- package/dist/tui/indexed-history.js +116 -0
- package/dist/tui/nested-widget.js +120 -0
- package/dist/tui/picker-page.js +59 -0
- package/dist/tui/render.js +58 -1501
- package/dist/tui/result-facts.js +64 -0
- package/dist/tui/task-observation.js +59 -0
- package/dist/tui/task-store.js +366 -0
- package/dist/tui/text-values.js +16 -0
- package/dist/tui/view-connections.js +47 -0
- package/dist/tui/view-model.js +94 -0
- package/dist/tui/view-persistence.js +51 -0
- package/dist/tui/view-ports.js +1 -0
- package/dist/tui/view-session.js +37 -0
- package/dist/tui/widget-details.js +144 -0
- package/dist/tui/widget-status.js +245 -0
- package/dist/tui/widget.js +145 -0
- package/dist/tui/workflow-labels.js +223 -0
- package/dist/tui/workflow-outcomes.js +124 -0
- package/docs/code-quality.md +38 -0
- package/docs/development.md +99 -0
- package/docs/intercom-bridge.md +22 -17
- package/docs/intercom.md +132 -106
- package/docs/performance.md +19 -17
- package/docs/reference.md +1472 -0
- package/generated/RunValidators.d.ts +28 -0
- package/generated/RunValidators.js +2 -0
- package/package.json +27 -6
- package/prompts/parallel-cleanup.md +3 -0
- package/prompts/parallel-context-build.md +3 -0
- package/prompts/parallel-handoff-plan.md +6 -0
- package/prompts/parallel-research.md +4 -0
- package/prompts/parallel-review.md +2 -0
- package/prompts/review-loop.md +2 -0
- package/scripts/build.mjs +129 -85
- package/scripts/check-compat.mjs +48 -11
- package/scripts/compat-host.mjs +35 -7
- package/scripts/generate-run-schemas.mjs +210 -0
- package/scripts/intercom-bridge-credentials.mjs +155 -28
- package/scripts/intercom-remote.mjs +175 -50
- package/scripts/local-install-smoke.mjs +47 -37
- package/scripts/native-package-smoke.mjs +135 -25
- package/scripts/package-smoke.mjs +360 -140
- package/scripts/prepare.mjs +54 -34
- package/scripts/real-pi-processes.mjs +261 -0
- package/scripts/real-pi-smoke.mjs +432 -351
- package/scripts/run-tests.mjs +29 -15
- package/skills/pi-intercom/SKILL.md +11 -11
- package/skills/pi-intercom/references/peer-sessions.md +7 -2
- package/skills/pi-subagents/SKILL.md +1 -1
- package/skills/pi-subagents/references/full-orchestration-guide.md +254 -112
- package/src/agents/agent-defaults.ts +13 -0
- package/src/agents/agent-definition.ts +253 -0
- package/src/agents/agent-management.ts +111 -808
- package/src/agents/agent-scope.ts +7 -3
- package/src/agents/agent-selection.ts +26 -16
- package/src/agents/agent-serializer.ts +84 -93
- package/src/agents/agents.ts +199 -906
- package/src/agents/builtin-overrides.ts +297 -0
- package/src/agents/chain-serializer.ts +3 -329
- package/src/agents/config-values.ts +57 -0
- package/src/agents/discovery-paths.ts +134 -0
- package/src/agents/frontmatter.ts +35 -17
- package/src/agents/identity.ts +49 -18
- package/src/agents/json-chain.ts +305 -0
- package/src/agents/management-config.ts +342 -0
- package/src/agents/management-format.ts +243 -0
- package/src/agents/management-persistence.ts +408 -0
- package/src/agents/management-targets.ts +260 -0
- package/src/agents/management-warnings.ts +115 -0
- package/src/agents/markdown-chain.ts +237 -0
- package/src/agents/package-agents.ts +231 -0
- package/src/agents/skill-files.ts +182 -0
- package/src/agents/skill-search-paths.ts +289 -0
- package/src/agents/skill-types.ts +31 -0
- package/src/agents/skills.ts +152 -610
- package/src/extension/acceptance-schema.ts +88 -0
- package/src/extension/chain-schema.ts +276 -0
- package/src/extension/child-runtime.ts +302 -0
- package/src/extension/compact-tools.ts +259 -102
- package/src/extension/config-schema.ts +59 -0
- package/src/extension/config.ts +39 -17
- package/src/extension/control-notice-schema.ts +55 -0
- package/src/extension/control-notices.ts +57 -33
- package/src/extension/delegation-bridges.ts +59 -0
- package/src/extension/doctor.ts +171 -135
- package/src/extension/everyday-schemas.ts +252 -0
- package/src/extension/fanout-child.ts +29 -308
- package/src/extension/index.ts +17 -642
- package/src/extension/message-renderers.ts +334 -0
- package/src/extension/nested-control-inbox.ts +196 -0
- package/src/extension/parent-runtime.ts +405 -0
- package/src/extension/primary-tool.ts +130 -0
- package/src/extension/result-snapshot.ts +35 -0
- package/src/extension/runtime-reload.ts +72 -0
- package/src/extension/runtime-storage.ts +49 -0
- package/src/extension/schema-overrides.ts +114 -0
- package/src/extension/schemas.ts +451 -418
- package/src/extension/tool-input.ts +40 -13
- package/src/extension/tool-result.ts +45 -14
- package/src/history/answer-texts.ts +74 -0
- package/src/history/canonical-result.ts +127 -51
- package/src/history/canonical-selection.ts +54 -0
- package/src/history/database-generation.ts +86 -0
- package/src/history/database.ts +86 -48
- package/src/history/entry-ingestion.ts +129 -0
- package/src/history/index.ts +426 -148
- package/src/history/ingest.ts +372 -342
- package/src/history/output-digests.ts +41 -0
- package/src/history/preview.ts +235 -0
- package/src/history/prune.ts +48 -0
- package/src/history/queries.ts +122 -256
- package/src/history/query-scope.ts +278 -0
- package/src/history/rows.ts +118 -0
- package/src/history/run-projection.ts +164 -0
- package/src/history/run-queries.ts +199 -0
- package/src/history/schema.ts +34 -0
- package/src/history/search-queries.ts +216 -0
- package/src/history/selected-record.ts +140 -0
- package/src/history/source-file.ts +51 -0
- package/src/history/source-watches.ts +156 -0
- package/src/history/store.ts +310 -197
- package/src/history/text-chunks.ts +181 -0
- package/src/history/text.ts +43 -0
- package/src/history/transcript-queries.ts +251 -0
- package/src/history/types.ts +27 -164
- package/src/history/values.ts +36 -0
- package/src/history/wire-inputs.ts +141 -0
- package/src/history/wire-models.ts +51 -0
- package/src/history/worker-runtime.ts +502 -0
- package/src/history/worker.ts +94 -336
- package/src/intercom/intercom-bridge.ts +136 -69
- package/src/intercom/live-intercom.ts +197 -92
- package/src/intercom/nested-result-tree.ts +213 -0
- package/src/intercom/result-delivery.ts +56 -0
- package/src/intercom/result-intercom.ts +364 -382
- package/src/pi-intercom/agent-dir.ts +9 -3
- package/src/pi-intercom/async.ts +33 -0
- package/src/pi-intercom/bridge-ask.ts +64 -0
- package/src/pi-intercom/bridge-config.ts +101 -0
- package/src/pi-intercom/bridge-http.ts +97 -0
- package/src/pi-intercom/bridge-protocol.ts +123 -0
- package/src/pi-intercom/bridge-routes.ts +90 -0
- package/src/pi-intercom/bridge-session.ts +506 -0
- package/src/pi-intercom/bridge.ts +258 -547
- package/src/pi-intercom/broker/broker.ts +326 -263
- package/src/pi-intercom/broker/client.ts +273 -354
- package/src/pi-intercom/broker/connection.ts +192 -0
- package/src/pi-intercom/broker/framing.ts +11 -6
- package/src/pi-intercom/broker/paths.ts +28 -25
- package/src/pi-intercom/broker/pid.ts +68 -24
- package/src/pi-intercom/broker/snapshot-reader.ts +91 -0
- package/src/pi-intercom/broker/snapshots.ts +241 -0
- package/src/pi-intercom/broker/spawn.ts +58 -34
- package/src/pi-intercom/config.ts +113 -108
- package/src/pi-intercom/connection.ts +346 -0
- package/src/pi-intercom/identity.ts +71 -0
- package/src/pi-intercom/inbound-delivery.ts +450 -0
- package/src/pi-intercom/inbound-journal.ts +350 -0
- package/src/pi-intercom/inbound-record.ts +141 -0
- package/src/pi-intercom/inbound.ts +237 -0
- package/src/pi-intercom/index.ts +86 -2923
- package/src/pi-intercom/inspection.ts +82 -0
- package/src/pi-intercom/interview.ts +295 -0
- package/src/pi-intercom/lifecycle.ts +183 -0
- package/src/pi-intercom/message-format.ts +77 -0
- package/src/pi-intercom/outbound.ts +418 -0
- package/src/pi-intercom/peer-awareness.ts +84 -0
- package/src/pi-intercom/reply-tracker.ts +121 -59
- package/src/pi-intercom/reply-wait.ts +247 -0
- package/src/pi-intercom/runtime-types.ts +97 -0
- package/src/pi-intercom/session-events.ts +247 -0
- package/src/pi-intercom/session-targets.ts +124 -72
- package/src/pi-intercom/subagent-events.ts +299 -0
- package/src/pi-intercom/subagent-live-events.ts +212 -109
- package/src/pi-intercom/supervisor.ts +362 -0
- package/src/pi-intercom/tool-arguments.ts +120 -0
- package/src/pi-intercom/tool-registration.ts +121 -0
- package/src/pi-intercom/tool-results.ts +54 -0
- package/src/pi-intercom/tool-schemas.ts +134 -0
- package/src/pi-intercom/tools.ts +80 -0
- package/src/pi-intercom/topic-actions.ts +243 -0
- package/src/pi-intercom/topics.ts +267 -121
- package/src/pi-intercom/transport.ts +14 -0
- package/src/pi-intercom/types.ts +288 -190
- package/src/pi-intercom/ui/compose-paste.ts +109 -0
- package/src/pi-intercom/ui/compose.ts +173 -157
- package/src/pi-intercom/ui/inline-message.ts +80 -62
- package/src/pi-intercom/ui/message-renderers.ts +182 -0
- package/src/pi-intercom/ui/overlay.ts +238 -0
- package/src/pi-intercom/ui/session-format.ts +146 -0
- package/src/pi-intercom/ui/session-list.ts +145 -62
- package/src/pi-intercom/ui/tool-renderers.ts +148 -0
- package/src/pi-intercom/ui/topic-view.ts +107 -0
- package/src/pi-intercom/validation.ts +69 -0
- package/src/runs/background/async-chain-plan.ts +451 -0
- package/src/runs/background/async-control.ts +201 -71
- package/src/runs/background/async-execution.ts +206 -829
- package/src/runs/background/async-job-admission.ts +54 -0
- package/src/runs/background/async-job-projection.ts +225 -0
- package/src/runs/background/async-job-tracker.ts +416 -360
- package/src/runs/background/async-launch.ts +319 -0
- package/src/runs/background/async-plan.ts +285 -0
- package/src/runs/background/async-result-file.ts +79 -37
- package/src/runs/background/async-resume.ts +338 -285
- package/src/runs/background/async-run-discovery.ts +270 -0
- package/src/runs/background/async-run-location.ts +194 -0
- package/src/runs/background/async-run-record.ts +14 -0
- package/src/runs/background/async-run-repair.ts +307 -0
- package/src/runs/background/async-run-summary.ts +71 -0
- package/src/runs/background/async-single-plan.ts +168 -0
- package/src/runs/background/async-status-projection.ts +188 -0
- package/src/runs/background/async-status-render.ts +164 -0
- package/src/runs/background/async-status-validation.ts +238 -0
- package/src/runs/background/async-status.ts +9 -481
- package/src/runs/background/async-value.ts +29 -0
- package/src/runs/background/completion-dedupe.ts +103 -54
- package/src/runs/background/completion-delivery.ts +313 -187
- package/src/runs/background/completion-receipts.ts +309 -0
- package/src/runs/background/legacy-status-acceptance.ts +38 -0
- package/src/runs/background/notify.ts +167 -106
- package/src/runs/background/parallel-groups.ts +95 -46
- package/src/runs/background/result-payload.ts +268 -0
- package/src/runs/background/result-watcher.ts +484 -387
- package/src/runs/background/run-id-resolver.ts +126 -57
- package/src/runs/background/run-schemas.ts +240 -0
- package/src/runs/background/run-status-contracts.ts +46 -0
- package/src/runs/background/run-status-render.ts +364 -0
- package/src/runs/background/run-status.ts +338 -356
- package/src/runs/background/runner-attempt-output.ts +281 -0
- package/src/runs/background/runner-attempt.ts +354 -0
- package/src/runs/background/runner-child-executor.ts +232 -0
- package/src/runs/background/runner-child-observer.ts +270 -0
- package/src/runs/background/runner-completion-summary.ts +106 -0
- package/src/runs/background/runner-completion.ts +274 -0
- package/src/runs/background/runner-config.ts +52 -0
- package/src/runs/background/runner-contract.ts +51 -0
- package/src/runs/background/runner-dynamic.ts +185 -0
- package/src/runs/background/runner-finalization.ts +203 -0
- package/src/runs/background/runner-graph.ts +91 -0
- package/src/runs/background/runner-initial-status.ts +72 -0
- package/src/runs/background/runner-lifecycle.ts +159 -0
- package/src/runs/background/runner-monitor.ts +399 -0
- package/src/runs/background/runner-parallel.ts +280 -0
- package/src/runs/background/runner-prepare-step.ts +128 -0
- package/src/runs/background/runner-reporting.ts +192 -0
- package/src/runs/background/runner-status.ts +220 -0
- package/src/runs/background/runner-step-output.ts +158 -0
- package/src/runs/background/runner-step-record.ts +76 -0
- package/src/runs/background/runner-step.ts +150 -0
- package/src/runs/background/runner-streaming.ts +220 -0
- package/src/runs/background/runner-workflow.ts +284 -0
- package/src/runs/background/stale-run-reconciler.ts +279 -336
- package/src/runs/background/subagent-runner-launcher.ts +67 -35
- package/src/runs/background/subagent-runner.ts +80 -2048
- package/src/runs/background/top-level-async.ts +9 -7
- package/src/runs/foreground/chain-clarify.ts +499 -1334
- package/src/runs/foreground/clarification-draft.ts +92 -0
- package/src/runs/foreground/clarify-contracts.ts +33 -0
- package/src/runs/foreground/clarify-invocation.ts +192 -65
- package/src/runs/foreground/clarify-text-editor.ts +229 -0
- package/src/runs/foreground/clarify-view.ts +222 -0
- package/src/runs/foreground/execution-input.ts +358 -424
- package/src/runs/foreground/execution-routing.ts +41 -0
- package/src/runs/foreground/execution-timeout.ts +92 -0
- package/src/runs/foreground/foreground-control.ts +333 -812
- package/src/runs/foreground/foreground-memory.ts +132 -0
- package/src/runs/foreground/invocation-context.ts +88 -0
- package/src/runs/foreground/invocation-execution.ts +465 -0
- package/src/runs/foreground/invocation-expansion.ts +58 -0
- package/src/runs/foreground/management-actions.ts +360 -0
- package/src/runs/foreground/nested-control.ts +248 -0
- package/src/runs/foreground/question-continuation.ts +112 -0
- package/src/runs/foreground/question-control.ts +297 -70
- package/src/runs/foreground/resume-target.ts +330 -0
- package/src/runs/foreground/revival-launch-policy.ts +112 -0
- package/src/runs/foreground/run-async-path.ts +307 -223
- package/src/runs/foreground/run-interrupt.ts +202 -0
- package/src/runs/foreground/run-nudge.ts +355 -0
- package/src/runs/foreground/saved-revival.ts +356 -0
- package/src/runs/foreground/subagent-executor.ts +195 -493
- package/src/runs/foreground/subagent-params.ts +314 -242
- package/src/runs/foreground/wait-observation.ts +160 -0
- package/src/runs/foreground/wait-registration.ts +18 -0
- package/src/runs/foreground/wait-run.ts +361 -119
- package/src/runs/shared/acceptance-contract.ts +410 -209
- package/src/runs/shared/acceptance-defaults.ts +1 -0
- package/src/runs/shared/acceptance-evaluation.ts +314 -240
- package/src/runs/shared/acceptance-finalization.ts +447 -305
- package/src/runs/shared/acceptance-outcome.ts +69 -0
- package/src/runs/shared/acceptance-reports.ts +220 -126
- package/src/runs/shared/acceptance-submission.ts +251 -0
- package/src/runs/shared/acceptance-verification.ts +118 -0
- package/src/runs/shared/acceptance.ts +25 -25
- package/src/runs/shared/chain-outputs.ts +190 -98
- package/src/runs/shared/child-attempt-types.ts +118 -0
- package/src/runs/shared/child-attempt.ts +372 -608
- package/src/runs/shared/child-boundaries.ts +217 -0
- package/src/runs/shared/child-context-filter.ts +53 -0
- package/src/runs/shared/child-event-observer.ts +496 -0
- package/src/runs/shared/child-execution-cwd.ts +139 -68
- package/src/runs/shared/child-execution-outcome.ts +103 -0
- package/src/runs/shared/child-invocation.ts +74 -0
- package/src/runs/shared/child-message-validation.ts +233 -0
- package/src/runs/shared/child-native-accounting.ts +154 -0
- package/src/runs/shared/child-native-observation.ts +79 -0
- package/src/runs/shared/child-observation-spool.ts +188 -0
- package/src/runs/shared/child-observations.ts +219 -89
- package/src/runs/shared/child-presence.ts +6 -0
- package/src/runs/shared/child-route-env.ts +142 -0
- package/src/runs/shared/child-stream-observer.ts +302 -0
- package/src/runs/shared/child-stream-projection.ts +160 -0
- package/src/runs/shared/child-structured-tool.ts +38 -0
- package/src/runs/shared/claude-code.ts +201 -228
- package/src/runs/shared/claude-model.ts +67 -0
- package/src/runs/shared/claude-session.ts +124 -0
- package/src/runs/shared/claude-types.ts +31 -0
- package/src/runs/shared/completion-guard.ts +35 -26
- package/src/runs/shared/control-event-policy.ts +15 -0
- package/src/runs/shared/control-notification-owner.ts +20 -0
- package/src/runs/shared/dynamic-fanout.ts +402 -238
- package/src/runs/shared/dynamic-item.ts +114 -0
- package/src/runs/shared/history-index.ts +112 -51
- package/src/runs/shared/legacy-async-recovery.ts +153 -0
- package/src/runs/shared/legacy-output-recovery.ts +214 -0
- package/src/runs/shared/mcp-config-schema.ts +46 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +396 -307
- package/src/runs/shared/model-fallback.ts +302 -180
- package/src/runs/shared/mutating-tool-guard.ts +259 -158
- package/src/runs/shared/native-finalization-types.ts +29 -0
- package/src/runs/shared/native-finalization.ts +233 -109
- package/src/runs/shared/native-usage.ts +379 -96
- package/src/runs/shared/nested-control-records.ts +178 -0
- package/src/runs/shared/nested-events.ts +45 -752
- package/src/runs/shared/nested-path.ts +47 -34
- package/src/runs/shared/nested-projection.ts +230 -0
- package/src/runs/shared/nested-protocol.ts +67 -0
- package/src/runs/shared/nested-registry.ts +273 -0
- package/src/runs/shared/nested-render.ts +198 -100
- package/src/runs/shared/nested-route.ts +292 -0
- package/src/runs/shared/nested-validation.ts +291 -0
- package/src/runs/shared/owned-child-evidence.ts +184 -0
- package/src/runs/shared/owned-run-list.ts +187 -0
- package/src/runs/shared/owned-run-observation.ts +368 -0
- package/src/runs/shared/owned-run-progress.ts +172 -0
- package/src/runs/shared/owned-run-read-state.ts +7 -0
- package/src/runs/shared/owned-run-results.ts +289 -0
- package/src/runs/shared/owned-run-status.ts +239 -0
- package/src/runs/shared/owned-run-view.ts +65 -0
- package/src/runs/shared/owned-workflow-details.ts +24 -0
- package/src/runs/shared/owner-output.ts +73 -0
- package/src/runs/shared/parallel-utils.ts +93 -129
- package/src/runs/shared/parent-receipts.ts +177 -50
- package/src/runs/shared/parent-usage.ts +314 -91
- package/src/runs/shared/pi-args.ts +241 -311
- package/src/runs/shared/pi-launch-input.ts +48 -0
- package/src/runs/shared/pi-session-launch.ts +94 -0
- package/src/runs/shared/pi-spawn.ts +57 -33
- package/src/runs/shared/run-history-queries.ts +189 -38
- package/src/runs/shared/run-history.ts +197 -76
- package/src/runs/shared/run-id-ambiguity.ts +7 -3
- package/src/runs/shared/run-metadata-paths.ts +17 -0
- package/src/runs/shared/run-metadata.ts +240 -0
- package/src/runs/shared/run-persistence.ts +181 -0
- package/src/runs/shared/run-records.ts +19 -607
- package/src/runs/shared/run-restoration.ts +455 -0
- package/src/runs/shared/run-state-owner.ts +31 -0
- package/src/runs/shared/session-cwd-preload.ts +39 -19
- package/src/runs/shared/single-output.ts +358 -205
- package/src/runs/shared/stable-value.ts +15 -0
- package/src/runs/shared/streaming-text.ts +39 -12
- package/src/runs/shared/structured-output.ts +76 -46
- package/src/runs/shared/subagent-control.ts +330 -197
- package/src/runs/shared/subagent-prompt-runtime.ts +92 -174
- package/src/runs/shared/subagent-tool-loop-guard.ts +118 -68
- package/src/runs/shared/supervisor-question-state.ts +221 -0
- package/src/runs/shared/supervisor-questions.ts +396 -401
- package/src/runs/shared/workflow-graph.ts +400 -198
- package/src/runs/shared/workflow-policy.ts +245 -110
- package/src/runs/shared/worktree-contract.ts +29 -0
- package/src/runs/shared/worktree-hook.ts +181 -0
- package/src/runs/shared/worktree-location.ts +61 -0
- package/src/runs/shared/worktree-preservation.ts +10 -0
- package/src/runs/shared/worktree-process.ts +132 -0
- package/src/runs/shared/worktree.ts +459 -587
- package/src/shared/agent-context-policy.ts +176 -145
- package/src/shared/agent-dir.ts +15 -0
- package/src/shared/artifacts.ts +99 -68
- package/src/shared/atomic-json.ts +14 -11
- package/src/shared/chain-files.ts +72 -0
- package/src/shared/concurrency.ts +27 -0
- package/src/shared/content-preview.ts +117 -0
- package/src/shared/cooperative.ts +17 -13
- package/src/shared/execution-cwd.ts +34 -9
- package/src/shared/file-coalescer.ts +24 -22
- package/src/shared/fork-context.ts +52 -48
- package/src/shared/formatters.ts +88 -47
- package/src/shared/journal-frames.ts +197 -0
- package/src/shared/journal-projections.ts +133 -0
- package/src/shared/journal-reader.ts +18 -333
- package/src/shared/json-projection.ts +224 -0
- package/src/shared/lazy-tools.ts +76 -27
- package/src/shared/message-output.ts +146 -0
- package/src/shared/model-info.ts +94 -58
- package/src/shared/native-import.ts +25 -0
- package/src/shared/native-journal.ts +172 -0
- package/src/shared/native-session.ts +8 -3
- package/src/shared/native-tui.ts +13 -3
- package/src/shared/native-typebox.ts +18 -3
- package/src/shared/output-page.ts +76 -0
- package/src/shared/post-exit-stdio-guard.ts +232 -172
- package/src/shared/prompt-sections.ts +13 -7
- package/src/shared/session-entries.ts +103 -44
- package/src/shared/session-identity.ts +17 -10
- package/src/shared/settings.ts +182 -367
- package/src/shared/status-format.ts +207 -98
- package/src/shared/stream-json.d.ts +10 -0
- package/src/shared/task-file-policy.ts +35 -0
- package/src/shared/temp-root.ts +122 -71
- package/src/shared/types/acceptance.ts +149 -0
- package/src/shared/types/async.ts +247 -0
- package/src/shared/types/config.ts +139 -0
- package/src/shared/types/details.ts +104 -0
- package/src/shared/types/history.ts +217 -0
- package/src/shared/types/inputs.ts +4 -0
- package/src/shared/types/intercom.ts +57 -0
- package/src/shared/types/launch.ts +39 -0
- package/src/shared/types/messages.ts +104 -0
- package/src/shared/types/nested.ts +153 -0
- package/src/shared/types/owned-runs.ts +148 -0
- package/src/shared/types/progress.ts +106 -0
- package/src/shared/types/questions.ts +103 -0
- package/src/shared/types/results.ts +119 -0
- package/src/shared/types/state.ts +56 -0
- package/src/shared/types/usage.ts +36 -0
- package/src/shared/types/workflow.ts +187 -0
- package/src/shared/types.ts +222 -1161
- package/src/shared/ui-mode.ts +1 -1
- package/src/shared/unknown.ts +59 -0
- package/src/shared/utils.ts +111 -305
- package/src/slash/command-discovery.ts +109 -0
- package/src/slash/command-input.ts +232 -0
- package/src/slash/prompt-template-bridge.ts +153 -400
- package/src/slash/prompt-template-contract.ts +152 -0
- package/src/slash/prompt-template-results.ts +189 -0
- package/src/slash/request-protocol.ts +87 -0
- package/src/slash/result-delivery.ts +312 -0
- package/src/slash/saved-chain.ts +115 -0
- package/src/slash/slash-bridge.ts +202 -156
- package/src/slash/slash-commands.ts +176 -598
- package/src/slash/slash-live-state.ts +287 -229
- package/src/tui/action-hints.ts +147 -61
- package/src/tui/activity-lines.ts +40 -0
- package/src/tui/agent-browser.ts +354 -0
- package/src/tui/agent-controls.ts +355 -0
- package/src/tui/agent-conversation.ts +514 -0
- package/src/tui/agent-dock.ts +250 -0
- package/src/tui/agent-history.ts +78 -203
- package/src/tui/agent-model.ts +78 -0
- package/src/tui/agent-picker.ts +325 -0
- package/src/tui/agent-view.ts +391 -1333
- package/src/tui/compact-results.ts +342 -0
- package/src/tui/conversation-details.ts +206 -0
- package/src/tui/conversation-frame.ts +184 -0
- package/src/tui/conversation-history.ts +246 -0
- package/src/tui/conversation-menu.ts +119 -0
- package/src/tui/conversation-notices.ts +116 -0
- package/src/tui/conversation-selection.ts +66 -0
- package/src/tui/conversation-viewport.ts +169 -0
- package/src/tui/direction-message.ts +35 -0
- package/src/tui/display.ts +409 -0
- package/src/tui/editor-viewport.ts +19 -0
- package/src/tui/expanded-content.ts +134 -0
- package/src/tui/expanded-multi.ts +264 -0
- package/src/tui/expanded-single.ts +92 -0
- package/src/tui/history-cards.ts +316 -0
- package/src/tui/history-display.ts +334 -0
- package/src/tui/history-json.ts +17 -0
- package/src/tui/history-metadata.ts +177 -0
- package/src/tui/history-record.ts +321 -0
- package/src/tui/history-text.ts +34 -0
- package/src/tui/indexed-history.ts +149 -0
- package/src/tui/nested-widget.ts +192 -0
- package/src/tui/picker-page.ts +80 -0
- package/src/tui/render.ts +100 -1546
- package/src/tui/result-facts.ts +99 -0
- package/src/tui/task-observation.ts +96 -0
- package/src/tui/task-store.ts +432 -0
- package/src/tui/text-values.ts +20 -0
- package/src/tui/view-connections.ts +64 -0
- package/src/tui/view-model.ts +181 -0
- package/src/tui/view-persistence.ts +57 -0
- package/src/tui/view-ports.ts +55 -0
- package/src/tui/view-session.ts +42 -0
- package/src/tui/widget-details.ts +220 -0
- package/src/tui/widget-status.ts +331 -0
- package/src/tui/widget.ts +208 -0
- package/src/tui/workflow-labels.ts +340 -0
- package/src/tui/workflow-outcomes.ts +150 -0
- package/tsconfig.build.json +11 -10
- package/tsconfig.json +30 -17
|
@@ -1,1872 +1,81 @@
|
|
|
1
|
-
var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
|
|
2
|
-
if (typeof path === "string" && /^\.\.?\//.test(path)) {
|
|
3
|
-
return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
|
|
4
|
-
return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
|
|
5
|
-
});
|
|
6
|
-
}
|
|
7
|
-
return path;
|
|
8
|
-
};
|
|
9
|
-
import { spawnSync } from "node:child_process";
|
|
10
|
-
import { readChildProcessIdentity } from "../../shared/post-exit-stdio-guard.js";
|
|
11
1
|
import * as fs from "node:fs";
|
|
12
2
|
import * as path from "node:path";
|
|
13
|
-
import { pathToFileURL } from "node:url";
|
|
14
3
|
import { writeAtomicJson } from "../../shared/atomic-json.js";
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
import { resolveSubagentIntercomTarget } from "../../intercom/intercom-bridge.js";
|
|
42
|
-
import { evaluateRunAcceptance, acceptanceHumanAction, createFinalizationReportRuntime, readFinalizationReport, formatUnconfirmedFinalizationOutput, resolveExecutionOutcome, resolveFinalizationOutput, formatAcceptancePrompt, stripAcceptanceReport, } from "../shared/acceptance.js";
|
|
43
|
-
const ASYNC_INTERRUPT_SIGNAL = "SIGUSR2";
|
|
44
|
-
function formatProcessExitFailure(input) {
|
|
45
|
-
const duration = input.durationMs !== undefined ? ` after ${input.durationMs}ms` : "";
|
|
46
|
-
if (input.exitCode === 143) {
|
|
47
|
-
return `${input.agent} exited with code 143${duration}. The child process received SIGTERM or exited as if terminated by SIGTERM; if this was close to 300000ms, Pi's default HTTP idle timeout is a likely provider-side cause.`;
|
|
48
|
-
}
|
|
49
|
-
return `${input.agent} exited with code ${input.exitCode ?? 1}${duration} without producing a final assistant response.`;
|
|
50
|
-
}
|
|
51
|
-
function emptyUsage() {
|
|
52
|
-
return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
|
|
53
|
-
}
|
|
54
|
-
function tokenUsageFromAttempts(attempts) {
|
|
55
|
-
if (!attempts || attempts.length === 0)
|
|
56
|
-
return null;
|
|
57
|
-
let input = 0;
|
|
58
|
-
let output = 0;
|
|
59
|
-
for (const attempt of attempts) {
|
|
60
|
-
input += attempt.usage?.input ?? 0;
|
|
61
|
-
output += attempt.usage?.output ?? 0;
|
|
62
|
-
}
|
|
63
|
-
const total = input + output;
|
|
64
|
-
return total > 0 ? { input, output, total } : null;
|
|
65
|
-
}
|
|
66
|
-
function appendRecentStepOutput(step, lines) {
|
|
67
|
-
const nonEmpty = lines.filter((line) => line.trim());
|
|
68
|
-
if (nonEmpty.length === 0)
|
|
69
|
-
return;
|
|
70
|
-
step.recentOutput ??= [];
|
|
71
|
-
step.recentOutput.push(...nonEmpty);
|
|
72
|
-
if (step.recentOutput.length > 50) {
|
|
73
|
-
step.recentOutput.splice(0, step.recentOutput.length - 50);
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
function clearStepCurrentActivity(step) {
|
|
77
|
-
step.currentTool = undefined;
|
|
78
|
-
step.currentToolArgs = undefined;
|
|
79
|
-
step.currentToolStartedAt = undefined;
|
|
80
|
-
step.currentPath = undefined;
|
|
81
|
-
}
|
|
82
|
-
function resetStepLiveDetail(step) {
|
|
83
|
-
clearStepCurrentActivity(step);
|
|
84
|
-
step.recentTools = [];
|
|
85
|
-
step.recentOutput = [];
|
|
86
|
-
}
|
|
87
|
-
function markStepPaused(step, now) {
|
|
88
|
-
step.status = "paused";
|
|
89
|
-
step.activityState = undefined;
|
|
90
|
-
clearStepCurrentActivity(step);
|
|
91
|
-
step.startedAt ??= now;
|
|
92
|
-
step.endedAt = now;
|
|
93
|
-
step.durationMs = step.startedAt !== undefined ? now - step.startedAt : undefined;
|
|
94
|
-
step.lastActivityAt = now;
|
|
95
|
-
step.exitCode = 0;
|
|
96
|
-
}
|
|
97
|
-
// Durable run records have no age cleanup. Streaming deltas and cumulative tool
|
|
98
|
-
// progress repeat what message_end and tool_execution_end already record.
|
|
99
|
-
const TRANSIENT_CHILD_EVENT_TYPES = new Set(["message_update", "tool_execution_update"]);
|
|
100
|
-
async function runPiStreaming(options, outputFile, context) {
|
|
101
|
-
const outputFd = fs.openSync(outputFile, "w", 0o600);
|
|
102
|
-
const auditPath = `${outputFile}.audit.log`;
|
|
103
|
-
const appendEvent = (event) => appendJsonl(context.eventsPath, JSON.stringify({
|
|
104
|
-
...event, recordVersion: 3, subagentSource: "child", subagentRunId: context.runId,
|
|
105
|
-
subagentStepIndex: context.stepIndex, subagentAgent: context.agent, observedAt: Date.now(),
|
|
4
|
+
import { appendJsonl } from "../../shared/artifacts.js";
|
|
5
|
+
import { saveRunStatus } from "../shared/supervisor-questions.js";
|
|
6
|
+
import { parseSubagentRunConfig } from "./run-schemas.js";
|
|
7
|
+
import { createRunnerStatus } from "./runner-initial-status.js";
|
|
8
|
+
import { RunnerMonitor } from "./runner-monitor.js";
|
|
9
|
+
import { RunnerLifecycle } from "./runner-lifecycle.js";
|
|
10
|
+
import { RunnerWorkflow } from "./runner-workflow.js";
|
|
11
|
+
import { completeRunner } from "./runner-completion.js";
|
|
12
|
+
async function runSubagent(config) {
|
|
13
|
+
const startedAt = Date.now();
|
|
14
|
+
const status = createRunnerStatus(config, startedAt);
|
|
15
|
+
fs.mkdirSync(config.asyncDir, { recursive: true });
|
|
16
|
+
writeAtomicJson(path.join(config.asyncDir, "status.json"), status);
|
|
17
|
+
if (config.runtimeVersion !== 2) {
|
|
18
|
+
saveRunStatus(config.id, status);
|
|
19
|
+
}
|
|
20
|
+
const monitor = new RunnerMonitor(config, status, startedAt);
|
|
21
|
+
const lifecycle = new RunnerLifecycle(config, status, monitor);
|
|
22
|
+
lifecycle.start(startedAt);
|
|
23
|
+
appendJsonl(path.join(config.asyncDir, "events.jsonl"), JSON.stringify({
|
|
24
|
+
type: "subagent.run.started",
|
|
25
|
+
ts: startedAt,
|
|
26
|
+
runId: config.id,
|
|
27
|
+
mode: status.mode,
|
|
28
|
+
cwd: config.cwd,
|
|
29
|
+
pid: process.pid,
|
|
106
30
|
}));
|
|
107
|
-
const output = (text) => { fs.writeFileSync(outputFd, text); };
|
|
108
31
|
try {
|
|
109
|
-
const
|
|
110
|
-
|
|
111
|
-
onStart: (control, result) => {
|
|
112
|
-
if (control.pid)
|
|
113
|
-
saveQuestionContract(context.runId, context.stepIndex, { pid: control.pid, processIdentity: readChildProcessIdentity(control.pid), sessionFile: options.sessionFile, attemptBaseline: result.attemptBaseline, updatedAt: Date.now() });
|
|
114
|
-
options.onStart?.(control, result);
|
|
115
|
-
},
|
|
116
|
-
onOutput: output,
|
|
117
|
-
onStderr: (text) => {
|
|
118
|
-
appendEvent({ type: "subagent.child.stderr", auditPath, length: Buffer.byteLength(text) });
|
|
119
|
-
},
|
|
120
|
-
onEvent: (event, result, mutation) => {
|
|
121
|
-
// Preserve live callback ordering; only the disk representation is reduced.
|
|
122
|
-
options.onEvent?.(event, result, mutation);
|
|
123
|
-
if (TRANSIENT_CHILD_EVENT_TYPES.has(event.type ?? ""))
|
|
124
|
-
return;
|
|
125
|
-
if (event.type === "subagent.native_baseline") {
|
|
126
|
-
appendEvent(event);
|
|
127
|
-
saveQuestionContract(context.runId, context.stepIndex, { attemptBaseline: result.attemptBaseline, baselineSource: "native-migration" });
|
|
128
|
-
}
|
|
129
|
-
else if (event.type === "subagent.native") {
|
|
130
|
-
appendEvent(event);
|
|
131
|
-
saveQuestionContract(context.runId, context.stepIndex, { nativeSessionId: result.nativeSessionId, terminalLeafId: result.terminalLeafId, effectiveConfiguration: result.effectiveConfiguration, updatedAt: Date.now() });
|
|
132
|
-
}
|
|
133
|
-
else if (event.type === FINALIZATION_EVENT) {
|
|
134
|
-
const marker = event;
|
|
135
|
-
const file = `${outputFile}.boundaries.jsonl`;
|
|
136
|
-
fs.appendFileSync(file, `${JSON.stringify(marker)}\n`, { mode: 0o600 });
|
|
137
|
-
appendEvent({ type: marker.type, nonce: marker.nonce, turn: marker.turn, lastEntryId: marker.lastEntryId, messageCount: marker.messageCount, at: marker.at, boundaryFile: file });
|
|
138
|
-
}
|
|
139
|
-
else {
|
|
140
|
-
appendEvent({ type: event.type, messageNumber: result.messageCount,
|
|
141
|
-
...(event.message ? { role: event.message.role, timestamp: event.message.timestamp } : {}),
|
|
142
|
-
toolCallId: event.toolCallId, toolName: event.toolName, isError: event.isError,
|
|
143
|
-
...(event.type === "tool_execution_start" ? { argsPreview: extractToolArgsPreview(event.args ?? {}) } : {}),
|
|
144
|
-
...(event.type === "tool_execution_end" ? { auditPath } : {}) });
|
|
145
|
-
}
|
|
146
|
-
},
|
|
147
|
-
});
|
|
148
|
-
appendEvent({ type: "subagent.child.finalized", agentProcessExit: result.agentProcessExit, exitCode: result.exitCode,
|
|
149
|
-
accounting: result.accounting, nativeSessionId: result.nativeSessionId, terminalLeafId: result.terminalLeafId,
|
|
150
|
-
terminalEntryId: result.terminalEntryId, nativeReferences: result.nativeReferences, auditPath: result.auditPath, auditRecords: result.auditRecords, auditSaveError: result.auditSaveError, outputFile });
|
|
151
|
-
saveQuestionContract(context.runId, context.stepIndex, { nativeSessionId: result.nativeSessionId, terminalLeafId: result.terminalLeafId, terminalEntryId: result.terminalEntryId,
|
|
152
|
-
effectiveConfiguration: result.effectiveConfiguration, accounting: result.accounting, auditPath: result.auditPath, updatedAt: Date.now() });
|
|
153
|
-
return result;
|
|
32
|
+
const evidence = await new RunnerWorkflow(config, monitor, lifecycle).run(startedAt);
|
|
33
|
+
await completeRunner(config, evidence, monitor, lifecycle);
|
|
154
34
|
}
|
|
155
35
|
finally {
|
|
156
|
-
|
|
36
|
+
lifecycle.dispose();
|
|
157
37
|
}
|
|
158
38
|
}
|
|
159
|
-
function
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
return root;
|
|
163
|
-
throw new Error(`Could not resolve ${PI_CODING_AGENT_PACKAGE} package root`);
|
|
39
|
+
function runnerError(error) {
|
|
40
|
+
console.error("Subagent runner error:", error);
|
|
41
|
+
process.exit(1);
|
|
164
42
|
}
|
|
165
|
-
|
|
166
|
-
const
|
|
167
|
-
const
|
|
168
|
-
|
|
169
|
-
const mod = await import(__rewriteRelativeImportExtension(moduleUrl));
|
|
170
|
-
const exportFromFile = mod
|
|
171
|
-
.exportFromFile;
|
|
172
|
-
if (typeof exportFromFile !== "function") {
|
|
173
|
-
throw new Error("exportFromFile not available");
|
|
174
|
-
}
|
|
175
|
-
const outputPath = path.join(outputDir, `${path.basename(sessionFile, ".jsonl")}.html`);
|
|
176
|
-
return exportFromFile(sessionFile, { outputPath });
|
|
177
|
-
}
|
|
178
|
-
function createShareLink(htmlPath) {
|
|
179
|
-
try {
|
|
180
|
-
const auth = spawnSync("gh", ["auth", "status"], { encoding: "utf-8" });
|
|
181
|
-
if (auth.status !== 0) {
|
|
182
|
-
return { error: "GitHub CLI is not logged in. Run 'gh auth login' first." };
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
catch {
|
|
186
|
-
return { error: "GitHub CLI (gh) is not installed." };
|
|
187
|
-
}
|
|
188
|
-
try {
|
|
189
|
-
const result = spawnSync("gh", ["gist", "create", htmlPath], { encoding: "utf-8" });
|
|
190
|
-
if (result.status !== 0) {
|
|
191
|
-
const err = (result.stderr || "").trim() || "Failed to create gist.";
|
|
192
|
-
return { error: err };
|
|
193
|
-
}
|
|
194
|
-
const gistUrl = (result.stdout || "").trim();
|
|
195
|
-
const gistId = gistUrl.split("/").pop();
|
|
196
|
-
if (!gistId)
|
|
197
|
-
return { error: "Failed to parse gist ID." };
|
|
198
|
-
const shareUrl = `https://shittycodingagent.ai/session/?${gistId}`;
|
|
199
|
-
return { shareUrl, gistUrl };
|
|
200
|
-
}
|
|
201
|
-
catch (err) {
|
|
202
|
-
return { error: String(err) };
|
|
203
|
-
}
|
|
204
|
-
}
|
|
205
|
-
function formatDuration(ms) {
|
|
206
|
-
if (ms < 1000)
|
|
207
|
-
return `${ms}ms`;
|
|
208
|
-
if (ms < 60000)
|
|
209
|
-
return `${(ms / 1000).toFixed(1)}s`;
|
|
210
|
-
const minutes = Math.floor(ms / 60000);
|
|
211
|
-
const seconds = Math.floor((ms % 60000) / 1000);
|
|
212
|
-
return `${minutes}m${seconds}s`;
|
|
213
|
-
}
|
|
214
|
-
function writeRunLog(logPath, input) {
|
|
215
|
-
const lines = [];
|
|
216
|
-
lines.push(`# Subagent run ${input.id}`);
|
|
217
|
-
lines.push("");
|
|
218
|
-
lines.push(`- **Mode:** ${input.mode}`);
|
|
219
|
-
lines.push(`- **Launch cwd:** ${input.cwd}`);
|
|
220
|
-
lines.push(`- **Started:** ${new Date(input.startedAt).toISOString()}`);
|
|
221
|
-
lines.push(`- **Ended:** ${new Date(input.endedAt).toISOString()}`);
|
|
222
|
-
lines.push(`- **Duration:** ${formatDuration(input.endedAt - input.startedAt)}`);
|
|
223
|
-
if (input.sessionFile)
|
|
224
|
-
lines.push(`- **Session:** ${input.sessionFile}`);
|
|
225
|
-
if (input.shareUrl)
|
|
226
|
-
lines.push(`- **Share:** ${input.shareUrl}`);
|
|
227
|
-
if (input.shareError)
|
|
228
|
-
lines.push(`- **Share error:** ${input.shareError}`);
|
|
229
|
-
if (input.artifactsDir)
|
|
230
|
-
lines.push(`- **Artifacts:** ${input.artifactsDir}`);
|
|
231
|
-
lines.push("");
|
|
232
|
-
lines.push("## Steps");
|
|
233
|
-
lines.push("| Step | Agent | Status | Duration |");
|
|
234
|
-
lines.push("| --- | --- | --- | --- |");
|
|
235
|
-
input.steps.forEach((step, i) => {
|
|
236
|
-
const duration = step.durationMs !== undefined ? formatDuration(step.durationMs) : "-";
|
|
237
|
-
lines.push(`| ${i + 1} | ${step.agent} | ${step.status} | ${duration} |`);
|
|
238
|
-
});
|
|
239
|
-
lines.push("");
|
|
240
|
-
lines.push("## Summary");
|
|
241
|
-
if (input.truncated) {
|
|
242
|
-
lines.push("_Output truncated_");
|
|
243
|
-
lines.push("");
|
|
244
|
-
}
|
|
245
|
-
lines.push(input.summary.trim() || "(no output)");
|
|
246
|
-
lines.push("");
|
|
247
|
-
fs.writeFileSync(logPath, lines.join("\n"), "utf-8");
|
|
248
|
-
}
|
|
249
|
-
/** Run a single pi agent step, returning output and metadata */
|
|
250
|
-
async function runSingleStep(step, ctx) {
|
|
251
|
-
const startedAt = Date.now();
|
|
252
|
-
let toolCount = 0;
|
|
253
|
-
const toolCalls = [];
|
|
254
|
-
if (ctx.signal?.aborted)
|
|
255
|
-
return { agent: step.agent, output: "", exitCode: 1, error: "Subagent cancelled." };
|
|
256
|
-
if (ctx.nativeFinalization && step.effectiveAcceptance?.explicit && !step.sessionFile) {
|
|
257
|
-
step = { ...step, sessionFile: path.join(path.dirname(ctx.outputFile), `session-${ctx.flatIndex}.jsonl`) };
|
|
258
|
-
}
|
|
259
|
-
saveQuestionContract(ctx.id, ctx.flatIndex, { task: step.task, label: step.label, effectiveAcceptance: step.effectiveAcceptance, output: step.outputPath ?? false, outputMode: step.outputMode, outputSchema: step.structuredOutputSchema ?? step.structuredOutput?.schema, launch: step.launch ? { ...step.launch, cwd: step.cwd ?? ctx.cwd, output: step.outputPath ?? false, outputMode: step.outputMode ?? "inline", outputSchema: step.structuredOutputSchema ?? step.structuredOutput?.schema, model: step.model, thinking: step.thinking } : undefined, sessionFile: step.sessionFile });
|
|
260
|
-
const interruptController = new AbortController();
|
|
261
|
-
ctx.registerInterrupt?.(() => interruptController.abort());
|
|
262
|
-
const interruptSignal = AbortSignal.any([ctx.interruptSignal, interruptController.signal].filter((signal) => signal !== undefined));
|
|
263
|
-
const verificationSignal = AbortSignal.any([ctx.signal, interruptSignal].filter((signal) => signal !== undefined));
|
|
264
|
-
const effectiveStructuredOutput = step.structuredOutput ?? (step.structuredOutputSchema
|
|
265
|
-
? createStructuredOutputRuntime(step.structuredOutputSchema, path.join(path.dirname(ctx.outputFile), "structured-output"))
|
|
266
|
-
: undefined);
|
|
267
|
-
let task = step.task;
|
|
268
|
-
if (step.effectiveAcceptance) {
|
|
269
|
-
const acceptancePrompt = formatAcceptancePrompt(step.effectiveAcceptance);
|
|
270
|
-
if (acceptancePrompt)
|
|
271
|
-
task = `${task}\n${acceptancePrompt}`;
|
|
272
|
-
}
|
|
273
|
-
const sessionEnabled = Boolean(step.sessionFile) || ctx.sessionEnabled;
|
|
274
|
-
const sessionDir = step.sessionFile ? undefined : ctx.sessionDir;
|
|
275
|
-
let artifactPaths;
|
|
276
|
-
if (ctx.artifactsDir) {
|
|
277
|
-
const index = ctx.flatStepCount > 1 ? ctx.flatIndex : undefined;
|
|
278
|
-
artifactPaths = getArtifactPaths(ctx.artifactsDir, ctx.id, step.agent, index);
|
|
279
|
-
fs.mkdirSync(ctx.artifactsDir, { recursive: true });
|
|
280
|
-
fs.writeFileSync(artifactPaths.inputPath, `# Task for ${step.agent}\n\n${task}`, "utf-8");
|
|
281
|
-
}
|
|
282
|
-
const eventsPath = path.join(path.dirname(ctx.outputFile), "events.jsonl");
|
|
283
|
-
let nativeExecution;
|
|
284
|
-
let nativeSegments = [];
|
|
285
|
-
const nativeAttempt = (segment) => {
|
|
286
|
-
const state = segment.execution;
|
|
287
|
-
const error = state?.error ?? segment.event.submission.error
|
|
288
|
-
?? (state?.exitCode && !state.interrupted ? formatProcessExitFailure({ agent: step.agent, exitCode: state.exitCode, durationMs: segment.durationMs }) : undefined);
|
|
289
|
-
return {
|
|
290
|
-
...nativeExecution, exitCode: error && !state?.exitCode ? 1 : state?.exitCode ?? 0, error,
|
|
291
|
-
interrupted: state?.interrupted, timedOut: state?.timedOut, resourceLimitExceeded: state?.resourceLimitExceeded,
|
|
292
|
-
terminalFailure: Boolean(segment.event.submission.error) || state?.terminalFailure,
|
|
293
|
-
messages: segment.messages, usage: segment.usage, durationMs: segment.durationMs,
|
|
294
|
-
finalOutput: segment.event.submission.output, reportSubmission: segment.event.turn > 0 ? segment.event.submission : undefined,
|
|
295
|
-
resolvedOutput: segment.event.resolvedOutput, finalization: undefined,
|
|
296
|
-
};
|
|
297
|
-
};
|
|
298
|
-
async function runAttempt(prompt, model, review) {
|
|
299
|
-
if (verificationSignal.aborted) {
|
|
300
|
-
const outcome = resolveExecutionOutcome({ result: { exitCode: 1 }, signal: ctx.signal, interruptSignal });
|
|
301
|
-
return { stderr: "", messages: [], usage: emptyUsage(), durationMs: 0, observedCompletedMutation: false, finalOutput: outcome.error ?? "Interrupted. Waiting for explicit next action.",
|
|
302
|
-
...outcome, exitCode: outcome.exitCode ?? 1, model, terminalFailure: true, resolvedOutput: { fullOutput: "" } };
|
|
303
|
-
}
|
|
304
|
-
ctx.onAttemptStart?.({ model, thinking: resolveEffectiveThinking(model, step.thinking) });
|
|
305
|
-
const structuredRuntime = review ? review.reportRuntime : effectiveStructuredOutput;
|
|
306
|
-
const outputSnapshot = review ? review.outputSnapshot : captureSingleOutputSnapshot(step.outputPath);
|
|
307
|
-
if (structuredRuntime) {
|
|
308
|
-
try {
|
|
309
|
-
fs.rmSync(structuredRuntime.outputPath, { force: true });
|
|
310
|
-
}
|
|
311
|
-
catch {
|
|
312
|
-
// readStructuredOutput reports unreadable or stale output after the attempt.
|
|
313
|
-
}
|
|
314
|
-
}
|
|
315
|
-
let args;
|
|
316
|
-
let env;
|
|
317
|
-
let tempDir;
|
|
318
|
-
let claudeCodeInvocation;
|
|
319
|
-
const sessionFile = review?.sessionFile ?? step.sessionFile;
|
|
320
|
-
const nativeFinalization = ctx.nativeFinalization && !review && !isClaudeCodeModel(model) && step.effectiveAcceptance?.explicit
|
|
321
|
-
? createNativeFinalization(step.effectiveAcceptance, structuredRuntime, step.outputPath) : undefined;
|
|
43
|
+
function launchConfig(text, file) {
|
|
44
|
+
const value = JSON.parse(text);
|
|
45
|
+
const config = parseSubagentRunConfig(value);
|
|
46
|
+
if (file !== undefined && config.runtimeVersion !== 2) {
|
|
322
47
|
try {
|
|
323
|
-
|
|
324
|
-
task: prompt, model, thinking: step.thinking,
|
|
325
|
-
sessionEnabled: review ? true : sessionEnabled, sessionDir: review ? undefined : sessionDir, sessionFile,
|
|
326
|
-
inheritProjectContext: step.inheritProjectContext, inheritSkills: step.inheritSkills,
|
|
327
|
-
tools: step.tools, allowSubagents: step.allowSubagents, extensions: step.extensions,
|
|
328
|
-
systemPrompt: step.systemPrompt, systemPromptMode: step.systemPromptMode, mcpDirectTools: step.mcpDirectTools,
|
|
329
|
-
cwd: step.cwd ?? ctx.cwd, intercomSessionName: ctx.childIntercomTarget, orchestratorIntercomTarget: ctx.orchestratorIntercomTarget,
|
|
330
|
-
runId: ctx.id, childAgentName: step.agent, childIndex: ctx.flatIndex, rootSessionId: ctx.rootSessionId,
|
|
331
|
-
parentEventSink: ctx.nestedRoute?.eventSink, parentControlInbox: ctx.nestedRoute?.controlInbox,
|
|
332
|
-
parentRootRunId: ctx.nestedRoute?.rootRunId, parentCapabilityToken: ctx.nestedRoute?.capabilityToken,
|
|
333
|
-
structuredOutput: structuredRuntime, projectTrust: ctx.projectTrust, nativeFinalization,
|
|
334
|
-
});
|
|
335
|
-
args = built.args;
|
|
336
|
-
env = built.env;
|
|
337
|
-
tempDir = built.tempDir;
|
|
338
|
-
claudeCodeInvocation = built.claudeCodeInvocation;
|
|
339
|
-
}
|
|
340
|
-
catch (error) {
|
|
341
|
-
if (nativeFinalization)
|
|
342
|
-
cleanupTempDir(path.dirname(nativeFinalization.reportRuntime.schemaPath));
|
|
343
|
-
const message = error instanceof Error ? error.message : String(error);
|
|
344
|
-
return { stderr: message, exitCode: 1, messages: [], usage: emptyUsage(), durationMs: 0, observedCompletedMutation: false, model, error: message,
|
|
345
|
-
finalOutput: message, terminalFailure: true, resolvedOutput: { fullOutput: message } };
|
|
346
|
-
}
|
|
347
|
-
let run;
|
|
348
|
-
try {
|
|
349
|
-
run = await runPiStreaming({ args, cwd: step.cwd ?? ctx.cwd, env, agent: step.agent, model,
|
|
350
|
-
maxSubagentDepth: step.maxSubagentDepth, maxExecutionTimeMs: step.maxExecutionTimeMs, maxTokens: step.maxTokens,
|
|
351
|
-
interruptSignal, signal: ctx.signal, claudeCodeInvocation, sessionFile,
|
|
352
|
-
structuredOutput: structuredRuntime, reportRuntime: review?.reportRuntime, nativeFinalization,
|
|
353
|
-
onEvent: (event, result, mutation) => {
|
|
354
|
-
if (event.type === "tool_execution_start")
|
|
355
|
-
toolCount++;
|
|
356
|
-
if (event.type === "message_end" && event.message?.role === "assistant") {
|
|
357
|
-
toolCalls.push(...(compactForegroundResult({ agent: step.agent, task: step.task, exitCode: 0, usage: result.usage, messages: [event.message] }).toolCalls ?? []));
|
|
358
|
-
}
|
|
359
|
-
ctx.onChildEvent?.(event, mutation);
|
|
360
|
-
},
|
|
361
|
-
}, review ? `${ctx.outputFile}.finalization-${review.turn}.log` : ctx.outputFile, { eventsPath, runId: ctx.id, stepIndex: ctx.flatIndex, agent: step.agent });
|
|
362
|
-
}
|
|
363
|
-
finally {
|
|
364
|
-
cleanupTempDir(tempDir);
|
|
365
|
-
if (nativeFinalization)
|
|
366
|
-
cleanupTempDir(path.dirname(nativeFinalization.reportRuntime.schemaPath));
|
|
367
|
-
}
|
|
368
|
-
const initialSegment = nativeFinalization ? run.finalization?.[0] : undefined;
|
|
369
|
-
if (initialSegment) {
|
|
370
|
-
nativeExecution = run;
|
|
371
|
-
nativeSegments = run.finalization.slice(1);
|
|
372
|
-
run = nativeAttempt(initialSegment);
|
|
373
|
-
}
|
|
374
|
-
const reportSubmission = review?.reportRuntime ? readFinalizationReport(run.messages, review.reportRuntime, { structuredResult: Boolean(claudeCodeInvocation) }) : undefined;
|
|
375
|
-
const hiddenError = run.exitCode === 0 && !run.error && !reportSubmission?.output ? detectSubagentError(run.messages) : undefined;
|
|
376
|
-
let structuredOutput;
|
|
377
|
-
let structuredError;
|
|
378
|
-
if (!review && structuredRuntime && run.exitCode === 0 && !run.error && !hiddenError?.hasError && !run.interrupted) {
|
|
379
|
-
const structured = readStructuredOutput(structuredRuntime);
|
|
380
|
-
structuredError = structured.error;
|
|
381
|
-
structuredOutput = structured.value;
|
|
382
|
-
}
|
|
383
|
-
const completionGuardTriggered = !review && run.exitCode === 0 && !run.error && !hiddenError?.hasError && !run.interrupted
|
|
384
|
-
&& resolveCompletionPolicy({ completionGuardEnabled: step.completionGuard === true, usesAcceptanceContract: step.effectiveAcceptance?.explicit === true }) === "mutation-guard"
|
|
385
|
-
&& !run.observedCompletedMutation && !hasCompletedMutationToolCall(run.messages);
|
|
386
|
-
let error = completionGuardTriggered
|
|
387
|
-
? "Subagent completed without making edits required by completionGuard: true.\nUse an acceptance contract when a valid no-op is allowed."
|
|
388
|
-
: structuredError ?? (hiddenError?.hasError
|
|
389
|
-
? hiddenError.details ? `${hiddenError.errorType} failed (exit ${hiddenError.exitCode ?? 1}): ${hiddenError.details}` : `${hiddenError.errorType} failed with exit code ${hiddenError.exitCode ?? 1}`
|
|
390
|
-
: run.error || (run.exitCode !== 0 ? run.stderr.trim() || formatProcessExitFailure({ agent: step.agent, exitCode: run.exitCode, durationMs: run.durationMs }) : undefined));
|
|
391
|
-
let exitCode = completionGuardTriggered || structuredError ? 1 : hiddenError?.hasError ? hiddenError.exitCode ?? 1 : error && run.exitCode === 0 ? 1 : run.exitCode;
|
|
392
|
-
const finalOutput = reportSubmission?.output ?? run.finalOutput;
|
|
393
|
-
const fullOutput = review ? resolveFinalizationOutput(finalOutput, review.previousOutput) : stripAcceptanceReport(finalOutput);
|
|
394
|
-
const resolvedOutput = initialSegment ? initialSegment.event.resolvedOutput : step.outputPath && exitCode === 0 && !run.interrupted && !reportSubmission?.reportSubmissionError
|
|
395
|
-
? resolveSingleOutput(step.outputPath, fullOutput, outputSnapshot)
|
|
396
|
-
: { fullOutput };
|
|
397
|
-
if (resolvedOutput.saveError) {
|
|
398
|
-
exitCode = 1;
|
|
399
|
-
error = `Failed to save output file '${step.outputPath}': ${resolvedOutput.saveError}`;
|
|
400
|
-
}
|
|
401
|
-
return { ...run, exitCode, error, model: model ?? run.model, structuredOutput, reportSubmission, finalOutput, resolvedOutput, completionGuardTriggered,
|
|
402
|
-
terminalFailure: Boolean(completionGuardTriggered || structuredError || hiddenError?.hasError || resolvedOutput.saveError) };
|
|
403
|
-
}
|
|
404
|
-
const { result: initial, modelAttempts, attemptedModels, notes: attemptNotes } = await runModelAttempts({
|
|
405
|
-
candidates: step.modelCandidates?.length ? step.modelCandidates : [step.model], signal: verificationSignal,
|
|
406
|
-
runAttempt: (model) => runAttempt(task, model),
|
|
407
|
-
});
|
|
408
|
-
for (const segment of nativeSegments) {
|
|
409
|
-
const attempt = nativeAttempt(segment);
|
|
410
|
-
modelAttempts.push({ model: attempt.model ?? "default", success: attempt.exitCode === 0 && !attempt.error && !attempt.interrupted,
|
|
411
|
-
exitCode: attempt.exitCode, error: attempt.error, accounting: attempt.accounting, usage: { ...attempt.usage } });
|
|
412
|
-
}
|
|
413
|
-
let execution = initial;
|
|
414
|
-
let structuredOutput = initial.structuredOutput;
|
|
415
|
-
let resolvedOutput = initial.resolvedOutput;
|
|
416
|
-
let output = stripAcceptanceReport(resolvedOutput.fullOutput);
|
|
417
|
-
const initialOutput = output;
|
|
418
|
-
const sessionFile = step.sessionFile ?? (sessionDir ? findLatestSessionFile(sessionDir) ?? undefined : undefined);
|
|
419
|
-
const nativeReport = !initial.model || !isClaudeCodeModel(initial.model);
|
|
420
|
-
const acceptance = step.effectiveAcceptance ? await evaluateRunAcceptance({
|
|
421
|
-
acceptance: step.effectiveAcceptance, initial, initialOutput: initial.finalOutput, sessionFile, cwd: step.cwd ?? ctx.cwd, signal: verificationSignal, nativeReport, outputSchema: effectiveStructuredOutput?.schema, recordedTurns: nativeSegments.length,
|
|
422
|
-
initialAcceptance: nativeExecution?.finalization?.[0]?.event.acceptance,
|
|
423
|
-
runTurn: async (prompt, turn, sessionFile) => {
|
|
424
|
-
const cached = nativeSegments[turn - 1];
|
|
425
|
-
const reportRuntime = !cached && (nativeReport || effectiveStructuredOutput) ? createFinalizationReportRuntime(effectiveStructuredOutput?.schema) : undefined;
|
|
426
|
-
let reviewed;
|
|
427
|
-
try {
|
|
428
|
-
reviewed = cached ? nativeAttempt(cached) : await runAttempt(prompt, initial.model ?? step.model, { turn, sessionFile, previousOutput: output, reportRuntime,
|
|
429
|
-
outputSnapshot: nativeReport ? resolvedOutput.writtenSnapshot : undefined });
|
|
430
|
-
}
|
|
431
|
-
finally {
|
|
432
|
-
if (reportRuntime)
|
|
433
|
-
cleanupTempDir(path.dirname(reportRuntime.schemaPath));
|
|
434
|
-
}
|
|
435
|
-
execution = reviewed;
|
|
436
|
-
if (!cached)
|
|
437
|
-
modelAttempts.push({ model: reviewed.model ?? "default", success: reviewed.exitCode === 0 && !reviewed.error && !reviewed.interrupted,
|
|
438
|
-
exitCode: reviewed.exitCode, error: reviewed.error, accounting: reviewed.accounting, usage: { ...reviewed.usage } });
|
|
439
|
-
if (reviewed.exitCode !== 0 || reviewed.error || reviewed.interrupted)
|
|
440
|
-
return { ...reviewed.reportSubmission, output: reviewed.finalOutput,
|
|
441
|
-
error: reviewed.error ?? reviewed.resourceLimitExceeded?.message ?? "Acceptance finalization turn did not complete successfully." };
|
|
442
|
-
if (reviewed.reportSubmission?.reportSubmissionError)
|
|
443
|
-
return reviewed.reportSubmission;
|
|
444
|
-
if (effectiveStructuredOutput && reviewed.reportSubmission?.structuredOutput !== undefined) {
|
|
445
|
-
structuredOutput = reviewed.reportSubmission.structuredOutput;
|
|
446
|
-
fs.writeFileSync(effectiveStructuredOutput.outputPath, JSON.stringify(structuredOutput), { mode: 0o600 });
|
|
447
|
-
}
|
|
448
|
-
resolvedOutput = reviewed.resolvedOutput;
|
|
449
|
-
output = stripAcceptanceReport(resolvedOutput.fullOutput);
|
|
450
|
-
return { ...reviewed.reportSubmission, output: reviewed.finalOutput, acceptance: cached?.event.acceptance };
|
|
451
|
-
},
|
|
452
|
-
}) : undefined;
|
|
453
|
-
const outcome = resolveExecutionOutcome({ result: execution, acceptance, signal: ctx.signal, interruptSignal });
|
|
454
|
-
const previousError = modelAttempts.slice(0, -1).reverse().find((attempt) => attempt.error)?.error;
|
|
455
|
-
if (outcome.exitCode !== 0 && outcome.error && previousError && execution.usage.turns === 0) {
|
|
456
|
-
const context = `Previous attempt before the empty retry failed with: ${previousError}`;
|
|
457
|
-
outcome.error += `\n${context}`;
|
|
458
|
-
output = output ? `${output}\n${context}` : outcome.error;
|
|
459
|
-
}
|
|
460
|
-
if (acceptance?.unconfirmedOutput !== undefined) {
|
|
461
|
-
const auditOutput = resolvedOutput.savedPath && !resolvedOutput.writtenSnapshot ? output : acceptance.unconfirmedOutput;
|
|
462
|
-
output = formatUnconfirmedFinalizationOutput(auditOutput);
|
|
463
|
-
}
|
|
464
|
-
if (outcome.timedOut) {
|
|
465
|
-
const reason = outcome.error ?? "Timed out.";
|
|
466
|
-
const partial = output.trim();
|
|
467
|
-
output = partial && partial !== reason ? `${reason}\n\nPartial output before timeout:\n${partial}` : reason;
|
|
468
|
-
}
|
|
469
|
-
const effectiveFinalExitCode = outcome.exitCode ?? 1;
|
|
470
|
-
const cleanup = effectiveFinalExitCode === 0 && !outcome.interrupted && resolvedOutput.savedPath && step.outputMode !== "file-only" && step.outputPathFromAgentDefault === true
|
|
471
|
-
? cleanupSingleOutputFile(resolvedOutput.savedPath, output, undefined)
|
|
472
|
-
: undefined;
|
|
473
|
-
if (ctx.worktreePath && resolvedOutput.savedPath && (!cleanup || cleanup.action === "skipped")) {
|
|
474
|
-
const relative = path.relative(ctx.worktreePath, resolvedOutput.savedPath);
|
|
475
|
-
if (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative)) {
|
|
476
|
-
const savedPath = path.join(path.dirname(ctx.outputFile), "outputs", String(ctx.flatIndex), path.basename(resolvedOutput.savedPath));
|
|
477
|
-
fs.mkdirSync(path.dirname(savedPath), { recursive: true });
|
|
478
|
-
fs.copyFileSync(resolvedOutput.savedPath, savedPath);
|
|
479
|
-
resolvedOutput.savedPath = savedPath;
|
|
48
|
+
fs.unlinkSync(file);
|
|
480
49
|
}
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
? cleanup ? formatConsumedOutputReference(resolvedOutput.savedPath, output, cleanup) : formatSavedOutputReference(resolvedOutput.savedPath, output)
|
|
484
|
-
: undefined;
|
|
485
|
-
const outputForSummary = finalizeSingleOutput({
|
|
486
|
-
fullOutput: attemptNotes.length ? `${attemptNotes.join("\n")}\n\n${output}`.trim() : output,
|
|
487
|
-
outputPath: step.outputPath, outputMode: step.outputMode, exitCode: effectiveFinalExitCode,
|
|
488
|
-
savedPath: resolvedOutput.savedPath, outputReference, saveError: resolvedOutput.saveError, cleanup,
|
|
489
|
-
}).displayOutput;
|
|
490
|
-
const usage = sumAttemptUsage(modelAttempts);
|
|
491
|
-
const progressSummary = { toolCount, tokens: usage.input + usage.output, durationMs: Date.now() - startedAt };
|
|
492
|
-
recordRun(step.agent, step.task, effectiveFinalExitCode, progressSummary.durationMs);
|
|
493
|
-
if (artifactPaths) {
|
|
494
|
-
fs.writeFileSync(artifactPaths.outputPath, output, "utf-8");
|
|
495
|
-
fs.writeFileSync(artifactPaths.metadataPath, JSON.stringify({
|
|
496
|
-
runId: ctx.id, agent: step.agent, task, exitCode: effectiveFinalExitCode, interrupted: outcome.interrupted, agentProcessExit: execution.agentProcessExit,
|
|
497
|
-
error: outcome.error, acceptance, initialOutput: acceptance?.finalization ? initialOutput : undefined, usage,
|
|
498
|
-
model: initial.model, attemptedModels: attemptedModels.length ? attemptedModels : undefined, modelAttempts,
|
|
499
|
-
resourceLimitExceeded: outcome.resourceLimitExceeded, skills: step.skills, timestamp: Date.now(),
|
|
500
|
-
}, null, 2), "utf-8");
|
|
501
|
-
}
|
|
502
|
-
const result = {
|
|
503
|
-
accounting: modelAttempts.find((attempt) => attempt.accounting?.state === "incomplete")?.accounting ?? execution.accounting,
|
|
504
|
-
nativeSessionId: execution.nativeSessionId, terminalLeafId: execution.terminalLeafId, terminalEntryId: execution.terminalEntryId,
|
|
505
|
-
auditPath: execution.auditPath, auditSaveError: execution.auditSaveError,
|
|
506
|
-
agent: step.agent, output: outputForSummary, exitCode: effectiveFinalExitCode, error: outcome.error, agentProcessExit: execution.agentProcessExit,
|
|
507
|
-
usage, timedOut: outcome.timedOut, task: step.task, skills: step.skills,
|
|
508
|
-
finalOutput: step.outputMode === "file-only" ? outputForSummary : output,
|
|
509
|
-
initialOutput: acceptance?.finalization ? initialOutput : undefined,
|
|
510
|
-
outputMode: step.outputMode ?? "inline", outputReference, outputCleanup: cleanup, outputSaveError: resolvedOutput.saveError,
|
|
511
|
-
savedOutputPath: cleanup && cleanup.action !== "skipped" ? undefined : resolvedOutput.savedPath,
|
|
512
|
-
toolCalls: toolCalls.length ? toolCalls : undefined, progressSummary,
|
|
513
|
-
sessionFile, intercomTarget: ctx.childIntercomTarget, model: initial.model,
|
|
514
|
-
attemptedModels: attemptedModels.length ? attemptedModels : undefined, modelAttempts, artifactPaths,
|
|
515
|
-
interrupted: outcome.interrupted, completionGuardTriggered: initial.completionGuardTriggered,
|
|
516
|
-
structuredOutput, structuredOutputPath: effectiveStructuredOutput?.outputPath,
|
|
517
|
-
structuredOutputSchemaPath: effectiveStructuredOutput?.schemaPath, acceptance, resourceLimitExceeded: outcome.resourceLimitExceeded,
|
|
518
|
-
};
|
|
519
|
-
saveQuestionContract(ctx.id, ctx.flatIndex, { result: { ...result, task: step.task, usage, finalOutput: result.finalOutput }, updatedAt: Date.now() });
|
|
520
|
-
return result;
|
|
521
|
-
}
|
|
522
|
-
function markParallelGroupSetupFailure(input) {
|
|
523
|
-
for (let taskIndex = 0; taskIndex < input.group.parallel.length; taskIndex++) {
|
|
524
|
-
const flatTaskIndex = input.groupStartFlatIndex + taskIndex;
|
|
525
|
-
input.statusPayload.steps[flatTaskIndex].status = "failed";
|
|
526
|
-
input.statusPayload.steps[flatTaskIndex].startedAt = input.failedAt;
|
|
527
|
-
input.statusPayload.steps[flatTaskIndex].endedAt = input.failedAt;
|
|
528
|
-
input.statusPayload.steps[flatTaskIndex].durationMs = 0;
|
|
529
|
-
input.statusPayload.steps[flatTaskIndex].exitCode = 1;
|
|
530
|
-
input.results.push({ agent: input.group.parallel[taskIndex].agent, output: input.setupError, success: false, exitCode: 1, sessionFile: input.group.parallel[taskIndex].sessionFile });
|
|
531
|
-
}
|
|
532
|
-
input.statusPayload.currentStep = input.groupStartFlatIndex;
|
|
533
|
-
input.statusPayload.lastUpdate = input.failedAt;
|
|
534
|
-
input.statusPayload.outputFile = path.join(input.asyncDir, `output-${input.groupStartFlatIndex}.log`);
|
|
535
|
-
writeAtomicJson(input.statusPath, input.statusPayload);
|
|
536
|
-
appendJsonl(input.eventsPath, JSON.stringify({
|
|
537
|
-
type: "subagent.parallel.completed",
|
|
538
|
-
ts: input.failedAt,
|
|
539
|
-
runId: input.runId,
|
|
540
|
-
stepIndex: input.stepIndex,
|
|
541
|
-
success: false,
|
|
542
|
-
}));
|
|
543
|
-
}
|
|
544
|
-
function markParallelGroupRunning(input) {
|
|
545
|
-
for (let taskIndex = 0; taskIndex < input.group.parallel.length; taskIndex++) {
|
|
546
|
-
const flatTaskIndex = input.groupStartFlatIndex + taskIndex;
|
|
547
|
-
input.statusPayload.steps[flatTaskIndex].status = "pending";
|
|
548
|
-
input.statusPayload.steps[flatTaskIndex].startedAt = undefined;
|
|
549
|
-
input.statusPayload.steps[flatTaskIndex].endedAt = undefined;
|
|
550
|
-
input.statusPayload.steps[flatTaskIndex].durationMs = undefined;
|
|
551
|
-
input.statusPayload.steps[flatTaskIndex].lastActivityAt = undefined;
|
|
552
|
-
input.statusPayload.steps[flatTaskIndex].activityState = undefined;
|
|
553
|
-
input.statusPayload.steps[flatTaskIndex].error = undefined;
|
|
554
|
-
}
|
|
555
|
-
input.statusPayload.currentStep = input.groupStartFlatIndex;
|
|
556
|
-
input.statusPayload.activityState = undefined;
|
|
557
|
-
input.statusPayload.lastActivityAt = input.groupStartTime;
|
|
558
|
-
input.statusPayload.lastUpdate = input.groupStartTime;
|
|
559
|
-
input.statusPayload.outputFile = path.join(input.asyncDir, `output-${input.groupStartFlatIndex}.log`);
|
|
560
|
-
writeAtomicJson(input.statusPath, input.statusPayload);
|
|
561
|
-
appendJsonl(input.eventsPath, JSON.stringify({
|
|
562
|
-
type: "subagent.parallel.started",
|
|
563
|
-
ts: input.groupStartTime,
|
|
564
|
-
runId: input.runId,
|
|
565
|
-
stepIndex: input.stepIndex,
|
|
566
|
-
agents: input.group.parallel.map((task) => task.agent),
|
|
567
|
-
count: input.group.parallel.length,
|
|
568
|
-
}));
|
|
569
|
-
}
|
|
570
|
-
function prepareParallelTaskRun(task, cwd, worktreeSetup, taskIndex) {
|
|
571
|
-
if (!worktreeSetup)
|
|
572
|
-
return { taskForRun: task, taskCwd: cwd };
|
|
573
|
-
return {
|
|
574
|
-
taskForRun: { ...task, cwd: undefined },
|
|
575
|
-
taskCwd: worktreeSetup.worktrees[taskIndex].agentCwd,
|
|
576
|
-
};
|
|
577
|
-
}
|
|
578
|
-
function formatRunnerWorktreeSummary(worktreeSetup, asyncDir, stepIndex, group) {
|
|
579
|
-
return formatParallelWorktreeSummary(worktreeSetup, path.join(asyncDir, "worktree-diffs", `step-${stepIndex}`), group.parallel.map((task) => task.agent));
|
|
580
|
-
}
|
|
581
|
-
function ensureParallelProgressFile(cwd, group) {
|
|
582
|
-
const progressPath = path.join(cwd, "progress.md");
|
|
583
|
-
if (!group.parallel.some((task) => task.task.includes(`Update progress at: ${progressPath}`)))
|
|
584
|
-
return;
|
|
585
|
-
writeInitialProgressFile(cwd);
|
|
586
|
-
}
|
|
587
|
-
function materializeDynamicOutputPath(input) {
|
|
588
|
-
if (!input.step.output || !input.step.outputPath)
|
|
589
|
-
return input.step;
|
|
590
|
-
const output = namespaceParallelOutput(input.step.output, input.step.agent, input.stepIndex, input.taskIndex);
|
|
591
|
-
if (!output)
|
|
592
|
-
return input.step;
|
|
593
|
-
const outputPath = path.resolve(input.chainDir, output);
|
|
594
|
-
const task = input.step.task.includes(input.step.outputPath)
|
|
595
|
-
? input.step.task.split(input.step.outputPath).join(outputPath)
|
|
596
|
-
: injectSingleOutputInstruction(input.step.task, outputPath);
|
|
597
|
-
return { ...input.step, task, outputPath };
|
|
598
|
-
}
|
|
599
|
-
async function runSubagent(config) {
|
|
600
|
-
const { id, steps, resultPath, cwd, placeholder, taskIndex, totalTasks, maxOutput, artifactsDir } = config;
|
|
601
|
-
let previousOutput = "";
|
|
602
|
-
const outputs = {};
|
|
603
|
-
const renderTask = (template, item) => config.resultMode === "single" || config.resultMode === "parallel" ? template
|
|
604
|
-
: renderChainTask(template, { originalTask: config.originalTask, previousOutput, chainDir: config.chainDir, outputs, item }, placeholder);
|
|
605
|
-
const results = [];
|
|
606
|
-
const worktreeSummaries = [];
|
|
607
|
-
let setupCleanupWarning = "";
|
|
608
|
-
const overallStartTime = Date.now();
|
|
609
|
-
const shareEnabled = config.share === true;
|
|
610
|
-
const asyncDir = config.asyncDir;
|
|
611
|
-
const statusPath = path.join(asyncDir, "status.json");
|
|
612
|
-
const eventsPath = path.join(asyncDir, "events.jsonl");
|
|
613
|
-
const logPath = path.join(asyncDir, `subagent-log-${id}.md`);
|
|
614
|
-
const controlConfig = config.controlConfig ?? DEFAULT_CONTROL_CONFIG;
|
|
615
|
-
const cancellation = new AbortController();
|
|
616
|
-
const cancelRunner = () => cancellation.abort();
|
|
617
|
-
for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"])
|
|
618
|
-
process.on(signal, cancelRunner);
|
|
619
|
-
const activeChildInterrupts = new Map();
|
|
620
|
-
const interruption = new AbortController();
|
|
621
|
-
let interrupted = false;
|
|
622
|
-
let currentActivityState;
|
|
623
|
-
let activityTimer;
|
|
624
|
-
let controlRequestTimer;
|
|
625
|
-
let latestSessionFile;
|
|
626
|
-
const parallelGroups = [];
|
|
627
|
-
const initialStatusSteps = [];
|
|
628
|
-
let flatStepCount = 0;
|
|
629
|
-
for (let stepIndex = 0; stepIndex < steps.length; stepIndex++) {
|
|
630
|
-
const step = steps[stepIndex];
|
|
631
|
-
if (isParallelGroup(step)) {
|
|
632
|
-
parallelGroups.push({ start: flatStepCount, count: step.parallel.length, stepIndex });
|
|
633
|
-
for (const task of step.parallel) {
|
|
634
|
-
initialStatusSteps.push({
|
|
635
|
-
agent: task.agent,
|
|
636
|
-
phase: task.phase,
|
|
637
|
-
label: task.label,
|
|
638
|
-
outputName: task.outputName,
|
|
639
|
-
structured: task.structured,
|
|
640
|
-
status: "pending",
|
|
641
|
-
...(task.sessionFile ? { sessionFile: task.sessionFile } : {}),
|
|
642
|
-
skills: task.skills,
|
|
643
|
-
model: task.model,
|
|
644
|
-
thinking: task.thinking,
|
|
645
|
-
attemptedModels: task.modelCandidates && task.modelCandidates.length > 0 ? task.modelCandidates : task.model ? [task.model] : undefined,
|
|
646
|
-
recentTools: [],
|
|
647
|
-
recentOutput: [],
|
|
648
|
-
});
|
|
649
|
-
}
|
|
650
|
-
flatStepCount += step.parallel.length;
|
|
651
|
-
}
|
|
652
|
-
else if (isDynamicRunnerGroup(step)) {
|
|
653
|
-
parallelGroups.push({ start: flatStepCount, count: 1, stepIndex });
|
|
654
|
-
initialStatusSteps.push({
|
|
655
|
-
agent: `expand:${step.parallel.agent}`,
|
|
656
|
-
phase: step.phase ?? step.parallel.phase,
|
|
657
|
-
label: step.label ?? step.parallel.label ?? `Dynamic fanout (${step.collect.as})`,
|
|
658
|
-
outputName: step.collect.as,
|
|
659
|
-
structured: Boolean(step.collect.outputSchema),
|
|
660
|
-
status: "pending",
|
|
661
|
-
recentTools: [],
|
|
662
|
-
recentOutput: [],
|
|
663
|
-
});
|
|
664
|
-
flatStepCount++;
|
|
665
|
-
}
|
|
666
|
-
else {
|
|
667
|
-
initialStatusSteps.push({
|
|
668
|
-
agent: step.agent,
|
|
669
|
-
phase: step.phase,
|
|
670
|
-
label: step.label,
|
|
671
|
-
outputName: step.outputName,
|
|
672
|
-
structured: step.structured,
|
|
673
|
-
status: "pending",
|
|
674
|
-
...(step.sessionFile ? { sessionFile: step.sessionFile } : {}),
|
|
675
|
-
skills: step.skills,
|
|
676
|
-
model: step.model,
|
|
677
|
-
thinking: step.thinking,
|
|
678
|
-
attemptedModels: step.modelCandidates && step.modelCandidates.length > 0 ? step.modelCandidates : step.model ? [step.model] : undefined,
|
|
679
|
-
recentTools: [],
|
|
680
|
-
recentOutput: [],
|
|
681
|
-
});
|
|
682
|
-
flatStepCount++;
|
|
683
|
-
}
|
|
684
|
-
}
|
|
685
|
-
const flatSteps = flattenSteps(steps);
|
|
686
|
-
const sessionEnabled = Boolean(config.sessionDir)
|
|
687
|
-
|| shareEnabled
|
|
688
|
-
|| flatSteps.some((step) => Boolean(step.sessionFile));
|
|
689
|
-
const statusPayload = {
|
|
690
|
-
runId: id,
|
|
691
|
-
runtimeVersion: config.runtimeVersion,
|
|
692
|
-
indexedControl: true,
|
|
693
|
-
controlRequestFiles: true,
|
|
694
|
-
...(config.sessionId ? { sessionId: config.sessionId } : {}),
|
|
695
|
-
mode: config.resultMode ?? (flatSteps.length > 1 ? "chain" : "single"),
|
|
696
|
-
state: "running",
|
|
697
|
-
lastActivityAt: overallStartTime,
|
|
698
|
-
startedAt: overallStartTime,
|
|
699
|
-
lastUpdate: overallStartTime,
|
|
700
|
-
pid: process.pid,
|
|
701
|
-
cwd,
|
|
702
|
-
currentStep: 0,
|
|
703
|
-
chainStepCount: steps.length,
|
|
704
|
-
parallelGroups,
|
|
705
|
-
workflowGraph: config.workflowGraph,
|
|
706
|
-
steps: initialStatusSteps,
|
|
707
|
-
artifactsDir,
|
|
708
|
-
sessionDir: config.sessionDir,
|
|
709
|
-
outputFile: path.join(asyncDir, "output-0.log"),
|
|
710
|
-
};
|
|
711
|
-
fs.mkdirSync(asyncDir, { recursive: true });
|
|
712
|
-
writeAtomicJson(statusPath, statusPayload);
|
|
713
|
-
if (config.runtimeVersion !== 2)
|
|
714
|
-
saveRunStatus(id, statusPayload);
|
|
715
|
-
const emitNestedSelfEvent = (type) => {
|
|
716
|
-
if (!config.nestedRoute || !config.nestedSelf)
|
|
717
|
-
return;
|
|
718
|
-
try {
|
|
719
|
-
writeNestedEvent(config.nestedRoute, {
|
|
720
|
-
type,
|
|
721
|
-
ts: Date.now(),
|
|
722
|
-
parentRunId: config.nestedSelf.parentRunId,
|
|
723
|
-
parentStepIndex: config.nestedSelf.parentStepIndex,
|
|
724
|
-
child: nestedSummaryFromAsyncStatus(statusPayload, asyncDir, {
|
|
725
|
-
id,
|
|
726
|
-
parentRunId: config.nestedSelf.parentRunId,
|
|
727
|
-
parentStepIndex: config.nestedSelf.parentStepIndex,
|
|
728
|
-
depth: config.nestedSelf.depth,
|
|
729
|
-
path: config.nestedSelf.path,
|
|
730
|
-
mode: statusPayload.mode,
|
|
731
|
-
ts: Date.now(),
|
|
732
|
-
}),
|
|
733
|
-
});
|
|
734
|
-
}
|
|
735
|
-
catch (error) {
|
|
736
|
-
console.error("Failed to emit nested async status event:", error);
|
|
737
|
-
}
|
|
738
|
-
};
|
|
739
|
-
const refreshWorkflowGraph = () => {
|
|
740
|
-
if (!config.workflowGraph)
|
|
741
|
-
return;
|
|
742
|
-
const graph = structuredClone(statusPayload.workflowGraph ?? config.workflowGraph);
|
|
743
|
-
const normalize = (status) => {
|
|
744
|
-
if (status === "complete" || status === "completed")
|
|
745
|
-
return "completed";
|
|
746
|
-
if (status === "running" || status === "failed" || status === "blocked" || status === "paused" || status === "pending")
|
|
747
|
-
return status;
|
|
748
|
-
return "pending";
|
|
749
|
-
};
|
|
750
|
-
const updateNode = (node) => {
|
|
751
|
-
if (node.flatIndex !== undefined) {
|
|
752
|
-
const step = statusPayload.steps[node.flatIndex];
|
|
753
|
-
if (step) {
|
|
754
|
-
node.status = normalize(step.status);
|
|
755
|
-
node.error = step.error;
|
|
756
|
-
node.acceptanceStatus = step.acceptance?.status;
|
|
757
|
-
}
|
|
758
|
-
if (statusPayload.currentStep === node.flatIndex)
|
|
759
|
-
graph.currentNodeId = node.id;
|
|
760
|
-
}
|
|
761
|
-
for (const child of node.children ?? [])
|
|
762
|
-
updateNode(child);
|
|
763
|
-
if (node.children?.length) {
|
|
764
|
-
if (node.children.every((child) => child.status === "completed"))
|
|
765
|
-
node.status = "completed";
|
|
766
|
-
else if (node.children.some((child) => child.status === "running"))
|
|
767
|
-
node.status = "running";
|
|
768
|
-
else if (node.children.some((child) => child.status === "failed"))
|
|
769
|
-
node.status = "failed";
|
|
770
|
-
else if (node.children.some((child) => child.status === "blocked"))
|
|
771
|
-
node.status = "blocked";
|
|
772
|
-
else if (node.children.some((child) => child.status === "paused"))
|
|
773
|
-
node.status = "paused";
|
|
774
|
-
}
|
|
775
|
-
if (node.error)
|
|
776
|
-
node.status = "failed";
|
|
777
|
-
};
|
|
778
|
-
for (const node of graph.nodes)
|
|
779
|
-
updateNode(node);
|
|
780
|
-
statusPayload.workflowGraph = graph;
|
|
781
|
-
};
|
|
782
|
-
let statusWriteTimer;
|
|
783
|
-
const writeStatusPayload = () => {
|
|
784
|
-
if (statusWriteTimer) {
|
|
785
|
-
clearTimeout(statusWriteTimer);
|
|
786
|
-
statusWriteTimer = undefined;
|
|
787
|
-
}
|
|
788
|
-
refreshWorkflowGraph();
|
|
789
|
-
writeAtomicJson(statusPath, statusPayload);
|
|
790
|
-
if (config.runtimeVersion !== 2)
|
|
791
|
-
saveRunStatus(id, statusPayload);
|
|
792
|
-
emitNestedSelfEvent(statusPayload.state === "running" || statusPayload.state === "queued" ? "subagent.nested.updated" : "subagent.nested.completed");
|
|
793
|
-
};
|
|
794
|
-
const scheduleStatusWrite = () => {
|
|
795
|
-
if (statusWriteTimer)
|
|
796
|
-
return;
|
|
797
|
-
statusWriteTimer = setTimeout(writeStatusPayload, 200);
|
|
798
|
-
statusWriteTimer.unref?.();
|
|
799
|
-
};
|
|
800
|
-
let deadlineTimer;
|
|
801
|
-
statusPayload.timeoutAt = config.timeoutMs !== undefined ? overallStartTime + config.timeoutMs : undefined;
|
|
802
|
-
const scheduleDeadline = () => {
|
|
803
|
-
clearTimeout(deadlineTimer);
|
|
804
|
-
if (statusPayload.timeoutAt === undefined || cancellation.signal.aborted)
|
|
805
|
-
return;
|
|
806
|
-
const expire = () => {
|
|
807
|
-
statusPayload.timedOut = true;
|
|
808
|
-
statusPayload.error = `Timed out after ${statusPayload.timeoutAt - overallStartTime}ms.`;
|
|
809
|
-
cancellation.abort(new DOMException(statusPayload.error, "TimeoutError"));
|
|
810
|
-
writeStatusPayload();
|
|
811
|
-
};
|
|
812
|
-
const remaining = statusPayload.timeoutAt - Date.now();
|
|
813
|
-
if (remaining <= 0)
|
|
814
|
-
expire();
|
|
815
|
-
else {
|
|
816
|
-
deadlineTimer = setTimeout(expire, remaining);
|
|
817
|
-
deadlineTimer.unref();
|
|
818
|
-
}
|
|
819
|
-
};
|
|
820
|
-
scheduleDeadline();
|
|
821
|
-
writeStatusPayload();
|
|
822
|
-
const markDynamicGraphGroup = (stepIndex, status, error, acceptance) => {
|
|
823
|
-
const groupNode = statusPayload.workflowGraph?.nodes.find((node) => node.id === `step-${stepIndex}`);
|
|
824
|
-
if (!groupNode)
|
|
825
|
-
return;
|
|
826
|
-
groupNode.status = status;
|
|
827
|
-
groupNode.error = error;
|
|
828
|
-
groupNode.acceptanceStatus = acceptance?.status ?? groupNode.acceptanceStatus;
|
|
829
|
-
};
|
|
830
|
-
const refreshUsageTotals = () => {
|
|
831
|
-
statusPayload.totalTokens = statusPayload.steps.reduce((total, step) => ({
|
|
832
|
-
input: total.input + (step.tokens?.input ?? 0), output: total.output + (step.tokens?.output ?? 0), total: total.total + (step.tokens?.total ?? 0),
|
|
833
|
-
}), { input: 0, output: 0, total: 0 });
|
|
834
|
-
};
|
|
835
|
-
const stepOutputActivityAt = (index) => {
|
|
836
|
-
const step = statusPayload.steps[index];
|
|
837
|
-
let lastActivityAt = step?.lastActivityAt ?? step?.startedAt ?? overallStartTime;
|
|
838
|
-
const outputPath = path.join(asyncDir, `output-${index}.log`);
|
|
839
|
-
try {
|
|
840
|
-
lastActivityAt = Math.max(lastActivityAt, fs.statSync(outputPath).mtimeMs);
|
|
841
|
-
}
|
|
842
|
-
catch (error) {
|
|
843
|
-
if (error.code !== "ENOENT") {
|
|
844
|
-
console.error(`Failed to inspect async output file '${outputPath}':`, error);
|
|
845
|
-
}
|
|
846
|
-
}
|
|
847
|
-
return lastActivityAt;
|
|
848
|
-
};
|
|
849
|
-
const childSafeControls = Boolean(config.nestedSelf) || (process.env[SUBAGENT_CHILD_ENV] === "1" && process.env[SUBAGENT_FANOUT_CHILD_ENV] === "1");
|
|
850
|
-
const emittedControlEventKeys = new Set();
|
|
851
|
-
const mutatingFailureStates = initialStatusSteps.map(() => createMutatingFailureState());
|
|
852
|
-
const mutatingFailureWindowMs = 5 * 60_000;
|
|
853
|
-
const appendControlEvent = (event) => {
|
|
854
|
-
if (!controlConfig.enabled)
|
|
855
|
-
return;
|
|
856
|
-
const childIntercomTarget = config.childIntercomTargets?.[event.index ?? statusPayload.currentStep];
|
|
857
|
-
const channels = controlConfig.notifyChannels;
|
|
858
|
-
if (channels.length === 0 || !claimControlNotification(controlConfig, event, emittedControlEventKeys, childIntercomTarget))
|
|
859
|
-
return;
|
|
860
|
-
appendJsonl(eventsPath, JSON.stringify({
|
|
861
|
-
type: "subagent.control",
|
|
862
|
-
event,
|
|
863
|
-
channels,
|
|
864
|
-
childIntercomTarget,
|
|
865
|
-
noticeText: formatControlNoticeMessage(event, childIntercomTarget, childSafeControls),
|
|
866
|
-
...(config.controlIntercomTarget && channels.includes("intercom") ? {
|
|
867
|
-
intercom: {
|
|
868
|
-
to: config.controlIntercomTarget,
|
|
869
|
-
message: formatControlIntercomMessage(event, childIntercomTarget, childSafeControls),
|
|
870
|
-
},
|
|
871
|
-
} : {}),
|
|
872
|
-
}));
|
|
873
|
-
};
|
|
874
|
-
const syncTopLevelCurrentTool = () => {
|
|
875
|
-
const activeStep = statusPayload.steps
|
|
876
|
-
.filter((step) => step.status === "running" && typeof step.currentTool === "string" && step.currentTool.length > 0)
|
|
877
|
-
.sort((left, right) => (right.currentToolStartedAt ?? 0) - (left.currentToolStartedAt ?? 0))[0];
|
|
878
|
-
statusPayload.currentTool = activeStep?.currentTool;
|
|
879
|
-
statusPayload.currentToolStartedAt = activeStep?.currentToolStartedAt;
|
|
880
|
-
statusPayload.currentPath = activeStep?.currentPath;
|
|
881
|
-
};
|
|
882
|
-
const updateStepModel = (flatIndex, model, thinking, now = Date.now()) => {
|
|
883
|
-
const step = statusPayload.steps[flatIndex];
|
|
884
|
-
if (!step)
|
|
885
|
-
return;
|
|
886
|
-
step.model = model;
|
|
887
|
-
step.thinking = thinking;
|
|
888
|
-
step.modelStartedAt = now;
|
|
889
|
-
statusPayload.lastUpdate = now;
|
|
890
|
-
writeStatusPayload();
|
|
891
|
-
};
|
|
892
|
-
const clearControlNotificationKeys = (flatIndex) => {
|
|
893
|
-
const childKey = config.childIntercomTargets?.[flatIndex] ?? `${config.id}:${flatIndex}`;
|
|
894
|
-
for (const key of emittedControlEventKeys)
|
|
895
|
-
if (key.startsWith(`${childKey}:`))
|
|
896
|
-
emittedControlEventKeys.delete(key);
|
|
897
|
-
};
|
|
898
|
-
const updateStepFromChildEvent = (flatIndex, event, toolSnapshot) => {
|
|
899
|
-
const step = statusPayload.steps[flatIndex];
|
|
900
|
-
if (!step)
|
|
901
|
-
return;
|
|
902
|
-
const now = Date.now();
|
|
903
|
-
statusPayload.currentStep = flatIndex;
|
|
904
|
-
if (step.activityState === "needs_attention") {
|
|
905
|
-
step.activityState = undefined;
|
|
906
|
-
clearControlNotificationKeys(flatIndex);
|
|
907
|
-
statusPayload.activityState = statusPayload.steps.some((candidate) => candidate.activityState === "needs_attention")
|
|
908
|
-
? "needs_attention"
|
|
909
|
-
: undefined;
|
|
910
|
-
}
|
|
911
|
-
step.streamingText = updateStreamingText(step.streamingText, event);
|
|
912
|
-
if (event.type === "tool_execution_start" && event.toolName) {
|
|
913
|
-
const currentPath = resolveCurrentPath(event.toolName, event.args);
|
|
914
|
-
step.toolCount = (step.toolCount ?? 0) + 1;
|
|
915
|
-
step.currentTool = event.toolName;
|
|
916
|
-
step.currentToolArgs = extractToolArgsPreview(event.args ?? {});
|
|
917
|
-
step.currentToolStartedAt = now;
|
|
918
|
-
step.currentPath = currentPath;
|
|
919
|
-
statusPayload.toolCount = (statusPayload.toolCount ?? 0) + 1;
|
|
920
|
-
syncTopLevelCurrentTool();
|
|
921
|
-
}
|
|
922
|
-
else if (event.type === "tool_execution_end") {
|
|
923
|
-
if (step.currentTool) {
|
|
924
|
-
step.recentTools ??= [];
|
|
925
|
-
step.recentTools.push({ tool: step.currentTool, args: step.currentToolArgs || "", endMs: now });
|
|
926
|
-
}
|
|
927
|
-
step.currentTool = undefined;
|
|
928
|
-
step.currentToolArgs = undefined;
|
|
929
|
-
step.currentToolStartedAt = undefined;
|
|
930
|
-
step.currentPath = undefined;
|
|
931
|
-
syncTopLevelCurrentTool();
|
|
932
|
-
}
|
|
933
|
-
else if (event.type === "message_end" && event.message?.role === "toolResult") {
|
|
934
|
-
const resultText = extractTextFromContent(event.message.content);
|
|
935
|
-
appendRecentStepOutput(step, resultText.split("\n").slice(-10));
|
|
936
|
-
if (toolSnapshot?.mutates && toolSnapshot.errored) {
|
|
937
|
-
const state = mutatingFailureStates[flatIndex];
|
|
938
|
-
recordMutatingFailure(state, {
|
|
939
|
-
tool: toolSnapshot.tool,
|
|
940
|
-
path: toolSnapshot.path,
|
|
941
|
-
error: resultText.split("\n").find((line) => line.trim())?.trim().slice(0, 180) ?? "mutating tool failed",
|
|
942
|
-
ts: now,
|
|
943
|
-
}, mutatingFailureWindowMs);
|
|
944
|
-
if (controlConfig.enabled && shouldEscalateMutatingFailures(state, controlConfig.failedToolAttemptsBeforeAttention) && step.activityState !== "needs_attention") {
|
|
945
|
-
const previous = step.activityState;
|
|
946
|
-
step.activityState = "needs_attention";
|
|
947
|
-
statusPayload.activityState = "needs_attention";
|
|
948
|
-
appendControlEvent(buildControlEvent({
|
|
949
|
-
type: "needs_attention",
|
|
950
|
-
from: previous,
|
|
951
|
-
to: "needs_attention",
|
|
952
|
-
runId: id,
|
|
953
|
-
agent: step.agent,
|
|
954
|
-
index: flatIndex,
|
|
955
|
-
ts: now,
|
|
956
|
-
message: `${step.agent} needs attention after repeated mutating tool failures`,
|
|
957
|
-
reason: "tool_failures",
|
|
958
|
-
turns: step.turnCount,
|
|
959
|
-
tokens: step.tokens?.total,
|
|
960
|
-
toolCount: step.toolCount,
|
|
961
|
-
currentTool: toolSnapshot.tool,
|
|
962
|
-
currentToolDurationMs: toolSnapshot.startedAt ? Math.max(0, now - toolSnapshot.startedAt) : undefined,
|
|
963
|
-
currentPath: toolSnapshot.path,
|
|
964
|
-
recentFailureSummary: summarizeRecentMutatingFailures(state),
|
|
965
|
-
}));
|
|
966
|
-
}
|
|
967
|
-
}
|
|
968
|
-
else if (toolSnapshot?.mutates) {
|
|
969
|
-
resetMutatingFailureState(mutatingFailureStates[flatIndex]);
|
|
970
|
-
}
|
|
971
|
-
}
|
|
972
|
-
else if (event.type === "message_end" && event.message?.role === "assistant") {
|
|
973
|
-
appendRecentStepOutput(step, stripAcceptanceReport(extractTextFromContent(event.message.content)).split("\n").slice(-10));
|
|
974
|
-
step.turnCount = (step.turnCount ?? 0) + 1;
|
|
975
|
-
const usage = event.message.usage;
|
|
976
|
-
if (usage) {
|
|
977
|
-
const input = usage.input ?? 0;
|
|
978
|
-
const output = usage.output ?? 0;
|
|
979
|
-
const previousInput = step.tokens?.input ?? 0;
|
|
980
|
-
const previousOutput = step.tokens?.output ?? 0;
|
|
981
|
-
step.tokens = { input: previousInput + input, output: previousOutput + output, total: previousInput + previousOutput + input + output };
|
|
982
|
-
const totalInput = statusPayload.totalTokens?.input ?? 0;
|
|
983
|
-
const totalOutput = statusPayload.totalTokens?.output ?? 0;
|
|
984
|
-
statusPayload.totalTokens = { input: totalInput + input, output: totalOutput + output, total: totalInput + totalOutput + input + output };
|
|
985
|
-
}
|
|
986
|
-
statusPayload.turnCount = Math.max(statusPayload.turnCount ?? 0, step.turnCount);
|
|
987
|
-
}
|
|
988
|
-
syncTopLevelCurrentTool();
|
|
989
|
-
step.lastActivityAt = now;
|
|
990
|
-
statusPayload.lastActivityAt = now;
|
|
991
|
-
statusPayload.lastUpdate = now;
|
|
992
|
-
scheduleStatusWrite();
|
|
993
|
-
};
|
|
994
|
-
const updateRunnerActivityState = (now) => {
|
|
995
|
-
if (!controlConfig.enabled)
|
|
996
|
-
return false;
|
|
997
|
-
let changed = false;
|
|
998
|
-
let runLastActivityAt = statusPayload.lastActivityAt ?? overallStartTime;
|
|
999
|
-
for (let index = 0; index < statusPayload.steps.length; index++) {
|
|
1000
|
-
const step = statusPayload.steps[index];
|
|
1001
|
-
if (step.status !== "running")
|
|
1002
|
-
continue;
|
|
1003
|
-
const lastActivityAt = stepOutputActivityAt(index);
|
|
1004
|
-
runLastActivityAt = Math.max(runLastActivityAt, lastActivityAt);
|
|
1005
|
-
if (step.lastActivityAt !== lastActivityAt) {
|
|
1006
|
-
step.lastActivityAt = lastActivityAt;
|
|
1007
|
-
changed = true;
|
|
1008
|
-
}
|
|
1009
|
-
const idleState = deriveActivityState({
|
|
1010
|
-
config: controlConfig,
|
|
1011
|
-
startedAt: step.startedAt ?? overallStartTime,
|
|
1012
|
-
lastActivityAt,
|
|
1013
|
-
now,
|
|
1014
|
-
});
|
|
1015
|
-
if (idleState === "needs_attention") {
|
|
1016
|
-
const previous = step.activityState;
|
|
1017
|
-
step.activityState = "needs_attention";
|
|
1018
|
-
if (previous !== "needs_attention") {
|
|
1019
|
-
appendControlEvent(buildControlEvent({
|
|
1020
|
-
from: previous,
|
|
1021
|
-
to: "needs_attention",
|
|
1022
|
-
runId: id,
|
|
1023
|
-
agent: step.agent,
|
|
1024
|
-
index,
|
|
1025
|
-
ts: now,
|
|
1026
|
-
lastActivityAt,
|
|
1027
|
-
currentTool: step.currentTool,
|
|
1028
|
-
currentToolDurationMs: step.currentToolStartedAt !== undefined ? Math.max(0, now - step.currentToolStartedAt) : undefined,
|
|
1029
|
-
supervisorQuestion: pendingSupervisorQuestion({ runId: id, agent: step.agent, index, sessionFile: step.sessionFile }),
|
|
1030
|
-
}));
|
|
1031
|
-
changed = true;
|
|
1032
|
-
}
|
|
1033
|
-
}
|
|
1034
|
-
else if (step.activityState === "needs_attention") {
|
|
1035
|
-
step.activityState = undefined;
|
|
1036
|
-
clearControlNotificationKeys(index);
|
|
1037
|
-
changed = true;
|
|
1038
|
-
}
|
|
1039
|
-
}
|
|
1040
|
-
if (statusPayload.lastActivityAt !== runLastActivityAt) {
|
|
1041
|
-
statusPayload.lastActivityAt = runLastActivityAt;
|
|
1042
|
-
changed = true;
|
|
1043
|
-
}
|
|
1044
|
-
const nextRunState = statusPayload.steps.some((step) => step.activityState === "needs_attention")
|
|
1045
|
-
? "needs_attention"
|
|
1046
|
-
: undefined;
|
|
1047
|
-
if (nextRunState !== currentActivityState) {
|
|
1048
|
-
currentActivityState = nextRunState;
|
|
1049
|
-
statusPayload.activityState = nextRunState;
|
|
1050
|
-
changed = true;
|
|
1051
|
-
}
|
|
1052
|
-
statusPayload.lastUpdate = now;
|
|
1053
|
-
if (changed)
|
|
1054
|
-
writeStatusPayload();
|
|
1055
|
-
return changed;
|
|
1056
|
-
};
|
|
1057
|
-
if (controlConfig.enabled) {
|
|
1058
|
-
activityTimer = setInterval(() => {
|
|
1059
|
-
if (statusPayload.state !== "running")
|
|
1060
|
-
return;
|
|
1061
|
-
const now = Date.now();
|
|
1062
|
-
updateRunnerActivityState(now);
|
|
1063
|
-
}, 1000);
|
|
1064
|
-
activityTimer.unref?.();
|
|
1065
|
-
}
|
|
1066
|
-
const interruptRunner = () => {
|
|
1067
|
-
if (interrupted || statusPayload.state !== "running")
|
|
1068
|
-
return;
|
|
1069
|
-
interrupted = true;
|
|
1070
|
-
interruption.abort();
|
|
1071
|
-
const now = Date.now();
|
|
1072
|
-
currentActivityState = undefined;
|
|
1073
|
-
statusPayload.activityState = undefined;
|
|
1074
|
-
statusPayload.lastUpdate = now;
|
|
1075
|
-
writeStatusPayload();
|
|
1076
|
-
appendJsonl(eventsPath, JSON.stringify({
|
|
1077
|
-
type: "subagent.run.stop-requested",
|
|
1078
|
-
ts: now,
|
|
1079
|
-
runId: id,
|
|
1080
|
-
}));
|
|
1081
|
-
for (const interrupt of activeChildInterrupts.values())
|
|
1082
|
-
interrupt();
|
|
1083
|
-
};
|
|
1084
|
-
process.on(ASYNC_INTERRUPT_SIGNAL, interruptRunner);
|
|
1085
|
-
controlRequestTimer = setInterval(() => {
|
|
1086
|
-
for (const request of readAsyncControlRequests(asyncDir, id)) {
|
|
1087
|
-
if (request.action === "extend") {
|
|
1088
|
-
if (statusPayload.timeoutAt === undefined || cancellation.signal.aborted || interrupted)
|
|
1089
|
-
continue;
|
|
1090
|
-
statusPayload.timeoutAt = Math.max(statusPayload.timeoutAt, Date.now()) + request.extendMs;
|
|
1091
|
-
scheduleDeadline();
|
|
1092
|
-
writeStatusPayload();
|
|
1093
|
-
appendJsonl(eventsPath, JSON.stringify({ type: "subagent.run.extended", requestId: request.requestId, runId: id, ts: Date.now(), timeoutAt: statusPayload.timeoutAt }));
|
|
1094
|
-
}
|
|
1095
|
-
else if (request.action === "cancel")
|
|
1096
|
-
cancellation.abort();
|
|
1097
|
-
else if (request.index === undefined)
|
|
1098
|
-
interruptRunner();
|
|
1099
|
-
else
|
|
1100
|
-
activeChildInterrupts.get(request.index)?.();
|
|
1101
|
-
}
|
|
1102
|
-
}, 100);
|
|
1103
|
-
controlRequestTimer.unref?.();
|
|
1104
|
-
appendJsonl(eventsPath, JSON.stringify({
|
|
1105
|
-
type: "subagent.run.started",
|
|
1106
|
-
ts: overallStartTime,
|
|
1107
|
-
runId: id,
|
|
1108
|
-
mode: statusPayload.mode,
|
|
1109
|
-
cwd,
|
|
1110
|
-
pid: process.pid,
|
|
1111
|
-
}));
|
|
1112
|
-
const stoppedParallelChild = (task, index, reason) => {
|
|
1113
|
-
const now = Date.now();
|
|
1114
|
-
const step = statusPayload.steps[index];
|
|
1115
|
-
const paused = reason === "interrupted";
|
|
1116
|
-
const error = `Skipped due to ${reason}`;
|
|
1117
|
-
const exitCode = paused ? 0 : -1;
|
|
1118
|
-
if (paused)
|
|
1119
|
-
markStepPaused(step, now);
|
|
1120
|
-
else
|
|
1121
|
-
Object.assign(step, { status: "failed", error, startedAt: now, endedAt: now, durationMs: 0, exitCode });
|
|
1122
|
-
statusPayload.lastUpdate = now;
|
|
1123
|
-
writeStatusPayload();
|
|
1124
|
-
appendJsonl(eventsPath, JSON.stringify({ type: paused ? "subagent.step.paused" : "subagent.step.failed", ts: now, runId: id, stepIndex: index, agent: task.agent, exitCode, interrupted: paused, durationMs: 0 }));
|
|
1125
|
-
return { agent: task.agent, output: error, error, exitCode, interrupted: paused, skipped: true };
|
|
1126
|
-
};
|
|
1127
|
-
const runParallelChild = async (input) => {
|
|
1128
|
-
const { task, flatIndex: fi } = input;
|
|
1129
|
-
const taskStartTime = Date.now();
|
|
1130
|
-
const statusStep = statusPayload.steps[fi];
|
|
1131
|
-
statusPayload.currentStep = fi;
|
|
1132
|
-
statusStep.status = "running";
|
|
1133
|
-
statusStep.error = undefined;
|
|
1134
|
-
statusStep.activityState = undefined;
|
|
1135
|
-
resetStepLiveDetail(statusStep);
|
|
1136
|
-
statusStep.startedAt = taskStartTime;
|
|
1137
|
-
if (input.resetTiming) {
|
|
1138
|
-
statusStep.endedAt = undefined;
|
|
1139
|
-
statusStep.durationMs = undefined;
|
|
1140
|
-
}
|
|
1141
|
-
statusStep.lastActivityAt = taskStartTime;
|
|
1142
|
-
statusPayload.outputFile = path.join(asyncDir, `output-${fi}.log`);
|
|
1143
|
-
statusPayload.lastActivityAt = taskStartTime;
|
|
1144
|
-
statusPayload.lastUpdate = taskStartTime;
|
|
1145
|
-
writeStatusPayload();
|
|
1146
|
-
appendJsonl(eventsPath, JSON.stringify({ type: "subagent.step.started", ts: taskStartTime, runId: id, stepIndex: fi, agent: task.agent }));
|
|
1147
|
-
const singleResult = await runSingleStep({ ...task, task: renderTask(task.task, input.item) }, {
|
|
1148
|
-
nativeFinalization: config.runtimeVersion === 2,
|
|
1149
|
-
worktreePath: input.worktreePath,
|
|
1150
|
-
cwd: input.taskCwd, sessionEnabled,
|
|
1151
|
-
sessionDir: input.sessionDir,
|
|
1152
|
-
artifactsDir, id,
|
|
1153
|
-
flatIndex: fi, flatStepCount: input.flatStepCount,
|
|
1154
|
-
outputFile: path.join(asyncDir, `output-${fi}.log`),
|
|
1155
|
-
childIntercomTarget: config.childIntercomTargets?.[fi],
|
|
1156
|
-
orchestratorIntercomTarget: config.childIntercomTargets?.[fi] ? config.controlIntercomTarget : undefined,
|
|
1157
|
-
nestedRoute: config.nestedRoute,
|
|
1158
|
-
projectTrust: config.projectTrust,
|
|
1159
|
-
rootSessionId: config.rootSessionId,
|
|
1160
|
-
signal: cancellation.signal,
|
|
1161
|
-
interruptSignal: input.interruptSignal,
|
|
1162
|
-
registerInterrupt: (interrupt) => {
|
|
1163
|
-
if (interrupt)
|
|
1164
|
-
activeChildInterrupts.set(fi, interrupt);
|
|
1165
|
-
else
|
|
1166
|
-
activeChildInterrupts.delete(fi);
|
|
1167
|
-
},
|
|
1168
|
-
onAttemptStart: (attempt) => updateStepModel(fi, attempt.model, attempt.thinking),
|
|
1169
|
-
onChildEvent: (event, mutation) => updateStepFromChildEvent(fi, event, mutation),
|
|
1170
|
-
});
|
|
1171
|
-
activeChildInterrupts.delete(fi);
|
|
1172
|
-
if (input.trackSession && task.sessionFile)
|
|
1173
|
-
latestSessionFile = task.sessionFile;
|
|
1174
|
-
const taskEndTime = Date.now();
|
|
1175
|
-
statusStep.status = singleResult.interrupted ? "paused" : singleResult.exitCode === 0 ? singleResult.acceptance?.status === "blocked" ? "blocked" : "complete" : "failed";
|
|
1176
|
-
clearStepCurrentActivity(statusStep);
|
|
1177
|
-
statusStep.endedAt = taskEndTime;
|
|
1178
|
-
statusStep.durationMs = taskEndTime - taskStartTime;
|
|
1179
|
-
statusStep.exitCode = singleResult.exitCode;
|
|
1180
|
-
statusStep.agentProcessExit = singleResult.agentProcessExit;
|
|
1181
|
-
statusStep.model = singleResult.model;
|
|
1182
|
-
statusStep.thinking = resolveEffectiveThinking(singleResult.model, statusStep.thinking);
|
|
1183
|
-
statusStep.attemptedModels = singleResult.attemptedModels;
|
|
1184
|
-
statusStep.modelAttempts = singleResult.modelAttempts;
|
|
1185
|
-
statusStep.tokens = tokenUsageFromAttempts(singleResult.modelAttempts) ?? undefined;
|
|
1186
|
-
refreshUsageTotals();
|
|
1187
|
-
statusStep.error = singleResult.error;
|
|
1188
|
-
statusStep.structuredOutput = singleResult.structuredOutput;
|
|
1189
|
-
statusStep.structuredOutputPath = singleResult.structuredOutputPath;
|
|
1190
|
-
statusStep.structuredOutputSchemaPath = singleResult.structuredOutputSchemaPath;
|
|
1191
|
-
statusStep.acceptance = singleResult.acceptance;
|
|
1192
|
-
statusStep.resourceLimitExceeded = singleResult.resourceLimitExceeded;
|
|
1193
|
-
statusPayload.lastUpdate = taskEndTime;
|
|
1194
|
-
writeStatusPayload();
|
|
1195
|
-
appendJsonl(eventsPath, JSON.stringify({
|
|
1196
|
-
type: singleResult.interrupted ? "subagent.step.paused" : singleResult.exitCode !== 0 ? "subagent.step.failed" : singleResult.acceptance?.status === "blocked" ? "subagent.step.blocked" : "subagent.step.completed",
|
|
1197
|
-
ts: taskEndTime, runId: id, stepIndex: fi, agent: task.agent,
|
|
1198
|
-
exitCode: singleResult.exitCode, durationMs: taskEndTime - taskStartTime,
|
|
1199
|
-
interrupted: singleResult.interrupted, agentProcessExit: singleResult.agentProcessExit,
|
|
1200
|
-
resourceLimitExceeded: singleResult.resourceLimitExceeded,
|
|
1201
|
-
}));
|
|
1202
|
-
if (input.notifyCompletionGuard && singleResult.completionGuardTriggered) {
|
|
1203
|
-
appendControlEvent(buildControlEvent({
|
|
1204
|
-
from: statusStep.activityState,
|
|
1205
|
-
to: "needs_attention",
|
|
1206
|
-
runId: id,
|
|
1207
|
-
agent: task.agent,
|
|
1208
|
-
index: fi,
|
|
1209
|
-
ts: taskEndTime,
|
|
1210
|
-
message: `${task.agent} completed without making edits for an implementation task`,
|
|
1211
|
-
reason: "completion_guard",
|
|
1212
|
-
}));
|
|
1213
|
-
}
|
|
1214
|
-
return { ...singleResult, skipped: false };
|
|
1215
|
-
};
|
|
1216
|
-
let flatIndex = 0;
|
|
1217
|
-
let workflowComplete = false;
|
|
1218
|
-
for (let stepIndex = 0; stepIndex < steps.length; stepIndex++) {
|
|
1219
|
-
if (interrupted || cancellation.signal.aborted)
|
|
1220
|
-
break;
|
|
1221
|
-
const step = steps[stepIndex];
|
|
1222
|
-
if (isDynamicRunnerGroup(step)) {
|
|
1223
|
-
const groupStartFlatIndex = flatIndex;
|
|
1224
|
-
let materialized;
|
|
1225
|
-
try {
|
|
1226
|
-
materialized = materializeDynamicParallelStep(step, outputs, stepIndex, { maxItems: config.dynamicFanoutMaxItems, allowRunnerFields: true });
|
|
1227
|
-
}
|
|
1228
|
-
catch (error) {
|
|
1229
|
-
const now = Date.now();
|
|
1230
|
-
const message = error instanceof DynamicFanoutError ? error.message : error instanceof Error ? error.message : String(error);
|
|
1231
|
-
statusPayload.state = "failed";
|
|
1232
|
-
statusPayload.error = message;
|
|
1233
|
-
statusPayload.currentStep = flatIndex;
|
|
1234
|
-
const placeholder = statusPayload.steps[groupStartFlatIndex];
|
|
1235
|
-
if (placeholder) {
|
|
1236
|
-
placeholder.status = "failed";
|
|
1237
|
-
placeholder.error = message;
|
|
1238
|
-
placeholder.startedAt = now;
|
|
1239
|
-
placeholder.endedAt = now;
|
|
1240
|
-
placeholder.durationMs = 0;
|
|
1241
|
-
placeholder.exitCode = 1;
|
|
1242
|
-
}
|
|
1243
|
-
statusPayload.lastUpdate = now;
|
|
1244
|
-
markDynamicGraphGroup(stepIndex, "failed", message);
|
|
1245
|
-
writeStatusPayload();
|
|
1246
|
-
break;
|
|
1247
|
-
}
|
|
1248
|
-
const dynamicSteps = materialized.parallel.map((task, itemIndex) => materializeDynamicOutputPath({
|
|
1249
|
-
step: {
|
|
1250
|
-
...step.parallel,
|
|
1251
|
-
label: task.label ?? step.parallel.label,
|
|
1252
|
-
sessionFile: step.sessionFiles?.[itemIndex],
|
|
1253
|
-
structuredOutput: undefined,
|
|
1254
|
-
structuredOutputSchema: step.parallel.structuredOutputSchema ?? step.parallel.structuredOutput?.schema,
|
|
1255
|
-
},
|
|
1256
|
-
chainDir: config.chainDir ?? cwd,
|
|
1257
|
-
stepIndex,
|
|
1258
|
-
taskIndex: itemIndex,
|
|
1259
|
-
}));
|
|
1260
|
-
const duplicateOutputError = findDuplicateOutputPath(dynamicSteps);
|
|
1261
|
-
if (duplicateOutputError) {
|
|
1262
|
-
const now = Date.now();
|
|
1263
|
-
statusPayload.state = "failed";
|
|
1264
|
-
statusPayload.error = duplicateOutputError;
|
|
1265
|
-
statusPayload.currentStep = flatIndex;
|
|
1266
|
-
const placeholderStep = statusPayload.steps[groupStartFlatIndex];
|
|
1267
|
-
if (placeholderStep) {
|
|
1268
|
-
placeholderStep.status = "failed";
|
|
1269
|
-
placeholderStep.error = duplicateOutputError;
|
|
1270
|
-
placeholderStep.startedAt = now;
|
|
1271
|
-
placeholderStep.endedAt = now;
|
|
1272
|
-
placeholderStep.durationMs = 0;
|
|
1273
|
-
placeholderStep.exitCode = 1;
|
|
1274
|
-
}
|
|
1275
|
-
statusPayload.lastUpdate = now;
|
|
1276
|
-
markDynamicGraphGroup(stepIndex, "failed", duplicateOutputError);
|
|
1277
|
-
writeStatusPayload();
|
|
1278
|
-
break;
|
|
1279
|
-
}
|
|
1280
|
-
const dynamicStatusSteps = dynamicSteps.map((task) => ({
|
|
1281
|
-
agent: task.agent,
|
|
1282
|
-
phase: task.phase ?? step.phase,
|
|
1283
|
-
label: task.label,
|
|
1284
|
-
outputName: undefined,
|
|
1285
|
-
structured: Boolean(task.structuredOutputSchema),
|
|
1286
|
-
status: "pending",
|
|
1287
|
-
...(task.sessionFile ? { sessionFile: task.sessionFile } : {}),
|
|
1288
|
-
skills: task.skills,
|
|
1289
|
-
model: task.model,
|
|
1290
|
-
thinking: task.thinking,
|
|
1291
|
-
attemptedModels: task.modelCandidates && task.modelCandidates.length > 0 ? task.modelCandidates : task.model ? [task.model] : undefined,
|
|
1292
|
-
recentTools: [],
|
|
1293
|
-
recentOutput: [],
|
|
1294
|
-
}));
|
|
1295
|
-
const previousChildIntercomTargets = config.childIntercomTargets;
|
|
1296
|
-
statusPayload.steps.splice(groupStartFlatIndex, 1, ...dynamicStatusSteps);
|
|
1297
|
-
if (previousChildIntercomTargets) {
|
|
1298
|
-
const dynamicGroupUsesIntercom = previousChildIntercomTargets[groupStartFlatIndex] !== undefined;
|
|
1299
|
-
config.childIntercomTargets = statusPayload.steps.map((statusStep, index) => {
|
|
1300
|
-
if (index >= groupStartFlatIndex && index < groupStartFlatIndex + dynamicStatusSteps.length) {
|
|
1301
|
-
return dynamicGroupUsesIntercom ? resolveSubagentIntercomTarget(id, statusStep.agent, index) : undefined;
|
|
1302
|
-
}
|
|
1303
|
-
const previousIndex = index < groupStartFlatIndex ? index : index - (dynamicStatusSteps.length - 1);
|
|
1304
|
-
return previousChildIntercomTargets[previousIndex] !== undefined
|
|
1305
|
-
? resolveSubagentIntercomTarget(id, statusStep.agent, index)
|
|
1306
|
-
: undefined;
|
|
1307
|
-
});
|
|
1308
|
-
}
|
|
1309
|
-
mutatingFailureStates.splice(groupStartFlatIndex, 1, ...dynamicStatusSteps.map(() => createMutatingFailureState()));
|
|
1310
|
-
const materializedDelta = dynamicStatusSteps.length - 1;
|
|
1311
|
-
for (const group of statusPayload.parallelGroups) {
|
|
1312
|
-
if (group.stepIndex === stepIndex) {
|
|
1313
|
-
group.start = groupStartFlatIndex;
|
|
1314
|
-
group.count = dynamicStatusSteps.length;
|
|
1315
|
-
}
|
|
1316
|
-
else if (group.stepIndex > stepIndex) {
|
|
1317
|
-
group.start += materializedDelta;
|
|
1318
|
-
}
|
|
1319
|
-
}
|
|
1320
|
-
if (statusPayload.workflowGraph) {
|
|
1321
|
-
const shiftFlatIndexes = (nodes) => {
|
|
1322
|
-
for (const node of nodes) {
|
|
1323
|
-
if (node.stepIndex !== undefined && node.stepIndex > stepIndex && node.flatIndex !== undefined && node.flatIndex >= groupStartFlatIndex) {
|
|
1324
|
-
node.flatIndex += dynamicStatusSteps.length;
|
|
1325
|
-
}
|
|
1326
|
-
if (node.children)
|
|
1327
|
-
shiftFlatIndexes(node.children);
|
|
1328
|
-
}
|
|
1329
|
-
};
|
|
1330
|
-
shiftFlatIndexes(statusPayload.workflowGraph.nodes);
|
|
1331
|
-
const groupNode = statusPayload.workflowGraph.nodes.find((node) => node.id === `step-${stepIndex}`);
|
|
1332
|
-
if (groupNode) {
|
|
1333
|
-
groupNode.children = materialized.items.map((item, itemIndex) => ({
|
|
1334
|
-
id: `step-${stepIndex}-item-${item.idKey}`,
|
|
1335
|
-
kind: "agent",
|
|
1336
|
-
agent: step.parallel.agent,
|
|
1337
|
-
phase: dynamicSteps[itemIndex]?.phase ?? step.phase,
|
|
1338
|
-
label: dynamicSteps[itemIndex]?.label?.trim() || `${step.parallel.agent} ${item.key}`,
|
|
1339
|
-
status: "pending",
|
|
1340
|
-
flatIndex: groupStartFlatIndex + itemIndex,
|
|
1341
|
-
stepIndex,
|
|
1342
|
-
itemKey: item.key,
|
|
1343
|
-
structured: Boolean(dynamicSteps[itemIndex]?.structuredOutputSchema),
|
|
1344
|
-
}));
|
|
1345
|
-
}
|
|
1346
|
-
}
|
|
1347
|
-
writeStatusPayload();
|
|
1348
|
-
const parallelResults = await runParallelTasks({
|
|
1349
|
-
tasks: dynamicSteps,
|
|
1350
|
-
concurrency: step.concurrency ?? MAX_PARALLEL_CONCURRENCY,
|
|
1351
|
-
failFast: step.failFast,
|
|
1352
|
-
signal: cancellation.signal,
|
|
1353
|
-
interruptSignal: interruption.signal,
|
|
1354
|
-
stoppedTask: (task, index, reason) => stoppedParallelChild(task, groupStartFlatIndex + index, reason),
|
|
1355
|
-
runTask: (task, taskIdx, failFastSignal) => runParallelChild({
|
|
1356
|
-
task,
|
|
1357
|
-
flatIndex: groupStartFlatIndex + taskIdx,
|
|
1358
|
-
interruptSignal: failFastSignal,
|
|
1359
|
-
item: { name: step.expand.item ?? "item", value: materialized.items[taskIdx].item },
|
|
1360
|
-
taskCwd: cwd,
|
|
1361
|
-
sessionDir: config.sessionDir ? path.join(config.sessionDir, `dynamic-${stepIndex}-${taskIdx}`) : undefined,
|
|
1362
|
-
flatStepCount: Math.max(statusPayload.steps.length, 1),
|
|
1363
|
-
}),
|
|
1364
|
-
});
|
|
1365
|
-
flatIndex += dynamicSteps.length;
|
|
1366
|
-
for (const pr of parallelResults)
|
|
1367
|
-
results.push({ ...pr, success: workflowChildSucceeded(pr) });
|
|
1368
|
-
const completion = completeWorkflowStep({ stepIndex, stepCount: steps.length, results: parallelResults, previousOutput, dynamic: { step, items: materialized.items } });
|
|
1369
|
-
Object.assign(outputs, completion.outputs);
|
|
1370
|
-
statusPayload.outputs = outputs;
|
|
1371
|
-
if (completion.error) {
|
|
1372
|
-
statusPayload.error = completion.error;
|
|
1373
|
-
}
|
|
1374
|
-
previousOutput = completion.previousOutput;
|
|
1375
|
-
workflowComplete = completion.complete;
|
|
1376
|
-
const error = completion.error ?? parallelResults[completion.failedIndices[0]]?.error;
|
|
1377
|
-
markDynamicGraphGroup(stepIndex, completion.status === "completed" ? "completed" : completion.status === "blocked" ? "blocked" : completion.status === "paused" ? "paused" : "failed", error);
|
|
1378
|
-
appendJsonl(eventsPath, JSON.stringify({
|
|
1379
|
-
type: "subagent.dynamic.completed",
|
|
1380
|
-
ts: Date.now(),
|
|
1381
|
-
runId: id,
|
|
1382
|
-
stepIndex,
|
|
1383
|
-
success: completion.advance,
|
|
1384
|
-
state: completion.status === "completed" ? "complete" : completion.status,
|
|
1385
|
-
}));
|
|
1386
|
-
statusPayload.lastUpdate = Date.now();
|
|
1387
|
-
writeStatusPayload();
|
|
1388
|
-
if (!completion.advance)
|
|
1389
|
-
break;
|
|
1390
|
-
continue;
|
|
1391
|
-
}
|
|
1392
|
-
if (isParallelGroup(step)) {
|
|
1393
|
-
const group = step;
|
|
1394
|
-
const groupCwd = group.cwd ?? cwd;
|
|
1395
|
-
const groupStartFlatIndex = flatIndex;
|
|
1396
|
-
let worktreeSetup;
|
|
1397
|
-
if (group.worktree) {
|
|
1398
|
-
const worktreeTaskCwdConflict = findWorktreeTaskCwdConflict(group.parallel, groupCwd);
|
|
1399
|
-
if (worktreeTaskCwdConflict) {
|
|
1400
|
-
const failedAt = Date.now();
|
|
1401
|
-
markParallelGroupSetupFailure({
|
|
1402
|
-
statusPayload,
|
|
1403
|
-
results,
|
|
1404
|
-
group,
|
|
1405
|
-
groupStartFlatIndex,
|
|
1406
|
-
setupError: formatWorktreeTaskCwdConflict(worktreeTaskCwdConflict, groupCwd),
|
|
1407
|
-
failedAt,
|
|
1408
|
-
statusPath,
|
|
1409
|
-
eventsPath,
|
|
1410
|
-
asyncDir,
|
|
1411
|
-
runId: id,
|
|
1412
|
-
stepIndex,
|
|
1413
|
-
});
|
|
1414
|
-
flatIndex += group.parallel.length;
|
|
1415
|
-
break;
|
|
1416
|
-
}
|
|
1417
|
-
try {
|
|
1418
|
-
worktreeSetup = await createWorktrees(groupCwd, `${id}-s${stepIndex}`, group.parallel.length, {
|
|
1419
|
-
agents: group.parallel.map((task) => task.agent),
|
|
1420
|
-
signal: AbortSignal.any([cancellation.signal, interruption.signal]),
|
|
1421
|
-
setupHook: config.worktreeSetupHook
|
|
1422
|
-
? { hookPath: config.worktreeSetupHook, timeoutMs: config.worktreeSetupHookTimeoutMs }
|
|
1423
|
-
: undefined,
|
|
1424
|
-
});
|
|
1425
|
-
}
|
|
1426
|
-
catch (error) {
|
|
1427
|
-
const setupError = error instanceof Error ? error.message : String(error);
|
|
1428
|
-
if (interrupted && !cancellation.signal.aborted) {
|
|
1429
|
-
if (error instanceof WorktreeCleanupError)
|
|
1430
|
-
setupCleanupWarning = setupError;
|
|
1431
|
-
for (const [index, task] of group.parallel.entries()) {
|
|
1432
|
-
const stopped = stoppedParallelChild(task, groupStartFlatIndex + index, "interrupted");
|
|
1433
|
-
if (error instanceof WorktreeCleanupError)
|
|
1434
|
-
stopped.output += `\n\n${setupError}`;
|
|
1435
|
-
results.push({ ...stopped, success: false });
|
|
1436
|
-
}
|
|
1437
|
-
flatIndex += group.parallel.length;
|
|
1438
|
-
break;
|
|
1439
|
-
}
|
|
1440
|
-
const failedAt = Date.now();
|
|
1441
|
-
markParallelGroupSetupFailure({
|
|
1442
|
-
statusPayload,
|
|
1443
|
-
results,
|
|
1444
|
-
group,
|
|
1445
|
-
groupStartFlatIndex,
|
|
1446
|
-
setupError,
|
|
1447
|
-
failedAt,
|
|
1448
|
-
statusPath,
|
|
1449
|
-
eventsPath,
|
|
1450
|
-
asyncDir,
|
|
1451
|
-
runId: id,
|
|
1452
|
-
stepIndex,
|
|
1453
|
-
});
|
|
1454
|
-
flatIndex += group.parallel.length;
|
|
1455
|
-
break;
|
|
1456
|
-
}
|
|
1457
|
-
}
|
|
1458
|
-
try {
|
|
1459
|
-
if (group.worktree)
|
|
1460
|
-
ensureParallelProgressFile(groupCwd, group);
|
|
1461
|
-
const groupStartTime = Date.now();
|
|
1462
|
-
markParallelGroupRunning({
|
|
1463
|
-
statusPayload,
|
|
1464
|
-
group,
|
|
1465
|
-
groupStartFlatIndex,
|
|
1466
|
-
groupStartTime,
|
|
1467
|
-
statusPath,
|
|
1468
|
-
eventsPath,
|
|
1469
|
-
asyncDir,
|
|
1470
|
-
runId: id,
|
|
1471
|
-
stepIndex,
|
|
1472
|
-
});
|
|
1473
|
-
const parallelResults = await runParallelTasks({
|
|
1474
|
-
tasks: group.parallel,
|
|
1475
|
-
concurrency: group.concurrency ?? MAX_PARALLEL_CONCURRENCY,
|
|
1476
|
-
failFast: group.failFast,
|
|
1477
|
-
signal: cancellation.signal,
|
|
1478
|
-
interruptSignal: interruption.signal,
|
|
1479
|
-
stoppedTask: (task, index, reason) => stoppedParallelChild(task, groupStartFlatIndex + index, reason),
|
|
1480
|
-
runTask: (task, taskIdx, failFastSignal) => {
|
|
1481
|
-
const { taskForRun, taskCwd } = prepareParallelTaskRun(task, groupCwd, worktreeSetup, taskIdx);
|
|
1482
|
-
return runParallelChild({
|
|
1483
|
-
task: taskForRun,
|
|
1484
|
-
worktreePath: worktreeSetup?.worktrees[taskIdx]?.path,
|
|
1485
|
-
flatIndex: groupStartFlatIndex + taskIdx,
|
|
1486
|
-
interruptSignal: failFastSignal,
|
|
1487
|
-
taskCwd,
|
|
1488
|
-
sessionDir: config.sessionDir ? path.join(config.sessionDir, `parallel-${taskIdx}`) : undefined,
|
|
1489
|
-
flatStepCount: flatSteps.length,
|
|
1490
|
-
resetTiming: true,
|
|
1491
|
-
trackSession: true,
|
|
1492
|
-
notifyCompletionGuard: true,
|
|
1493
|
-
});
|
|
1494
|
-
},
|
|
1495
|
-
});
|
|
1496
|
-
flatIndex += group.parallel.length;
|
|
1497
|
-
refreshUsageTotals();
|
|
1498
|
-
statusPayload.lastUpdate = Date.now();
|
|
1499
|
-
writeStatusPayload();
|
|
1500
|
-
for (const pr of parallelResults)
|
|
1501
|
-
results.push({ ...pr, success: workflowChildSucceeded(pr) });
|
|
1502
|
-
const completion = completeWorkflowStep({
|
|
1503
|
-
stepIndex, stepCount: steps.length, results: parallelResults, previousOutput, parallel: true,
|
|
1504
|
-
outputNames: group.parallel.map((task) => task.outputName),
|
|
1505
|
-
});
|
|
1506
|
-
Object.assign(outputs, completion.outputs);
|
|
1507
|
-
statusPayload.outputs = outputs;
|
|
1508
|
-
const worktreeSummary = formatRunnerWorktreeSummary(worktreeSetup, asyncDir, stepIndex, group);
|
|
1509
|
-
previousOutput = completion.advance ? appendWorktreeSummary(completion.previousOutput, worktreeSummary) : completion.previousOutput;
|
|
1510
|
-
workflowComplete = completion.complete;
|
|
1511
|
-
if (worktreeSummary)
|
|
1512
|
-
worktreeSummaries.push(worktreeSummary);
|
|
1513
|
-
appendJsonl(eventsPath, JSON.stringify({
|
|
1514
|
-
type: "subagent.parallel.completed",
|
|
1515
|
-
ts: Date.now(),
|
|
1516
|
-
runId: id,
|
|
1517
|
-
stepIndex,
|
|
1518
|
-
success: completion.advance,
|
|
1519
|
-
state: completion.status === "completed" ? "complete" : completion.status,
|
|
1520
|
-
}));
|
|
1521
|
-
writeStatusPayload();
|
|
1522
|
-
if (!completion.advance)
|
|
1523
|
-
break;
|
|
1524
|
-
}
|
|
1525
|
-
catch (error) {
|
|
1526
|
-
if (worktreeSetup)
|
|
1527
|
-
worktreeSetup.preserveOnCleanup = true;
|
|
1528
|
-
throw error;
|
|
1529
|
-
}
|
|
1530
|
-
finally {
|
|
1531
|
-
if (worktreeSetup)
|
|
1532
|
-
cleanupWorktrees(worktreeSetup);
|
|
1533
|
-
}
|
|
1534
|
-
}
|
|
1535
|
-
else {
|
|
1536
|
-
const seqStep = step;
|
|
1537
|
-
const stepStartTime = Date.now();
|
|
1538
|
-
statusPayload.currentStep = flatIndex;
|
|
1539
|
-
statusPayload.steps[flatIndex].status = "running";
|
|
1540
|
-
statusPayload.steps[flatIndex].activityState = undefined;
|
|
1541
|
-
statusPayload.activityState = undefined;
|
|
1542
|
-
resetStepLiveDetail(statusPayload.steps[flatIndex]);
|
|
1543
|
-
statusPayload.steps[flatIndex].skills = seqStep.skills;
|
|
1544
|
-
statusPayload.steps[flatIndex].startedAt = stepStartTime;
|
|
1545
|
-
statusPayload.steps[flatIndex].lastActivityAt = stepStartTime;
|
|
1546
|
-
statusPayload.lastActivityAt = stepStartTime;
|
|
1547
|
-
statusPayload.lastUpdate = stepStartTime;
|
|
1548
|
-
statusPayload.outputFile = path.join(asyncDir, `output-${flatIndex}.log`);
|
|
1549
|
-
writeStatusPayload();
|
|
1550
|
-
appendJsonl(eventsPath, JSON.stringify({
|
|
1551
|
-
type: "subagent.step.started",
|
|
1552
|
-
ts: stepStartTime,
|
|
1553
|
-
runId: id,
|
|
1554
|
-
stepIndex: flatIndex,
|
|
1555
|
-
agent: seqStep.agent,
|
|
1556
|
-
}));
|
|
1557
|
-
const singleResult = await runSingleStep({ ...seqStep, task: renderTask(seqStep.task) }, {
|
|
1558
|
-
nativeFinalization: config.runtimeVersion === 2,
|
|
1559
|
-
cwd, sessionEnabled,
|
|
1560
|
-
sessionDir: config.sessionDir,
|
|
1561
|
-
artifactsDir, id,
|
|
1562
|
-
flatIndex, flatStepCount: flatSteps.length,
|
|
1563
|
-
outputFile: path.join(asyncDir, `output-${flatIndex}.log`),
|
|
1564
|
-
childIntercomTarget: config.childIntercomTargets?.[flatIndex],
|
|
1565
|
-
orchestratorIntercomTarget: config.childIntercomTargets?.[flatIndex] ? config.controlIntercomTarget : undefined,
|
|
1566
|
-
nestedRoute: config.nestedRoute,
|
|
1567
|
-
projectTrust: config.projectTrust,
|
|
1568
|
-
rootSessionId: config.rootSessionId,
|
|
1569
|
-
signal: cancellation.signal,
|
|
1570
|
-
registerInterrupt: (interrupt) => {
|
|
1571
|
-
if (interrupt)
|
|
1572
|
-
activeChildInterrupts.set(flatIndex, interrupt);
|
|
1573
|
-
else
|
|
1574
|
-
activeChildInterrupts.delete(flatIndex);
|
|
1575
|
-
},
|
|
1576
|
-
onAttemptStart: (attempt) => updateStepModel(flatIndex, attempt.model, attempt.thinking),
|
|
1577
|
-
onChildEvent: (event, mutation) => updateStepFromChildEvent(flatIndex, event, mutation),
|
|
1578
|
-
});
|
|
1579
|
-
activeChildInterrupts.delete(flatIndex);
|
|
1580
|
-
if (seqStep.sessionFile) {
|
|
1581
|
-
latestSessionFile = seqStep.sessionFile;
|
|
1582
|
-
}
|
|
1583
|
-
const completion = completeWorkflowStep({ stepIndex, stepCount: steps.length, results: [singleResult], previousOutput, outputNames: [seqStep.outputName] });
|
|
1584
|
-
previousOutput = completion.previousOutput;
|
|
1585
|
-
workflowComplete = completion.complete;
|
|
1586
|
-
results.push({ ...singleResult, success: workflowChildSucceeded(singleResult) });
|
|
1587
|
-
Object.assign(outputs, completion.outputs);
|
|
1588
|
-
statusPayload.outputs = outputs;
|
|
1589
|
-
const stepTokens = tokenUsageFromAttempts(singleResult.modelAttempts);
|
|
1590
|
-
const stepEndTime = Date.now();
|
|
1591
|
-
statusPayload.steps[flatIndex].status = singleResult.interrupted ? "paused" : singleResult.exitCode === 0 ? singleResult.acceptance?.status === "blocked" ? "blocked" : "complete" : "failed";
|
|
1592
|
-
clearStepCurrentActivity(statusPayload.steps[flatIndex]);
|
|
1593
|
-
statusPayload.steps[flatIndex].endedAt = stepEndTime;
|
|
1594
|
-
statusPayload.steps[flatIndex].durationMs = stepEndTime - stepStartTime;
|
|
1595
|
-
statusPayload.steps[flatIndex].exitCode = singleResult.exitCode;
|
|
1596
|
-
statusPayload.steps[flatIndex].agentProcessExit = singleResult.agentProcessExit;
|
|
1597
|
-
statusPayload.steps[flatIndex].model = singleResult.model;
|
|
1598
|
-
statusPayload.steps[flatIndex].thinking = resolveEffectiveThinking(singleResult.model, statusPayload.steps[flatIndex].thinking);
|
|
1599
|
-
statusPayload.steps[flatIndex].attemptedModels = singleResult.attemptedModels;
|
|
1600
|
-
statusPayload.steps[flatIndex].modelAttempts = singleResult.modelAttempts;
|
|
1601
|
-
statusPayload.steps[flatIndex].error = singleResult.error;
|
|
1602
|
-
statusPayload.steps[flatIndex].structuredOutput = singleResult.structuredOutput;
|
|
1603
|
-
statusPayload.steps[flatIndex].structuredOutputPath = singleResult.structuredOutputPath;
|
|
1604
|
-
statusPayload.steps[flatIndex].structuredOutputSchemaPath = singleResult.structuredOutputSchemaPath;
|
|
1605
|
-
statusPayload.steps[flatIndex].acceptance = singleResult.acceptance;
|
|
1606
|
-
statusPayload.steps[flatIndex].resourceLimitExceeded = singleResult.resourceLimitExceeded;
|
|
1607
|
-
if (stepTokens) {
|
|
1608
|
-
statusPayload.steps[flatIndex].tokens = stepTokens;
|
|
1609
|
-
refreshUsageTotals();
|
|
1610
|
-
}
|
|
1611
|
-
statusPayload.lastUpdate = stepEndTime;
|
|
1612
|
-
writeStatusPayload();
|
|
1613
|
-
appendJsonl(eventsPath, JSON.stringify({
|
|
1614
|
-
type: singleResult.interrupted ? "subagent.step.paused" : singleResult.exitCode !== 0 ? "subagent.step.failed" : singleResult.acceptance?.status === "blocked" ? "subagent.step.blocked" : "subagent.step.completed",
|
|
1615
|
-
ts: stepEndTime,
|
|
1616
|
-
runId: id,
|
|
1617
|
-
stepIndex: flatIndex,
|
|
1618
|
-
agent: seqStep.agent,
|
|
1619
|
-
exitCode: singleResult.exitCode,
|
|
1620
|
-
durationMs: stepEndTime - stepStartTime,
|
|
1621
|
-
interrupted: singleResult.interrupted, agentProcessExit: singleResult.agentProcessExit,
|
|
1622
|
-
tokens: stepTokens,
|
|
1623
|
-
resourceLimitExceeded: singleResult.resourceLimitExceeded,
|
|
1624
|
-
}));
|
|
1625
|
-
if (singleResult.completionGuardTriggered) {
|
|
1626
|
-
const event = buildControlEvent({
|
|
1627
|
-
from: statusPayload.steps[flatIndex].activityState,
|
|
1628
|
-
to: "needs_attention",
|
|
1629
|
-
runId: id,
|
|
1630
|
-
agent: seqStep.agent,
|
|
1631
|
-
index: flatIndex,
|
|
1632
|
-
ts: stepEndTime,
|
|
1633
|
-
message: `${seqStep.agent} completed without making edits for an implementation task`,
|
|
1634
|
-
reason: "completion_guard",
|
|
1635
|
-
});
|
|
1636
|
-
appendControlEvent(event);
|
|
1637
|
-
}
|
|
1638
|
-
flatIndex++;
|
|
1639
|
-
if (!completion.advance)
|
|
1640
|
-
break;
|
|
1641
|
-
}
|
|
1642
|
-
}
|
|
1643
|
-
const resultMode = config.resultMode ?? statusPayload.mode;
|
|
1644
|
-
const childText = (result) => result.error && !result.output.includes(result.error) ? `${result.error}\n${result.output}`.trim() : result.output;
|
|
1645
|
-
let summary = resultMode === "single" && results.length === 1 ? childText(results[0]) : results.map((result) => `${result.agent}:\n${childText(result)}`).join("\n\n");
|
|
1646
|
-
if (statusPayload.error && !summary.includes(statusPayload.error))
|
|
1647
|
-
summary = `${statusPayload.error}\n\n${summary}`.trim();
|
|
1648
|
-
if (statusPayload.timedOut)
|
|
1649
|
-
summary = [
|
|
1650
|
-
`${resultMode === "parallel" ? "Parallel run" : resultMode === "chain" ? "Chain" : "Run"} timed out.`,
|
|
1651
|
-
summary,
|
|
1652
|
-
].filter(Boolean).join("\n\n");
|
|
1653
|
-
if (worktreeSummaries.length > 0)
|
|
1654
|
-
summary = appendWorktreeSummary(summary, worktreeSummaries.join("\n\n"));
|
|
1655
|
-
const fullSummary = summary;
|
|
1656
|
-
let truncated = false;
|
|
1657
|
-
const outputLimits = { ...DEFAULT_MAX_OUTPUT, ...maxOutput };
|
|
1658
|
-
const lastArtifactPath = results[results.length - 1]?.artifactPaths?.outputPath;
|
|
1659
|
-
const referenceOnly = resultMode === "single" && results.length === 1 && results[0]?.outputMode === "file-only" && results[0].exitCode === 0 && results[0].outputReference;
|
|
1660
|
-
const truncResult = referenceOnly ? { text: summary, truncated: false } : truncateOutput(summary, outputLimits, lastArtifactPath);
|
|
1661
|
-
if (truncResult.truncated) {
|
|
1662
|
-
summary = truncResult.text;
|
|
1663
|
-
truncated = true;
|
|
1664
|
-
}
|
|
1665
|
-
const agentName = flatSteps.length === 1
|
|
1666
|
-
? flatSteps[0].agent
|
|
1667
|
-
: resultMode === "parallel"
|
|
1668
|
-
? `parallel:${flatSteps.map((s) => s.agent).join("+")}`
|
|
1669
|
-
: `chain:${flatSteps.map((s) => s.agent).join("->")}`;
|
|
1670
|
-
let sessionFile;
|
|
1671
|
-
let shareUrl;
|
|
1672
|
-
let gistUrl;
|
|
1673
|
-
let shareError;
|
|
1674
|
-
if (shareEnabled) {
|
|
1675
|
-
sessionFile = config.sessionDir
|
|
1676
|
-
? (findLatestSessionFile(config.sessionDir) ?? undefined)
|
|
1677
|
-
: undefined;
|
|
1678
|
-
if (!sessionFile && latestSessionFile) {
|
|
1679
|
-
sessionFile = latestSessionFile;
|
|
1680
|
-
}
|
|
1681
|
-
if (sessionFile) {
|
|
1682
|
-
try {
|
|
1683
|
-
const exportDir = config.sessionDir ?? path.dirname(sessionFile);
|
|
1684
|
-
fs.mkdirSync(exportDir, { recursive: true });
|
|
1685
|
-
const htmlPath = await exportSessionHtml(sessionFile, exportDir, config.piPackageRoot);
|
|
1686
|
-
const share = createShareLink(htmlPath);
|
|
1687
|
-
if ("error" in share)
|
|
1688
|
-
shareError = share.error;
|
|
1689
|
-
else {
|
|
1690
|
-
shareUrl = share.shareUrl;
|
|
1691
|
-
gistUrl = share.gistUrl;
|
|
1692
|
-
}
|
|
1693
|
-
}
|
|
1694
|
-
catch (err) {
|
|
1695
|
-
shareError = String(err);
|
|
1696
|
-
}
|
|
1697
|
-
}
|
|
1698
|
-
else {
|
|
1699
|
-
shareError = "Session file not found.";
|
|
1700
|
-
}
|
|
1701
|
-
}
|
|
1702
|
-
clearTimeout(deadlineTimer);
|
|
1703
|
-
if (activityTimer) {
|
|
1704
|
-
clearInterval(activityTimer);
|
|
1705
|
-
activityTimer = undefined;
|
|
1706
|
-
}
|
|
1707
|
-
if (controlRequestTimer) {
|
|
1708
|
-
clearInterval(controlRequestTimer);
|
|
1709
|
-
controlRequestTimer = undefined;
|
|
1710
|
-
}
|
|
1711
|
-
process.off(ASYNC_INTERRUPT_SIGNAL, interruptRunner);
|
|
1712
|
-
for (const signal of ["SIGTERM", "SIGINT", "SIGHUP"])
|
|
1713
|
-
process.off(signal, cancelRunner);
|
|
1714
|
-
const effectiveSessionFile = sessionFile ?? latestSessionFile ?? undefined;
|
|
1715
|
-
const runEndedAt = Date.now();
|
|
1716
|
-
if (interrupted) {
|
|
1717
|
-
for (let index = 0; index < statusPayload.steps.length; index++) {
|
|
1718
|
-
const step = statusPayload.steps[index];
|
|
1719
|
-
if (step.status !== "pending")
|
|
1720
|
-
continue;
|
|
1721
|
-
markStepPaused(step, runEndedAt);
|
|
1722
|
-
appendJsonl(eventsPath, JSON.stringify({
|
|
1723
|
-
type: "subagent.step.paused",
|
|
1724
|
-
ts: runEndedAt,
|
|
1725
|
-
runId: id,
|
|
1726
|
-
stepIndex: index,
|
|
1727
|
-
agent: step.agent,
|
|
1728
|
-
interrupted: true,
|
|
1729
|
-
durationMs: 0,
|
|
1730
|
-
}));
|
|
1731
|
-
}
|
|
1732
|
-
}
|
|
1733
|
-
const hasFailedSteps = statusPayload.steps.some((step) => step.status === "failed");
|
|
1734
|
-
const hasPausedSteps = statusPayload.steps.some((step) => step.status === "paused");
|
|
1735
|
-
const finalRunState = hasFailedSteps || statusPayload.error || cancellation.signal.aborted ? "failed"
|
|
1736
|
-
: statusPayload.steps.some((step) => step.status === "blocked") ? "blocked"
|
|
1737
|
-
: interrupted || hasPausedSteps ? "paused" : workflowComplete ? "complete" : "failed";
|
|
1738
|
-
statusPayload.state = finalRunState;
|
|
1739
|
-
statusPayload.activityState = undefined;
|
|
1740
|
-
statusPayload.currentTool = undefined;
|
|
1741
|
-
statusPayload.currentToolStartedAt = undefined;
|
|
1742
|
-
statusPayload.currentPath = undefined;
|
|
1743
|
-
statusPayload.endedAt = runEndedAt;
|
|
1744
|
-
statusPayload.lastUpdate = runEndedAt;
|
|
1745
|
-
statusPayload.sessionFile = effectiveSessionFile;
|
|
1746
|
-
statusPayload.shareUrl = shareUrl;
|
|
1747
|
-
statusPayload.gistUrl = gistUrl;
|
|
1748
|
-
statusPayload.shareError = shareError;
|
|
1749
|
-
if (statusPayload.state === "failed" && !statusPayload.error) {
|
|
1750
|
-
const failedStep = statusPayload.steps.find((s) => s.status === "failed");
|
|
1751
|
-
if (failedStep?.agent) {
|
|
1752
|
-
statusPayload.error = `Step failed: ${failedStep.agent}`;
|
|
1753
|
-
}
|
|
1754
|
-
else if (cancellation.signal.aborted) {
|
|
1755
|
-
statusPayload.error = "Subagent cancelled.";
|
|
50
|
+
catch {
|
|
51
|
+
/* Legacy temporary configuration cleanup is best effort. */
|
|
1756
52
|
}
|
|
1757
53
|
}
|
|
1758
|
-
|
|
1759
|
-
appendJsonl(eventsPath, JSON.stringify({
|
|
1760
|
-
type: "subagent.run.completed",
|
|
1761
|
-
ts: runEndedAt,
|
|
1762
|
-
runId: id,
|
|
1763
|
-
status: statusPayload.state,
|
|
1764
|
-
durationMs: runEndedAt - overallStartTime,
|
|
1765
|
-
}));
|
|
1766
|
-
writeRunLog(logPath, {
|
|
1767
|
-
id,
|
|
1768
|
-
mode: statusPayload.mode,
|
|
1769
|
-
cwd,
|
|
1770
|
-
startedAt: overallStartTime,
|
|
1771
|
-
endedAt: runEndedAt,
|
|
1772
|
-
steps: statusPayload.steps.map((step) => ({
|
|
1773
|
-
agent: step.agent,
|
|
1774
|
-
status: step.status,
|
|
1775
|
-
durationMs: step.durationMs,
|
|
1776
|
-
})),
|
|
1777
|
-
summary: fullSummary,
|
|
1778
|
-
truncated: false,
|
|
1779
|
-
artifactsDir,
|
|
1780
|
-
sessionFile: effectiveSessionFile,
|
|
1781
|
-
shareUrl,
|
|
1782
|
-
shareError,
|
|
1783
|
-
});
|
|
1784
|
-
try {
|
|
1785
|
-
const resultData = {
|
|
1786
|
-
id,
|
|
1787
|
-
runtimeVersion: config.runtimeVersion,
|
|
1788
|
-
maxOutput: outputLimits, error: statusPayload.error,
|
|
1789
|
-
timedOut: statusPayload.timedOut,
|
|
1790
|
-
agent: agentName,
|
|
1791
|
-
mode: resultMode,
|
|
1792
|
-
success: finalRunState === "complete",
|
|
1793
|
-
state: finalRunState,
|
|
1794
|
-
summary: finalRunState === "blocked" ? `Needs your action — acceptance incomplete.\n${results.map((result) => acceptanceHumanAction(result.acceptance)).filter(Boolean).join("\n")}` : finalRunState === "paused" ? `Paused after interrupt. Waiting for explicit next action.${setupCleanupWarning ? `\n\n${setupCleanupWarning}` : ""}` : summary,
|
|
1795
|
-
results: results.map((r) => {
|
|
1796
|
-
const referenceOnly = r.outputMode === "file-only" && r.exitCode === 0 && r.outputReference;
|
|
1797
|
-
const childOutput = referenceOnly ? { text: referenceOnly.message, truncated: false } : truncateOutput(r.output, outputLimits, r.artifactPaths?.outputPath);
|
|
1798
|
-
return { ...r, output: childOutput.text,
|
|
1799
|
-
finalOutput: referenceOnly ? referenceOnly.message : r.finalOutput === undefined ? undefined : truncateOutput(r.finalOutput, outputLimits, r.artifactPaths?.outputPath).text,
|
|
1800
|
-
initialOutput: r.initialOutput === undefined ? undefined : truncateOutput(r.initialOutput, outputLimits, r.artifactPaths?.outputPath).text,
|
|
1801
|
-
truncated: r.truncated || childOutput.truncated || undefined };
|
|
1802
|
-
}),
|
|
1803
|
-
outputs,
|
|
1804
|
-
workflowGraph: statusPayload.workflowGraph,
|
|
1805
|
-
exitCode: statusPayload.timedOut ? 124 : finalRunState === "failed" ? 1 : 0,
|
|
1806
|
-
timestamp: runEndedAt,
|
|
1807
|
-
durationMs: runEndedAt - overallStartTime,
|
|
1808
|
-
truncated,
|
|
1809
|
-
artifactsDir,
|
|
1810
|
-
cwd,
|
|
1811
|
-
asyncDir,
|
|
1812
|
-
sessionId: config.sessionId ?? undefined,
|
|
1813
|
-
sessionFile: effectiveSessionFile,
|
|
1814
|
-
intercomTarget: config.controlIntercomTarget,
|
|
1815
|
-
shareUrl,
|
|
1816
|
-
gistUrl,
|
|
1817
|
-
shareError,
|
|
1818
|
-
...(taskIndex !== undefined && { taskIndex }),
|
|
1819
|
-
...(totalTasks !== undefined && { totalTasks }),
|
|
1820
|
-
};
|
|
1821
|
-
const saved = saveAsyncRunResult(id, resultData);
|
|
1822
|
-
resultData.completionId = saved.completionId;
|
|
1823
|
-
resultData.recordVersion = 3;
|
|
1824
|
-
if (config.runtimeVersion !== 2 || path.resolve(resultPath) !== path.resolve(asyncDir, "result.json"))
|
|
1825
|
-
writeAtomicJson(resultPath, resultData);
|
|
1826
|
-
}
|
|
1827
|
-
catch (err) {
|
|
1828
|
-
console.error(`Failed to write result file ${resultPath}:`, err);
|
|
1829
|
-
}
|
|
54
|
+
runSubagent(config).catch(runnerError);
|
|
1830
55
|
}
|
|
1831
|
-
const configArg = process.argv
|
|
1832
|
-
if (configArg) {
|
|
56
|
+
const configArg = process.argv.at(2);
|
|
57
|
+
if (configArg !== undefined && configArg.length > 0) {
|
|
1833
58
|
try {
|
|
1834
|
-
|
|
1835
|
-
const config = JSON.parse(configJson);
|
|
1836
|
-
try {
|
|
1837
|
-
if (config.runtimeVersion !== 2)
|
|
1838
|
-
fs.unlinkSync(configArg);
|
|
1839
|
-
}
|
|
1840
|
-
catch {
|
|
1841
|
-
// Temp config cleanup is best effort.
|
|
1842
|
-
}
|
|
1843
|
-
runSubagent(config).catch((runErr) => {
|
|
1844
|
-
console.error("Subagent runner error:", runErr);
|
|
1845
|
-
process.exit(1);
|
|
1846
|
-
});
|
|
59
|
+
launchConfig(fs.readFileSync(configArg, "utf-8"), configArg);
|
|
1847
60
|
}
|
|
1848
|
-
catch (
|
|
1849
|
-
|
|
1850
|
-
process.exit(1);
|
|
61
|
+
catch (error) {
|
|
62
|
+
runnerError(error);
|
|
1851
63
|
}
|
|
1852
64
|
}
|
|
1853
65
|
else {
|
|
1854
66
|
let input = "";
|
|
1855
67
|
process.stdin.setEncoding("utf-8");
|
|
1856
68
|
process.stdin.on("data", (chunk) => {
|
|
1857
|
-
|
|
69
|
+
if (typeof chunk === "string") {
|
|
70
|
+
input += chunk;
|
|
71
|
+
}
|
|
1858
72
|
});
|
|
1859
73
|
process.stdin.on("end", () => {
|
|
1860
74
|
try {
|
|
1861
|
-
|
|
1862
|
-
runSubagent(config).catch((runErr) => {
|
|
1863
|
-
console.error("Subagent runner error:", runErr);
|
|
1864
|
-
process.exit(1);
|
|
1865
|
-
});
|
|
75
|
+
launchConfig(input);
|
|
1866
76
|
}
|
|
1867
|
-
catch (
|
|
1868
|
-
|
|
1869
|
-
process.exit(1);
|
|
77
|
+
catch (error) {
|
|
78
|
+
runnerError(error);
|
|
1870
79
|
}
|
|
1871
80
|
});
|
|
1872
81
|
}
|