@tea-agent/loop-agent 0.1.0-fe-test.2 → 0.1.0-fe-test.4
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/AGENTS.md +6 -3
- package/CHANGELOG.md +607 -93
- package/README.md +11 -5
- package/bin/loop-agent.js +7 -3
- package/dist/adapters/context-transfer/optional-pi-handoff.js +31 -0
- package/dist/adapters/context-transfer/pi-session.js +61 -0
- package/dist/application/dag/generate-task-dag.js +90 -21
- package/dist/application/dag/run-dag.js +41 -0
- package/dist/application/task-lifecycle/advance.js +40 -5
- package/dist/application/task-lifecycle/observe.js +171 -17
- package/dist/application/task-lifecycle/plan-transitions.js +42 -7
- package/dist/application/task-lifecycle/recommendations.js +13 -2
- package/dist/build-stamp.json +3 -3
- package/dist/cli/command-definitions.js +44 -10
- package/dist/cli/program.js +82 -6
- package/dist/cli/update/notifier.js +2 -2
- package/dist/cli/update/runtime-activity.js +1 -29
- package/dist/cli.js +2 -1
- package/dist/commands/client-recovery.js +11 -36
- package/dist/commands/dag-artifact.js +284 -0
- package/dist/commands/dag-context.js +184 -0
- package/dist/commands/dag-follow-up.js +138 -0
- package/dist/commands/dag-rerun-task.js +2 -0
- package/dist/commands/dag-rerun.js +261 -2
- package/dist/commands/init-model-catalog.js +486 -0
- package/dist/commands/init-upgrade.js +265 -97
- package/dist/commands/init.js +455 -28
- package/dist/commands/inspect-next.js +8 -0
- package/dist/commands/task-advance.js +73 -1
- package/dist/commands/task-source-prepare.js +5 -0
- package/dist/commands/task-status.js +1 -0
- package/dist/executors/dag-pi-executor.js +4321 -231
- package/dist/executors/pi-event-serializer.js +42 -1
- package/dist/executors/pi-executor.js +70 -6
- package/dist/executors/pi-extension-resolver.js +245 -0
- package/dist/executors/pi-playwright-cli-tool.js +74 -28
- package/dist/executors/pi-read-budget-policy.js +239 -0
- package/dist/executors/pi-sdk-executor.js +263 -59
- package/dist/executors/pi-writer-tool-policy.js +57 -1
- package/dist/executors/shell-executor.js +1443 -240
- package/dist/executors/shell-write-guard.js +14 -0
- package/dist/executors/workspace-write-snapshot.js +68 -0
- package/dist/governance/checks.js +1 -0
- package/dist/{worker → infrastructure}/console/app-data.js +4 -0
- package/dist/infrastructure/console/artifact-revision-store.js +430 -0
- package/dist/infrastructure/console/context-export-store.js +160 -0
- package/dist/infrastructure/console/dir-lock.js +132 -0
- package/dist/infrastructure/console/operation-store.js +417 -0
- package/dist/infrastructure/harness/artifact-store.js +10 -1
- package/dist/infrastructure/harness/atomic-write.js +35 -2
- package/dist/shared/context-transfer/artifact-revision.js +172 -0
- package/dist/shared/context-transfer.js +418 -0
- package/dist/shared/dag-failure-category.js +150 -0
- package/dist/shared/dag-prompt-override.js +27 -0
- package/dist/shared/openspec-spec.js +70 -4
- package/dist/shared/operator/capabilities.js +65 -4
- package/dist/shared/operator/safe-run-summary.js +1 -0
- package/dist/shared/path-safety.js +93 -0
- package/dist/shared/pi-context-pressure/checkpoint.js +116 -0
- package/dist/shared/pi-context-pressure/compaction-policy.js +151 -0
- package/dist/shared/pi-context-pressure/env.js +58 -0
- package/dist/shared/pi-context-pressure/extension.js +100 -0
- package/dist/shared/pi-context-pressure/index.js +7 -0
- package/dist/shared/pi-context-pressure/overflow.js +252 -0
- package/dist/shared/pi-context-pressure/sift-bridge.js +386 -0
- package/dist/shared/pi-context-pressure/telemetry.js +51 -0
- package/dist/shared/playwright-cli-command-policy.js +15 -0
- package/dist/shared/preview.js +28 -4
- package/dist/shared/update/console-notifier.js +100 -0
- package/dist/{cli → shared}/update/npm-client.js +70 -15
- package/dist/{cli → shared}/update/state.js +41 -13
- package/dist/task/config-types.js +125 -6
- package/dist/task/contract/adopt.js +4 -0
- package/dist/task/contract/apply.js +11 -1
- package/dist/task/contract/constants.js +3 -0
- package/dist/task/contract/diff.js +26 -0
- package/dist/task/contract/hash.js +3 -0
- package/dist/task/contract/import-revision.js +4 -0
- package/dist/task/contract/observe.js +25 -4
- package/dist/task/contract/paths.js +2 -1
- package/dist/task/contract/project.js +23 -1
- package/dist/task/contract/schema.js +9 -1
- package/dist/task/contract/transaction.js +12 -0
- package/dist/task/frontend-project-capability.js +203 -20
- package/dist/task/runtime.js +5 -2
- package/dist/task/source-prepare/build-draft.js +18 -3
- package/dist/task/source-prepare/completeness.js +188 -0
- package/dist/task/source-prepare/fragment-inventory.js +513 -0
- package/dist/task/source-prepare/index.js +3 -0
- package/dist/task/source-prepare/ledger-reconciliation.js +127 -0
- package/dist/task/source-prepare/ledger-review.js +214 -0
- package/dist/task/source-prepare/ledger.js +545 -0
- package/dist/task/source-prepare/parse-intent.js +24 -4
- package/dist/task/source-prepare/prepare.js +368 -2
- package/dist/task/source-prepare/semantic-intake.js +25 -5
- package/dist/task/source-prepare/source-fidelity-pi.js +384 -0
- package/dist/task/source-prepare/types.js +22 -0
- package/dist/task/source-references.js +22 -1
- package/dist/task/task-demand-routing.js +3 -0
- package/dist/worker/cli.js +18 -2
- package/dist/worker/console/chat/assistant-content.js +7 -0
- package/dist/worker/console/chat/chat-event-store.js +159 -18
- package/dist/worker/console/chat/chat-ui-policy.js +4 -2
- package/dist/worker/console/chat/context-panel.js +7 -0
- package/dist/worker/console/chat/deferred-turn.js +103 -0
- package/dist/worker/console/chat/goal-round-driver.js +72 -0
- package/dist/worker/console/chat/goals.js +300 -0
- package/dist/worker/console/chat/model-resolver.js +7 -4
- package/dist/worker/console/chat/operation-card.js +8 -1
- package/dist/worker/console/chat/pi-console-config.js +81 -10
- package/dist/worker/console/chat/pi-runtime.js +868 -30
- package/dist/worker/console/chat/provider-error.js +99 -0
- package/dist/worker/console/chat/repo-browser.js +101 -12
- package/dist/worker/console/chat/resource-preferences-store.js +1 -1
- package/dist/worker/console/chat/routes.js +1451 -145
- package/dist/worker/console/chat/sdd-data-alignment.js +222 -0
- package/dist/worker/console/chat/semantic-activity.js +25 -24
- package/dist/worker/console/chat/session-catalog.js +50 -0
- package/dist/worker/console/chat/session-stats.js +275 -0
- package/dist/worker/console/chat/session-store.js +348 -76
- package/dist/worker/console/chat/shortcuts.js +26 -3
- package/dist/worker/console/chat/sift-bridge.js +1 -0
- package/dist/worker/console/chat/todos.js +115 -0
- package/dist/worker/console/chat/tool-preview.js +42 -0
- package/dist/worker/console/chat/turn-process.js +185 -112
- package/dist/worker/console/chat/user-questions.js +266 -0
- package/dist/worker/console/chat/workspace-landing.js +79 -0
- package/dist/worker/console/console-handoff.js +82 -0
- package/dist/worker/console/console-update-and-init.js +115 -0
- package/dist/worker/console/console-update-runtime.js +84 -0
- package/dist/worker/console/context-transfer-diagnostics.js +198 -0
- package/dist/worker/console/dag-confirmation.js +1 -1
- package/dist/worker/console/dag-execution-receipt.js +54 -3
- package/dist/worker/console/doctor.js +1 -1
- package/dist/worker/console/draft-store.js +50 -1
- package/dist/worker/console/frontend-human-decision-adapter.js +19 -0
- package/dist/worker/console/frontend-split-operation-adapter.js +20 -0
- package/dist/worker/console/human-gate-token.js +1 -1
- package/dist/worker/console/index.js +6 -3
- package/dist/worker/console/inspect-split.js +18 -0
- package/dist/worker/console/interview/assessment.js +1 -1
- package/dist/worker/console/interview/session.js +1 -1
- package/dist/worker/console/native-directory-picker.js +13 -0
- package/dist/worker/console/operation-run-facts.js +19 -3
- package/dist/worker/console/operation-runner.js +45 -4
- package/dist/worker/console/operation-sse.js +1 -1
- package/dist/worker/console/operation-wait.js +1 -1
- package/dist/worker/console/operator-actions.js +534 -15
- package/dist/worker/console/operator-selection.js +6 -2
- package/dist/worker/console/operator-surface-health.js +2 -1
- package/dist/worker/console/operator-user-error.js +171 -2
- package/dist/worker/console/pi-plugins.catalog.json +73658 -0
- package/dist/worker/console/pi-plugins.js +238 -0
- package/dist/worker/console/pi-readiness.js +7 -6
- package/dist/worker/console/prd-intake-bridge.js +13 -0
- package/dist/worker/console/recovery-cta.js +4 -4
- package/dist/worker/console/recovery-error-copy.js +4 -4
- package/dist/worker/console/routes.js +1231 -10
- package/dist/worker/console/security.js +102 -13
- package/dist/worker/console/server.js +762 -159
- package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-BmOEx0gA.js → abnfDiagram-N423BO3Z-BZogYNl1.js} +1 -1
- package/dist/worker/console/static/assets/{arc-BGiVVe8b.js → arc-DcJTLe2v.js} +1 -1
- package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-nDdu4rgJ.js → architectureDiagram-T3A2C74G-B39EQQ9n.js} +1 -1
- package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-Bb5u0BWf.js → blockDiagram-VBNYF7ZC-CitCGV56.js} +1 -1
- package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-BlhC0j94.js → c4Diagram-5PPSVZJV-rvWuOHLG.js} +1 -1
- package/dist/worker/console/static/assets/channel-CXqdP5pW.js +1 -0
- package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-Ai8_qQXI.js → chunk-2GRJ4B5K-DGXplIJs.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-B9gyCjqX.js → chunk-2Q5K7J3B-ur9OqjPn.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-5RXB4S5H-Bzbj3zGH.js → chunk-5RXB4S5H-D1KqU_Vi.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-5VM5RSS4-BT415PvT.js → chunk-5VM5RSS4-BlVZrbtM.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-D_A5_5QL.js → chunk-6Q2QTUOP-BAzz3nQy.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-GF5L2VYU-srJkaP3f.js → chunk-GF5L2VYU-CP_nYuCV.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-JWPE2WC7-UYGvEP4l.js → chunk-JWPE2WC7-CWvKQ80X.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-KBJHAD2P-B8luBrrz.js → chunk-KBJHAD2P-CyUki8wp.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-RYQCIY6F-DN7wXZSq.js → chunk-RYQCIY6F-5NYzNKfY.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-XXDRQBXY-DXKyMuKS.js → chunk-XXDRQBXY-DHdUgjS-.js} +1 -1
- package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-D9C3agF7.js +1 -0
- package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-D9C3agF7.js +1 -0
- package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-dqvoynXj.js → cose-bilkent-JH36ORCC-ANQ5g_t6.js} +1 -1
- package/dist/worker/console/static/assets/{cynefin-VYW2F7L2--PcyL34A.js → cynefin-VYW2F7L2-CruT_4-0.js} +1 -1
- package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-DvWs_hTY.js → cynefinDiagram-MW4NZA55-rbFo77ID.js} +1 -1
- package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-DxeIxbyO.js → dagre-VZM6K2ZE-asstxBQs.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-7IWD3JNH-DPCG61Of.js → diagram-7IWD3JNH-DzTyBZwI.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-CmuU50-U.js → diagram-B4RE2ZJO-gw8ccH3B.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-LBJQPF4R-B61XLD_v.js → diagram-LBJQPF4R-B8RpZzOf.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-Q27KOJAE-BB7HTRRY.js → diagram-Q27KOJAE-B1zJkCS9.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-UB23O5K3-DvkboAIp.js → diagram-UB23O5K3-B6JLWZmO.js} +1 -1
- package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-BdJ_y1fL.js → ebnfDiagram-BXEA7PRR-q2iZP-Ps.js} +1 -1
- package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-9bUBZTRi.js → erDiagram-JOGREHBK-B3dbbktQ.js} +1 -1
- package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-Dw4L4RBa.js → flowDiagram-UKHOOZJN-C-zc6-kB.js} +1 -1
- package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-Jr82N_QP.js → ganttDiagram-PKOTCBZU-BSolnot9.js} +1 -1
- package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-DAz9wFLr.js → gitGraphDiagram-DS77QQ5N-Bo8jGxTk.js} +1 -1
- package/dist/worker/console/static/assets/index-CAZ2fC_X.css +1 -0
- package/dist/worker/console/static/assets/index-DhfjOafu.js +449 -0
- package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-CBB5Np7y.js → infoDiagram-6WML65LV-DQaZqJOH.js} +1 -1
- package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-D8IOp94y.js → ishikawaDiagram-WSZJBQD7-DsdX1WnE.js} +1 -1
- package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-Dgd3AHGG.js → journeyDiagram-NVQOT4AX-CP5EYDZL.js} +1 -1
- package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-BmYOxLE9.js → kanban-definition-27J2QSJJ-DAm14Dr8.js} +1 -1
- package/dist/worker/console/static/assets/{linear-DfYTEF6J.js → linear-gZECoLc5.js} +1 -1
- package/dist/worker/console/static/assets/{mermaid.core-BjuFPRqa.js → mermaid.core-BRJNIM6p.js} +5 -5
- package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-CLyUViGd.js → mindmap-definition-FAOFIHXS-Cja3kLkR.js} +1 -1
- package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-BvX2Di4-.js → pegDiagram-VL7TDLO6-22ZGFisL.js} +1 -1
- package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BFj0_OLv.js → pieDiagram-7S7Q4E2Y-BXin0Y1o.js} +1 -1
- package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-BIUrD_hx.js → quadrantDiagram-CIZ2JOQS-Cw6T69Yt.js} +1 -1
- package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-CHBB48fj.js → railroadDiagram-AXF67PYL-C1-gTieN.js} +1 -1
- package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-sJrYw2Sf.js → requirementDiagram-LRYGKXZP--H5N2iI1.js} +1 -1
- package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-BzHH6fPR.js → sankeyDiagram-W5VNT64P-CgWAPeRz.js} +1 -1
- package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-7QCnelCt.js → sequenceDiagram-SI44F4Z6-CrKqzGvt.js} +1 -1
- package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-sDYSxn72.js → sizeCapture-X5ZJPWSS-BB3wG06K.js} +1 -1
- package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-XpiUdwzm.js → stateDiagram-OKZ733FA-DjsGgdgY.js} +1 -1
- package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Tp7V0U4q.js +1 -0
- package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-DvqgNPzD.js → swimlanes-SLNWSIFB-DYKEbvAR.js} +2 -2
- package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-DUZWZWi8.js +8 -0
- package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-2TyOYNx0.js → timeline-definition-Z64GVDOM-eQOb5k9Y.js} +1 -1
- package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-B-nM6wM2.js → vennDiagram-T6HMQDX7-B2-l9FIu.js} +1 -1
- package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-B86wPdbr.js → wardleyDiagram-T6FBY63Y-BX2Cda3l.js} +1 -1
- package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-Dr1C4AQz.js → xychartDiagram-ELKLHX3M-D9S892ph.js} +1 -1
- package/dist/worker/console/static/index.html +7 -2
- package/dist/worker/console/static-src/active-run-badge.js +17 -0
- package/dist/worker/console/static-src/app/console-types.js +68 -4
- package/dist/worker/console/static-src/app/useConsoleShell.js +30 -12
- package/dist/worker/console/static-src/app/useOperatorActions.js +43 -7
- package/dist/worker/console/static-src/app/useRecoveryActions.js +2 -2
- package/dist/worker/console/static-src/app/useRecoveryConsole.js +45 -10
- package/dist/worker/console/static-src/app/useRunProgress.js +54 -0
- package/dist/worker/console/static-src/app/useTaskWizard.js +74 -2
- package/dist/worker/console/static-src/night/useNightBoard.js +8 -5
- package/dist/worker/console/static-src/operator-chat/cards/failure-category-advice.js +25 -0
- package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +264 -13
- package/dist/worker/console/static-src/operator-chat/compaction-message.js +113 -0
- package/dist/worker/console/static-src/operator-chat/dag-progress-link.js +22 -0
- package/dist/worker/console/static-src/operator-chat/details-dag-actions.js +122 -0
- package/dist/worker/console/static-src/operator-chat/input-history.js +78 -0
- package/dist/worker/console/static-src/operator-chat/mutation-gate.js +1 -1
- package/dist/worker/console/static-src/operator-chat/open-preview-in-browser.js +338 -0
- package/dist/worker/console/static-src/operator-chat/refs.js +3 -0
- package/dist/worker/console/static-src/operator-chat/runtime-selection-labels.js +27 -0
- package/dist/worker/console/static-src/operator-chat/runtime-snapshot-store.js +10 -0
- package/dist/worker/console/static-src/operator-chat/spatial-overlay.js +1 -2
- package/dist/worker/console/static-src/operator-chat/turn-stream-controller.js +33 -1
- package/dist/worker/console/static-src/operator-chat/turn-submission.js +55 -0
- package/dist/worker/console/static-src/operator-chat/useChatSessions.js +448 -109
- package/dist/worker/console/static-src/operator-chat/useChatStream.js +344 -27
- package/dist/worker/console/static-src/operator-chat/useChatThread.js +323 -11
- package/dist/worker/console/static-src/operator-chat/useComposer.js +45 -4
- package/dist/worker/console/static-src/operator-chat/useRepoBrowser.js +97 -13
- package/dist/worker/console/static-src/operator-chat/useRuntimeControls.js +57 -9
- package/dist/worker/console/static-src/operator-chat/useRuntimeSnapshot.js +8 -2
- package/dist/worker/console/static-src/operator-chat/useWorkspaceBrowserGate.js +4 -0
- package/dist/worker/console/static-src/operator-chat/workspace-layout-mode.js +3 -3
- package/dist/worker/console/static-src/operator-chat/workspace-reorder.js +18 -0
- package/dist/worker/console/static-src/pages/tasks/run-id-resolution.js +79 -0
- package/dist/worker/console/static-src/pages/tasks/run-ownership-verify.js +23 -0
- package/dist/worker/console/static-src/pages/tasks/run-panel-progress.js +216 -0
- package/dist/worker/console/static-src/shell/console-update-reload.js +52 -0
- package/dist/worker/console/static-src/shell/useWorkspaces.js +415 -0
- package/dist/worker/console/static-src/shell/workspace-route.js +356 -0
- package/dist/worker/console/workspace-context.js +399 -0
- package/dist/worker/console/workspace-registry.js +487 -0
- package/dist/worker/continuation/worker-continuation.js +278 -0
- package/dist/worker/loop-agent/loop-agent-client.js +7 -3
- package/dist/worker/materialize/frontend-split-task-materializer.js +72 -0
- package/dist/worker/materialize/harness-task-lineage.js +5 -2
- package/dist/worker/observability/init-runtime-activity.js +26 -0
- package/dist/worker/observability/read-model.js +26 -0
- package/dist/worker/observe/health.js +1 -1
- package/dist/worker/observe/node-input.js +160 -3
- package/dist/worker/observe/node-process.js +377 -0
- package/dist/worker/observe/node-transparency.js +572 -0
- package/dist/worker/observe/routes.js +278 -3
- package/dist/worker/observe/server.js +4 -0
- package/dist/worker/observe/shell-handler-keys.js +34 -0
- package/dist/worker/observe/static/api.js +154 -4
- package/dist/worker/observe/static/app.js +18 -70
- package/dist/worker/observe/static/constants.js +26 -19
- package/dist/worker/observe/static/dag-context-reason-labels.d.ts +9 -0
- package/dist/worker/observe/static/dag-context-reason-labels.js +139 -0
- package/dist/worker/observe/static/dag-helpers.js +4 -2
- package/dist/worker/observe/static/dag-history-labels.js +5 -0
- package/dist/worker/observe/static/dag-inspector-humanize.d.ts +16 -0
- package/dist/worker/observe/static/dag-inspector-humanize.js +339 -0
- package/dist/worker/observe/static/dag-node-purpose.d.ts +6 -0
- package/dist/worker/observe/static/dag-node-purpose.js +208 -0
- package/dist/worker/observe/static/format.js +60 -0
- package/dist/worker/observe/static/index.html +10 -5
- package/dist/worker/observe/static/inspect-bootstrap.d.ts +8 -0
- package/dist/worker/observe/static/inspect-bootstrap.js +57 -0
- package/dist/worker/observe/static/inspect-workspace.js +374 -0
- package/dist/worker/observe/static/kpi.js +2 -2
- package/dist/worker/observe/static/markdown-render.js +20 -1
- package/dist/worker/observe/static/operator-chrome.css +168 -24
- package/dist/worker/observe/static/operator-chrome.d.ts +30 -5
- package/dist/worker/observe/static/operator-chrome.js +354 -101
- package/dist/worker/observe/static/prompt-restart-candidates.d.ts +18 -0
- package/dist/worker/observe/static/prompt-restart-candidates.js +38 -0
- package/dist/worker/observe/static/relations.js +7 -7
- package/dist/worker/observe/static/router.d.ts +57 -0
- package/dist/worker/observe/static/router.js +67 -1
- package/dist/worker/observe/static/run-processing.js +4 -2
- package/dist/worker/observe/static/shell-chrome.js +2 -2
- package/dist/worker/observe/static/state.d.ts +50 -0
- package/dist/worker/observe/static/state.js +191 -1
- package/dist/worker/observe/static/styles.css +1720 -86
- package/dist/worker/observe/static/views/dag-graph.js +5 -3
- package/dist/worker/observe/static/views/dag-inspector.js +2601 -188
- package/dist/worker/observe/static/views/dag.d.ts +13 -0
- package/dist/worker/observe/static/views/dag.js +39 -18
- package/dist/worker/observe/static/views/dags.js +10 -6
- package/dist/worker/observe/static/views/dashboard.js +18 -8
- package/dist/worker/observe/static/views/failures.js +5 -2
- package/dist/worker/observe/static/views/night.js +2 -2
- package/dist/worker/observe/static/views/pool.js +8 -2
- package/dist/worker/observe/static/views/run.js +15 -4
- package/dist/worker/observe/static/views/session-timeline.js +386 -25
- package/dist/worker/observe/static/views/task.js +63 -3
- package/dist/worker/outcomes/adapters.js +19 -0
- package/dist/worker/outcomes/types.js +1 -0
- package/dist/worker/pool/attempt-lease.js +97 -66
- package/dist/worker/pool/begin-attempt-with-lease.js +1 -0
- package/dist/worker/pool/reconcile.js +46 -1
- package/dist/worker/pool/run-store.js +2 -0
- package/dist/worker/pool/state-projection.js +2 -0
- package/dist/worker/task-spec/workflow-routing.js +8 -3
- package/dist/workflows/dag/artifact-bindings.js +149 -0
- package/dist/workflows/dag/artifact-revision-schema-registry.js +31 -0
- package/dist/workflows/dag/backend-test-case-coverage-analysis.js +470 -31
- package/dist/workflows/dag/backend-test-markdown-workflow.js +189 -2
- package/dist/workflows/dag/backend-test-plan-protocol.js +210 -0
- package/dist/workflows/dag/backend-test-pytest-collection.js +168 -16
- package/dist/workflows/dag/backend-test-result-contract.js +5 -1
- package/dist/workflows/dag/backend-test-scenario-param.js +506 -73
- package/dist/workflows/dag/backend-test-scenario-partitions.js +135 -2
- package/dist/workflows/dag/backend-test-writer-completeness.js +131 -28
- package/dist/workflows/dag/budget-enforcement.js +10 -0
- package/dist/workflows/dag/context-receipt.js +305 -0
- package/dist/workflows/dag/context-transfer/context-bundle.js +423 -0
- package/dist/workflows/dag/context-transfer/operator-actions.js +61 -0
- package/dist/workflows/dag/context-transfer/renderers.js +93 -0
- package/dist/workflows/dag/contract-output-registry.js +15 -0
- package/dist/workflows/dag/contract-validator-registrations.js +1 -2
- package/dist/workflows/dag/convergence/controller.js +141 -0
- package/dist/workflows/dag/dag-retry-schema.js +138 -0
- package/dist/workflows/dag/dynamic-runtime/loop-until.js +1 -1
- package/dist/workflows/dag/dynamic-runtime/map.js +2 -1
- package/dist/workflows/dag/failure-category.js +7 -116
- package/dist/workflows/dag/frontend-closeout.js +221 -0
- package/dist/workflows/dag/frontend-design-policy.js +400 -0
- package/dist/workflows/dag/frontend-human-decision.js +182 -0
- package/dist/workflows/dag/frontend-implementation-contract.js +1377 -141
- package/dist/workflows/dag/frontend-plan-render.js +26 -1
- package/dist/workflows/dag/frontend-prewrite-gate.js +376 -318
- package/dist/workflows/dag/frontend-provider-capability-matrix.js +159 -0
- package/dist/workflows/dag/frontend-recovery-capsule.js +455 -0
- package/dist/workflows/dag/frontend-recovery-controller.js +226 -0
- package/dist/workflows/dag/frontend-recovery-lineage.js +178 -0
- package/dist/workflows/dag/frontend-recovery-plan.js +21 -10
- package/dist/workflows/dag/frontend-recovery-run.js +166 -34
- package/dist/workflows/dag/frontend-repair.js +7 -424
- package/dist/workflows/dag/frontend-review-context.js +348 -20
- package/dist/workflows/dag/frontend-review-findings.js +270 -0
- package/dist/workflows/dag/frontend-risk.js +15 -2
- package/dist/workflows/dag/frontend-shadow-dual-write.js +941 -0
- package/dist/workflows/dag/frontend-shape-capsule-store.js +191 -0
- package/dist/workflows/dag/frontend-shape-facts.js +419 -0
- package/dist/workflows/dag/frontend-shape.js +435 -0
- package/dist/workflows/dag/frontend-source-fidelity-ledger.js +108 -0
- package/dist/workflows/dag/frontend-split-application-service.js +203 -0
- package/dist/workflows/dag/frontend-split-orchestrator.js +899 -0
- package/dist/workflows/dag/frontend-test-case-checklist.js +53 -5
- package/dist/workflows/dag/frontend-test-case-manifest.js +11 -4
- package/dist/workflows/dag/frontend-test-case-quality.js +11 -16
- package/dist/workflows/dag/frontend-test-environment-probe.js +230 -0
- package/dist/workflows/dag/frontend-test-html-report.js +3 -1
- package/dist/workflows/dag/frontend-test-l5-report.js +3 -1
- package/dist/workflows/dag/frontend-test-layout.js +159 -0
- package/dist/workflows/dag/frontend-test-markdown.js +61 -0
- package/dist/workflows/dag/frontend-test-rerun-candidates.js +103 -0
- package/dist/workflows/dag/frontend-test-result-contract.js +188 -42
- package/dist/workflows/dag/frontend-test-standard-scenarios.js +70 -0
- package/dist/workflows/dag/frontend-typed-event-store.js +452 -0
- package/dist/workflows/dag/frontend-typed-event-transaction.js +180 -0
- package/dist/workflows/dag/frontend-verification-trace.js +281 -29
- package/dist/workflows/dag/frontend-worktree-diff.js +250 -17
- package/dist/workflows/dag/frontend-writer-admission.js +319 -0
- package/dist/workflows/dag/frontend-writer-rollback.js +32 -0
- package/dist/workflows/dag/frontend-writer-status.js +256 -0
- package/dist/workflows/dag/init-hybrid.js +1675 -721
- package/dist/workflows/dag/interrupt-request.js +10 -3
- package/dist/workflows/dag/lifecycle.js +3 -3
- package/dist/workflows/dag/node-execution.js +1141 -32
- package/dist/workflows/dag/path-safety.js +1 -0
- package/dist/workflows/dag/prompt.js +158 -7
- package/dist/workflows/dag/recovery-lease.js +170 -0
- package/dist/workflows/dag/report.js +37 -1
- package/dist/workflows/dag/rerun-feedback.js +526 -0
- package/dist/workflows/dag/rerun-plan.js +790 -28
- package/dist/workflows/dag/rerun-run.js +700 -21
- package/dist/workflows/dag/rerun-task.js +311 -14
- package/dist/workflows/dag/retry-policy.js +336 -101
- package/dist/workflows/dag/runner.js +596 -121
- package/dist/workflows/dag/scheduler.js +133 -20
- package/dist/workflows/dag/skill-snapshot.js +17 -0
- package/dist/workflows/dag/structured-output-repair.js +712 -0
- package/dist/workflows/dag/types.js +585 -31
- package/dist/workflows/dag/validate.js +93 -32
- package/docs/README.md +2 -0
- package/docs/architecture/evolution.md +45 -0
- package/docs/architecture/runtime-boundaries.md +8 -7
- package/docs/architecture/worker-and-feature.md +1 -1
- package/docs/examples/README.md +5 -0
- package/docs/init-surface.manifest.json +36 -12
- package/docs/operations/README.md +1 -1
- package/docs/operations/local-development-environment.md +22 -5
- package/docs/skills/vetted-skill-registry.md +16 -0
- package/docs/templates/README.md +4 -2
- package/docs/templates/agent-dag-report.schema.json +8 -2
- package/docs/templates/agent-dag.schema.json +95 -1
- package/docs/templates/backend-test-dag.json +278 -244
- package/docs/templates/frontend-implementation-contract.schema.json +684 -24
- package/docs/templates/frontend-implementation-dag.json +89 -0
- package/docs/templates/frontend-test-case-checklist.md +2 -2
- package/docs/templates/frontend-test-dag.json +8 -10
- package/docs/templates/frontend-test-dag.retrieve-context.prompt.md +1 -1
- package/docs/templates/init-managed-agents.md +13 -3
- package/docs/templates/product-line/task.yaml +1 -1
- package/docs/templates/spec-registry.schema.json +45 -0
- package/harness.json +2 -2
- package/package.json +19 -5
- package/scripts/next-info.mjs +356 -0
- package/scripts/next-publish-gate.mjs +238 -0
- package/scripts/release-source-binding.mjs +251 -0
- package/skills/analyze-product-requirements/SKILL.md +8 -5
- package/skills/analyze-product-requirements/references/acceptance-criteria.md +1 -1
- package/skills/analyze-product-requirements/references/clarification-and-knowledge.md +10 -6
- package/skills/analyze-product-requirements/references/example.md +50 -0
- package/skills/analyze-product-requirements/references/forward-test-cases.md +11 -7
- package/skills/analyze-product-requirements/references/kb-integration.md +5 -5
- package/skills/analyze-product-requirements/references/product-analysis-schema.md +8 -4
- package/skills/analyze-product-requirements/references/product-requirement-schema.md +2 -2
- package/skills/analyze-product-requirements/references/requirement-clarification-schema.md +1 -1
- package/skills/analyze-product-requirements/scripts/test-validators.mjs +11 -1
- package/skills/analyze-product-requirements/scripts/validate-product-analysis.mjs +20 -1
- package/skills/analyze-product-requirements/scripts/validate-requirement-clarification.mjs +9 -0
- package/skills/codebase-scout/SKILL.md +1 -1
- package/skills/fe-test-ui-scout/SKILL.md +65 -0
- package/skills/fe-test-ui-scout/references/ledger-schema.md +62 -0
- package/skills/fe-test-ui-scout/references/recon-protocol.md +54 -0
- package/skills/frontend-bounded-implement/SKILL.md +15 -14
- package/skills/frontend-bounded-implement/references/code-standards.md +19 -0
- package/skills/frontend-contract/SKILL.md +23 -0
- package/skills/frontend-contract/references/contract-protocol.md +34 -0
- package/skills/frontend-design-review/SKILL.md +22 -41
- package/skills/frontend-plan/SKILL.md +26 -0
- package/skills/frontend-plan/references/decision-contract.md +37 -0
- package/skills/frontend-plan/references/design-decisions.md +17 -0
- package/skills/frontend-review/SKILL.md +20 -15
- package/skills/frontend-review/references/review-findings.md +6 -7
- package/skills/frontend-scout/SKILL.md +25 -0
- package/skills/frontend-scout/references/design-evidence.md +16 -0
- package/skills/frontend-scout/references/scout-evidence.md +23 -0
- package/skills/frontend-verification/SKILL.md +1 -1
- package/skills/improve-codebase-architecture/SKILL.md +81 -0
- package/skills/improve-codebase-architecture/deepening.md +37 -0
- package/skills/improve-codebase-architecture/html-report.md +123 -0
- package/skills/improve-codebase-architecture/interface-design.md +44 -0
- package/skills/improve-codebase-architecture/language.md +53 -0
- package/skills/loop-agent/references/command-reference.md +32 -4
- package/skills/loop-agent/references/hybrid-dag.md +9 -2
- package/skills/playwright-cli/SKILL.md +23 -1
- package/skills/playwright-cli-case-generator/SKILL.md +50 -13
- package/dist/worker/console/operation-store.js +0 -169
- package/dist/worker/console/static/assets/channel-Tl-FkUqr.js +0 -1
- package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-BaehtRk4.js +0 -1
- package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-BaehtRk4.js +0 -1
- package/dist/worker/console/static/assets/index-B7Y-0g3J.css +0 -1
- package/dist/worker/console/static/assets/index-DkCrqaYg.js +0 -325
- package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-eEhq2A8Y.js +0 -1
- package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-la8AC7fo.js +0 -8
- package/dist/worker/console/static-src/operator-chat/activity-rail-presentation.js +0 -73
- package/dist/worker/console/static-src/operator-chat/useActivityRailTransition.js +0 -59
- package/skills/frontend-implementation/SKILL.md +0 -52
- package/skills/frontend-implementation/references/code-standards.md +0 -33
- package/skills/frontend-implementation/references/design-spec.md +0 -56
- package/skills/frontend-implementation/references/node-contracts.md +0 -31
- /package/dist/{worker → infrastructure}/console/repo-fingerprint.js +0 -0
|
@@ -12,17 +12,20 @@
|
|
|
12
12
|
* Mutation routes go through the Console mutation gate (boot token + Origin).
|
|
13
13
|
* Read routes (GET capabilities / sessions) are open to loopback.
|
|
14
14
|
*/
|
|
15
|
+
import { randomUUID } from "node:crypto";
|
|
16
|
+
import { access } from "node:fs/promises";
|
|
15
17
|
import { parseAssistantContent } from "./assistant-content.js";
|
|
16
18
|
import { OPERATOR_CHAT_ALLOWED_TOOLS, OPERATOR_CHAT_DENIED_TOOLS, OPERATOR_CHAT_DENIED_OPERATOR_ACTIONS, } from "./tools.js";
|
|
17
19
|
import { buildModelCallableToolSchemas } from "./tool-adapter.js";
|
|
18
|
-
import { cleanChatTitle, acceptedOperationIdFromResult } from "./session-store.js";
|
|
20
|
+
import { cleanChatTitle, acceptedOperationIdFromResult, isBlankChatSession } from "./session-store.js";
|
|
19
21
|
import { hashChatTurnPayload, projectChatToolEventPayload, projectCompactSnapshot, } from "./chat-event-store.js";
|
|
22
|
+
import { projectDeferredTurnSummary, projectDeferredTurnSummaries, } from "./deferred-turn.js";
|
|
20
23
|
import { THINKING_LEVELS, RuntimeSnapshotUnavailableError, } from "./pi-runtime.js";
|
|
21
24
|
import { ResourcePreferencesError, setSkillAutoInvocationPreference, } from "./resource-preferences-store.js";
|
|
22
25
|
import { ComposerDraftStore } from "./composer-draft-store.js";
|
|
23
26
|
import { walkRepoFiles } from "./repo-walk.js";
|
|
24
27
|
import { isSensitivePath, scrubSecrets } from "./explore-tools.js";
|
|
25
|
-
import { listRepoDirectory, readRepoPreview, RepoBrowserError, } from "./repo-browser.js";
|
|
28
|
+
import { listRepoDirectory, matchRepoHtmlPreviewRoute, readRepoHtmlAsset, readRepoPreview, RepoBrowserError, } from "./repo-browser.js";
|
|
26
29
|
import { projectRuntimeContext } from "./runtime-context.js";
|
|
27
30
|
import { patchModelsConfig, readModelsConfig, readPackageInventory, } from "./pi-console-config.js";
|
|
28
31
|
import { ChatInterviewAdapter, projectChatInterviewState, } from "./interview-adapter.js";
|
|
@@ -32,9 +35,90 @@ import { dispatchOperatorAction } from "../operator-actions.js";
|
|
|
32
35
|
import { makeHumanGateCard, } from "./human-gate-card.js";
|
|
33
36
|
import { ContractApplyReceiptStore } from "./contract-apply-receipt-store.js";
|
|
34
37
|
import { projectTaskContext } from "./context-panel.js";
|
|
38
|
+
import { deriveChatSessionTelemetry, deriveChatTurnTelemetry } from "./session-stats.js";
|
|
35
39
|
import { contractApplyPayloadHash, issueHumanGateToken, verifyHumanGateToken, } from "../human-gate-token.js";
|
|
36
40
|
import { sendJson } from "../routes.js";
|
|
37
41
|
import { openSseResponse, writeSseEvent } from "../operation-sse.js";
|
|
42
|
+
import { buildTodoCompactionInstructions, projectCurrentTodos } from "./todos.js";
|
|
43
|
+
import { buildGoalCompactionInstructions, buildGoalContinuationContext, } from "./goals.js";
|
|
44
|
+
import { classifyGoalRoundAdmission, } from "./goal-round-driver.js";
|
|
45
|
+
import { isTerminalOperationState } from "../../../infrastructure/console/operation-store.js";
|
|
46
|
+
import { SddDataAlignmentError, } from "./sdd-data-alignment.js";
|
|
47
|
+
function projectBrowserChatSession(record) {
|
|
48
|
+
const { telemetrySessionId, ...projected } = record;
|
|
49
|
+
void telemetrySessionId;
|
|
50
|
+
return projected;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Reattach the durable event-ring order to session-store rows. The session
|
|
54
|
+
* store remains the content authority; the ring only supplies chronology.
|
|
55
|
+
* This makes refresh hydration use the same turnId/seq ordering as live SSE.
|
|
56
|
+
*/
|
|
57
|
+
export function projectStoredMessagesWithEventOrder(messages, events) {
|
|
58
|
+
let assistantCursor = 0;
|
|
59
|
+
const nextAssistantEvent = (message) => {
|
|
60
|
+
const expectedKind = message.kind === "provider-error" ? "error" : "message_end";
|
|
61
|
+
const messageAt = Date.parse(message.at);
|
|
62
|
+
for (let index = assistantCursor; index < events.length; index += 1) {
|
|
63
|
+
const event = events[index];
|
|
64
|
+
if (event.kind !== expectedKind)
|
|
65
|
+
continue;
|
|
66
|
+
const data = event.data;
|
|
67
|
+
const eventText = typeof data.text === "string"
|
|
68
|
+
? data.text
|
|
69
|
+
: typeof data.message === "string"
|
|
70
|
+
? data.message
|
|
71
|
+
: undefined;
|
|
72
|
+
const closeInTime = Number.isFinite(messageAt) && Number.isFinite(Date.parse(event.at))
|
|
73
|
+
? Math.abs(Date.parse(event.at) - messageAt) <= 30_000
|
|
74
|
+
: true;
|
|
75
|
+
if (eventText === message.text && closeInTime) {
|
|
76
|
+
assistantCursor = index + 1;
|
|
77
|
+
return event;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
// The bounded ring may no longer contain this old message. Leave it on the
|
|
81
|
+
// legacy timestamp fallback; never steal a newer event just to fill a seq.
|
|
82
|
+
return undefined;
|
|
83
|
+
};
|
|
84
|
+
return messages.map((message) => {
|
|
85
|
+
let start;
|
|
86
|
+
let finish;
|
|
87
|
+
if (message.role === "user") {
|
|
88
|
+
start = events.find((event) => {
|
|
89
|
+
if (event.kind !== "user_message")
|
|
90
|
+
return false;
|
|
91
|
+
const payload = event.data;
|
|
92
|
+
return payload.message?.id === message.id;
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
else if (message.role === "assistant") {
|
|
96
|
+
start = nextAssistantEvent(message);
|
|
97
|
+
}
|
|
98
|
+
else if (message.role === "tool" && message.toolCallId) {
|
|
99
|
+
start = events.find((event) => event.kind === "tool_call" &&
|
|
100
|
+
event.data.toolCallId ===
|
|
101
|
+
message.toolCallId);
|
|
102
|
+
finish = events.find((event) => event.kind === "tool_result" &&
|
|
103
|
+
event.data.toolCallId ===
|
|
104
|
+
message.toolCallId);
|
|
105
|
+
start ??= finish;
|
|
106
|
+
}
|
|
107
|
+
return {
|
|
108
|
+
...message,
|
|
109
|
+
...(start
|
|
110
|
+
? {
|
|
111
|
+
eventSeq: start.seq,
|
|
112
|
+
turnId: start.turnId,
|
|
113
|
+
startedAt: start.at,
|
|
114
|
+
}
|
|
115
|
+
: {}),
|
|
116
|
+
...(finish
|
|
117
|
+
? { finishedSeq: finish.seq, finishedAt: finish.at }
|
|
118
|
+
: {}),
|
|
119
|
+
};
|
|
120
|
+
});
|
|
121
|
+
}
|
|
38
122
|
function turnSummary(turn) {
|
|
39
123
|
return {
|
|
40
124
|
turnId: turn.turnId,
|
|
@@ -51,7 +135,6 @@ function turnSummary(turn) {
|
|
|
51
135
|
function isTerminalTurnState(state) {
|
|
52
136
|
return state === "settled" || state === "aborted" || state === "failed";
|
|
53
137
|
}
|
|
54
|
-
const DEFAULT_ABORT_WAIT_MS = 2_500;
|
|
55
138
|
/** Parse Chat's `<epoch>:<seq>` SSE cursor. Legacy `<sessionId>:<seq>` has
|
|
56
139
|
* the same wire shape; its prefix intentionally fails the current process
|
|
57
140
|
* epoch comparison and triggers safe snapshot recovery (M5.1). */
|
|
@@ -86,11 +169,38 @@ function turnEventToStorePartial(event) {
|
|
|
86
169
|
case "message_update":
|
|
87
170
|
case "message_end": {
|
|
88
171
|
const content = parseAssistantContent(event.content);
|
|
172
|
+
const timingSource = event.type === "message_end" &&
|
|
173
|
+
event.timing &&
|
|
174
|
+
typeof event.timing === "object"
|
|
175
|
+
? event.timing
|
|
176
|
+
: undefined;
|
|
177
|
+
const timing = timingSource &&
|
|
178
|
+
typeof timingSource.llmMs === "number" &&
|
|
179
|
+
Number.isFinite(timingSource.llmMs)
|
|
180
|
+
? {
|
|
181
|
+
llmMs: Math.max(0, timingSource.llmMs),
|
|
182
|
+
...(typeof timingSource.ttftMs === "number" &&
|
|
183
|
+
Number.isFinite(timingSource.ttftMs)
|
|
184
|
+
? { ttftMs: Math.max(0, timingSource.ttftMs) }
|
|
185
|
+
: {}),
|
|
186
|
+
...(typeof timingSource.decodeMs === "number" &&
|
|
187
|
+
Number.isFinite(timingSource.decodeMs)
|
|
188
|
+
? { decodeMs: Math.max(0, timingSource.decodeMs) }
|
|
189
|
+
: {}),
|
|
190
|
+
...(typeof timingSource.outputTokens === "number" &&
|
|
191
|
+
Number.isFinite(timingSource.outputTokens)
|
|
192
|
+
? {
|
|
193
|
+
outputTokens: Math.max(0, timingSource.outputTokens),
|
|
194
|
+
}
|
|
195
|
+
: {}),
|
|
196
|
+
}
|
|
197
|
+
: undefined;
|
|
89
198
|
return {
|
|
90
199
|
kind: event.type,
|
|
91
200
|
data: {
|
|
92
201
|
text: String(event.text ?? ""),
|
|
93
202
|
...(content ? { content } : {}),
|
|
203
|
+
...(timing ? { timing } : {}),
|
|
94
204
|
},
|
|
95
205
|
};
|
|
96
206
|
}
|
|
@@ -122,6 +232,9 @@ function turnEventToStorePartial(event) {
|
|
|
122
232
|
}),
|
|
123
233
|
};
|
|
124
234
|
}
|
|
235
|
+
case "todo_updated":
|
|
236
|
+
case "todo_cleared":
|
|
237
|
+
return { kind: event.type, data: { todos: Array.isArray(event.todos) ? event.todos : [], ...(event.toolCallId ? { toolCallId: String(event.toolCallId) } : {}) } };
|
|
125
238
|
case "agent_end":
|
|
126
239
|
return {
|
|
127
240
|
kind: "agent_end",
|
|
@@ -129,8 +242,53 @@ function turnEventToStorePartial(event) {
|
|
|
129
242
|
};
|
|
130
243
|
case "agent_settled":
|
|
131
244
|
return { kind: "agent_settled", data: {} };
|
|
132
|
-
case "
|
|
133
|
-
|
|
245
|
+
case "compaction_start":
|
|
246
|
+
case "compaction_end": {
|
|
247
|
+
const reason = event.reason === "threshold" || event.reason === "overflow"
|
|
248
|
+
? event.reason
|
|
249
|
+
: "manual";
|
|
250
|
+
const status = event.type === "compaction_start"
|
|
251
|
+
? "running"
|
|
252
|
+
: event.status === "aborted" || event.status === "failed"
|
|
253
|
+
? event.status
|
|
254
|
+
: "completed";
|
|
255
|
+
const data = {
|
|
256
|
+
schemaVersion: 1,
|
|
257
|
+
compactionId: String(event.compactionId ?? ""),
|
|
258
|
+
reason,
|
|
259
|
+
status,
|
|
260
|
+
...(typeof event.summary === "string"
|
|
261
|
+
? { summary: event.summary }
|
|
262
|
+
: {}),
|
|
263
|
+
...(typeof event.firstKeptEntryId === "string"
|
|
264
|
+
? { firstKeptEntryId: event.firstKeptEntryId }
|
|
265
|
+
: {}),
|
|
266
|
+
...(typeof event.tokensBefore === "number"
|
|
267
|
+
? { tokensBefore: event.tokensBefore }
|
|
268
|
+
: {}),
|
|
269
|
+
...(typeof event.estimatedTokensAfter === "number"
|
|
270
|
+
? { estimatedTokensAfter: event.estimatedTokensAfter }
|
|
271
|
+
: {}),
|
|
272
|
+
willRetry: Boolean(event.willRetry),
|
|
273
|
+
...(typeof event.errorMessage === "string"
|
|
274
|
+
? { errorMessage: event.errorMessage }
|
|
275
|
+
: {}),
|
|
276
|
+
};
|
|
277
|
+
return { kind: event.type, data };
|
|
278
|
+
}
|
|
279
|
+
case "error": {
|
|
280
|
+
const content = parseAssistantContent(event.content);
|
|
281
|
+
return {
|
|
282
|
+
kind: "error",
|
|
283
|
+
data: {
|
|
284
|
+
message: String(event.message ?? ""),
|
|
285
|
+
...(content ? { content } : {}),
|
|
286
|
+
...(event.providerError && typeof event.providerError === "object"
|
|
287
|
+
? { providerError: event.providerError }
|
|
288
|
+
: {}),
|
|
289
|
+
},
|
|
290
|
+
};
|
|
291
|
+
}
|
|
134
292
|
default:
|
|
135
293
|
return undefined;
|
|
136
294
|
}
|
|
@@ -196,6 +354,13 @@ function ensureAgentEndEvent(deps, sessionId, turnId) {
|
|
|
196
354
|
}
|
|
197
355
|
}
|
|
198
356
|
async function readJsonBody(req, maxBytes = 2 * 1024 * 1024) {
|
|
357
|
+
// AC-R5-003: the multi-workspace dispatcher (server.ts readBodyOnce)
|
|
358
|
+
// pre-reads and JSON-parses the body for workspaceId resolution, stashing
|
|
359
|
+
// it on req.__preReadBody. Consume it first so the body is parsed exactly
|
|
360
|
+
// once per request; re-reading the consumed stream would yield {}.
|
|
361
|
+
const preRead = req.__preReadBody;
|
|
362
|
+
if (preRead !== undefined)
|
|
363
|
+
return preRead;
|
|
199
364
|
const chunks = [];
|
|
200
365
|
let total = 0;
|
|
201
366
|
for await (const chunk of req) {
|
|
@@ -269,6 +434,7 @@ export function parseChatImages(value) {
|
|
|
269
434
|
}
|
|
270
435
|
function gateMutation(req, deps) {
|
|
271
436
|
const failure = evaluateMutationGate(req, {
|
|
437
|
+
cookieName: deps.bootToken.cookieName,
|
|
272
438
|
bootToken: deps.bootToken.value,
|
|
273
439
|
confirmationToken: deps.bootToken.confirmationToken,
|
|
274
440
|
consoleOrigin: deps.getConsoleOrigin(),
|
|
@@ -309,7 +475,7 @@ function sendRuntimeUnavailable(res, error) {
|
|
|
309
475
|
* handled here — only reopen/init readiness failures.
|
|
310
476
|
*/
|
|
311
477
|
function mapReopenSessionFailure(reopen) {
|
|
312
|
-
if (reopen.code === "NO_SESSION_FILE") {
|
|
478
|
+
if (reopen.code === "NO_SESSION_FILE" || reopen.code === "SESSION_FILE_MISSING") {
|
|
313
479
|
return {
|
|
314
480
|
status: 404,
|
|
315
481
|
code: "PI_SESSION_NOT_FOUND",
|
|
@@ -329,6 +495,19 @@ function mapReopenSessionFailure(reopen) {
|
|
|
329
495
|
message: reopen.message,
|
|
330
496
|
};
|
|
331
497
|
}
|
|
498
|
+
/** Drop an orphan catalog record whose promised Pi JSONL is gone. */
|
|
499
|
+
async function healMissingSessionFile(deps, sessionId, reopen) {
|
|
500
|
+
if (reopen && reopen.code !== "NO_SESSION_FILE" && reopen.code !== "SESSION_FILE_MISSING") {
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
if (typeof deps.store.remove !== "function")
|
|
504
|
+
return;
|
|
505
|
+
await deps.store.remove(sessionId).catch(() => undefined);
|
|
506
|
+
}
|
|
507
|
+
async function mapFailedReopen(deps, sessionId, reopen) {
|
|
508
|
+
await healMissingSessionFile(deps, sessionId, reopen);
|
|
509
|
+
return mapReopenSessionFailure(reopen);
|
|
510
|
+
}
|
|
332
511
|
export async function handleChatCapabilities(_req, res, deps) {
|
|
333
512
|
const toolSchemas = buildModelCallableToolSchemas();
|
|
334
513
|
sendJson(res, 200, {
|
|
@@ -342,7 +521,10 @@ export async function handleChatCapabilities(_req, res, deps) {
|
|
|
342
521
|
hasBash: true,
|
|
343
522
|
});
|
|
344
523
|
}
|
|
345
|
-
export async function handleCreateChatSession(req, res, deps
|
|
524
|
+
export async function handleCreateChatSession(req, res, deps,
|
|
525
|
+
/** Explicit owning workspaceId from the multi-workspace dispatcher
|
|
526
|
+
* (AC-R7-002). The body still parses exactly once via req.__preReadBody. */
|
|
527
|
+
workspaceId) {
|
|
346
528
|
const gate = gateMutation(req, deps);
|
|
347
529
|
if (!gate.ok) {
|
|
348
530
|
sendJson(res, gate.status, {
|
|
@@ -393,9 +575,15 @@ export async function handleCreateChatSession(req, res, deps) {
|
|
|
393
575
|
});
|
|
394
576
|
return;
|
|
395
577
|
}
|
|
578
|
+
let createdSessionId;
|
|
579
|
+
let persisted = false;
|
|
396
580
|
try {
|
|
397
581
|
const snapshot = snapshotInput === undefined ? undefined : projectCompactSnapshot(snapshotInput);
|
|
398
|
-
//
|
|
582
|
+
// A Console record promises that its Pi JSONL can be reopened after a
|
|
583
|
+
// Console restart. Do not make that promise until Pi has finished
|
|
584
|
+
// materializing the session: the old fast path wrote a record for a
|
|
585
|
+
// future JSONL path, leaving an unrecoverable orphan when init failed or
|
|
586
|
+
// the process restarted in that window.
|
|
399
587
|
const handle = await deps.runtime.createSession({
|
|
400
588
|
...(provider && modelId ? { model: { provider, modelId } } : {}),
|
|
401
589
|
...(snapshot
|
|
@@ -415,51 +603,51 @@ export async function handleCreateChatSession(req, res, deps) {
|
|
|
415
603
|
});
|
|
416
604
|
return;
|
|
417
605
|
}
|
|
606
|
+
createdSessionId = handle.sessionId;
|
|
607
|
+
await deps.runtime.ensureSessionReady(handle.sessionId);
|
|
608
|
+
const selection = deps.runtime.getRuntimeSelection(handle.sessionId);
|
|
418
609
|
const session = await deps.store.create({
|
|
419
610
|
sessionId: handle.sessionId,
|
|
420
611
|
sessionFile: handle.sessionFile,
|
|
421
|
-
modelProvider: handle.model?.provider,
|
|
422
|
-
modelId: handle.model?.modelId,
|
|
612
|
+
modelProvider: selection.model?.provider ?? handle.model?.provider,
|
|
613
|
+
modelId: selection.model?.modelId ?? handle.model?.modelId,
|
|
614
|
+
// AC-R7-002: explicit parameter from the dispatcher — the runtime
|
|
615
|
+
// store.create wrapper is gone; body workspaceId (if any) only acts as
|
|
616
|
+
// a fallback for direct (non-dispatcher) handler tests.
|
|
617
|
+
workspaceId: workspaceId ?? (typeof body.workspaceId === "string" && body.workspaceId ? body.workspaceId : undefined),
|
|
423
618
|
});
|
|
619
|
+
persisted = true;
|
|
620
|
+
await deps.attachSession?.(handle.sessionId).catch(() => undefined);
|
|
424
621
|
if (snapshot)
|
|
425
622
|
deps.events.append(handle.sessionId, `${handle.sessionId}:snapshot`, {
|
|
426
623
|
kind: "compact",
|
|
427
624
|
data: snapshot,
|
|
428
625
|
});
|
|
429
|
-
// Best-effort: after materialization, patch resolved default model onto the
|
|
430
|
-
// durable record. Failures stay on the init fence (PI_SESSION_INIT_FAILED).
|
|
431
|
-
if (typeof deps.runtime.ensureSessionReady === "function") {
|
|
432
|
-
void deps.runtime
|
|
433
|
-
.ensureSessionReady(handle.sessionId)
|
|
434
|
-
.then(async () => {
|
|
435
|
-
if (typeof deps.runtime.getRuntimeSelection !== "function")
|
|
436
|
-
return;
|
|
437
|
-
const selection = deps.runtime.getRuntimeSelection(handle.sessionId);
|
|
438
|
-
if (!selection?.model)
|
|
439
|
-
return;
|
|
440
|
-
await deps.store.setRuntimeSelection(handle.sessionId, {
|
|
441
|
-
modelProvider: selection.model.provider,
|
|
442
|
-
modelId: selection.model.modelId,
|
|
443
|
-
});
|
|
444
|
-
})
|
|
445
|
-
.catch(() => undefined);
|
|
446
|
-
}
|
|
447
626
|
sendJson(res, 201, {
|
|
448
627
|
ok: true,
|
|
449
628
|
sessionId: handle.sessionId,
|
|
450
629
|
sessionFile: handle.sessionFile,
|
|
451
630
|
model: handle.model,
|
|
452
|
-
session,
|
|
631
|
+
session: { ...session, isBlank: isBlankChatSession(session) },
|
|
453
632
|
activeTools: handle.activeTools,
|
|
454
633
|
hasBash: true,
|
|
455
|
-
...(handle.initializing ? { initializing: true } : {}),
|
|
456
634
|
});
|
|
457
635
|
}
|
|
458
636
|
catch (error) {
|
|
637
|
+
// Before store.create succeeds, this handle has no durable owner. Dispose
|
|
638
|
+
// it so a failed create cannot survive in-memory until the next restart.
|
|
639
|
+
if (createdSessionId && !persisted)
|
|
640
|
+
deps.runtime.dispose(createdSessionId);
|
|
459
641
|
const message = error instanceof Error ? error.message : String(error);
|
|
460
|
-
|
|
642
|
+
const code = error && typeof error === "object" && "code" in error
|
|
643
|
+
? String(error.code ?? "")
|
|
644
|
+
: "";
|
|
645
|
+
sendJson(res, code === "PI_SESSION_INIT_FAILED" ? 503 : 500, {
|
|
461
646
|
ok: false,
|
|
462
|
-
error: {
|
|
647
|
+
error: {
|
|
648
|
+
code: code === "PI_SESSION_INIT_FAILED" ? code : "CHAT_SESSION_CREATE_FAILED",
|
|
649
|
+
message,
|
|
650
|
+
},
|
|
463
651
|
});
|
|
464
652
|
}
|
|
465
653
|
}
|
|
@@ -502,6 +690,7 @@ export async function handleForkChatSession(req, res, deps, sourceSessionId) {
|
|
|
502
690
|
targetSessionId: handle.sessionId,
|
|
503
691
|
targetSessionFile: handle.sessionFile,
|
|
504
692
|
});
|
|
693
|
+
await deps.attachSession?.(handle.sessionId).catch(() => undefined);
|
|
505
694
|
const copied = deps.events.forkContextRefs({
|
|
506
695
|
sourceSessionId,
|
|
507
696
|
targetSessionId: handle.sessionId,
|
|
@@ -563,10 +752,7 @@ export async function handleBranchChatSession(req, res, deps, sessionId) {
|
|
|
563
752
|
sessionFile: record.sessionFile,
|
|
564
753
|
});
|
|
565
754
|
if (!reopened.ok) {
|
|
566
|
-
const mapped =
|
|
567
|
-
code: reopened.code,
|
|
568
|
-
message: reopened.message,
|
|
569
|
-
});
|
|
755
|
+
const mapped = await mapFailedReopen(deps, sessionId, reopened);
|
|
570
756
|
sendJson(res, mapped.status, {
|
|
571
757
|
ok: false,
|
|
572
758
|
error: { code: mapped.code, message: mapped.message },
|
|
@@ -641,23 +827,332 @@ export async function handleGetChatSession(_req, res, deps, sessionId) {
|
|
|
641
827
|
});
|
|
642
828
|
return;
|
|
643
829
|
}
|
|
830
|
+
if (record.sessionFile) {
|
|
831
|
+
try {
|
|
832
|
+
await access(record.sessionFile);
|
|
833
|
+
}
|
|
834
|
+
catch (error) {
|
|
835
|
+
const code = error && typeof error === "object" && "code" in error
|
|
836
|
+
? String(error.code ?? "")
|
|
837
|
+
: "";
|
|
838
|
+
if (code === "ENOENT") {
|
|
839
|
+
await healMissingSessionFile(deps, sessionId, {
|
|
840
|
+
code: "NO_SESSION_FILE",
|
|
841
|
+
});
|
|
842
|
+
sendJson(res, 404, {
|
|
843
|
+
ok: false,
|
|
844
|
+
error: {
|
|
845
|
+
code: "PI_SESSION_NOT_FOUND",
|
|
846
|
+
message: `Pi session file missing or not openable: ${record.sessionFile}`,
|
|
847
|
+
},
|
|
848
|
+
});
|
|
849
|
+
return;
|
|
850
|
+
}
|
|
851
|
+
}
|
|
852
|
+
}
|
|
644
853
|
await deps.operationLinker.recoverSession(sessionId);
|
|
854
|
+
const messagePage = await deps.store.listMessages(sessionId, { limit: 50 });
|
|
645
855
|
const composerDraft = await new ComposerDraftStore(deps.appData).get(sessionId);
|
|
646
856
|
const snapshot = deps.events.snapshot(sessionId);
|
|
857
|
+
const telemetry = deriveChatSessionTelemetry(snapshot);
|
|
647
858
|
const lastEvent = snapshot.at(-1);
|
|
859
|
+
const activeTurn = deps.events.getActiveTurn(sessionId);
|
|
860
|
+
const pendingQuestion = await deps.questionRegistry?.get(sessionId);
|
|
648
861
|
sendJson(res, 200, {
|
|
649
862
|
ok: true,
|
|
650
863
|
eventEpoch: deps.events.epoch(sessionId),
|
|
651
864
|
session: {
|
|
652
|
-
...record,
|
|
865
|
+
...projectBrowserChatSession(record),
|
|
866
|
+
messages: projectStoredMessagesWithEventOrder(messagePage.messages, snapshot),
|
|
653
867
|
composerDraft,
|
|
654
|
-
activeTurnId:
|
|
868
|
+
activeTurnId: activeTurn?.turnId,
|
|
869
|
+
turnPhase: activeTurn
|
|
870
|
+
? activeTurn.abortRequestedAt
|
|
871
|
+
? "stopping"
|
|
872
|
+
: "running"
|
|
873
|
+
: "idle",
|
|
874
|
+
pendingQuestion: pendingQuestion ?? null,
|
|
875
|
+
todos: projectCurrentTodos(snapshot) ?? [],
|
|
876
|
+
goal: deps.goalRegistry?.get(sessionId) ?? null,
|
|
877
|
+
},
|
|
878
|
+
history: {
|
|
879
|
+
hasMore: messagePage.hasMore,
|
|
880
|
+
...(messagePage.nextCursor ? { nextCursor: messagePage.nextCursor } : {}),
|
|
655
881
|
},
|
|
656
882
|
hasBash: true,
|
|
883
|
+
sessionStats: telemetry.stats,
|
|
884
|
+
usage: telemetry.usage,
|
|
885
|
+
turnTelemetry: deriveChatTurnTelemetry(snapshot),
|
|
886
|
+
contextPressure: typeof deps.runtime.getContextPressureTelemetry === "function"
|
|
887
|
+
? deps.runtime.getContextPressureTelemetry(sessionId)
|
|
888
|
+
: undefined,
|
|
889
|
+
compactions: snapshot
|
|
890
|
+
.filter((event) => event.kind === "compact" ||
|
|
891
|
+
event.kind === "compaction_start" ||
|
|
892
|
+
event.kind === "compaction_end")
|
|
893
|
+
.map((event) => ({
|
|
894
|
+
eventId: event.eventId,
|
|
895
|
+
kind: event.kind,
|
|
896
|
+
at: event.at,
|
|
897
|
+
seq: event.seq,
|
|
898
|
+
turnId: event.turnId,
|
|
899
|
+
data: event.data,
|
|
900
|
+
})),
|
|
657
901
|
lastEventId: lastEvent?.eventId ?? null,
|
|
658
902
|
lastEventSeq: lastEvent?.seq ?? 0,
|
|
659
903
|
});
|
|
660
904
|
}
|
|
905
|
+
function parseDeferredImages(value) {
|
|
906
|
+
const parsed = parseChatImages(value);
|
|
907
|
+
const raw = Array.isArray(value) ? value : [];
|
|
908
|
+
return parsed.map((image, index) => {
|
|
909
|
+
const candidate = raw[index];
|
|
910
|
+
const name = candidate &&
|
|
911
|
+
typeof candidate === "object" &&
|
|
912
|
+
typeof candidate.name === "string"
|
|
913
|
+
? candidate.name.trim().slice(0, 180)
|
|
914
|
+
: `image-${index + 1}`;
|
|
915
|
+
return { ...image, name: name || `image-${index + 1}` };
|
|
916
|
+
});
|
|
917
|
+
}
|
|
918
|
+
export async function handlePutDeferredTurn(req, res, deps, sessionId) {
|
|
919
|
+
const gate = gateMutation(req, deps);
|
|
920
|
+
if (!gate.ok) {
|
|
921
|
+
sendJson(res, gate.status, {
|
|
922
|
+
ok: false,
|
|
923
|
+
accepted: false,
|
|
924
|
+
error: { code: gate.code, message: gate.message },
|
|
925
|
+
});
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
let body;
|
|
929
|
+
try {
|
|
930
|
+
body = await readJsonBody(req);
|
|
931
|
+
}
|
|
932
|
+
catch (error) {
|
|
933
|
+
sendJson(res, 400, {
|
|
934
|
+
ok: false,
|
|
935
|
+
accepted: false,
|
|
936
|
+
error: {
|
|
937
|
+
code: "INVALID_INPUT",
|
|
938
|
+
message: error instanceof Error ? error.message : String(error),
|
|
939
|
+
},
|
|
940
|
+
});
|
|
941
|
+
return;
|
|
942
|
+
}
|
|
943
|
+
const clientRequestId = typeof body.clientRequestId === "string" ? body.clientRequestId.trim() : "";
|
|
944
|
+
const blockedByTurnId = typeof body.blockedByTurnId === "string" ? body.blockedByTurnId.trim() : "";
|
|
945
|
+
const text = typeof body.text === "string" ? body.text : "";
|
|
946
|
+
const expectedRevision = typeof body.expectedRevision === "number" &&
|
|
947
|
+
Number.isSafeInteger(body.expectedRevision) &&
|
|
948
|
+
body.expectedRevision >= 0
|
|
949
|
+
? body.expectedRevision
|
|
950
|
+
: undefined;
|
|
951
|
+
let images;
|
|
952
|
+
try {
|
|
953
|
+
images = parseDeferredImages(body.images);
|
|
954
|
+
}
|
|
955
|
+
catch (error) {
|
|
956
|
+
sendJson(res, 400, {
|
|
957
|
+
ok: false,
|
|
958
|
+
accepted: false,
|
|
959
|
+
error: {
|
|
960
|
+
code: "INVALID_ATTACHMENT",
|
|
961
|
+
message: error instanceof Error ? error.message : String(error),
|
|
962
|
+
},
|
|
963
|
+
});
|
|
964
|
+
return;
|
|
965
|
+
}
|
|
966
|
+
const active = deps.events.getActiveTurn(sessionId);
|
|
967
|
+
// Queueing binds to the active Turn (running OR stopping); the durable
|
|
968
|
+
// follow-up auto-dispatches when that Turn reaches a terminal state.
|
|
969
|
+
if (!active || active.turnId !== blockedByTurnId) {
|
|
970
|
+
sendJson(res, 409, {
|
|
971
|
+
ok: false,
|
|
972
|
+
accepted: false,
|
|
973
|
+
error: {
|
|
974
|
+
code: "TURN_NOT_ACTIVE",
|
|
975
|
+
message: "没有匹配的运行中 Turn,无法保存待发送消息",
|
|
976
|
+
},
|
|
977
|
+
activeTurn: active ? turnSummary(active) : null,
|
|
978
|
+
});
|
|
979
|
+
return;
|
|
980
|
+
}
|
|
981
|
+
const result = await deps.store.putDeferredTurn(sessionId, {
|
|
982
|
+
clientRequestId,
|
|
983
|
+
blockedByTurnId,
|
|
984
|
+
text,
|
|
985
|
+
images,
|
|
986
|
+
...(expectedRevision !== undefined ? { expectedRevision } : {}),
|
|
987
|
+
});
|
|
988
|
+
if (!result.ok) {
|
|
989
|
+
const status = result.code === "NOT_FOUND"
|
|
990
|
+
? 404
|
|
991
|
+
: result.code === "INVALID_INPUT"
|
|
992
|
+
? 400
|
|
993
|
+
: 409;
|
|
994
|
+
sendJson(res, status, {
|
|
995
|
+
ok: false,
|
|
996
|
+
accepted: false,
|
|
997
|
+
error: {
|
|
998
|
+
code: result.code,
|
|
999
|
+
message: result.code === "REVISION_CONFLICT"
|
|
1000
|
+
? "待发送消息已在其他页面更新,请使用服务端最新状态"
|
|
1001
|
+
: result.code === "NOT_REPLACEABLE"
|
|
1002
|
+
? "待发送消息已经开始发送,不能再覆盖"
|
|
1003
|
+
: result.code === "REQUEST_ID_REUSE_CONFLICT"
|
|
1004
|
+
? "clientRequestId 已绑定到不同消息"
|
|
1005
|
+
: "待发送消息无效或会话不存在",
|
|
1006
|
+
},
|
|
1007
|
+
deferredTurn: result.deferredTurn ?? null,
|
|
1008
|
+
deferredTurns: projectDeferredTurnSummaries(await deps.store.listDeferredTurns(sessionId)),
|
|
1009
|
+
summary: projectDeferredTurnSummary(result.deferredTurn),
|
|
1010
|
+
});
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
await emitDeferredTurnUpdate(deps, sessionId, blockedByTurnId, result.deferredTurn, result.deferredTurn.revision);
|
|
1014
|
+
sendJson(res, 200, {
|
|
1015
|
+
ok: true,
|
|
1016
|
+
accepted: true,
|
|
1017
|
+
idempotent: result.idempotent,
|
|
1018
|
+
state: result.deferredTurn.state,
|
|
1019
|
+
revision: result.deferredTurn.revision,
|
|
1020
|
+
deferredTurn: result.deferredTurn,
|
|
1021
|
+
deferredTurns: projectDeferredTurnSummaries(await deps.store.listDeferredTurns(sessionId)),
|
|
1022
|
+
summary: projectDeferredTurnSummary(result.deferredTurn),
|
|
1023
|
+
});
|
|
1024
|
+
void dispatchDeferredTurn(deps, sessionId);
|
|
1025
|
+
}
|
|
1026
|
+
export async function handleDeleteDeferredTurn(req, res, deps, sessionId) {
|
|
1027
|
+
const gate = gateMutation(req, deps);
|
|
1028
|
+
if (!gate.ok) {
|
|
1029
|
+
sendJson(res, gate.status, {
|
|
1030
|
+
ok: false,
|
|
1031
|
+
error: { code: gate.code, message: gate.message },
|
|
1032
|
+
});
|
|
1033
|
+
return;
|
|
1034
|
+
}
|
|
1035
|
+
let body;
|
|
1036
|
+
try {
|
|
1037
|
+
body = await readJsonBody(req);
|
|
1038
|
+
}
|
|
1039
|
+
catch (error) {
|
|
1040
|
+
sendJson(res, 400, {
|
|
1041
|
+
ok: false,
|
|
1042
|
+
error: {
|
|
1043
|
+
code: "INVALID_INPUT",
|
|
1044
|
+
message: error instanceof Error ? error.message : String(error),
|
|
1045
|
+
},
|
|
1046
|
+
});
|
|
1047
|
+
return;
|
|
1048
|
+
}
|
|
1049
|
+
const clientRequestId = typeof body.clientRequestId === "string" ? body.clientRequestId.trim() : "";
|
|
1050
|
+
const expectedRevision = typeof body.expectedRevision === "number" && Number.isSafeInteger(body.expectedRevision)
|
|
1051
|
+
? body.expectedRevision
|
|
1052
|
+
: -1;
|
|
1053
|
+
const result = await deps.store.deleteDeferredTurn(sessionId, {
|
|
1054
|
+
clientRequestId,
|
|
1055
|
+
expectedRevision,
|
|
1056
|
+
});
|
|
1057
|
+
if (!result.ok) {
|
|
1058
|
+
sendJson(res, result.code === "NOT_FOUND" ? 404 : 409, {
|
|
1059
|
+
ok: false,
|
|
1060
|
+
error: {
|
|
1061
|
+
code: result.code,
|
|
1062
|
+
message: result.code === "NOT_CANCELLABLE"
|
|
1063
|
+
? "消息已经开始发送,不能再撤回"
|
|
1064
|
+
: "待发送消息已变化,请刷新后重试",
|
|
1065
|
+
},
|
|
1066
|
+
deferredTurn: result.deferredTurn ?? null,
|
|
1067
|
+
deferredTurns: projectDeferredTurnSummaries(await deps.store.listDeferredTurns(sessionId)),
|
|
1068
|
+
});
|
|
1069
|
+
return;
|
|
1070
|
+
}
|
|
1071
|
+
const clearedRevision = result.deferredTurn.revision + 1;
|
|
1072
|
+
await emitDeferredTurnUpdate(deps, sessionId, result.deferredTurn.blockedByTurnId, undefined, clearedRevision);
|
|
1073
|
+
sendJson(res, 200, {
|
|
1074
|
+
ok: true,
|
|
1075
|
+
cancelled: true,
|
|
1076
|
+
deferredTurn: result.deferredTurn,
|
|
1077
|
+
deferredTurns: projectDeferredTurnSummaries(await deps.store.listDeferredTurns(sessionId)),
|
|
1078
|
+
revision: clearedRevision,
|
|
1079
|
+
});
|
|
1080
|
+
}
|
|
1081
|
+
/** Move one addressed FIFO item into Pi's live steering queue. */
|
|
1082
|
+
export async function handleSteerDeferredTurn(req, res, deps, sessionId, clientRequestId) {
|
|
1083
|
+
const gate = gateMutation(req, deps);
|
|
1084
|
+
if (!gate.ok) {
|
|
1085
|
+
sendJson(res, gate.status, { ok: false, error: { code: gate.code, message: gate.message } });
|
|
1086
|
+
return;
|
|
1087
|
+
}
|
|
1088
|
+
let body = {};
|
|
1089
|
+
try {
|
|
1090
|
+
body = await readJsonBody(req);
|
|
1091
|
+
}
|
|
1092
|
+
catch (error) {
|
|
1093
|
+
sendJson(res, 400, { ok: false, error: { code: "INVALID_INPUT", message: error instanceof Error ? error.message : String(error) } });
|
|
1094
|
+
return;
|
|
1095
|
+
}
|
|
1096
|
+
const expectedRevision = typeof body.expectedRevision === "number" && Number.isSafeInteger(body.expectedRevision)
|
|
1097
|
+
? body.expectedRevision
|
|
1098
|
+
: -1;
|
|
1099
|
+
const active = deps.events.getActiveTurn(sessionId);
|
|
1100
|
+
if (!active) {
|
|
1101
|
+
sendJson(res, 409, { ok: false, error: { code: "TURN_NOT_ACTIVE", message: "当前没有可插话的运行中回合" } });
|
|
1102
|
+
return;
|
|
1103
|
+
}
|
|
1104
|
+
const claim = await deps.store.claimDeferredTurn(sessionId, expectedRevision, clientRequestId);
|
|
1105
|
+
if (!claim.ok) {
|
|
1106
|
+
sendJson(res, claim.code === "NOT_FOUND" ? 404 : 409, {
|
|
1107
|
+
ok: false,
|
|
1108
|
+
error: { code: claim.code, message: "排队消息已变化,请刷新后重试" },
|
|
1109
|
+
});
|
|
1110
|
+
return;
|
|
1111
|
+
}
|
|
1112
|
+
const item = claim.deferredTurn;
|
|
1113
|
+
try {
|
|
1114
|
+
await deps.runtime.steer(sessionId, item.clientRequestId, item.text, item.images);
|
|
1115
|
+
// session.steer() only acknowledges queueing. Keep the durable item in
|
|
1116
|
+
// dispatching until Pi emits the corresponding user message_start.
|
|
1117
|
+
await emitDeferredTurnUpdate(deps, sessionId, active.turnId, item, item.revision);
|
|
1118
|
+
sendJson(res, 200, {
|
|
1119
|
+
ok: true,
|
|
1120
|
+
accepted: true,
|
|
1121
|
+
deferredTurns: projectDeferredTurnSummaries(await deps.store.listDeferredTurns(sessionId)),
|
|
1122
|
+
});
|
|
1123
|
+
}
|
|
1124
|
+
catch (error) {
|
|
1125
|
+
const restored = await deps.store.transitionDeferredTurn(sessionId, {
|
|
1126
|
+
expectedRevision: item.revision,
|
|
1127
|
+
clientRequestId: item.clientRequestId,
|
|
1128
|
+
state: "queued",
|
|
1129
|
+
});
|
|
1130
|
+
if (restored)
|
|
1131
|
+
await emitDeferredTurnUpdate(deps, sessionId, active.turnId, restored, restored.revision);
|
|
1132
|
+
sendJson(res, 409, {
|
|
1133
|
+
ok: false,
|
|
1134
|
+
error: {
|
|
1135
|
+
code: "STEER_FAILED",
|
|
1136
|
+
message: error instanceof Error ? error.message : "插话发送失败",
|
|
1137
|
+
},
|
|
1138
|
+
});
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
async function persistAcceptedSteering(deps, sessionId, turnId, userMessage, clientRequestId) {
|
|
1142
|
+
deps.events.append(sessionId, turnId, {
|
|
1143
|
+
kind: "user_message",
|
|
1144
|
+
data: {
|
|
1145
|
+
clientRequestId,
|
|
1146
|
+
steering: true,
|
|
1147
|
+
message: {
|
|
1148
|
+
id: userMessage.id,
|
|
1149
|
+
text: userMessage.text,
|
|
1150
|
+
at: userMessage.at,
|
|
1151
|
+
},
|
|
1152
|
+
},
|
|
1153
|
+
});
|
|
1154
|
+
await emitDeferredTurnUpdate(deps, sessionId, turnId, undefined, 0);
|
|
1155
|
+
}
|
|
661
1156
|
/** Lightweight busy-truth endpoint for the client reconcile loop (pi-web
|
|
662
1157
|
* get_state equivalent): exposes the active turn + the latest turn's durable
|
|
663
1158
|
* outcome WITHOUT the full message payload, so the UI can poll it on an
|
|
@@ -684,6 +1179,15 @@ export async function handleGetChatSessionState(_req, res, deps, sessionId) {
|
|
|
684
1179
|
isCompacting: false,
|
|
685
1180
|
isBashRunning: false,
|
|
686
1181
|
};
|
|
1182
|
+
const runtimeBusy = Object.values(runtimeFacts).some((value) => value === true);
|
|
1183
|
+
const pendingQuestion = await deps.questionRegistry?.get(sessionId);
|
|
1184
|
+
const turnPhase = active
|
|
1185
|
+
? active.abortRequestedAt
|
|
1186
|
+
? "stopping"
|
|
1187
|
+
: "running"
|
|
1188
|
+
: runtimeBusy
|
|
1189
|
+
? "running"
|
|
1190
|
+
: "idle";
|
|
687
1191
|
sendJson(res, 200, {
|
|
688
1192
|
ok: true,
|
|
689
1193
|
state: {
|
|
@@ -695,21 +1199,263 @@ export async function handleGetChatSessionState(_req, res, deps, sessionId) {
|
|
|
695
1199
|
activeTurn: active ? turnSummary(active) : null,
|
|
696
1200
|
latestTurn: latest ? turnSummary(latest) : null,
|
|
697
1201
|
runtime: runtimeFacts,
|
|
1202
|
+
turnPhase,
|
|
1203
|
+
deferredTurn: projectDeferredTurnSummary(record.deferredTurns?.[0]),
|
|
1204
|
+
deferredTurns: projectDeferredTurnSummaries(record.deferredTurns ?? []),
|
|
1205
|
+
pendingQuestion: pendingQuestion ?? null,
|
|
1206
|
+
todos: projectCurrentTodos(deps.events.snapshot(sessionId)) ?? [],
|
|
1207
|
+
goal: deps.goalRegistry?.get(sessionId) ?? null,
|
|
698
1208
|
},
|
|
699
1209
|
});
|
|
700
1210
|
}
|
|
1211
|
+
function goalHttpStatus(code) {
|
|
1212
|
+
if (code === "GOAL_NOT_FOUND")
|
|
1213
|
+
return 404;
|
|
1214
|
+
if (code === "GOAL_INVALID_INPUT")
|
|
1215
|
+
return 400;
|
|
1216
|
+
return 409;
|
|
1217
|
+
}
|
|
1218
|
+
export async function handleChatGoal(req, res, deps, sessionId) {
|
|
1219
|
+
const registry = deps.goalRegistry;
|
|
1220
|
+
if (!registry) {
|
|
1221
|
+
sendJson(res, 503, {
|
|
1222
|
+
ok: false,
|
|
1223
|
+
error: { code: "GOAL_UNAVAILABLE", message: "Goal runtime is unavailable" },
|
|
1224
|
+
});
|
|
1225
|
+
return;
|
|
1226
|
+
}
|
|
1227
|
+
if (!(await deps.store.get(sessionId))) {
|
|
1228
|
+
sendJson(res, 404, {
|
|
1229
|
+
ok: false,
|
|
1230
|
+
error: { code: "NOT_FOUND", message: `chat session not found: ${sessionId}` },
|
|
1231
|
+
});
|
|
1232
|
+
return;
|
|
1233
|
+
}
|
|
1234
|
+
if (req.method === "GET") {
|
|
1235
|
+
sendJson(res, 200, { ok: true, goal: registry.get(sessionId) });
|
|
1236
|
+
return;
|
|
1237
|
+
}
|
|
1238
|
+
const gate = gateMutation(req, deps);
|
|
1239
|
+
if (!gate.ok) {
|
|
1240
|
+
sendJson(res, gate.status, {
|
|
1241
|
+
ok: false,
|
|
1242
|
+
error: { code: gate.code, message: gate.message },
|
|
1243
|
+
});
|
|
1244
|
+
return;
|
|
1245
|
+
}
|
|
1246
|
+
let body = {};
|
|
1247
|
+
try {
|
|
1248
|
+
body = await readJsonBody(req);
|
|
1249
|
+
}
|
|
1250
|
+
catch (error) {
|
|
1251
|
+
sendJson(res, 400, {
|
|
1252
|
+
ok: false,
|
|
1253
|
+
error: {
|
|
1254
|
+
code: "GOAL_INVALID_INPUT",
|
|
1255
|
+
message: error instanceof Error ? error.message : String(error),
|
|
1256
|
+
},
|
|
1257
|
+
});
|
|
1258
|
+
return;
|
|
1259
|
+
}
|
|
1260
|
+
if (req.method === "POST") {
|
|
1261
|
+
const result = registry.create({
|
|
1262
|
+
sessionId,
|
|
1263
|
+
objective: body.objective,
|
|
1264
|
+
maxRounds: typeof body.maxRounds === "number" ? body.maxRounds : undefined,
|
|
1265
|
+
arm: true,
|
|
1266
|
+
});
|
|
1267
|
+
if (!result.ok) {
|
|
1268
|
+
sendJson(res, goalHttpStatus(result.code), {
|
|
1269
|
+
ok: false,
|
|
1270
|
+
error: { code: result.code, message: result.message },
|
|
1271
|
+
goal: result.goal,
|
|
1272
|
+
});
|
|
1273
|
+
return;
|
|
1274
|
+
}
|
|
1275
|
+
deps.goalRoundDriver?.wake(sessionId);
|
|
1276
|
+
sendJson(res, 201, { ok: true, goal: result.goal });
|
|
1277
|
+
return;
|
|
1278
|
+
}
|
|
1279
|
+
const current = registry.get(sessionId);
|
|
1280
|
+
const goalId = typeof body.goalId === "string" ? body.goalId : "";
|
|
1281
|
+
const revision = typeof body.revision === "number" ? body.revision : Number.NaN;
|
|
1282
|
+
if (!current || !goalId || !Number.isSafeInteger(revision)) {
|
|
1283
|
+
sendJson(res, current ? 400 : 404, {
|
|
1284
|
+
ok: false,
|
|
1285
|
+
error: {
|
|
1286
|
+
code: current ? "GOAL_INVALID_INPUT" : "GOAL_NOT_FOUND",
|
|
1287
|
+
message: current
|
|
1288
|
+
? "goalId and integer revision are required"
|
|
1289
|
+
: "Goal not found",
|
|
1290
|
+
},
|
|
1291
|
+
});
|
|
1292
|
+
return;
|
|
1293
|
+
}
|
|
1294
|
+
if (req.method === "DELETE") {
|
|
1295
|
+
const result = registry.clear({
|
|
1296
|
+
sessionId,
|
|
1297
|
+
goalId,
|
|
1298
|
+
expectedRevision: revision,
|
|
1299
|
+
});
|
|
1300
|
+
if (!result.ok) {
|
|
1301
|
+
sendJson(res, goalHttpStatus(result.code), {
|
|
1302
|
+
ok: false,
|
|
1303
|
+
error: { code: result.code, message: result.message },
|
|
1304
|
+
goal: result.goal,
|
|
1305
|
+
});
|
|
1306
|
+
return;
|
|
1307
|
+
}
|
|
1308
|
+
deps.goalRoundDriver?.cancel(sessionId);
|
|
1309
|
+
sendJson(res, 200, { ok: true, goal: null });
|
|
1310
|
+
return;
|
|
1311
|
+
}
|
|
1312
|
+
if (req.method === "PATCH") {
|
|
1313
|
+
const action = typeof body.action === "string" ? body.action : "edit";
|
|
1314
|
+
let phase;
|
|
1315
|
+
let arm;
|
|
1316
|
+
if (action === "pause") {
|
|
1317
|
+
phase = "paused";
|
|
1318
|
+
arm = false;
|
|
1319
|
+
}
|
|
1320
|
+
else if (action === "resume") {
|
|
1321
|
+
phase = "active";
|
|
1322
|
+
arm = true;
|
|
1323
|
+
}
|
|
1324
|
+
else if (action === "edit") {
|
|
1325
|
+
phase = current.phase;
|
|
1326
|
+
arm = current.armed;
|
|
1327
|
+
}
|
|
1328
|
+
else {
|
|
1329
|
+
sendJson(res, 400, {
|
|
1330
|
+
ok: false,
|
|
1331
|
+
error: { code: "GOAL_INVALID_INPUT", message: "unsupported Goal action" },
|
|
1332
|
+
});
|
|
1333
|
+
return;
|
|
1334
|
+
}
|
|
1335
|
+
const result = registry.update({
|
|
1336
|
+
sessionId,
|
|
1337
|
+
goalId,
|
|
1338
|
+
expectedRevision: revision,
|
|
1339
|
+
phase,
|
|
1340
|
+
arm,
|
|
1341
|
+
...(body.objective !== undefined ? { objective: body.objective } : {}),
|
|
1342
|
+
});
|
|
1343
|
+
if (!result.ok) {
|
|
1344
|
+
sendJson(res, goalHttpStatus(result.code), {
|
|
1345
|
+
ok: false,
|
|
1346
|
+
error: { code: result.code, message: result.message },
|
|
1347
|
+
goal: result.goal,
|
|
1348
|
+
});
|
|
1349
|
+
return;
|
|
1350
|
+
}
|
|
1351
|
+
if (action === "resume")
|
|
1352
|
+
deps.goalRoundDriver?.wake(sessionId);
|
|
1353
|
+
else if (action === "pause")
|
|
1354
|
+
deps.goalRoundDriver?.cancel(sessionId);
|
|
1355
|
+
sendJson(res, 200, { ok: true, goal: result.goal });
|
|
1356
|
+
return;
|
|
1357
|
+
}
|
|
1358
|
+
sendJson(res, 405, {
|
|
1359
|
+
ok: false,
|
|
1360
|
+
error: { code: "METHOD_NOT_ALLOWED", message: "method not allowed" },
|
|
1361
|
+
});
|
|
1362
|
+
}
|
|
1363
|
+
export async function handleAnswerUserQuestion(req, res, deps, sessionId, requestId) {
|
|
1364
|
+
const gate = gateMutation(req, deps);
|
|
1365
|
+
if (!gate.ok) {
|
|
1366
|
+
sendJson(res, gate.status, { ok: false, error: { code: gate.code, message: gate.message } });
|
|
1367
|
+
return;
|
|
1368
|
+
}
|
|
1369
|
+
if (!(await requireChatSession(res, deps, sessionId)))
|
|
1370
|
+
return;
|
|
1371
|
+
if (!deps.questionRegistry) {
|
|
1372
|
+
sendJson(res, 503, { ok: false, error: { code: "USER_QUESTIONS_UNAVAILABLE", message: "user question capability is unavailable" } });
|
|
1373
|
+
return;
|
|
1374
|
+
}
|
|
1375
|
+
try {
|
|
1376
|
+
const body = await readJsonBody(req);
|
|
1377
|
+
const question = await deps.questionRegistry.answer(sessionId, requestId, body);
|
|
1378
|
+
sendJson(res, 200, { ok: true, resolved: true, question });
|
|
1379
|
+
}
|
|
1380
|
+
catch (error) {
|
|
1381
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1382
|
+
const status = message === "USER_QUESTION_NOT_FOUND" ? 404 : message === "USER_QUESTION_STALE" ? 409 : 400;
|
|
1383
|
+
sendJson(res, status, { ok: false, error: { code: message, message } });
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
export async function handleCancelUserQuestion(req, res, deps, sessionId, requestId) {
|
|
1387
|
+
const gate = gateMutation(req, deps);
|
|
1388
|
+
if (!gate.ok) {
|
|
1389
|
+
sendJson(res, gate.status, { ok: false, error: { code: gate.code, message: gate.message } });
|
|
1390
|
+
return;
|
|
1391
|
+
}
|
|
1392
|
+
if (!(await requireChatSession(res, deps, sessionId)))
|
|
1393
|
+
return;
|
|
1394
|
+
if (!deps.questionRegistry) {
|
|
1395
|
+
sendJson(res, 503, { ok: false, error: { code: "USER_QUESTIONS_UNAVAILABLE", message: "user question capability is unavailable" } });
|
|
1396
|
+
return;
|
|
1397
|
+
}
|
|
1398
|
+
try {
|
|
1399
|
+
const body = await readJsonBody(req).catch(() => ({}));
|
|
1400
|
+
const reason = typeof body.reason === "string" && body.reason.trim() ? body.reason.trim().slice(0, 120) : "USER_CANCELLED";
|
|
1401
|
+
const question = await deps.questionRegistry.cancel(sessionId, requestId, reason);
|
|
1402
|
+
sendJson(res, 200, { ok: true, cancelled: true, question });
|
|
1403
|
+
}
|
|
1404
|
+
catch (error) {
|
|
1405
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1406
|
+
const status = message === "USER_QUESTION_NOT_FOUND" ? 404 : 409;
|
|
1407
|
+
sendJson(res, status, { ok: false, error: { code: message, message } });
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
701
1410
|
export async function handleListChatSessions(_req, res, deps) {
|
|
702
|
-
const sessions = await deps
|
|
1411
|
+
const sessions = await listChatSessionSummaries(deps);
|
|
703
1412
|
sendJson(res, 200, {
|
|
704
1413
|
ok: true,
|
|
705
1414
|
schemaVersion: 2,
|
|
706
|
-
sessions
|
|
707
|
-
...session,
|
|
708
|
-
activeTurnId: deps.events.getActiveTurn(session.sessionId)?.turnId,
|
|
709
|
-
})),
|
|
1415
|
+
sessions,
|
|
710
1416
|
hasBash: true,
|
|
711
1417
|
});
|
|
712
1418
|
}
|
|
1419
|
+
/**
|
|
1420
|
+
* Build sidebar-only summaries from one Workspace store without opening a
|
|
1421
|
+
* runtime. Message bodies, Pi session paths and tool audit rows belong to the
|
|
1422
|
+
* detail endpoint; returning them here makes the global multi-Workspace index
|
|
1423
|
+
* grow with the entire chat history.
|
|
1424
|
+
*/
|
|
1425
|
+
export async function listChatSessionSummaries(deps, ownerWorkspaceId) {
|
|
1426
|
+
const sessions = await deps.store.list({ includeArchived: true });
|
|
1427
|
+
return sessions.map((session) => {
|
|
1428
|
+
const active = deps.events?.getActiveTurn(session.sessionId);
|
|
1429
|
+
const workspaceId = ownerWorkspaceId ?? session.workspaceId;
|
|
1430
|
+
return {
|
|
1431
|
+
sessionId: session.sessionId,
|
|
1432
|
+
...(workspaceId ? { workspaceId } : {}),
|
|
1433
|
+
state: session.state,
|
|
1434
|
+
createdAt: session.createdAt,
|
|
1435
|
+
updatedAt: session.updatedAt,
|
|
1436
|
+
...(session.title !== undefined ? { title: session.title } : {}),
|
|
1437
|
+
...(session.displayTitle !== undefined
|
|
1438
|
+
? { displayTitle: session.displayTitle }
|
|
1439
|
+
: {}),
|
|
1440
|
+
...(session.modelProvider !== undefined
|
|
1441
|
+
? { modelProvider: session.modelProvider }
|
|
1442
|
+
: {}),
|
|
1443
|
+
...(session.modelId !== undefined ? { modelId: session.modelId } : {}),
|
|
1444
|
+
...(session.thinkingLevel !== undefined
|
|
1445
|
+
? { thinkingLevel: session.thinkingLevel }
|
|
1446
|
+
: {}),
|
|
1447
|
+
activeTurnId: active?.turnId,
|
|
1448
|
+
turnPhase: active?.abortRequestedAt
|
|
1449
|
+
? "stopping"
|
|
1450
|
+
: active
|
|
1451
|
+
? "running"
|
|
1452
|
+
: "idle",
|
|
1453
|
+
deferredTurn: projectDeferredTurnSummary(session.deferredTurns?.[0]),
|
|
1454
|
+
deferredTurns: projectDeferredTurnSummaries(session.deferredTurns ?? []),
|
|
1455
|
+
isBlank: isBlankChatSession(session) && !active,
|
|
1456
|
+
};
|
|
1457
|
+
});
|
|
1458
|
+
}
|
|
713
1459
|
export async function handlePatchChatSession(req, res, deps, sessionId) {
|
|
714
1460
|
const gate = gateMutation(req, deps);
|
|
715
1461
|
if (!gate.ok) {
|
|
@@ -737,7 +1483,7 @@ export async function handlePatchChatSession(req, res, deps, sessionId) {
|
|
|
737
1483
|
});
|
|
738
1484
|
return;
|
|
739
1485
|
}
|
|
740
|
-
sendJson(res, 200, { ok: true, session: record });
|
|
1486
|
+
sendJson(res, 200, { ok: true, session: projectBrowserChatSession(record) });
|
|
741
1487
|
}
|
|
742
1488
|
catch (error) {
|
|
743
1489
|
sendJson(res, 404, {
|
|
@@ -787,10 +1533,7 @@ export async function handleReopenChatSession(req, res, deps, sessionId) {
|
|
|
787
1533
|
: {}),
|
|
788
1534
|
});
|
|
789
1535
|
if (!result.ok) {
|
|
790
|
-
const mapped =
|
|
791
|
-
code: result.code,
|
|
792
|
-
message: result.message,
|
|
793
|
-
});
|
|
1536
|
+
const mapped = await mapFailedReopen(deps, sessionId, result);
|
|
794
1537
|
sendJson(res, mapped.status, {
|
|
795
1538
|
ok: false,
|
|
796
1539
|
error: { code: mapped.code, message: mapped.message },
|
|
@@ -876,10 +1619,7 @@ export async function handleChatPrompt(req, res, deps, sessionId) {
|
|
|
876
1619
|
: {}),
|
|
877
1620
|
});
|
|
878
1621
|
if (!reopen.ok) {
|
|
879
|
-
const mapped =
|
|
880
|
-
code: reopen.code,
|
|
881
|
-
message: reopen.message,
|
|
882
|
-
});
|
|
1622
|
+
const mapped = await mapFailedReopen(deps, sessionId, reopen);
|
|
883
1623
|
sendJson(res, mapped.status, {
|
|
884
1624
|
ok: false,
|
|
885
1625
|
error: { code: mapped.code, message: mapped.message },
|
|
@@ -951,6 +1691,7 @@ export async function handleChatPrompt(req, res, deps, sessionId) {
|
|
|
951
1691
|
store: deps.store,
|
|
952
1692
|
actionContext,
|
|
953
1693
|
sessionId,
|
|
1694
|
+
turnId,
|
|
954
1695
|
text,
|
|
955
1696
|
images,
|
|
956
1697
|
signal: ac.signal,
|
|
@@ -966,6 +1707,9 @@ export async function handleChatPrompt(req, res, deps, sessionId) {
|
|
|
966
1707
|
if (!res.writableEnded)
|
|
967
1708
|
writeChatSse(res, persisted);
|
|
968
1709
|
},
|
|
1710
|
+
onSteeringMessagePersisted: async (_record, userMessage, accepted) => {
|
|
1711
|
+
await persistAcceptedSteering(deps, sessionId, turnId, userMessage, accepted.clientRequestId);
|
|
1712
|
+
},
|
|
969
1713
|
onOperationAccepted: (accepted) => deps.operationLinker.link({
|
|
970
1714
|
sessionId,
|
|
971
1715
|
turnId,
|
|
@@ -1057,49 +1801,63 @@ export async function handleChatPrompt(req, res, deps, sessionId) {
|
|
|
1057
1801
|
* Pi prompt continues independently of this HTTP response and publishes to the
|
|
1058
1802
|
* persisted event ring consumed by GET /events.
|
|
1059
1803
|
*/
|
|
1060
|
-
export async function handleCreateChatTurn(req, res, deps, sessionId) {
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
})
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
body = await readJsonBody(req);
|
|
1073
|
-
}
|
|
1074
|
-
catch (error) {
|
|
1075
|
-
sendJson(res, 400, {
|
|
1076
|
-
ok: false,
|
|
1077
|
-
accepted: false,
|
|
1078
|
-
error: {
|
|
1079
|
-
code: "INVALID_INPUT",
|
|
1080
|
-
message: error instanceof Error ? error.message : String(error),
|
|
1081
|
-
},
|
|
1082
|
-
});
|
|
1083
|
-
return;
|
|
1084
|
-
}
|
|
1085
|
-
const text = typeof body.text === "string" ? body.text.trim() : "";
|
|
1086
|
-
const clientRequestId = typeof body.clientRequestId === "string" && body.clientRequestId.trim()
|
|
1087
|
-
? body.clientRequestId.trim()
|
|
1088
|
-
: undefined;
|
|
1089
|
-
let images;
|
|
1090
|
-
try {
|
|
1091
|
-
images = parseChatImages(body.images);
|
|
1804
|
+
export async function handleCreateChatTurn(req, res, deps, sessionId, trustedPayload) {
|
|
1805
|
+
let text;
|
|
1806
|
+
let clientRequestId;
|
|
1807
|
+
let images;
|
|
1808
|
+
if (trustedPayload) {
|
|
1809
|
+
text = trustedPayload.text.trim();
|
|
1810
|
+
clientRequestId = trustedPayload.clientRequestId.trim();
|
|
1811
|
+
images = trustedPayload.images.map(({ type, mimeType, data }) => ({
|
|
1812
|
+
type,
|
|
1813
|
+
mimeType,
|
|
1814
|
+
data,
|
|
1815
|
+
}));
|
|
1092
1816
|
}
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
}
|
|
1101
|
-
|
|
1102
|
-
|
|
1817
|
+
else {
|
|
1818
|
+
const gate = gateMutation(req, deps);
|
|
1819
|
+
if (!gate.ok) {
|
|
1820
|
+
sendJson(res, gate.status, {
|
|
1821
|
+
ok: false,
|
|
1822
|
+
accepted: false,
|
|
1823
|
+
error: { code: gate.code, message: gate.message },
|
|
1824
|
+
});
|
|
1825
|
+
return;
|
|
1826
|
+
}
|
|
1827
|
+
let body;
|
|
1828
|
+
try {
|
|
1829
|
+
body = await readJsonBody(req);
|
|
1830
|
+
}
|
|
1831
|
+
catch (error) {
|
|
1832
|
+
sendJson(res, 400, {
|
|
1833
|
+
ok: false,
|
|
1834
|
+
accepted: false,
|
|
1835
|
+
error: {
|
|
1836
|
+
code: "INVALID_INPUT",
|
|
1837
|
+
message: error instanceof Error ? error.message : String(error),
|
|
1838
|
+
},
|
|
1839
|
+
});
|
|
1840
|
+
return;
|
|
1841
|
+
}
|
|
1842
|
+
text = typeof body.text === "string" ? body.text.trim() : "";
|
|
1843
|
+
clientRequestId =
|
|
1844
|
+
typeof body.clientRequestId === "string" && body.clientRequestId.trim()
|
|
1845
|
+
? body.clientRequestId.trim()
|
|
1846
|
+
: undefined;
|
|
1847
|
+
try {
|
|
1848
|
+
images = parseChatImages(body.images);
|
|
1849
|
+
}
|
|
1850
|
+
catch (error) {
|
|
1851
|
+
sendJson(res, 400, {
|
|
1852
|
+
ok: false,
|
|
1853
|
+
accepted: false,
|
|
1854
|
+
error: {
|
|
1855
|
+
code: "INVALID_ATTACHMENT",
|
|
1856
|
+
message: error instanceof Error ? error.message : String(error),
|
|
1857
|
+
},
|
|
1858
|
+
});
|
|
1859
|
+
return;
|
|
1860
|
+
}
|
|
1103
1861
|
}
|
|
1104
1862
|
if (!text) {
|
|
1105
1863
|
sendJson(res, 400, {
|
|
@@ -1130,10 +1888,7 @@ export async function handleCreateChatTurn(req, res, deps, sessionId) {
|
|
|
1130
1888
|
: {}),
|
|
1131
1889
|
});
|
|
1132
1890
|
if (!reopen.ok) {
|
|
1133
|
-
const mapped =
|
|
1134
|
-
code: reopen.code,
|
|
1135
|
-
message: reopen.message,
|
|
1136
|
-
});
|
|
1891
|
+
const mapped = await mapFailedReopen(deps, sessionId, reopen);
|
|
1137
1892
|
sendJson(res, mapped.status, {
|
|
1138
1893
|
ok: false,
|
|
1139
1894
|
accepted: false,
|
|
@@ -1197,6 +1952,22 @@ export async function handleCreateChatTurn(req, res, deps, sessionId) {
|
|
|
1197
1952
|
});
|
|
1198
1953
|
return;
|
|
1199
1954
|
}
|
|
1955
|
+
try {
|
|
1956
|
+
trustedPayload?.onTurnCreated?.(turn.turnId);
|
|
1957
|
+
}
|
|
1958
|
+
catch (error) {
|
|
1959
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
1960
|
+
deps.events.setTurnState(sessionId, turn.turnId, "failed", {
|
|
1961
|
+
code: "GOAL_ADMISSION_STALE",
|
|
1962
|
+
message,
|
|
1963
|
+
});
|
|
1964
|
+
sendJson(res, 409, {
|
|
1965
|
+
ok: false,
|
|
1966
|
+
accepted: false,
|
|
1967
|
+
error: { code: "GOAL_ADMISSION_STALE", message },
|
|
1968
|
+
});
|
|
1969
|
+
return;
|
|
1970
|
+
}
|
|
1200
1971
|
const controller = new AbortController();
|
|
1201
1972
|
const execution = deps.turnExecutions?.register({
|
|
1202
1973
|
sessionId,
|
|
@@ -1232,10 +2003,12 @@ export async function handleCreateChatTurn(req, res, deps, sessionId) {
|
|
|
1232
2003
|
store: deps.store,
|
|
1233
2004
|
actionContext,
|
|
1234
2005
|
sessionId,
|
|
2006
|
+
turnId: turn.turnId,
|
|
1235
2007
|
text,
|
|
1236
2008
|
images,
|
|
1237
2009
|
signal: controller.signal,
|
|
1238
|
-
onUserMessagePersisted: (record) => {
|
|
2010
|
+
onUserMessagePersisted: async (record, userMessage) => {
|
|
2011
|
+
await trustedPayload?.onUserMessagePersisted?.(turn.turnId, userMessage);
|
|
1239
2012
|
const users = record.messages.filter((message) => message.role === "user");
|
|
1240
2013
|
if (users.length !== 1)
|
|
1241
2014
|
return;
|
|
@@ -1244,6 +2017,10 @@ export async function handleCreateChatTurn(req, res, deps, sessionId) {
|
|
|
1244
2017
|
if (placeholder)
|
|
1245
2018
|
emitSessionTitle(deps, sessionId, turn.turnId, placeholder);
|
|
1246
2019
|
},
|
|
2020
|
+
onSteeringMessagePersisted: async (_record, userMessage, accepted) => {
|
|
2021
|
+
await persistAcceptedSteering(deps, sessionId, turn.turnId, userMessage, accepted.clientRequestId);
|
|
2022
|
+
},
|
|
2023
|
+
persistUserMessage: trustedPayload?.persistUserMessage,
|
|
1247
2024
|
onOperationAccepted: (accepted) => deps.operationLinker.link({
|
|
1248
2025
|
sessionId,
|
|
1249
2026
|
turnId: turn.turnId,
|
|
@@ -1306,15 +2083,336 @@ export async function handleCreateChatTurn(req, res, deps, sessionId) {
|
|
|
1306
2083
|
}
|
|
1307
2084
|
}
|
|
1308
2085
|
finally {
|
|
2086
|
+
if (terminalState !== "settled") {
|
|
2087
|
+
pauseGoalForSafety(deps, sessionId, turn.turnId);
|
|
2088
|
+
deps.goalRoundDriver?.cancel(sessionId);
|
|
2089
|
+
}
|
|
1309
2090
|
execution?.resolveCompletion({
|
|
1310
2091
|
ok: terminalState === "settled",
|
|
1311
2092
|
state: terminalState,
|
|
1312
2093
|
error: terminalError,
|
|
1313
2094
|
});
|
|
1314
2095
|
deps.turnExecutions?.clear(sessionId, turn.turnId);
|
|
2096
|
+
void dispatchDeferredTurn(deps, sessionId).finally(() => {
|
|
2097
|
+
deps.goalRoundDriver?.wake(sessionId);
|
|
2098
|
+
});
|
|
1315
2099
|
}
|
|
1316
2100
|
})();
|
|
1317
2101
|
}
|
|
2102
|
+
function buildGoalRoundPrompt(goal) {
|
|
2103
|
+
const remaining = Math.max(0, goal.maxRounds - goal.round);
|
|
2104
|
+
return [
|
|
2105
|
+
buildGoalContinuationContext(goal),
|
|
2106
|
+
`This is autonomous Goal round ${goal.round + 1} of at most ${goal.maxRounds} (${remaining} rounds remain before this one).`,
|
|
2107
|
+
"Continue from the current session state. Prefer the user's queued or newly supplied instructions when present. Use todo_write for multi-step work.",
|
|
2108
|
+
"Before ending this round, call get_goal. If the objective is fully achieved, call update_goal(status=complete). If no safe progress remains, call update_goal(status=blocked) with the concrete blocker. Otherwise leave it active for the next bounded round.",
|
|
2109
|
+
].filter(Boolean).join("\n\n");
|
|
2110
|
+
}
|
|
2111
|
+
function pauseGoalForSafety(deps, sessionId, turnId) {
|
|
2112
|
+
const current = deps.goalRegistry?.get(sessionId);
|
|
2113
|
+
if (!current || current.phase !== "active") {
|
|
2114
|
+
deps.goalRegistry?.disarm(sessionId);
|
|
2115
|
+
return;
|
|
2116
|
+
}
|
|
2117
|
+
deps.goalRegistry?.update({
|
|
2118
|
+
sessionId,
|
|
2119
|
+
goalId: current.goalId,
|
|
2120
|
+
expectedRevision: current.revision,
|
|
2121
|
+
phase: "paused",
|
|
2122
|
+
arm: false,
|
|
2123
|
+
turnId,
|
|
2124
|
+
});
|
|
2125
|
+
}
|
|
2126
|
+
export function linkedOperationIdsForGoal(events) {
|
|
2127
|
+
const linked = new Set();
|
|
2128
|
+
for (const event of events) {
|
|
2129
|
+
const operationId = event.data && typeof event.data === "object"
|
|
2130
|
+
? event.data.operationId
|
|
2131
|
+
: undefined;
|
|
2132
|
+
if (typeof operationId !== "string" || !operationId)
|
|
2133
|
+
continue;
|
|
2134
|
+
if (event.kind === "operation-ref" || event.kind === "operation-status")
|
|
2135
|
+
linked.add(operationId);
|
|
2136
|
+
if (event.kind === "operation-unlinked")
|
|
2137
|
+
linked.delete(operationId);
|
|
2138
|
+
}
|
|
2139
|
+
return [...linked];
|
|
2140
|
+
}
|
|
2141
|
+
/** One admission attempt used by the process-local GoalRoundDriver. */
|
|
2142
|
+
export async function driveGoalRound(deps, sessionId) {
|
|
2143
|
+
const registry = deps.goalRegistry;
|
|
2144
|
+
if (!registry || !registry.isArmed(sessionId))
|
|
2145
|
+
return "idle";
|
|
2146
|
+
const goal = registry.get(sessionId);
|
|
2147
|
+
if (!goal || goal.phase !== "active" || !goal.armed)
|
|
2148
|
+
return "idle";
|
|
2149
|
+
if (goal.round >= goal.maxRounds) {
|
|
2150
|
+
registry.update({
|
|
2151
|
+
sessionId,
|
|
2152
|
+
goalId: goal.goalId,
|
|
2153
|
+
expectedRevision: goal.revision,
|
|
2154
|
+
phase: "paused",
|
|
2155
|
+
arm: false,
|
|
2156
|
+
});
|
|
2157
|
+
return "idle";
|
|
2158
|
+
}
|
|
2159
|
+
const record = await deps.store.get(sessionId);
|
|
2160
|
+
if (!record) {
|
|
2161
|
+
registry.disarm(sessionId);
|
|
2162
|
+
return "idle";
|
|
2163
|
+
}
|
|
2164
|
+
const runtimeFacts = deps.runtime.getSessionBusyFacts(sessionId);
|
|
2165
|
+
const operationStore = deps.runtime.actionContext?.operations;
|
|
2166
|
+
const linkedOperationIds = linkedOperationIdsForGoal(deps.events.snapshot(sessionId));
|
|
2167
|
+
const operations = operationStore
|
|
2168
|
+
? await Promise.all(linkedOperationIds.map((operationId) => operationStore.get(operationId)))
|
|
2169
|
+
: [];
|
|
2170
|
+
const admission = classifyGoalRoundAdmission({
|
|
2171
|
+
phase: goal.phase,
|
|
2172
|
+
armed: goal.armed,
|
|
2173
|
+
round: goal.round,
|
|
2174
|
+
maxRounds: goal.maxRounds,
|
|
2175
|
+
hasQueuedUserTurn: (record.deferredTurns ?? []).some((item) => item.state === "queued" || item.state === "dispatching"),
|
|
2176
|
+
hasActiveTurn: Boolean(deps.events.getActiveTurn(sessionId)),
|
|
2177
|
+
runtimeBusy: Object.values(runtimeFacts).some((value) => value === true),
|
|
2178
|
+
operationBusy: operations.some((operation) => Boolean(operation) && !isTerminalOperationState(operation.state)),
|
|
2179
|
+
});
|
|
2180
|
+
if (admission.action === "wait")
|
|
2181
|
+
return "wait";
|
|
2182
|
+
if (admission.action === "idle")
|
|
2183
|
+
return "idle";
|
|
2184
|
+
const expectedRound = goal.round + 1;
|
|
2185
|
+
const clientRequestId = `goal:${goal.goalId}:${expectedRound}`;
|
|
2186
|
+
const started = await startTrustedChatTurn(deps, sessionId, {
|
|
2187
|
+
clientRequestId,
|
|
2188
|
+
text: buildGoalRoundPrompt(goal),
|
|
2189
|
+
images: [],
|
|
2190
|
+
persistUserMessage: false,
|
|
2191
|
+
onTurnCreated: (turnId) => {
|
|
2192
|
+
const advanced = registry.beginRound({
|
|
2193
|
+
sessionId,
|
|
2194
|
+
goalId: goal.goalId,
|
|
2195
|
+
expectedRevision: goal.revision,
|
|
2196
|
+
turnId,
|
|
2197
|
+
});
|
|
2198
|
+
if (!advanced.ok) {
|
|
2199
|
+
registry.disarm(sessionId);
|
|
2200
|
+
throw new Error(advanced.message);
|
|
2201
|
+
}
|
|
2202
|
+
},
|
|
2203
|
+
});
|
|
2204
|
+
const accepted = started.body.accepted === true;
|
|
2205
|
+
const turnId = started.body.turn && typeof started.body.turn === "object"
|
|
2206
|
+
? started.body.turn.turnId
|
|
2207
|
+
: undefined;
|
|
2208
|
+
if (!accepted || !turnId) {
|
|
2209
|
+
const code = started.body.error && typeof started.body.error === "object"
|
|
2210
|
+
? String(started.body.error.code ?? "")
|
|
2211
|
+
: "";
|
|
2212
|
+
if (code === "TURN_ACTIVE")
|
|
2213
|
+
return "wait";
|
|
2214
|
+
registry.disarm(sessionId);
|
|
2215
|
+
return "idle";
|
|
2216
|
+
}
|
|
2217
|
+
return "started";
|
|
2218
|
+
}
|
|
2219
|
+
async function emitDeferredTurnUpdate(deps, sessionId, turnId, _deferredTurn, _revision) {
|
|
2220
|
+
const record = await deps.store.get(sessionId);
|
|
2221
|
+
if (!record)
|
|
2222
|
+
return;
|
|
2223
|
+
deps.events.append(sessionId, turnId, {
|
|
2224
|
+
kind: "queue_update",
|
|
2225
|
+
data: {
|
|
2226
|
+
deferredTurn: projectDeferredTurnSummary(record.deferredTurns?.[0]),
|
|
2227
|
+
deferredTurns: projectDeferredTurnSummaries(record.deferredTurns ?? []),
|
|
2228
|
+
revision: record.deferredQueueRevision ?? 0,
|
|
2229
|
+
},
|
|
2230
|
+
});
|
|
2231
|
+
}
|
|
2232
|
+
async function startTrustedChatTurn(deps, sessionId, payload) {
|
|
2233
|
+
let status = 500;
|
|
2234
|
+
let raw = "";
|
|
2235
|
+
const response = {
|
|
2236
|
+
writeHead(code) {
|
|
2237
|
+
status = code;
|
|
2238
|
+
return this;
|
|
2239
|
+
},
|
|
2240
|
+
end(chunk) {
|
|
2241
|
+
if (chunk !== undefined)
|
|
2242
|
+
raw += Buffer.isBuffer(chunk) ? chunk.toString("utf8") : chunk;
|
|
2243
|
+
return this;
|
|
2244
|
+
},
|
|
2245
|
+
};
|
|
2246
|
+
await handleCreateChatTurn({}, response, deps, sessionId, payload);
|
|
2247
|
+
let body = {};
|
|
2248
|
+
try {
|
|
2249
|
+
body = raw ? JSON.parse(raw) : {};
|
|
2250
|
+
}
|
|
2251
|
+
catch {
|
|
2252
|
+
body = {};
|
|
2253
|
+
}
|
|
2254
|
+
return { status, body };
|
|
2255
|
+
}
|
|
2256
|
+
const deferredDispatchingSessions = new Set();
|
|
2257
|
+
/** Dispatch one durable follow-up through the exact normal Turn creation path. */
|
|
2258
|
+
export async function dispatchDeferredTurn(deps, sessionId) {
|
|
2259
|
+
if (deferredDispatchingSessions.has(sessionId))
|
|
2260
|
+
return;
|
|
2261
|
+
deferredDispatchingSessions.add(sessionId);
|
|
2262
|
+
try {
|
|
2263
|
+
let record = await deps.store.get(sessionId);
|
|
2264
|
+
let deferred = record?.deferredTurns?.find((item) => item.state === "dispatching" || item.state === "queued");
|
|
2265
|
+
if (!deferred)
|
|
2266
|
+
return;
|
|
2267
|
+
if (deferred.state === "accepted")
|
|
2268
|
+
return;
|
|
2269
|
+
if (deferred.state === "failed")
|
|
2270
|
+
return;
|
|
2271
|
+
if (deferred.state === "dispatching") {
|
|
2272
|
+
const existing = deps.events.findTurnByClientRequestId(sessionId, deferred.clientRequestId);
|
|
2273
|
+
if (existing) {
|
|
2274
|
+
const accepted = await deps.store.transitionDeferredTurn(sessionId, {
|
|
2275
|
+
expectedRevision: deferred.revision,
|
|
2276
|
+
clientRequestId: deferred.clientRequestId,
|
|
2277
|
+
state: "accepted",
|
|
2278
|
+
acceptedTurnId: existing.turnId,
|
|
2279
|
+
});
|
|
2280
|
+
if (accepted)
|
|
2281
|
+
await emitDeferredTurnUpdate(deps, sessionId, existing.turnId, accepted, accepted.revision);
|
|
2282
|
+
return;
|
|
2283
|
+
}
|
|
2284
|
+
if (deps.events.getActiveTurn(sessionId))
|
|
2285
|
+
return;
|
|
2286
|
+
const requeued = await deps.store.transitionDeferredTurn(sessionId, {
|
|
2287
|
+
expectedRevision: deferred.revision,
|
|
2288
|
+
clientRequestId: deferred.clientRequestId,
|
|
2289
|
+
state: "queued",
|
|
2290
|
+
});
|
|
2291
|
+
if (!requeued)
|
|
2292
|
+
return;
|
|
2293
|
+
deferred = requeued;
|
|
2294
|
+
}
|
|
2295
|
+
const runtimeFacts = deps.runtime.getSessionBusyFacts?.(sessionId);
|
|
2296
|
+
const runtimeBusy = Boolean(runtimeFacts && Object.values(runtimeFacts).some((value) => value === true));
|
|
2297
|
+
if (deps.events.getActiveTurn(sessionId) || runtimeBusy)
|
|
2298
|
+
return;
|
|
2299
|
+
const claim = await deps.store.claimDeferredTurn(sessionId, deferred.revision, deferred.clientRequestId);
|
|
2300
|
+
if (!claim.ok)
|
|
2301
|
+
return;
|
|
2302
|
+
deferred = claim.deferredTurn;
|
|
2303
|
+
await emitDeferredTurnUpdate(deps, sessionId, deferred.blockedByTurnId, deferred, deferred.revision);
|
|
2304
|
+
const started = await startTrustedChatTurn(deps, sessionId, {
|
|
2305
|
+
clientRequestId: deferred.clientRequestId,
|
|
2306
|
+
text: deferred.text,
|
|
2307
|
+
images: deferred.images,
|
|
2308
|
+
onUserMessagePersisted: async (turnId, userMessage) => {
|
|
2309
|
+
deps.events.append(sessionId, turnId, {
|
|
2310
|
+
kind: "user_message",
|
|
2311
|
+
data: {
|
|
2312
|
+
clientRequestId: deferred.clientRequestId,
|
|
2313
|
+
message: {
|
|
2314
|
+
id: userMessage.id,
|
|
2315
|
+
text: userMessage.text,
|
|
2316
|
+
at: userMessage.at,
|
|
2317
|
+
},
|
|
2318
|
+
},
|
|
2319
|
+
});
|
|
2320
|
+
const cleared = await deps.store.clearDeferredTurnForRequest(sessionId, deferred.clientRequestId);
|
|
2321
|
+
if (cleared)
|
|
2322
|
+
await emitDeferredTurnUpdate(deps, sessionId, turnId, undefined, cleared.clearedRevision);
|
|
2323
|
+
},
|
|
2324
|
+
});
|
|
2325
|
+
const accepted = started.body.accepted === true;
|
|
2326
|
+
const turn = started.body.turn && typeof started.body.turn === "object"
|
|
2327
|
+
? started.body.turn
|
|
2328
|
+
: undefined;
|
|
2329
|
+
if (accepted && turn?.turnId) {
|
|
2330
|
+
const next = await deps.store.transitionDeferredTurn(sessionId, {
|
|
2331
|
+
expectedRevision: deferred.revision,
|
|
2332
|
+
clientRequestId: deferred.clientRequestId,
|
|
2333
|
+
state: "accepted",
|
|
2334
|
+
acceptedTurnId: turn.turnId,
|
|
2335
|
+
});
|
|
2336
|
+
if (next)
|
|
2337
|
+
await emitDeferredTurnUpdate(deps, sessionId, turn.turnId, next, next.revision);
|
|
2338
|
+
return;
|
|
2339
|
+
}
|
|
2340
|
+
const error = started.body.error && typeof started.body.error === "object"
|
|
2341
|
+
? started.body.error
|
|
2342
|
+
: {};
|
|
2343
|
+
if (error.code === "TURN_ACTIVE") {
|
|
2344
|
+
const next = await deps.store.transitionDeferredTurn(sessionId, {
|
|
2345
|
+
expectedRevision: deferred.revision,
|
|
2346
|
+
clientRequestId: deferred.clientRequestId,
|
|
2347
|
+
state: "queued",
|
|
2348
|
+
});
|
|
2349
|
+
if (next)
|
|
2350
|
+
await emitDeferredTurnUpdate(deps, sessionId, deferred.blockedByTurnId, next, next.revision);
|
|
2351
|
+
return;
|
|
2352
|
+
}
|
|
2353
|
+
const failed = await deps.store.transitionDeferredTurn(sessionId, {
|
|
2354
|
+
expectedRevision: deferred.revision,
|
|
2355
|
+
clientRequestId: deferred.clientRequestId,
|
|
2356
|
+
state: "failed",
|
|
2357
|
+
lastError: {
|
|
2358
|
+
code: error.code ?? `HTTP_${started.status}`,
|
|
2359
|
+
message: error.message ?? "停止后的消息未能自动发送",
|
|
2360
|
+
},
|
|
2361
|
+
});
|
|
2362
|
+
if (failed)
|
|
2363
|
+
await emitDeferredTurnUpdate(deps, sessionId, deferred.blockedByTurnId, failed, failed.revision);
|
|
2364
|
+
}
|
|
2365
|
+
catch (error) {
|
|
2366
|
+
// Keep fire-and-forget callers safe and make a dispatch failure visible and
|
|
2367
|
+
// recoverable from the composer instead of leaving the slot indefinitely
|
|
2368
|
+
// in an ambiguous queued/dispatching state.
|
|
2369
|
+
try {
|
|
2370
|
+
const current = (await deps.store.get(sessionId))?.deferredTurns?.find((item) => item.state === "queued" || item.state === "dispatching");
|
|
2371
|
+
if (current && (current.state === "queued" || current.state === "dispatching")) {
|
|
2372
|
+
const failed = await deps.store.transitionDeferredTurn(sessionId, {
|
|
2373
|
+
expectedRevision: current.revision,
|
|
2374
|
+
clientRequestId: current.clientRequestId,
|
|
2375
|
+
state: "failed",
|
|
2376
|
+
lastError: {
|
|
2377
|
+
code: "DEFERRED_TURN_DISPATCH_FAILED",
|
|
2378
|
+
message: error instanceof Error ? error.message : String(error),
|
|
2379
|
+
},
|
|
2380
|
+
});
|
|
2381
|
+
if (failed)
|
|
2382
|
+
await emitDeferredTurnUpdate(deps, sessionId, failed.blockedByTurnId, failed, failed.revision);
|
|
2383
|
+
}
|
|
2384
|
+
}
|
|
2385
|
+
catch {
|
|
2386
|
+
// The durable store itself is unavailable. Leave the original record in
|
|
2387
|
+
// place so a later Console boot can recover it.
|
|
2388
|
+
}
|
|
2389
|
+
}
|
|
2390
|
+
finally {
|
|
2391
|
+
deferredDispatchingSessions.delete(sessionId);
|
|
2392
|
+
}
|
|
2393
|
+
}
|
|
2394
|
+
export async function recoverDeferredTurns(deps) {
|
|
2395
|
+
const sessions = await deps.store.list({ includeArchived: false });
|
|
2396
|
+
await Promise.all(sessions
|
|
2397
|
+
.filter((session) => (session.deferredTurns ?? []).some((item) => item.state === "queued" || item.state === "dispatching"))
|
|
2398
|
+
.map(async (session) => {
|
|
2399
|
+
const deferred = session.deferredTurns.find((item) => item.state === "dispatching" || item.state === "queued");
|
|
2400
|
+
const active = deps.events.getActiveTurn(session.sessionId);
|
|
2401
|
+
// A process restart cannot retain AbortController ownership. When the
|
|
2402
|
+
// durable blocker was already stopping and no execution owns it now,
|
|
2403
|
+
// close that orphan before dispatching the server-owned follow-up.
|
|
2404
|
+
if (active?.turnId === deferred.blockedByTurnId &&
|
|
2405
|
+
active.abortRequestedAt &&
|
|
2406
|
+
deps.turnExecutions &&
|
|
2407
|
+
!deps.turnExecutions.get(session.sessionId, active.turnId)) {
|
|
2408
|
+
deps.events.setTurnState(session.sessionId, active.turnId, "failed", {
|
|
2409
|
+
code: "CHAT_TURN_OWNER_LOST",
|
|
2410
|
+
message: "turn ownership was lost during Console restart",
|
|
2411
|
+
});
|
|
2412
|
+
}
|
|
2413
|
+
await dispatchDeferredTurn(deps, session.sessionId);
|
|
2414
|
+
}));
|
|
2415
|
+
}
|
|
1318
2416
|
/** Real server-side abort: invokes Pi session.abort via the execution registry. */
|
|
1319
2417
|
export async function handleAbortChatTurn(req, res, deps, sessionId, turnId) {
|
|
1320
2418
|
const gate = gateMutation(req, deps);
|
|
@@ -1338,6 +2436,8 @@ export async function handleAbortChatTurn(req, res, deps, sessionId, turnId) {
|
|
|
1338
2436
|
});
|
|
1339
2437
|
return;
|
|
1340
2438
|
}
|
|
2439
|
+
pauseGoalForSafety(deps, sessionId, turnId);
|
|
2440
|
+
deps.goalRoundDriver?.cancel(sessionId);
|
|
1341
2441
|
if (isTerminalTurnState(turn.state)) {
|
|
1342
2442
|
sendJson(res, 200, {
|
|
1343
2443
|
ok: true,
|
|
@@ -1365,34 +2465,24 @@ export async function handleAbortChatTurn(req, res, deps, sessionId, turnId) {
|
|
|
1365
2465
|
});
|
|
1366
2466
|
return;
|
|
1367
2467
|
}
|
|
1368
|
-
deps.events.markAbortRequested?.(sessionId, turnId);
|
|
2468
|
+
const stopping = deps.events.markAbortRequested?.(sessionId, turnId) ?? turn;
|
|
2469
|
+
// DSH-style acknowledgement: deliver the AbortSignal synchronously, then let
|
|
2470
|
+
// the detached Turn closeout own SDK/process cleanup and terminal persistence.
|
|
2471
|
+
// The HTTP request reports that Stop was accepted; it does not wait for Pi to
|
|
2472
|
+
// become idle. This keeps cancellation latency independent of slow providers,
|
|
2473
|
+
// tools and process-tree cleanup while preserving the active-Turn lease.
|
|
1369
2474
|
if (!execution.controller.signal.aborted)
|
|
1370
2475
|
execution.controller.abort();
|
|
1371
|
-
const
|
|
1372
|
-
if (
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
...turn,
|
|
1376
|
-
state: waited.outcome.state,
|
|
1377
|
-
};
|
|
1378
|
-
sendJson(res, 200, {
|
|
1379
|
-
ok: true,
|
|
1380
|
-
accepted: true,
|
|
1381
|
-
idempotent: false,
|
|
1382
|
-
turn: turnSummary(finalTurn),
|
|
1383
|
-
});
|
|
1384
|
-
return;
|
|
1385
|
-
}
|
|
1386
|
-
// Timeout or missing completion: keep non-terminal; client reconciles via /state.
|
|
1387
|
-
const pending = deps.events.getTurn(sessionId, turnId) ?? turn;
|
|
2476
|
+
const questionCancellation = deps.questionRegistry?.cancelForSession(sessionId, "TURN_ABORTED");
|
|
2477
|
+
if (questionCancellation)
|
|
2478
|
+
void questionCancellation.catch(() => undefined);
|
|
2479
|
+
const acceptedTurn = deps.events.getTurn(sessionId, turnId) ?? stopping;
|
|
1388
2480
|
sendJson(res, 202, {
|
|
1389
|
-
ok:
|
|
1390
|
-
accepted:
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
},
|
|
1395
|
-
turn: turnSummary(pending),
|
|
2481
|
+
ok: true,
|
|
2482
|
+
accepted: true,
|
|
2483
|
+
idempotent: false,
|
|
2484
|
+
cleanupPending: !isTerminalTurnState(acceptedTurn.state),
|
|
2485
|
+
turn: turnSummary(acceptedTurn),
|
|
1396
2486
|
});
|
|
1397
2487
|
}
|
|
1398
2488
|
export async function handleGetChatTurn(_req, res, deps, sessionId, turnId) {
|
|
@@ -1516,6 +2606,10 @@ export async function handleDeleteChatSession(req, res, deps, sessionId) {
|
|
|
1516
2606
|
});
|
|
1517
2607
|
return;
|
|
1518
2608
|
}
|
|
2609
|
+
await deps.questionRegistry?.cancelForSession(sessionId, "SESSION_DELETED").catch(() => undefined);
|
|
2610
|
+
deps.todoRegistry?.clear(sessionId);
|
|
2611
|
+
deps.goalRegistry?.clearRuntime(sessionId);
|
|
2612
|
+
deps.goalRoundDriver?.cancel(sessionId);
|
|
1519
2613
|
deps.runtime.dispose(sessionId);
|
|
1520
2614
|
deps.operationLinker.clearSession(sessionId);
|
|
1521
2615
|
deps.events.clear(sessionId);
|
|
@@ -1531,6 +2625,7 @@ export async function handleDeleteChatSession(req, res, deps, sessionId) {
|
|
|
1531
2625
|
});
|
|
1532
2626
|
return;
|
|
1533
2627
|
}
|
|
2628
|
+
await deps.detachSession?.(sessionId).catch(() => undefined);
|
|
1534
2629
|
sendJson(res, 200, { ok: true, sessionId, disposed: true, removed: true });
|
|
1535
2630
|
}
|
|
1536
2631
|
export async function handleGetTaskContext(_res, res, deps, sessionId) {
|
|
@@ -1590,6 +2685,46 @@ async function handleRepoBrowser(res, deps, kind, rawPath) {
|
|
|
1590
2685
|
});
|
|
1591
2686
|
}
|
|
1592
2687
|
}
|
|
2688
|
+
async function handleRepoHtmlPreview(res, deps, rawPath) {
|
|
2689
|
+
try {
|
|
2690
|
+
const asset = await readRepoHtmlAsset(deps.appData.repoRoot, rawPath);
|
|
2691
|
+
const origin = deps.getConsoleOrigin();
|
|
2692
|
+
res.writeHead(200, {
|
|
2693
|
+
"Content-Type": asset.contentType,
|
|
2694
|
+
"Content-Length": asset.body.byteLength,
|
|
2695
|
+
"Cache-Control": "no-store",
|
|
2696
|
+
"X-Content-Type-Options": "nosniff",
|
|
2697
|
+
"Referrer-Policy": "no-referrer",
|
|
2698
|
+
// Project scripts may drive tabs and other local interactions, but the
|
|
2699
|
+
// opaque sandbox still withholds same-origin access, forms, popups and
|
|
2700
|
+
// top-level navigation. Network requests remain disabled below.
|
|
2701
|
+
"Content-Security-Policy": [
|
|
2702
|
+
"sandbox allow-scripts",
|
|
2703
|
+
"default-src 'none'",
|
|
2704
|
+
`script-src 'unsafe-inline' ${origin}`,
|
|
2705
|
+
"object-src 'none'",
|
|
2706
|
+
"frame-src 'none'",
|
|
2707
|
+
"form-action 'none'",
|
|
2708
|
+
"base-uri 'none'",
|
|
2709
|
+
"connect-src 'none'",
|
|
2710
|
+
`style-src 'unsafe-inline' ${origin}`,
|
|
2711
|
+
`img-src data: blob: ${origin}`,
|
|
2712
|
+
`font-src data: ${origin}`,
|
|
2713
|
+
`media-src blob: ${origin}`,
|
|
2714
|
+
].join("; "),
|
|
2715
|
+
});
|
|
2716
|
+
res.end(asset.body);
|
|
2717
|
+
}
|
|
2718
|
+
catch (error) {
|
|
2719
|
+
const failure = error instanceof RepoBrowserError
|
|
2720
|
+
? error
|
|
2721
|
+
: new RepoBrowserError(500, "READ_FAILED", error instanceof Error ? error.message : String(error));
|
|
2722
|
+
sendJson(res, failure.status, {
|
|
2723
|
+
ok: false,
|
|
2724
|
+
error: { code: failure.code, message: failure.message },
|
|
2725
|
+
});
|
|
2726
|
+
}
|
|
2727
|
+
}
|
|
1593
2728
|
async function handlePiConfig(req, res, deps, resource) {
|
|
1594
2729
|
try {
|
|
1595
2730
|
if (resource === "models") {
|
|
@@ -1679,6 +2814,9 @@ export async function handleChatCommands(res, deps, sessionId) {
|
|
|
1679
2814
|
res.end(JSON.stringify({
|
|
1680
2815
|
ok: true,
|
|
1681
2816
|
commands,
|
|
2817
|
+
capabilities: {
|
|
2818
|
+
sddBingo: Boolean(await deps.sddDataAlignment?.isEligible()),
|
|
2819
|
+
},
|
|
1682
2820
|
...(warning ? { warning } : {}),
|
|
1683
2821
|
}));
|
|
1684
2822
|
}
|
|
@@ -1689,10 +2827,46 @@ export async function handleChatCommands(res, deps, sessionId) {
|
|
|
1689
2827
|
res.end(JSON.stringify({
|
|
1690
2828
|
ok: true,
|
|
1691
2829
|
commands: [],
|
|
2830
|
+
capabilities: { sddBingo: false },
|
|
1692
2831
|
warning: error instanceof Error ? error.message : "commands unavailable",
|
|
1693
2832
|
}));
|
|
1694
2833
|
}
|
|
1695
2834
|
}
|
|
2835
|
+
async function handleSddBingo(req, res, deps, sessionId) {
|
|
2836
|
+
const gate = gateMutation(req, deps);
|
|
2837
|
+
if (!gate.ok) {
|
|
2838
|
+
sendJson(res, gate.status, { ok: false, error: { code: gate.code, message: gate.message } });
|
|
2839
|
+
return;
|
|
2840
|
+
}
|
|
2841
|
+
if (!deps.sddDataAlignment) {
|
|
2842
|
+
sendJson(res, 403, {
|
|
2843
|
+
ok: false,
|
|
2844
|
+
error: { code: "SDD_NOT_ELIGIBLE", message: "当前用户不可使用 SDD 数据对齐" },
|
|
2845
|
+
});
|
|
2846
|
+
return;
|
|
2847
|
+
}
|
|
2848
|
+
try {
|
|
2849
|
+
const body = await readJsonBody(req);
|
|
2850
|
+
if (Object.keys(body).some((key) => key !== "skillName")) {
|
|
2851
|
+
throw new SddDataAlignmentError("SDD_INVALID_SKILL_NAME", "请求体只允许 skillName 字段", 400);
|
|
2852
|
+
}
|
|
2853
|
+
await deps.sddDataAlignment.report(sessionId, body.skillName);
|
|
2854
|
+
sendJson(res, 200, { ok: true });
|
|
2855
|
+
}
|
|
2856
|
+
catch (error) {
|
|
2857
|
+
if (error instanceof SddDataAlignmentError) {
|
|
2858
|
+
sendJson(res, error.status, {
|
|
2859
|
+
ok: false,
|
|
2860
|
+
error: { code: error.code, message: error.message },
|
|
2861
|
+
});
|
|
2862
|
+
return;
|
|
2863
|
+
}
|
|
2864
|
+
sendJson(res, 502, {
|
|
2865
|
+
ok: false,
|
|
2866
|
+
error: { code: "SDD_UPSTREAM_FAILED", message: "SDD 数据对齐上报失败" },
|
|
2867
|
+
});
|
|
2868
|
+
}
|
|
2869
|
+
}
|
|
1696
2870
|
export async function handleRuntimeContext(res, deps, sessionId) {
|
|
1697
2871
|
const ensured = await ensureActiveSession(deps, sessionId);
|
|
1698
2872
|
if (!ensured.ok) {
|
|
@@ -1824,7 +2998,11 @@ export async function handleModels(req, res, deps, sessionId) {
|
|
|
1824
2998
|
// folded into a 409 MODEL_SWITCH_FAILED (the frontend refresh path
|
|
1825
2999
|
// re-reads the snapshot to converge on the applied selection).
|
|
1826
3000
|
const snapshot = await deps.runtime.getRuntimeSnapshot(sessionId);
|
|
1827
|
-
sendJson(res, 200, {
|
|
3001
|
+
sendJson(res, 200, {
|
|
3002
|
+
ok: true,
|
|
3003
|
+
session: projectBrowserChatSession(updated),
|
|
3004
|
+
snapshot,
|
|
3005
|
+
});
|
|
1828
3006
|
}
|
|
1829
3007
|
catch (error) {
|
|
1830
3008
|
if (error instanceof RuntimeSnapshotUnavailableError) {
|
|
@@ -1902,7 +3080,7 @@ export async function ensureActiveSession(deps, sessionId) {
|
|
|
1902
3080
|
: {}),
|
|
1903
3081
|
});
|
|
1904
3082
|
if (!reopened.ok) {
|
|
1905
|
-
return { ok: false, ...
|
|
3083
|
+
return { ok: false, ...(await mapFailedReopen(deps, sessionId, reopened)) };
|
|
1906
3084
|
}
|
|
1907
3085
|
return { ok: true };
|
|
1908
3086
|
}
|
|
@@ -2190,6 +3368,36 @@ async function handleLinkWorkspaceOperation(req, res, deps, sessionId) {
|
|
|
2190
3368
|
});
|
|
2191
3369
|
}
|
|
2192
3370
|
}
|
|
3371
|
+
async function handleUnlinkWorkspaceOperation(req, res, deps, sessionId, operationId) {
|
|
3372
|
+
const gate = gateMutation(req, deps);
|
|
3373
|
+
if (!gate.ok) {
|
|
3374
|
+
sendJson(res, gate.status, {
|
|
3375
|
+
ok: false,
|
|
3376
|
+
error: { code: gate.code, message: gate.message },
|
|
3377
|
+
});
|
|
3378
|
+
return;
|
|
3379
|
+
}
|
|
3380
|
+
if (!(await requireChatSession(res, deps, sessionId)))
|
|
3381
|
+
return;
|
|
3382
|
+
// AC-R7-001 (2026-08-23): removing a workspace-linked DAG association is
|
|
3383
|
+
// idempotent — a missing link is already-removed (200), never an error.
|
|
3384
|
+
try {
|
|
3385
|
+
const removed = await deps.operationLinker.unlink({
|
|
3386
|
+
sessionId,
|
|
3387
|
+
operationId,
|
|
3388
|
+
});
|
|
3389
|
+
sendJson(res, 200, { ok: true, removed });
|
|
3390
|
+
}
|
|
3391
|
+
catch (error) {
|
|
3392
|
+
sendJson(res, 400, {
|
|
3393
|
+
ok: false,
|
|
3394
|
+
error: {
|
|
3395
|
+
code: "INVALID_INPUT",
|
|
3396
|
+
message: error instanceof Error ? error.message : String(error),
|
|
3397
|
+
},
|
|
3398
|
+
});
|
|
3399
|
+
}
|
|
3400
|
+
}
|
|
2193
3401
|
async function handleStartInterview(req, res, deps, sessionId) {
|
|
2194
3402
|
const gate = gateMutation(req, deps);
|
|
2195
3403
|
if (!gate.ok) {
|
|
@@ -2305,7 +3513,7 @@ async function ctxConfirmationCard(deps, sessionId, turnId, confirmationId) {
|
|
|
2305
3513
|
taskId,
|
|
2306
3514
|
confirmationId,
|
|
2307
3515
|
expiresAt: confirmation.expiresAt,
|
|
2308
|
-
inspectHref:
|
|
3516
|
+
inspectHref: `/#/inspect?taskId=${encodeURIComponent(taskId)}`,
|
|
2309
3517
|
humanGateToken: confirmation.humanGateToken,
|
|
2310
3518
|
displayOnlyChallenges: [
|
|
2311
3519
|
"source",
|
|
@@ -2331,7 +3539,7 @@ async function ctxMutationGateCard(deps, sessionId, receiptId) {
|
|
|
2331
3539
|
receiptId: receipt.receiptId,
|
|
2332
3540
|
expiresAt: receipt.expiresAt,
|
|
2333
3541
|
humanGateToken: receipt.humanGateToken,
|
|
2334
|
-
inspectHref:
|
|
3542
|
+
inspectHref: `/#/inspect`,
|
|
2335
3543
|
}));
|
|
2336
3544
|
}
|
|
2337
3545
|
function actionResultBody(result) {
|
|
@@ -2420,7 +3628,7 @@ async function handleContractApplyHumanGate(req, res, deps, sessionId, step) {
|
|
|
2420
3628
|
humanGateToken,
|
|
2421
3629
|
contractRevision: binding.revision,
|
|
2422
3630
|
contractDiffSummary: `revision ${binding.revision}; draft ${binding.draftSha256.slice(0, 12)}; observed ${binding.expectedObservedHash.slice(0, 12)}`,
|
|
2423
|
-
inspectHref:
|
|
3631
|
+
inspectHref: `/#/inspect?taskId=${encodeURIComponent(taskId)}`,
|
|
2424
3632
|
});
|
|
2425
3633
|
appendHumanGateCard(deps, sessionId, card);
|
|
2426
3634
|
sendJson(res, 201, { ok: true, card });
|
|
@@ -2474,8 +3682,8 @@ async function handleContractApplyHumanGate(req, res, deps, sessionId, step) {
|
|
|
2474
3682
|
contractRevision: receipt.revision,
|
|
2475
3683
|
operationId,
|
|
2476
3684
|
inspectHref: operationId
|
|
2477
|
-
?
|
|
2478
|
-
:
|
|
3685
|
+
? `/#/inspect?operationId=${encodeURIComponent(operationId)}`
|
|
3686
|
+
: `/#/inspect?taskId=${encodeURIComponent(receipt.taskId)}`,
|
|
2479
3687
|
});
|
|
2480
3688
|
appendHumanGateCard(deps, sessionId, card);
|
|
2481
3689
|
sendJson(res, 202, {
|
|
@@ -2521,8 +3729,8 @@ async function handleContractApplyHumanGate(req, res, deps, sessionId, step) {
|
|
|
2521
3729
|
contractRevision: receipt.revision,
|
|
2522
3730
|
operationId,
|
|
2523
3731
|
inspectHref: operationId
|
|
2524
|
-
?
|
|
2525
|
-
:
|
|
3732
|
+
? `/#/inspect?operationId=${encodeURIComponent(operationId)}`
|
|
3733
|
+
: `/#/inspect?taskId=${encodeURIComponent(receipt.taskId)}`,
|
|
2526
3734
|
});
|
|
2527
3735
|
appendHumanGateCard(deps, sessionId, card);
|
|
2528
3736
|
if (operationId)
|
|
@@ -2623,8 +3831,8 @@ async function handleDagHumanGate(req, res, deps, sessionId, step) {
|
|
|
2623
3831
|
confirmationId,
|
|
2624
3832
|
expiresAt: String(confirmation?.expiresAt ?? new Date().toISOString()),
|
|
2625
3833
|
inspectHref: operationId
|
|
2626
|
-
?
|
|
2627
|
-
:
|
|
3834
|
+
? `/#/inspect?operationId=${encodeURIComponent(operationId)}`
|
|
3835
|
+
: `/#/inspect?taskId=${encodeURIComponent(taskId)}`,
|
|
2628
3836
|
...(confirmation?.humanGateToken
|
|
2629
3837
|
? { humanGateToken: confirmation.humanGateToken }
|
|
2630
3838
|
: {}),
|
|
@@ -2718,8 +3926,8 @@ async function handleMutationHumanGate(req, res, deps, sessionId) {
|
|
|
2718
3926
|
expiresAt: receipt.expiresAt,
|
|
2719
3927
|
operationId,
|
|
2720
3928
|
inspectHref: operationId
|
|
2721
|
-
?
|
|
2722
|
-
:
|
|
3929
|
+
? `/#/inspect?operationId=${encodeURIComponent(operationId)}`
|
|
3930
|
+
: `/#/inspect`,
|
|
2723
3931
|
});
|
|
2724
3932
|
appendHumanGateCard(deps, sessionId, card);
|
|
2725
3933
|
if (operationId) {
|
|
@@ -2819,10 +4027,7 @@ export async function handleChatCompact(req, res, deps, sessionId) {
|
|
|
2819
4027
|
: {}),
|
|
2820
4028
|
});
|
|
2821
4029
|
if (!reopened.ok) {
|
|
2822
|
-
const mapped =
|
|
2823
|
-
code: reopened.code,
|
|
2824
|
-
message: reopened.message,
|
|
2825
|
-
});
|
|
4030
|
+
const mapped = await mapFailedReopen(deps, sessionId, reopened);
|
|
2826
4031
|
sendJson(res, mapped.status, {
|
|
2827
4032
|
ok: false,
|
|
2828
4033
|
error: { code: mapped.code, message: mapped.message },
|
|
@@ -2842,14 +4047,60 @@ export async function handleChatCompact(req, res, deps, sessionId) {
|
|
|
2842
4047
|
return;
|
|
2843
4048
|
}
|
|
2844
4049
|
const rawInstructions = typeof body.instructions === "string" ? body.instructions : undefined;
|
|
2845
|
-
const
|
|
4050
|
+
const currentTodos = projectCurrentTodos(deps.events.snapshot(sessionId));
|
|
4051
|
+
const todoInstructions = buildTodoCompactionInstructions(rawInstructions, currentTodos);
|
|
4052
|
+
const customInstructions = buildGoalCompactionInstructions(todoInstructions, deps.goalRegistry?.get(sessionId) ?? null);
|
|
4053
|
+
const turnId = deps.events.latestTurnId(sessionId) ?? `${sessionId}:compact`;
|
|
4054
|
+
const compactionId = `${sessionId}:compaction:${randomUUID()}`;
|
|
4055
|
+
deps.events.append(sessionId, turnId, {
|
|
4056
|
+
kind: "compaction_start",
|
|
4057
|
+
data: {
|
|
4058
|
+
schemaVersion: 1,
|
|
4059
|
+
compactionId,
|
|
4060
|
+
reason: "manual",
|
|
4061
|
+
status: "running",
|
|
4062
|
+
willRetry: false,
|
|
4063
|
+
},
|
|
4064
|
+
});
|
|
2846
4065
|
try {
|
|
2847
4066
|
const snapshot = await deps.runtime.compact(sessionId, customInstructions);
|
|
2848
|
-
const event = deps.events.append(sessionId,
|
|
4067
|
+
const event = deps.events.append(sessionId, turnId, {
|
|
4068
|
+
kind: "compaction_end",
|
|
4069
|
+
data: {
|
|
4070
|
+
schemaVersion: 1,
|
|
4071
|
+
compactionId,
|
|
4072
|
+
reason: "manual",
|
|
4073
|
+
status: "completed",
|
|
4074
|
+
summary: snapshot.summary,
|
|
4075
|
+
...(snapshot.firstKeptEntryId
|
|
4076
|
+
? { firstKeptEntryId: snapshot.firstKeptEntryId }
|
|
4077
|
+
: {}),
|
|
4078
|
+
...(snapshot.tokensBefore === undefined
|
|
4079
|
+
? {}
|
|
4080
|
+
: { tokensBefore: snapshot.tokensBefore }),
|
|
4081
|
+
...(snapshot.estimatedTokensAfter === undefined
|
|
4082
|
+
? {}
|
|
4083
|
+
: { estimatedTokensAfter: snapshot.estimatedTokensAfter }),
|
|
4084
|
+
willRetry: false,
|
|
4085
|
+
},
|
|
4086
|
+
});
|
|
2849
4087
|
sendJson(res, 200, { ok: true, snapshot, eventId: event.eventId });
|
|
2850
4088
|
}
|
|
2851
4089
|
catch (error) {
|
|
2852
4090
|
const classified = classifyChatCompactionFailure(error);
|
|
4091
|
+
const aborted = error instanceof Error &&
|
|
4092
|
+
(error.name === "AbortError" || /cancel(?:led|ed)|aborted/i.test(error.message));
|
|
4093
|
+
deps.events.append(sessionId, turnId, {
|
|
4094
|
+
kind: "compaction_end",
|
|
4095
|
+
data: {
|
|
4096
|
+
schemaVersion: 1,
|
|
4097
|
+
compactionId,
|
|
4098
|
+
reason: "manual",
|
|
4099
|
+
status: aborted ? "aborted" : "failed",
|
|
4100
|
+
willRetry: false,
|
|
4101
|
+
...(aborted ? {} : { errorMessage: classified.message }),
|
|
4102
|
+
},
|
|
4103
|
+
});
|
|
2853
4104
|
sendJson(res, classified.status, {
|
|
2854
4105
|
ok: false,
|
|
2855
4106
|
error: { code: classified.code, message: classified.message },
|
|
@@ -2878,8 +4129,10 @@ export async function handleChatMessages(res, deps, sessionId, url) {
|
|
|
2878
4129
|
/**
|
|
2879
4130
|
* Dispatch a chat HTTP request. Returns true if handled.
|
|
2880
4131
|
* Mounted under /api/operator/v1/chat/*.
|
|
4132
|
+
* workspaceScope (AC-R7-002): the explicit owning workspaceId for session
|
|
4133
|
+
* create, forwarded to handleCreateChatSession → store.create.
|
|
2881
4134
|
*/
|
|
2882
|
-
export async function handleChatRequest(req, res, deps, pathname) {
|
|
4135
|
+
export async function handleChatRequest(req, res, deps, pathname, workspaceScope) {
|
|
2883
4136
|
if (!deps)
|
|
2884
4137
|
return false;
|
|
2885
4138
|
if (!pathname.startsWith("/api/operator/v1/chat/") &&
|
|
@@ -2933,6 +4186,17 @@ export async function handleChatRequest(req, res, deps, pathname) {
|
|
|
2933
4186
|
await handleChatCapabilities(req, res, deps);
|
|
2934
4187
|
return true;
|
|
2935
4188
|
}
|
|
4189
|
+
const htmlPreviewRoute = matchRepoHtmlPreviewRoute(pathname);
|
|
4190
|
+
if (method === "GET" && htmlPreviewRoute) {
|
|
4191
|
+
if (!htmlPreviewRoute.rawPath)
|
|
4192
|
+
sendJson(res, 400, {
|
|
4193
|
+
ok: false,
|
|
4194
|
+
error: { code: "INVALID_PATH", message: "path is required" },
|
|
4195
|
+
});
|
|
4196
|
+
else
|
|
4197
|
+
await handleRepoHtmlPreview(res, deps, htmlPreviewRoute.rawPath);
|
|
4198
|
+
return true;
|
|
4199
|
+
}
|
|
2936
4200
|
if (method === "GET" && pathname === "/api/operator/v1/chat/repo/tree") {
|
|
2937
4201
|
await handleRepoBrowser(res, deps, "tree", url.searchParams.get("path") ?? "");
|
|
2938
4202
|
return true;
|
|
@@ -2957,6 +4221,16 @@ export async function handleChatRequest(req, res, deps, pathname) {
|
|
|
2957
4221
|
await handleStartInterview(req, res, deps, decodeURIComponent(interviewStart[1]));
|
|
2958
4222
|
return true;
|
|
2959
4223
|
}
|
|
4224
|
+
const userQuestionAnswer = pathname.match(/^\/api\/operator\/v1\/chat\/sessions\/([^/]+)\/questions\/([^/]+)\/answer$/);
|
|
4225
|
+
if (method === "POST" && userQuestionAnswer) {
|
|
4226
|
+
await handleAnswerUserQuestion(req, res, deps, decodeURIComponent(userQuestionAnswer[1]), decodeURIComponent(userQuestionAnswer[2]));
|
|
4227
|
+
return true;
|
|
4228
|
+
}
|
|
4229
|
+
const userQuestionCancel = pathname.match(/^\/api\/operator\/v1\/chat\/sessions\/([^/]+)\/questions\/([^/]+)\/cancel$/);
|
|
4230
|
+
if (method === "POST" && userQuestionCancel) {
|
|
4231
|
+
await handleCancelUserQuestion(req, res, deps, decodeURIComponent(userQuestionCancel[1]), decodeURIComponent(userQuestionCancel[2]));
|
|
4232
|
+
return true;
|
|
4233
|
+
}
|
|
2960
4234
|
const interviewAnswer = pathname.match(/^\/api\/operator\/v1\/chat\/sessions\/([^/]+)\/interviews\/([^/]+)\/answers$/);
|
|
2961
4235
|
if (method === "POST" && interviewAnswer) {
|
|
2962
4236
|
await handleAnswerInterview(req, res, deps, decodeURIComponent(interviewAnswer[1]), decodeURIComponent(interviewAnswer[2]));
|
|
@@ -2992,6 +4266,11 @@ export async function handleChatRequest(req, res, deps, pathname) {
|
|
|
2992
4266
|
await handleSkillAutoInvocation(req, res, deps, decodeURIComponent(skillAutoInvocation[1]), decodeURIComponent(skillAutoInvocation[2]));
|
|
2993
4267
|
return true;
|
|
2994
4268
|
}
|
|
4269
|
+
const sddBingo = pathname.match(/^\/api\/operator\/v1\/chat\/sessions\/([^/]+)\/sdd-bingo$/);
|
|
4270
|
+
if (method === "POST" && sddBingo) {
|
|
4271
|
+
await handleSddBingo(req, res, deps, decodeURIComponent(sddBingo[1]));
|
|
4272
|
+
return true;
|
|
4273
|
+
}
|
|
2995
4274
|
const m4Route = pathname.match(/^\/api\/operator\/v1\/chat\/sessions\/([^/]+)\/(draft|files|runtime-context|runtime-snapshot|models|model|reload|commands)$/);
|
|
2996
4275
|
if (m4Route) {
|
|
2997
4276
|
const id = decodeURIComponent(m4Route[1]);
|
|
@@ -3054,6 +4333,26 @@ export async function handleChatRequest(req, res, deps, pathname) {
|
|
|
3054
4333
|
await handleCreateChatTurn(req, res, deps, decodeURIComponent(sessionTurn[1]));
|
|
3055
4334
|
return true;
|
|
3056
4335
|
}
|
|
4336
|
+
const sessionGoal = pathname.match(/^\/api\/operator\/v1\/chat\/sessions\/([^/]+)\/goal$/);
|
|
4337
|
+
if (sessionGoal &&
|
|
4338
|
+
(method === "GET" || method === "POST" || method === "PATCH" || method === "DELETE")) {
|
|
4339
|
+
await handleChatGoal(req, res, deps, decodeURIComponent(sessionGoal[1]));
|
|
4340
|
+
return true;
|
|
4341
|
+
}
|
|
4342
|
+
const deferredTurn = pathname.match(/^\/api\/operator\/v1\/chat\/sessions\/([^/]+)\/deferred-turn$/);
|
|
4343
|
+
if (method === "PUT" && deferredTurn) {
|
|
4344
|
+
await handlePutDeferredTurn(req, res, deps, decodeURIComponent(deferredTurn[1]));
|
|
4345
|
+
return true;
|
|
4346
|
+
}
|
|
4347
|
+
if (method === "DELETE" && deferredTurn) {
|
|
4348
|
+
await handleDeleteDeferredTurn(req, res, deps, decodeURIComponent(deferredTurn[1]));
|
|
4349
|
+
return true;
|
|
4350
|
+
}
|
|
4351
|
+
const deferredTurnSteer = pathname.match(/^\/api\/operator\/v1\/chat\/sessions\/([^/]+)\/deferred-turn\/([^/]+)\/steer$/);
|
|
4352
|
+
if (method === "POST" && deferredTurnSteer) {
|
|
4353
|
+
await handleSteerDeferredTurn(req, res, deps, decodeURIComponent(deferredTurnSteer[1]), decodeURIComponent(deferredTurnSteer[2]));
|
|
4354
|
+
return true;
|
|
4355
|
+
}
|
|
3057
4356
|
const sessionTurnAbort = pathname.match(/^\/api\/operator\/v1\/chat\/sessions\/([^/]+)\/turns\/([^/]+)\/abort$/);
|
|
3058
4357
|
if (method === "POST" && sessionTurnAbort) {
|
|
3059
4358
|
await handleAbortChatTurn(req, res, deps, decodeURIComponent(sessionTurnAbort[1]), decodeURIComponent(sessionTurnAbort[2]));
|
|
@@ -3069,6 +4368,13 @@ export async function handleChatRequest(req, res, deps, pathname) {
|
|
|
3069
4368
|
await handleLinkWorkspaceOperation(req, res, deps, decodeURIComponent(operationLink[1]));
|
|
3070
4369
|
return true;
|
|
3071
4370
|
}
|
|
4371
|
+
const operationLinkItem = pathname.match(/^\/api\/operator\/v1\/chat\/sessions\/([^/]+)\/operation-links\/([^/]+)$/);
|
|
4372
|
+
if (method === "DELETE" && operationLinkItem) {
|
|
4373
|
+
// AC-R7-001: Details rail DAG remove — real DELETE of the workspace
|
|
4374
|
+
// operation-link association (idempotent).
|
|
4375
|
+
await handleUnlinkWorkspaceOperation(req, res, deps, decodeURIComponent(operationLinkItem[1]), decodeURIComponent(operationLinkItem[2]));
|
|
4376
|
+
return true;
|
|
4377
|
+
}
|
|
3072
4378
|
const sessionCompact = pathname.match(/^\/api\/operator\/v1\/chat\/sessions\/([^/]+)\/compact$/);
|
|
3073
4379
|
if (method === "POST" && sessionCompact) {
|
|
3074
4380
|
await handleChatCompact(req, res, deps, decodeURIComponent(sessionCompact[1]));
|
|
@@ -3116,7 +4422,7 @@ export async function handleChatRequest(req, res, deps, pathname) {
|
|
|
3116
4422
|
}
|
|
3117
4423
|
}
|
|
3118
4424
|
if (method === "POST" && pathname === "/api/operator/v1/chat/sessions") {
|
|
3119
|
-
await handleCreateChatSession(req, res, deps);
|
|
4425
|
+
await handleCreateChatSession(req, res, deps, workspaceScope);
|
|
3120
4426
|
return true;
|
|
3121
4427
|
}
|
|
3122
4428
|
if (isMutationMethod(method)) {
|