pi-better-server 0.5.0 → 0.7.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/package.json +7 -3
- package/scripts/copy-pi-test-providers.mjs +10 -0
- package/scripts/event-publication/README.md +26 -0
- package/scripts/event-publication/commit.mjs +21 -0
- package/scripts/event-publication/measure.mjs +37 -5
- package/scripts/event-publication/writer.mjs +3 -8
- package/scripts/measure-full-runtime/frontend.ts +10 -2
- package/scripts/measure-full-runtime/probe.mjs +4 -2
- package/scripts/measure-full-runtime/recovery-trace-loader.mjs +51 -0
- package/scripts/measure-full-runtime/recovery-trace.mjs +16 -0
- package/scripts/measure-full-runtime.mjs +2 -0
- package/scripts/measure-shared-reads.mjs +2 -1
- package/scripts/private-runtime/package-lock.json +18 -0
- package/scripts/private-runtime/package.json +4 -1
- package/scripts/source-provenance.mjs +2 -2
- package/scripts/test-on-pi.sh +2 -9
- package/src/handshake.ts +1 -1
- package/src/hosted-session.ts +32 -4
- package/src/maintenance.ts +35 -7
- package/src/registry.ts +28 -4
- package/src/runtime/attempt-invalidation.ts +54 -0
- package/src/runtime/background-history.ts +151 -45
- package/src/runtime/background-policy.ts +9 -4
- package/src/runtime/background-tools.ts +181 -27
- package/src/runtime/background.ts +365 -70
- package/src/runtime/cancellation.ts +28 -7
- package/src/runtime/catalog-sources.ts +199 -0
- package/src/runtime/catalog.ts +53 -21
- package/src/runtime/client.ts +22 -2
- package/src/runtime/domain/assignment-inbox.mjs +119 -0
- package/src/runtime/domain/assignment-observation.d.mts +1 -1
- package/src/runtime/domain/assignment-observation.mjs +43 -35
- package/src/runtime/domain/background/process-identity.mjs +20 -2
- package/src/runtime/domain/background/process.mjs +52 -14
- package/src/runtime/domain/background/registry.mjs +61 -3
- package/src/runtime/domain/background/supervisor/store.mjs +3 -3
- package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -3
- package/src/runtime/domain/background/types.mjs +1 -0
- package/src/runtime/domain/background-service/adapter-contract.domain.mjs +1 -1
- package/src/runtime/domain/background-service/adapter-contract.ts +1 -1
- package/src/runtime/domain/background-service/goal-provider.domain.mjs +35 -16
- package/src/runtime/domain/background-service/goal-provider.ts +31 -16
- package/src/runtime/domain/background-service/index.domain.mjs +25 -9
- package/src/runtime/domain/background-service/index.ts +25 -9
- package/src/runtime/domain/background-service/managed-authority.domain.mjs +6 -3
- package/src/runtime/domain/background-service/managed-authority.ts +5 -3
- package/src/runtime/domain/background-service/managed-client.domain.mjs +21 -7
- package/src/runtime/domain/background-service/managed-client.ts +20 -7
- package/src/runtime/domain/background-service/managed-frontend.domain.mjs +159 -19
- package/src/runtime/domain/background-service/managed-frontend.ts +135 -19
- package/src/runtime/domain/background-service/navigator-provider.domain.mjs +21 -5
- package/src/runtime/domain/background-service/navigator-provider.ts +19 -5
- package/src/runtime/domain/background-service/observed-wait-client.domain.mjs +6 -0
- package/src/runtime/domain/background-service/observed-wait-client.ts +10 -0
- package/src/runtime/domain/background-service/observed-waits.domain.mjs +372 -57
- package/src/runtime/domain/background-service/observed-waits.ts +321 -53
- package/src/runtime/domain/background-service/process-identity.domain.mjs +20 -2
- package/src/runtime/domain/background-service/process-identity.ts +18 -2
- package/src/runtime/domain/background-service/process.domain.mjs +52 -14
- package/src/runtime/domain/background-service/process.ts +48 -14
- package/src/runtime/domain/background-service/registry.domain.mjs +61 -3
- package/src/runtime/domain/background-service/registry.ts +53 -5
- package/src/runtime/domain/background-service/review-settings.domain.mjs +16 -0
- package/src/runtime/domain/background-service/review-settings.ts +18 -0
- package/src/runtime/domain/background-service/runtime.domain.mjs +40 -86
- package/src/runtime/domain/background-service/runtime.ts +27 -82
- package/src/runtime/domain/background-service/sandbox.domain.mjs +14 -15
- package/src/runtime/domain/background-service/sandbox.ts +14 -11
- package/src/runtime/domain/background-service/shared-callback-batcher.domain.mjs +8 -1
- package/src/runtime/domain/background-service/shared-callback-batcher.ts +11 -2
- package/src/runtime/domain/background-service/shared-navigator-panels.domain.mjs +24 -2
- package/src/runtime/domain/background-service/shared-navigator-panels.ts +26 -4
- package/src/runtime/domain/background-service/shared-navigator.domain.mjs +273 -41
- package/src/runtime/domain/background-service/shared-navigator.ts +244 -40
- package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +144 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +53 -41
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +73 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.ts +14 -3
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +5 -3
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +44 -4
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +50 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +12 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.domain.mjs +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.ts +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +42 -21
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +40 -24
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +26 -4
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +40 -8
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.ts +24 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.domain.mjs +1 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.ts +5 -1
- package/src/runtime/domain/background-service/shared-sandbox-core.ts +1 -1
- package/src/runtime/domain/background-service/shared-work-client.mjs +174 -7
- package/src/runtime/domain/background-service/stall.domain.mjs +5 -3
- package/src/runtime/domain/background-service/stall.ts +7 -4
- package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
- package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
- package/src/runtime/domain/background-service/supervisor/README.md +1 -4
- package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
- package/src/runtime/domain/background-service/supervisor/generated/process-identity.mjs +20 -2
- package/src/runtime/domain/background-service/supervisor/generated/process.mjs +52 -14
- package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
- package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
- package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
- package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
- package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
- package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
- package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
- package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
- package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -3
- package/src/runtime/domain/background-service/task-diagnostics.domain.mjs +1 -1
- package/src/runtime/domain/background-service/task-diagnostics.ts +1 -1
- package/src/runtime/domain/background-service/tools.domain.mjs +53 -40
- package/src/runtime/domain/background-service/tools.ts +67 -54
- package/src/runtime/domain/background-service/types.domain.mjs +1 -0
- package/src/runtime/domain/background-service/types.ts +7 -3
- package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
- package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
- package/src/runtime/domain/background-service/work-observation.domain.mjs +46 -20
- package/src/runtime/domain/background-service/work-observation.ts +46 -19
- package/src/runtime/domain/catalog/catalog-store.d.mts +9 -1
- package/src/runtime/domain/catalog/catalog-store.mjs +20 -22
- package/src/runtime/domain/coordinator/src/assignment-changes.mjs +75 -0
- package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +2 -0
- package/src/runtime/domain/coordinator/src/background-requests.mjs +11 -2
- package/src/runtime/domain/coordinator/src/discovery.mjs +4 -2
- package/src/runtime/domain/coordinator/src/operations.mjs +44 -4
- package/src/runtime/domain/coordinator/src/outbox.mjs +7 -0
- package/src/runtime/domain/coordinator/src/result-supervision.mjs +12 -0
- package/src/runtime/domain/coordinator/src/rows.mjs +2 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +42 -21
- package/src/runtime/domain/coordinator/src/store.mjs +26 -4
- package/src/runtime/domain/coordinator/src/subagent-launch.mjs +23 -1
- package/src/runtime/domain/coordinator/src/types.mjs +1 -1
- package/src/runtime/domain/health-observation.d.mts +3 -1
- package/src/runtime/domain/health-observation.mjs +189 -190
- package/src/runtime/domain/log-cursor.d.mts +2 -0
- package/src/runtime/domain/log-cursor.mjs +85 -16
- package/src/runtime/domain/log-paths.mjs +8 -1
- package/src/runtime/domain/parse.d.mts +4 -1
- package/src/runtime/domain/parse.mjs +58 -9
- package/src/runtime/domain/sandbox-policy/README.md +63 -65
- package/src/runtime/domain/sandbox-policy/commands.domain.mjs +11 -8
- package/src/runtime/domain/sandbox-policy/commands.ts +12 -7
- package/src/runtime/domain/sandbox-policy/index.domain.mjs +53 -9
- package/src/runtime/domain/sandbox-policy/index.ts +52 -9
- package/src/runtime/domain/sandbox-policy/package.json +1 -1
- package/src/runtime/domain/sandbox-policy/permission-settings.domain.mjs +5 -2
- package/src/runtime/domain/sandbox-policy/permission-settings.ts +9 -2
- package/src/runtime/domain/sandbox-policy/permissions-page.domain.mjs +56 -137
- package/src/runtime/domain/sandbox-policy/permissions-page.ts +52 -130
- package/src/runtime/domain/sandbox-policy/permissions.domain.mjs +1 -6
- package/src/runtime/domain/sandbox-policy/permissions.ts +1 -6
- package/src/runtime/domain/sandbox-policy/shared-sandbox-core.ts +1 -1
- package/src/runtime/domain/sandbox-policy/shared-task-exec.domain.mjs +14 -1
- package/src/runtime/domain/sandbox-policy/shared-task-exec.ts +12 -1
- package/src/runtime/domain/sandbox-policy/shared-task-process-identity.domain.mjs +140 -0
- package/src/runtime/domain/sandbox-policy/shared-task-process-identity.ts +126 -0
- package/src/runtime/domain/sandbox-policy/shared-task-process-list.domain.mjs +3 -2
- package/src/runtime/domain/sandbox-policy/shared-task-process-list.ts +8 -2
- package/src/runtime/domain/sandbox-policy/shared-task-sandbox.domain.mjs +4 -3
- package/src/runtime/domain/sandbox-policy/shared-task-sandbox.ts +5 -3
- package/src/runtime/domain/sandbox-policy/shared-task-tools.domain.mjs +8 -5
- package/src/runtime/domain/sandbox-policy/shared-task-tools.ts +8 -5
- package/src/runtime/domain/session-store.mjs +7 -0
- package/src/runtime/domain/subagents/README.md +13 -11
- package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +10 -7
- package/src/runtime/domain/subagents/assignment-outcomes.ts +9 -6
- package/src/runtime/domain/subagents/assignment-report.domain.mjs +109 -24
- package/src/runtime/domain/subagents/assignment-report.ts +103 -19
- package/src/runtime/domain/subagents/batch.mjs +13 -5
- package/src/runtime/domain/subagents/catalog-host-admission.domain.mjs +21 -3
- package/src/runtime/domain/subagents/catalog-host-admission.ts +19 -3
- package/src/runtime/domain/subagents/catalog-preferences.ts +1 -1
- package/src/runtime/domain/subagents/catalog-resolver.domain.mjs +35 -1
- package/src/runtime/domain/subagents/catalog-resolver.ts +35 -1
- package/src/runtime/domain/subagents/catalog-store.domain.mjs +20 -22
- package/src/runtime/domain/subagents/catalog-store.ts +27 -20
- package/src/runtime/domain/subagents/child-apply-patch.domain.mjs +13 -0
- package/src/runtime/domain/subagents/child-apply-patch.ts +13 -0
- package/src/runtime/domain/subagents/child-dependencies.mjs +27 -15
- package/src/runtime/domain/subagents/child-operations.domain.mjs +80 -2
- package/src/runtime/domain/subagents/child-operations.ts +80 -1
- package/src/runtime/domain/subagents/child-preflight.mjs +9 -2
- package/src/runtime/domain/subagents/child-process-list.domain.mjs +7 -0
- package/src/runtime/domain/subagents/child-process-list.ts +8 -0
- package/src/runtime/domain/subagents/cleanup.domain.mjs +11 -2
- package/src/runtime/domain/subagents/cleanup.ts +10 -2
- package/src/runtime/domain/subagents/config.domain.mjs +54 -2
- package/src/runtime/domain/subagents/config.ts +53 -3
- package/src/runtime/domain/subagents/continuation-authority.domain.mjs +5 -1
- package/src/runtime/domain/subagents/continuation-authority.ts +3 -1
- package/src/runtime/domain/subagents/continuation-runtime.domain.mjs +89 -0
- package/src/runtime/domain/subagents/continuation-runtime.ts +88 -0
- package/src/runtime/domain/subagents/continuation.domain.mjs +4 -2
- package/src/runtime/domain/subagents/continuation.ts +4 -2
- package/src/runtime/domain/subagents/extensions.mjs +11 -13
- package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
- package/src/runtime/domain/subagents/failures.ts +10 -2
- package/src/runtime/domain/subagents/finalization.domain.mjs +16 -1
- package/src/runtime/domain/subagents/finalization.ts +21 -1
- package/src/runtime/domain/subagents/goal-provider.domain.mjs +44 -2
- package/src/runtime/domain/subagents/goal-provider.ts +44 -2
- package/src/runtime/domain/subagents/health-observation.domain.mjs +189 -190
- package/src/runtime/domain/subagents/health-observation.ts +43 -48
- package/src/runtime/domain/subagents/index.domain.mjs +457 -182
- package/src/runtime/domain/subagents/index.ts +417 -155
- package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +515 -0
- package/src/runtime/domain/subagents/isolated-workspace.ts +557 -0
- package/src/runtime/domain/subagents/launch-context.domain.mjs +24 -0
- package/src/runtime/domain/subagents/launch-context.ts +23 -0
- package/src/runtime/domain/subagents/launch-digest.mjs +6 -0
- package/src/runtime/domain/subagents/list.mjs +2 -2
- package/src/runtime/domain/subagents/log-cursor.domain.mjs +85 -16
- package/src/runtime/domain/subagents/log-cursor.ts +91 -15
- package/src/runtime/domain/subagents/managed-launch-bootstrap.mjs +2 -2
- package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +27 -7
- package/src/runtime/domain/subagents/managed-launch-client.ts +28 -8
- package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +222 -14
- package/src/runtime/domain/subagents/managed-launch-host.ts +168 -15
- package/src/runtime/domain/subagents/managed-launch-journal.mjs +1 -5
- package/src/runtime/domain/subagents/managed-launch-port.ts +4 -0
- package/src/runtime/domain/subagents/operation-bridge-types.domain.mjs +27 -2
- package/src/runtime/domain/subagents/operation-bridge-types.ts +27 -2
- package/src/runtime/domain/subagents/output-payload.domain.mjs +24 -9
- package/src/runtime/domain/subagents/output-payload.ts +26 -12
- package/src/runtime/domain/subagents/owned-exit.domain.mjs +12 -0
- package/src/runtime/domain/subagents/owned-exit.ts +12 -0
- package/src/runtime/domain/subagents/package.json +4 -2
- package/src/runtime/domain/subagents/parse.domain.mjs +58 -9
- package/src/runtime/domain/subagents/parse.ts +57 -10
- package/src/runtime/domain/subagents/permission-policy.domain.mjs +32 -8
- package/src/runtime/domain/subagents/permission-policy.ts +41 -8
- package/src/runtime/domain/subagents/process-identity.mjs +33 -0
- package/src/runtime/domain/subagents/registry.domain.mjs +71 -51
- package/src/runtime/domain/subagents/registry.ts +77 -38
- package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
- package/src/runtime/domain/subagents/retained-result.ts +65 -0
- package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
- package/src/runtime/domain/subagents/session-selection.ts +2 -1
- package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
- package/src/runtime/domain/subagents/session-store.ts +9 -0
- package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
- package/src/runtime/domain/subagents/settings-page.ts +147 -108
- package/src/runtime/domain/subagents/shared-callback-batcher.domain.mjs +8 -1
- package/src/runtime/domain/subagents/shared-callback-batcher.ts +11 -2
- package/src/runtime/domain/subagents/shared-catalog.domain.mjs +28 -29
- package/src/runtime/domain/subagents/shared-catalog.ts +29 -21
- package/src/runtime/domain/subagents/shared-navigator-panels.domain.mjs +24 -2
- package/src/runtime/domain/subagents/shared-navigator-panels.ts +26 -4
- package/src/runtime/domain/subagents/shared-navigator.domain.mjs +273 -41
- package/src/runtime/domain/subagents/shared-navigator.ts +244 -40
- package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +144 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +53 -41
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +73 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.ts +14 -3
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +5 -3
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +44 -4
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +50 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +12 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.domain.mjs +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.ts +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +42 -21
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +40 -24
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +26 -4
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +40 -8
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.ts +24 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.domain.mjs +1 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.ts +5 -1
- package/src/runtime/domain/subagents/shared-sandbox-core.ts +1 -1
- package/src/runtime/domain/subagents/shared-task-exec.domain.mjs +14 -1
- package/src/runtime/domain/subagents/shared-task-exec.ts +12 -1
- package/src/runtime/domain/subagents/shared-task-process-identity.domain.mjs +140 -0
- package/src/runtime/domain/subagents/shared-task-process-identity.ts +126 -0
- package/src/runtime/domain/subagents/shared-task-process-list.domain.mjs +3 -2
- package/src/runtime/domain/subagents/shared-task-process-list.ts +8 -2
- package/src/runtime/domain/subagents/shared-task-sandbox.domain.mjs +4 -3
- package/src/runtime/domain/subagents/shared-task-sandbox.ts +5 -3
- package/src/runtime/domain/subagents/shared-task-tools.domain.mjs +8 -5
- package/src/runtime/domain/subagents/shared-task-tools.ts +8 -5
- package/src/runtime/domain/subagents/shared-work-client.mjs +174 -7
- package/src/runtime/domain/subagents/subagent-tools.domain.mjs +22 -38
- package/src/runtime/domain/subagents/subagent-tools.ts +28 -34
- package/src/runtime/domain/subagents/task-guard.domain.mjs +14 -1
- package/src/runtime/domain/subagents/task-guard.ts +13 -1
- package/src/runtime/domain/subagents/task-policy.domain.mjs +3 -2
- package/src/runtime/domain/subagents/task-policy.ts +8 -2
- package/src/runtime/domain/subagents/timing.domain.mjs +10 -1
- package/src/runtime/domain/subagents/timing.ts +10 -1
- package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
- package/src/runtime/domain/subagents/tools.ts +4 -7
- package/src/runtime/domain/subagents/work-observation.domain.mjs +102 -17
- package/src/runtime/domain/subagents/work-observation.ts +91 -17
- package/src/runtime/domain/subagents/worker-operations-host.domain.mjs +9 -4
- package/src/runtime/domain/subagents/worker-operations-host.ts +12 -4
- package/src/runtime/domain/subagents/worker-waits.domain.mjs +89 -35
- package/src/runtime/domain/subagents/worker-waits.ts +93 -34
- package/src/runtime/domain/subagents/workspace-files.domain.mjs +103 -0
- package/src/runtime/domain/subagents/workspace-files.ts +114 -0
- package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
- package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
- package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
- package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
- package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
- package/src/runtime/health-config.ts +27 -11
- package/src/runtime/log-checkpoints.ts +117 -0
- package/src/runtime/mutation-store.ts +5 -4
- package/src/runtime/queries.ts +25 -2
- package/src/runtime/query-executor.ts +149 -28
- package/src/runtime/query-worker.mjs +106 -21
- package/src/runtime/read-model.ts +849 -121
- package/src/runtime/read-watchdog-probe.ts +4 -0
- package/src/runtime/result-supervision.ts +188 -16
- package/src/runtime/root.ts +5 -2
- package/src/runtime/source-watch.ts +175 -0
- package/src/runtime/subagent-launch.ts +11 -4
- package/src/runtime/work-budget.ts +130 -0
- package/src/runtime/work-client.d.mts +8 -0
- package/src/runtime/work-client.mjs +150 -7
- package/src/server.ts +104 -23
- package/src/session-activity.ts +26 -4
- package/src/version.ts +1 -1
|
@@ -1,4 +1,6 @@
|
|
|
1
|
+
import { shouldRestoreWorkObservation } from "./shared-work-client.mjs";
|
|
1
2
|
import { appendTimingWake, removeTimingReceipt, receiptTimingWake, timingWakeReceipt } from "./timing-notifications.ts";
|
|
3
|
+
import { captureLaunchContext } from "./launch-context.ts";
|
|
2
4
|
/**
|
|
3
5
|
* pi-better-subagents — Claude Code-style async subagents for pi.
|
|
4
6
|
*
|
|
@@ -16,7 +18,7 @@ import { createAssignmentProjector } from "./assignment-projection.mjs";
|
|
|
16
18
|
import { historicalWaits, attentionRevision, attentionDismissed, dismissAttention } from "./historical-attention.ts";
|
|
17
19
|
import { registerAssignmentAttempt, commitAssignmentTerminal, readOutcome, receiptOutcome, outcomeTranscriptReceipt, inspectOutcome, createOutcomeHost, closeOutcomeHost, claimOutcome, type AssignmentBinding } from "./assignment-outcomes.ts";
|
|
18
20
|
import { currentSandboxPermissions } from "./permission-policy.ts";
|
|
19
|
-
import { createToolDescriptor } from "./operation-bridge-types.ts";
|
|
21
|
+
import { assertWaitToolDependencies, createToolDescriptor } from "./operation-bridge-types.ts";
|
|
20
22
|
import { requestResumeAdmission } from "./worker-waits.ts";
|
|
21
23
|
import { execSync } from "node:child_process";
|
|
22
24
|
import { writeFileSync, mkdirSync, renameSync, statSync } from "node:fs";
|
|
@@ -25,7 +27,7 @@ import * as PiCodingAgent from "@earendil-works/pi-coding-agent";
|
|
|
25
27
|
import * as PiTui from "@earendil-works/pi-tui";
|
|
26
28
|
import { CustomEditor } from "@earendil-works/pi-coding-agent";
|
|
27
29
|
import { initializeNavigatorPanels } from "./shared-navigator-panels.ts";
|
|
28
|
-
import { workObservation, workObservationFailure,
|
|
30
|
+
import { workObservation, workObservationStarted, workObservationFailure, configureWorkObservation, activateWorkObservation, stopWorkObservation, observedAssignment, observedList, requestWorkDetail, TERMINAL_NAVIGATOR_RETENTION_MS } from "./work-observation.ts";
|
|
29
31
|
import { withAssignmentObservations } from "./assignment-projection.mjs";
|
|
30
32
|
import { formatNavigatorHealthFacts } from "./health-surface.mjs";
|
|
31
33
|
import { matchesKey, Key, truncateToWidth, type AutocompleteItem } from "@earendil-works/pi-tui";
|
|
@@ -36,18 +38,20 @@ import {
|
|
|
36
38
|
isNavigatorUiAvailable,
|
|
37
39
|
refreshBackgroundWorkNavigator,
|
|
38
40
|
registerBackgroundWorkProvider,
|
|
41
|
+
observeNavigatorLaunch,
|
|
39
42
|
renderRegisteredWorkDetail,
|
|
40
43
|
type BackgroundWorkDetail,
|
|
41
44
|
type BackgroundWorkProvider,
|
|
42
45
|
type BackgroundWorkRow,
|
|
43
46
|
} from "./shared-navigator.ts";
|
|
44
47
|
import { spawnDetached, killProcessTree, type SpawnResult } from "./spawn.ts";
|
|
45
|
-
import { abortUncommittedLaunch } from "./launch-abort.ts";
|
|
46
48
|
import { parseRun, parseRunForLifecycle, readRunTranscript, resetParseRunCursor, type Usage } from "./parse.ts";
|
|
47
|
-
import { finalizeRun as finalizeRunCore } from "./finalization.ts";
|
|
49
|
+
import { finalizeRun as finalizeRunCore, reconcileInterruptedRun } from "./finalization.ts";
|
|
50
|
+
import { completeOwnedExit } from "./owned-exit.ts";
|
|
48
51
|
import { selectSessionByName } from "./session-selection.ts";
|
|
49
52
|
import { isWithinWorkspace } from "./workspace-scope.ts";
|
|
50
|
-
import {
|
|
53
|
+
import { BUILTIN_TOOLS } from "./extensions.ts";
|
|
54
|
+
import { ORDINARY_TOOL_PROVIDERS, activeChildProviders, ordinaryChildConfig, addEditablePatch, loadConfig, writeDelegationMode, writeSubagentSettings, isConcurrencyCap, normalizeConcurrencyCap, normalizeTools, resolveExtensionPath, configPath, selfDir, SAFE_DEFAULT_TOOLS, SAFE_CLEAN_TOOLS } from "./config.ts";
|
|
51
55
|
import { createSubagentSettingsPage } from "./settings-page.ts";
|
|
52
56
|
import { deliverSubagentPrompt, effectiveSubagentSettings, formatSubagentSettings, subagentSettingsTool, SUBAGENT_SETTINGS_CONTEXT } from "./effective-settings.ts";
|
|
53
57
|
import { STEER_FILE_ENV, readSteerReceipt } from "./child-steer.ts";
|
|
@@ -76,17 +80,15 @@ import {
|
|
|
76
80
|
} from "./timing.ts";
|
|
77
81
|
import { readAppendedLines, type LogCursor } from "./log-cursor.ts";
|
|
78
82
|
import { DELEGATION_MODES, DELEGATION_MODE_REQUEST, isDelegationMode, normalizeDelegationMode, type DelegationMode } from "./delegation.ts";
|
|
79
|
-
import { resolveChildClosure, resolveChildLaunch, configSnapshot } from "./child-dependencies.mjs";
|
|
80
|
-
import { PREFLIGHT_ENV } from "./child-preflight.mjs";
|
|
81
83
|
import { resolveExtensions, extensionArgs } from "./extensions.ts";
|
|
82
|
-
import { prepareTaskRuntime, applyDirectApplicationLoadout, RUN_APPLICATION, SDK_BUILTIN_TOOLS } from "./task-policy.ts";
|
|
83
|
-
import {
|
|
84
|
+
import { prepareTaskRuntime, applyDirectApplicationLoadout, DEFAULT_TASK_PERMISSIONS, RUN_APPLICATION, SDK_BUILTIN_TOOLS } from "./task-policy.ts";
|
|
85
|
+
import { worktreePolicyNotice } from "./worktree-feedback.ts";
|
|
86
|
+
import { canonicalizePath, compileWritePolicy, takeRecoverySnapshot } from "./shared-sandbox-core.ts";
|
|
84
87
|
import { TASK_BUILTINS } from "./shared-task-sandbox.ts";
|
|
85
|
-
import {
|
|
88
|
+
import { describeTaskTools, planTaskTools, selectEffectiveTaskTools } from "./subagent-tools.ts";
|
|
86
89
|
import {
|
|
87
|
-
announceExecutionAdapter, observeSandboxPermissions, resolveCommandSettings, resolveSubagentPermissions,
|
|
90
|
+
announceExecutionAdapter, describeSubagentProcessPolicy, effectiveWorkerProcessAccess, observeSandboxPermissions, resolveCommandSettings, resolveSubagentPermissions,
|
|
88
91
|
} from "./permission-policy.ts";
|
|
89
|
-
import { resolveSubagentWorkspace } from "./git-workspace.ts";
|
|
90
92
|
import { dirname, isAbsolute, join } from "node:path";
|
|
91
93
|
import {
|
|
92
94
|
baseDir,
|
|
@@ -127,6 +129,7 @@ import {
|
|
|
127
129
|
type ChildEventFacts,
|
|
128
130
|
type HealthObservation,
|
|
129
131
|
type ProcessProbe,
|
|
132
|
+
type ReconcileResult,
|
|
130
133
|
type RawLogDiagnostic,
|
|
131
134
|
} from "./health.ts";
|
|
132
135
|
import {
|
|
@@ -135,6 +138,7 @@ import {
|
|
|
135
138
|
batchLaunchResult,
|
|
136
139
|
mergeJobOptions,
|
|
137
140
|
nextBatchId,
|
|
141
|
+
normalizeSessionSelector,
|
|
138
142
|
planBatchLaunches,
|
|
139
143
|
validateBatchPlan,
|
|
140
144
|
} from "./batch.mjs";
|
|
@@ -143,7 +147,7 @@ import {
|
|
|
143
147
|
getSharedCapacityGate,
|
|
144
148
|
} from "./capacity.mjs";
|
|
145
149
|
import { buildHealthCallbackDelivery } from "./completion.ts";
|
|
146
|
-
import { cancelCallbackBatch, getCallbackBatcher, setCallbackBatchContext } from "./shared-callback-batcher.ts";
|
|
150
|
+
import { cancelCallbackBatch, getCallbackBatcher, packCallbackBatch, setCallbackBatchContext } from "./shared-callback-batcher.ts";
|
|
147
151
|
let managementPort: import("./managed-launch-port.ts").ManagedLaunchPort | undefined;
|
|
148
152
|
const ownedByThisParent = (meta: Partial<RunMeta>) => managementPort ? managementPort.owns(meta) : ownedByFrontend(meta as RunMeta);
|
|
149
153
|
const supervisedMetas = () => managementPort ? managementPort.supervised() : listMetasForParent(process.pid);
|
|
@@ -174,6 +178,7 @@ import {
|
|
|
174
178
|
buildNavigatorDetail,
|
|
175
179
|
} from "./navigator.ts";
|
|
176
180
|
import { enforceRegistrySizeCapOnce, runDailyCleanupOnce } from "./cleanup.ts";
|
|
181
|
+
import { managedRuntimeRoot, selectContinuationRuntime } from "./continuation-runtime.ts";
|
|
177
182
|
import {
|
|
178
183
|
ContinuationError,
|
|
179
184
|
acquireConversationLease,
|
|
@@ -353,7 +358,7 @@ function callbackOriginFromContext(ctx: ExtensionContext): RunCallbackOrigin {
|
|
|
353
358
|
} catch {
|
|
354
359
|
sessionId = undefined;
|
|
355
360
|
}
|
|
356
|
-
return { cwd: ctx.cwd, sessionId };
|
|
361
|
+
return { cwd: ctx.cwd, sessionId, branchId: ctx.sessionManager?.getLeafId?.() ?? null };
|
|
357
362
|
}
|
|
358
363
|
|
|
359
364
|
/** Origin with a readable session id, or undefined when identity is unavailable. */
|
|
@@ -640,10 +645,52 @@ async function tryEnqueueAssignmentOutcome(pi: ExtensionAPI, meta: RunMeta): Pro
|
|
|
640
645
|
const prior = outcomeTranscriptReceipt(ctx.sessionManager.getBranch(), outcome.eventId);
|
|
641
646
|
if (prior) { receiptOutcome(meta, prior); return; }
|
|
642
647
|
const deliveryHost = outcomeHost;
|
|
643
|
-
|
|
648
|
+
// The Goal scheduler can take up to 20 seconds. Keep the short probe only
|
|
649
|
+
// for a standalone parent, with no bound Goal or acknowledged check.
|
|
650
|
+
const workflowBudgetMs = 25_000;
|
|
651
|
+
const gate = await requestResumeAdmission(pi, active, {
|
|
652
|
+
timeoutMs: active.goalId || outcome.recipient.goalId ? workflowBudgetMs : 50,
|
|
653
|
+
pendingTimeoutMs: workflowBudgetMs,
|
|
654
|
+
});
|
|
644
655
|
outcomeAdmission.set(outcome.eventId, () => gate.allowed ? gate.isCurrent?.() !== false : !active.goalId && !outcome.recipient.goalId && gate.revision === -1);
|
|
645
656
|
if (!gate.allowed && (active.goalId || outcome.recipient.goalId || gate.revision !== -1)) {
|
|
646
|
-
|
|
657
|
+
// Admission controls model execution, not delivery of an already
|
|
658
|
+
// committed result. Paused Goals still owe their human a notification.
|
|
659
|
+
if (sessionTornDown || outcomeHost !== deliveryHost || uiCtx !== ctx || callbackSuppressionReason(meta)
|
|
660
|
+
|| (outcome.recipient.branchId && !ctx.sessionManager.getBranch().some(entry => entry.id === outcome.recipient.branchId))) {
|
|
661
|
+
deferOutcome(meta, "Recorded parent delivery scope changed; automatic reconciliation will retry.");
|
|
662
|
+
return;
|
|
663
|
+
}
|
|
664
|
+
// Native Pi queues messages during a turn even with triggerTurn:false.
|
|
665
|
+
// Wait for idle so replay cannot enqueue the same unreceipted message.
|
|
666
|
+
if (!ctx.isIdle()) {
|
|
667
|
+
deferOutcome(meta, "Waiting for an idle parent to append the outcome without starting a turn.");
|
|
668
|
+
return;
|
|
669
|
+
}
|
|
670
|
+
if (!claimOutcome(meta, deliveryHost)) {
|
|
671
|
+
deferOutcome(meta, "Outcome dispatch is owned by another host; automatic reconciliation will retry.");
|
|
672
|
+
return;
|
|
673
|
+
}
|
|
674
|
+
const details = { completionEventIds: [outcome.eventId] };
|
|
675
|
+
const packed = packCallbackBatch([{
|
|
676
|
+
source: "subagent", id: outcome.eventId, inspectId: meta.id, receiptId: outcome.eventId,
|
|
677
|
+
label: meta.name ?? meta.id, status: outcome.outcome, outcome: outcome.reason,
|
|
678
|
+
detailTool: "subagent_result", callback: true,
|
|
679
|
+
}]);
|
|
680
|
+
try {
|
|
681
|
+
await pi.sendMessage({ customType: "background-completion-batch", display: true,
|
|
682
|
+
content: `${packed.text}\nAutomatic continuation: ${gate.reason}`, details }, { triggerTurn: false });
|
|
683
|
+
} catch (error) {
|
|
684
|
+
// A failed persistence must not look like a durable transcript receipt.
|
|
685
|
+
details.completionEventIds.length = 0;
|
|
686
|
+
throw error;
|
|
687
|
+
}
|
|
688
|
+
const entry = outcomeTranscriptReceipt(ctx.sessionManager.getBranch(), outcome.eventId);
|
|
689
|
+
if (!entry) throw new Error("Awaiting durable recipient transcript receipt.");
|
|
690
|
+
receiptOutcome(meta, entry);
|
|
691
|
+
markCompletionCallbackSent(meta.id, Date.now());
|
|
692
|
+
deferOutcome(meta);
|
|
693
|
+
try { ctx.ui?.notify(`${meta.name ?? meta.id}: ${outcome.outcome}. Automatic continuation: ${gate.reason}. Inspect subagent_result.`, outcome.outcome === "failed" ? "warning" : "info"); } catch { /* transcript remains visible */ }
|
|
647
694
|
return;
|
|
648
695
|
}
|
|
649
696
|
// Admission may yield across a session switch or Goal/workflow change.
|
|
@@ -767,16 +814,12 @@ function deliverFailureAttention(pi: ExtensionAPI | undefined, meta: RunMeta, no
|
|
|
767
814
|
|
|
768
815
|
function markHealthCallbackSuppressed(meta: RunMeta, status: "orphaned" | "lost", reason: string, now: number): void {
|
|
769
816
|
if (isConversationIdentityReason(reason)) return;
|
|
770
|
-
|
|
771
|
-
if (
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
meta.lostCallbackSuppressedAt = now;
|
|
777
|
-
meta.lostCallbackSuppressedReason = reason;
|
|
778
|
-
}
|
|
779
|
-
writeMeta(meta);
|
|
817
|
+
writeMeta(meta, { patch: current => {
|
|
818
|
+
if (isHealthCallbackHandled(current, status)) return;
|
|
819
|
+
return status === "orphaned"
|
|
820
|
+
? { orphanedCallbackSuppressedAt: now, orphanedCallbackSuppressedReason: reason }
|
|
821
|
+
: { lostCallbackSuppressedAt: now, lostCallbackSuppressedReason: reason };
|
|
822
|
+
} });
|
|
780
823
|
}
|
|
781
824
|
|
|
782
825
|
function isHealthCallbackHandled(meta: RunMeta, status: "orphaned" | "lost"): boolean {
|
|
@@ -922,8 +965,10 @@ function stopTicker(): void {
|
|
|
922
965
|
/** How often supervision is reconciled. Independent of TUI render scheduling. */
|
|
923
966
|
const HEALTH_TICK_MS = 15_000;
|
|
924
967
|
let healthTicker: ReturnType<typeof setInterval> | undefined;
|
|
968
|
+
let managedHealthClose: (() => void) | undefined;
|
|
925
969
|
/** ExtensionAPI retained so health transitions can deliver coordinator follow-ups (#65). */
|
|
926
970
|
let healthPi: ExtensionAPI | undefined;
|
|
971
|
+
let recoverWorkerWaitsAfterExit: (() => Promise<void>) | undefined;
|
|
927
972
|
|
|
928
973
|
/**
|
|
929
974
|
* Deliver a durable, deduped coordinator follow-up for orphaned/lost (#65).
|
|
@@ -958,9 +1003,10 @@ function deliverHealthCallback(pi: ExtensionAPI | undefined, meta: RunMeta, stat
|
|
|
958
1003
|
try { uiCtx.ui.notify(notice, "warning"); }
|
|
959
1004
|
catch { return; }
|
|
960
1005
|
// The marker acknowledges quiet delivery, never a model turn.
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
1006
|
+
writeMeta(meta, { patch: current => {
|
|
1007
|
+
if (current.status !== status || isHealthCallbackHandled(current, status) || callbackSuppressionReason(current)) return;
|
|
1008
|
+
return status === "orphaned" ? { orphanedCallbackSentAt: now } : { lostCallbackSentAt: now };
|
|
1009
|
+
} });
|
|
964
1010
|
return;
|
|
965
1011
|
}
|
|
966
1012
|
void getCallbackBatcher(pi).deliverUrgent({
|
|
@@ -982,9 +1028,10 @@ function deliverHealthCallback(pi: ExtensionAPI | undefined, meta: RunMeta, stat
|
|
|
982
1028
|
markFailureAttentionDelivered(failurePath(meta.id), attention, at);
|
|
983
1029
|
if (attention.incidents.some((incident) => pendingFailureAttention(collectRunFailures(meta.id, meta.cwd), at, { terminal: true })?.incidents.includes(incident))) return;
|
|
984
1030
|
}
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
1031
|
+
writeMeta(current, { patch: current => {
|
|
1032
|
+
if (isHealthCallbackHandled(current, status)) return;
|
|
1033
|
+
return status === "orphaned" ? { orphanedCallbackSentAt: at } : { lostCallbackSentAt: at };
|
|
1034
|
+
} });
|
|
988
1035
|
},
|
|
989
1036
|
onSuppressed: (reason, at) => {
|
|
990
1037
|
const current = readMeta(meta.id);
|
|
@@ -1297,12 +1344,13 @@ function enforceTiming(pi: ExtensionAPI | undefined, meta: RunMeta, now: number)
|
|
|
1297
1344
|
}
|
|
1298
1345
|
|
|
1299
1346
|
/** One reconciliation + durable health-callback recovery pass. */
|
|
1300
|
-
function reconcileHealth(): void {
|
|
1347
|
+
function reconcileHealth(ids?: readonly string[]): void {
|
|
1301
1348
|
if (!managementPort) return;
|
|
1302
1349
|
try { managementPort.assertCurrent(); } catch { stopHealthTicker(); return; }
|
|
1303
1350
|
const ctx = uiCtx;
|
|
1304
1351
|
const pi = healthPi;
|
|
1305
|
-
|
|
1352
|
+
const selected = ids ? ids.map(id => readMeta(id)).filter((meta): meta is NonNullable<typeof meta> => Boolean(meta)) : supervisedMetas();
|
|
1353
|
+
for (const summary of selected) {
|
|
1306
1354
|
if (!ownedByThisParent(summary)) continue;
|
|
1307
1355
|
// running/orphaned: process reconcile. lost: durable callback recovery only.
|
|
1308
1356
|
if (summary.status !== "running" && summary.status !== "orphaned" && summary.status !== "lost") continue;
|
|
@@ -1320,9 +1368,22 @@ function reconcileHealth(): void {
|
|
|
1320
1368
|
// Interrupted work whose child already exited is finalized from its own
|
|
1321
1369
|
// coherent log before any other verdict (and before timing can mislabel
|
|
1322
1370
|
// an already-finished run as stopped) (#625).
|
|
1371
|
+
let interruptedReconciliation: ReconcileResult | undefined;
|
|
1323
1372
|
if (meta.status === "running" || meta.status === "orphaned") {
|
|
1324
1373
|
try {
|
|
1325
|
-
if (
|
|
1374
|
+
if (pi && !directlySupervisedRunIds.has(meta.id) && meta.supervisionInterruptedAt !== undefined) {
|
|
1375
|
+
const observed = reconcileInterruptedRun(meta, realProcessProbe, now, {
|
|
1376
|
+
renderWidget,
|
|
1377
|
+
notify: (message, level) => { try { ctx?.ui.notify(message, level); } catch { /* unavailable UI */ } },
|
|
1378
|
+
sendMessage: () => enqueueCompletionCallback(pi, meta.id),
|
|
1379
|
+
});
|
|
1380
|
+
if (observed.finalization?.applied) {
|
|
1381
|
+
void recoverWorkerWaitsAfterExit?.().catch(() => undefined);
|
|
1382
|
+
syncHealthTicker();
|
|
1383
|
+
continue;
|
|
1384
|
+
}
|
|
1385
|
+
interruptedReconciliation = observed.reconciliation;
|
|
1386
|
+
}
|
|
1326
1387
|
} catch { /* best-effort; the ordinary reconciliation below still runs */ }
|
|
1327
1388
|
}
|
|
1328
1389
|
try {
|
|
@@ -1330,7 +1391,7 @@ function reconcileHealth(): void {
|
|
|
1330
1391
|
} catch { /* timing is best-effort per tick; supervision below still runs */ }
|
|
1331
1392
|
|
|
1332
1393
|
if (meta.status === "running" || meta.status === "orphaned") {
|
|
1333
|
-
const result = reconcileRun(meta, realProcessProbe, now);
|
|
1394
|
+
const result = interruptedReconciliation ?? reconcileRun(meta, realProcessProbe, now);
|
|
1334
1395
|
if (result.changed) {
|
|
1335
1396
|
Object.assign(meta, result.patch, { status: result.status });
|
|
1336
1397
|
writeMeta(meta);
|
|
@@ -1373,7 +1434,7 @@ function reconcileHealth(): void {
|
|
|
1373
1434
|
// is the human's own interrupted work, not another session's live run, and
|
|
1374
1435
|
// `finalizeInterruptedRunFromLog` still requires all process evidence to be
|
|
1375
1436
|
// absent, so a live writer is never touched.
|
|
1376
|
-
for (const summary of listMetas({ includeArchived: false })) {
|
|
1437
|
+
for (const summary of ids ? selected : listMetas({ includeArchived: false })) {
|
|
1377
1438
|
if (summary.status !== "running" && summary.status !== "orphaned") continue;
|
|
1378
1439
|
if (ownedByThisParent(summary) || !ownsInterruptedSupervision(summary)) continue;
|
|
1379
1440
|
const meta = readMeta(summary.id);
|
|
@@ -1381,7 +1442,7 @@ function reconcileHealth(): void {
|
|
|
1381
1442
|
try { finalizeInterruptedRunFromLog(pi, meta, Date.now()); } catch { /* the next tick retries */ }
|
|
1382
1443
|
}
|
|
1383
1444
|
// Completed runs can still have failed completion handoffs to retry.
|
|
1384
|
-
for (const summary of
|
|
1445
|
+
for (const summary of selected) {
|
|
1385
1446
|
if (!pi || !ownedByThisParent(summary) || summary.status === "running" || summary.status === "orphaned" || summary.status === "lost") continue;
|
|
1386
1447
|
const meta = readMeta(summary.id);
|
|
1387
1448
|
if (meta && meta.completionCallbackPendingAt !== undefined && meta.completionCallbackSentAt === undefined && meta.completionCallbackSuppressedAt === undefined) enqueueCompletionCallback(pi!, meta.id);
|
|
@@ -1474,6 +1535,7 @@ function syncHealthTicker(): void {
|
|
|
1474
1535
|
stopHealthTicker();
|
|
1475
1536
|
return;
|
|
1476
1537
|
}
|
|
1538
|
+
if (managementPort.observeHealth) { ensureHealthTicker(); return; }
|
|
1477
1539
|
if (needsMonitoring(supervisedMetas()) || needsInterruptedSupervision()) ensureHealthTicker();
|
|
1478
1540
|
else stopHealthTicker();
|
|
1479
1541
|
}
|
|
@@ -1481,6 +1543,10 @@ function syncHealthTicker(): void {
|
|
|
1481
1543
|
/** Start the reconciliation loop if it isn't already running. */
|
|
1482
1544
|
function ensureHealthTicker(): void {
|
|
1483
1545
|
if (!managementPort) return;
|
|
1546
|
+
if (managementPort.observeHealth) {
|
|
1547
|
+
managedHealthClose ??= managementPort.observeHealth(ids => reconcileHealth(ids));
|
|
1548
|
+
return;
|
|
1549
|
+
}
|
|
1484
1550
|
// Not gated on `sessionTornDown`: a spawn always means the current session is
|
|
1485
1551
|
// doing new work. Only `syncHealthTicker` — the path a late child finalizer
|
|
1486
1552
|
// takes — stays closed in a replaced instance.
|
|
@@ -1490,12 +1556,13 @@ function ensureHealthTicker(): void {
|
|
|
1490
1556
|
}
|
|
1491
1557
|
|
|
1492
1558
|
function stopHealthTicker(): void {
|
|
1559
|
+
managedHealthClose?.(); managedHealthClose = undefined;
|
|
1493
1560
|
if (healthTicker) { clearInterval(healthTicker); healthTicker = undefined; }
|
|
1494
1561
|
}
|
|
1495
1562
|
|
|
1496
1563
|
/** Test/diagnostic seam: whether the periodic reconciliation loop is active. */
|
|
1497
1564
|
export function isHealthTickerActive(): boolean {
|
|
1498
|
-
return healthTicker !== undefined;
|
|
1565
|
+
return healthTicker !== undefined || managedHealthClose !== undefined;
|
|
1499
1566
|
}
|
|
1500
1567
|
|
|
1501
1568
|
/**
|
|
@@ -1563,7 +1630,7 @@ const pendingNavigatorDismissals = new Set<string>();
|
|
|
1563
1630
|
function navigatorRunningCount(): number {
|
|
1564
1631
|
const snapshot = workObservation();
|
|
1565
1632
|
return (snapshot?.rows.filter((row: any) => !pendingNavigatorDismissals.has(row.meta.id) && !row.meta.dismissedAt && ["running", "waiting"].includes(row.assignment.state)).length ?? 0) +
|
|
1566
|
-
(
|
|
1633
|
+
(workObservationStarted() && snapshot?.status !== "ready" ? 1 : 0);
|
|
1567
1634
|
}
|
|
1568
1635
|
|
|
1569
1636
|
/**
|
|
@@ -1671,21 +1738,19 @@ function subagentWorkRows(now: number): BackgroundWorkRow[] {
|
|
|
1671
1738
|
const undismissed = new Set(sourceRows.filter((row: any) => !row.meta.dismissedAt).map((row: any) => row.meta.id));
|
|
1672
1739
|
for (const id of pendingNavigatorDismissals) if (!undismissed.has(id)) pendingNavigatorDismissals.delete(id);
|
|
1673
1740
|
}
|
|
1674
|
-
const rows: BackgroundWorkRow[] = sourceRows.filter((row: any) => !pendingNavigatorDismissals.has(row.meta.id) && !row.meta.dismissedAt
|
|
1675
|
-
(["running", "waiting"].includes(row.assignment.state) || typeof (row.meta.endedAt ?? row.meta.lostAt) !== "number" ||
|
|
1676
|
-
now - (row.meta.endedAt ?? row.meta.lostAt) < TERMINAL_NAVIGATOR_RETENTION_MS)).map((row: any) => {
|
|
1741
|
+
const rows: BackgroundWorkRow[] = sourceRows.filter((row: any) => !pendingNavigatorDismissals.has(row.meta.id) && !row.meta.dismissedAt).map((row: any) => {
|
|
1677
1742
|
const meta = row.meta;
|
|
1678
1743
|
const health = row.health ? observeRunHealth({ ...row.health, status: row.assignment.processStatus === "exited" ? meta.status : row.assignment.processStatus, now, startedAt: meta.startedAt }) : undefined;
|
|
1679
1744
|
const terminal = !["running", "waiting"].includes(row.assignment.state);
|
|
1680
|
-
return { providerId: "subagents", id: meta.id, name: meta.name || meta.id,
|
|
1745
|
+
return { providerId: "subagents", id: meta.id, agentId: meta.sessionId ?? meta.id, name: meta.name || meta.id,
|
|
1681
1746
|
model: shortModel(meta.model), effort: meta.effort, status: row.assignment.state,
|
|
1682
1747
|
tool: row.display?.tool, tokens: row.display?.spend,
|
|
1683
1748
|
statusTone: statusTone(row.assignment.state), kind: "subagent", elapsed: fmtElapsed((meta.endedAt ?? now) - meta.startedAt),
|
|
1684
1749
|
primary: [shortModel(meta.model), meta.effort, row.display?.tool, row.display?.spend].filter(Boolean).join(" ") || "subagent run", facts: formatNavigatorHealthFacts(health), sortStartedAt: meta.startedAt,
|
|
1685
1750
|
expiresAt: terminal && typeof meta.endedAt === "number" ? meta.endedAt + TERMINAL_NAVIGATOR_RETENTION_MS : undefined };
|
|
1686
1751
|
});
|
|
1687
|
-
if (
|
|
1688
|
-
status: snapshot?.status ?? "degraded", statusTone: "warning", kind: "observation", elapsed: "", primary:
|
|
1752
|
+
if (workObservationStarted() && snapshot?.status !== "ready") rows.unshift({ providerId: "subagents", id: "runtime-observation", name: "Status sync",
|
|
1753
|
+
status: snapshot?.status ?? "degraded", statusTone: "warning", kind: "observation", readOnly: true, elapsed: "", primary: "Task status unconfirmed · enter for details", sortStartedAt: now });
|
|
1689
1754
|
return rows;
|
|
1690
1755
|
}
|
|
1691
1756
|
|
|
@@ -1763,6 +1828,13 @@ function mainAgentWorkDetail(now: number): BackgroundWorkDetail {
|
|
|
1763
1828
|
|
|
1764
1829
|
function subagentWorkDetail(id: string, now: number, options?: { logTailLines?: number }): BackgroundWorkDetail | null {
|
|
1765
1830
|
if (id === "main") return mainAgentWorkDetail(now);
|
|
1831
|
+
if (id === "runtime-observation") return {
|
|
1832
|
+
providerId: "subagents", id, title: "Subagent status sync", status: workObservation()?.status ?? "rebuilding", statusTone: "warning",
|
|
1833
|
+
subtitle: "Shared status service · task status unconfirmed",
|
|
1834
|
+
metadata: [{ label: "scope", value: "Subagent status reads; not an individual task" }],
|
|
1835
|
+
evidence: { label: "Full diagnostic", text: workObservationFailure() },
|
|
1836
|
+
footerActions: [],
|
|
1837
|
+
};
|
|
1766
1838
|
const row = requestWorkDetail(id);
|
|
1767
1839
|
if (!row?.detail) return { providerId: "subagents", id, title: id, status: row?.observationError ? "degraded" : "rebuilding", statusTone: "warning", metadata: [], evidence: { label: "observation", text: row?.observationError ?? workObservationFailure() } };
|
|
1768
1840
|
const health = row.health ? observeRunHealth({ ...row.health, status: row.assignment.processStatus === "exited" ? row.meta.status : row.assignment.processStatus, now, startedAt: row.meta.startedAt }) : undefined;
|
|
@@ -1867,8 +1939,10 @@ function ensureSubagentProvider(): void {
|
|
|
1867
1939
|
id: "subagents",
|
|
1868
1940
|
label: "Subagents",
|
|
1869
1941
|
priority: 10,
|
|
1942
|
+
onOpen: () => { void activateWorkObservation(); },
|
|
1870
1943
|
visibleCount: () => navigatorRunningCount(),
|
|
1871
|
-
|
|
1944
|
+
// The last worker becoming terminal must not hide its retained result.
|
|
1945
|
+
showSection: (rows) => rows.length > 0,
|
|
1872
1946
|
parentRow: (now) => mainAgentWorkRow(now),
|
|
1873
1947
|
listRows: (now) => subagentWorkRows(now),
|
|
1874
1948
|
detail: (id, now, options) => subagentWorkDetail(id, now, options),
|
|
@@ -1884,6 +1958,7 @@ function ensureSubagentProvider(): void {
|
|
|
1884
1958
|
},
|
|
1885
1959
|
armCloseLabel: (row) => pendingNavigatorPark(workObservation()?.rows.find((observed: any) => observed.meta.id === row.id)?.meta) ? "x again to cancel resume" : row.status === "running" || row.status === "orphaned" ? "x again to stop" : "x again to dismiss",
|
|
1886
1960
|
close: (id) => {
|
|
1961
|
+
if (id === "runtime-observation") return { action: "not-closable", providerId: "subagents", id };
|
|
1887
1962
|
const outcome = navigatorCloseRun(id) as { action: string; id: string; status?: string };
|
|
1888
1963
|
return { ...outcome, providerId: "subagents" };
|
|
1889
1964
|
},
|
|
@@ -1993,19 +2068,25 @@ function resolvePiBinary(): string {
|
|
|
1993
2068
|
* first-party finalizer (finalization.ts) so tests can exercise the durable
|
|
1994
2069
|
* path without importing the pi package.
|
|
1995
2070
|
*/
|
|
1996
|
-
function finalizeRun(pi: ExtensionAPI, ctx: ExtensionContext | undefined, id: string, code: number | null): void {
|
|
2071
|
+
function finalizeRun(pi: ExtensionAPI, ctx: ExtensionContext | undefined, id: string, code: number | null, recoveredWriterExit = false): void {
|
|
1997
2072
|
progressCache.delete(id);
|
|
1998
2073
|
directlySupervisedRunIds.delete(id);
|
|
1999
2074
|
// Host-facing wrapper around first-party finalizer (finalization.ts).
|
|
2000
2075
|
// Coherent child-exit evidence may supersede provisional orphaned/lost
|
|
2001
2076
|
// reconciliation; finalization.ts enforces canExitFinalize + lifecycle authority.
|
|
2002
|
-
finalizeRunCore(id, code, {
|
|
2077
|
+
const result = finalizeRunCore(id, code, {
|
|
2078
|
+
recoveredWriterExit,
|
|
2003
2079
|
renderWidget,
|
|
2004
2080
|
notify: (message, level) => {
|
|
2005
2081
|
try { ctx?.ui.notify(message, level); } catch { /* ignore */ }
|
|
2006
2082
|
},
|
|
2007
2083
|
sendMessage: () => enqueueCompletionCallback(pi, id),
|
|
2008
2084
|
});
|
|
2085
|
+
if (recoveredWriterExit && result.applied) {
|
|
2086
|
+
// The old exit callback is gone. Finish its durable wait handoff after
|
|
2087
|
+
// recovery, including the independent writer and lease proof checks.
|
|
2088
|
+
void recoverWorkerWaitsAfterExit?.().catch(() => undefined);
|
|
2089
|
+
}
|
|
2009
2090
|
syncHealthTicker();
|
|
2010
2091
|
}
|
|
2011
2092
|
|
|
@@ -2037,7 +2118,7 @@ function finalizeInterruptedRunFromLog(
|
|
|
2037
2118
|
if (!run.sawEnd || run.unmatchedToolCalls.length > 0) return false;
|
|
2038
2119
|
// Exit code is unknown after the observer is gone; the lifecycle authority
|
|
2039
2120
|
// classifies from the coherent stream instead of inventing one.
|
|
2040
|
-
finalizeRun(pi, uiCtx, meta.id, null);
|
|
2121
|
+
finalizeRun(pi, uiCtx, meta.id, null, true);
|
|
2041
2122
|
return true;
|
|
2042
2123
|
}
|
|
2043
2124
|
|
|
@@ -2115,7 +2196,8 @@ function revalidateContinuationUnderLease(
|
|
|
2115
2196
|
id: plan.prior.id,
|
|
2116
2197
|
prior: current,
|
|
2117
2198
|
origin,
|
|
2118
|
-
|
|
2199
|
+
// Archived attempts are completed and cannot be competing writers.
|
|
2200
|
+
others: listMetas({ includeArchived: false }),
|
|
2119
2201
|
});
|
|
2120
2202
|
if (fresh.conversation.sessionId !== plan.conversation.sessionId || fresh.conversation.path !== plan.conversation.path) {
|
|
2121
2203
|
throw new ContinuationError(
|
|
@@ -2260,14 +2342,16 @@ function latestConversationAttempt(sessionId: string, metas: readonly RunMeta[])
|
|
|
2260
2342
|
* missing session is the only error added here. Nothing is ever recreated.
|
|
2261
2343
|
*/
|
|
2262
2344
|
function requestedSessionId(job: { session_id?: string; session_name?: string }, cwd: string): string | undefined {
|
|
2263
|
-
|
|
2345
|
+
const sessionId = normalizeSessionSelector(job.session_id);
|
|
2346
|
+
const sessionName = normalizeSessionSelector(job.session_name);
|
|
2347
|
+
if (sessionId !== undefined && sessionName !== undefined) {
|
|
2264
2348
|
throw new Error("Pass either session_id or session_name, not both.");
|
|
2265
2349
|
}
|
|
2266
|
-
if (
|
|
2267
|
-
if (typeof
|
|
2268
|
-
return selectSessionByName(listMetas(),
|
|
2350
|
+
if (sessionName !== undefined) {
|
|
2351
|
+
if (typeof sessionName !== "string") throw new Error("session_name must be a non-empty name.");
|
|
2352
|
+
return selectSessionByName(listMetas(), sessionName, (workspace) => isWithinWorkspace(workspace, cwd));
|
|
2269
2353
|
}
|
|
2270
|
-
return
|
|
2354
|
+
return sessionId;
|
|
2271
2355
|
}
|
|
2272
2356
|
|
|
2273
2357
|
function continuationPlanFor(sessionId: string, origin: RunCallbackOrigin | undefined): ContinuationPlan {
|
|
@@ -2340,6 +2424,12 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
2340
2424
|
let catalogModelRegistry: ExtensionContext["modelRegistry"] | undefined;
|
|
2341
2425
|
let delegationOverride: DelegationMode | undefined;
|
|
2342
2426
|
let capOverride: number | undefined;
|
|
2427
|
+
let workspaceOverride: "clone" | "worktree" | undefined;
|
|
2428
|
+
const activeWorkspace = () => workspaceOverride ?? (loadConfig().gitWorkspace === "worktree" ? "worktree" : "clone");
|
|
2429
|
+
const changeWorkspace = (mode: "clone" | "worktree") => {
|
|
2430
|
+
workspaceOverride = mode;
|
|
2431
|
+
pi.appendEntry("pi-better-subagents-workspace", { version: 1, mode });
|
|
2432
|
+
};
|
|
2343
2433
|
let timingOverride: { maxMinutes?: number; toolWaitMinutes?: number; stuckMinutes?: number } = {};
|
|
2344
2434
|
interface SkillSelection { mode: SkillExposureMode; paths: string[] }
|
|
2345
2435
|
let skillsOverride: SkillSelection | undefined;
|
|
@@ -2467,7 +2557,9 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
2467
2557
|
capOverride = undefined;
|
|
2468
2558
|
delegationOverride = undefined;
|
|
2469
2559
|
timingOverride = {};
|
|
2560
|
+
workspaceOverride = undefined;
|
|
2470
2561
|
skillsOverride = undefined;
|
|
2562
|
+
pi.appendEntry("pi-better-subagents-workspace", { version: 1, mode: null });
|
|
2471
2563
|
pi.appendEntry("pi-better-subagents-cap", { version: 1, maxConcurrent: null });
|
|
2472
2564
|
pi.appendEntry("pi-better-subagents-delegation", { version: 1, mode: null });
|
|
2473
2565
|
pi.appendEntry("pi-better-subagents-timing", { version: 1, maxMinutes: null, toolWaitMinutes: null, stuckMinutes: null });
|
|
@@ -2560,6 +2652,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
2560
2652
|
savedTiming.stuckMinutes = cfg.stuckMinutes;
|
|
2561
2653
|
}
|
|
2562
2654
|
writeSubagentSettings({
|
|
2655
|
+
...(workspaceOverride ? { gitWorkspace: workspaceOverride } : {}),
|
|
2563
2656
|
delegationMode: activeDelegationMode(),
|
|
2564
2657
|
maxConcurrent: activeConcurrencyCap(),
|
|
2565
2658
|
...savedTiming,
|
|
@@ -2600,6 +2693,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
2600
2693
|
delegationOverride = undefined;
|
|
2601
2694
|
capOverride = undefined;
|
|
2602
2695
|
timingOverride = {};
|
|
2696
|
+
workspaceOverride = undefined;
|
|
2603
2697
|
skillsOverride = undefined;
|
|
2604
2698
|
const branch = ctx.sessionManager?.getBranch?.();
|
|
2605
2699
|
if (!Array.isArray(branch)) return;
|
|
@@ -2634,6 +2728,12 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
2634
2728
|
}
|
|
2635
2729
|
continue;
|
|
2636
2730
|
}
|
|
2731
|
+
if (entry.type === "custom" && entry.customType === "pi-better-subagents-workspace") {
|
|
2732
|
+
const data = entry.data as { version?: number; mode?: unknown } | null;
|
|
2733
|
+
if (data?.version === 1 && (data.mode === "worktree" || data.mode === "clone" || data.mode === null)) {
|
|
2734
|
+
workspaceOverride = data.mode ?? undefined;
|
|
2735
|
+
}
|
|
2736
|
+
}
|
|
2637
2737
|
if (entry.type === "custom" && entry.customType === "pi-better-subagents-timing") {
|
|
2638
2738
|
const data = entry.data as {
|
|
2639
2739
|
version?: unknown; maxMinutes?: unknown; toolWaitMinutes?: unknown; stuckMinutes?: unknown;
|
|
@@ -2659,6 +2759,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
2659
2759
|
// Capture for the health ticker (module-level); needed for orphaned/lost
|
|
2660
2760
|
// coordinator follow-ups that fire outside a tool-call stack (#65).
|
|
2661
2761
|
healthPi = pi;
|
|
2762
|
+
recoverWorkerWaitsAfterExit = reconcileWorkerWaits;
|
|
2662
2763
|
ensureSubagentProvider();
|
|
2663
2764
|
registerSubagentsGoalProvider(pi);
|
|
2664
2765
|
observeSandboxPermissions(pi);
|
|
@@ -2668,13 +2769,16 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
2668
2769
|
const registerSpawnTool: ExtensionAPI["registerTool"] = (definition) => {
|
|
2669
2770
|
registeredSpawnSchemas.set(definition.name, definition.parameters);
|
|
2670
2771
|
pi.registerTool(managed ? { ...definition, async execute(key, params, signal, onUpdate, ctx) {
|
|
2772
|
+
ctx = captureLaunchContext(ctx);
|
|
2671
2773
|
restoreDelegationMode(ctx);
|
|
2672
2774
|
await workerOperations.start();
|
|
2673
2775
|
return definition.execute(key, params, signal, onUpdate, ctx);
|
|
2674
|
-
} } : { ...definition, async execute(key, params,
|
|
2776
|
+
} } : { ...definition, async execute(key, params, signal, _onUpdate, ctx) {
|
|
2777
|
+
ctx = captureLaunchContext(ctx);
|
|
2675
2778
|
catalogHostFrom(ctx);
|
|
2676
2779
|
const { submitManagedLaunch } = await import("./managed-launch-client.ts");
|
|
2677
|
-
|
|
2780
|
+
void activateWorkObservation();
|
|
2781
|
+
return await observeNavigatorLaunch(ctx, "subagents", key, "Subagent launch", () => submitManagedLaunch(pi, ctx, key, definition.name, params, signal)) as never;
|
|
2678
2782
|
} });
|
|
2679
2783
|
};
|
|
2680
2784
|
announceExecutionAdapter(pi, {
|
|
@@ -2764,7 +2868,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
2764
2868
|
/** Skill exposure for this launch; omit to inherit catalog/config/discovery. */
|
|
2765
2869
|
skills?: readonly string[];
|
|
2766
2870
|
sandbox_dir?: string; callback?: boolean; cwd?: string;
|
|
2767
|
-
git_clone_workspace?: boolean; approve?: boolean; allow_nested?: boolean;
|
|
2871
|
+
git_clone_workspace?: boolean; isolation?: boolean; recover_in_clone?: boolean; approve?: boolean; allow_nested?: boolean;
|
|
2768
2872
|
agent?: string; role?: string | readonly string[]; alias?: string;
|
|
2769
2873
|
catalog?: CatalogRunRecord; catalogResolved?: boolean;
|
|
2770
2874
|
/**
|
|
@@ -2828,6 +2932,10 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
2828
2932
|
/** Set only when a catalog run's model or effort differs from its role or agent default. */
|
|
2829
2933
|
modelNote?: string;
|
|
2830
2934
|
}> {
|
|
2935
|
+
const { resolveChildClosure, resolveChildLaunch, configSnapshot } = await import("./child-dependencies.mjs");
|
|
2936
|
+
const { resolveSubagentWorkspace, inspectGitWorkspace } = await import("./git-workspace.ts");
|
|
2937
|
+
const { workspaceChoice, createIsolatedWorkspace, restoreWorkspace, discardWorkspace, markWorkspaceWriter } = await import("./isolated-workspace.ts");
|
|
2938
|
+
const { PREFLIGHT_ENV } = await import("./child-preflight.mjs");
|
|
2831
2939
|
assertThinkingLevel(p.thinking);
|
|
2832
2940
|
// Skill exposure is a caller choice, not a launch: validate its shape
|
|
2833
2941
|
// before any attempt directory or capacity effect exists. A continuation
|
|
@@ -2846,13 +2954,13 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
2846
2954
|
// frozen confinement intent. Historical metadata can never widen authority,
|
|
2847
2955
|
// and a profile that would change confinement refuses instead of silently
|
|
2848
2956
|
// moving a live conversation into a different sandbox.
|
|
2849
|
-
const permissionPlan = resolveSubagentPermissions(pi,
|
|
2850
|
-
|
|
2851
|
-
|
|
2852
|
-
|
|
2853
|
-
|
|
2854
|
-
|
|
2855
|
-
|
|
2957
|
+
const permissionPlan = resolveSubagentPermissions(pi, p.sandbox,
|
|
2958
|
+
resume && { runId: resume.prior.id, sandbox: resume.recipe.sandbox });
|
|
2959
|
+
const processPolicy = describeSubagentProcessPolicy(permissionPlan, process.platform);
|
|
2960
|
+
const processAccess = effectiveWorkerProcessAccess(permissionPlan);
|
|
2961
|
+
const taskPermissions = permissionPlan.inactiveProfile
|
|
2962
|
+
? { ...DEFAULT_TASK_PERMISSIONS, processAccess }
|
|
2963
|
+
: permissionPlan.permissions;
|
|
2856
2964
|
const cfg = loadConfig();
|
|
2857
2965
|
// Harness-owned timing (soft deadline, ceiling, tool-wait and stuck windows); validated before any side effect.
|
|
2858
2966
|
resolveRunTiming({ params: launchTimingParams(p), settings: timingSettingsFor(cfg), env: process.env, startedAt: 0 });
|
|
@@ -2918,7 +3026,38 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
2918
3026
|
// The disposable clone this launch owns (removed if the spawn fails); a caller's sandbox_dir is not ours.
|
|
2919
3027
|
// A continuation never prepares another clone: the recipe's workspace already
|
|
2920
3028
|
// holds the prior attempt's uncommitted work.
|
|
2921
|
-
|
|
3029
|
+
if (p.isolation === false && p.git_clone_workspace) throw new Error("Choose either live checkout or git_clone_workspace.");
|
|
3030
|
+
if (p.recover_in_clone && (!resume || resume.recipe.workspace?.mode !== "worktree" || internal?.resumeWait)) {
|
|
3031
|
+
throw new Error("Clone handoff requires an explicit continuation of a linked worktree.");
|
|
3032
|
+
}
|
|
3033
|
+
if (resume && p.isolation !== undefined && Boolean(resume.recipe.workspace || resume.recipe.gitCloneWorkspace) !== p.isolation) {
|
|
3034
|
+
throw new ContinuationError("Changing isolation would replace the saved workspace.");
|
|
3035
|
+
}
|
|
3036
|
+
const handoffAuthority = p.recover_in_clone ? resume?.recipe.workspaceAuthority : undefined;
|
|
3037
|
+
if (p.recover_in_clone && resume) {
|
|
3038
|
+
const previous = handoffAuthority?.sandbox;
|
|
3039
|
+
const permissions = taskPermissions ?? DEFAULT_TASK_PERMISSIONS;
|
|
3040
|
+
assertAssignmentPermissionScope(handoffAuthority, {
|
|
3041
|
+
mandatoryPermissions: permissionPlan.enforced,
|
|
3042
|
+
sandbox: sandboxEnabled ? {
|
|
3043
|
+
root: resume.recipe.sandboxDir,
|
|
3044
|
+
denyWrite: previous?.denyWrite ?? [],
|
|
3045
|
+
permissions: {
|
|
3046
|
+
...DEFAULT_TASK_PERMISSIONS, ...permissions, ...resolveCommandSettings(permissions),
|
|
3047
|
+
processAccess: permissions.processAccess ?? "off",
|
|
3048
|
+
},
|
|
3049
|
+
} : null,
|
|
3050
|
+
});
|
|
3051
|
+
}
|
|
3052
|
+
const selected = normalizeTools(p.tools ?? cfg.defaultTools ?? (p.clean ? SAFE_CLEAN_TOOLS : SAFE_DEFAULT_TOOLS));
|
|
3053
|
+
let isolated = resume?.recipe.workspace;
|
|
3054
|
+
if (!resume && !p.sandbox_dir && p.isolation !== false) {
|
|
3055
|
+
isolated = workspaceChoice(
|
|
3056
|
+
p.cwd ?? ctx.cwd, id, p.git_clone_workspace ? "clone" : activeWorkspace(),
|
|
3057
|
+
p.git_clone_workspace ? "write" : selected, p.git_clone_workspace ? "" : p.exclude_tools ?? "",
|
|
3058
|
+
);
|
|
3059
|
+
}
|
|
3060
|
+
const ownedCloneWorkspace = !resume && !p.sandbox_dir && (isolated || p.git_clone_workspace) ? taskWorkspaceDir(id) : undefined;
|
|
2922
3061
|
// A launch attempt only becomes a run when `writeMeta` commits. Until
|
|
2923
3062
|
// then everything it creates (prompt, control/, provenance, its own
|
|
2924
3063
|
// session dir, clone workspace, task scratch) belongs to the attempt and
|
|
@@ -2928,6 +3067,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
2928
3067
|
let spawned: ReturnType<typeof spawnDetached> | undefined;
|
|
2929
3068
|
let launchScratch: string | undefined;
|
|
2930
3069
|
let committed = false;
|
|
3070
|
+
let createdWorkspace = false;
|
|
2931
3071
|
try {
|
|
2932
3072
|
if (!resume) mkdirSync(childSessionDir, { recursive: true });
|
|
2933
3073
|
mkdirSync(runDir(id), { recursive: true });
|
|
@@ -2937,17 +3077,30 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
2937
3077
|
// (#623 R1). The outer catch drops the whole directory on failure.
|
|
2938
3078
|
recordLaunchAttempt(id);
|
|
2939
3079
|
|
|
3080
|
+
// Cleanup, restoration and the actual writer share the conversation lease.
|
|
3081
|
+
if (resume || managed) lease = acquireConversationLease({ sessionId, attemptId: id });
|
|
3082
|
+
if (resume) {
|
|
3083
|
+
revalidateContinuationUnderLease(resume, callbackOrigin);
|
|
3084
|
+
if (isolated) isolated = restoreWorkspace(isolated, p.recover_in_clone, resume.prior.id);
|
|
3085
|
+
}
|
|
3086
|
+
if (!resume && isolated) {
|
|
3087
|
+
const root = taskWorkspaceDir(id);
|
|
3088
|
+
mkdirSync(dirname(root), { recursive: true });
|
|
3089
|
+
mkdirSync(root, { mode: 0o700 });
|
|
3090
|
+
createdWorkspace = true;
|
|
3091
|
+
}
|
|
3092
|
+
const isolatedCwd = isolated && !resume && !p.git_clone_workspace ? createIsolatedWorkspace(isolated, true) : undefined;
|
|
2940
3093
|
const workspace = resume
|
|
2941
3094
|
? { cwd: resume.recipe.cwd, requestedSandboxDir: resume.recipe.sandboxDir }
|
|
3095
|
+
: isolatedCwd ? { cwd: isolatedCwd, requestedSandboxDir: sandboxEnabled ? isolatedCwd : undefined }
|
|
2942
3096
|
: resolveSubagentWorkspace({
|
|
2943
|
-
ctxCwd: ctx.cwd,
|
|
2944
|
-
|
|
2945
|
-
sandboxDir: p.sandbox_dir ?? ownedCloneWorkspace,
|
|
2946
|
-
gitCloneWorkspace: p.git_clone_workspace,
|
|
2947
|
-
runId: id,
|
|
2948
|
-
runDirPath: runDir(id),
|
|
2949
|
-
sandboxEnabled,
|
|
3097
|
+
ctxCwd: ctx.cwd, cwd: p.cwd, sandboxDir: p.sandbox_dir ?? ownedCloneWorkspace,
|
|
3098
|
+
gitCloneWorkspace: p.git_clone_workspace, runId: id, runDirPath: runDir(id), sandboxEnabled,
|
|
2950
3099
|
});
|
|
3100
|
+
// Legacy explicit clones launch at the repository root, even when the source is a subdirectory.
|
|
3101
|
+
if (!resume && isolated && p.git_clone_workspace) isolated = { ...isolated, subdir: "" };
|
|
3102
|
+
let workspaceNote = isolated ? `Git workspace: ${isolated.mode} at ${workspace.cwd}. Base ${isolated.base}.`
|
|
3103
|
+
+ (isolated.mode === "worktree" && sandboxEnabled ? " Git metadata is shared outside this checkout. If the sandbox denies a Git operation, report the operation and current changes. The parent can review them here or continue this session with recover_in_clone:true." : "") : "";
|
|
2951
3104
|
const cwd = workspace.cwd;
|
|
2952
3105
|
const requestedSandboxDir = workspace.requestedSandboxDir;
|
|
2953
3106
|
|
|
@@ -2974,7 +3127,8 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
2974
3127
|
});
|
|
2975
3128
|
|
|
2976
3129
|
if (requestedSandboxDir) mkdirSync(requestedSandboxDir, { recursive: true });
|
|
2977
|
-
|
|
3130
|
+
const workerPrompt = workspaceNote ? workspaceNote + "\n\n" + p.prompt : p.prompt;
|
|
3131
|
+
writeFileSync(promptPathFor(id), workerPrompt);
|
|
2978
3132
|
|
|
2979
3133
|
// A continuation keeps the recipe's launch intent; only current
|
|
2980
3134
|
// permission-driven adjustments are re-derived from it.
|
|
@@ -2983,7 +3137,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
2983
3137
|
const clean = resume ? resume.recipe.clean : p.clean === true;
|
|
2984
3138
|
const allowNested = resume ? resume.recipe.allowNested : p.allow_nested === true;
|
|
2985
3139
|
const approve = resume ? resume.recipe.approve : p.approve === true;
|
|
2986
|
-
const gitCloneWorkspace = resume ? resume.recipe.gitCloneWorkspace : p.git_clone_workspace === true;
|
|
3140
|
+
const gitCloneWorkspace = isolated ? isolated.mode === "clone" : resume ? resume.recipe.gitCloneWorkspace : p.git_clone_workspace === true;
|
|
2987
3141
|
const callbackEnabled = resume ? p.callback ?? resume.recipe.callback : p.callback !== false;
|
|
2988
3142
|
const launchName = resume ? resume.recipe.name : p.name;
|
|
2989
3143
|
// The frozen launch snapshot is the same shape a fresh spawn freezes.
|
|
@@ -3000,8 +3154,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3000
3154
|
.filter(Boolean).join(",");
|
|
3001
3155
|
}
|
|
3002
3156
|
|
|
3003
|
-
//
|
|
3004
|
-
// the guarded apply_patch adapter, and trusted tools admitted by name and package.
|
|
3157
|
+
// Exclusions apply to the worker selection before provider admission (ADR 0027).
|
|
3005
3158
|
const requestedExcludes = new Set(requestedExcludeTools.split(",").map((t) => t.trim()).filter(Boolean));
|
|
3006
3159
|
|
|
3007
3160
|
// Supervised worker operations. This only decides which names the
|
|
@@ -3044,19 +3197,19 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3044
3197
|
bridgePlan.capabilities = { ...bridgePlan.capabilities, reportAssignment: true };
|
|
3045
3198
|
productionBridgeSchemas.schemas.set("report_assignment_result", createToolDescriptor("report_assignment_result"));
|
|
3046
3199
|
}
|
|
3200
|
+
assertWaitToolDependencies(bridgePlan.capabilities, bridgePlan.tools);
|
|
3047
3201
|
const bridgeEnabled = bridgePlan.tools.length > 0;
|
|
3048
3202
|
if (bridgeEnabled) {
|
|
3049
3203
|
allow = [...new Set([...allow.split(",").filter(Boolean), ...bridgePlan.tools])].join(",");
|
|
3050
3204
|
}
|
|
3051
3205
|
|
|
3052
|
-
if (
|
|
3206
|
+
if (!clean) {
|
|
3053
3207
|
const names = allow.split(",").filter(Boolean);
|
|
3054
|
-
//
|
|
3055
|
-
if (
|
|
3056
|
-
if (requestedTools === undefined) names.push(...permissionPlan.tools.trusted.map((entry) => entry.name));
|
|
3208
|
+
// Derive the editable loadout before applying the resource policy.
|
|
3209
|
+
if (!resume) addEditablePatch(names, requestedExcludes);
|
|
3057
3210
|
allow = [...new Set(names)].join(",");
|
|
3058
3211
|
}
|
|
3059
|
-
if (sandboxEnabled && requestedTools === undefined &&
|
|
3212
|
+
if (sandboxEnabled && requestedTools === undefined && processAccess === "read") {
|
|
3060
3213
|
allow = [...new Set([...allow.split(","), "process_list"])].join(",");
|
|
3061
3214
|
}
|
|
3062
3215
|
// Shell Off confines the child to directly launched applications: a requested bash
|
|
@@ -3076,12 +3229,20 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3076
3229
|
// Candidates for the task-tool plan: exclusions and bridge-supplied
|
|
3077
3230
|
// names never reach extension admission.
|
|
3078
3231
|
const plannedTools = allow.split(",").filter((name) => name && !requestedExcludes.has(name) && !bridgeToolNames.has(name));
|
|
3232
|
+
const continuationRuntime = selectContinuationRuntime({ currentDir: selfDir(), recipe: resume?.recipe });
|
|
3233
|
+
const workerPath = (path: string) => continuationRuntime?.mapPath(path) ?? path;
|
|
3234
|
+
const workerArgs = (args: string[]) => continuationRuntime?.mapArgs(args) ?? args;
|
|
3235
|
+
const workerResolvePath = (spec: string) => {
|
|
3236
|
+
const path = resolveExtensionPath(spec);
|
|
3237
|
+
return path ? workerPath(path) : path;
|
|
3238
|
+
};
|
|
3239
|
+
const normalProviders = ordinaryChildConfig(cfg, managed?.activeProviders?.() ?? activeChildProviders(pi));
|
|
3079
3240
|
const taskTools = sandboxEnabled ? planTaskTools({
|
|
3080
3241
|
requested: plannedTools,
|
|
3081
3242
|
settings: permissionPlan.tools, network: permissionPlan.permissions?.network ?? true,
|
|
3082
|
-
processAccess
|
|
3243
|
+
processAccess,
|
|
3083
3244
|
builtins: [...TASK_BUILTINS, "codemode"], registered: pi.getAllTools?.() ?? [],
|
|
3084
|
-
toolExtensions:
|
|
3245
|
+
toolExtensions: normalProviders.toolExtensions, resolvePath: workerResolvePath,
|
|
3085
3246
|
}) : undefined;
|
|
3086
3247
|
// One effective selection feeds the task policy, child preflight, worker
|
|
3087
3248
|
// bridge and frozen recipe, so a refused tool cannot leak into any of them
|
|
@@ -3102,11 +3263,11 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3102
3263
|
throw resume
|
|
3103
3264
|
? new ContinuationError(
|
|
3104
3265
|
`Cannot continue ${resume.prior.id}: its frozen launch requires tool(s) this parent can no longer provide: ${detail}. ` +
|
|
3105
|
-
`Launch a new run instead of continuing this conversation
|
|
3266
|
+
`Launch a new run instead of continuing this conversation. ${processPolicy}`,
|
|
3106
3267
|
)
|
|
3107
3268
|
: new Error(
|
|
3108
3269
|
`Requested tool(s) are not available in the task sandbox: ${detail}. ` +
|
|
3109
|
-
`
|
|
3270
|
+
`Check the child tool provider and the Subagents resource permissions; nothing was launched.`,
|
|
3110
3271
|
);
|
|
3111
3272
|
}
|
|
3112
3273
|
if (toolSelection) {
|
|
@@ -3115,53 +3276,63 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3115
3276
|
}
|
|
3116
3277
|
allow = toolSelection.tools.join(",");
|
|
3117
3278
|
}
|
|
3279
|
+
// Older recipes were frozen before isolated workers gained Harness providers
|
|
3280
|
+
// and inherited workers began loading mappings explicitly.
|
|
3281
|
+
const legacyToolLoading = resume !== undefined && !resume.recipe.toolLoadingVersion;
|
|
3282
|
+
let extensionConfig = cfg;
|
|
3283
|
+
if (!sandboxEnabled && !legacyToolLoading) extensionConfig = normalProviders;
|
|
3284
|
+
if (legacyToolLoading && cfg.inheritExtensions) extensionConfig = { ...cfg, toolExtensions: {} };
|
|
3118
3285
|
const dependencyOptions = {
|
|
3119
3286
|
model, virtual: (() => {
|
|
3120
3287
|
const slash = model?.indexOf("/") ?? -1;
|
|
3121
3288
|
return slash > 0 && ctx.modelRegistry?.find?.(model!.slice(0, slash), model!.slice(slash + 1))?.api === "pi-virtual";
|
|
3122
|
-
})(), config:
|
|
3123
|
-
configPaths: [configPath(), join(selfDir(), "config.json")],
|
|
3289
|
+
})(), config: extensionConfig, resolvePath: workerResolvePath,
|
|
3290
|
+
configPaths: [configPath(), workerPath(join(selfDir(), "config.json"))],
|
|
3124
3291
|
};
|
|
3125
3292
|
// Bridge tools are supplied by the worker bridge extension, not by a
|
|
3126
3293
|
// configured toolExtensions mapping: keep them out of extension
|
|
3127
3294
|
// resolution so `unmapped` stays an accurate operator warning and the
|
|
3128
3295
|
// frozen launch recipe never depends on bridge availability.
|
|
3129
|
-
const extensionAllowlist = () => (
|
|
3130
|
-
|
|
3131
|
-
: allow);
|
|
3296
|
+
const extensionAllowlist = () => allow.split(",")
|
|
3297
|
+
.filter(name => !requestedExcludes.has(name) && !bridgeToolNames.has(name)).join(",");
|
|
3132
3298
|
const { resolution, fullResolution } = await resolveChildLaunch({ ...dependencyOptions, resolution: resolveExtensions({
|
|
3133
3299
|
// Only SDK builtins reach `--tools` and extension resolution: process_list and run_application
|
|
3134
3300
|
// are task builtins that the mandatory guard installs and activates itself.
|
|
3135
3301
|
tools: sandboxEnabled ? allow.split(",").filter((name) => (SDK_BUILTIN_TOOLS as readonly string[]).includes(name)).join(",") : extensionAllowlist(),
|
|
3136
|
-
model, clean, allowNested: sandboxEnabled ? false : allowNested, config:
|
|
3302
|
+
model, clean, allowNested: sandboxEnabled ? false : allowNested, config: extensionConfig,
|
|
3137
3303
|
}) }, taskTools?.trusted.map(tool => tool.loadPath) ?? []);
|
|
3138
|
-
|
|
3304
|
+
if (!sandboxEnabled && resolution.mode === "isolated" &&
|
|
3305
|
+
fullResolution.specs.every((spec: string) => Object.values(ORDINARY_TOOL_PROVIDERS).includes(spec))) {
|
|
3306
|
+
const missingTools = resolution.unmapped.filter((name: string) => requiredToolNames.has(name));
|
|
3307
|
+
if (missingTools.length) throw new Error(`No provider for required child tools: ${missingTools.join(", ")}. Configure toolExtensions or change the requested tools.`);
|
|
3308
|
+
}
|
|
3309
|
+
const { args: resolvedExtArgs, missing } = extensionArgs(resolution, (spec) => resolution.paths[spec] ?? workerResolvePath(spec));
|
|
3139
3310
|
const trustedExtArgs = fullResolution.specs.map(spec => fullResolution.paths[spec])
|
|
3140
3311
|
.filter(path => !resolvedExtArgs.includes(path)).flatMap(path => ["--extension", path]);
|
|
3141
3312
|
// Harness child controls ride along in every mode, including clean and unsandboxed runs.
|
|
3142
3313
|
// They deliver deadline steers and keep external monitoring with the coordinator.
|
|
3143
3314
|
const codemodeArgs = !sandboxEnabled && allow.split(",").includes("codemode") && !requestedExcludes.has("codemode")
|
|
3144
3315
|
? ["--extension", join(selfDir(), "child-codemode.ts")] : [];
|
|
3145
|
-
const extArgs = [...resolvedExtArgs, ...trustedExtArgs, ...codemodeArgs,
|
|
3316
|
+
const extArgs = workerArgs([...resolvedExtArgs, ...trustedExtArgs, ...codemodeArgs,
|
|
3146
3317
|
"--extension", childSteerExtensionPath(), "--extension", join(selfDir(), "child-ownership.ts")]
|
|
3147
|
-
.map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value);
|
|
3148
|
-
const baseExtensionArgs = [...resolvedExtArgs, ...codemodeArgs,
|
|
3318
|
+
.map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value));
|
|
3319
|
+
const baseExtensionArgs = workerArgs([...resolvedExtArgs, ...codemodeArgs,
|
|
3149
3320
|
"--extension", childSteerExtensionPath(), "--extension", join(selfDir(), "child-ownership.ts")]
|
|
3150
|
-
.map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value);
|
|
3321
|
+
.map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value));
|
|
3151
3322
|
if (resume?.recipe.extensionArgs) {
|
|
3152
3323
|
// A model escalation may change provider auth, but an unchanged tool
|
|
3153
3324
|
// must not silently switch implementations with current configuration.
|
|
3154
3325
|
const reference = model === resume.recipe.model ? resolution : await resolveChildClosure({
|
|
3155
3326
|
...dependencyOptions, model: resume.recipe.model, virtual: false, resolution: resolveExtensions({
|
|
3156
3327
|
tools: sandboxEnabled ? allow.split(",").filter((name) => (SDK_BUILTIN_TOOLS as readonly string[]).includes(name)).join(",") : extensionAllowlist(),
|
|
3157
|
-
model: resume.recipe.model, clean, allowNested: sandboxEnabled ? false : allowNested, config:
|
|
3328
|
+
model: resume.recipe.model, clean, allowNested: sandboxEnabled ? false : allowNested, config: extensionConfig,
|
|
3158
3329
|
}) });
|
|
3159
|
-
const referenceArgs = [...extensionArgs(reference, (spec) => reference.paths[spec] ??
|
|
3330
|
+
const referenceArgs = [...extensionArgs(reference, (spec) => reference.paths[spec] ?? workerResolvePath(spec)).args, ...codemodeArgs,
|
|
3160
3331
|
...(!resume.recipe.baseExtensionArgs ? trustedExtArgs : []),
|
|
3161
3332
|
"--extension", childSteerExtensionPath(), "--extension", join(selfDir(), "child-ownership.ts")]
|
|
3162
3333
|
.map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value);
|
|
3163
3334
|
assertContinuationExtensions(resume.prior.id, resume.recipe,
|
|
3164
|
-
referenceArgs, taskTools?.trusted ?? []);
|
|
3335
|
+
workerArgs(referenceArgs), (taskTools?.trusted ?? []).map(tool => ({ ...tool, loadPath: workerPath(tool.loadPath) })));
|
|
3165
3336
|
}
|
|
3166
3337
|
if (sandboxEnabled && resolution.mode === "inherit") {
|
|
3167
3338
|
throw new Error("Task confinement requires explicit extensions; inheritExtensions is unsupported while sandboxing is enabled.");
|
|
@@ -3190,7 +3361,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3190
3361
|
// supervision capability, not a tool implementation, so it must not
|
|
3191
3362
|
// invalidate a conversation's saved recipe when it appears later.
|
|
3192
3363
|
const commandExtArgs = bridgeEnabled
|
|
3193
|
-
? [...extArgs, "--extension", childBridgeExtensionPath(selfDir())]
|
|
3364
|
+
? [...extArgs, "--extension", workerPath(childBridgeExtensionPath(selfDir()))]
|
|
3194
3365
|
: extArgs;
|
|
3195
3366
|
const args = [
|
|
3196
3367
|
"-p", "--mode", "json",
|
|
@@ -3202,29 +3373,46 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3202
3373
|
...(allow && !sandboxEnabled ? ["--tools", allow] : []),
|
|
3203
3374
|
...(excludes.size ? ["--exclude-tools", [...excludes].join(",")] : []),
|
|
3204
3375
|
...(sandboxEnabled ? ["--no-builtin-tools", "--no-approve"] : approve ? ["--approve"] : []),
|
|
3205
|
-
|
|
3376
|
+
workerPrompt,
|
|
3206
3377
|
];
|
|
3207
3378
|
|
|
3208
3379
|
const selectedTools = allow.split(",").filter((name) => name && !excludes.has(name));
|
|
3380
|
+
const inheritedTrusted = resume ? new Set(resume.recipe.optionalTrustedTools ?? []) : undefined;
|
|
3381
|
+
const optionalTrustedTools = taskTools?.trusted.filter(({ name }) => selectedTools.includes(name)
|
|
3382
|
+
&& (inheritedTrusted ? inheritedTrusted.has(name) : requestedTools === undefined)).map(({ name }) => name) ?? [];
|
|
3209
3383
|
const dropped = toolSelection?.dropped ?? [];
|
|
3210
3384
|
const taskRuntime = sandboxEnabled && requestedSandboxDir ? prepareTaskRuntime({
|
|
3385
|
+
worktreeGitDir: isolated?.mode === "worktree" ? inspectGitWorkspace(cwd).gitDir : undefined,
|
|
3211
3386
|
root: requestedSandboxDir, controlDir: join(runDir(id), "control"),
|
|
3212
3387
|
tools: selectedTools,
|
|
3213
|
-
permissions:
|
|
3388
|
+
permissions: taskPermissions && { ...taskPermissions, ...commandSettings },
|
|
3214
3389
|
applyPatch: taskTools?.applyPatch === true,
|
|
3215
|
-
extensionTools: taskTools?.trusted.map(({ loadPath: _loadPath, ...tool }) => tool) ?? [],
|
|
3390
|
+
extensionTools: taskTools?.trusted.map(({ loadPath: _loadPath, ...tool }) => ({ ...tool, root: workerPath(tool.root) })) ?? [],
|
|
3216
3391
|
// The sandboxed child's policy enables the guarded operation bridge
|
|
3217
3392
|
// only when the fixed bridge adapter path is among its extension
|
|
3218
3393
|
// paths; the task guard then admits those tools by exact source.
|
|
3219
3394
|
extensionPaths: [
|
|
3220
3395
|
...extArgs.flatMap((arg, index) => arg === "--extension" && extArgs[index + 1] ? [extArgs[index + 1]!] : []),
|
|
3221
|
-
...(bridgeEnabled ? [childBridgeExtensionPath(selfDir())] : []),
|
|
3396
|
+
...(bridgeEnabled ? [workerPath(childBridgeExtensionPath(selfDir()))] : []),
|
|
3222
3397
|
],
|
|
3398
|
+
operationBridgePath: workerPath(childBridgeExtensionPath(selfDir())),
|
|
3223
3399
|
runtimeRoots: [baseDir()],
|
|
3224
3400
|
capturedDenyWrite: internal?.resumeWait
|
|
3225
3401
|
? (resume?.prior.operations?.policy.sandbox as WorkerSandboxAuthority | null)?.denyWrite
|
|
3226
|
-
:
|
|
3402
|
+
: handoffAuthority?.sandbox?.denyWrite,
|
|
3227
3403
|
}) : undefined;
|
|
3404
|
+
if (taskRuntime?.policy.worktreeGitDir) {
|
|
3405
|
+
const policy = taskRuntime.policy;
|
|
3406
|
+
const notice = worktreePolicyNotice(policy.worktreeGitDir!, compileWritePolicy({
|
|
3407
|
+
writableRoot: policy.root, home: policy.home, permissions: policy.permissions,
|
|
3408
|
+
denyWrite: policy.denyWrite, runtimeCompatibility: true, runtimeWrite: [policy.scratch],
|
|
3409
|
+
}));
|
|
3410
|
+
if (notice) {
|
|
3411
|
+
workspaceNote += " " + notice;
|
|
3412
|
+
args[args.length - 1] = workspaceNote + "\n\n" + p.prompt;
|
|
3413
|
+
writeFileSync(promptPathFor(id), args[args.length - 1]!);
|
|
3414
|
+
}
|
|
3415
|
+
}
|
|
3228
3416
|
launchScratch = taskRuntime?.policy.scratch;
|
|
3229
3417
|
if (sandboxEnabled && !taskRuntime) throw new Error("Task sandbox has no workspace; refusing an unconfined child.");
|
|
3230
3418
|
// Parent-authored trust record, written before the child can run (#325).
|
|
@@ -3240,9 +3428,10 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3240
3428
|
try { ctx.ui?.notify?.(`Subagent ${id}: recovery snapshot failed (run continues): ${outcome.detail}`, "warning"); } catch { /* ignore */ }
|
|
3241
3429
|
});
|
|
3242
3430
|
}
|
|
3243
|
-
const
|
|
3431
|
+
const currentCommand = taskRuntime ? { file: taskRuntime.file, fileArgs: [...taskRuntime.fileArgs, ...args] }
|
|
3244
3432
|
: managed ? managed.workerCommand(args)
|
|
3245
3433
|
: { file: process.execPath, fileArgs: [join(selfDir(), "child-runtime.mjs"), resolvePiBinary(), ...args] };
|
|
3434
|
+
const cmd = continuationRuntime?.command(currentCommand) ?? currentCommand;
|
|
3246
3435
|
const sandboxDir = taskRuntime ? requestedSandboxDir : undefined;
|
|
3247
3436
|
|
|
3248
3437
|
// Reservations prevent competing admissions, but do not grandfather
|
|
@@ -3252,21 +3441,11 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3252
3441
|
if (countRunning() >= maxConcurrent) {
|
|
3253
3442
|
throw new Error(`Max concurrent subagents (${maxConcurrent}) reached. Stop or let some finish first.`);
|
|
3254
3443
|
}
|
|
3255
|
-
//
|
|
3256
|
-
// and finalization. A live duplicate continuation is refused instead of
|
|
3257
|
-
// letting two processes rewrite one session file. A fresh launch has a
|
|
3258
|
-
// brand-new native session id, so it cannot contend with anyone and
|
|
3259
|
-
// needs no lease; every continuation does.
|
|
3260
|
-
if (resume || managed) {
|
|
3261
|
-
lease = acquireConversationLease({ sessionId, attemptId: id });
|
|
3262
|
-
}
|
|
3263
|
-
// The lease is the first moment no other process can retire this
|
|
3264
|
-
// conversation: re-prove the history identity the cached plan was
|
|
3265
|
-
// built from, so `--session` can never reopen a file another sweep
|
|
3266
|
-
// removed as an empty replacement.
|
|
3444
|
+
// Recheck the saved conversation after asynchronous launch preparation.
|
|
3267
3445
|
if (resume) revalidateContinuationUnderLease(resume, callbackOrigin);
|
|
3268
3446
|
const preflightPath = join(runDir(id), "child-preflight.json");
|
|
3269
3447
|
writeFileSync(preflightPath, JSON.stringify({ ...fullResolution, model, tools: selectedTools,
|
|
3448
|
+
optionalTrustedTools,
|
|
3270
3449
|
configSnapshot: configSnapshot([dirname(configPath()), join(cwd, ".pi")]),
|
|
3271
3450
|
}));
|
|
3272
3451
|
// Register the worker's bridge run before the child can start, so the
|
|
@@ -3336,23 +3515,29 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3336
3515
|
// cannot hide inside a final asynchronous window.
|
|
3337
3516
|
if (internal?.resumeWait && !resume?.prior.assignment) throw new PreSpawnResumeError("This legacy park has no verified assignment outcome recipient; refusing continuation on an unsupported binding.");
|
|
3338
3517
|
if (!assignment && bridgeEnabled) throw new Error("Durable assignment outcomes require a recorded parent session and transcript capability.");
|
|
3339
|
-
|
|
3340
|
-
|
|
3341
|
-
|
|
3518
|
+
const workspaceAuthority = {
|
|
3519
|
+
mandatoryPermissions: permissionPlan.enforced,
|
|
3520
|
+
sandbox: taskRuntime ? {
|
|
3342
3521
|
root: taskRuntime.policy.root,
|
|
3343
|
-
|
|
3344
|
-
|
|
3345
|
-
} : null
|
|
3346
|
-
|
|
3522
|
+
permissions: taskRuntime.policy.permissions,
|
|
3523
|
+
denyWrite: [...taskRuntime.policy.denyWrite],
|
|
3524
|
+
} : null,
|
|
3525
|
+
};
|
|
3526
|
+
if (internal?.resumeWait) {
|
|
3527
|
+
assertAssignmentPermissionScope(resume?.prior.operations?.policy, workspaceAuthority, Boolean(managed));
|
|
3347
3528
|
}
|
|
3348
3529
|
// Freeze the ordinary recipe before the durable external-launch intent.
|
|
3349
3530
|
const recipe = buildLaunchRecipe({
|
|
3531
|
+
...(!legacyToolLoading ? { toolLoadingVersion: 1 as const } : {}),
|
|
3532
|
+
...(isolated ? { workspace: isolated, workspaceAuthority } : {}),
|
|
3350
3533
|
attemptId: id, sessionId, sessionDir: childSessionDir, cwd, model, effort: thinking,
|
|
3351
3534
|
tools: callerLaunchTools(allow), excludeTools: requestedExcludes.size ? [...requestedExcludes].join(",") : undefined,
|
|
3535
|
+
...(optionalTrustedTools.length ? { optionalTrustedTools } : {}),
|
|
3352
3536
|
skills: skills.mode === "inherit" ? undefined : [...skills.paths], clean, allowNested, approve,
|
|
3353
3537
|
sandbox: sandboxEnabled, sandboxDir: requestedSandboxDir, gitCloneWorkspace, callback: callbackEnabled, name: launchName,
|
|
3354
3538
|
agent: resume ? resume.recipe.agent : p.agent, role: resume ? resume.recipe.role : p.role,
|
|
3355
3539
|
alias: resume ? resume.recipe.alias : p.alias, catalog: launchCatalog, extensionArgs: extArgs, baseExtensionArgs,
|
|
3540
|
+
runtimeRoot: continuationRuntime?.root ?? managedRuntimeRoot(selfDir()),
|
|
3356
3541
|
trustedExtensions: resume?.recipe.trustedExtensions ?? taskTools?.trusted.map(({ name, package: owner, loadPath }) => ({ name, package: owner, loadPath })),
|
|
3357
3542
|
});
|
|
3358
3543
|
const startedAt = Date.now();
|
|
@@ -3408,6 +3593,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3408
3593
|
timing: resolveRunTiming({ params: launchTimingParams(p), settings: timingSettingsFor(cfg), env: process.env, startedAt }),
|
|
3409
3594
|
};
|
|
3410
3595
|
const dispatchGuard = await internal?.beforeSpawn?.({ runId: id, permissionPlan });
|
|
3596
|
+
if (isolated) markWorkspaceWriter(isolated,id);
|
|
3411
3597
|
const managedEnv = managed?.beforeSpawn({ id, sessionId, lease: lease!.token, leasePath: lease!.path,
|
|
3412
3598
|
preflightPath, policyPath: taskRuntime?.policyPath, permissions: permissionPlan, recipe, recoveryMeta: meta });
|
|
3413
3599
|
spawned = releaseChild(dispatchGuard, () => spawnDetached({ file: cmd.file, fileArgs: cmd.fileArgs, cwd, logPath: logPathFor(id),
|
|
@@ -3437,14 +3623,15 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3437
3623
|
// Register exit supervision before any fallible post-spawn publication.
|
|
3438
3624
|
// A failed metadata write must not strand a running child without a close
|
|
3439
3625
|
// handler; the lease stays held until that child has actually exited.
|
|
3440
|
-
|
|
3441
|
-
|
|
3442
|
-
|
|
3626
|
+
const exitCompletion = completeOwnedExit(spawned.exit,
|
|
3627
|
+
code => finalizeRun(pi, ctx, id, code),
|
|
3628
|
+
() => { lease?.release(); }, async () => {
|
|
3443
3629
|
if (workerBridge) workerOperations.release(id, "attempt-exited");
|
|
3444
3630
|
// Reconcile this attempt's earlier published writer before its
|
|
3445
3631
|
// next park can admit another continuation of the conversation.
|
|
3446
|
-
await settleResumedAttemptExit({
|
|
3632
|
+
if (internal?.resumeWait && resume) await settleResumedAttemptExit({
|
|
3447
3633
|
attemptId: id,
|
|
3634
|
+
priorPark: { runId: resume.prior.id, ...internal.resumeWait },
|
|
3448
3635
|
service: workerOperations.service,
|
|
3449
3636
|
status: readMeta(id)?.status ?? "exited",
|
|
3450
3637
|
// The exit handler releases the conversation writer lease just
|
|
@@ -3456,6 +3643,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3456
3643
|
});
|
|
3457
3644
|
await settleParkedExit(id);
|
|
3458
3645
|
});
|
|
3646
|
+
managed?.observeExit?.(id, exitCompletion);
|
|
3459
3647
|
writeMeta(meta);
|
|
3460
3648
|
committed = true;
|
|
3461
3649
|
// `meta.json` is now the record of this run; the claim has served its
|
|
@@ -3477,7 +3665,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3477
3665
|
: resolution.specs.length
|
|
3478
3666
|
? `Runtime: isolated · extensions ${resolution.specs.join(", ")}\n`
|
|
3479
3667
|
: `Runtime: isolated · built-in tools only\n`;
|
|
3480
|
-
const warn = (dropped.length ? `Task sandbox: ${dropped.map((tool) => `${tool.name} disabled (${withheldBridgeReasons.get(tool.name) ?? tool.reason})`).join("; ")}.\n` : "") +
|
|
3668
|
+
const warn = (workspaceNote ? workspaceNote + "\n" : "") + (dropped.length ? `Task sandbox: ${dropped.map((tool) => `${tool.name} disabled (${withheldBridgeReasons.get(tool.name) ?? tool.reason})`).join("; ")}.\n` : "") +
|
|
3481
3669
|
(!sandboxEnabled && resolution.unmapped.length
|
|
3482
3670
|
? `NOTE: no extension mapped for ${resolution.unmapped.join(", ")} — ` +
|
|
3483
3671
|
`${resolution.unmapped.length > 1 ? "these tools" : "this tool"} will NOT exist in the child. ` +
|
|
@@ -3486,7 +3674,9 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3486
3674
|
const modelNote = catalogDefaultNote(resume ? undefined : p.catalog, model, thinking);
|
|
3487
3675
|
// The resolved skill exposure rides with the runtime summary, which every
|
|
3488
3676
|
// launch and continuation message already prints.
|
|
3489
|
-
|
|
3677
|
+
const inventoryNote = taskRuntime?.policy.permissions?.processAccess === "read" &&
|
|
3678
|
+
!taskRuntime.policy.tools.includes("process_list") ? " process_list is not in this launch's tool loadout." : "";
|
|
3679
|
+
return { id, meta, spawned, runtime: `${runtime}${processPolicy}${inventoryNote}\n${describeSkillExposure(skills)}\n${meta.timing ? `${formatTimingLimits(meta.timing, startedAt)}\n` : ""}`, warn, sandboxDir, modelNote };
|
|
3490
3680
|
} catch (error) {
|
|
3491
3681
|
// A launch that never committed metadata is not a run: drop
|
|
3492
3682
|
// everything the attempt created so the registry keeps no
|
|
@@ -3497,10 +3687,12 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3497
3687
|
// must not keep running unsupervised; its log goes with the
|
|
3498
3688
|
// attempt, because a record without metadata can never be read.
|
|
3499
3689
|
if (!committed) {
|
|
3690
|
+
const { abortUncommittedLaunch } = await import("./launch-abort.ts");
|
|
3500
3691
|
await abortUncommittedLaunch(id, {
|
|
3501
3692
|
child: spawned, lease,
|
|
3502
|
-
artifacts: { sessionDir: childSessionDir, workspaceDir: ownedCloneWorkspace, scratch: launchScratch },
|
|
3693
|
+
artifacts: { sessionDir: childSessionDir, workspaceDir: isolated ? undefined : ownedCloneWorkspace, scratch: launchScratch },
|
|
3503
3694
|
});
|
|
3695
|
+
if (createdWorkspace && isolated) discardWorkspace(isolated);
|
|
3504
3696
|
}
|
|
3505
3697
|
throw error;
|
|
3506
3698
|
}
|
|
@@ -3568,7 +3760,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3568
3760
|
id: prior.id,
|
|
3569
3761
|
prior,
|
|
3570
3762
|
origin: { cwd: input.park.record.ownerWorkspace ?? prior.callbackOrigin?.cwd ?? prior.cwd, sessionId: input.park.record.ownerSessionId ?? prior.callbackOrigin?.sessionId },
|
|
3571
|
-
others: listMetas(),
|
|
3763
|
+
others: listMetas({ includeArchived: false }),
|
|
3572
3764
|
});
|
|
3573
3765
|
} catch (error) {
|
|
3574
3766
|
throw new PreSpawnResumeError(error instanceof Error ? error.message : String(error));
|
|
@@ -3619,7 +3811,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3619
3811
|
admissionRevision: input.admissionRevision,
|
|
3620
3812
|
permissionsUnchanged: () => samePermissionPlan(
|
|
3621
3813
|
permissionPlan,
|
|
3622
|
-
resolveSubagentPermissions(pi, target.recipe.sandbox),
|
|
3814
|
+
resolveSubagentPermissions(pi, undefined, { runId: target.prior.id, sandbox: target.recipe.sandbox }),
|
|
3623
3815
|
),
|
|
3624
3816
|
capacityAvailable: () => resumeCapacity().recheck(),
|
|
3625
3817
|
}),
|
|
@@ -3656,7 +3848,10 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3656
3848
|
};
|
|
3657
3849
|
return JSON.stringify(sort(value));
|
|
3658
3850
|
};
|
|
3659
|
-
|
|
3851
|
+
// Describe provenance to the caller, but fence on authority, not its display label.
|
|
3852
|
+
const { activationSource: _leftSource, ...leftAuthority } = left;
|
|
3853
|
+
const { activationSource: _rightSource, ...rightAuthority } = right;
|
|
3854
|
+
return canonical(leftAuthority) === canonical(rightAuthority);
|
|
3660
3855
|
}
|
|
3661
3856
|
|
|
3662
3857
|
/** Preserve the original assignment deadline across parking; never extend it. */
|
|
@@ -3718,11 +3913,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3718
3913
|
service.registerContinuationAdapter(orchestration.adapter);
|
|
3719
3914
|
} catch { /* a host that refuses the adapter leaves parking unavailable */ }
|
|
3720
3915
|
try {
|
|
3721
|
-
const reconciliation =
|
|
3722
|
-
resume: (park) => orchestration.resume(park),
|
|
3723
|
-
notifyWhen: (meta) => Boolean(activeCallbackOrigin && belongsToOrigin(meta, activeCallbackOrigin)),
|
|
3724
|
-
notify: notifyOwnedWait,
|
|
3725
|
-
});
|
|
3916
|
+
const reconciliation = reconcileWorkerWaits();
|
|
3726
3917
|
if (managed) {
|
|
3727
3918
|
void reconciliation.catch(() => undefined);
|
|
3728
3919
|
return;
|
|
@@ -3735,6 +3926,17 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3735
3926
|
} catch { /* reconciliation retries on the next session start */ }
|
|
3736
3927
|
}
|
|
3737
3928
|
|
|
3929
|
+
async function reconcileWorkerWaits(): Promise<void> {
|
|
3930
|
+
const service = workerOperations.service;
|
|
3931
|
+
if (!service) return;
|
|
3932
|
+
const orchestration = ensureResumeOrchestration();
|
|
3933
|
+
await reconcileParkedWaits(service, {
|
|
3934
|
+
resume: (park) => orchestration.resume(park),
|
|
3935
|
+
notifyWhen: (meta) => Boolean(activeCallbackOrigin && belongsToOrigin(meta, activeCallbackOrigin)),
|
|
3936
|
+
notify: notifyOwnedWait,
|
|
3937
|
+
});
|
|
3938
|
+
}
|
|
3939
|
+
|
|
3738
3940
|
// ---- subagent_spawn -------------------------------------------------
|
|
3739
3941
|
//
|
|
3740
3942
|
// One tool launches both fresh work and a continuation of saved work. A
|
|
@@ -3762,7 +3964,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3762
3964
|
...CATALOG_GUIDELINES,
|
|
3763
3965
|
"Subagent sandboxing defaults to off. Human settings in /sandbox control file, credential-file, command, and network permissions; sandbox:false cannot override an enabled human profile. Set sandbox:true to request kernel confinement, including without published settings. Set callback:false to finish quietly — then read the result on demand via subagent_result.",
|
|
3764
3966
|
"Every launch automatically joins one shared harness-owned watcher, including batch launches; it stops when the last active run ends. Do not start a separate heartbeat or background watcher for subagents. A tool call still open for tool_wait_minutes (default 5) or no progress for stuck_minutes (default 10) sends one factual alert; these alerts never stop, cancel, or restart the run. Hard timeouts default to 60 minutes; max_minutes overrides that default (0 disables). Soft deadlines remain opt-in for work with a real wall-clock bound: deadline_minutes steers the child to wrap up and later stops it after grace_minutes, while max_minutes stops it without grace. Do not set elapsed-time limits merely because a task may take a while; use them only when the work needs a real wall-clock bound.",
|
|
3765
|
-
"
|
|
3967
|
+
"Git writers receive separate checkouts by default. /subagents settings selects Clone or Worktree. isolation:false selects the live checkout. A sandboxed Worktree can return its files or explicitly continue in a verified Clone with recover_in_clone:true.",
|
|
3766
3968
|
"Saved conversations persist automatically. To continue a completed or stopped worker in its own history, call subagent_spawn with session_id (the native session id reported for the saved conversation) and the new feedback as prompt. Omit session_id for a brand-new conversation.",
|
|
3767
3969
|
"On a continuation, pass prompt, session_id, and only optional model, thinking, callback, or timing overrides. Launch-only options (name, agent, role, alias, tools, exclude_tools, skills, clean, sandbox, sandbox_dir, cwd, git_clone_workspace, approve, allow_nested) keep the saved recipe; repeat them only with the same value, otherwise the launch is refused.",
|
|
3768
3970
|
"Do not restate the original task or role when continuing: they already live in the saved conversation. A running or orphaned latest attempt blocks continuation until it stops, and missing saved history is refused rather than recreated.",
|
|
@@ -3785,6 +3987,8 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3785
3987
|
sandbox_dir: Type.Optional(Type.String({ description: "Confine writes to (and run the child in) this directory instead of the working dir. Created if missing." })),
|
|
3786
3988
|
callback: Type.Optional(Type.Boolean({ description: "Default TRUE: on completion, trigger a turn that calls subagent_result and presents the result. Set false to finish quietly — the result is then read on demand via subagent_result." })),
|
|
3787
3989
|
cwd: Type.Optional(Type.String({ description: "Working directory (default: current)." })),
|
|
3990
|
+
isolation: Type.Optional(Type.Boolean({ description: "Use false to work in the live checkout. By default each Git writer gets its own workspace." })),
|
|
3991
|
+
recover_in_clone: Type.Optional(Type.Boolean({ description: "Continue a stopped or completed linked-worktree conversation in a verified clone with the same history and permissions." })),
|
|
3788
3992
|
git_clone_workspace: Type.Optional(Type.Boolean({ description: "Prepare a disposable Git clone workspace for sandboxed Git-mutating subagents. The clone has a real .git/ directory inside the sandbox writable root and is self-contained after setup." })),
|
|
3789
3993
|
approve: Type.Optional(Type.Boolean({ description: "Trust project-local files in the child (default: false; headless runs cannot prompt for trust)." })),
|
|
3790
3994
|
allow_nested: Type.Optional(Type.Boolean({ description: "Allow the child to spawn its own subagents (default: false). Loads this extension in the child and allowlists its tools." })),
|
|
@@ -3828,6 +4032,8 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3828
4032
|
model: p.model,
|
|
3829
4033
|
thinking: p.thinking,
|
|
3830
4034
|
callback: p.callback,
|
|
4035
|
+
isolation: p.isolation,
|
|
4036
|
+
recover_in_clone: p.recover_in_clone,
|
|
3831
4037
|
deadline_minutes: p.deadline_minutes,
|
|
3832
4038
|
grace_minutes: p.grace_minutes,
|
|
3833
4039
|
max_minutes: p.max_minutes,
|
|
@@ -3955,6 +4161,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3955
4161
|
callback: Type.Optional(Type.Boolean({ description: "Default TRUE: post result back on completion." })),
|
|
3956
4162
|
clean: Type.Optional(Type.Boolean({ description: "Hermetic builtins-only child; no extensions load." })),
|
|
3957
4163
|
cwd: Type.Optional(Type.String({ description: "Working directory (default: current)." })),
|
|
4164
|
+
isolation: Type.Optional(Type.Boolean({ description: "Use false to work in the live checkout. By default each Git writer gets its own workspace." })),
|
|
3958
4165
|
git_clone_workspace: Type.Optional(Type.Boolean({ description: "Prepare a disposable Git clone workspace for each job (same semantics as subagent_spawn)." })),
|
|
3959
4166
|
approve: Type.Optional(Type.Boolean({ description: "Trust project-local files in children." })),
|
|
3960
4167
|
allow_nested: Type.Optional(Type.Boolean({ description: "Allow children to spawn their own subagents." })),
|
|
@@ -3978,6 +4185,8 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
3978
4185
|
callback: Type.Optional(Type.Boolean()),
|
|
3979
4186
|
clean: Type.Optional(Type.Boolean()),
|
|
3980
4187
|
cwd: Type.Optional(Type.String()),
|
|
4188
|
+
isolation: Type.Optional(Type.Boolean({ description: "Use false to work in the live checkout. By default each Git writer gets its own workspace." })),
|
|
4189
|
+
recover_in_clone: Type.Optional(Type.Boolean({ description: "Continue this job in a verified Clone." })),
|
|
3981
4190
|
git_clone_workspace: Type.Optional(Type.Boolean()),
|
|
3982
4191
|
approve: Type.Optional(Type.Boolean()),
|
|
3983
4192
|
allow_nested: Type.Optional(Type.Boolean()),
|
|
@@ -4020,8 +4229,10 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
4020
4229
|
|
|
4021
4230
|
let catalogSnapshot: CatalogSnapshot | undefined;
|
|
4022
4231
|
let catalogHost: CatalogHost | undefined;
|
|
4023
|
-
const needsCatalog = p.jobs.some((job) =>
|
|
4024
|
-
|
|
4232
|
+
const needsCatalog = p.jobs.some((job) => {
|
|
4233
|
+
const merged = mergeJobOptions(p.shared, job);
|
|
4234
|
+
return merged.session_id === undefined && merged.session_name === undefined && hasCatalogSelector(merged);
|
|
4235
|
+
});
|
|
4025
4236
|
if (needsCatalog) {
|
|
4026
4237
|
catalogHost = catalogHostFrom(ctx);
|
|
4027
4238
|
noteCatalogHost(catalogHost);
|
|
@@ -4083,7 +4294,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
4083
4294
|
const job = p.jobs[i];
|
|
4084
4295
|
let name = names[i];
|
|
4085
4296
|
const merged = mergeJobOptions(p.shared, job);
|
|
4086
|
-
const isContinuation =
|
|
4297
|
+
const isContinuation = merged.session_id !== undefined || merged.session_name !== undefined;
|
|
4087
4298
|
// A continuation keeps its own frozen model and effort. shared.model
|
|
4088
4299
|
// is a default for NEW conversations, so only a per-job value is an
|
|
4089
4300
|
// explicit escalation of the saved recipe.
|
|
@@ -4101,7 +4312,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
4101
4312
|
}
|
|
4102
4313
|
|
|
4103
4314
|
try {
|
|
4104
|
-
const sessionId = requestedSessionId(
|
|
4315
|
+
const sessionId = requestedSessionId(merged, ctx.cwd);
|
|
4105
4316
|
// A saved conversation is never re-resolved against the catalog.
|
|
4106
4317
|
if (sessionId === undefined && catalogSnapshot && catalogHost && hasCatalogSelector(merged)) {
|
|
4107
4318
|
const explicitName = typeof job.name === "string" && job.name.trim() !== "" ? job.name : undefined;
|
|
@@ -4278,6 +4489,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
4278
4489
|
const timing = timingState();
|
|
4279
4490
|
return {
|
|
4280
4491
|
mode: settings.delegationMode, maxConcurrent: settings.maxConcurrent,
|
|
4492
|
+
gitWorkspace: activeWorkspace(),
|
|
4281
4493
|
maxMinutes: timing.maxMinutes,
|
|
4282
4494
|
modeSource: settings.sources.delegationMode,
|
|
4283
4495
|
capSource: settings.sources.maxConcurrent,
|
|
@@ -4293,7 +4505,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
4293
4505
|
skillsError: skills.error,
|
|
4294
4506
|
};
|
|
4295
4507
|
},
|
|
4296
|
-
changeMode, changeCap, changeTiming, changeSkills, save: saveSettings, reset: resetSettings,
|
|
4508
|
+
changeMode, changeWorkspace, changeCap, changeTiming, changeSkills, save: saveSettings, reset: resetSettings,
|
|
4297
4509
|
discoverSkills: () => discoveredSkillsFromContext(ctx),
|
|
4298
4510
|
// Close this page first; the catalog opens after ui.custom resolves.
|
|
4299
4511
|
openAgents: () => done("agents"),
|
|
@@ -4305,7 +4517,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
4305
4517
|
: skills.mode === "none" ? "no skills" : `${skills.paths.length} selected skills`;
|
|
4306
4518
|
const timing = timingState();
|
|
4307
4519
|
ctx.ui.notify(`Delegation mode: ${activeDelegationMode()}. Concurrent subagents: ${activeConcurrencyCap()}. ` +
|
|
4308
|
-
`
|
|
4520
|
+
`Run timeout: ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "No limit"}. Tool-wait alert: ${timing.toolWaitMinutes} min. ` +
|
|
4309
4521
|
`No-progress alert: ${timing.stuckMinutes} min. Skills: ${skillChoice}. ` +
|
|
4310
4522
|
`Use /subagents mode <mode>, cap <number>, tool-wait <minutes>, stuck <minutes>, or settings; /subagents save persists them.`, "info");
|
|
4311
4523
|
}
|
|
@@ -4316,6 +4528,28 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
4316
4528
|
pi.events?.emit("harness-settings:register", contribution);
|
|
4317
4529
|
pi.events?.emit("harness-settings:register", agentsContribution);
|
|
4318
4530
|
};
|
|
4531
|
+
const unsubscribeToolLoading = pi.events?.on?.("pi-better-subagents:default-tool-loading", (request: unknown) => {
|
|
4532
|
+
const query = request as { reply?: (rows: { name: string; provider: string }[]) => void } | undefined;
|
|
4533
|
+
if (typeof query?.reply !== "function") return;
|
|
4534
|
+
const config = ordinaryChildConfig(loadConfig(), activeChildProviders(pi));
|
|
4535
|
+
const names = normalizeTools(config.defaultTools ?? SAFE_DEFAULT_TOOLS).split(",").filter(Boolean);
|
|
4536
|
+
addEditablePatch(names, new Set());
|
|
4537
|
+
const rows = [...new Set(names)].map(name => {
|
|
4538
|
+
if (name === "codemode") {
|
|
4539
|
+
const supported = "createCodemodeExtension" in PiCodingAgent && typeof PiCodingAgent.createCodemodeExtension === "function";
|
|
4540
|
+
return { name, provider: supported ? "Harness" : "SDK unavailable" };
|
|
4541
|
+
}
|
|
4542
|
+
if (BUILTIN_TOOLS.includes(name)) return { name, provider: "Pi" };
|
|
4543
|
+
const spec = config.toolExtensions?.[name];
|
|
4544
|
+
const sources = typeof spec === "string" ? [spec] : spec ?? [];
|
|
4545
|
+
const providers = sources.map(source => {
|
|
4546
|
+
const label = source === ORDINARY_TOOL_PROVIDERS[name] ? "Harness" : source;
|
|
4547
|
+
return resolveExtensionPath(source) ? label : `${label} (missing)`;
|
|
4548
|
+
});
|
|
4549
|
+
return { name, provider: providers.join(", ") || (config.inheritExtensions ? "Session extensions" : "No provider mapped") };
|
|
4550
|
+
});
|
|
4551
|
+
query.reply(rows);
|
|
4552
|
+
});
|
|
4319
4553
|
const unsubscribeSettingsRequest = pi.events?.on?.("harness-settings:request", registerSettings);
|
|
4320
4554
|
const unsubscribeOutcomeWorkflow = pi.events?.on?.("pi-better-workflow:changed", () => recoverAssignmentOutcomes(pi));
|
|
4321
4555
|
registerSettings();
|
|
@@ -4369,7 +4603,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
4369
4603
|
const timing = timingState();
|
|
4370
4604
|
if (ctx.hasUI && !(await ctx.ui.confirm("Save subagent defaults?",
|
|
4371
4605
|
`Future sessions will start in ${activeDelegationMode()} with a cap of ${activeConcurrencyCap()}, ` +
|
|
4372
|
-
`timeout ${timing.maxMinutes
|
|
4606
|
+
`run timeout ${timing.maxMinutes ? timing.maxMinutes + " minutes" : "No limit"}, tool-wait alert ${timing.toolWaitMinutes} min, ` +
|
|
4373
4607
|
`no-progress alert ${timing.stuckMinutes} min, and ${skillChoice}.`))) {
|
|
4374
4608
|
ctx.ui.notify("Subagent defaults unchanged.", "info");
|
|
4375
4609
|
return;
|
|
@@ -4475,7 +4709,14 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
4475
4709
|
// Capture a UI-bearing context and, if runs from a prior session are still
|
|
4476
4710
|
// alive, resume the ticking widget. Deferred out of the factory per pi's
|
|
4477
4711
|
// "no background resources at load" rule.
|
|
4478
|
-
|
|
4712
|
+
let restoreObservation: NodeJS.Immediate | undefined;
|
|
4713
|
+
let offFirstAssignment: (() => void) | undefined;
|
|
4714
|
+
const cancelDeferredObservation = () => {
|
|
4715
|
+
if (restoreObservation) clearImmediate(restoreObservation);
|
|
4716
|
+
offFirstAssignment?.();
|
|
4717
|
+
offFirstAssignment = undefined;
|
|
4718
|
+
};
|
|
4719
|
+
pi.on("session_start", async (event, ctx) => {
|
|
4479
4720
|
// A session begins in this process again (reload, restart, or a session
|
|
4480
4721
|
// switch), so the previous session's teardown no longer applies: the
|
|
4481
4722
|
// replacing session owns this instance's supervision loops (#625).
|
|
@@ -4493,10 +4734,28 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
4493
4734
|
activeCallbackOrigin = callbackOriginFromContext(ctx);
|
|
4494
4735
|
pendingRecipientRecovery.clear();
|
|
4495
4736
|
observedRecipientRows.clear();
|
|
4496
|
-
|
|
4497
|
-
|
|
4498
|
-
|
|
4499
|
-
|
|
4737
|
+
cancelDeferredObservation();
|
|
4738
|
+
if (!managed && activeCallbackOrigin) {
|
|
4739
|
+
configureWorkObservation(PiCodingAgent.getAgentDir(), activeCallbackOrigin, () => {
|
|
4740
|
+
refreshBackgroundWorkNavigator(ctx);
|
|
4741
|
+
observeRecipientNotifications(pi);
|
|
4742
|
+
});
|
|
4743
|
+
if (!event?.reason) {
|
|
4744
|
+
// Older hosts use completion of their untyped start callback as the readiness signal.
|
|
4745
|
+
await activateWorkObservation();
|
|
4746
|
+
} else if (shouldRestoreWorkObservation(event, ctx.sessionManager)) {
|
|
4747
|
+
restoreObservation = setImmediate(() => { void activateWorkObservation(); });
|
|
4748
|
+
} else {
|
|
4749
|
+
// Another extension can assign work to this recipient before it calls a tool.
|
|
4750
|
+
const origin = activeCallbackOrigin;
|
|
4751
|
+
offFirstAssignment = onMetaChanged(meta => {
|
|
4752
|
+
if (!meta || !belongsToOrigin(meta, origin)) return;
|
|
4753
|
+
offFirstAssignment?.();
|
|
4754
|
+
offFirstAssignment = undefined;
|
|
4755
|
+
void activateWorkObservation();
|
|
4756
|
+
});
|
|
4757
|
+
}
|
|
4758
|
+
}
|
|
4500
4759
|
if (!managed) {
|
|
4501
4760
|
recoverCompletionCallbacks(pi);
|
|
4502
4761
|
observeRecipientNotifications(pi);
|
|
@@ -4546,6 +4805,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
4546
4805
|
});
|
|
4547
4806
|
|
|
4548
4807
|
pi.on("session_before_switch", () => {
|
|
4808
|
+
cancelDeferredObservation();
|
|
4549
4809
|
closeCatalogHost();
|
|
4550
4810
|
agentSessionSettings.clear();
|
|
4551
4811
|
catalogModelRegistry = undefined;
|
|
@@ -4561,6 +4821,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
4561
4821
|
// Tear down the timer and clear the widget when the session ends.
|
|
4562
4822
|
pi.on("session_shutdown", async (event, ctx) => {
|
|
4563
4823
|
closeCatalogHost();
|
|
4824
|
+
cancelDeferredObservation();
|
|
4564
4825
|
stopWorkObservation();
|
|
4565
4826
|
pendingNavigatorDismissals.clear();
|
|
4566
4827
|
if (outcomeTicker) clearInterval(outcomeTicker);
|
|
@@ -4568,6 +4829,7 @@ export default function (pi: ExtensionAPI, managed?: import("./managed-launch-po
|
|
|
4568
4829
|
outcomeAdmission.clear();
|
|
4569
4830
|
closeOutcomeHost(outcomeHost);
|
|
4570
4831
|
if (typeof unsubscribeOutcomeWorkflow === "function") unsubscribeOutcomeWorkflow();
|
|
4832
|
+
if (typeof unsubscribeToolLoading === "function") unsubscribeToolLoading();
|
|
4571
4833
|
if (typeof unsubscribeSettingsRequest === "function") unsubscribeSettingsRequest();
|
|
4572
4834
|
// #625: subagent children are detached process groups that outlive this
|
|
4573
4835
|
// foreground session. A controlled reload or quit must not destroy
|