@caupulican/pi-adaptative 0.86.3 → 0.86.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +44 -0
- package/dist/core/agent-paths.d.ts +13 -0
- package/dist/core/agent-paths.d.ts.map +1 -1
- package/dist/core/agent-paths.js +23 -0
- package/dist/core/agent-paths.js.map +1 -1
- package/dist/core/autonomy/bounded-completion.d.ts +7 -0
- package/dist/core/autonomy/bounded-completion.d.ts.map +1 -1
- package/dist/core/autonomy/bounded-completion.js +12 -4
- package/dist/core/autonomy/bounded-completion.js.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.d.ts +2 -0
- package/dist/core/autonomy/lane-tool-surface.d.ts.map +1 -1
- package/dist/core/autonomy/lane-tool-surface.js +6 -3
- package/dist/core/autonomy/lane-tool-surface.js.map +1 -1
- package/dist/core/autonomy/subagent-prompt.js +1 -1
- package/dist/core/autonomy/subagent-prompt.js.map +1 -1
- package/dist/core/background-lane-controller.d.ts +25 -2
- package/dist/core/background-lane-controller.d.ts.map +1 -1
- package/dist/core/background-lane-controller.js +67 -0
- package/dist/core/background-lane-controller.js.map +1 -1
- package/dist/core/delegation/replay-safe-mailbox-bounds.d.ts +4 -0
- package/dist/core/delegation/replay-safe-mailbox-bounds.d.ts.map +1 -0
- package/dist/core/delegation/replay-safe-mailbox-bounds.js +20 -0
- package/dist/core/delegation/replay-safe-mailbox-bounds.js.map +1 -0
- package/dist/core/delegation/sanitized-context-fork.d.ts +25 -0
- package/dist/core/delegation/sanitized-context-fork.d.ts.map +1 -0
- package/dist/core/delegation/sanitized-context-fork.js +299 -0
- package/dist/core/delegation/sanitized-context-fork.js.map +1 -0
- package/dist/core/delegation/session-root-mailbox.d.ts +75 -0
- package/dist/core/delegation/session-root-mailbox.d.ts.map +1 -0
- package/dist/core/delegation/session-root-mailbox.js +627 -0
- package/dist/core/delegation/session-root-mailbox.js.map +1 -0
- package/dist/core/delegation/worker-agent-control-coordinator.d.ts +102 -9
- package/dist/core/delegation/worker-agent-control-coordinator.d.ts.map +1 -1
- package/dist/core/delegation/worker-agent-control-coordinator.js +1307 -125
- package/dist/core/delegation/worker-agent-control-coordinator.js.map +1 -1
- package/dist/core/delegation/worker-agent-control.d.ts +183 -8
- package/dist/core/delegation/worker-agent-control.d.ts.map +1 -1
- package/dist/core/delegation/worker-agent-control.js +778 -48
- package/dist/core/delegation/worker-agent-control.js.map +1 -1
- package/dist/core/delegation/worker-attempt-executor.d.ts +9 -0
- package/dist/core/delegation/worker-attempt-executor.d.ts.map +1 -1
- package/dist/core/delegation/worker-attempt-executor.js +479 -214
- package/dist/core/delegation/worker-attempt-executor.js.map +1 -1
- package/dist/core/delegation/worker-authority-resolver.d.ts +9 -0
- package/dist/core/delegation/worker-authority-resolver.d.ts.map +1 -1
- package/dist/core/delegation/worker-authority-resolver.js +21 -2
- package/dist/core/delegation/worker-authority-resolver.js.map +1 -1
- package/dist/core/delegation/worker-context-fork-store.d.ts +71 -0
- package/dist/core/delegation/worker-context-fork-store.d.ts.map +1 -0
- package/dist/core/delegation/worker-context-fork-store.js +437 -0
- package/dist/core/delegation/worker-context-fork-store.js.map +1 -0
- package/dist/core/delegation/worker-context-inheritance-policy.d.ts +18 -0
- package/dist/core/delegation/worker-context-inheritance-policy.d.ts.map +1 -0
- package/dist/core/delegation/worker-context-inheritance-policy.js +28 -0
- package/dist/core/delegation/worker-context-inheritance-policy.js.map +1 -0
- package/dist/core/delegation/worker-conversation-revision.d.ts +31 -0
- package/dist/core/delegation/worker-conversation-revision.d.ts.map +1 -0
- package/dist/core/delegation/worker-conversation-revision.js +203 -0
- package/dist/core/delegation/worker-conversation-revision.js.map +1 -0
- package/dist/core/delegation/worker-conversation-store.d.ts +130 -18
- package/dist/core/delegation/worker-conversation-store.d.ts.map +1 -1
- package/dist/core/delegation/worker-conversation-store.js +1263 -79
- package/dist/core/delegation/worker-conversation-store.js.map +1 -1
- package/dist/core/delegation/worker-delegation-controller.d.ts +30 -2
- package/dist/core/delegation/worker-delegation-controller.d.ts.map +1 -1
- package/dist/core/delegation/worker-delegation-controller.js +675 -111
- package/dist/core/delegation/worker-delegation-controller.js.map +1 -1
- package/dist/core/delegation/worker-delegation-request.d.ts +2 -0
- package/dist/core/delegation/worker-delegation-request.d.ts.map +1 -1
- package/dist/core/delegation/worker-delegation-request.js.map +1 -1
- package/dist/core/delegation/worker-dispatch-scheduler.d.ts +20 -1
- package/dist/core/delegation/worker-dispatch-scheduler.d.ts.map +1 -1
- package/dist/core/delegation/worker-dispatch-scheduler.js +210 -37
- package/dist/core/delegation/worker-dispatch-scheduler.js.map +1 -1
- package/dist/core/delegation/worker-execution-policy.d.ts.map +1 -1
- package/dist/core/delegation/worker-execution-policy.js +14 -2
- package/dist/core/delegation/worker-execution-policy.js.map +1 -1
- package/dist/core/delegation/worker-fleet-limits.d.ts +38 -0
- package/dist/core/delegation/worker-fleet-limits.d.ts.map +1 -0
- package/dist/core/delegation/worker-fleet-limits.js +113 -0
- package/dist/core/delegation/worker-fleet-limits.js.map +1 -0
- package/dist/core/delegation/worker-lane-projection.d.ts +1 -0
- package/dist/core/delegation/worker-lane-projection.d.ts.map +1 -1
- package/dist/core/delegation/worker-lane-projection.js +6 -2
- package/dist/core/delegation/worker-lane-projection.js.map +1 -1
- package/dist/core/delegation/worker-lifecycle.d.ts +20 -3
- package/dist/core/delegation/worker-lifecycle.d.ts.map +1 -1
- package/dist/core/delegation/worker-lifecycle.js +42 -18
- package/dist/core/delegation/worker-lifecycle.js.map +1 -1
- package/dist/core/delegation/worker-notification-coordinator.d.ts +4 -0
- package/dist/core/delegation/worker-notification-coordinator.d.ts.map +1 -1
- package/dist/core/delegation/worker-notification-coordinator.js +45 -4
- package/dist/core/delegation/worker-notification-coordinator.js.map +1 -1
- package/dist/core/delegation/worker-provider-turn-protocol.d.ts +50 -0
- package/dist/core/delegation/worker-provider-turn-protocol.d.ts.map +1 -0
- package/dist/core/delegation/worker-provider-turn-protocol.js +185 -0
- package/dist/core/delegation/worker-provider-turn-protocol.js.map +1 -0
- package/dist/core/delegation/worker-recovery-coordinator.d.ts +45 -4
- package/dist/core/delegation/worker-recovery-coordinator.d.ts.map +1 -1
- package/dist/core/delegation/worker-recovery-coordinator.js +223 -17
- package/dist/core/delegation/worker-recovery-coordinator.js.map +1 -1
- package/dist/core/delegation/worker-retry-policy.d.ts +36 -0
- package/dist/core/delegation/worker-retry-policy.d.ts.map +1 -0
- package/dist/core/delegation/worker-retry-policy.js +41 -0
- package/dist/core/delegation/worker-retry-policy.js.map +1 -0
- package/dist/core/delegation/worker-runner.d.ts +3 -1
- package/dist/core/delegation/worker-runner.d.ts.map +1 -1
- package/dist/core/delegation/worker-runner.js +4 -2
- package/dist/core/delegation/worker-runner.js.map +1 -1
- package/dist/core/delegation/worker-task-view.d.ts +43 -0
- package/dist/core/delegation/worker-task-view.d.ts.map +1 -0
- package/dist/core/delegation/worker-task-view.js +194 -0
- package/dist/core/delegation/worker-task-view.js.map +1 -0
- package/dist/core/delegation/worker-terminal-handoff-coordinator.d.ts +55 -0
- package/dist/core/delegation/worker-terminal-handoff-coordinator.d.ts.map +1 -0
- package/dist/core/delegation/worker-terminal-handoff-coordinator.js +179 -0
- package/dist/core/delegation/worker-terminal-handoff-coordinator.js.map +1 -0
- package/dist/core/delegation/worker-tree-budget-coordinator.d.ts +2 -2
- package/dist/core/delegation/worker-tree-budget-coordinator.d.ts.map +1 -1
- package/dist/core/delegation/worker-tree-budget-coordinator.js +12 -46
- package/dist/core/delegation/worker-tree-budget-coordinator.js.map +1 -1
- package/dist/core/goals/goal-continuation-controller.d.ts.map +1 -1
- package/dist/core/goals/goal-continuation-controller.js +15 -0
- package/dist/core/goals/goal-continuation-controller.js.map +1 -1
- package/dist/core/goals/goal-state.d.ts +6 -0
- package/dist/core/goals/goal-state.d.ts.map +1 -1
- package/dist/core/goals/goal-state.js +1 -0
- package/dist/core/goals/goal-state.js.map +1 -1
- package/dist/core/goals/goal-tool-core.d.ts +1 -0
- package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
- package/dist/core/goals/goal-tool-core.js +25 -3
- package/dist/core/goals/goal-tool-core.js.map +1 -1
- package/dist/core/keybindings.d.ts +10 -0
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +2 -0
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/orchestration/attempt-ordering.d.ts +9 -0
- package/dist/core/orchestration/attempt-ordering.d.ts.map +1 -0
- package/dist/core/orchestration/attempt-ordering.js +29 -0
- package/dist/core/orchestration/attempt-ordering.js.map +1 -0
- package/dist/core/orchestration/capability-gateway.d.ts +19 -0
- package/dist/core/orchestration/capability-gateway.d.ts.map +1 -1
- package/dist/core/orchestration/capability-gateway.js +19 -2
- package/dist/core/orchestration/capability-gateway.js.map +1 -1
- package/dist/core/orchestration/contracts.d.ts +43 -3
- package/dist/core/orchestration/contracts.d.ts.map +1 -1
- package/dist/core/orchestration/contracts.js +24 -0
- package/dist/core/orchestration/contracts.js.map +1 -1
- package/dist/core/orchestration/delegation-ledger.d.ts +8 -3
- package/dist/core/orchestration/delegation-ledger.d.ts.map +1 -1
- package/dist/core/orchestration/delegation-ledger.js +148 -55
- package/dist/core/orchestration/delegation-ledger.js.map +1 -1
- package/dist/core/orchestration/event-store.d.ts +6 -3
- package/dist/core/orchestration/event-store.d.ts.map +1 -1
- package/dist/core/orchestration/event-store.js +228 -30
- package/dist/core/orchestration/event-store.js.map +1 -1
- package/dist/core/orchestration/task-runtime-codecs.d.ts +31 -0
- package/dist/core/orchestration/task-runtime-codecs.d.ts.map +1 -0
- package/dist/core/orchestration/task-runtime-codecs.js +1471 -0
- package/dist/core/orchestration/task-runtime-codecs.js.map +1 -0
- package/dist/core/orchestration/task-runtime-projection.d.ts +30 -0
- package/dist/core/orchestration/task-runtime-projection.d.ts.map +1 -0
- package/dist/core/orchestration/task-runtime-projection.js +340 -0
- package/dist/core/orchestration/task-runtime-projection.js.map +1 -0
- package/dist/core/orchestration/task-runtime-reducer.d.ts +38 -0
- package/dist/core/orchestration/task-runtime-reducer.d.ts.map +1 -0
- package/dist/core/orchestration/task-runtime-reducer.js +1270 -0
- package/dist/core/orchestration/task-runtime-reducer.js.map +1 -0
- package/dist/core/orchestration/task-runtime-state.d.ts +142 -0
- package/dist/core/orchestration/task-runtime-state.d.ts.map +1 -0
- package/dist/core/orchestration/task-runtime-state.js +14 -0
- package/dist/core/orchestration/task-runtime-state.js.map +1 -0
- package/dist/core/orchestration/task-runtime.d.ts +44 -98
- package/dist/core/orchestration/task-runtime.d.ts.map +1 -1
- package/dist/core/orchestration/task-runtime.js +357 -1113
- package/dist/core/orchestration/task-runtime.js.map +1 -1
- package/dist/core/orchestration/worker-context-fork-reference.d.ts +20 -0
- package/dist/core/orchestration/worker-context-fork-reference.d.ts.map +1 -0
- package/dist/core/orchestration/worker-context-fork-reference.js +53 -0
- package/dist/core/orchestration/worker-context-fork-reference.js.map +1 -0
- package/dist/core/orchestration/worker-execution-contract.d.ts.map +1 -1
- package/dist/core/orchestration/worker-execution-contract.js +4 -2
- package/dist/core/orchestration/worker-execution-contract.js.map +1 -1
- package/dist/core/research/research-runner.d.ts +2 -0
- package/dist/core/research/research-runner.d.ts.map +1 -1
- package/dist/core/research/research-runner.js +1 -0
- package/dist/core/research/research-runner.js.map +1 -1
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +8 -0
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/secrets/credential-project.d.ts.map +1 -1
- package/dist/core/secrets/credential-project.js +24 -2
- package/dist/core/secrets/credential-project.js.map +1 -1
- package/dist/core/security/secret-text.d.ts +3 -0
- package/dist/core/security/secret-text.d.ts.map +1 -1
- package/dist/core/security/secret-text.js +15 -0
- package/dist/core/security/secret-text.js.map +1 -1
- package/dist/core/settings-manager.d.ts +3 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +160 -8
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/tools/delegate.d.ts +33 -15
- package/dist/core/tools/delegate.d.ts.map +1 -1
- package/dist/core/tools/delegate.js +763 -115
- package/dist/core/tools/delegate.js.map +1 -1
- package/dist/core/tools/goal.d.ts +1 -0
- package/dist/core/tools/goal.d.ts.map +1 -1
- package/dist/core/tools/goal.js +9 -1
- package/dist/core/tools/goal.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +1 -0
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/activity-lane.d.ts +5 -0
- package/dist/modes/interactive/components/activity-lane.d.ts.map +1 -1
- package/dist/modes/interactive/components/activity-lane.js +133 -49
- package/dist/modes/interactive/components/activity-lane.js.map +1 -1
- package/dist/modes/interactive/components/agents-overlay.d.ts +40 -0
- package/dist/modes/interactive/components/agents-overlay.d.ts.map +1 -0
- package/dist/modes/interactive/components/agents-overlay.js +153 -0
- package/dist/modes/interactive/components/agents-overlay.js.map +1 -0
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +18 -13
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/interactive-event-controller.d.ts +1 -1
- package/dist/modes/interactive/interactive-event-controller.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-event-controller.js +6 -3
- package/dist/modes/interactive/interactive-event-controller.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +5 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +51 -0
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/key-handlers.d.ts +1 -0
- package/dist/modes/interactive/key-handlers.d.ts.map +1 -1
- package/dist/modes/interactive/key-handlers.js +1 -0
- package/dist/modes/interactive/key-handlers.js.map +1 -1
- package/docs/harness-architecture.md +61 -17
- package/docs/settings.md +17 -9
- package/docs/worker-profiles.md +6 -2
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-recovery-coordinator.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-recovery-coordinator.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,qBAAqB,EAAE,MAAM,mCAAmC,CAAC;AAsB1E;;;;GAIG;AACH,MAAM,OAAO,yBAAyB;IAMrC,YAAY,OAAyC;QAJ7C,mBAAc,GAAG,KAAK,CAAC;QACvB,2BAAsB,GAAG,KAAK,CAAC;QACtB,iCAA4B,GAAG,IAAI,GAAG,EAAkB,CAAC;QAGzE,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACxB,CAAC;IAED,6FAA6F;IAC7F,OAAO;QACN,IAAI,IAAI,CAAC,sBAAsB;YAAE,OAAO;QACxC,IAAI,CAAC,sBAAsB,GAAG,IAAI,CAAC;QACnC,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,GAAG,IAAI,CAAC,OAAO,CAAC;QAC9C,IAAI,CAAC;YACJ,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC;gBAC1B,MAAM,mBAAmB,GAAG,IAAI,GAAG,CAAC,SAAS,CAAC,uCAAuC,EAAE,CAAC,CAAC;gBACzF,IAAI,CAAC;oBACJ,IAAI,CAAC,OAAO,CAAC,wBAAwB,EAAE,CAAC;gBACzC,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBAChB,IAAI,CAAC,OAAO,CAAC,IAAI,CAChB,oDAAoD,KAAK,YA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,CAAC,QAAQ,EAAE,IAAI,CAClD,CAAC;YACH,CAAC,CAAC,CAAC;QACJ,OAAO,CACN,KAAK,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,QAAQ,EAAE,EAAE,CAAC,YAAY,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YAClE,KAAK,CAAC,YAAY,CAAC,KAAK,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,mBAAmB,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;YAC7E,wBAAwB;YACxB,qBAAqB,CAAC,KAAK,CAAC,SAAS,EAAE,IAAI,CAAC,SAAS,CAAC;YACtD,qBAAqB,CAAC,KAAK,CAAC,UAAU,EAAE,IAAI,CAAC,UAAU,CAAC;YACxD,yBAAyB;YACzB,sBAAsB,CACtB,CAAC;IACH,CAAC;CACD","sourcesContent":["import type { Message, Usage } from \"@caupulican/pi-ai\";\nimport type { LaneRecord } from \"../autonomy/lane-tracker.ts\";\nimport { isPathWithinScope } from \"../autonomy/path-scope.ts\";\nimport { reconcileAttemptUsage } from \"../orchestration/attempt-usage.ts\";\nimport type { AttemptUsageSnapshot, ExecutionGrant, ResourcePointer, RiskBudget } from \"../orchestration/contracts.ts\";\nimport type { AttemptRuntimeState } from \"../orchestration/task-runtime.ts\";\nimport type { WorkerConversation } from \"./worker-conversation-store.ts\";\nimport type { WorkerDelegationRequest } from \"./worker-delegation-request.ts\";\nimport type { WorkerDispatchScheduler } from \"./worker-dispatch-scheduler.ts\";\nimport type { WorkerExecutionPlan } from \"./worker-execution-policy.ts\";\nimport type { PendingVerificationRecovery, WorkerLifecycle } from \"./worker-lifecycle.ts\";\n\nexport type WorkerRecoveryDispatchResult = { started: true } | { started: false; skipReason: string };\n\nexport interface WorkerRecoveryCoordinatorOptions {\n\tlifecycle: WorkerLifecycle;\n\tscheduler: Pick<WorkerDispatchScheduler, \"enqueue\">;\n\trecoverWriteReservations(): void;\n\tpublishTerminalRecord(record: LaneRecord): void;\n\tdispatchVerification(\n\t\trecovery: Extract<PendingVerificationRecovery, { action: \"dispatch\" }>,\n\t): WorkerRecoveryDispatchResult;\n\twarn(message: string): void;\n}\n\n/**\n * Owns restart-only worker state repair. It has no provider or tool execution authority: it\n * reconstructs bounded durable requests, requeues them through the owner scheduler, and supplies\n * the execution layer with narrow transcript/usage/grant recovery decisions.\n */\nexport class WorkerRecoveryCoordinator {\n\tprivate readonly options: WorkerRecoveryCoordinatorOptions;\n\tprivate queueRecovered = false;\n\tprivate recoveringDurableState = false;\n\tprivate readonly verificationRecoveryFailures = new Map<string, string>();\n\n\tconstructor(options: WorkerRecoveryCoordinatorOptions) {\n\t\tthis.options = options;\n\t}\n\n\t/** Idempotently rebuild in-process queue state and replay only durable terminal handoffs. */\n\trecover(): void {\n\t\tif (this.recoveringDurableState) return;\n\t\tthis.recoveringDurableState = true;\n\t\tconst { lifecycle, scheduler } = this.options;\n\t\ttry {\n\t\t\tif (!this.queueRecovered) {\n\t\t\t\tconst suspendedAttemptIds = new Set(lifecycle.suspendBoundInProcessAttemptsForRestart());\n\t\t\t\ttry {\n\t\t\t\t\tthis.options.recoverWriteReservations();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.options.warn(\n\t\t\t\t\t\t`Worker write reservation recovery failed closed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst queued = lifecycle.recoverQueued();\n\t\t\t\tconst snapshot = lifecycle.getTaskRuntimeSnapshot();\n\t\t\t\tfor (const attemptId of suspendedAttemptIds) {\n\t\t\t\t\tconst attempt = snapshot.attempts[attemptId];\n\t\t\t\t\tif (!attempt || attempt.dispatch.executionKind === \"managed-process\") continue;\n\t\t\t\t\tconst record = lifecycle.getRecord(attempt.taskId);\n\t\t\t\t\tconst task = snapshot.tasks[attempt.taskId]?.task;\n\t\t\t\t\tif (!record || !task) continue;\n\t\t\t\t\tqueued.push({\n\t\t\t\t\t\trecord,\n\t\t\t\t\t\tattempt,\n\t\t\t\t\t\t...(task.verificationOfTaskId ? { verificationOfTaskId: task.verificationOfTaskId } : {}),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tfor (const { attempt, record, verificationOfTaskId } of queued) {\n\t\t\t\t\tscheduler.enqueue(\n\t\t\t\t\t\trecord,\n\t\t\t\t\t\tthis.recoveredRequest(attempt, verificationOfTaskId),\n\t\t\t\t\t\ttrue,\n\t\t\t\t\t\tverificationOfTaskId !== undefined,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tthis.queueRecovered = true;\n\t\t\t}\n\n\t\t\tfor (const recovery of lifecycle.getPendingVerificationRecoveries()) {\n\t\t\t\tif (recovery.action === \"reconcile\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.options.publishTerminalRecord(lifecycle.reconcileVerification(recovery));\n\t\t\t\t\t\tthis.verificationRecoveryFailures.delete(recovery.subjectTaskId);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tthis.options.warn(\n\t\t\t\t\t\t\t`Failed to reconcile recovered verification for ${recovery.subjectTaskId}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst started = this.options.dispatchVerification(recovery);\n\t\t\t\tif (started.started) {\n\t\t\t\t\tthis.verificationRecoveryFailures.delete(recovery.subjectTaskId);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (this.verificationRecoveryFailures.get(recovery.subjectTaskId) === started.skipReason) continue;\n\t\t\t\tthis.verificationRecoveryFailures.set(recovery.subjectTaskId, started.skipReason);\n\t\t\t\tthis.options.warn(\n\t\t\t\t\t`Recovered verification for ${recovery.subjectTaskId} did not start: ${started.skipReason}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tfor (const notification of lifecycle.getPendingTerminalNotifications()) {\n\t\t\t\tthis.options.publishTerminalRecord(notification.record);\n\t\t\t}\n\t\t} finally {\n\t\t\tthis.recoveringDurableState = false;\n\t\t}\n\t}\n\n\t/** Rebuild task metadata from its durable dispatch; no current profile/model selection is consulted. */\n\trecoveredRequest(attempt: AttemptRuntimeState, verificationOfTaskId?: string): WorkerDelegationRequest {\n\t\tconst task = this.options.lifecycle.getTask(attempt.taskId)?.task;\n\t\treturn {\n\t\t\tinstructions: attempt.dispatch.instructions,\n\t\t\tprofileId: attempt.dispatch.profileId,\n\t\t\t...(attempt.dispatch.parentAgentId ? { parentAgentId: attempt.dispatch.parentAgentId } : {}),\n\t\t\t...(verificationOfTaskId ? { verificationOfTaskId } : {}),\n\t\t\t...(task\n\t\t\t\t? {\n\t\t\t\t\t\ttaskContext: {\n\t\t\t\t\t\t\trequirementIds: attempt.dispatch.requirementIds ?? [],\n\t\t\t\t\t\t\tdependsOnTaskIds: task.dependsOn,\n\t\t\t\t\t\t\tacceptanceCriterionIds: task.acceptanceCriterionIds,\n\t\t\t\t\t\t\tresourcePointerIds: attempt.dispatch.resourcePointerIds,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t};\n\t}\n\n\t/** Append deterministic unknown outcomes only for tool calls not durably followed by a result. */\n\trepairInterruptedToolResults(conversation: WorkerConversation): void {\n\t\tconst messages = conversation.getProviderMessages();\n\t\tconst completedToolCallIds = new Set<string>();\n\t\tlet index = messages.length - 1;\n\t\twhile (index >= 0 && messages[index]?.role === \"toolResult\") {\n\t\t\tcompletedToolCallIds.add((messages[index] as Extract<Message, { role: \"toolResult\" }>).toolCallId);\n\t\t\tindex -= 1;\n\t\t}\n\t\tconst assistant = messages[index];\n\t\tif (!assistant || assistant.role !== \"assistant\") return;\n\t\tfor (const content of assistant.content) {\n\t\t\tif (content.type !== \"toolCall\" || completedToolCallIds.has(content.id)) continue;\n\t\t\tconversation.appendMessage({\n\t\t\t\trole: \"toolResult\",\n\t\t\t\ttoolCallId: content.id,\n\t\t\t\ttoolName: content.name,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Execution outcome is unknown because this worker was interrupted before a durable tool result was recorded. Inspect the workspace and prior evidence before deciding whether to retry this operation.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tisError: true,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t});\n\t\t}\n\t}\n\n\t/** Return an already-persisted final assistant response so recovery cannot duplicate provider work. */\n\trecoveredTerminalCompletion(\n\t\tconversation: WorkerConversation,\n\t): { text: string; usage: Usage; stopReason: string } | undefined {\n\t\tconst last = conversation.getProviderMessages().at(-1);\n\t\tif (!last || last.role !== \"assistant\" || last.stopReason === \"error\" || last.stopReason === \"aborted\") {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (last.content.some((content) => content.type === \"toolCall\")) return undefined;\n\t\tconst text = last.content\n\t\t\t.filter(\n\t\t\t\t(content): content is Extract<(typeof last.content)[number], { type: \"text\" }> => content.type === \"text\",\n\t\t\t)\n\t\t\t.map((content) => content.text)\n\t\t\t.join(\"\");\n\t\treturn text ? { text, usage: last.usage, stopReason: last.stopReason } : undefined;\n\t}\n\n\t/** Legacy raw transcripts predate durable usage checkpoints; reconstruct their bounded cumulative baseline. */\n\tinitialUsage(\n\t\tconversation: WorkerConversation,\n\t\tcheckpointUsage: AttemptUsageSnapshot | undefined,\n\t): AttemptUsageSnapshot {\n\t\tconst transcriptUsage = conversation.getRawTranscriptUsage();\n\t\treturn checkpointUsage ? reconcileAttemptUsage(checkpointUsage, transcriptUsage) : transcriptUsage;\n\t}\n\n\t/** Fail closed when the current owner profile no longer permits a persisted grant. */\n\tdurableGrantIsStillPermitted(\n\t\tgrant: ExecutionGrant,\n\t\tplan: WorkerExecutionPlan,\n\t\tselectedResources: readonly ResourcePointer[],\n\t): boolean {\n\t\tconst allowedTools = new Set(plan.toolManifests.map((manifest) => manifest.toolName));\n\t\tconst allowedCapabilities = new Set(plan.requiredCapabilities);\n\t\tconst scopesRemainPermitted = (granted: readonly string[], permitted: readonly string[]) =>\n\t\t\tgranted.every((scope) => permitted.some((candidate) => isPathWithinScope(scope, candidate)));\n\t\tconst liveDenialsRemainEnforced = plan.deniedPaths.every((denied) =>\n\t\t\tgrant.deniedPaths.some((granted) => isPathWithinScope(denied, granted)),\n\t\t);\n\t\tconst budgetRemainsPermitted = (Object.keys(plan.budget) as Array<keyof RiskBudget>).every((field) => {\n\t\t\tconst current = plan.budget[field];\n\t\t\tconst persisted = grant.budget[field];\n\t\t\treturn current === undefined || (persisted !== undefined && persisted <= current);\n\t\t});\n\t\tconst resourcesRemainPermitted =\n\t\t\tgrant.resources.length === selectedResources.length &&\n\t\t\tgrant.resources.every((granted, index) => {\n\t\t\t\tconst selected = selectedResources[index];\n\t\t\t\treturn (\n\t\t\t\t\tselected !== undefined &&\n\t\t\t\t\tgranted.id === selected.id &&\n\t\t\t\t\tgranted.kind === selected.kind &&\n\t\t\t\t\tgranted.uri === selected.uri &&\n\t\t\t\t\tgranted.readOnly === selected.readOnly &&\n\t\t\t\t\ttypeof granted.digest === \"string\" &&\n\t\t\t\t\t(selected.digest === undefined || selected.digest === granted.digest) &&\n\t\t\t\t\tgranted.metadata?.name === selected.metadata?.name\n\t\t\t\t);\n\t\t\t});\n\t\treturn (\n\t\t\tgrant.allowedTools.every((toolName) => allowedTools.has(toolName)) &&\n\t\t\tgrant.capabilities.every((capability) => allowedCapabilities.has(capability)) &&\n\t\t\tresourcesRemainPermitted &&\n\t\t\tscopesRemainPermitted(grant.readPaths, plan.readPaths) &&\n\t\t\tscopesRemainPermitted(grant.writePaths, plan.writePaths) &&\n\t\t\tliveDenialsRemainEnforced &&\n\t\t\tbudgetRemainsPermitted\n\t\t);\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"worker-recovery-coordinator.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-recovery-coordinator.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,iBAAiB,EAAE,MAAM,2BAA2B,CAAC;AAC9D,OAAO,EAAE,q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\";\nimport { isPathWithinScope } from \"../autonomy/path-scope.ts\";\nimport { reconcileAttemptUsage } from \"../orchestration/attempt-usage.ts\";\nimport type { AttemptUsageSnapshot, ExecutionGrant, ResourcePointer, RiskBudget } from \"../orchestration/contracts.ts\";\nimport type { AttemptRuntimeState } from \"../orchestration/task-runtime.ts\";\nimport type { WorkerConversation } from \"./worker-conversation-store.ts\";\nimport type { WorkerDelegationRequest } from \"./worker-delegation-request.ts\";\nimport type { WorkerDispatchScheduler } from \"./worker-dispatch-scheduler.ts\";\nimport type { WorkerExecutionPlan } from \"./worker-execution-policy.ts\";\nimport type { PendingVerificationRecovery, WorkerLifecycle } from \"./worker-lifecycle.ts\";\nimport { evaluateWorkerRetry } from \"./worker-retry-policy.ts\";\n\nexport type WorkerRecoveryDispatchResult = { started: true } | { started: false; skipReason: string };\n\nexport type WorkerRetryScheduleResult =\n\t| { scheduled: true; record: LaneRecord; retriesUsed: number; notBefore: string }\n\t| { scheduled: false; reason: string };\n\ninterface PendingRetryDispatch {\n\tlaneId: string;\n\tnotBefore: string;\n\trequest: WorkerDelegationRequest;\n\tpriority: boolean;\n\ttimer?: ReturnType<typeof setTimeout>;\n}\n\nexport interface WorkerRecoveryCoordinatorOptions {\n\tlifecycle: WorkerLifecycle;\n\tscheduler: Pick<WorkerDispatchScheduler, \"enqueue\"> &\n\t\tPartial<Pick<WorkerDispatchScheduler, \"onQueueCapacityAvailable\">>;\n\trecoverWriteReservations(): void;\n\tpublishTerminalRecord(record: LaneRecord): void;\n\tpublishTerminalRecords?(records: readonly LaneRecord[]): void;\n\tdispatchVerification(\n\t\trecovery: Extract<PendingVerificationRecovery, { action: \"dispatch\" }>,\n\t): WorkerRecoveryDispatchResult;\n\trecoverTaskBearingMailboxTurns(): void;\n\trecoverSessionRootReplies(): void;\n\t/** Wake the scheduler and UI after a retained retry deadline becomes eligible. */\n\tretryReady?(): void;\n\tnow?(): number;\n\twarn(message: string): void;\n}\n\nfunction restartResumableSuspension(\n\tattempt: AttemptRuntimeState,\n\tnewlySuspendedAttemptIds: ReadonlySet<string>,\n): boolean {\n\treturn (\n\t\tnewlySuspendedAttemptIds.has(attempt.attemptId) ||\n\t\tattempt.reasonCode === \"agent_process_recovered_after_owner_exit\" ||\n\t\tattempt.reasonCode === \"agent_process_interrupted\" ||\n\t\tattempt.reasonCode?.startsWith(\"retry_scheduled:\") === true\n\t);\n}\n\n/**\n * Owns restart-only worker state repair. It has no provider or tool execution authority: it\n * reconstructs bounded durable requests, requeues them through the owner scheduler, and supplies\n * the execution layer with narrow transcript/usage/grant recovery decisions.\n */\nexport class WorkerRecoveryCoordinator {\n\tprivate readonly options: WorkerRecoveryCoordinatorOptions;\n\tprivate queueRecovered = false;\n\tprivate recoveringDurableState = false;\n\tprivate readonly verificationRecoveryFailures = new Map<string, string>();\n\tprivate readonly retryTimers = new Map<string, PendingRetryDispatch>();\n\tprivate readonly unsubscribeQueueCapacity: (() => void) | undefined;\n\n\tconstructor(options: WorkerRecoveryCoordinatorOptions) {\n\t\tthis.options = options;\n\t\tthis.unsubscribeQueueCapacity = options.scheduler.onQueueCapacityAvailable?.(() => {\n\t\t\tthis.flushDueRetries();\n\t\t\t// Mandatory verifier dispatches remain derivable from durable subject state even after the\n\t\t\t// ordinary queue was fully recovered. Every released slot must replay that retained demand.\n\t\t\tthis.recover();\n\t\t});\n\t}\n\n\t/** Idempotently rebuild in-process queues, terminal outboxes, and task-bearing mailboxes. */\n\trecover(): void {\n\t\tif (this.recoveringDurableState) return;\n\t\tthis.recoveringDurableState = true;\n\t\tconst { lifecycle } = this.options;\n\t\ttry {\n\t\t\tif (!this.queueRecovered) {\n\t\t\t\tconst newlySuspendedAttemptIds = new Set(lifecycle.suspendBoundInProcessAttemptsForRestart());\n\t\t\t\ttry {\n\t\t\t\t\tthis.options.recoverWriteReservations();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.options.warn(\n\t\t\t\t\t\t`Worker write reservation recovery failed closed: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tconst queued = lifecycle.recoverQueued();\n\t\t\t\tconst snapshot = lifecycle.getTaskRuntimeSnapshot();\n\t\t\t\tfor (const attempt of Object.values(snapshot.attempts)) {\n\t\t\t\t\tif (\n\t\t\t\t\t\tattempt.status !== \"suspended\" ||\n\t\t\t\t\t\t!attempt.agentId ||\n\t\t\t\t\t\tattempt.dispatch.executionKind === \"managed-process\" ||\n\t\t\t\t\t\t!restartResumableSuspension(attempt, newlySuspendedAttemptIds)\n\t\t\t\t\t) {\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tconst record = lifecycle.getRecord(attempt.taskId);\n\t\t\t\t\tconst task = snapshot.tasks[attempt.taskId]?.task;\n\t\t\t\t\tif (!record || !task) continue;\n\t\t\t\t\tqueued.push({\n\t\t\t\t\t\trecord,\n\t\t\t\t\t\tattempt,\n\t\t\t\t\t\t...(task.verificationOfTaskId ? { verificationOfTaskId: task.verificationOfTaskId } : {}),\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tlet recoveredAll = true;\n\t\t\t\tfor (const { attempt, record, verificationOfTaskId } of queued) {\n\t\t\t\t\tlet retained: boolean;\n\t\t\t\t\ttry {\n\t\t\t\t\t\tretained = this.enqueueOrDeferRetry(\n\t\t\t\t\t\t\trecord,\n\t\t\t\t\t\t\tattempt,\n\t\t\t\t\t\t\tthis.recoveredRequest(attempt, verificationOfTaskId),\n\t\t\t\t\t\t\tverificationOfTaskId !== undefined,\n\t\t\t\t\t\t);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\trecoveredAll = false;\n\t\t\t\t\t\tthis.options.warn(\n\t\t\t\t\t\t\t`Failed to recover queued worker ${record.laneId}; retaining durable dispatch: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\t}\n\t\t\t\t\tif (retained) continue;\n\t\t\t\t\trecoveredAll = false;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tthis.queueRecovered = recoveredAll;\n\t\t\t}\n\n\t\t\tfor (const recovery of lifecycle.getPendingVerificationRecoveries()) {\n\t\t\t\tif (recovery.action === \"reconcile\") {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tthis.options.publishTerminalRecord(lifecycle.reconcileVerification(recovery));\n\t\t\t\t\t\tthis.verificationRecoveryFailures.delete(recovery.subjectTaskId);\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\tthis.options.warn(\n\t\t\t\t\t\t\t`Failed to reconcile recovered verification for ${recovery.subjectTaskId}: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tlet started: WorkerRecoveryDispatchResult;\n\t\t\t\ttry {\n\t\t\t\t\tstarted = this.options.dispatchVerification(recovery);\n\t\t\t\t} catch (error) {\n\t\t\t\t\tconst reason = error instanceof Error ? error.message : String(error);\n\t\t\t\t\tconst failureKey = `dispatch_threw:${reason}`;\n\t\t\t\t\tif (this.verificationRecoveryFailures.get(recovery.subjectTaskId) !== failureKey) {\n\t\t\t\t\t\tthis.verificationRecoveryFailures.set(recovery.subjectTaskId, failureKey);\n\t\t\t\t\t\tthis.options.warn(\n\t\t\t\t\t\t\t`Recovered verification for ${recovery.subjectTaskId} threw during dispatch: ${reason}`,\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (started.started) {\n\t\t\t\t\tthis.verificationRecoveryFailures.delete(recovery.subjectTaskId);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (this.verificationRecoveryFailures.get(recovery.subjectTaskId) === started.skipReason) continue;\n\t\t\t\tthis.verificationRecoveryFailures.set(recovery.subjectTaskId, started.skipReason);\n\t\t\t\tthis.options.warn(\n\t\t\t\t\t`Recovered verification for ${recovery.subjectTaskId} did not start: ${started.skipReason}`,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst terminalRecords = lifecycle.getPendingTerminalNotifications().map((notification) => notification.record);\n\t\t\tif (terminalRecords.length > 0) {\n\t\t\t\tif (this.options.publishTerminalRecords) this.options.publishTerminalRecords(terminalRecords);\n\t\t\t\telse for (const record of terminalRecords) this.options.publishTerminalRecord(record);\n\t\t\t}\n\t\t\tthis.options.recoverSessionRootReplies();\n\t\t\tthis.options.recoverTaskBearingMailboxTurns();\n\t\t} finally {\n\t\t\tthis.recoveringDurableState = false;\n\t\t}\n\t}\n\n\t/** Evaluate, persist, and arm one retry through the same durable path used by restart recovery. */\n\tscheduleAttemptRetry(args: {\n\t\tlaneId: string;\n\t\tagentId: string;\n\t\townerId: string;\n\t\trequest: WorkerDelegationRequest;\n\t\toutcome: { laneStatus: string; reasonCode: string; reasonDetail?: string };\n\t\tprovider: string;\n\t\tmaxAttempts?: number;\n\t}): WorkerRetryScheduleResult {\n\t\tconst attempt = this.options.lifecycle.getActiveAttempt(args.laneId);\n\t\tconst record = this.options.lifecycle.getRecord(args.laneId);\n\t\tif (!attempt || !record) return { scheduled: false, reason: \"attempt_missing\" };\n\t\tconst retriesUsed = attempt.retry?.retriesUsed ?? 0;\n\t\tconst decision = evaluateWorkerRetry({\n\t\t\tlaneStatus: args.outcome.laneStatus,\n\t\t\treasonCode: args.outcome.reasonCode,\n\t\t\t...(args.outcome.reasonDetail ? { reasonDetail: args.outcome.reasonDetail } : {}),\n\t\t\tprovider: args.provider,\n\t\t\tretriesUsed,\n\t\t\t...(args.maxAttempts !== undefined ? { maxAttempts: args.maxAttempts } : {}),\n\t\t});\n\t\tif (!decision.retry) return { scheduled: false, reason: decision.reason };\n\t\tconst nextRetriesUsed = retriesUsed + 1;\n\t\tconst notBefore = new Date(this.now() + decision.delayMs).toISOString();\n\t\tlet suspended: AttemptRuntimeState;\n\t\ttry {\n\t\t\tsuspended = this.options.lifecycle.scheduleAgentRetry({\n\t\t\t\tlaneId: args.laneId,\n\t\t\t\tagentId: args.agentId,\n\t\t\t\townerId: args.ownerId,\n\t\t\t\treasonCode: `retry_scheduled:${decision.reason}`,\n\t\t\t\tretry: { retriesUsed: nextRetriesUsed, notBefore },\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis.options.warn(\n\t\t\t\t`Worker ${args.laneId} retry suspension failed; terminalizing instead: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t\treturn { scheduled: false, reason: \"retry_suspension_failed\" };\n\t\t}\n\t\tthis.options.warn(\n\t\t\t`Worker ${args.laneId} failed (${decision.reason}); retrying from the persisted transcript in ${Math.ceil(decision.delayMs / 1000)}s (attempt ${nextRetriesUsed + 1}).`,\n\t\t);\n\t\tthis.enqueueOrDeferRetry(record, suspended, args.request, args.request.verificationOfTaskId !== undefined);\n\t\treturn { scheduled: true, record, retriesUsed: nextRetriesUsed, notBefore };\n\t}\n\n\t/** Cancel only process-local alarms; the retained deadline remains authoritative on disk. */\n\tdispose(): void {\n\t\tthis.unsubscribeQueueCapacity?.();\n\t\tfor (const entry of this.retryTimers.values()) {\n\t\t\tif (entry.timer) clearTimeout(entry.timer);\n\t\t}\n\t\tthis.retryTimers.clear();\n\t}\n\n\tclearScheduledRetry(laneId: string): void {\n\t\tfor (const [attemptId, entry] of this.retryTimers) {\n\t\t\tif (entry.laneId !== laneId) continue;\n\t\t\tif (entry.timer) clearTimeout(entry.timer);\n\t\t\tthis.retryTimers.delete(attemptId);\n\t\t}\n\t}\n\n\t/** Keep an externally requested wake queued while the durable retry deadline is still retained. */\n\tdeferRetryIfNeeded(record: LaneRecord, request: WorkerDelegationRequest): boolean {\n\t\tconst attempt = this.options.lifecycle.getActiveAttempt(record.laneId);\n\t\tif (\n\t\t\t!attempt ||\n\t\t\tattempt.status !== \"suspended\" ||\n\t\t\t!attempt.retry ||\n\t\t\tDate.parse(attempt.retry.notBefore) <= this.now()\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\tthis.enqueueOrDeferRetry(record, attempt, request, request.verificationOfTaskId !== undefined);\n\t\treturn true;\n\t}\n\n\tprivate enqueueOrDeferRetry(\n\t\trecord: LaneRecord,\n\t\tattempt: AttemptRuntimeState,\n\t\trequest: WorkerDelegationRequest,\n\t\tpriority: boolean,\n\t): boolean {\n\t\tconst retry = attempt.retry;\n\t\tif (!retry) {\n\t\t\ttry {\n\t\t\t\tthis.options.scheduler.enqueue(record, request, true, priority);\n\t\t\t\treturn true;\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof Error && error.message === \"worker_dispatch_queue_full\") return false;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t\tconst existing = this.retryTimers.get(attempt.attemptId);\n\t\tif (existing?.notBefore === retry.notBefore) return true;\n\t\tif (existing?.timer) clearTimeout(existing.timer);\n\t\tconst entry: PendingRetryDispatch = {\n\t\t\tlaneId: record.laneId,\n\t\t\tnotBefore: retry.notBefore,\n\t\t\trequest,\n\t\t\tpriority,\n\t\t};\n\t\tthis.retryTimers.set(attempt.attemptId, entry);\n\t\tconst remainingMs = Date.parse(retry.notBefore) - this.now();\n\t\tif (remainingMs <= 0) {\n\t\t\tthis.tryEnqueueDueRetry(attempt.attemptId, entry);\n\t\t\treturn true;\n\t\t}\n\t\tconst timer = setTimeout(() => this.onRetryTimer(attempt.attemptId), Math.min(remainingMs, 2_147_000_000));\n\t\tif (typeof timer === \"object\" && \"unref\" in timer) timer.unref();\n\t\tentry.timer = timer;\n\t\treturn true;\n\t}\n\n\tprivate onRetryTimer(attemptId: string): void {\n\t\tconst entry = this.retryTimers.get(attemptId);\n\t\tif (!entry) return;\n\t\tdelete entry.timer;\n\t\tthis.tryEnqueueDueRetry(attemptId, entry);\n\t}\n\n\tprivate tryEnqueueDueRetry(attemptId: string, entry: PendingRetryDispatch): \"enqueued\" | \"full\" | \"stale\" {\n\t\tconst attempt = this.options.lifecycle.getActiveAttempt(entry.laneId);\n\t\tif (\n\t\t\t!attempt ||\n\t\t\tattempt.attemptId !== attemptId ||\n\t\t\tattempt.status !== \"suspended\" ||\n\t\t\tattempt.retry?.notBefore !== entry.notBefore\n\t\t) {\n\t\t\tthis.retryTimers.delete(attemptId);\n\t\t\treturn \"stale\";\n\t\t}\n\t\tconst record = this.options.lifecycle.getRecord(entry.laneId);\n\t\tif (!record) {\n\t\t\tthis.retryTimers.delete(attemptId);\n\t\t\treturn \"stale\";\n\t\t}\n\t\tconst remainingMs = Date.parse(entry.notBefore) - this.now();\n\t\tif (remainingMs > 0) {\n\t\t\tconst timer = setTimeout(() => this.onRetryTimer(attemptId), Math.min(remainingMs, 2_147_000_000));\n\t\t\tif (typeof timer === \"object\" && \"unref\" in timer) timer.unref();\n\t\t\tentry.timer = timer;\n\t\t\treturn \"stale\";\n\t\t}\n\t\ttry {\n\t\t\tthis.options.scheduler.enqueue(record, entry.request, true, entry.priority);\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"worker_dispatch_queue_full\") return \"full\";\n\t\t\tthis.options.warn(\n\t\t\t\t`Worker ${entry.laneId} retry enqueue failed; retaining the durable retry: ${error instanceof Error ? error.message : String(error)}`,\n\t\t\t);\n\t\t\treturn \"full\";\n\t\t}\n\t\tthis.retryTimers.delete(attemptId);\n\t\tthis.options.retryReady?.();\n\t\treturn \"enqueued\";\n\t}\n\n\tprivate flushDueRetries(): void {\n\t\tfor (const [attemptId, entry] of this.retryTimers) {\n\t\t\tif (entry.timer || Date.parse(entry.notBefore) > this.now()) continue;\n\t\t\tif (this.tryEnqueueDueRetry(attemptId, entry) === \"full\") break;\n\t\t}\n\t}\n\n\tprivate now(): number {\n\t\treturn this.options.now?.() ?? Date.now();\n\t}\n\n\t/** Rebuild task metadata from its durable dispatch; no current profile/model selection is consulted. */\n\trecoveredRequest(attempt: AttemptRuntimeState, verificationOfTaskId?: string): WorkerDelegationRequest {\n\t\tconst task = this.options.lifecycle.getTask(attempt.taskId)?.task;\n\t\tconst durableVerificationOfTaskId = verificationOfTaskId ?? task?.verificationOfTaskId;\n\t\treturn {\n\t\t\tinstructions: attempt.dispatch.instructions,\n\t\t\tprofileId: attempt.dispatch.profileId,\n\t\t\t...(attempt.dispatch.parentAgentId ? { parentAgentId: attempt.dispatch.parentAgentId } : {}),\n\t\t\t...(durableVerificationOfTaskId ? { verificationOfTaskId: durableVerificationOfTaskId } : {}),\n\t\t\t...(task\n\t\t\t\t? {\n\t\t\t\t\t\ttaskContext: {\n\t\t\t\t\t\t\trequirementIds: attempt.dispatch.requirementIds ?? [],\n\t\t\t\t\t\t\tdependsOnTaskIds: task.dependsOn,\n\t\t\t\t\t\t\tacceptanceCriterionIds: task.acceptanceCriterionIds,\n\t\t\t\t\t\t\tresourcePointerIds: attempt.dispatch.resourcePointerIds,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t};\n\t}\n\n\t/** Append deterministic unknown outcomes only for tool calls not durably followed by a result. */\n\trepairInterruptedToolResults(conversation: WorkerConversation): void {\n\t\tconst messages = conversation.getProviderMessages();\n\t\tconst completedToolCallIds = new Set<string>();\n\t\tlet index = messages.length - 1;\n\t\twhile (index >= 0 && messages[index]?.role === \"toolResult\") {\n\t\t\tcompletedToolCallIds.add((messages[index] as Extract<Message, { role: \"toolResult\" }>).toolCallId);\n\t\t\tindex -= 1;\n\t\t}\n\t\tconst assistant = messages[index];\n\t\tif (!assistant || assistant.role !== \"assistant\") return;\n\t\tfor (const content of assistant.content) {\n\t\t\tif (content.type !== \"toolCall\" || completedToolCallIds.has(content.id)) continue;\n\t\t\tconversation.appendMessage({\n\t\t\t\trole: \"toolResult\",\n\t\t\t\ttoolCallId: content.id,\n\t\t\t\ttoolName: content.name,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Execution outcome is unknown because this worker was interrupted before a durable tool result was recorded. Inspect the workspace and prior evidence before deciding whether to retry this operation.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tisError: true,\n\t\t\t\ttimestamp: Date.now(),\n\t\t\t});\n\t\t}\n\t}\n\n\t/** Return an already-persisted final assistant response so recovery cannot duplicate provider work. */\n\trecoveredTerminalCompletion(\n\t\tconversation: WorkerConversation,\n\t\tattemptId: string,\n\t): { text: string; usage: Usage; stopReason: string } | undefined {\n\t\tconst last = conversation.getLastAttemptMessage(attemptId);\n\t\tif (!last || last.role !== \"assistant\" || last.stopReason === \"error\" || last.stopReason === \"aborted\") {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (last.content.some((content) => content.type === \"toolCall\")) return undefined;\n\t\tconst text = last.content\n\t\t\t.filter(\n\t\t\t\t(content): content is Extract<(typeof last.content)[number], { type: \"text\" }> => content.type === \"text\",\n\t\t\t)\n\t\t\t.map((content) => content.text)\n\t\t\t.join(\"\");\n\t\treturn { text, usage: last.usage, stopReason: last.stopReason };\n\t}\n\n\t/** Legacy raw transcripts predate durable usage checkpoints; reconstruct their bounded cumulative baseline. */\n\tinitialUsage(\n\t\tconversation: WorkerConversation,\n\t\tcheckpointUsage: AttemptUsageSnapshot | undefined,\n\t\tattemptId: string,\n\t): AttemptUsageSnapshot {\n\t\tconst transcriptUsage = conversation.getRawTranscriptUsage(attemptId);\n\t\treturn checkpointUsage ? reconcileAttemptUsage(checkpointUsage, transcriptUsage) : transcriptUsage;\n\t}\n\n\t/** Fail closed when the current owner profile no longer permits a persisted grant. */\n\tdurableGrantIsStillPermitted(\n\t\tgrant: ExecutionGrant,\n\t\tplan: WorkerExecutionPlan,\n\t\tselectedResources: readonly ResourcePointer[],\n\t): boolean {\n\t\tconst allowedTools = new Set(plan.toolManifests.map((manifest) => manifest.toolName));\n\t\tconst allowedCapabilities = new Set(plan.requiredCapabilities);\n\t\tconst scopesRemainPermitted = (granted: readonly string[], permitted: readonly string[]) =>\n\t\t\tgranted.every((scope) => permitted.some((candidate) => isPathWithinScope(scope, candidate)));\n\t\tconst liveDenialsRemainEnforced = plan.deniedPaths.every((denied) =>\n\t\t\tgrant.deniedPaths.some((granted) => isPathWithinScope(denied, granted)),\n\t\t);\n\t\tconst budgetRemainsPermitted = (Object.keys(plan.budget) as Array<keyof RiskBudget>).every((field) => {\n\t\t\tconst current = plan.budget[field];\n\t\t\tconst persisted = grant.budget[field];\n\t\t\treturn current === undefined || (persisted !== undefined && persisted <= current);\n\t\t});\n\t\tconst resourcesRemainPermitted =\n\t\t\tgrant.resources.length === selectedResources.length &&\n\t\t\tgrant.resources.every((granted, index) => {\n\t\t\t\tconst selected = selectedResources[index];\n\t\t\t\treturn (\n\t\t\t\t\tselected !== undefined &&\n\t\t\t\t\tgranted.id === selected.id &&\n\t\t\t\t\tgranted.kind === selected.kind &&\n\t\t\t\t\tgranted.uri === selected.uri &&\n\t\t\t\t\tgranted.readOnly === selected.readOnly &&\n\t\t\t\t\ttypeof granted.digest === \"string\" &&\n\t\t\t\t\t(selected.digest === undefined || selected.digest === granted.digest) &&\n\t\t\t\t\tgranted.metadata?.name === selected.metadata?.name\n\t\t\t\t);\n\t\t\t});\n\t\treturn (\n\t\t\tgrant.allowedTools.every((toolName) => allowedTools.has(toolName)) &&\n\t\t\tgrant.capabilities.every((capability) => allowedCapabilities.has(capability)) &&\n\t\t\tresourcesRemainPermitted &&\n\t\t\tscopesRemainPermitted(grant.readPaths, plan.readPaths) &&\n\t\t\tscopesRemainPermitted(grant.writePaths, plan.writePaths) &&\n\t\t\tliveDenialsRemainEnforced &&\n\t\t\tbudgetRemainsPermitted\n\t\t);\n\t}\n}\n"]}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { type RetryPolicy } from "@caupulican/pi-agent-core/reliability";
|
|
2
|
+
/**
|
|
3
|
+
* Restart-durable, host-owned attempt ladder policy for delegated workers.
|
|
4
|
+
*
|
|
5
|
+
* The budget model has always carried `maxAttempts`, but nothing drove a second attempt: a
|
|
6
|
+
* failed worker terminalized immediately and "retry" meant the orchestrator model burning a
|
|
7
|
+
* turn to re-delegate blind, losing the worker's transcript. The ladder makes retry a host
|
|
8
|
+
* mechanism instead: a retryable bounded failure suspends the attempt (durable, fenced) and
|
|
9
|
+
* re-enqueues it through the owner scheduler after backoff, resuming from the persisted
|
|
10
|
+
* conversation exactly like restart recovery does.
|
|
11
|
+
*
|
|
12
|
+
* Retries are deliberately evidence-gated: only failures whose recorded detail classifies as
|
|
13
|
+
* transient (network, 5xx, rate limits) are retried. A missing detail or an unknown
|
|
14
|
+
* classification never retries — an undiagnosed failure repeated is spend without evidence.
|
|
15
|
+
*/
|
|
16
|
+
export declare const DEFAULT_WORKER_TASK_ATTEMPTS = 2;
|
|
17
|
+
export declare const WORKER_TASK_RETRY_POLICY: RetryPolicy;
|
|
18
|
+
export type WorkerRetryDecision = {
|
|
19
|
+
retry: true;
|
|
20
|
+
reason: string;
|
|
21
|
+
delayMs: number;
|
|
22
|
+
} | {
|
|
23
|
+
retry: false;
|
|
24
|
+
reason: string;
|
|
25
|
+
};
|
|
26
|
+
export declare function evaluateWorkerRetry(args: {
|
|
27
|
+
laneStatus: string;
|
|
28
|
+
reasonCode: string;
|
|
29
|
+
reasonDetail?: string;
|
|
30
|
+
provider: string;
|
|
31
|
+
/** Restart-durable ladder retries already consumed for this attempt. */
|
|
32
|
+
retriesUsed: number;
|
|
33
|
+
/** Grant budget ceiling for total attempts; defaults to {@link DEFAULT_WORKER_TASK_ATTEMPTS}. */
|
|
34
|
+
maxAttempts?: number;
|
|
35
|
+
}): WorkerRetryDecision;
|
|
36
|
+
//# sourceMappingURL=worker-retry-policy.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"worker-retry-policy.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/worker-retry-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAwC,KAAK,WAAW,EAAE,MAAM,uCAAuC,CAAC;AAE/G;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,4BAA4B,IAAI,CAAC;AAE9C,eAAO,MAAM,wBAAwB,EAAE,WAKtC,CAAC;AAEF,MAAM,MAAM,mBAAmB,GAAG;IAAE,KAAK,EAAE,IAAI,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,KAAK,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAEtH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE;IACzC,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,QAAQ,EAAE,MAAM,CAAC;IACjB,wEAAwE;IACxE,WAAW,EAAE,MAAM,CAAC;IACpB,iGAAiG;IACjG,WAAW,CAAC,EAAE,MAAM,CAAC;CACrB,GAAG,mBAAmB,CAYtB"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { classifyFailure, computeRetryDelayMs } from "@caupulican/pi-agent-core/reliability";
|
|
2
|
+
/**
|
|
3
|
+
* Restart-durable, host-owned attempt ladder policy for delegated workers.
|
|
4
|
+
*
|
|
5
|
+
* The budget model has always carried `maxAttempts`, but nothing drove a second attempt: a
|
|
6
|
+
* failed worker terminalized immediately and "retry" meant the orchestrator model burning a
|
|
7
|
+
* turn to re-delegate blind, losing the worker's transcript. The ladder makes retry a host
|
|
8
|
+
* mechanism instead: a retryable bounded failure suspends the attempt (durable, fenced) and
|
|
9
|
+
* re-enqueues it through the owner scheduler after backoff, resuming from the persisted
|
|
10
|
+
* conversation exactly like restart recovery does.
|
|
11
|
+
*
|
|
12
|
+
* Retries are deliberately evidence-gated: only failures whose recorded detail classifies as
|
|
13
|
+
* transient (network, 5xx, rate limits) are retried. A missing detail or an unknown
|
|
14
|
+
* classification never retries — an undiagnosed failure repeated is spend without evidence.
|
|
15
|
+
*/
|
|
16
|
+
export const DEFAULT_WORKER_TASK_ATTEMPTS = 2;
|
|
17
|
+
export const WORKER_TASK_RETRY_POLICY = {
|
|
18
|
+
maxAttempts: DEFAULT_WORKER_TASK_ATTEMPTS,
|
|
19
|
+
baseDelayMs: 5_000,
|
|
20
|
+
maxDelayMs: 60_000,
|
|
21
|
+
jitterRatio: 0.2,
|
|
22
|
+
};
|
|
23
|
+
export function evaluateWorkerRetry(args) {
|
|
24
|
+
if (args.laneStatus !== "failed")
|
|
25
|
+
return { retry: false, reason: `lane_status_${args.laneStatus}` };
|
|
26
|
+
if (args.reasonCode !== "completion_error")
|
|
27
|
+
return { retry: false, reason: `reason_code_${args.reasonCode}` };
|
|
28
|
+
if (!args.reasonDetail)
|
|
29
|
+
return { retry: false, reason: "no_failure_detail" };
|
|
30
|
+
const attemptsAllowed = args.maxAttempts ?? DEFAULT_WORKER_TASK_ATTEMPTS;
|
|
31
|
+
if (args.retriesUsed + 1 >= attemptsAllowed)
|
|
32
|
+
return { retry: false, reason: "attempts_exhausted" };
|
|
33
|
+
const classified = classifyFailure({ message: args.reasonDetail, provider: args.provider });
|
|
34
|
+
if (!classified.retryable)
|
|
35
|
+
return { retry: false, reason: `not_retryable_${classified.reason}` };
|
|
36
|
+
const delayMs = computeRetryDelayMs(WORKER_TASK_RETRY_POLICY, args.retriesUsed + 1, {
|
|
37
|
+
...(classified.retryAfterMs !== undefined ? { retryAfterMs: classified.retryAfterMs } : {}),
|
|
38
|
+
});
|
|
39
|
+
return { retry: true, reason: classified.reason, delayMs };
|
|
40
|
+
}
|
|
41
|
+
//# sourceMappingURL=worker-retry-policy.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"worker-retry-policy.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-retry-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAoB,MAAM,uCAAuC,CAAC;AAE/G;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,CAAC,CAAC;AAE9C,MAAM,CAAC,MAAM,wBAAwB,GAAgB;IACpD,WAAW,EAAE,4BAA4B;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E,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,UAAU,CAAC,MAAM,EAAE,OAAO,EAAE,CAAC;AAC5D,CAAC","sourcesContent":["import { classifyFailure, computeRetryDelayMs, type RetryPolicy } from \"@caupulican/pi-agent-core/reliability\";\n\n/**\n * Restart-durable, host-owned attempt ladder policy for delegated workers.\n *\n * The budget model has always carried `maxAttempts`, but nothing drove a second attempt: a\n * failed worker terminalized immediately and \"retry\" meant the orchestrator model burning a\n * turn to re-delegate blind, losing the worker's transcript. The ladder makes retry a host\n * mechanism instead: a retryable bounded failure suspends the attempt (durable, fenced) and\n * re-enqueues it through the owner scheduler after backoff, resuming from the persisted\n * conversation exactly like restart recovery does.\n *\n * Retries are deliberately evidence-gated: only failures whose recorded detail classifies as\n * transient (network, 5xx, rate limits) are retried. A missing detail or an unknown\n * classification never retries — an undiagnosed failure repeated is spend without evidence.\n */\nexport const DEFAULT_WORKER_TASK_ATTEMPTS = 2;\n\nexport const WORKER_TASK_RETRY_POLICY: RetryPolicy = {\n\tmaxAttempts: DEFAULT_WORKER_TASK_ATTEMPTS,\n\tbaseDelayMs: 5_000,\n\tmaxDelayMs: 60_000,\n\tjitterRatio: 0.2,\n};\n\nexport type WorkerRetryDecision = { retry: true; reason: string; delayMs: number } | { retry: false; reason: string };\n\nexport function evaluateWorkerRetry(args: {\n\tlaneStatus: string;\n\treasonCode: string;\n\treasonDetail?: string;\n\tprovider: string;\n\t/** Restart-durable ladder retries already consumed for this attempt. */\n\tretriesUsed: number;\n\t/** Grant budget ceiling for total attempts; defaults to {@link DEFAULT_WORKER_TASK_ATTEMPTS}. */\n\tmaxAttempts?: number;\n}): WorkerRetryDecision {\n\tif (args.laneStatus !== \"failed\") return { retry: false, reason: `lane_status_${args.laneStatus}` };\n\tif (args.reasonCode !== \"completion_error\") return { retry: false, reason: `reason_code_${args.reasonCode}` };\n\tif (!args.reasonDetail) return { retry: false, reason: \"no_failure_detail\" };\n\tconst attemptsAllowed = args.maxAttempts ?? DEFAULT_WORKER_TASK_ATTEMPTS;\n\tif (args.retriesUsed + 1 >= attemptsAllowed) return { retry: false, reason: \"attempts_exhausted\" };\n\tconst classified = classifyFailure({ message: args.reasonDetail, provider: args.provider });\n\tif (!classified.retryable) return { retry: false, reason: `not_retryable_${classified.reason}` };\n\tconst delayMs = computeRetryDelayMs(WORKER_TASK_RETRY_POLICY, args.retriesUsed + 1, {\n\t\t...(classified.retryAfterMs !== undefined ? { retryAfterMs: classified.retryAfterMs } : {}),\n\t});\n\treturn { retry: true, reason: classified.reason, delayMs };\n}\n"]}
|
|
@@ -46,7 +46,7 @@ export interface WorkerRunnerOptions {
|
|
|
46
46
|
complete: (args: {
|
|
47
47
|
systemPrompt: string;
|
|
48
48
|
userPrompt: string;
|
|
49
|
-
signal
|
|
49
|
+
signal: AbortSignal;
|
|
50
50
|
}) => Promise<WorkerCompletion>;
|
|
51
51
|
/** Live successful child-tool mutations, including writes completed before timeout/cancellation. */
|
|
52
52
|
getChangedFiles?: () => readonly string[];
|
|
@@ -73,6 +73,8 @@ export interface WorkerRunOutcome {
|
|
|
73
73
|
accepted: boolean;
|
|
74
74
|
laneStatus: LaneTerminalStatus;
|
|
75
75
|
reasonCode: string;
|
|
76
|
+
/** Underlying executor error for bounded failures; drives the in-process retry decision. */
|
|
77
|
+
reasonDetail?: string;
|
|
76
78
|
costUsd: number;
|
|
77
79
|
}
|
|
78
80
|
export declare function buildWorkerUserPrompt(request: WorkerRequest): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-runner.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/worker-runner.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAe,WAAW,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,0BAA0B,CAAC;AACrG,OAAO,EACN,KAAK,oBAAoB,EAGzB,MAAM,4CAA4C,CAAC;AACpD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,6BAA6B,CAAC;AAEtE,OAAO,EAC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AM,EAAE,CAAC;CACtB;AAkFD,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,kBAAkB,GAAG,SAAS,CAkD9E;AA8CD,wBAAsB,SAAS,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAsRvF"}
|
|
@@ -21,7 +21,7 @@ export function buildWorkerSystemPrompt(capabilities) {
|
|
|
21
21
|
"Use every provided tool when it improves the result; the host enforces the exact inherited grant at execution time.",
|
|
22
22
|
...(capabilities.delegate
|
|
23
23
|
? [
|
|
24
|
-
"You may create agents recursively
|
|
24
|
+
"You may create agents recursively within host-enforced depth, direct-child, session-agent, and queue bounds. Use list/transcript/threaded messages to coordinate the tree; the scheduler owns concurrency, budgets, leases, exact-cycle rejection, and cancellation.",
|
|
25
25
|
]
|
|
26
26
|
: []),
|
|
27
27
|
...(capabilities.write
|
|
@@ -242,6 +242,7 @@ function finishOutcome(args) {
|
|
|
242
242
|
accepted: acceptance.outcome === "allow",
|
|
243
243
|
laneStatus: args.laneStatus,
|
|
244
244
|
reasonCode: args.reasonCode,
|
|
245
|
+
...(args.reasonDetail ? { reasonDetail: args.reasonDetail } : {}),
|
|
245
246
|
costUsd: args.costUsd,
|
|
246
247
|
};
|
|
247
248
|
}
|
|
@@ -287,11 +288,12 @@ export async function runWorker(options) {
|
|
|
287
288
|
...baseClaim,
|
|
288
289
|
changedFiles: liveChangedFiles,
|
|
289
290
|
status: cancelled ? "cancelled" : "failed",
|
|
290
|
-
summary: `Worker did not complete: ${bounded.failure.reasonCode}`,
|
|
291
|
+
summary: `Worker did not complete: ${bounded.failure.reasonCode}${bounded.failure.detail ? ` — ${bounded.failure.detail}` : ""}`,
|
|
291
292
|
...(blockers ? { blockers } : {}),
|
|
292
293
|
},
|
|
293
294
|
laneStatus: bounded.failure.status,
|
|
294
295
|
reasonCode: bounded.failure.reasonCode,
|
|
296
|
+
...(bounded.failure.detail ? { reasonDetail: bounded.failure.detail } : {}),
|
|
295
297
|
costUsd,
|
|
296
298
|
});
|
|
297
299
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-runner.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AAEzE,OAAO,EAEN,wBAAwB,EACxB,uBAAuB,GACvB,MAAM,4CAA4C,CAAC;AAEpD,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EAEN,kBAAkB,GAGlB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACN,iCAAiC,EACjC,qCAAqC,EACrC,8BAA8B,EAC9B,yBAAyB,EACzB,8BAA8B,EAC9B,2BAA2B,EAC3B,mBAAmB,GACnB,MAAM,mBAAmB,CAAC;AAE3B;;;;;;;GAOG;AAEH,kGAAkG;AAClG,MAAM,UAAU,uBAAuB,CAAC,YAIvC;IACA,MAAM,WAAW,GAAG,YAAY,CAAC,KAAK;QACrC,CAAC,CAAC,0SAA0S;QAC5S,CAAC,CAAC,uLAAuL,CAAC;IAC3L,OAAO;QACN,8DAA8D;QAC9D,qHAAqH;QACrH,GAAG,CAAC,YAAY,CAAC,QAAQ;YACxB,CAAC,CAAC;gBACA,qNAAqN;aACrN;YACF,CAAC,CAAC,EAAE,CAAC;QACN,GAAG,CAAC,YAAY,CAAC,KAAK;YACrB,CAAC,CAAC,CAAC,oGAAoG,CAAC;YACxG,CAAC,CAAC,CAAC,+DAA+D,CAAC,CAAC;QACrE,GAAG,CAAC,YAAY,CAAC,OAAO;YACvB,CAAC,CAAC;gBACA,oJAAoJ;gBACpJ,iGAAiG;aACjG;YACF,CAAC,CAAC,EAAE,CAAC;QACN,+DAA+D;QAC/D,WAAW;QACX,GAAG,CAAC,YAAY,CAAC,KAAK;YACrB,CAAC,CAAC;gBACA,+BAA+B;gBAC/B,gHAAgH;aAChH;YACF,CAAC,CAAC,EAAE,CAAC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O;QACxB,GAAG,EAAE,OAAO,CAAC,GAAG;QAChB,KAAK;QACL,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,kBAAkB,CAAC,CAAC,CAAC,WAAW;QACzD,UAAU,EAAE,UAAU;YACrB,CAAC,CAAC,sBAAsB;YACxB,CAAC,CAAC,KAAK,CAAC,YAAY;gBACnB,CAAC,CAAC,KAAK,CAAC,YAAY,CAAC,OAAO,KAAK,UAAU;oBAC1C,CAAC,CAAC,uBAAuB;oBACzB,CAAC,CAAC,uBAAuB;gBAC1B,CAAC,CAAC,kBAAkB;QACtB,OAAO;KACP,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { runBoundedCompletion } from \"../autonomy/bounded-completion.ts\";\nimport type { EvidenceRef, GateOutcome, WorkerClaim, WorkerRequest } from \"../autonomy/contracts.ts\";\nimport {\n\ttype EvidenceFindingDraft,\n\tnormalizeEvidenceFinding,\n\tprojectEvidenceFindings,\n} from \"../autonomy/evidence-finding-projection.ts\";\nimport type { LaneTerminalStatus } from \"../autonomy/lane-tracker.ts\";\nimport { createEvidenceBundle } from \"../research/evidence-bundle.ts\";\nimport {\n\ttype AppliedActionsReport,\n\tparseWorkerActions,\n\ttype RejectedWorkerActions,\n\ttype WorkerAction,\n} from \"./worker-actions.ts\";\nimport {\n\tcollectBoundedWorkerClaimBlockers,\n\tcollectBoundedWorkerClaimChangedFiles,\n\tMAX_WORKER_CLAIM_BLOCKER_CHARS,\n\tMAX_WORKER_CLAIM_BLOCKERS,\n\tMAX_WORKER_CLAIM_SUMMARY_CHARS,\n\tnormalizeWorkerClaimForHost,\n\tvalidateWorkerClaim,\n} from \"./worker-claim.ts\";\n\n/**\n * Pure execution for one bounded specialist delegation: bounded isolated completion ->\n * parse -> untrusted `WorkerClaim` -> parent validation via {@link validateWorkerClaim}.\n *\n * The injected completion may be a bounded child tool loop. Its tool surface is built and gated by\n * the host; this module keeps the structured-output contract and treats every claim as untrusted\n * until parent validation succeeds.\n */\n\n/** Builds one capability-exact prompt; no role text may deny a tool already granted by policy. */\nexport function buildWorkerSystemPrompt(capabilities: {\n\twrite: boolean;\n\tprocess: boolean;\n\tdelegate?: boolean;\n}): string {\n\tconst resultShape = capabilities.write\n\t\t? '{\"summary\":\"<what you did>\",\"status\":\"completed\"|\"blocked\",\"blockers\":[],\"findings\":[{\"summary\":\"<finding>\",\"confidence\":<0..1>}],\"actions\":[{\"op\":\"write\",\"path\":\"<relative path>\",\"content\":\"<full file content>\"},{\"op\":\"edit\",\"path\":\"<relative path>\",\"old\":\"<exact text>\",\"new\":\"<replacement>\"}]}'\n\t\t: '{\"summary\":\"<what you concluded>\",\"status\":\"completed\"|\"blocked\",\"blockers\":[\"<failure or missing authority>\"],\"findings\":[{\"summary\":\"<one concrete finding>\",\"confidence\":<0..1>}]}';\n\treturn [\n\t\t\"You are an autonomous agent in a durable orchestration tree.\",\n\t\t\"Use every provided tool when it improves the result; the host enforces the exact inherited grant at execution time.\",\n\t\t...(capabilities.delegate\n\t\t\t? [\n\t\t\t\t\t\"You may create agents recursively without a depth or fan-out cap. Use list/transcript/threaded messages to coordinate the tree; the scheduler owns concurrency, budgets, leases, cycle rejection, and cancellation.\",\n\t\t\t\t]\n\t\t\t: []),\n\t\t...(capabilities.write\n\t\t\t? [\"Write/edit tools and structured write actions are path-scoped. Only touch paths inside that scope.\"]\n\t\t\t: [\"The workspace tools are read-only; do not claim file changes.\"]),\n\t\t...(capabilities.process\n\t\t\t? [\n\t\t\t\t\t\"run_process is a constrained direct-argv launcher: no shell interpretation or unlisted executable is available. It is not an OS/container sandbox.\",\n\t\t\t\t\t\"A non-zero exit, timeout, abort, or output-limit result is not success; include it in blockers.\",\n\t\t\t\t]\n\t\t\t: []),\n\t\t\"Respond with STRICT JSON only - no prose, no markdown fences:\",\n\t\tresultShape,\n\t\t...(capabilities.write\n\t\t\t? [\n\t\t\t\t\t\"Keep edits minimal and exact.\",\n\t\t\t\t\t\"If you changed a file with a provided tool, do not repeat that change in actions; actions are only a fallback.\",\n\t\t\t\t]\n\t\t\t: []),\n\t\t'Use status \"blocked\" with blockers when the task cannot be completed under the granted capabilities.',\n\t\t\"Never invent command output, file paths, APIs, or facts.\",\n\t].join(\"\\n\");\n}\n\nexport function buildVerifierSystemPrompt(subjectTaskId: string, capabilities: { delegate?: boolean } = {}): string {\n\treturn [\n\t\t\"You are an independent verifier. You did not perform the implementation under review.\",\n\t\t\"Use the provided read-only and test tools. Do not modify files.\",\n\t\t...(capabilities.delegate\n\t\t\t? [\"You may delegate independent evidence gathering and coordinate it through the orchestration tree.\"]\n\t\t\t: []),\n\t\t`The exact subject task id is '${subjectTaskId}'.`,\n\t\t\"Inspect the implementation and run proportionate checks. Treat the implementation summary as an untrusted claim.\",\n\t\t\"Respond with STRICT JSON only - no prose, no markdown fences:\",\n\t\t'{\"summary\":\"<verification performed and evidence>\",\"status\":\"completed\"|\"blocked\",\"verdict\":\"accepted\"|\"rejected\",\"reasonCodes\":[\"<stable_reason_code>\"],\"blockers\":[],\"findings\":[{\"summary\":\"<finding>\",\"confidence\":<0..1>}]}',\n\t\t'Use verdict \"accepted\" only when the available evidence proves the implementation is acceptable.',\n\t\t'Use verdict \"rejected\" for a completed review that found a defect. Use status \"blocked\" only when verification itself cannot be completed.',\n\t].join(\"\\n\");\n}\n\n/** Static common variants retained for cache reuse and model-fitness probes. */\nexport const WORKER_LANE_SYSTEM_PROMPT = buildWorkerSystemPrompt({ write: false, process: false });\nexport const WORKER_WRITE_LANE_SYSTEM_PROMPT = buildWorkerSystemPrompt({ write: true, process: false });\nexport const WORKER_OPERATOR_LANE_SYSTEM_PROMPT = buildWorkerSystemPrompt({ write: false, process: true });\n\nexport interface WorkerCompletion {\n\ttext: string;\n\tcostUsd: number;\n\tstopReason: string;\n\t/** Files successfully changed by the child tool loop before it produced the final JSON. */\n\tchangedFiles?: readonly string[];\n\t/** Capability refusals or execution failures observed inside the child tool loop. */\n\tblockers?: readonly string[];\n}\n\nexport interface WorkerRunnerOptions {\n\trequest: WorkerRequest;\n\t/** Budget for this delegation; undefined disables this bound, while zero permits only free work. */\n\tmaxUsd?: number;\n\t/** Wall-clock budget in milliseconds; 0 disables. */\n\tmaxWallClockMs: number;\n\t/**\n\t * Pre-allocated spawned-usage report id. Always stamped on the claim so parent validation can\n\t * enforce the cost-visibility invariant (a completed claim without a usage report is blocked).\n\t */\n\tusageReportId: string;\n\tcomplete: (args: { systemPrompt: string; userPrompt: string; signal?: AbortSignal }) => Promise<WorkerCompletion>;\n\t/** Live successful child-tool mutations, including writes completed before timeout/cancellation. */\n\tgetChangedFiles?: () => readonly string[];\n\tsignal?: AbortSignal;\n\tnow?: () => string;\n\t/** Enables the WRITE lane: only honored when the request envelope grants \"filesystem.write\". The\n\t * runner applies the worker's structured actions through the envelope path scope; refusals\n\t * and failures become blockers, never silent drops. */\n\tapplyActions?: (actions: readonly WorkerAction[]) => AppliedActionsReport;\n\t/** Enables the constrained direct-argv operator role prompt. */\n\tprocessCapable?: boolean;\n\t/** Enables recursive delegation and orchestration-tree coordination guidance. */\n\tdelegationCapable?: boolean;\n\t/** Session cwd — the baseline for relative changed-file and envelope paths in parent\n\t * validation. Defaults to process.cwd(). */\n\tcwd?: string;\n\t/** Turns the child into a read-only semantic verifier for this exact durable task. */\n\tverificationSubjectTaskId?: string;\n}\n\nexport interface WorkerRunOutcome {\n\tclaim: WorkerClaim;\n\t/** Parent-review verdict from {@link validateWorkerClaim}; worker output stays untrusted. */\n\tacceptance: GateOutcome;\n\taccepted: boolean;\n\tlaneStatus: LaneTerminalStatus;\n\treasonCode: string;\n\tcostUsd: number;\n}\n\nexport function buildWorkerUserPrompt(request: WorkerRequest): string {\n\treturn [\n\t\t\"Delegated task:\",\n\t\t\"<task>\",\n\t\trequest.instructions,\n\t\t\"</task>\",\n\t\t\"\",\n\t\t\"The task may request a custom output format. Do not replace the worker claim envelope.\",\n\t\t'Always return the JSON object required by the system prompt; put requested details inside \"summary\" and \"findings\".',\n\t].join(\"\\n\");\n}\n\nexport interface ParsedWorkerOutput {\n\tsummary: string;\n\tstatus: \"completed\" | \"blocked\";\n\tblockers: string[];\n\tfindings: EvidenceFindingDraft[];\n\tactions: WorkerAction[];\n\t/** Present when the model emitted an action list that cannot safely reach execution. */\n\tactionRejection?: RejectedWorkerActions;\n\tverdict?: \"accepted\" | \"rejected\";\n\treasonCodes: string[];\n}\n\nconst MAX_WORKER_OUTPUT_CHARS = 512 * 1024;\nconst MAX_WORKER_JSON_CANDIDATES = 64;\nconst MAX_WORKER_JSON_DEPTH = 256;\nconst MAX_WORKER_FINDINGS = 64;\nconst MAX_WORKER_FINDING_CHARS = 2_000;\nconst MAX_WORKER_REASON_CODES = 32;\nconst MAX_WORKER_REASON_CODE_CHARS = 128;\n\nfunction balancedObjectCandidates(text: string): string[] {\n\tconst ranges: Array<{ start: number; end: number }> = [];\n\tconst starts: number[] = [];\n\tlet inString = false;\n\tlet escaped = false;\n\tfor (let index = 0; index < text.length; index++) {\n\t\tconst character = text[index];\n\t\tif (inString) {\n\t\t\tif (escaped) escaped = false;\n\t\t\telse if (character === \"\\\\\") escaped = true;\n\t\t\telse if (character === '\"') inString = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === '\"') {\n\t\t\tinString = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"{\") {\n\t\t\tif (starts.length >= MAX_WORKER_JSON_DEPTH) return ranges.map(({ start, end }) => text.slice(start, end));\n\t\t\tstarts.push(index);\n\t\t\tcontinue;\n\t\t}\n\t\tif (character !== \"}\") continue;\n\t\tconst start = starts.pop();\n\t\tif (start === undefined || ranges.length >= MAX_WORKER_JSON_CANDIDATES) continue;\n\t\tconst end = index + 1;\n\t\tif (end - start <= MAX_WORKER_OUTPUT_CHARS) ranges.push({ start, end });\n\t}\n\treturn ranges.map(({ start, end }) => text.slice(start, end));\n}\n\nfunction workerOutputRecords(text: string): Record<string, unknown>[] {\n\tconst trimmed = text.trim();\n\tif (trimmed.length === 0 || trimmed.length > MAX_WORKER_OUTPUT_CHARS) return [];\n\tconst candidates: string[] = [trimmed];\n\tconst fenced = /```(?:json)?\\s*([\\s\\S]*?)```/.exec(trimmed);\n\tif (fenced?.[1]) candidates.push(fenced[1].trim());\n\tcandidates.push(...balancedObjectCandidates(trimmed));\n\tconst records: Record<string, unknown>[] = [];\n\tfor (const candidate of candidates) {\n\t\ttry {\n\t\t\tconst parsed: unknown = JSON.parse(candidate);\n\t\t\tif (parsed && typeof parsed === \"object\" && !Array.isArray(parsed))\n\t\t\t\trecords.push(parsed as Record<string, unknown>);\n\t\t} catch {\n\t\t\t// Candidate extraction is deliberately best-effort; a later balanced candidate may still be valid.\n\t\t}\n\t}\n\treturn records;\n}\n\nfunction isWorkerStatus(value: unknown): value is ParsedWorkerOutput[\"status\"] {\n\treturn value === \"completed\" || value === \"blocked\";\n}\n\n/**\n * Plain-text fallback is for output that never attempted the worker claim envelope. A JSON object\n * with a claim summary but malformed typed fields is a contract failure, never an implicit success.\n */\nfunction hasMalformedWorkerClaimEnvelope(text: string): boolean {\n\treturn workerOutputRecords(text).some((record) => {\n\t\tif (typeof record.summary !== \"string\" || record.summary.trim().length === 0) return false;\n\t\tif (!isWorkerStatus(record.status)) return true;\n\t\tif (record.verdict !== undefined && record.verdict !== \"accepted\" && record.verdict !== \"rejected\") return true;\n\t\treturn (\n\t\t\trecord.reasonCodes !== undefined &&\n\t\t\t(!Array.isArray(record.reasonCodes) ||\n\t\t\t\trecord.reasonCodes.some((reasonCode) => typeof reasonCode !== \"string\" || reasonCode.trim().length === 0))\n\t\t);\n\t});\n}\n\nexport function parseWorkerOutput(text: string): ParsedWorkerOutput | undefined {\n\tfor (const record of workerOutputRecords(text)) {\n\t\tconst summary = record.summary;\n\t\tif (typeof summary !== \"string\" || summary.trim().length === 0) continue;\n\t\tif (!isWorkerStatus(record.status)) continue;\n\t\tif (record.verdict !== undefined && record.verdict !== \"accepted\" && record.verdict !== \"rejected\") continue;\n\t\tif (\n\t\t\trecord.reasonCodes !== undefined &&\n\t\t\t(!Array.isArray(record.reasonCodes) ||\n\t\t\t\trecord.reasonCodes.some((reasonCode) => typeof reasonCode !== \"string\" || reasonCode.trim().length === 0))\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst status = record.status;\n\t\tconst blockers = Array.isArray(record.blockers)\n\t\t\t? record.blockers\n\t\t\t\t\t.filter((blocker): blocker is string => typeof blocker === \"string\" && blocker.trim().length > 0)\n\t\t\t\t\t.slice(0, MAX_WORKER_CLAIM_BLOCKERS)\n\t\t\t\t\t.map((blocker) => blocker.trim().slice(0, MAX_WORKER_CLAIM_BLOCKER_CHARS))\n\t\t\t: [];\n\t\tconst findings: EvidenceFindingDraft[] = [];\n\t\tif (Array.isArray(record.findings)) {\n\t\t\tfor (let index = 0; index < record.findings.length && index < MAX_WORKER_FINDINGS; index++) {\n\t\t\t\tconst finding = normalizeEvidenceFinding(record.findings[index], MAX_WORKER_FINDING_CHARS);\n\t\t\t\tif (finding) findings.push(finding);\n\t\t\t}\n\t\t}\n\t\tconst verdict = record.verdict === \"accepted\" || record.verdict === \"rejected\" ? record.verdict : undefined;\n\t\tconst reasonCodes = Array.isArray(record.reasonCodes)\n\t\t\t? record.reasonCodes\n\t\t\t\t\t.filter(\n\t\t\t\t\t\t(reasonCode): reasonCode is string => typeof reasonCode === \"string\" && reasonCode.trim().length > 0,\n\t\t\t\t\t)\n\t\t\t\t\t.slice(0, MAX_WORKER_REASON_CODES)\n\t\t\t\t\t.map((reasonCode) => reasonCode.trim().slice(0, MAX_WORKER_REASON_CODE_CHARS))\n\t\t\t: [];\n\t\tconst actionOutcome = parseWorkerActions(record.actions);\n\t\treturn {\n\t\t\tsummary: summary.trim().slice(0, MAX_WORKER_CLAIM_SUMMARY_CHARS),\n\t\t\tstatus,\n\t\t\tblockers,\n\t\t\tfindings,\n\t\t\tactions: actionOutcome.kind === \"accepted\" ? actionOutcome.actions : [],\n\t\t\t...(actionOutcome.kind === \"rejected\" ? { actionRejection: actionOutcome } : {}),\n\t\t\t...(verdict ? { verdict } : {}),\n\t\t\treasonCodes,\n\t\t};\n\t}\n\treturn undefined;\n}\n\nfunction buildWorkerEvidence(request: WorkerRequest, findings: ParsedWorkerOutput[\"findings\"]) {\n\tif (findings.length === 0) return undefined;\n\tconst instructionsRef: EvidenceRef = {\n\t\tid: \"src-instructions\",\n\t\tkind: \"user\",\n\t\ttitle: \"Delegated task instructions\",\n\t\ttrusted: true,\n\t\texcerpt: request.instructions.slice(0, 2000),\n\t};\n\tconst synthesisRef: EvidenceRef = {\n\t\tid: \"src-worker\",\n\t\tkind: \"tool\",\n\t\ttitle: \"Delegated worker synthesis\",\n\t\ttrusted: false,\n\t};\n\treturn createEvidenceBundle({\n\t\tquery: `worker:${request.id}`,\n\t\tsources: [instructionsRef, synthesisRef],\n\t\tfindings: projectEvidenceFindings(findings, synthesisRef.id),\n\t});\n}\n\nfunction finishOutcome(args: {\n\trequest: WorkerRequest;\n\tclaim: WorkerClaim;\n\tlaneStatus: LaneTerminalStatus;\n\treasonCode: string;\n\tcostUsd: number;\n\tcwd?: string;\n}): WorkerRunOutcome {\n\tconst claim = normalizeWorkerClaimForHost(args.claim);\n\tconst acceptance = validateWorkerClaim({ request: args.request, claim, cwd: args.cwd });\n\treturn {\n\t\tclaim,\n\t\tacceptance,\n\t\taccepted: acceptance.outcome === \"allow\",\n\t\tlaneStatus: args.laneStatus,\n\t\treasonCode: args.reasonCode,\n\t\tcostUsd: args.costUsd,\n\t};\n}\n\nexport async function runWorker(options: WorkerRunnerOptions): Promise<WorkerRunOutcome> {\n\tconst now = options.now ?? (() => new Date().toISOString());\n\tconst baseClaim = {\n\t\trequestId: options.request.id,\n\t\tchangedFiles: [] as string[],\n\t\tusageReportId: options.usageReportId,\n\t\tcreatedAt: now(),\n\t};\n\n\t// The write prompt requires BOTH the envelope grant and a caller-supplied applier.\n\tconst writeCapable =\n\t\toptions.request.envelope.capabilities.includes(\"filesystem.write\") && options.applyActions !== undefined;\n\n\tconst bounded = await runBoundedCompletion({\n\t\tmaxWallClockMs: options.maxWallClockMs,\n\t\tsignal: options.signal,\n\t\texecute: (signal) =>\n\t\t\toptions.complete({\n\t\t\t\tsystemPrompt: options.verificationSubjectTaskId\n\t\t\t\t\t? buildVerifierSystemPrompt(options.verificationSubjectTaskId, {\n\t\t\t\t\t\t\tdelegate: options.delegationCapable === true,\n\t\t\t\t\t\t})\n\t\t\t\t\t: buildWorkerSystemPrompt({\n\t\t\t\t\t\t\twrite: writeCapable,\n\t\t\t\t\t\t\tprocess: options.processCapable === true,\n\t\t\t\t\t\t\tdelegate: options.delegationCapable === true,\n\t\t\t\t\t\t}),\n\t\t\t\tuserPrompt: buildWorkerUserPrompt(options.request),\n\t\t\t\tsignal,\n\t\t\t}),\n\t});\n\tconst costUsd = bounded.completion?.costUsd ?? 0;\n\tconst liveChangedFilesReport = collectBoundedWorkerClaimChangedFiles(options.getChangedFiles?.() ?? []);\n\tconst liveChangedFiles = liveChangedFilesReport.values;\n\n\tif (bounded.failure) {\n\t\tconst cancelled = bounded.failure.status === \"canceled\" || bounded.failure.status === \"timeout\";\n\t\tconst blockers = liveChangedFilesReport.overflowed\n\t\t\t? [\"worker changed-file report exceeded the durable claim bound; parent review is required\"]\n\t\t\t: undefined;\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tclaim: {\n\t\t\t\t...baseClaim,\n\t\t\t\tchangedFiles: liveChangedFiles,\n\t\t\t\tstatus: cancelled ? \"cancelled\" : \"failed\",\n\t\t\t\tsummary: `Worker did not complete: ${bounded.failure.reasonCode}`,\n\t\t\t\t...(blockers ? { blockers } : {}),\n\t\t\t},\n\t\t\tlaneStatus: bounded.failure.status,\n\t\t\treasonCode: bounded.failure.reasonCode,\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst completion = bounded.completion as WorkerCompletion | undefined;\n\tconst completionChangedFilesReport = collectBoundedWorkerClaimChangedFiles(completion?.changedFiles ?? []);\n\tconst mergedChangedFilesReport = collectBoundedWorkerClaimChangedFiles([\n\t\t...liveChangedFiles,\n\t\t...completionChangedFilesReport.values,\n\t]);\n\tconst changedFilesOverflowed =\n\t\tliveChangedFilesReport.overflowed ||\n\t\tcompletionChangedFilesReport.overflowed ||\n\t\tmergedChangedFilesReport.overflowed;\n\tconst completionChangedFiles = mergedChangedFilesReport.values;\n\tconst completionBaseClaim = { ...baseClaim, changedFiles: completionChangedFiles };\n\tif (!completion || completion.stopReason === \"error\" || completion.stopReason === \"aborted\") {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tclaim: { ...completionBaseClaim, status: \"failed\", summary: \"Worker model call failed.\" },\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"model_error\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst parsed = parseWorkerOutput(completion.text);\n\tif (!parsed) {\n\t\tif (hasMalformedWorkerClaimEnvelope(completion.text)) {\n\t\t\treturn finishOutcome({\n\t\t\t\trequest: options.request,\n\t\t\t\tcwd: options.cwd,\n\t\t\t\tclaim: {\n\t\t\t\t\t...completionBaseClaim,\n\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\tsummary: \"Worker output used a malformed structured claim envelope.\",\n\t\t\t\t},\n\t\t\t\tlaneStatus: \"failed\",\n\t\t\t\treasonCode: \"unparseable_output\",\n\t\t\t\tcostUsd,\n\t\t\t});\n\t\t}\n\t\tconst readOnlyPlainText =\n\t\t\t!options.verificationSubjectTaskId &&\n\t\t\t!writeCapable &&\n\t\t\tcompletion.text.trim().length > 0 &&\n\t\t\tcompletionChangedFiles.length === 0 &&\n\t\t\t!changedFilesOverflowed;\n\t\tif (readOnlyPlainText) {\n\t\t\tconst completionBlockersReport = collectBoundedWorkerClaimBlockers(completion.blockers ?? []);\n\t\t\tconst completionBlockers = completionBlockersReport.overflowed\n\t\t\t\t? [\n\t\t\t\t\t\t...completionBlockersReport.values.slice(0, Math.max(0, MAX_WORKER_CLAIM_BLOCKERS - 1)),\n\t\t\t\t\t\t\"worker blocker report exceeded the durable claim bound; parent review is required\",\n\t\t\t\t\t]\n\t\t\t\t: completionBlockersReport.values;\n\t\t\tconst incompleteNote =\n\t\t\t\tcompletion.stopReason === \"stop\"\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: `\\n\\n[Worker output ended with stop reason '${completion.stopReason}'; verify completeness.]`;\n\t\t\tconst summary = `${completion.text.trim().slice(0, Math.max(0, MAX_WORKER_CLAIM_SUMMARY_CHARS - incompleteNote.length))}${incompleteNote}`;\n\t\t\tconst blocked = completionBlockers.length > 0;\n\t\t\treturn finishOutcome({\n\t\t\t\trequest: options.request,\n\t\t\t\tcwd: options.cwd,\n\t\t\t\tclaim: {\n\t\t\t\t\t...completionBaseClaim,\n\t\t\t\t\tstatus: blocked ? \"blocked\" : \"completed\",\n\t\t\t\t\toutputFormat: \"plain_text\",\n\t\t\t\t\tsummary,\n\t\t\t\t\t...(blocked ? { blockers: completionBlockers } : {}),\n\t\t\t\t},\n\t\t\t\tlaneStatus: blocked ? \"failed\" : \"succeeded\",\n\t\t\t\treasonCode: blocked\n\t\t\t\t\t? \"worker_blocked\"\n\t\t\t\t\t: completion.stopReason === \"stop\"\n\t\t\t\t\t\t? \"worker_completed_plain_text\"\n\t\t\t\t\t\t: \"worker_completed_plain_text_incomplete\",\n\t\t\t\tcostUsd,\n\t\t\t});\n\t\t}\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tclaim: {\n\t\t\t\t...completionBaseClaim,\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tsummary: \"Worker output was not valid structured JSON.\",\n\t\t\t\t...(changedFilesOverflowed\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tblockers: [\n\t\t\t\t\t\t\t\t\"worker changed-file report exceeded the durable claim bound; parent review is required\",\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"unparseable_output\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst evidence = buildWorkerEvidence(options.request, parsed.findings);\n\tif (parsed.actionRejection) {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tclaim: {\n\t\t\t\t...completionBaseClaim,\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tsummary: \"Worker output contained invalid structured actions.\",\n\t\t\t\tblockers: [parsed.actionRejection.reasonCode],\n\t\t\t},\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"unparseable_output\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\tif (options.verificationSubjectTaskId && (!parsed.verdict || parsed.reasonCodes.length === 0)) {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tclaim: {\n\t\t\t\t...completionBaseClaim,\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tsummary: \"Verifier output omitted its typed verdict or reasonCodes.\",\n\t\t\t},\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"invalid_verifier_result\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\tlet changedFiles: string[] = [...completionChangedFiles];\n\tconst completionBlockersReport = collectBoundedWorkerClaimBlockers(completion.blockers ?? []);\n\tconst actionBlockers: string[] = [...completionBlockersReport.values];\n\tif (changedFilesOverflowed) {\n\t\tactionBlockers.push(\"worker changed-file report exceeded the durable claim bound; parent review is required\");\n\t}\n\tif (completionBlockersReport.overflowed) {\n\t\tactionBlockers.push(\"worker blocker report exceeded the durable claim bound; parent review is required\");\n\t}\n\tif (!writeCapable && completionChangedFiles.length > 0) {\n\t\tactionBlockers.push(\"worker reported file changes without a filesystem.write envelope grant\");\n\t}\n\tif (writeCapable && parsed.status !== \"blocked\" && parsed.actions.length > 0 && options.applyActions) {\n\t\t// Runner-side application through the envelope path scope: refusals and failures are\n\t\t// surfaced as blockers so a partially-applied change can never look like clean success.\n\t\tconst applied = options.applyActions(parsed.actions);\n\t\tconst appliedChangedFilesReport = collectBoundedWorkerClaimChangedFiles(applied.changedFiles);\n\t\tconst mergedAppliedChangedFilesReport = collectBoundedWorkerClaimChangedFiles([\n\t\t\t...changedFiles,\n\t\t\t...appliedChangedFilesReport.values,\n\t\t]);\n\t\tchangedFiles = mergedAppliedChangedFilesReport.values;\n\t\tif (appliedChangedFilesReport.overflowed || mergedAppliedChangedFilesReport.overflowed) {\n\t\t\tactionBlockers.push(\"applied changed-file report exceeded the durable claim bound; parent review is required\");\n\t\t}\n\t\tfor (const refusal of applied.refused) {\n\t\t\tactionBlockers.push(`action refused (${refusal.path}): ${refusal.reason}`);\n\t\t}\n\t\tfor (const failure of applied.failed) {\n\t\t\tactionBlockers.push(`action failed (${failure.path}): ${failure.reason}`);\n\t\t}\n\t\tfor (const inspection of applied.inspectionRequired) {\n\t\t\tactionBlockers.push(\n\t\t\t\t`action requires workspace/evidence inspection (${inspection.path}, ${inspection.state}): ${inspection.reasonCode}`,\n\t\t\t);\n\t\t}\n\t} else if (!writeCapable && parsed.actions.length > 0) {\n\t\tactionBlockers.push(\"worker emitted file actions without a filesystem.write envelope grant; nothing was applied\");\n\t}\n\tconst allBlockersReport = collectBoundedWorkerClaimBlockers([...parsed.blockers, ...actionBlockers]);\n\tconst allBlockers = allBlockersReport.overflowed\n\t\t? [\n\t\t\t\t...allBlockersReport.values.slice(0, Math.max(0, MAX_WORKER_CLAIM_BLOCKERS - 1)),\n\t\t\t\t\"worker blocker report exceeded the durable claim bound; parent review is required\",\n\t\t\t]\n\t\t: allBlockersReport.values;\n\tconst claim: WorkerClaim = {\n\t\t...baseClaim,\n\t\tchangedFiles,\n\t\tstatus: parsed.status === \"blocked\" || allBlockers.length > 0 ? \"blocked\" : \"completed\",\n\t\tsummary: parsed.summary,\n\t\t...(allBlockers.length > 0 ? { blockers: allBlockers } : {}),\n\t\t...(evidence ? { evidence } : {}),\n\t\t...(options.verificationSubjectTaskId && parsed.verdict\n\t\t\t? {\n\t\t\t\t\tverification: {\n\t\t\t\t\t\tsubjectTaskId: options.verificationSubjectTaskId,\n\t\t\t\t\t\tverdict: parsed.verdict,\n\t\t\t\t\t\treasonCodes: parsed.reasonCodes,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n\n\tif (claim.status === \"blocked\") {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tclaim,\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"worker_blocked\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst overBudget = options.maxUsd !== undefined && costUsd > options.maxUsd;\n\treturn finishOutcome({\n\t\trequest: options.request,\n\t\tcwd: options.cwd,\n\t\tclaim,\n\t\tlaneStatus: overBudget ? \"budget_exhausted\" : \"succeeded\",\n\t\treasonCode: overBudget\n\t\t\t? \"cost_budget_exceeded\"\n\t\t\t: claim.verification\n\t\t\t\t? claim.verification.verdict === \"accepted\"\n\t\t\t\t\t? \"verification_accepted\"\n\t\t\t\t\t: \"verification_rejected\"\n\t\t\t\t: \"worker_completed\",\n\t\tcostUsd,\n\t});\n}\n"]}
|
|
1
|
+
{"version":3,"file":"worker-runner.js","sourceRoot":"","sources":["../../../src/core/delegation/worker-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AAEzE,OAAO,EAEN,wBAAwB,EACxB,uBAAuB,GACvB,MAAM,4CAA4C,CAAC;AAEpD,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EAEN,kBAAkB,GAGlB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACN,iCAAiC,EACjC,qCAAqC,EACrC,8BAA8B,EAC9B,yBAAyB,EACzB,8BAA8B,EAC9B,2BAA2B,EAC3B,mBAAmB,GACnB,MAAM,mBAAmB,CA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AW;QACzD,UAAU,EAAE,UAAU;YACrB,CAAC,CAAC,sBAAsB;YACxB,CAAC,CAAC,KAAK,CAAC,YAAY;gBACnB,CAAC,CAAC,KAAK,CAAC,YAAY,CAAC,OAAO,KAAK,UAAU;oBAC1C,CAAC,CAAC,uBAAuB;oBACzB,CAAC,CAAC,uBAAuB;gBAC1B,CAAC,CAAC,kBAAkB;QACtB,OAAO;KACP,CAAC,CAAC;AACJ,CAAC","sourcesContent":["import { runBoundedCompletion } from \"../autonomy/bounded-completion.ts\";\nimport type { EvidenceRef, GateOutcome, WorkerClaim, WorkerRequest } from \"../autonomy/contracts.ts\";\nimport {\n\ttype EvidenceFindingDraft,\n\tnormalizeEvidenceFinding,\n\tprojectEvidenceFindings,\n} from \"../autonomy/evidence-finding-projection.ts\";\nimport type { LaneTerminalStatus } from \"../autonomy/lane-tracker.ts\";\nimport { createEvidenceBundle } from \"../research/evidence-bundle.ts\";\nimport {\n\ttype AppliedActionsReport,\n\tparseWorkerActions,\n\ttype RejectedWorkerActions,\n\ttype WorkerAction,\n} from \"./worker-actions.ts\";\nimport {\n\tcollectBoundedWorkerClaimBlockers,\n\tcollectBoundedWorkerClaimChangedFiles,\n\tMAX_WORKER_CLAIM_BLOCKER_CHARS,\n\tMAX_WORKER_CLAIM_BLOCKERS,\n\tMAX_WORKER_CLAIM_SUMMARY_CHARS,\n\tnormalizeWorkerClaimForHost,\n\tvalidateWorkerClaim,\n} from \"./worker-claim.ts\";\n\n/**\n * Pure execution for one bounded specialist delegation: bounded isolated completion ->\n * parse -> untrusted `WorkerClaim` -> parent validation via {@link validateWorkerClaim}.\n *\n * The injected completion may be a bounded child tool loop. Its tool surface is built and gated by\n * the host; this module keeps the structured-output contract and treats every claim as untrusted\n * until parent validation succeeds.\n */\n\n/** Builds one capability-exact prompt; no role text may deny a tool already granted by policy. */\nexport function buildWorkerSystemPrompt(capabilities: {\n\twrite: boolean;\n\tprocess: boolean;\n\tdelegate?: boolean;\n}): string {\n\tconst resultShape = capabilities.write\n\t\t? '{\"summary\":\"<what you did>\",\"status\":\"completed\"|\"blocked\",\"blockers\":[],\"findings\":[{\"summary\":\"<finding>\",\"confidence\":<0..1>}],\"actions\":[{\"op\":\"write\",\"path\":\"<relative path>\",\"content\":\"<full file content>\"},{\"op\":\"edit\",\"path\":\"<relative path>\",\"old\":\"<exact text>\",\"new\":\"<replacement>\"}]}'\n\t\t: '{\"summary\":\"<what you concluded>\",\"status\":\"completed\"|\"blocked\",\"blockers\":[\"<failure or missing authority>\"],\"findings\":[{\"summary\":\"<one concrete finding>\",\"confidence\":<0..1>}]}';\n\treturn [\n\t\t\"You are an autonomous agent in a durable orchestration tree.\",\n\t\t\"Use every provided tool when it improves the result; the host enforces the exact inherited grant at execution time.\",\n\t\t...(capabilities.delegate\n\t\t\t? [\n\t\t\t\t\t\"You may create agents recursively within host-enforced depth, direct-child, session-agent, and queue bounds. Use list/transcript/threaded messages to coordinate the tree; the scheduler owns concurrency, budgets, leases, exact-cycle rejection, and cancellation.\",\n\t\t\t\t]\n\t\t\t: []),\n\t\t...(capabilities.write\n\t\t\t? [\"Write/edit tools and structured write actions are path-scoped. Only touch paths inside that scope.\"]\n\t\t\t: [\"The workspace tools are read-only; do not claim file changes.\"]),\n\t\t...(capabilities.process\n\t\t\t? [\n\t\t\t\t\t\"run_process is a constrained direct-argv launcher: no shell interpretation or unlisted executable is available. It is not an OS/container sandbox.\",\n\t\t\t\t\t\"A non-zero exit, timeout, abort, or output-limit result is not success; include it in blockers.\",\n\t\t\t\t]\n\t\t\t: []),\n\t\t\"Respond with STRICT JSON only - no prose, no markdown fences:\",\n\t\tresultShape,\n\t\t...(capabilities.write\n\t\t\t? [\n\t\t\t\t\t\"Keep edits minimal and exact.\",\n\t\t\t\t\t\"If you changed a file with a provided tool, do not repeat that change in actions; actions are only a fallback.\",\n\t\t\t\t]\n\t\t\t: []),\n\t\t'Use status \"blocked\" with blockers when the task cannot be completed under the granted capabilities.',\n\t\t\"Never invent command output, file paths, APIs, or facts.\",\n\t].join(\"\\n\");\n}\n\nexport function buildVerifierSystemPrompt(subjectTaskId: string, capabilities: { delegate?: boolean } = {}): string {\n\treturn [\n\t\t\"You are an independent verifier. You did not perform the implementation under review.\",\n\t\t\"Use the provided read-only and test tools. Do not modify files.\",\n\t\t...(capabilities.delegate\n\t\t\t? [\"You may delegate independent evidence gathering and coordinate it through the orchestration tree.\"]\n\t\t\t: []),\n\t\t`The exact subject task id is '${subjectTaskId}'.`,\n\t\t\"Inspect the implementation and run proportionate checks. Treat the implementation summary as an untrusted claim.\",\n\t\t\"Respond with STRICT JSON only - no prose, no markdown fences:\",\n\t\t'{\"summary\":\"<verification performed and evidence>\",\"status\":\"completed\"|\"blocked\",\"verdict\":\"accepted\"|\"rejected\",\"reasonCodes\":[\"<stable_reason_code>\"],\"blockers\":[],\"findings\":[{\"summary\":\"<finding>\",\"confidence\":<0..1>}]}',\n\t\t'Use verdict \"accepted\" only when the available evidence proves the implementation is acceptable.',\n\t\t'Use verdict \"rejected\" for a completed review that found a defect. Use status \"blocked\" only when verification itself cannot be completed.',\n\t].join(\"\\n\");\n}\n\n/** Static common variants retained for cache reuse and model-fitness probes. */\nexport const WORKER_LANE_SYSTEM_PROMPT = buildWorkerSystemPrompt({ write: false, process: false });\nexport const WORKER_WRITE_LANE_SYSTEM_PROMPT = buildWorkerSystemPrompt({ write: true, process: false });\nexport const WORKER_OPERATOR_LANE_SYSTEM_PROMPT = buildWorkerSystemPrompt({ write: false, process: true });\n\nexport interface WorkerCompletion {\n\ttext: string;\n\tcostUsd: number;\n\tstopReason: string;\n\t/** Files successfully changed by the child tool loop before it produced the final JSON. */\n\tchangedFiles?: readonly string[];\n\t/** Capability refusals or execution failures observed inside the child tool loop. */\n\tblockers?: readonly string[];\n}\n\nexport interface WorkerRunnerOptions {\n\trequest: WorkerRequest;\n\t/** Budget for this delegation; undefined disables this bound, while zero permits only free work. */\n\tmaxUsd?: number;\n\t/** Wall-clock budget in milliseconds; 0 disables. */\n\tmaxWallClockMs: number;\n\t/**\n\t * Pre-allocated spawned-usage report id. Always stamped on the claim so parent validation can\n\t * enforce the cost-visibility invariant (a completed claim without a usage report is blocked).\n\t */\n\tusageReportId: string;\n\tcomplete: (args: { systemPrompt: string; userPrompt: string; signal: AbortSignal }) => Promise<WorkerCompletion>;\n\t/** Live successful child-tool mutations, including writes completed before timeout/cancellation. */\n\tgetChangedFiles?: () => readonly string[];\n\tsignal?: AbortSignal;\n\tnow?: () => string;\n\t/** Enables the WRITE lane: only honored when the request envelope grants \"filesystem.write\". The\n\t * runner applies the worker's structured actions through the envelope path scope; refusals\n\t * and failures become blockers, never silent drops. */\n\tapplyActions?: (actions: readonly WorkerAction[]) => AppliedActionsReport;\n\t/** Enables the constrained direct-argv operator role prompt. */\n\tprocessCapable?: boolean;\n\t/** Enables recursive delegation and orchestration-tree coordination guidance. */\n\tdelegationCapable?: boolean;\n\t/** Session cwd — the baseline for relative changed-file and envelope paths in parent\n\t * validation. Defaults to process.cwd(). */\n\tcwd?: string;\n\t/** Turns the child into a read-only semantic verifier for this exact durable task. */\n\tverificationSubjectTaskId?: string;\n}\n\nexport interface WorkerRunOutcome {\n\tclaim: WorkerClaim;\n\t/** Parent-review verdict from {@link validateWorkerClaim}; worker output stays untrusted. */\n\tacceptance: GateOutcome;\n\taccepted: boolean;\n\tlaneStatus: LaneTerminalStatus;\n\treasonCode: string;\n\t/** Underlying executor error for bounded failures; drives the in-process retry decision. */\n\treasonDetail?: string;\n\tcostUsd: number;\n}\n\nexport function buildWorkerUserPrompt(request: WorkerRequest): string {\n\treturn [\n\t\t\"Delegated task:\",\n\t\t\"<task>\",\n\t\trequest.instructions,\n\t\t\"</task>\",\n\t\t\"\",\n\t\t\"The task may request a custom output format. Do not replace the worker claim envelope.\",\n\t\t'Always return the JSON object required by the system prompt; put requested details inside \"summary\" and \"findings\".',\n\t].join(\"\\n\");\n}\n\nexport interface ParsedWorkerOutput {\n\tsummary: string;\n\tstatus: \"completed\" | \"blocked\";\n\tblockers: string[];\n\tfindings: EvidenceFindingDraft[];\n\tactions: WorkerAction[];\n\t/** Present when the model emitted an action list that cannot safely reach execution. */\n\tactionRejection?: RejectedWorkerActions;\n\tverdict?: \"accepted\" | \"rejected\";\n\treasonCodes: string[];\n}\n\nconst MAX_WORKER_OUTPUT_CHARS = 512 * 1024;\nconst MAX_WORKER_JSON_CANDIDATES = 64;\nconst MAX_WORKER_JSON_DEPTH = 256;\nconst MAX_WORKER_FINDINGS = 64;\nconst MAX_WORKER_FINDING_CHARS = 2_000;\nconst MAX_WORKER_REASON_CODES = 32;\nconst MAX_WORKER_REASON_CODE_CHARS = 128;\n\nfunction balancedObjectCandidates(text: string): string[] {\n\tconst ranges: Array<{ start: number; end: number }> = [];\n\tconst starts: number[] = [];\n\tlet inString = false;\n\tlet escaped = false;\n\tfor (let index = 0; index < text.length; index++) {\n\t\tconst character = text[index];\n\t\tif (inString) {\n\t\t\tif (escaped) escaped = false;\n\t\t\telse if (character === \"\\\\\") escaped = true;\n\t\t\telse if (character === '\"') inString = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === '\"') {\n\t\t\tinString = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"{\") {\n\t\t\tif (starts.length >= MAX_WORKER_JSON_DEPTH) return ranges.map(({ start, end }) => text.slice(start, end));\n\t\t\tstarts.push(index);\n\t\t\tcontinue;\n\t\t}\n\t\tif (character !== \"}\") continue;\n\t\tconst start = starts.pop();\n\t\tif (start === undefined || ranges.length >= MAX_WORKER_JSON_CANDIDATES) continue;\n\t\tconst end = index + 1;\n\t\tif (end - start <= MAX_WORKER_OUTPUT_CHARS) ranges.push({ start, end });\n\t}\n\treturn ranges.map(({ start, end }) => text.slice(start, end));\n}\n\nfunction workerOutputRecords(text: string): Record<string, unknown>[] {\n\tconst trimmed = text.trim();\n\tif (trimmed.length === 0 || trimmed.length > MAX_WORKER_OUTPUT_CHARS) return [];\n\tconst candidates: string[] = [trimmed];\n\tconst fenced = /```(?:json)?\\s*([\\s\\S]*?)```/.exec(trimmed);\n\tif (fenced?.[1]) candidates.push(fenced[1].trim());\n\tcandidates.push(...balancedObjectCandidates(trimmed));\n\tconst records: Record<string, unknown>[] = [];\n\tfor (const candidate of candidates) {\n\t\ttry {\n\t\t\tconst parsed: unknown = JSON.parse(candidate);\n\t\t\tif (parsed && typeof parsed === \"object\" && !Array.isArray(parsed))\n\t\t\t\trecords.push(parsed as Record<string, unknown>);\n\t\t} catch {\n\t\t\t// Candidate extraction is deliberately best-effort; a later balanced candidate may still be valid.\n\t\t}\n\t}\n\treturn records;\n}\n\nfunction isWorkerStatus(value: unknown): value is ParsedWorkerOutput[\"status\"] {\n\treturn value === \"completed\" || value === \"blocked\";\n}\n\n/**\n * Plain-text fallback is for output that never attempted the worker claim envelope. A JSON object\n * with a claim summary but malformed typed fields is a contract failure, never an implicit success.\n */\nfunction hasMalformedWorkerClaimEnvelope(text: string): boolean {\n\treturn workerOutputRecords(text).some((record) => {\n\t\tif (typeof record.summary !== \"string\" || record.summary.trim().length === 0) return false;\n\t\tif (!isWorkerStatus(record.status)) return true;\n\t\tif (record.verdict !== undefined && record.verdict !== \"accepted\" && record.verdict !== \"rejected\") return true;\n\t\treturn (\n\t\t\trecord.reasonCodes !== undefined &&\n\t\t\t(!Array.isArray(record.reasonCodes) ||\n\t\t\t\trecord.reasonCodes.some((reasonCode) => typeof reasonCode !== \"string\" || reasonCode.trim().length === 0))\n\t\t);\n\t});\n}\n\nexport function parseWorkerOutput(text: string): ParsedWorkerOutput | undefined {\n\tfor (const record of workerOutputRecords(text)) {\n\t\tconst summary = record.summary;\n\t\tif (typeof summary !== \"string\" || summary.trim().length === 0) continue;\n\t\tif (!isWorkerStatus(record.status)) continue;\n\t\tif (record.verdict !== undefined && record.verdict !== \"accepted\" && record.verdict !== \"rejected\") continue;\n\t\tif (\n\t\t\trecord.reasonCodes !== undefined &&\n\t\t\t(!Array.isArray(record.reasonCodes) ||\n\t\t\t\trecord.reasonCodes.some((reasonCode) => typeof reasonCode !== \"string\" || reasonCode.trim().length === 0))\n\t\t) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst status = record.status;\n\t\tconst blockers = Array.isArray(record.blockers)\n\t\t\t? record.blockers\n\t\t\t\t\t.filter((blocker): blocker is string => typeof blocker === \"string\" && blocker.trim().length > 0)\n\t\t\t\t\t.slice(0, MAX_WORKER_CLAIM_BLOCKERS)\n\t\t\t\t\t.map((blocker) => blocker.trim().slice(0, MAX_WORKER_CLAIM_BLOCKER_CHARS))\n\t\t\t: [];\n\t\tconst findings: EvidenceFindingDraft[] = [];\n\t\tif (Array.isArray(record.findings)) {\n\t\t\tfor (let index = 0; index < record.findings.length && index < MAX_WORKER_FINDINGS; index++) {\n\t\t\t\tconst finding = normalizeEvidenceFinding(record.findings[index], MAX_WORKER_FINDING_CHARS);\n\t\t\t\tif (finding) findings.push(finding);\n\t\t\t}\n\t\t}\n\t\tconst verdict = record.verdict === \"accepted\" || record.verdict === \"rejected\" ? record.verdict : undefined;\n\t\tconst reasonCodes = Array.isArray(record.reasonCodes)\n\t\t\t? record.reasonCodes\n\t\t\t\t\t.filter(\n\t\t\t\t\t\t(reasonCode): reasonCode is string => typeof reasonCode === \"string\" && reasonCode.trim().length > 0,\n\t\t\t\t\t)\n\t\t\t\t\t.slice(0, MAX_WORKER_REASON_CODES)\n\t\t\t\t\t.map((reasonCode) => reasonCode.trim().slice(0, MAX_WORKER_REASON_CODE_CHARS))\n\t\t\t: [];\n\t\tconst actionOutcome = parseWorkerActions(record.actions);\n\t\treturn {\n\t\t\tsummary: summary.trim().slice(0, MAX_WORKER_CLAIM_SUMMARY_CHARS),\n\t\t\tstatus,\n\t\t\tblockers,\n\t\t\tfindings,\n\t\t\tactions: actionOutcome.kind === \"accepted\" ? actionOutcome.actions : [],\n\t\t\t...(actionOutcome.kind === \"rejected\" ? { actionRejection: actionOutcome } : {}),\n\t\t\t...(verdict ? { verdict } : {}),\n\t\t\treasonCodes,\n\t\t};\n\t}\n\treturn undefined;\n}\n\nfunction buildWorkerEvidence(request: WorkerRequest, findings: ParsedWorkerOutput[\"findings\"]) {\n\tif (findings.length === 0) return undefined;\n\tconst instructionsRef: EvidenceRef = {\n\t\tid: \"src-instructions\",\n\t\tkind: \"user\",\n\t\ttitle: \"Delegated task instructions\",\n\t\ttrusted: true,\n\t\texcerpt: request.instructions.slice(0, 2000),\n\t};\n\tconst synthesisRef: EvidenceRef = {\n\t\tid: \"src-worker\",\n\t\tkind: \"tool\",\n\t\ttitle: \"Delegated worker synthesis\",\n\t\ttrusted: false,\n\t};\n\treturn createEvidenceBundle({\n\t\tquery: `worker:${request.id}`,\n\t\tsources: [instructionsRef, synthesisRef],\n\t\tfindings: projectEvidenceFindings(findings, synthesisRef.id),\n\t});\n}\n\nfunction finishOutcome(args: {\n\trequest: WorkerRequest;\n\tclaim: WorkerClaim;\n\tlaneStatus: LaneTerminalStatus;\n\treasonCode: string;\n\treasonDetail?: string;\n\tcostUsd: number;\n\tcwd?: string;\n}): WorkerRunOutcome {\n\tconst claim = normalizeWorkerClaimForHost(args.claim);\n\tconst acceptance = validateWorkerClaim({ request: args.request, claim, cwd: args.cwd });\n\treturn {\n\t\tclaim,\n\t\tacceptance,\n\t\taccepted: acceptance.outcome === \"allow\",\n\t\tlaneStatus: args.laneStatus,\n\t\treasonCode: args.reasonCode,\n\t\t...(args.reasonDetail ? { reasonDetail: args.reasonDetail } : {}),\n\t\tcostUsd: args.costUsd,\n\t};\n}\n\nexport async function runWorker(options: WorkerRunnerOptions): Promise<WorkerRunOutcome> {\n\tconst now = options.now ?? (() => new Date().toISOString());\n\tconst baseClaim = {\n\t\trequestId: options.request.id,\n\t\tchangedFiles: [] as string[],\n\t\tusageReportId: options.usageReportId,\n\t\tcreatedAt: now(),\n\t};\n\n\t// The write prompt requires BOTH the envelope grant and a caller-supplied applier.\n\tconst writeCapable =\n\t\toptions.request.envelope.capabilities.includes(\"filesystem.write\") && options.applyActions !== undefined;\n\n\tconst bounded = await runBoundedCompletion({\n\t\tmaxWallClockMs: options.maxWallClockMs,\n\t\tsignal: options.signal,\n\t\texecute: (signal) =>\n\t\t\toptions.complete({\n\t\t\t\tsystemPrompt: options.verificationSubjectTaskId\n\t\t\t\t\t? buildVerifierSystemPrompt(options.verificationSubjectTaskId, {\n\t\t\t\t\t\t\tdelegate: options.delegationCapable === true,\n\t\t\t\t\t\t})\n\t\t\t\t\t: buildWorkerSystemPrompt({\n\t\t\t\t\t\t\twrite: writeCapable,\n\t\t\t\t\t\t\tprocess: options.processCapable === true,\n\t\t\t\t\t\t\tdelegate: options.delegationCapable === true,\n\t\t\t\t\t\t}),\n\t\t\t\tuserPrompt: buildWorkerUserPrompt(options.request),\n\t\t\t\tsignal,\n\t\t\t}),\n\t});\n\tconst costUsd = bounded.completion?.costUsd ?? 0;\n\tconst liveChangedFilesReport = collectBoundedWorkerClaimChangedFiles(options.getChangedFiles?.() ?? []);\n\tconst liveChangedFiles = liveChangedFilesReport.values;\n\n\tif (bounded.failure) {\n\t\tconst cancelled = bounded.failure.status === \"canceled\" || bounded.failure.status === \"timeout\";\n\t\tconst blockers = liveChangedFilesReport.overflowed\n\t\t\t? [\"worker changed-file report exceeded the durable claim bound; parent review is required\"]\n\t\t\t: undefined;\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tclaim: {\n\t\t\t\t...baseClaim,\n\t\t\t\tchangedFiles: liveChangedFiles,\n\t\t\t\tstatus: cancelled ? \"cancelled\" : \"failed\",\n\t\t\t\tsummary: `Worker did not complete: ${bounded.failure.reasonCode}${\n\t\t\t\t\tbounded.failure.detail ? ` — ${bounded.failure.detail}` : \"\"\n\t\t\t\t}`,\n\t\t\t\t...(blockers ? { blockers } : {}),\n\t\t\t},\n\t\t\tlaneStatus: bounded.failure.status,\n\t\t\treasonCode: bounded.failure.reasonCode,\n\t\t\t...(bounded.failure.detail ? { reasonDetail: bounded.failure.detail } : {}),\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst completion = bounded.completion as WorkerCompletion | undefined;\n\tconst completionChangedFilesReport = collectBoundedWorkerClaimChangedFiles(completion?.changedFiles ?? []);\n\tconst mergedChangedFilesReport = collectBoundedWorkerClaimChangedFiles([\n\t\t...liveChangedFiles,\n\t\t...completionChangedFilesReport.values,\n\t]);\n\tconst changedFilesOverflowed =\n\t\tliveChangedFilesReport.overflowed ||\n\t\tcompletionChangedFilesReport.overflowed ||\n\t\tmergedChangedFilesReport.overflowed;\n\tconst completionChangedFiles = mergedChangedFilesReport.values;\n\tconst completionBaseClaim = { ...baseClaim, changedFiles: completionChangedFiles };\n\tif (!completion || completion.stopReason === \"error\" || completion.stopReason === \"aborted\") {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tclaim: { ...completionBaseClaim, status: \"failed\", summary: \"Worker model call failed.\" },\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"model_error\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst parsed = parseWorkerOutput(completion.text);\n\tif (!parsed) {\n\t\tif (hasMalformedWorkerClaimEnvelope(completion.text)) {\n\t\t\treturn finishOutcome({\n\t\t\t\trequest: options.request,\n\t\t\t\tcwd: options.cwd,\n\t\t\t\tclaim: {\n\t\t\t\t\t...completionBaseClaim,\n\t\t\t\t\tstatus: \"failed\",\n\t\t\t\t\tsummary: \"Worker output used a malformed structured claim envelope.\",\n\t\t\t\t},\n\t\t\t\tlaneStatus: \"failed\",\n\t\t\t\treasonCode: \"unparseable_output\",\n\t\t\t\tcostUsd,\n\t\t\t});\n\t\t}\n\t\tconst readOnlyPlainText =\n\t\t\t!options.verificationSubjectTaskId &&\n\t\t\t!writeCapable &&\n\t\t\tcompletion.text.trim().length > 0 &&\n\t\t\tcompletionChangedFiles.length === 0 &&\n\t\t\t!changedFilesOverflowed;\n\t\tif (readOnlyPlainText) {\n\t\t\tconst completionBlockersReport = collectBoundedWorkerClaimBlockers(completion.blockers ?? []);\n\t\t\tconst completionBlockers = completionBlockersReport.overflowed\n\t\t\t\t? [\n\t\t\t\t\t\t...completionBlockersReport.values.slice(0, Math.max(0, MAX_WORKER_CLAIM_BLOCKERS - 1)),\n\t\t\t\t\t\t\"worker blocker report exceeded the durable claim bound; parent review is required\",\n\t\t\t\t\t]\n\t\t\t\t: completionBlockersReport.values;\n\t\t\tconst incompleteNote =\n\t\t\t\tcompletion.stopReason === \"stop\"\n\t\t\t\t\t? \"\"\n\t\t\t\t\t: `\\n\\n[Worker output ended with stop reason '${completion.stopReason}'; verify completeness.]`;\n\t\t\tconst summary = `${completion.text.trim().slice(0, Math.max(0, MAX_WORKER_CLAIM_SUMMARY_CHARS - incompleteNote.length))}${incompleteNote}`;\n\t\t\tconst blocked = completionBlockers.length > 0;\n\t\t\treturn finishOutcome({\n\t\t\t\trequest: options.request,\n\t\t\t\tcwd: options.cwd,\n\t\t\t\tclaim: {\n\t\t\t\t\t...completionBaseClaim,\n\t\t\t\t\tstatus: blocked ? \"blocked\" : \"completed\",\n\t\t\t\t\toutputFormat: \"plain_text\",\n\t\t\t\t\tsummary,\n\t\t\t\t\t...(blocked ? { blockers: completionBlockers } : {}),\n\t\t\t\t},\n\t\t\t\tlaneStatus: blocked ? \"failed\" : \"succeeded\",\n\t\t\t\treasonCode: blocked\n\t\t\t\t\t? \"worker_blocked\"\n\t\t\t\t\t: completion.stopReason === \"stop\"\n\t\t\t\t\t\t? \"worker_completed_plain_text\"\n\t\t\t\t\t\t: \"worker_completed_plain_text_incomplete\",\n\t\t\t\tcostUsd,\n\t\t\t});\n\t\t}\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tclaim: {\n\t\t\t\t...completionBaseClaim,\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tsummary: \"Worker output was not valid structured JSON.\",\n\t\t\t\t...(changedFilesOverflowed\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tblockers: [\n\t\t\t\t\t\t\t\t\"worker changed-file report exceeded the durable claim bound; parent review is required\",\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"unparseable_output\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst evidence = buildWorkerEvidence(options.request, parsed.findings);\n\tif (parsed.actionRejection) {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tclaim: {\n\t\t\t\t...completionBaseClaim,\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tsummary: \"Worker output contained invalid structured actions.\",\n\t\t\t\tblockers: [parsed.actionRejection.reasonCode],\n\t\t\t},\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"unparseable_output\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\tif (options.verificationSubjectTaskId && (!parsed.verdict || parsed.reasonCodes.length === 0)) {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tclaim: {\n\t\t\t\t...completionBaseClaim,\n\t\t\t\tstatus: \"failed\",\n\t\t\t\tsummary: \"Verifier output omitted its typed verdict or reasonCodes.\",\n\t\t\t},\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"invalid_verifier_result\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\tlet changedFiles: string[] = [...completionChangedFiles];\n\tconst completionBlockersReport = collectBoundedWorkerClaimBlockers(completion.blockers ?? []);\n\tconst actionBlockers: string[] = [...completionBlockersReport.values];\n\tif (changedFilesOverflowed) {\n\t\tactionBlockers.push(\"worker changed-file report exceeded the durable claim bound; parent review is required\");\n\t}\n\tif (completionBlockersReport.overflowed) {\n\t\tactionBlockers.push(\"worker blocker report exceeded the durable claim bound; parent review is required\");\n\t}\n\tif (!writeCapable && completionChangedFiles.length > 0) {\n\t\tactionBlockers.push(\"worker reported file changes without a filesystem.write envelope grant\");\n\t}\n\tif (writeCapable && parsed.status !== \"blocked\" && parsed.actions.length > 0 && options.applyActions) {\n\t\t// Runner-side application through the envelope path scope: refusals and failures are\n\t\t// surfaced as blockers so a partially-applied change can never look like clean success.\n\t\tconst applied = options.applyActions(parsed.actions);\n\t\tconst appliedChangedFilesReport = collectBoundedWorkerClaimChangedFiles(applied.changedFiles);\n\t\tconst mergedAppliedChangedFilesReport = collectBoundedWorkerClaimChangedFiles([\n\t\t\t...changedFiles,\n\t\t\t...appliedChangedFilesReport.values,\n\t\t]);\n\t\tchangedFiles = mergedAppliedChangedFilesReport.values;\n\t\tif (appliedChangedFilesReport.overflowed || mergedAppliedChangedFilesReport.overflowed) {\n\t\t\tactionBlockers.push(\"applied changed-file report exceeded the durable claim bound; parent review is required\");\n\t\t}\n\t\tfor (const refusal of applied.refused) {\n\t\t\tactionBlockers.push(`action refused (${refusal.path}): ${refusal.reason}`);\n\t\t}\n\t\tfor (const failure of applied.failed) {\n\t\t\tactionBlockers.push(`action failed (${failure.path}): ${failure.reason}`);\n\t\t}\n\t\tfor (const inspection of applied.inspectionRequired) {\n\t\t\tactionBlockers.push(\n\t\t\t\t`action requires workspace/evidence inspection (${inspection.path}, ${inspection.state}): ${inspection.reasonCode}`,\n\t\t\t);\n\t\t}\n\t} else if (!writeCapable && parsed.actions.length > 0) {\n\t\tactionBlockers.push(\"worker emitted file actions without a filesystem.write envelope grant; nothing was applied\");\n\t}\n\tconst allBlockersReport = collectBoundedWorkerClaimBlockers([...parsed.blockers, ...actionBlockers]);\n\tconst allBlockers = allBlockersReport.overflowed\n\t\t? [\n\t\t\t\t...allBlockersReport.values.slice(0, Math.max(0, MAX_WORKER_CLAIM_BLOCKERS - 1)),\n\t\t\t\t\"worker blocker report exceeded the durable claim bound; parent review is required\",\n\t\t\t]\n\t\t: allBlockersReport.values;\n\tconst claim: WorkerClaim = {\n\t\t...baseClaim,\n\t\tchangedFiles,\n\t\tstatus: parsed.status === \"blocked\" || allBlockers.length > 0 ? \"blocked\" : \"completed\",\n\t\tsummary: parsed.summary,\n\t\t...(allBlockers.length > 0 ? { blockers: allBlockers } : {}),\n\t\t...(evidence ? { evidence } : {}),\n\t\t...(options.verificationSubjectTaskId && parsed.verdict\n\t\t\t? {\n\t\t\t\t\tverification: {\n\t\t\t\t\t\tsubjectTaskId: options.verificationSubjectTaskId,\n\t\t\t\t\t\tverdict: parsed.verdict,\n\t\t\t\t\t\treasonCodes: parsed.reasonCodes,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: {}),\n\t};\n\n\tif (claim.status === \"blocked\") {\n\t\treturn finishOutcome({\n\t\t\trequest: options.request,\n\t\t\tcwd: options.cwd,\n\t\t\tclaim,\n\t\t\tlaneStatus: \"failed\",\n\t\t\treasonCode: \"worker_blocked\",\n\t\t\tcostUsd,\n\t\t});\n\t}\n\n\tconst overBudget = options.maxUsd !== undefined && costUsd > options.maxUsd;\n\treturn finishOutcome({\n\t\trequest: options.request,\n\t\tcwd: options.cwd,\n\t\tclaim,\n\t\tlaneStatus: overBudget ? \"budget_exhausted\" : \"succeeded\",\n\t\treasonCode: overBudget\n\t\t\t? \"cost_budget_exceeded\"\n\t\t\t: claim.verification\n\t\t\t\t? claim.verification.verdict === \"accepted\"\n\t\t\t\t\t? \"verification_accepted\"\n\t\t\t\t\t: \"verification_rejected\"\n\t\t\t\t: \"worker_completed\",\n\t\tcostUsd,\n\t});\n}\n"]}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { AttemptStatus, OrchestrationTaskStatus, WorkerRole } from "../orchestration/contracts.ts";
|
|
2
|
+
import type { TaskRuntimeProjection } from "../orchestration/task-runtime.ts";
|
|
3
|
+
/** Keep task views within the same durable session fan-out ceiling as the worker fleet. */
|
|
4
|
+
export declare const MAX_WORKER_TASK_VIEW_ENTRIES: number;
|
|
5
|
+
/** Bound model-facing serialization independently of task-count and field-count limits. */
|
|
6
|
+
export declare const MAX_WORKER_TASK_VIEW_BYTES: number;
|
|
7
|
+
export interface WorkerTaskAttemptView {
|
|
8
|
+
agentId?: string;
|
|
9
|
+
status: AttemptStatus;
|
|
10
|
+
reasonCode?: string;
|
|
11
|
+
retry?: {
|
|
12
|
+
retriesUsed: number;
|
|
13
|
+
notBefore: string;
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
export interface WorkerTaskView {
|
|
17
|
+
taskId: string;
|
|
18
|
+
title: string;
|
|
19
|
+
role: WorkerRole;
|
|
20
|
+
status: OrchestrationTaskStatus;
|
|
21
|
+
dependsOn: readonly string[];
|
|
22
|
+
verificationOfTaskId?: string;
|
|
23
|
+
verificationOutcome?: {
|
|
24
|
+
verifierTaskId: string;
|
|
25
|
+
verdict: VerificationVerdict;
|
|
26
|
+
reasonCode: string;
|
|
27
|
+
};
|
|
28
|
+
latestAttempt?: WorkerTaskAttemptView;
|
|
29
|
+
}
|
|
30
|
+
type VerificationVerdict = "accepted" | "rejected" | "inconclusive";
|
|
31
|
+
export interface WorkerTaskSessionView {
|
|
32
|
+
totalTasks: number;
|
|
33
|
+
omittedTaskCount: number;
|
|
34
|
+
tasks: readonly WorkerTaskView[];
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Derive a provider-neutral, bounded team-task read model from the durable runtime projection.
|
|
38
|
+
* Every returned field is selected explicitly so execution authority and provider diagnostics
|
|
39
|
+
* cannot cross this read boundary through object spread.
|
|
40
|
+
*/
|
|
41
|
+
export declare function projectWorkerTaskSessionView(snapshot: TaskRuntimeProjection): WorkerTaskSessionView;
|
|
42
|
+
export {};
|
|
43
|
+
//# sourceMappingURL=worker-task-view.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"worker-task-view.d.ts","sourceRoot":"","sources":["../../../src/core/delegation/worker-task-view.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,uBAAuB,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AASxG,O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