@tea-agent/loop-agent 0.1.0-fe-test.5 → 0.1.0-fe-test.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +1 -1
- package/CHANGELOG.md +441 -2525
- package/README.md +19 -12
- package/dist/adapters/loop-agent.js +34 -0
- package/dist/application/dag/args.js +8 -0
- package/dist/application/dag/run-dag.js +5 -0
- package/dist/application/evaluation/budget.js +40 -1
- package/dist/application/evaluation/corpus-hash.js +10 -15
- package/dist/application/evaluation/corpus.js +2 -1
- package/dist/application/evaluation/frontend-browser-acceptance.js +77 -0
- package/dist/application/evaluation/frontend-corpus-browser-acceptance.js +175 -0
- package/dist/application/evaluation/frontend-gateway-evidence.js +226 -0
- package/dist/application/evaluation/frontend-pair-registration.js +143 -0
- package/dist/application/evaluation/frontend-paired-summary.js +150 -0
- package/dist/application/evaluation/frontend-run-observation.js +144 -0
- package/dist/application/evaluation/frontend-shared-evidence.js +105 -0
- package/dist/application/evaluation/types.js +45 -12
- package/dist/application/task-lifecycle/advance.js +64 -15
- package/dist/application/task-lifecycle/observe.js +69 -30
- package/dist/application/task-lifecycle/plan-transitions.js +5 -4
- package/dist/build-stamp.json +3 -3
- package/dist/cli/command-definitions.js +18 -5
- package/dist/cli/program.js +8 -5
- package/dist/cli/update/init-surface-notifier.js +2 -0
- package/dist/cli/update/policy.js +2 -0
- package/dist/commands/client-recovery.js +20 -55
- package/dist/commands/cursor-prompt.js +2 -0
- package/dist/commands/dag-approve.js +2 -0
- package/dist/commands/dag-final-verification.js +2 -0
- package/dist/commands/dag-init-hybrid.js +2 -0
- package/dist/commands/dag-reconcile-tasks.js +2 -0
- package/dist/commands/dag-reject.js +2 -0
- package/dist/commands/dag-report.js +2 -0
- package/dist/commands/dag-rerun.js +2 -0
- package/dist/commands/dag-resume.js +2 -0
- package/dist/commands/dag-workflow-compile.js +2 -0
- package/dist/commands/dag-workflow-plan.js +2 -0
- package/dist/commands/dag-workflow-validate.js +2 -0
- package/dist/commands/delegate.js +2 -0
- package/dist/commands/examples.js +2 -0
- package/dist/commands/import-prd.js +2 -0
- package/dist/commands/init-legacy-audit.js +330 -0
- package/dist/commands/init-model-catalog.js +2 -0
- package/dist/commands/init-upgrade.js +644 -104
- package/dist/commands/init.js +700 -338
- package/dist/commands/instructions.js +2 -0
- package/dist/commands/knowledge.js +2 -0
- package/dist/commands/loop-benchmark.js +2 -0
- package/dist/commands/operator-guide.js +99 -0
- package/dist/commands/operator.js +16 -3
- package/dist/commands/pi-prompt.js +2 -0
- package/dist/commands/pi-reuse-benchmark.js +2 -0
- package/dist/commands/promote-run.js +2 -0
- package/dist/commands/stats.js +1 -1
- package/dist/commands/study-init.js +2 -0
- package/dist/commands/task-advance.js +32 -0
- package/dist/commands/task-source-prepare.js +18 -2
- package/dist/commands/worktree-create.js +2 -0
- package/dist/commands/worktree-remove.js +2 -0
- package/dist/executors/dag-pi/guards.js +4 -0
- package/dist/executors/dag-pi/model-config.js +30 -0
- package/dist/executors/dag-pi/plan/fact-adoption.js +55 -0
- package/dist/executors/dag-pi/plan/facts.js +180 -0
- package/dist/executors/dag-pi/plan/finalize-tools.js +259 -0
- package/dist/executors/dag-pi/plan/ledger-contract.js +55 -0
- package/dist/executors/dag-pi/plan/record-tools.js +861 -0
- package/dist/executors/dag-pi/plan/schema.js +129 -0
- package/dist/executors/dag-pi/plan/tool-helpers.js +16 -0
- package/dist/executors/dag-pi/sessions/index.js +6 -0
- package/dist/executors/dag-pi/sessions/plan-batches.js +280 -0
- package/dist/executors/dag-pi/sessions/plan-prompts.js +367 -0
- package/dist/executors/dag-pi/sessions/scout-parallel.js +197 -0
- package/dist/executors/dag-pi/sessions/segmented-plan.js +1184 -0
- package/dist/executors/dag-pi/sessions/writer-evidence.js +60 -0
- package/dist/executors/dag-pi/tools/contract-tools.js +515 -0
- package/dist/executors/dag-pi/tools/design-terminal-tools.js +159 -0
- package/dist/executors/dag-pi/tools/plan-decision-tools.js +529 -0
- package/dist/executors/dag-pi/tools/review-terminal-tools.js +159 -0
- package/dist/executors/dag-pi/tools/scout-evidence-tools.js +270 -0
- package/dist/executors/dag-pi-executor.js +1516 -3181
- package/dist/executors/pi-executor.js +112 -4
- package/dist/executors/pi-sdk-executor.js +258 -44
- package/dist/executors/pi-writer-tool-policy.js +60 -4
- package/dist/executors/playwright-cli-launcher.js +31 -45
- package/dist/executors/shell-executor.js +313 -48
- package/dist/executors/shell-presets.js +1 -1
- package/dist/executors/shell-verification.js +3 -0
- package/dist/executors/shell-write-guard.js +77 -102
- package/dist/governance/exec-plans.js +16 -4
- package/dist/governance/harness.js +2 -7
- package/dist/governance/manifest-types.js +28 -9
- package/dist/governance/project-capability-scanner.js +263 -0
- package/dist/governance/project-config.js +96 -0
- package/dist/governance/resource-catalog.js +151 -0
- package/dist/infrastructure/console/app-data.js +12 -2
- package/dist/infrastructure/console/operation-store.js +48 -14
- package/dist/infrastructure/evaluation/corpus-store.js +37 -12
- package/dist/shared/artifacts-core.js +2 -0
- package/dist/shared/backend-dogfood-preflight.js +47 -0
- package/dist/shared/dag-failure-category.js +9 -0
- package/dist/shared/file-identity.js +23 -0
- package/dist/shared/frontend-execution-policy.js +23 -0
- package/dist/shared/git-progress.js +2 -0
- package/dist/shared/git-workspace-status.js +482 -0
- package/dist/shared/one-shot-prompt-args.js +2 -0
- package/dist/shared/operator/capabilities.js +185 -0
- package/dist/shared/package-metadata.js +29 -11
- package/dist/shared/path-safety.js +2 -2
- package/dist/shared/pi-context-pressure/extension.js +49 -16
- package/dist/shared/pi-context-pressure/index.js +1 -0
- package/dist/shared/pi-context-pressure/sift-bridge.js +1 -1
- package/dist/shared/pi-context-pressure/telemetry.js +4 -0
- package/dist/shared/pi-context-pressure/tool-result-pruner.js +98 -0
- package/dist/shared/pi-provider-recovery.js +182 -0
- package/dist/shared/pi-retry-settings.js +40 -0
- package/dist/shared/reference-context.js +2 -0
- package/dist/shared/update/npm-client.js +49 -1
- package/dist/shared/wizard-local-telemetry.js +51 -0
- package/dist/task/config-types.js +51 -2
- package/dist/task/contract/apply.js +36 -2
- package/dist/task/contract/project.js +22 -0
- package/dist/task/contract/recover.js +6 -0
- package/dist/task/contract/schema.js +12 -0
- package/dist/task/frontend-preflight.js +1 -1
- package/dist/task/source-prepare/artifact-meta.js +9 -2
- package/dist/task/source-prepare/build-draft.js +61 -0
- package/dist/task/source-prepare/fragment-inventory.js +4 -1
- package/dist/task/source-prepare/ledger-reconciliation.js +2 -2
- package/dist/task/source-prepare/ledger-review.js +6 -9
- package/dist/task/source-prepare/parse-intent.js +165 -14
- package/dist/task/source-prepare/path-policy.js +17 -7
- package/dist/task/source-prepare/prepare.js +6 -1
- package/dist/task/source-prepare/semantic-intake.js +33 -28
- package/dist/task/source-prepare/source-execution.js +65 -0
- package/dist/task/source-prepare/source-fidelity-pi.js +49 -17
- package/dist/task/source-prepare/source-provider-budget.js +290 -0
- package/dist/task/source-references.js +48 -23
- package/dist/task/task-demand-routing.js +5 -2
- package/dist/worker/cli.js +3 -5
- package/dist/worker/console/chat/assistant-content.js +5 -13
- package/dist/worker/console/chat/browser-automation.js +937 -0
- package/dist/worker/console/chat/browser-content.js +74 -0
- package/dist/worker/console/chat/browser-diagnostics.js +250 -0
- package/dist/worker/console/chat/browser-evaluation.js +58 -0
- package/dist/worker/console/chat/browser-operation-queue.js +19 -0
- package/dist/worker/console/chat/browser-pick.js +113 -0
- package/dist/worker/console/chat/browser-policy.js +113 -0
- package/dist/worker/console/chat/browser-routes.js +329 -0
- package/dist/worker/console/chat/browser-screenshot-result.js +47 -0
- package/dist/worker/console/chat/browser-storage.js +89 -0
- package/dist/worker/console/chat/chat-event-store.js +73 -18
- package/dist/worker/console/chat/context-insights.js +788 -0
- package/dist/worker/console/chat/conversation-nodes.js +383 -0
- package/dist/worker/console/chat/db-connections.js +854 -0
- package/dist/worker/console/chat/explore-tools.js +18 -2
- package/dist/worker/console/chat/pet/pet-affinity.js +169 -0
- package/dist/worker/console/chat/pet/pet-persist.js +109 -0
- package/dist/worker/console/chat/pet/pet-registry.js +142 -0
- package/dist/worker/console/chat/pet/pet-remarks.js +48 -0
- package/dist/worker/console/chat/pet/pet-routes.js +125 -0
- package/dist/worker/console/chat/pet/pet-service.js +262 -0
- package/dist/worker/console/chat/pet/pet-state.js +99 -0
- package/dist/worker/console/chat/pi-mode-loop-isolation.js +170 -0
- package/dist/worker/console/chat/pi-runtime/custom-tools/ask-user-question.js +44 -0
- package/dist/worker/console/chat/pi-runtime/custom-tools/browser-tools.js +135 -0
- package/dist/worker/console/chat/pi-runtime/custom-tools/explore-tools.js +202 -0
- package/dist/worker/console/chat/pi-runtime/custom-tools/goal-tools.js +79 -0
- package/dist/worker/console/chat/pi-runtime/custom-tools/operator-tools.js +94 -0
- package/dist/worker/console/chat/pi-runtime/custom-tools/scheduled-goal-tools.js +22 -0
- package/dist/worker/console/chat/pi-runtime/custom-tools/sql-tools.js +670 -0
- package/dist/worker/console/chat/pi-runtime/custom-tools/todo-write.js +38 -0
- package/dist/worker/console/chat/pi-runtime/inspection-types.js +28 -0
- package/dist/worker/console/chat/pi-runtime/inspection.js +439 -0
- package/dist/worker/console/chat/pi-runtime/progressive-tools.js +195 -0
- package/dist/worker/console/chat/pi-runtime/sdk-bindings.js +153 -0
- package/dist/worker/console/chat/pi-runtime/sdk-session.js +5 -0
- package/dist/worker/console/chat/pi-runtime.js +793 -1230
- package/dist/worker/console/chat/provider-error.js +0 -12
- package/dist/worker/console/chat/repo-browser.js +132 -6
- package/dist/worker/console/chat/repo-preview-kind.js +155 -0
- package/dist/worker/console/chat/resource-loader.js +4 -1
- package/dist/worker/console/chat/routes.js +861 -148
- package/dist/worker/console/chat/scheduled-goal-booking.js +59 -0
- package/dist/worker/console/chat/scheduled-goal-delivery.js +27 -0
- package/dist/worker/console/chat/scheduled-goal-request.js +198 -0
- package/dist/worker/console/chat/scm-routes.js +217 -0
- package/dist/worker/console/chat/scm-service.js +283 -0
- package/dist/worker/console/chat/scm-tools.js +111 -0
- package/dist/worker/console/chat/sdd-data-alignment.js +85 -41
- package/dist/worker/console/chat/session-catalog.js +32 -0
- package/dist/worker/console/chat/session-mode-view.js +49 -0
- package/dist/worker/console/chat/session-mode.js +224 -0
- package/dist/worker/console/chat/session-store.js +232 -32
- package/dist/worker/console/chat/shortcuts.js +13 -0
- package/dist/worker/console/chat/subagents/agent-tool.js +62 -0
- package/dist/worker/console/chat/subagents/explore-agent.js +169 -0
- package/dist/worker/console/chat/subagents/index.js +5 -0
- package/dist/worker/console/chat/subagents/orchestrator.js +273 -0
- package/dist/worker/console/chat/subagents/tool-policy.js +53 -0
- package/dist/worker/console/chat/subagents/types.js +13 -0
- package/dist/worker/console/chat/terminal-routes.js +216 -0
- package/dist/worker/console/chat/terminal-sessions.js +348 -0
- package/dist/worker/console/chat/terminal-tools.js +211 -0
- package/dist/worker/console/chat/timeline-message-order.js +22 -0
- package/dist/worker/console/chat/tool-preview.js +136 -0
- package/dist/worker/console/chat/tools.js +69 -1
- package/dist/worker/console/chat/turn-order.js +13 -0
- package/dist/worker/console/chat/turn-process.js +210 -36
- package/dist/worker/console/chat/user-turn-outline.js +19 -0
- package/dist/worker/console/console-shutdown.js +34 -0
- package/dist/worker/console/console-update-and-init.js +1 -19
- package/dist/worker/console/console-update-runtime.js +7 -22
- package/dist/worker/console/dag-confirmation.js +3 -0
- package/dist/worker/console/dag-execution-receipt.js +3 -0
- package/dist/worker/console/interview/tools.js +1 -0
- package/dist/worker/console/operator-actions.js +95 -4
- package/dist/worker/console/operator-user-error.js +28 -1
- package/dist/worker/console/pi-readiness.js +4 -4
- package/dist/worker/console/prd-intake-bridge.js +47 -1
- package/dist/worker/console/recovery-cta.js +14 -14
- package/dist/worker/console/routes.js +13 -0
- package/dist/worker/console/scheduled-goal-host.js +98 -0
- package/dist/worker/console/scheduled-goal-operation-adapter.js +127 -0
- package/dist/worker/console/server.js +33 -31
- package/dist/worker/console/static/app-icon.svg +39 -0
- package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-BZogYNl1.js → abnfDiagram-N423BO3Z-DASc69AM.js} +1 -1
- package/dist/worker/console/static/assets/{arc-DcJTLe2v.js → arc-h09p-LAc.js} +1 -1
- package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-B39EQQ9n.js → architectureDiagram-T3A2C74G-CZ3dtLkh.js} +1 -1
- package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-CitCGV56.js → blockDiagram-VBNYF7ZC-DMrRhMXG.js} +1 -1
- package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-rvWuOHLG.js → c4Diagram-5PPSVZJV-DQxisHV6.js} +1 -1
- package/dist/worker/console/static/assets/channel-D1zgKZfg.js +1 -0
- package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-DGXplIJs.js → chunk-2GRJ4B5K-CefVN9zh.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-ur9OqjPn.js → chunk-2Q5K7J3B-DmR1Koq2.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-5RXB4S5H-D1KqU_Vi.js → chunk-5RXB4S5H-NlzrSW7L.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-5VM5RSS4-BlVZrbtM.js → chunk-5VM5RSS4-DfelJv-0.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-BAzz3nQy.js → chunk-6Q2QTUOP-BK6RFy58.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-GF5L2VYU-CP_nYuCV.js → chunk-GF5L2VYU-BAeh9lz4.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-JWPE2WC7-CWvKQ80X.js → chunk-JWPE2WC7-ChPS5WzG.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-KBJHAD2P-CyUki8wp.js → chunk-KBJHAD2P-BoVe5IM6.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-RYQCIY6F-5NYzNKfY.js → chunk-RYQCIY6F-C4q_0Lw9.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-XXDRQBXY-DHdUgjS-.js → chunk-XXDRQBXY-Bb9TvjeY.js} +1 -1
- package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-CXNNsY2M.js +1 -0
- package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-CXNNsY2M.js +1 -0
- package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-ANQ5g_t6.js → cose-bilkent-JH36ORCC-DmNnL8Ff.js} +1 -1
- package/dist/worker/console/static/assets/{cynefin-VYW2F7L2-CruT_4-0.js → cynefin-VYW2F7L2-Contvx58.js} +1 -1
- package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-rbFo77ID.js → cynefinDiagram-MW4NZA55-Cigq7cjk.js} +1 -1
- package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-asstxBQs.js → dagre-VZM6K2ZE-dEbC0nxb.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-7IWD3JNH-DzTyBZwI.js → diagram-7IWD3JNH-CzIztESV.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-gw8ccH3B.js → diagram-B4RE2ZJO-Bo14zbaY.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-LBJQPF4R-B8RpZzOf.js → diagram-LBJQPF4R-C4xUyil6.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-Q27KOJAE-B1zJkCS9.js → diagram-Q27KOJAE-CaBY_uYa.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-UB23O5K3-B6JLWZmO.js → diagram-UB23O5K3-ClUXUeiu.js} +1 -1
- package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-q2iZP-Ps.js → ebnfDiagram-BXEA7PRR-BbGCgjC6.js} +1 -1
- package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-B3dbbktQ.js → erDiagram-JOGREHBK-Dr-AcwSl.js} +1 -1
- package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-C-zc6-kB.js → flowDiagram-UKHOOZJN-BG8Gcfyc.js} +1 -1
- package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-BSolnot9.js → ganttDiagram-PKOTCBZU-CFVaPs5r.js} +1 -1
- package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-Bo8jGxTk.js → gitGraphDiagram-DS77QQ5N-ChJ8pm-O.js} +1 -1
- package/dist/worker/console/static/assets/index-B_5GhVIO.js +488 -0
- package/dist/worker/console/static/assets/index-C7YMBluX.css +1 -0
- package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-DQaZqJOH.js → infoDiagram-6WML65LV-C5J9-uCZ.js} +1 -1
- package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-DsdX1WnE.js → ishikawaDiagram-WSZJBQD7-BcfjqzDv.js} +1 -1
- package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-CP5EYDZL.js → journeyDiagram-NVQOT4AX-BzzCO-rD.js} +1 -1
- package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-DAm14Dr8.js → kanban-definition-27J2QSJJ-NCHUZ46h.js} +1 -1
- package/dist/worker/console/static/assets/{linear-gZECoLc5.js → linear-BKZlWCUU.js} +1 -1
- package/dist/worker/console/static/assets/{mermaid.core-BRJNIM6p.js → mermaid.core-DbTaQjFE.js} +5 -5
- package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-Cja3kLkR.js → mindmap-definition-FAOFIHXS-CroYl5xQ.js} +1 -1
- package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-22ZGFisL.js → pegDiagram-VL7TDLO6-DgMBx-9k.js} +1 -1
- package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BXin0Y1o.js → pieDiagram-7S7Q4E2Y-CyWDmbq1.js} +1 -1
- package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-Cw6T69Yt.js → quadrantDiagram-CIZ2JOQS-BgGEOqSP.js} +1 -1
- package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-C1-gTieN.js → railroadDiagram-AXF67PYL-BMZ7oeeV.js} +1 -1
- package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP--H5N2iI1.js → requirementDiagram-LRYGKXZP-DxqyGhcc.js} +1 -1
- package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-CgWAPeRz.js → sankeyDiagram-W5VNT64P-DnSvNCG8.js} +1 -1
- package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-CrKqzGvt.js → sequenceDiagram-SI44F4Z6-BiZh6f-R.js} +1 -1
- package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-BB3wG06K.js → sizeCapture-X5ZJPWSS-BKXSI8WB.js} +1 -1
- package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-DjsGgdgY.js → stateDiagram-OKZ733FA-CfSgoYFm.js} +1 -1
- package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-DgHi3vjb.js +1 -0
- package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-DYKEbvAR.js → swimlanes-SLNWSIFB-CyGADcHe.js} +2 -2
- package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-Bgvdt1Y0.js +8 -0
- package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-eQOb5k9Y.js → timeline-definition-Z64GVDOM-HmPaSPOK.js} +1 -1
- package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-B2-l9FIu.js → vennDiagram-T6HMQDX7-VA2VBbez.js} +1 -1
- package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-BX2Cda3l.js → wardleyDiagram-T6FBY63Y-BxjiBPZa.js} +1 -1
- package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-D9S892ph.js → xychartDiagram-ELKLHX3M--hUY-qFj.js} +1 -1
- package/dist/worker/console/static/index.html +5 -2
- package/dist/worker/console/static/manifest.webmanifest +19 -0
- package/dist/worker/console/static/pets/ember/pet.json +167 -0
- package/dist/worker/console/static/pets/ember/spritesheet.png +0 -0
- package/dist/worker/console/static-src/app/console-types.js +9 -1
- package/dist/worker/console/static-src/chat-view-types.js +1 -1
- package/dist/worker/console/static-src/operator-chat/active-turn-tail.js +10 -0
- package/dist/worker/console/static-src/operator-chat/animation-frame-batcher.js +38 -0
- package/dist/worker/console/static-src/operator-chat/chat-link.js +114 -0
- package/dist/worker/console/static-src/operator-chat/chat-scroll-position.js +24 -0
- package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +360 -14
- package/dist/worker/console/static-src/operator-chat/chat-stream-continuity.js +101 -0
- package/dist/worker/console/static-src/operator-chat/compaction-message.js +10 -2
- package/dist/worker/console/static-src/operator-chat/composer-session-ledger.js +192 -0
- package/dist/worker/console/static-src/operator-chat/context-insights-store.js +64 -0
- package/dist/worker/console/static-src/operator-chat/details-rail-surfaces.js +99 -0
- package/dist/worker/console/static-src/operator-chat/file-palette-nav.js +81 -0
- package/dist/worker/console/static-src/operator-chat/open-preview-in-browser.js +57 -9
- package/dist/worker/console/static-src/operator-chat/pending-user-message.js +66 -0
- package/dist/worker/console/static-src/operator-chat/process-label.js +63 -0
- package/dist/worker/console/static-src/operator-chat/slash-palette-nav.js +15 -5
- package/dist/worker/console/static-src/operator-chat/timeline-merge.js +29 -0
- package/dist/worker/console/static-src/operator-chat/tools-catalog.js +36 -8
- package/dist/worker/console/static-src/operator-chat/transcript-mode.js +21 -0
- package/dist/worker/console/static-src/operator-chat/turn-group-equality.js +16 -0
- package/dist/worker/console/static-src/operator-chat/turn-process-disclosure.js +18 -0
- package/dist/worker/console/static-src/operator-chat/turn-state-projection.js +166 -0
- package/dist/worker/console/static-src/operator-chat/turn-stream-controller.js +58 -2
- package/dist/worker/console/static-src/operator-chat/use-searchable-hidden.js +51 -0
- package/dist/worker/console/static-src/operator-chat/use-stat-dialog.js +95 -0
- package/dist/worker/console/static-src/operator-chat/useChatSessions.js +338 -93
- package/dist/worker/console/static-src/operator-chat/useChatStream.js +310 -106
- package/dist/worker/console/static-src/operator-chat/useChatThread.js +179 -75
- package/dist/worker/console/static-src/operator-chat/useComposer.js +281 -79
- package/dist/worker/console/static-src/operator-chat/useRepoBrowser.js +21 -3
- package/dist/worker/console/static-src/operator-chat/useRuntimeControls.js +36 -17
- package/dist/worker/console/static-src/operator-chat/useRuntimeSnapshot.js +18 -0
- package/dist/worker/console/static-src/operator-chat/useWorkspaceBrowserGate.js +4 -0
- package/dist/worker/console/static-src/operator-chat/user-turn-anchor-equality.js +21 -0
- package/dist/worker/console/static-src/prd-file-import.js +3 -1
- package/dist/worker/console/static-src/shell/console-update-reload.js +1 -1
- package/dist/worker/console/workspace-context.js +54 -1
- package/dist/worker/console/workspace-initialization.js +218 -0
- package/dist/worker/delivery/git-transaction.js +2 -0
- package/dist/worker/delivery/package.js +4 -1
- package/dist/worker/feature/fullstack-validate.js +2 -0
- package/dist/worker/loop-agent/loop-agent-client.js +8 -2
- package/dist/worker/materialize/harness-task-lineage.js +4 -2
- package/dist/worker/materialize/harness-task-materializer.js +4 -1
- package/dist/worker/metrics/projector.js +1 -1
- package/dist/worker/observability/event-store.js +4 -1
- package/dist/worker/observability/read-model.js +27 -3
- package/dist/worker/observe/node-context-insights.js +479 -0
- package/dist/worker/observe/node-transparency.js +103 -72
- package/dist/worker/observe/routes.js +24 -1
- package/dist/worker/observe/static/console-theme.css +178 -0
- package/dist/worker/observe/static/console-theme.js +74 -0
- package/dist/worker/observe/static/dag-inspector-humanize.js +3 -0
- package/dist/worker/observe/static/dom.js +20 -1
- package/dist/worker/observe/static/format-pool.d.ts +2 -0
- package/dist/worker/observe/static/format-pool.js +6 -0
- package/dist/worker/observe/static/format.js +7 -0
- package/dist/worker/observe/static/inspect-workspace.js +34 -7
- package/dist/worker/observe/static/inspector-submission.js +32 -0
- package/dist/worker/observe/static/kpi.js +1 -0
- package/dist/worker/observe/static/operator-chrome.css +85 -0
- package/dist/worker/observe/static/operator-chrome.js +13 -1
- package/dist/worker/observe/static/relations.js +2 -0
- package/dist/worker/observe/static/router.js +13 -0
- package/dist/worker/observe/static/run-processing.js +2 -0
- package/dist/worker/observe/static/shell-chrome.js +36 -3
- package/dist/worker/observe/static/state.js +35 -2
- package/dist/worker/observe/static/styles.css +263 -39
- package/dist/worker/observe/static/task-failure-labels.d.ts +4 -0
- package/dist/worker/observe/static/task-failure-labels.js +67 -0
- package/dist/worker/observe/static/task-history.js +12 -0
- package/dist/worker/observe/static/views/batch.js +6 -13
- package/dist/worker/observe/static/views/dag-graph.js +50 -3
- package/dist/worker/observe/static/views/dag-inspector.js +742 -268
- package/dist/worker/observe/static/views/dag-trajectory.js +3 -0
- package/dist/worker/observe/static/views/dag.d.ts +6 -0
- package/dist/worker/observe/static/views/dag.js +49 -11
- package/dist/worker/observe/static/views/dags.js +2 -0
- package/dist/worker/observe/static/views/dashboard.js +21 -12
- package/dist/worker/observe/static/views/failures.js +21 -11
- package/dist/worker/observe/static/views/feature.js +11 -29
- package/dist/worker/observe/static/views/pool.js +37 -28
- package/dist/worker/observe/static/views/run.js +48 -5
- package/dist/worker/observe/static/views/session-timeline.js +189 -240
- package/dist/worker/observe/static/views/task.js +81 -62
- package/dist/worker/outcomes/declared-artifacts.js +2 -0
- package/dist/worker/preflight.js +3 -0
- package/dist/worker/scheduler/scheduled-goal-dispatch.js +118 -0
- package/dist/worker/scheduler/scheduled-goal-evidence.js +230 -0
- package/dist/worker/scheduler/scheduled-goal-recovery.js +62 -0
- package/dist/worker/scheduler/scheduled-goal-store.js +709 -0
- package/dist/worker/scheduler/scheduled-goal-supervisor.js +132 -0
- package/dist/worker/scheduler/scheduled-goal-time.js +102 -0
- package/dist/worker/scheduler/scheduled-goal-types.js +95 -0
- package/dist/worker/task-spec/validate.js +4 -1
- package/dist/workflows/dag/backend-test-case-coverage-analysis.js +3 -1
- package/dist/workflows/dag/backend-test-layout.js +27 -7
- package/dist/workflows/dag/backend-test-markdown-workflow.js +9 -25
- package/dist/workflows/dag/backend-test-plan-protocol.js +82 -5
- package/dist/workflows/dag/backend-test-pytest-collection.js +4 -1
- package/dist/workflows/dag/budget-enforcement.js +82 -3
- package/dist/workflows/dag/checkpoint.js +686 -0
- package/dist/workflows/dag/dag-retry-schema.js +14 -0
- package/dist/workflows/dag/decision-envelope.js +2 -0
- package/dist/workflows/dag/dynamic-runtime/shared.js +2 -2
- package/dist/workflows/dag/final-verification.js +45 -10
- package/dist/workflows/dag/frontend-capacity.js +9 -0
- package/dist/workflows/dag/frontend-closeout.js +5 -1
- package/dist/workflows/dag/frontend-committed-facts.js +461 -0
- package/dist/workflows/dag/frontend-contract-facts.js +133 -0
- package/dist/workflows/dag/frontend-design-policy.js +107 -21
- package/dist/workflows/dag/frontend-durable-tools.js +225 -0
- package/dist/workflows/dag/frontend-execution-groups.js +24 -0
- package/dist/workflows/dag/frontend-implementation-contract.js +554 -26
- package/dist/workflows/dag/frontend-input-projection.js +76 -0
- package/dist/workflows/dag/frontend-plan-canary.js +103 -0
- package/dist/workflows/dag/frontend-plan-decision-contract.js +795 -0
- package/dist/workflows/dag/frontend-plan-progress.js +92 -0
- package/dist/workflows/dag/frontend-plan-recovery-policy.js +18 -0
- package/dist/workflows/dag/frontend-plan-render.js +21 -5
- package/dist/workflows/dag/frontend-provider-capability-matrix.js +8 -61
- package/dist/workflows/dag/frontend-recovery-controller.js +7 -7
- package/dist/workflows/dag/frontend-recovery-lineage.js +13 -0
- package/dist/workflows/dag/frontend-recovery-plan.js +10 -5
- package/dist/workflows/dag/frontend-recovery-run.js +148 -47
- package/dist/workflows/dag/frontend-repair-assertions.js +36 -0
- package/dist/workflows/dag/frontend-repair.js +79 -76
- package/dist/workflows/dag/frontend-review-context.js +71 -69
- package/dist/workflows/dag/frontend-review-scopes.js +237 -0
- package/dist/workflows/dag/frontend-risk.js +101 -12
- package/dist/workflows/dag/frontend-root-observation.js +261 -0
- package/dist/workflows/dag/frontend-session-budget.js +376 -0
- package/dist/workflows/dag/frontend-session-context.js +10 -0
- package/dist/workflows/dag/frontend-shape-facts.js +12 -2
- package/dist/workflows/dag/frontend-shape.js +27 -32
- package/dist/workflows/dag/frontend-test-case-checklist.js +12 -3
- package/dist/workflows/dag/frontend-test-case-generation-assessment.js +21 -2
- package/dist/workflows/dag/frontend-test-case-quality.js +3 -3
- package/dist/workflows/dag/frontend-test-environment-probe.js +0 -2
- package/dist/workflows/dag/frontend-test-execution-evidence.js +328 -0
- package/dist/workflows/dag/frontend-test-framework-adapters.js +309 -0
- package/dist/workflows/dag/frontend-test-layout.js +41 -12
- package/dist/workflows/dag/frontend-typed-event-store.js +57 -26
- package/dist/workflows/dag/frontend-verification-trace.js +65 -48
- package/dist/workflows/dag/frontend-writer-admission.js +6 -48
- package/dist/workflows/dag/frontend-writer-status.js +0 -23
- package/dist/workflows/dag/hybrid/sources.js +1831 -0
- package/dist/workflows/dag/hybrid/templates/backend-test.js +1822 -0
- package/dist/workflows/dag/hybrid/templates/frontend-test.js +807 -0
- package/dist/workflows/dag/hybrid/templates/frontend.js +1529 -0
- package/dist/workflows/dag/hybrid/templates/index.js +8 -0
- package/dist/workflows/dag/hybrid/templates/kg-bootstrap.js +449 -0
- package/dist/workflows/dag/hybrid/templates/knowledge-sync.js +495 -0
- package/dist/workflows/dag/hybrid/templates/shared.js +101 -0
- package/dist/workflows/dag/hybrid/templates/standard.js +265 -0
- package/dist/workflows/dag/hybrid/types.js +32 -0
- package/dist/workflows/dag/init-hybrid.js +57 -7167
- package/dist/workflows/dag/interrupt-request.js +2 -0
- package/dist/workflows/dag/lifecycle.js +11 -2
- package/dist/workflows/dag/node-execution.js +257 -247
- package/dist/workflows/dag/output-protocol.js +1 -0
- package/dist/workflows/dag/prompt.js +4 -0
- package/dist/workflows/dag/reconcile-run.js +2 -0
- package/dist/workflows/dag/repair-artifact.js +3 -1
- package/dist/workflows/dag/report.js +2 -0
- package/dist/workflows/dag/rerun-feedback.js +36 -4
- package/dist/workflows/dag/rerun-plan.js +106 -4
- package/dist/workflows/dag/rerun-run.js +7 -0
- package/dist/workflows/dag/rerun-task.js +75 -1
- package/dist/workflows/dag/retry-policy.js +34 -10
- package/dist/workflows/dag/runner-exit-diagnostics.js +125 -0
- package/dist/workflows/dag/runner.js +38 -1074
- package/dist/workflows/dag/scheduler.js +2 -4
- package/dist/workflows/dag/skill-instructions.js +102 -32
- package/dist/workflows/dag/skill-snapshot.js +3 -0
- package/dist/workflows/dag/skills.js +7 -7
- package/dist/workflows/dag/structured-output-repair.js +4 -1
- package/dist/workflows/dag/terminal-status.js +502 -0
- package/dist/workflows/dag/test-artifact-namespace.js +73 -0
- package/dist/workflows/dag/types.js +58 -7
- package/dist/workflows/dag/validate.js +38 -13
- package/dist/workflows/dag/workspace-checkpoint.js +79 -1
- package/dist/workflows/loop/benchmark.js +11 -8
- package/docs/README.md +2 -1
- package/docs/architecture/dag-execution.md +4 -4
- package/docs/architecture/runtime-boundaries.md +29 -23
- package/docs/governance/README.md +1 -0
- package/docs/governance/harness-methodology-verification.md +11 -0
- package/docs/init-surface.manifest.json +44 -295
- package/docs/operations/README.md +4 -0
- package/docs/templates/README.md +5 -5
- package/docs/templates/agent-dag.base.json +9 -9
- package/docs/templates/agent-dag.final-verification.json +6 -6
- package/docs/templates/agent-dag.schema.json +2 -2
- package/docs/templates/agent-dag.supervised-implementation.json +12 -12
- package/docs/templates/backend-test-dag.generate-pytest.prompt.md +3 -3
- package/docs/templates/backend-test-dag.json +708 -703
- package/docs/templates/backend-test-dag.review-cases.prompt.md +3 -3
- package/docs/templates/frontend-design-contract.md +4 -4
- package/docs/templates/frontend-implementation-contract.schema.json +99 -22
- package/docs/templates/frontend-implementation-dag.json +7 -7
- package/docs/templates/frontend-test-case-checklist.md +2 -2
- package/docs/templates/frontend-test-case.example.md +2 -0
- package/docs/templates/frontend-test-dag.generate-cases.prompt.md +1 -1
- package/docs/templates/frontend-test-dag.json +46 -37
- package/docs/templates/frontend-test-dag.retrieve-context.prompt.md +2 -2
- package/docs/templates/frontend-test-dag.retrospect.prompt.md +1 -1
- package/docs/templates/frontend-test-dag.review-cases.prompt.md +1 -1
- package/docs/templates/hybrid-dag.json +9 -9
- package/docs/templates/knowledge-sync-dag.json +8 -8
- package/harness.json +1 -1
- package/package.json +27 -8
- package/resource-catalog.v1.json +1981 -0
- package/resources/agent-bridge/loop-agent/SKILL.md +40 -0
- package/resources/init-history/legacy-surface.v1.json +33 -0
- package/skills/fe-test-ui-scout/SKILL.md +4 -4
- package/skills/fe-test-ui-scout/references/ledger-schema.md +1 -1
- package/skills/frontend-bounded-implement/references/code-standards.md +3 -3
- package/skills/frontend-contract/SKILL.md +2 -1
- package/skills/frontend-contract/references/contract-protocol.md +22 -4
- package/skills/frontend-design-review/SKILL.md +16 -18
- package/skills/frontend-design-review/references/review-checklist.md +3 -4
- package/skills/frontend-plan/SKILL.md +25 -3
- package/skills/frontend-plan/references/decision-contract.md +117 -8
- package/skills/frontend-plan/references/design-decisions.md +32 -0
- package/skills/frontend-review/SKILL.md +29 -36
- package/skills/frontend-review/references/review-findings.md +8 -3
- package/skills/frontend-scout/references/scout-evidence.md +4 -0
- package/skills/init-update/SKILL.md +34 -0
- package/skills/init-update/agents/openai.yaml +6 -0
- package/skills/loop-agent/references/command-reference.md +8 -0
- package/skills/loop-agent/references/hybrid-dag.md +1 -1
- package/skills/playwright-cli/SKILL.md +1 -1
- package/skills/playwright-cli-case-generator/SKILL.md +7 -5
- package/dist/commands/new-task.js +0 -5
- package/dist/commands/status.js +0 -57
- package/dist/commands/task-contract.js +0 -269
- package/dist/shared/prompts.js +0 -26
- package/dist/task/config.js +0 -2
- package/dist/task/contract/validate-draft.js +0 -106
- package/dist/task/goal.js +0 -3
- package/dist/task/index.js +0 -12
- package/dist/task/lifecycle.js +0 -1
- package/dist/task/operator/capabilities.js +0 -6
- package/dist/task/operator/envelope.js +0 -2
- package/dist/task/operator/index.js +0 -5
- package/dist/task/operator/registry.js +0 -2
- package/dist/task/paths.js +0 -1
- package/dist/task/source-state.js +0 -1
- package/dist/task/subagent-guidance.js +0 -1
- package/dist/worker/console/chat/sift-bridge.js +0 -1
- package/dist/worker/console/index.js +0 -20
- package/dist/worker/console/static/assets/channel-CXqdP5pW.js +0 -1
- package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-D9C3agF7.js +0 -1
- package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-D9C3agF7.js +0 -1
- package/dist/worker/console/static/assets/index-CAZ2fC_X.css +0 -1
- package/dist/worker/console/static/assets/index-DhfjOafu.js +0 -449
- package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Tp7V0U4q.js +0 -1
- package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-DUZWZWi8.js +0 -8
- package/dist/worker/scheduler/index.js +0 -25
- package/dist/workflows/dag/facts.js +0 -4
- package/dist/workflows/dag/frontend-shadow-dual-write.js +0 -941
- package/dist/workflows/dag/index.js +0 -6
- package/dist/workflows/dynamic/index.js +0 -7
- /package/dist/{task/operator/types.js → executors/dag-pi/plan/session.js} +0 -0
|
@@ -26,24 +26,43 @@
|
|
|
26
26
|
* `createDefaultPiSdkBindings()`.
|
|
27
27
|
*/
|
|
28
28
|
import { createHash, randomBytes } from "node:crypto";
|
|
29
|
-
import {
|
|
29
|
+
import { stat } from "node:fs/promises";
|
|
30
30
|
import path from "node:path";
|
|
31
31
|
import { extractAssistantContentBlocks, extractAssistantText, isAssistantSdkMessage, } from "./assistant-content.js";
|
|
32
32
|
import { parseProviderError, } from "./provider-error.js";
|
|
33
33
|
import { projectCompactSnapshot, } from "./chat-event-store.js";
|
|
34
34
|
import { extractUsageSample } from "./usage.js";
|
|
35
35
|
import { OPERATOR_CHAT_ALLOWED_TOOLS, authorizeOperatorChatTool, assertNoWriteToolInList, } from "./tools.js";
|
|
36
|
+
import { authorizeChatSessionTool, DEFAULT_CONSOLE_CHAT_SESSION_MODE, chatActiveToolBaseline, composeChatSystemPrompt, composeChatSystemPromptParts, computeChatActiveToolNames, shouldLoadWorkflowBusinessTools, } from "./session-mode.js";
|
|
37
|
+
import { buildAgentCustomTool, ExploreOrchestrator, } from "./subagents/index.js";
|
|
36
38
|
import { createOperatorChatResourceLoader, } from "./resource-loader.js";
|
|
37
|
-
import { applySkillAutoInvocationPreferences,
|
|
38
|
-
import {
|
|
39
|
-
import {
|
|
39
|
+
import { applySkillAutoInvocationPreferences, loadResourcePreferences, } from "./resource-preferences-store.js";
|
|
40
|
+
import { buildPiModeLoopIsolationOptions } from "./pi-mode-loop-isolation.js";
|
|
41
|
+
import { applyProcessRetryOverride, } from "../../../shared/pi-retry-settings.js";
|
|
42
|
+
import { applyProcessCompactionOverride, createCompactionController, createContextPressureExtension, createSiftBridgeState, housekeepSiftStash, isConsoleSiftEnabled, parseCompactionPolicy, parsePiToolResultPruneConfig, parseSiftBridgeConfig, projectPromptPressure, deriveEffectiveWindow, projectSafeTelemetry, emptyContextPressureCounters, } from "../../../shared/pi-context-pressure/index.js";
|
|
40
43
|
import { incrementCounter as incrementPressureCounter } from "../../../shared/pi-context-pressure/telemetry.js";
|
|
41
44
|
import { resolveDefaultChatModel, resolveLowChatModel, } from "./model-resolver.js";
|
|
42
45
|
import { filterActiveInterviewTools } from "../interview/tools.js";
|
|
43
|
-
import {
|
|
46
|
+
import { redactRuntimeText } from "./runtime-context.js";
|
|
47
|
+
import { BrowserAutomationService } from "./browser-automation.js";
|
|
44
48
|
import { buildTodoContinuationContext, } from "./todos.js";
|
|
49
|
+
import { buildPersistentTerminalTools } from "./terminal-tools.js";
|
|
50
|
+
import { buildScmTools } from "./scm-tools.js";
|
|
51
|
+
import { DbConnectionRegistry } from "./db-connections.js";
|
|
52
|
+
import { buildSqlTools } from "./pi-runtime/custom-tools/sql-tools.js";
|
|
45
53
|
import { buildGoalContinuationContext, } from "./goals.js";
|
|
46
54
|
import { injectWizardLocalHeaders, } from "./sdd-data-alignment.js";
|
|
55
|
+
import { buildScheduledGoalTools } from "./pi-runtime/custom-tools/scheduled-goal-tools.js";
|
|
56
|
+
import { WorkflowToolExposure, configuredToolExposure, isScheduledBookingTurn, pinScheduledBookingTurnTools, } from "./pi-runtime/progressive-tools.js";
|
|
57
|
+
import { buildCustomOperatorTools } from "./pi-runtime/custom-tools/operator-tools.js";
|
|
58
|
+
import { buildBrowserTools } from "./pi-runtime/custom-tools/browser-tools.js";
|
|
59
|
+
import { buildAskUserQuestionTool } from "./pi-runtime/custom-tools/ask-user-question.js";
|
|
60
|
+
import { buildTodoWriteTool } from "./pi-runtime/custom-tools/todo-write.js";
|
|
61
|
+
import { buildGoalTools } from "./pi-runtime/custom-tools/goal-tools.js";
|
|
62
|
+
import { buildExploreCustomTools } from "./pi-runtime/custom-tools/explore-tools.js";
|
|
63
|
+
import { THINKING_LEVELS, RuntimeSnapshotUnavailableError, } from "./pi-runtime/inspection-types.js";
|
|
64
|
+
import { collectRuntimeInventories, collectSlashCommands, projectRuntimeSnapshot, } from "./pi-runtime/inspection.js";
|
|
65
|
+
import { createDefaultPiSdkBindings, safeGetAgentDir, } from "./pi-runtime/sdk-bindings.js";
|
|
47
66
|
/**
|
|
48
67
|
* Base system prompt fragment every General Operator Chat session receives.
|
|
49
68
|
*
|
|
@@ -66,23 +85,15 @@ import { injectWizardLocalHeaders, } from "./sdd-data-alignment.js";
|
|
|
66
85
|
*/
|
|
67
86
|
export const OPERATOR_CHAT_SYSTEM_PROMPT_BASE = [
|
|
68
87
|
"You are General Operator Chat.",
|
|
69
|
-
"
|
|
88
|
+
"For workflow requests use operator tools; discover missing capabilities via operatorCapabilities(target). Obey AGENTS.md. Deny apply_patch/full-tools/shell/coding-chat; probe with safe-read/safe-grep. Browser_*: external window, independent sidebar; follow tool contracts for refs/eval/storage.",
|
|
70
89
|
"No harness and asked to init: `loop-agent init instructions --repo-root .`, then `loop-agent init --repo-root . --profile full --merge`; verify with doctor, inspect and docs audit. Updates: `loop-agent init upgrade --repo-root . --json` until stable; `loop-agent init check-update` is read-only.",
|
|
90
|
+
"Scheduled intent takes precedence over task content: prepareScheduledTask first; no curl/HTTP probes or tests; never perform the scheduled work now. Only a planned goalId means booked; never self-confirm.",
|
|
71
91
|
"Long DAGs: prepareDagExecution → runDag → operationId. Never foreground-Bash task advance, tail/head pipes or nohup/Start-Process/start; do not end on accepted/queued/running or an operationId — NOT completion. Supervise operationGet/status/dagReport/dagDoctor/operationWait at 60s → 90s → 120s → 180s; reset to 60s on state change; 30-60s re-checks when stall suspected. operationWait MUST use afterSeq=previous nextSeq (recommendedNextCall). Heartbeats: not meaningful progress. Run id ≠ task id.",
|
|
72
|
-
"Failure: terminal runSummary
|
|
73
|
-
"
|
|
74
|
-
"Continue until success, user stop, or no safe recovery remains
|
|
75
|
-
"
|
|
92
|
+
"Failure: dagReport(runId) → terminal runSummary. With progress wait; else dagRerunPlan(fromNode=primaryFailure.nodeId); eligible → dagRerun: reruns the failed subgraph, keeps prior successes. Ineligible: Worker → workerTaskRetry; standalone → standaloneTaskRerun after contract adopt (regenerates the whole task, not node continue). No dagResume or re-advance of run-failed tasks. Pre-run identical state twice: stop and report; never loop identical bash/read/grep. Approve only bounded writeSet inside allowedPaths, outside forbiddenPaths, with structured verification.",
|
|
93
|
+
"Each bounded round: summarize the previous round's error in one line, fix its root cause — not the symptom — then rerun the failed node with a fresh plan. Never resubmit an unchanged fix; after two rounds failing the same way, stop and report evidence and remaining routes.",
|
|
94
|
+
"Continue until success, user stop, or no safe recovery remains. Never create a new task for a transient failure or replace repair-pi with direct edits.",
|
|
95
|
+
"Report start, meaningful phase changes, failures, prolonged quiet and completion: what finished and what is next. Never narrate unchanged operationWait polls or heartbeats.",
|
|
76
96
|
].join("\n");
|
|
77
|
-
/** Compose the inspectable system prompt actually injected into Operator Chat. */
|
|
78
|
-
export function composeOperatorChatSystemPrompt(input) {
|
|
79
|
-
return [
|
|
80
|
-
OPERATOR_CHAT_SYSTEM_PROMPT_BASE,
|
|
81
|
-
...(input.systemPromptSuffix?.trim()
|
|
82
|
-
? [input.systemPromptSuffix.trim()]
|
|
83
|
-
: []),
|
|
84
|
-
].join("\n\n");
|
|
85
|
-
}
|
|
86
97
|
/**
|
|
87
98
|
* Built-in SDK tool names registered for every Chat session (ADR 0011).
|
|
88
99
|
* Full Pi builtins: read/write/edit/bash/grep/find/ls. safe-* custom tools
|
|
@@ -111,26 +122,8 @@ export const OPERATOR_CHAT_SAFE_EXPLORE_TOOL_IDS = Object.freeze([
|
|
|
111
122
|
"git-diff",
|
|
112
123
|
]);
|
|
113
124
|
export function OPERATOR_CHAT_ACTIVE_TOOL_NAMES() {
|
|
114
|
-
return
|
|
115
|
-
...OPERATOR_CHAT_ALLOWED_TOOLS,
|
|
116
|
-
...OPERATOR_CHAT_BUILTIN_EXPLORE_TOOLS,
|
|
117
|
-
...OPERATOR_CHAT_SAFE_EXPLORE_TOOL_IDS,
|
|
118
|
-
];
|
|
125
|
+
return chatActiveToolBaseline("workflow");
|
|
119
126
|
}
|
|
120
|
-
/**
|
|
121
|
-
* Non-Pi write / coding channels that must never be activated in Operator
|
|
122
|
-
* Chat even when a user/project extension registers them (ADR 0011 / 0012).
|
|
123
|
-
* Mirrors the NON_PI_WRITE_CHANNELS guard in tools.ts for the Gate 2 pin.
|
|
124
|
-
*/
|
|
125
|
-
const OPERATOR_CHAT_EXTENSION_DENIED_TOOL_IDS = new Set([
|
|
126
|
-
"apply_patch",
|
|
127
|
-
"apply-patch",
|
|
128
|
-
"full-tools",
|
|
129
|
-
"full_tools",
|
|
130
|
-
"coding-chat",
|
|
131
|
-
"coding_chat",
|
|
132
|
-
"shell",
|
|
133
|
-
].map((t) => t.toLowerCase()));
|
|
134
127
|
/**
|
|
135
128
|
* Gate 2 active-tool set for a live session (ADR 0012): the operator-chat
|
|
136
129
|
* baseline (operator actions + Pi builtins + safe explore) PLUS extension
|
|
@@ -141,24 +134,8 @@ const OPERATOR_CHAT_EXTENSION_DENIED_TOOL_IDS = new Set([
|
|
|
141
134
|
* coding-chat). Unknown/denied names are never activated; Gate 3 still
|
|
142
135
|
* re-authorizes every tool call per invocation.
|
|
143
136
|
*/
|
|
144
|
-
export function computeOperatorChatActiveToolNames(session) {
|
|
145
|
-
|
|
146
|
-
if (!session?.getAllTools)
|
|
147
|
-
return baseline;
|
|
148
|
-
const baselineLower = new Set(baseline.map((t) => t.toLowerCase()));
|
|
149
|
-
const extras = [];
|
|
150
|
-
for (const tool of session.getAllTools()) {
|
|
151
|
-
const name = tool?.name;
|
|
152
|
-
if (!name || typeof name !== "string")
|
|
153
|
-
continue;
|
|
154
|
-
const lower = name.toLowerCase();
|
|
155
|
-
if (baselineLower.has(lower))
|
|
156
|
-
continue;
|
|
157
|
-
if (OPERATOR_CHAT_EXTENSION_DENIED_TOOL_IDS.has(lower))
|
|
158
|
-
continue;
|
|
159
|
-
extras.push(name);
|
|
160
|
-
}
|
|
161
|
-
return extras.length > 0 ? [...baseline, ...extras] : baseline;
|
|
137
|
+
export function computeOperatorChatActiveToolNames(session, sessionMode = DEFAULT_CONSOLE_CHAT_SESSION_MODE) {
|
|
138
|
+
return computeChatActiveToolNames(session, sessionMode);
|
|
162
139
|
}
|
|
163
140
|
const OPERATOR_CHAT_SESSION_EXCLUDE_TOOLS = Object.freeze([
|
|
164
141
|
"apply_patch",
|
|
@@ -214,8 +191,27 @@ async function bindSessionExtensions(session) {
|
|
|
214
191
|
return;
|
|
215
192
|
await session.bindExtensions(createConsoleExtensionBindings());
|
|
216
193
|
}
|
|
217
|
-
function
|
|
218
|
-
|
|
194
|
+
export function branchForkedSessionManager(sessionManager, throughUserMessageIndex) {
|
|
195
|
+
const userEntries = (sessionManager.getBranch?.() ?? []).filter((entry) => {
|
|
196
|
+
if (!entry || typeof entry !== "object")
|
|
197
|
+
return false;
|
|
198
|
+
const candidate = entry;
|
|
199
|
+
return candidate.type === "message" && candidate.message?.role === "user";
|
|
200
|
+
});
|
|
201
|
+
const target = userEntries[throughUserMessageIndex];
|
|
202
|
+
if (!target || typeof target.id !== "string") {
|
|
203
|
+
throw new Error("FORK_MESSAGE_ENTRY_NOT_FOUND");
|
|
204
|
+
}
|
|
205
|
+
sessionManager.branch(target.id);
|
|
206
|
+
if (typeof sessionManager.appendCustomEntry !== "function") {
|
|
207
|
+
throw new Error("FORK_MESSAGE_ENTRY_PERSIST_UNSUPPORTED");
|
|
208
|
+
}
|
|
209
|
+
sessionManager.appendCustomEntry("loop-agent-fork-point", {
|
|
210
|
+
throughUserMessageIndex,
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
function pinOperatorChatTools(session, sessionMode = DEFAULT_CONSOLE_CHAT_SESSION_MODE) {
|
|
214
|
+
session.setActiveToolsByName(computeChatActiveToolNames(session, sessionMode));
|
|
219
215
|
}
|
|
220
216
|
/**
|
|
221
217
|
* Pi has no hook result that merely appends instructions to its built-in
|
|
@@ -317,593 +313,46 @@ export function createWizardLocalHeadersExtension(options) {
|
|
|
317
313
|
},
|
|
318
314
|
};
|
|
319
315
|
}
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
const
|
|
333
|
-
const
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
let t;
|
|
344
|
-
switch (param.type) {
|
|
345
|
-
case "string":
|
|
346
|
-
t = Type.String(desc);
|
|
347
|
-
break;
|
|
348
|
-
case "boolean":
|
|
349
|
-
t = Type.Boolean(desc);
|
|
350
|
-
break;
|
|
351
|
-
case "number":
|
|
352
|
-
t = Type.Number(desc);
|
|
353
|
-
break;
|
|
354
|
-
case "array":
|
|
355
|
-
t = Type.Array(Type.String({}), Object.keys(desc).length ? desc : {});
|
|
356
|
-
break;
|
|
357
|
-
default:
|
|
358
|
-
t = Type.Object({}, { additionalProperties: true });
|
|
359
|
-
}
|
|
360
|
-
acc[param.name] = param.required ? t : Type.Optional(t);
|
|
361
|
-
return acc;
|
|
362
|
-
}, {}), { additionalProperties: false });
|
|
363
|
-
return defineTool({
|
|
364
|
-
name: schema.toolId,
|
|
365
|
-
label: schema.toolId,
|
|
366
|
-
description: `${schema.description} (kind=${schema.kind}; cli: ${schema.cli})`,
|
|
367
|
-
promptSnippet: schema.description,
|
|
368
|
-
parameters: parameters,
|
|
369
|
-
async execute(toolCallId, params) {
|
|
370
|
-
const decision = authorizeOperatorChatTool(schema.toolId);
|
|
371
|
-
if (!decision.ok) {
|
|
372
|
-
return {
|
|
373
|
-
content: [
|
|
374
|
-
{
|
|
375
|
-
type: "text",
|
|
376
|
-
text: JSON.stringify({
|
|
377
|
-
error: decision.message,
|
|
378
|
-
code: decision.code,
|
|
379
|
-
}),
|
|
380
|
-
},
|
|
381
|
-
],
|
|
382
|
-
details: { error: decision.message, code: decision.code },
|
|
383
|
-
};
|
|
384
|
-
}
|
|
385
|
-
// Defer require to avoid circular import at module load.
|
|
386
|
-
const { dispatchChatToolCall } = await import("./session-store.js");
|
|
387
|
-
const result = await dispatchChatToolCall(ctx, decision.toolId, params, toolCallId);
|
|
388
|
-
const payload = result.ok
|
|
389
|
-
? result.result
|
|
390
|
-
: { error: result.message, code: result.errorCode };
|
|
391
|
-
return {
|
|
392
|
-
content: [{ type: "text", text: JSON.stringify(payload) }],
|
|
393
|
-
details: payload,
|
|
394
|
-
};
|
|
395
|
-
},
|
|
396
|
-
});
|
|
397
|
-
});
|
|
398
|
-
}
|
|
399
|
-
const ASK_USER_QUESTION_DESCRIPTION = "Ask the user concise questions when a confirmation, choice, or missing detail is required before proceeding. " +
|
|
400
|
-
"The tool pauses until the user answers. Use it instead of writing questions as ordinary assistant text. " +
|
|
401
|
-
"Send one or more questions with stable ids; recommended options should be first and end with (Recommended).";
|
|
402
|
-
async function buildAskUserQuestionTool(options) {
|
|
403
|
-
const [{ Type }, { defineTool }] = await Promise.all([
|
|
404
|
-
import("typebox"),
|
|
405
|
-
import("@earendil-works/pi-coding-agent"),
|
|
406
|
-
]);
|
|
407
|
-
return defineTool({
|
|
408
|
-
name: "ask_user_question",
|
|
409
|
-
label: "Ask user",
|
|
410
|
-
description: ASK_USER_QUESTION_DESCRIPTION,
|
|
411
|
-
promptSnippet: ASK_USER_QUESTION_DESCRIPTION,
|
|
412
|
-
parameters: Type.Object({
|
|
413
|
-
questions: Type.Array(Type.Object({
|
|
414
|
-
id: Type.String({ description: "Stable question id echoed in the answer." }),
|
|
415
|
-
question: Type.String({ description: "Specific user-facing question." }),
|
|
416
|
-
header: Type.Optional(Type.String({ description: "Optional short heading." })),
|
|
417
|
-
detail: Type.Optional(Type.String({ description: "Optional Markdown context shown below the question." })),
|
|
418
|
-
options: Type.Optional(Type.Array(Type.Object({
|
|
419
|
-
label: Type.String({ description: "Short user-facing option label." }),
|
|
420
|
-
description: Type.Optional(Type.String({ description: "One sentence explaining impact or tradeoff." })),
|
|
421
|
-
}, { additionalProperties: false }))),
|
|
422
|
-
multi_select: Type.Optional(Type.Boolean({ description: "Allow more than one option." })),
|
|
423
|
-
}, { additionalProperties: false }), { minItems: 1, maxItems: 20 }),
|
|
424
|
-
}, { additionalProperties: false }),
|
|
425
|
-
async execute(toolCallId, params, signal) {
|
|
426
|
-
const answer = await options.registry.ask({
|
|
427
|
-
sessionId: options.sessionId,
|
|
428
|
-
toolCallId,
|
|
429
|
-
questions: params.questions,
|
|
430
|
-
signal,
|
|
431
|
-
});
|
|
432
|
-
return {
|
|
433
|
-
content: [{ type: "text", text: JSON.stringify(answer) }],
|
|
434
|
-
details: answer,
|
|
435
|
-
};
|
|
436
|
-
},
|
|
437
|
-
});
|
|
438
|
-
}
|
|
439
|
-
const TODO_WRITE_DESCRIPTION = "Record and update a structured task list for the current work. Send the ENTIRE list every call — it REPLACES the previous list (no partial updates, no per-item edits). Before starting multi-step work, add one todo per concrete step. Keep at least one todo `in_progress` while work remains. Mark a todo `completed` immediately when it is done (do not batch completions) and resend the full list as progress or DAG state advances. Skip the list for simple Q&A, read-only lookups, and single-step tasks. Use it for multi-step implementation and whenever you prepare, run, or supervise a DAG — call `todo_write` before entering the DAG tool chain. Phrase DAG todos as user-facing phases users can understand, not copies of internal DAG nodes. Statuses: `pending` / `in_progress` / `completed`.";
|
|
440
|
-
async function buildTodoWriteTool(options) {
|
|
441
|
-
const [{ Type }, { defineTool }] = await Promise.all([
|
|
442
|
-
import("typebox"),
|
|
443
|
-
import("@earendil-works/pi-coding-agent"),
|
|
444
|
-
]);
|
|
445
|
-
return defineTool({
|
|
446
|
-
name: "todo_write",
|
|
447
|
-
label: "Update todo list",
|
|
448
|
-
description: TODO_WRITE_DESCRIPTION,
|
|
449
|
-
promptSnippet: TODO_WRITE_DESCRIPTION,
|
|
450
|
-
parameters: Type.Object({
|
|
451
|
-
todos: Type.Array(Type.Object({
|
|
452
|
-
content: Type.String({ description: "Short imperative task description." }),
|
|
453
|
-
status: Type.Union([
|
|
454
|
-
Type.Literal("pending"),
|
|
455
|
-
Type.Literal("in_progress"),
|
|
456
|
-
Type.Literal("completed"),
|
|
457
|
-
]),
|
|
458
|
-
}, { additionalProperties: false })),
|
|
459
|
-
}, { additionalProperties: false }),
|
|
460
|
-
async execute(toolCallId, params) {
|
|
461
|
-
const result = options.registry.write(options.sessionId, toolCallId, params.todos);
|
|
462
|
-
return {
|
|
463
|
-
content: [{ type: "text", text: JSON.stringify(result) }],
|
|
464
|
-
details: result,
|
|
465
|
-
};
|
|
466
|
-
},
|
|
467
|
-
});
|
|
468
|
-
}
|
|
469
|
-
const GET_GOAL_DESCRIPTION = "Read the current session's durable cross-turn Goal, including revision, status, round limit, and whether this Console process is authorized to continue it.";
|
|
470
|
-
const CREATE_GOAL_DESCRIPTION = "Create a durable cross-turn Goal only when the user explicitly asks to start or create a Goal. Never silently upgrade an ordinary request. A session may have only one unfinished Goal.";
|
|
471
|
-
const UPDATE_GOAL_DESCRIPTION = "Finish or block the current durable Goal using its exact goalId and revision. Set complete only when the objective is genuinely achieved and no required work remains. Set blocked only when safe progress cannot continue; include the blocker.";
|
|
472
|
-
async function buildGoalTools(options) {
|
|
473
|
-
const [{ Type }, { defineTool }] = await Promise.all([
|
|
474
|
-
import("typebox"),
|
|
475
|
-
import("@earendil-works/pi-coding-agent"),
|
|
476
|
-
]);
|
|
477
|
-
const textResult = (value) => ({
|
|
478
|
-
content: [{ type: "text", text: JSON.stringify(value) }],
|
|
479
|
-
details: value,
|
|
480
|
-
});
|
|
481
|
-
return [
|
|
482
|
-
defineTool({
|
|
483
|
-
name: "get_goal",
|
|
484
|
-
label: "Get goal",
|
|
485
|
-
description: GET_GOAL_DESCRIPTION,
|
|
486
|
-
promptSnippet: GET_GOAL_DESCRIPTION,
|
|
487
|
-
parameters: Type.Object({}, { additionalProperties: false }),
|
|
488
|
-
async execute() {
|
|
489
|
-
return textResult({ goal: options.registry.get(options.sessionId) });
|
|
490
|
-
},
|
|
491
|
-
}),
|
|
492
|
-
defineTool({
|
|
493
|
-
name: "create_goal",
|
|
494
|
-
label: "Create goal",
|
|
495
|
-
description: CREATE_GOAL_DESCRIPTION,
|
|
496
|
-
promptSnippet: CREATE_GOAL_DESCRIPTION,
|
|
497
|
-
parameters: Type.Object({
|
|
498
|
-
objective: Type.String({
|
|
499
|
-
description: "Concrete final objective and completion standard explicitly requested by the user.",
|
|
500
|
-
}),
|
|
501
|
-
}, { additionalProperties: false }),
|
|
502
|
-
async execute(_toolCallId, params) {
|
|
503
|
-
if (!options.registry.consumeModelCreateGrant(options.sessionId)) {
|
|
504
|
-
return textResult({
|
|
505
|
-
ok: false,
|
|
506
|
-
code: "GOAL_EXPLICIT_REQUEST_REQUIRED",
|
|
507
|
-
message: "create_goal requires an explicit user request to create or start a Goal",
|
|
508
|
-
});
|
|
509
|
-
}
|
|
510
|
-
return textResult(options.registry.create({
|
|
511
|
-
sessionId: options.sessionId,
|
|
512
|
-
objective: params.objective,
|
|
513
|
-
}));
|
|
514
|
-
},
|
|
515
|
-
}),
|
|
516
|
-
defineTool({
|
|
517
|
-
name: "update_goal",
|
|
518
|
-
label: "Update goal",
|
|
519
|
-
description: UPDATE_GOAL_DESCRIPTION,
|
|
520
|
-
promptSnippet: UPDATE_GOAL_DESCRIPTION,
|
|
521
|
-
parameters: Type.Object({
|
|
522
|
-
goalId: Type.String(),
|
|
523
|
-
revision: Type.Number({ minimum: 1 }),
|
|
524
|
-
status: Type.Union([
|
|
525
|
-
Type.Literal("complete"),
|
|
526
|
-
Type.Literal("blocked"),
|
|
527
|
-
]),
|
|
528
|
-
blocker: Type.Optional(Type.String()),
|
|
529
|
-
}, { additionalProperties: false }),
|
|
530
|
-
async execute(_toolCallId, params) {
|
|
531
|
-
return textResult(options.registry.update({
|
|
532
|
-
sessionId: options.sessionId,
|
|
533
|
-
goalId: params.goalId,
|
|
534
|
-
expectedRevision: params.revision,
|
|
535
|
-
phase: params.status,
|
|
536
|
-
blocker: params.blocker,
|
|
537
|
-
arm: false,
|
|
538
|
-
}));
|
|
539
|
-
},
|
|
540
|
-
}),
|
|
541
|
-
];
|
|
542
|
-
}
|
|
543
|
-
/**
|
|
544
|
-
* Build the safe explore custom tools (roadmap M0-A / G16): safe-read,
|
|
545
|
-
* safe-grep, gitStatus, gitDiff. These replace the bare SDK bash/read/grep so
|
|
546
|
-
* the model can probe the repo WITHOUT write escapes (echo redirect, tee,
|
|
547
|
-
* sed -i, node -e) and WITHOUT reading sensitive files (env files, key/pem,
|
|
548
|
-
* auth.json, sessions dir) — and every returned byte is secret-scrubbed
|
|
549
|
-
* before reaching the model context.
|
|
550
|
-
*
|
|
551
|
-
* gitStatus/gitDiff use a FIXED argv (typed, no shell) so they cannot be
|
|
552
|
-
* turned into an arbitrary-shell vector.
|
|
553
|
-
*/
|
|
554
|
-
async function buildExploreCustomTools(options) {
|
|
555
|
-
const [{ Type }, { defineTool }] = await Promise.all([
|
|
556
|
-
import("typebox"),
|
|
557
|
-
import("@earendil-works/pi-coding-agent"),
|
|
558
|
-
]);
|
|
559
|
-
const { execFileSync } = await import("node:child_process");
|
|
560
|
-
const repoRoot = options.repoRoot;
|
|
561
|
-
const { safeReadFile, safeGrep, scrubSecrets } = await import("./explore-tools.js");
|
|
562
|
-
function safeGit(args) {
|
|
563
|
-
try {
|
|
564
|
-
const stdout = execFileSync("git", args, {
|
|
565
|
-
cwd: repoRoot,
|
|
566
|
-
encoding: "utf8",
|
|
567
|
-
// Fixed argv, no shell, bounded output.
|
|
568
|
-
maxBuffer: 512 * 1024,
|
|
569
|
-
timeout: 10_000,
|
|
570
|
-
windowsHide: true,
|
|
571
|
-
});
|
|
572
|
-
return { ok: true, stdout };
|
|
573
|
-
}
|
|
574
|
-
catch (e) {
|
|
575
|
-
return {
|
|
576
|
-
ok: false,
|
|
577
|
-
code: "GIT_FAILED",
|
|
578
|
-
message: e instanceof Error ? e.message : String(e),
|
|
579
|
-
};
|
|
580
|
-
}
|
|
581
|
-
}
|
|
582
|
-
const safeReadTool = defineTool({
|
|
583
|
-
name: "safe-read",
|
|
584
|
-
label: "safe-read",
|
|
585
|
-
description: "Read a repo-relative file with sensitive-file denylist (.env*/*.key/*.pem/.git/**/auth.json/sessions/**) and secret scrubbing. Absolute paths and .. are rejected.",
|
|
586
|
-
promptSnippet: "safe-read: read a repo file (safe; secrets scrubbed)",
|
|
587
|
-
parameters: Type.Object({
|
|
588
|
-
path: Type.String({ description: "repo-relative file path" }),
|
|
589
|
-
}, { additionalProperties: false }),
|
|
590
|
-
async execute(_toolCallId, params) {
|
|
591
|
-
const raw = String(params.path ?? "");
|
|
592
|
-
try {
|
|
593
|
-
const result = await safeReadFile(repoRoot, raw);
|
|
594
|
-
return {
|
|
595
|
-
content: [{ type: "text", text: JSON.stringify(result) }],
|
|
596
|
-
details: result,
|
|
597
|
-
};
|
|
598
|
-
}
|
|
599
|
-
catch (e) {
|
|
600
|
-
const err = e;
|
|
601
|
-
return {
|
|
602
|
-
content: [
|
|
603
|
-
{
|
|
604
|
-
type: "text",
|
|
605
|
-
text: JSON.stringify({
|
|
606
|
-
error: err.message ?? String(e),
|
|
607
|
-
code: err.code ?? "READ_FAILED",
|
|
608
|
-
}),
|
|
609
|
-
},
|
|
610
|
-
],
|
|
611
|
-
details: {
|
|
612
|
-
error: err.message ?? String(e),
|
|
613
|
-
code: err.code ?? "READ_FAILED",
|
|
614
|
-
},
|
|
615
|
-
};
|
|
616
|
-
}
|
|
617
|
-
},
|
|
618
|
-
});
|
|
619
|
-
const safeGrepTool = defineTool({
|
|
620
|
-
name: "safe-grep",
|
|
621
|
-
label: "safe-grep",
|
|
622
|
-
description: "Line search across the repo working tree with sensitive-file denylist and secret scrubbing. pattern is a JS regex source; optional glob filters paths.",
|
|
623
|
-
promptSnippet: "safe-grep: search repo files (safe; secrets scrubbed)",
|
|
624
|
-
parameters: Type.Object({
|
|
625
|
-
pattern: Type.String({ description: "regex source (no shell)" }),
|
|
626
|
-
caseInsensitive: Type.Optional(Type.Boolean()),
|
|
627
|
-
glob: Type.Optional(Type.String({ description: "optional glob filter e.g. *.ts" })),
|
|
628
|
-
}, { additionalProperties: false }),
|
|
629
|
-
async execute(_toolCallId, params) {
|
|
630
|
-
try {
|
|
631
|
-
const result = await safeGrep(repoRoot, String(params.pattern ?? ""), {
|
|
632
|
-
caseInsensitive: Boolean(params.caseInsensitive),
|
|
633
|
-
glob: params.glob ? String(params.glob) : undefined,
|
|
634
|
-
});
|
|
635
|
-
return {
|
|
636
|
-
content: [{ type: "text", text: JSON.stringify(result) }],
|
|
637
|
-
details: result,
|
|
638
|
-
};
|
|
639
|
-
}
|
|
640
|
-
catch (e) {
|
|
641
|
-
const err = e;
|
|
642
|
-
return {
|
|
643
|
-
content: [
|
|
644
|
-
{
|
|
645
|
-
type: "text",
|
|
646
|
-
text: JSON.stringify({
|
|
647
|
-
error: err.message ?? String(e),
|
|
648
|
-
code: err.code ?? "GREP_FAILED",
|
|
649
|
-
}),
|
|
650
|
-
},
|
|
651
|
-
],
|
|
652
|
-
details: {
|
|
653
|
-
error: err.message ?? String(e),
|
|
654
|
-
code: err.code ?? "GREP_FAILED",
|
|
655
|
-
},
|
|
656
|
-
};
|
|
657
|
-
}
|
|
658
|
-
},
|
|
659
|
-
});
|
|
660
|
-
const gitStatusTool = defineTool({
|
|
661
|
-
name: "git-status",
|
|
662
|
-
label: "git-status",
|
|
663
|
-
description: "Typed `git status --porcelain` (fixed argv, no shell). Returns scrubbed working-tree status.",
|
|
664
|
-
promptSnippet: "git-status: working tree status (read-only)",
|
|
665
|
-
parameters: Type.Object({}, { additionalProperties: false }),
|
|
666
|
-
async execute() {
|
|
667
|
-
const r = safeGit(["status", "--porcelain"]);
|
|
668
|
-
if (!r.ok) {
|
|
669
|
-
return {
|
|
670
|
-
content: [
|
|
671
|
-
{
|
|
672
|
-
type: "text",
|
|
673
|
-
text: JSON.stringify({ error: r.message, code: r.code }),
|
|
674
|
-
},
|
|
675
|
-
],
|
|
676
|
-
details: { error: r.message, code: r.code },
|
|
677
|
-
};
|
|
678
|
-
}
|
|
679
|
-
const { scrubbed, redactions } = scrubSecrets(r.stdout);
|
|
680
|
-
const payload = { status: scrubbed, redactions };
|
|
681
|
-
return {
|
|
682
|
-
content: [{ type: "text", text: JSON.stringify(payload) }],
|
|
683
|
-
details: payload,
|
|
684
|
-
};
|
|
685
|
-
},
|
|
686
|
-
});
|
|
687
|
-
const gitDiffTool = defineTool({
|
|
688
|
-
name: "git-diff",
|
|
689
|
-
label: "git-diff",
|
|
690
|
-
description: "Typed `git diff` (fixed argv: --stat or a single -- path; no shell). Returns scrubbed diff. path must be repo-relative and not sensitive.",
|
|
691
|
-
promptSnippet: "git-diff: diff (read-only, scrubbed)",
|
|
692
|
-
parameters: Type.Object({
|
|
693
|
-
path: Type.Optional(Type.String({
|
|
694
|
-
description: "optional repo-relative path to diff (default: whole tree --stat)",
|
|
695
|
-
})),
|
|
696
|
-
}, { additionalProperties: false }),
|
|
697
|
-
async execute(_toolCallId, params) {
|
|
698
|
-
let rawPath = params.path ? String(params.path) : undefined;
|
|
699
|
-
// If a path is supplied, validate it via the read-path guard so git diff
|
|
700
|
-
// cannot be aimed at sensitive files (.env* / auth.json / sessions).
|
|
701
|
-
if (rawPath) {
|
|
702
|
-
const { guardReadPath } = await import("./explore-tools.js");
|
|
703
|
-
const g = await guardReadPath(repoRoot, rawPath);
|
|
704
|
-
if (!g.ok) {
|
|
705
|
-
return {
|
|
706
|
-
content: [
|
|
707
|
-
{
|
|
708
|
-
type: "text",
|
|
709
|
-
text: JSON.stringify({ error: g.message, code: g.code }),
|
|
710
|
-
},
|
|
711
|
-
],
|
|
712
|
-
details: { error: g.message, code: g.code },
|
|
713
|
-
};
|
|
714
|
-
}
|
|
715
|
-
rawPath = g.repoRelative;
|
|
716
|
-
}
|
|
717
|
-
const args = rawPath ? ["diff", "--", rawPath] : ["diff", "--stat"];
|
|
718
|
-
const r = safeGit(args);
|
|
719
|
-
if (!r.ok) {
|
|
720
|
-
return {
|
|
721
|
-
content: [
|
|
722
|
-
{
|
|
723
|
-
type: "text",
|
|
724
|
-
text: JSON.stringify({ error: r.message, code: r.code }),
|
|
725
|
-
},
|
|
726
|
-
],
|
|
727
|
-
details: { error: r.message, code: r.code },
|
|
728
|
-
};
|
|
729
|
-
}
|
|
730
|
-
const { scrubbed, redactions } = scrubSecrets(r.stdout);
|
|
731
|
-
const payload = { diff: scrubbed, redactions };
|
|
732
|
-
return {
|
|
733
|
-
content: [{ type: "text", text: JSON.stringify(payload) }],
|
|
734
|
-
details: payload,
|
|
735
|
-
};
|
|
736
|
-
},
|
|
737
|
-
});
|
|
738
|
-
return [safeReadTool, safeGrepTool, gitStatusTool, gitDiffTool];
|
|
739
|
-
}
|
|
740
|
-
export const THINKING_LEVELS = [
|
|
741
|
-
"off",
|
|
742
|
-
"minimal",
|
|
743
|
-
"low",
|
|
744
|
-
"medium",
|
|
745
|
-
"high",
|
|
746
|
-
"xhigh",
|
|
747
|
-
"max",
|
|
748
|
-
];
|
|
749
|
-
/**
|
|
750
|
-
* Structured critical-failure error for snapshot projection (RF-02). Model
|
|
751
|
-
* enumeration or system prompt projection failures throw this so consuming
|
|
752
|
-
* routes can return 503 PI_RUNTIME_UNAVAILABLE instead of a fake-empty 200.
|
|
753
|
-
* Partial ResourceLoader / package-inventory failures are NOT critical — they
|
|
754
|
-
* keep the 200 snapshot and surface as structured diagnostics instead.
|
|
755
|
-
*/
|
|
756
|
-
export class RuntimeSnapshotUnavailableError extends Error {
|
|
757
|
-
code = "PI_RUNTIME_UNAVAILABLE";
|
|
758
|
-
constructor(message) {
|
|
759
|
-
super(message);
|
|
760
|
-
this.name = "RuntimeSnapshotUnavailableError";
|
|
761
|
-
}
|
|
762
|
-
}
|
|
763
|
-
/**
|
|
764
|
-
* Browser-safe projection of a live runtime snapshot (design §2.2 / RF-03).
|
|
765
|
-
*
|
|
766
|
-
* Every browser-visible string runs the shared secret-scrub chain
|
|
767
|
-
* (scrubSecrets + ghp_/Bearer redaction via redactRuntimeText) and a fixed
|
|
768
|
-
* per-field length limit: 200 (names/spec/source/origin), 400 (paths/errors/
|
|
769
|
-
* diagnostic messages), 600 (skill descriptions), 80 (package versions);
|
|
770
|
-
* truncation uses the fixed `…[truncated N chars …]` marker. The server-only
|
|
771
|
-
* `raw` prompt and the RAW-based `sha256`/`characters` pass through untouched,
|
|
772
|
-
* and real empty lists stay empty.
|
|
773
|
-
*
|
|
774
|
-
* Pure + deterministic and exported so the route harness reuses the exact
|
|
775
|
-
* production implementation (same code path as getRuntimeSnapshot).
|
|
776
|
-
*/
|
|
777
|
-
export function projectRuntimeSnapshot(input) {
|
|
778
|
-
const field = (value, max) => value === undefined ? undefined : redactRuntimeText(value, max);
|
|
779
|
-
const projectSkill = (skill) => ({
|
|
780
|
-
name: field(skill.name, 200) ?? "",
|
|
781
|
-
description: field(skill.description, 600) ?? "",
|
|
782
|
-
path: field(skill.path, 400) ?? "",
|
|
783
|
-
...(skill.baseDir ? { baseDir: field(skill.baseDir, 400) } : {}),
|
|
784
|
-
scope: skill.scope,
|
|
785
|
-
source: field(skill.source, 200) ?? "",
|
|
786
|
-
resourceId: field(skill.resourceId, 200) ?? "",
|
|
787
|
-
autoInvocationEnabled: skill.autoInvocationEnabled,
|
|
788
|
-
diagnostics: skill.diagnostics.map((diag) => field(diag, 400) ?? ""),
|
|
789
|
-
});
|
|
790
|
-
const projectExtension = (ext) => ({
|
|
791
|
-
name: field(ext.name, 200) ?? "",
|
|
792
|
-
path: field(ext.path, 400) ?? "",
|
|
793
|
-
...(ext.resolvedPath
|
|
794
|
-
? { resolvedPath: field(ext.resolvedPath, 400) }
|
|
795
|
-
: {}),
|
|
796
|
-
source: field(ext.source, 200) ?? "",
|
|
797
|
-
scope: ext.scope,
|
|
798
|
-
...(ext.origin ? { origin: field(ext.origin, 200) } : {}),
|
|
799
|
-
enabled: ext.enabled,
|
|
800
|
-
...(ext.error ? { error: field(ext.error, 400) } : {}),
|
|
801
|
-
});
|
|
802
|
-
const projectPackage = (pkg) => ({
|
|
803
|
-
spec: field(pkg.spec, 200) ?? "",
|
|
804
|
-
scope: pkg.scope,
|
|
805
|
-
enabled: pkg.enabled,
|
|
806
|
-
...(pkg.version ? { version: field(pkg.version, 80) } : {}),
|
|
807
|
-
...(pkg.configuredVersion
|
|
808
|
-
? { configuredVersion: field(pkg.configuredVersion, 80) }
|
|
809
|
-
: {}),
|
|
810
|
-
...(pkg.packageName ? { packageName: field(pkg.packageName, 200) } : {}),
|
|
811
|
-
...(pkg.path ? { path: field(pkg.path, 400) } : {}),
|
|
812
|
-
...(pkg.installedPath ? { installedPath: field(pkg.installedPath, 400) } : {}),
|
|
813
|
-
...(pkg.cwd ? { cwd: field(pkg.cwd, 400) } : {}),
|
|
814
|
-
resolved: pkg.resolved.map((resource) => ({
|
|
815
|
-
type: resource.type,
|
|
816
|
-
name: field(resource.name, 200) ?? "",
|
|
817
|
-
path: field(resource.path, 400) ?? "",
|
|
818
|
-
source: field(resource.source, 200) ?? "",
|
|
819
|
-
scope: resource.scope,
|
|
820
|
-
})),
|
|
821
|
-
diagnostics: pkg.diagnostics.map((diag) => field(diag, 400) ?? ""),
|
|
822
|
-
});
|
|
823
|
-
const projectMcpTool = (tool) => ({
|
|
824
|
-
name: field(tool.name, 200) ?? "",
|
|
825
|
-
description: field(tool.description, 600) ?? "",
|
|
826
|
-
...(tool.server ? { server: field(tool.server, 200) } : {}),
|
|
827
|
-
source: field(tool.source, 200) ?? "",
|
|
828
|
-
scope: tool.scope,
|
|
829
|
-
...(tool.path ? { path: field(tool.path, 400) } : {}),
|
|
830
|
-
active: tool.active,
|
|
831
|
-
});
|
|
832
|
-
const projectMcp = (mcp) => ({
|
|
833
|
-
servers: mcp.servers.map((server) => ({
|
|
834
|
-
name: field(server.name, 200) ?? "",
|
|
835
|
-
scope: server.scope,
|
|
836
|
-
status: server.status,
|
|
837
|
-
enabled: server.enabled,
|
|
838
|
-
...(server.transport ? { transport: field(server.transport, 80) } : {}),
|
|
839
|
-
...(server.command ? { command: field(server.command, 400) } : {}),
|
|
840
|
-
...(server.url ? { url: field(server.url, 400) } : {}),
|
|
841
|
-
...(server.configPath ? { configPath: field(server.configPath, 400) } : {}),
|
|
842
|
-
tools: server.tools.map(projectMcpTool),
|
|
843
|
-
})),
|
|
844
|
-
unassignedTools: mcp.unassignedTools.map(projectMcpTool),
|
|
845
|
-
});
|
|
846
|
-
const projectDiagnostic = (diag) => ({
|
|
847
|
-
type: diag.type,
|
|
848
|
-
...(diag.code ? { code: diag.code } : {}),
|
|
849
|
-
message: field(diag.message, 400) ?? "",
|
|
850
|
-
...(diag.path ? { path: field(diag.path, 400) } : {}),
|
|
851
|
-
...(diag.retryable !== undefined
|
|
852
|
-
? { retryable: diag.retryable }
|
|
853
|
-
: {}),
|
|
854
|
-
});
|
|
316
|
+
export { THINKING_LEVELS, RuntimeSnapshotUnavailableError, projectRuntimeSnapshot, };
|
|
317
|
+
export { createDefaultPiSdkBindings } from "./pi-runtime/sdk-bindings.js";
|
|
318
|
+
/** Catalog listing must not load skills/extensions/context — those belong to reopen. */
|
|
319
|
+
const CATALOG_RESOURCE_LOADER_OPTIONS = Object.freeze({
|
|
320
|
+
noContextFiles: true,
|
|
321
|
+
noSkills: true,
|
|
322
|
+
noExtensions: true,
|
|
323
|
+
noPromptTemplates: true,
|
|
324
|
+
noThemes: true,
|
|
325
|
+
});
|
|
326
|
+
export { extractAssistantContentBlocks, extractAssistantText, isAssistantSdkMessage };
|
|
327
|
+
export function buildRequestContextEvent(input) {
|
|
328
|
+
const systemPrompt = input.session.state?.systemPrompt ?? input.session.systemPrompt ?? "";
|
|
329
|
+
const activeTools = input.session.getActiveToolNames()
|
|
330
|
+
.filter((name) => typeof name === "string" && name.trim())
|
|
331
|
+
.slice(0, 256);
|
|
332
|
+
const provider = input.session.model?.provider;
|
|
333
|
+
const modelId = input.session.model?.modelId ?? input.session.model?.id;
|
|
334
|
+
const sources = ["system", "conversation"];
|
|
335
|
+
if (activeTools.length > 0)
|
|
336
|
+
sources.push("tools");
|
|
337
|
+
if (input.imageCount > 0)
|
|
338
|
+
sources.push("images");
|
|
855
339
|
return {
|
|
340
|
+
type: "request_context",
|
|
856
341
|
sessionId: input.sessionId,
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
}
|
|
870
|
-
: {}),
|
|
871
|
-
thinkingSelection: input.selection.thinkingSelection,
|
|
872
|
-
...(input.selection.effectiveThinkingLevel
|
|
873
|
-
? { effectiveThinkingLevel: input.selection.effectiveThinkingLevel }
|
|
874
|
-
: {}),
|
|
875
|
-
},
|
|
876
|
-
models: input.models.map((model) => ({
|
|
877
|
-
provider: model.provider,
|
|
878
|
-
id: model.id,
|
|
879
|
-
...(model.name ? { name: field(model.name, 200) } : {}),
|
|
880
|
-
...(model.hasCredentials !== undefined
|
|
881
|
-
? { hasCredentials: model.hasCredentials }
|
|
882
|
-
: {}),
|
|
883
|
-
})),
|
|
884
|
-
thinkingLevels: input.thinkingLevels.map((option) => ({ ...option })),
|
|
885
|
-
systemPrompt: {
|
|
886
|
-
...(input.systemPrompt.raw !== undefined
|
|
887
|
-
? { raw: input.systemPrompt.raw }
|
|
888
|
-
: {}),
|
|
889
|
-
text: redactRuntimeText(input.systemPrompt.text, RUNTIME_CONTEXT_TEXT_MAX),
|
|
890
|
-
sha256: input.systemPrompt.sha256,
|
|
891
|
-
characters: input.systemPrompt.characters,
|
|
892
|
-
},
|
|
893
|
-
activeTools: [...input.activeTools],
|
|
894
|
-
contextFiles: input.contextFiles.map((file) => ({
|
|
895
|
-
path: field(file.path, 400) ?? "",
|
|
896
|
-
characters: file.characters,
|
|
897
|
-
})),
|
|
898
|
-
skills: input.skills.map(projectSkill),
|
|
899
|
-
extensions: input.extensions.map(projectExtension),
|
|
900
|
-
packages: input.packages.map(projectPackage),
|
|
901
|
-
mcp: projectMcp(input.mcp ?? { servers: [], unassignedTools: [] }),
|
|
902
|
-
diagnostics: input.diagnostics.map(projectDiagnostic),
|
|
903
|
-
hasBash: input.hasBash,
|
|
342
|
+
requestId: `${input.turnId}:request:1`,
|
|
343
|
+
step: 1,
|
|
344
|
+
...(provider && modelId ? { model: { provider, modelId } } : {}),
|
|
345
|
+
...(input.session.thinkingLevel
|
|
346
|
+
? { thinkingLevel: input.session.thinkingLevel }
|
|
347
|
+
: {}),
|
|
348
|
+
systemPromptHash: createHash("sha256").update(systemPrompt).digest("hex"),
|
|
349
|
+
systemPromptChars: systemPrompt.length,
|
|
350
|
+
activeTools,
|
|
351
|
+
inputChars: input.text.length,
|
|
352
|
+
imageCount: input.imageCount,
|
|
353
|
+
sources,
|
|
904
354
|
};
|
|
905
355
|
}
|
|
906
|
-
export { extractAssistantContentBlocks, extractAssistantText, isAssistantSdkMessage };
|
|
907
356
|
function readSessionManagerId(manager) {
|
|
908
357
|
if (!manager || typeof manager !== "object")
|
|
909
358
|
return undefined;
|
|
@@ -1000,6 +449,7 @@ export class ConsolePiRuntime {
|
|
|
1000
449
|
/** Non-sensitive models.json metadata used to avoid reparsing unchanged config. */
|
|
1001
450
|
modelConfigFiles = new Map();
|
|
1002
451
|
sessionManagers = new Map();
|
|
452
|
+
toolExposures = new Map();
|
|
1003
453
|
/** Per-session SDK service scope (resourceLoader / settingsManager) used by the live runtime snapshot. */
|
|
1004
454
|
serviceScopes = new Map();
|
|
1005
455
|
/** Snapshot revision: bumped on create / reopen / model / thinking / reload. */
|
|
@@ -1017,21 +467,63 @@ export class ConsolePiRuntime {
|
|
|
1017
467
|
mainlineLeaves = new Map();
|
|
1018
468
|
/** Per-sessionId single-flight materialization (create fast-path / readiness fence). */
|
|
1019
469
|
sessionInit = new Map();
|
|
470
|
+
/** Concurrent reopen of the same historical JSONL shares one in-flight promise. */
|
|
471
|
+
reopenInFlight = new Map();
|
|
1020
472
|
/** Resolved model binding after materialization (create may return before this is known). */
|
|
1021
473
|
sessionModels = new Map();
|
|
474
|
+
/** Durable session mode; record is the source of truth, this is the live handle cache. */
|
|
475
|
+
sessionModes = new Map();
|
|
1022
476
|
/** SessionIds disposed while materialization was still in flight. */
|
|
1023
477
|
disposedSessions = new Set();
|
|
1024
478
|
compactionControllers = new Map();
|
|
1025
479
|
siftStates = new Map();
|
|
1026
480
|
/** Session-less tool definition caches (no AgentSession state). */
|
|
1027
|
-
|
|
1028
|
-
operatorCustomToolsPromise;
|
|
481
|
+
operatorCustomToolsBySession = new Map();
|
|
1029
482
|
exploreCustomToolsPromise;
|
|
483
|
+
exploreOrchestrator;
|
|
1030
484
|
bindings;
|
|
485
|
+
browserAutomation;
|
|
486
|
+
ownsBrowserAutomation;
|
|
487
|
+
dbConnections;
|
|
488
|
+
ownsDbConnections;
|
|
1031
489
|
constructor(options) {
|
|
1032
490
|
this.options = options;
|
|
1033
491
|
this.loader = createOperatorChatResourceLoader();
|
|
1034
492
|
this.bindings = options.bindings ?? createDefaultPiSdkBindings();
|
|
493
|
+
this.ownsBrowserAutomation = options.browserAutomation === undefined;
|
|
494
|
+
this.browserAutomation = options.browserAutomation ?? new BrowserAutomationService({
|
|
495
|
+
profileDir: path.join(this.options.sessionDir, "..", "browser-profile"),
|
|
496
|
+
downloadsDir: path.join(this.options.sessionDir, "..", "browser-downloads"),
|
|
497
|
+
screenshotsDir: path.join(this.options.sessionDir, "..", "browser-screenshots"),
|
|
498
|
+
});
|
|
499
|
+
// Governed DB connections are Console-global, not repository-scoped.
|
|
500
|
+
// This keeps named connections available when the user switches folders.
|
|
501
|
+
this.ownsDbConnections = options.dbConnections === undefined;
|
|
502
|
+
this.dbConnections =
|
|
503
|
+
options.dbConnections ??
|
|
504
|
+
new DbConnectionRegistry(path.join(options.globalAppDataRoot ?? path.resolve(this.options.sessionDir, ".."), "db"), undefined, undefined, path.join(this.options.sessionDir, "..", "db"));
|
|
505
|
+
this.exploreOrchestrator = new ExploreOrchestrator({
|
|
506
|
+
cwd: this.options.cwd,
|
|
507
|
+
bindings: this.bindings,
|
|
508
|
+
loadSafeExploreCustomTools: () => this.loadExploreCustomTools(),
|
|
509
|
+
// Fallback when the parent session's model is unknown at Agent-call
|
|
510
|
+
// time (e.g. turn started before materialization finished): resolve
|
|
511
|
+
// the default Chat model from the child services' modelRuntime.
|
|
512
|
+
resolveModel: async (modelRuntime) => {
|
|
513
|
+
const available = this.bindings.listAvailableModels({ modelRuntime });
|
|
514
|
+
const descriptor = await resolveDefaultChatModel(this.options.cwd, available);
|
|
515
|
+
if (!descriptor)
|
|
516
|
+
return undefined;
|
|
517
|
+
return this.bindings.resolveModel({
|
|
518
|
+
modelRuntime,
|
|
519
|
+
provider: descriptor.provider,
|
|
520
|
+
modelId: descriptor.modelId,
|
|
521
|
+
});
|
|
522
|
+
},
|
|
523
|
+
});
|
|
524
|
+
}
|
|
525
|
+
async syncAimaxAuthToken() {
|
|
526
|
+
await this.options.sddDataAlignment?.auth?.getToken();
|
|
1035
527
|
}
|
|
1036
528
|
/** Absolute path for repo-scoped resource preferences (may be undefined in unit tests). */
|
|
1037
529
|
get resourcePreferencesPath() {
|
|
@@ -1061,7 +553,16 @@ export class ConsolePiRuntime {
|
|
|
1061
553
|
* after a PATCH sees the latest resource-preferences.json (not create-time
|
|
1062
554
|
* closure state).
|
|
1063
555
|
*/
|
|
1064
|
-
|
|
556
|
+
sessionModeOf(sessionId) {
|
|
557
|
+
if (!sessionId)
|
|
558
|
+
return DEFAULT_CONSOLE_CHAT_SESSION_MODE;
|
|
559
|
+
return this.sessionModes.get(sessionId) ?? DEFAULT_CONSOLE_CHAT_SESSION_MODE;
|
|
560
|
+
}
|
|
561
|
+
rememberSessionMode(sessionId, sessionMode = DEFAULT_CONSOLE_CHAT_SESSION_MODE) {
|
|
562
|
+
this.sessionModes.set(sessionId, sessionMode);
|
|
563
|
+
return sessionMode;
|
|
564
|
+
}
|
|
565
|
+
async buildResourceLoaderOptions(base = {}, sessionId, sessionMode = DEFAULT_CONSOLE_CHAT_SESSION_MODE) {
|
|
1065
566
|
const inheritedFactories = Array.isArray(base.extensionFactories)
|
|
1066
567
|
? base.extensionFactories
|
|
1067
568
|
: [];
|
|
@@ -1092,6 +593,7 @@ export class ConsolePiRuntime {
|
|
|
1092
593
|
pressureExtension,
|
|
1093
594
|
wizardLocalHeadersExtension,
|
|
1094
595
|
].filter((item) => Boolean(item));
|
|
596
|
+
const piMode = sessionMode === "pi";
|
|
1095
597
|
return {
|
|
1096
598
|
...base,
|
|
1097
599
|
...(extraFactories.length > 0
|
|
@@ -1099,18 +601,23 @@ export class ConsolePiRuntime {
|
|
|
1099
601
|
extensionFactories: [...inheritedFactories, ...extraFactories],
|
|
1100
602
|
}
|
|
1101
603
|
: {}),
|
|
1102
|
-
|
|
604
|
+
...buildPiModeLoopIsolationOptions({
|
|
605
|
+
enabled: piMode,
|
|
606
|
+
cwd: this.options.cwd,
|
|
1103
607
|
// Synchronous override surface: use last-known prefs via a sync
|
|
1104
608
|
// fail-closed path. Prefer async cache filled by ensurePrefs.
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
609
|
+
readPreferences: () => this.cachedSkillPrefs,
|
|
610
|
+
skillsOverride: (current) => {
|
|
611
|
+
const prefs = this.cachedSkillPrefs ?? {
|
|
612
|
+
schemaVersion: 1,
|
|
613
|
+
skills: {},
|
|
614
|
+
};
|
|
615
|
+
return {
|
|
616
|
+
skills: applySkillAutoInvocationPreferences(current.skills, prefs),
|
|
617
|
+
diagnostics: current.diagnostics,
|
|
618
|
+
};
|
|
619
|
+
},
|
|
620
|
+
}),
|
|
1114
621
|
};
|
|
1115
622
|
}
|
|
1116
623
|
/** Last successfully loaded skill prefs (sync override + snapshot projection). */
|
|
@@ -1134,6 +641,7 @@ export class ConsolePiRuntime {
|
|
|
1134
641
|
}
|
|
1135
642
|
createContextPressureInlineExtension(sessionId) {
|
|
1136
643
|
const policy = parseCompactionPolicy();
|
|
644
|
+
const pruneSettings = parsePiToolResultPruneConfig();
|
|
1137
645
|
const siftEnabled = isConsoleSiftEnabled();
|
|
1138
646
|
let sift;
|
|
1139
647
|
if (siftEnabled.enabled) {
|
|
@@ -1160,9 +668,12 @@ export class ConsolePiRuntime {
|
|
|
1160
668
|
policy,
|
|
1161
669
|
controller: this.getCompactionController(sessionId),
|
|
1162
670
|
sift,
|
|
671
|
+
normalizeTransientProviderErrors: true,
|
|
672
|
+
...(pruneSettings.enabled && policy.mode !== "off" ? { prune: pruneSettings.config } : {}),
|
|
1163
673
|
});
|
|
1164
674
|
}
|
|
1165
|
-
|
|
675
|
+
applySessionRecoveryOverrides(sessionId, services, session) {
|
|
676
|
+
applyProcessRetryOverride(services?.settingsManager);
|
|
1166
677
|
const manager = services?.settingsManager;
|
|
1167
678
|
const window = session?.getSessionStats?.()?.contextUsage?.contextWindow;
|
|
1168
679
|
applyProcessCompactionOverride(manager, {
|
|
@@ -1180,7 +691,7 @@ export class ConsolePiRuntime {
|
|
|
1180
691
|
const window = stats?.contextUsage?.contextWindow;
|
|
1181
692
|
const tokens = stats?.contextUsage?.tokens;
|
|
1182
693
|
if (typeof window === "number" && window > 0) {
|
|
1183
|
-
this.
|
|
694
|
+
this.applySessionRecoveryOverrides(sessionId, this.serviceScopes.get(sessionId) ?? {}, session);
|
|
1184
695
|
}
|
|
1185
696
|
const projection = projectPromptPressure({
|
|
1186
697
|
currentContextTokens: tokens,
|
|
@@ -1194,8 +705,11 @@ export class ConsolePiRuntime {
|
|
|
1194
705
|
const effective = typeof window === "number" && window > 0
|
|
1195
706
|
? deriveEffectiveWindow(window, policy)
|
|
1196
707
|
: undefined;
|
|
1197
|
-
if (!effective || projection.projected < effective.triggerTokens)
|
|
708
|
+
if (!effective || projection.projected < effective.triggerTokens) {
|
|
709
|
+
controller.pruneArmed = false;
|
|
1198
710
|
return;
|
|
711
|
+
}
|
|
712
|
+
controller.pruneArmed = true;
|
|
1199
713
|
if (typeof session.compact !== "function")
|
|
1200
714
|
return;
|
|
1201
715
|
const compactionId = newCompactionId(sessionId);
|
|
@@ -1320,8 +834,10 @@ export class ConsolePiRuntime {
|
|
|
1320
834
|
* `initializing: true`; dependent routes wait on the same promise.
|
|
1321
835
|
*/
|
|
1322
836
|
async createSession(init) {
|
|
837
|
+
await this.syncAimaxAuthToken();
|
|
1323
838
|
const sessionId = `operator-chat-${randomBytes(12).toString("hex")}`;
|
|
1324
839
|
this.disposedSessions.delete(sessionId);
|
|
840
|
+
const sessionMode = this.rememberSessionMode(sessionId, init?.sessionMode ?? DEFAULT_CONSOLE_CHAT_SESSION_MODE);
|
|
1325
841
|
const sessionManager = await this.bindings.createSessionManager({
|
|
1326
842
|
cwd: this.options.cwd,
|
|
1327
843
|
sessionDir: this.options.sessionDir,
|
|
@@ -1347,6 +863,7 @@ export class ConsolePiRuntime {
|
|
|
1347
863
|
sessionManager,
|
|
1348
864
|
model: init?.model,
|
|
1349
865
|
systemPromptSuffix: init?.systemPromptSuffix,
|
|
866
|
+
sessionMode,
|
|
1350
867
|
// Create path must resolve default model from the SAME services object
|
|
1351
868
|
// used for formal materialization (no throwaway createServices).
|
|
1352
869
|
resolveDefaultModel: !init?.model,
|
|
@@ -1356,7 +873,8 @@ export class ConsolePiRuntime {
|
|
|
1356
873
|
sessionFile,
|
|
1357
874
|
createdAt: new Date().toISOString(),
|
|
1358
875
|
model: init?.model,
|
|
1359
|
-
activeTools:
|
|
876
|
+
activeTools: chatActiveToolBaseline(sessionMode),
|
|
877
|
+
sessionMode,
|
|
1360
878
|
initializing: true,
|
|
1361
879
|
};
|
|
1362
880
|
}
|
|
@@ -1414,28 +932,36 @@ export class ConsolePiRuntime {
|
|
|
1414
932
|
this.sessionInit.set(sessionId, { status: "initializing", promise });
|
|
1415
933
|
return promise;
|
|
1416
934
|
}
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
935
|
+
/**
|
|
936
|
+
* Shared session preparation for create/reopen/fork: config capture, prompt
|
|
937
|
+
* composition, resource loading, model resolution, tool assembly, SDK session
|
|
938
|
+
* create, extension bind, tool pin, compaction override. Lifecycle maps stay
|
|
939
|
+
* owned by the caller.
|
|
940
|
+
*/
|
|
941
|
+
async prepareLiveSession(init) {
|
|
942
|
+
const aborted = () => Boolean(init.abortIfDisposed && this.disposedSessions.has(init.sessionId));
|
|
943
|
+
if (aborted())
|
|
944
|
+
return undefined;
|
|
945
|
+
if (init.sessionMode === "workflow" && this.options.actionContext) {
|
|
946
|
+
this.toolExposures.set(init.sessionId, new WorkflowToolExposure(init.sessionManager, this.options.toolExposure ?? configuredToolExposure(process.env.CONSOLE_CHAT_TOOL_EXPOSURE)));
|
|
947
|
+
}
|
|
1420
948
|
const agentDir = await safeGetAgentDir(this.bindings);
|
|
1421
949
|
// Capture before services parse models.json. A concurrent edit can therefore
|
|
1422
950
|
// cause at most one harmless extra refresh, never a missed next-turn refresh.
|
|
1423
951
|
const modelConfigFile = await captureModelConfigFile(agentDir);
|
|
1424
|
-
const appendSystemPrompt =
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
// default-model resolve from the same modelRuntime). Repo-scoped skill
|
|
1430
|
-
// auto-invocation prefs inject skillsOverride without touching SKILL.md.
|
|
952
|
+
const appendSystemPrompt = composeChatSystemPromptParts({
|
|
953
|
+
sessionMode: init.sessionMode,
|
|
954
|
+
workflowPrompt: OPERATOR_CHAT_SYSTEM_PROMPT_BASE,
|
|
955
|
+
systemPromptSuffix: init.systemPromptSuffix,
|
|
956
|
+
});
|
|
1431
957
|
await this.refreshSkillPrefsCache().catch(() => undefined);
|
|
1432
958
|
const { services } = await this.bindings.createServices({
|
|
1433
959
|
cwd: this.options.cwd,
|
|
1434
960
|
agentDir,
|
|
1435
|
-
resourceLoaderOptions: await this.buildResourceLoaderOptions({ appendSystemPrompt }, sessionId),
|
|
961
|
+
resourceLoaderOptions: await this.buildResourceLoaderOptions({ appendSystemPrompt }, init.sessionId, init.sessionMode),
|
|
1436
962
|
});
|
|
1437
|
-
if (
|
|
1438
|
-
return;
|
|
963
|
+
if (aborted())
|
|
964
|
+
return undefined;
|
|
1439
965
|
const modelRuntime = services.modelRuntime;
|
|
1440
966
|
let model = init.model;
|
|
1441
967
|
if (!model && init.resolveDefaultModel) {
|
|
@@ -1449,9 +975,9 @@ export class ConsolePiRuntime {
|
|
|
1449
975
|
}) ?? undefined)
|
|
1450
976
|
: undefined;
|
|
1451
977
|
assertNoWriteToolInList(OPERATOR_CHAT_ALLOWED_TOOLS);
|
|
1452
|
-
const customTools = await this.loadCustomTools(sessionId);
|
|
1453
|
-
if (
|
|
1454
|
-
return;
|
|
978
|
+
const customTools = await this.loadCustomTools(init.sessionId);
|
|
979
|
+
if (aborted())
|
|
980
|
+
return undefined;
|
|
1455
981
|
// pi-web parity: do NOT pass `tools`. A closed allowlist becomes
|
|
1456
982
|
// SDK allowedToolNames and filters extension MCP tools out of the
|
|
1457
983
|
// registry before Gate 2 can re-add them. Operator/safe customTools
|
|
@@ -1465,55 +991,115 @@ export class ConsolePiRuntime {
|
|
|
1465
991
|
...(customTools.length > 0 ? { customTools } : {}),
|
|
1466
992
|
...(resolvedModel ? { model: resolvedModel } : {}),
|
|
1467
993
|
});
|
|
1468
|
-
if (
|
|
994
|
+
if (aborted()) {
|
|
1469
995
|
try {
|
|
1470
996
|
session.dispose();
|
|
1471
997
|
}
|
|
1472
998
|
catch {
|
|
1473
999
|
// ignore late dispose cleanup
|
|
1474
1000
|
}
|
|
1475
|
-
return;
|
|
1001
|
+
return undefined;
|
|
1002
|
+
}
|
|
1003
|
+
try {
|
|
1004
|
+
await bindSessionExtensions(session);
|
|
1005
|
+
this.pinSessionTools(init.sessionId, session);
|
|
1006
|
+
}
|
|
1007
|
+
catch (error) {
|
|
1008
|
+
try {
|
|
1009
|
+
session.dispose();
|
|
1010
|
+
}
|
|
1011
|
+
finally {
|
|
1012
|
+
this.toolExposures.delete(init.sessionId);
|
|
1013
|
+
}
|
|
1014
|
+
throw error;
|
|
1476
1015
|
}
|
|
1477
|
-
|
|
1478
|
-
|
|
1016
|
+
this.applySessionRecoveryOverrides(init.sessionId, services, session);
|
|
1017
|
+
return {
|
|
1018
|
+
session,
|
|
1019
|
+
modelRuntime,
|
|
1020
|
+
modelConfigFile,
|
|
1021
|
+
model,
|
|
1022
|
+
services: {
|
|
1023
|
+
resourceLoader: services.resourceLoader,
|
|
1024
|
+
settingsManager: services.settingsManager,
|
|
1025
|
+
},
|
|
1026
|
+
};
|
|
1027
|
+
}
|
|
1028
|
+
async materializeSession(sessionId, init) {
|
|
1029
|
+
if (this.disposedSessions.has(sessionId))
|
|
1030
|
+
return;
|
|
1031
|
+
await this.syncAimaxAuthToken();
|
|
1032
|
+
const sessionMode = this.rememberSessionMode(sessionId, init.sessionMode ?? this.sessionModeOf(sessionId));
|
|
1033
|
+
const prepared = await this.prepareLiveSession({
|
|
1034
|
+
sessionId,
|
|
1035
|
+
sessionManager: init.sessionManager,
|
|
1036
|
+
model: init.model,
|
|
1037
|
+
systemPromptSuffix: init.systemPromptSuffix,
|
|
1038
|
+
sessionMode,
|
|
1039
|
+
resolveDefaultModel: init.resolveDefaultModel,
|
|
1040
|
+
abortIfDisposed: true,
|
|
1041
|
+
});
|
|
1042
|
+
if (!prepared)
|
|
1043
|
+
return;
|
|
1479
1044
|
// Register then re-check dispose race: a concurrent dispose must win.
|
|
1480
|
-
this.sessions.set(sessionId, session);
|
|
1045
|
+
this.sessions.set(sessionId, prepared.session);
|
|
1481
1046
|
this.sessionManagers.set(sessionId, init.sessionManager);
|
|
1482
|
-
this.modelRuntimes.set(sessionId, modelRuntime);
|
|
1483
|
-
this.modelConfigFiles.set(sessionId, modelConfigFile);
|
|
1484
|
-
this.sessionModels.set(sessionId, model);
|
|
1485
|
-
this.serviceScopes.set(sessionId,
|
|
1486
|
-
resourceLoader: services.resourceLoader,
|
|
1487
|
-
settingsManager: services.settingsManager,
|
|
1488
|
-
});
|
|
1489
|
-
this.applySessionCompactionOverride(sessionId, services, session);
|
|
1047
|
+
this.modelRuntimes.set(sessionId, prepared.modelRuntime);
|
|
1048
|
+
this.modelConfigFiles.set(sessionId, prepared.modelConfigFile);
|
|
1049
|
+
this.sessionModels.set(sessionId, prepared.model);
|
|
1050
|
+
this.serviceScopes.set(sessionId, prepared.services);
|
|
1490
1051
|
this.revisions.set(sessionId, 1);
|
|
1491
1052
|
if (!this.thinkingSelections.has(sessionId)) {
|
|
1492
1053
|
this.thinkingSelections.set(sessionId, "auto");
|
|
1493
1054
|
}
|
|
1494
1055
|
if (this.disposedSessions.has(sessionId)) {
|
|
1495
1056
|
try {
|
|
1496
|
-
session.dispose();
|
|
1057
|
+
prepared.session.dispose();
|
|
1497
1058
|
}
|
|
1498
1059
|
catch {
|
|
1499
1060
|
// ignore
|
|
1500
1061
|
}
|
|
1501
1062
|
this.sessions.delete(sessionId);
|
|
1502
1063
|
this.sessionManagers.delete(sessionId);
|
|
1064
|
+
this.toolExposures.delete(sessionId);
|
|
1503
1065
|
this.modelRuntimes.delete(sessionId);
|
|
1504
1066
|
this.modelConfigFiles.delete(sessionId);
|
|
1505
1067
|
this.sessionModels.delete(sessionId);
|
|
1068
|
+
this.sessionModes.delete(sessionId);
|
|
1506
1069
|
this.serviceScopes.delete(sessionId);
|
|
1507
1070
|
this.revisions.delete(sessionId);
|
|
1508
1071
|
this.thinkingSelections.delete(sessionId);
|
|
1509
1072
|
}
|
|
1510
1073
|
}
|
|
1074
|
+
pinSessionTools(sessionId, session, interview = false) {
|
|
1075
|
+
const exposure = this.toolExposures.get(sessionId);
|
|
1076
|
+
if (exposure) {
|
|
1077
|
+
exposure.pin(session, interview);
|
|
1078
|
+
return;
|
|
1079
|
+
}
|
|
1080
|
+
if (interview) {
|
|
1081
|
+
session.setActiveToolsByName(filterActiveInterviewTools(chatActiveToolBaseline(this.sessionModeOf(sessionId))).allowed);
|
|
1082
|
+
}
|
|
1083
|
+
else
|
|
1084
|
+
pinOperatorChatTools(session, this.sessionModeOf(sessionId));
|
|
1085
|
+
}
|
|
1086
|
+
/** Read-only rollout diagnostics; no model parameters or host identities. */
|
|
1087
|
+
getToolExposure(sessionId) { return this.toolExposures.get(sessionId)?.snapshot; }
|
|
1511
1088
|
/** Cached session-less custom tool definitions (operator + explore). */
|
|
1512
1089
|
async loadCustomTools(sessionId) {
|
|
1090
|
+
const sessionMode = this.sessionModeOf(sessionId);
|
|
1091
|
+
const loadWorkflowTools = shouldLoadWorkflowBusinessTools(sessionMode);
|
|
1513
1092
|
const [operatorCustomTools, exploreCustomTools] = await Promise.all([
|
|
1514
|
-
|
|
1093
|
+
loadWorkflowTools
|
|
1094
|
+
? this.loadOperatorCustomTools(sessionId, sessionMode)
|
|
1095
|
+
: Promise.resolve([]),
|
|
1515
1096
|
this.loadExploreCustomTools(),
|
|
1516
1097
|
]);
|
|
1098
|
+
const scheduledGoalTools = loadWorkflowTools && this.options.actionContext
|
|
1099
|
+
? await buildScheduledGoalTools({ sessionId, actionContext: this.options.actionContext }) : [];
|
|
1100
|
+
const browserTools = await buildBrowserTools({
|
|
1101
|
+
automation: this.browserAutomation,
|
|
1102
|
+
});
|
|
1517
1103
|
const questionTool = this.options.questionRegistry
|
|
1518
1104
|
? await buildAskUserQuestionTool({
|
|
1519
1105
|
sessionId,
|
|
@@ -1521,33 +1107,97 @@ export class ConsolePiRuntime {
|
|
|
1521
1107
|
})
|
|
1522
1108
|
: undefined;
|
|
1523
1109
|
const todoTool = this.options.todoRegistry
|
|
1524
|
-
? await buildTodoWriteTool({
|
|
1110
|
+
? await buildTodoWriteTool({
|
|
1111
|
+
sessionId,
|
|
1112
|
+
registry: this.options.todoRegistry,
|
|
1113
|
+
sessionMode,
|
|
1114
|
+
})
|
|
1525
1115
|
: undefined;
|
|
1526
1116
|
const goalTools = this.options.goalRegistry
|
|
1527
1117
|
? await buildGoalTools({ sessionId, registry: this.options.goalRegistry })
|
|
1528
1118
|
: [];
|
|
1119
|
+
const terminalTools = this.options.terminalRegistry
|
|
1120
|
+
? await buildPersistentTerminalTools({
|
|
1121
|
+
ownerSessionId: sessionId,
|
|
1122
|
+
registry: this.options.terminalRegistry,
|
|
1123
|
+
defaultCwd: this.options.cwd,
|
|
1124
|
+
}).catch((error) => {
|
|
1125
|
+
process.stderr.write(`[console] chat terminal-tools build failed: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
1126
|
+
return [];
|
|
1127
|
+
})
|
|
1128
|
+
: [];
|
|
1129
|
+
const scmTools = this.options.scmService
|
|
1130
|
+
? await buildScmTools({ scm: this.options.scmService }).catch((error) => {
|
|
1131
|
+
process.stderr.write(`[console] chat scm-tools build failed: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
1132
|
+
return [];
|
|
1133
|
+
})
|
|
1134
|
+
: [];
|
|
1135
|
+
const sqlTools = await buildSqlTools({
|
|
1136
|
+
sessionId,
|
|
1137
|
+
registry: this.dbConnections,
|
|
1138
|
+
...(this.options.questionRegistry
|
|
1139
|
+
? { questionRegistry: this.options.questionRegistry }
|
|
1140
|
+
: {}),
|
|
1141
|
+
}).catch((error) => {
|
|
1142
|
+
process.stderr.write(`[console] chat sql-tools build failed: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
1143
|
+
return [];
|
|
1144
|
+
});
|
|
1145
|
+
const agentTool = await buildAgentCustomTool({
|
|
1146
|
+
parentSessionId: sessionId,
|
|
1147
|
+
orchestrator: this.exploreOrchestrator,
|
|
1148
|
+
resolveModel: () => {
|
|
1149
|
+
const model = this.sessionModels.get(sessionId);
|
|
1150
|
+
const modelRuntime = this.modelRuntimes.get(sessionId);
|
|
1151
|
+
if (!model || !modelRuntime)
|
|
1152
|
+
return undefined;
|
|
1153
|
+
return this.bindings.resolveModel({
|
|
1154
|
+
modelRuntime,
|
|
1155
|
+
provider: model.provider,
|
|
1156
|
+
modelId: model.modelId,
|
|
1157
|
+
});
|
|
1158
|
+
},
|
|
1159
|
+
}).catch((error) => {
|
|
1160
|
+
process.stderr.write(`[console] chat Agent tool build failed: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
1161
|
+
return undefined;
|
|
1162
|
+
});
|
|
1163
|
+
const exposure = this.toolExposures.get(sessionId);
|
|
1164
|
+
const fullCapabilities = operatorCustomTools.find(tool => tool.name === "operatorCapabilities");
|
|
1165
|
+
// Always session-bound: a branch can restore progressive after full fallback.
|
|
1166
|
+
const discovery = exposure?.buildTool(fullCapabilities);
|
|
1529
1167
|
return [
|
|
1530
|
-
...operatorCustomTools,
|
|
1168
|
+
...operatorCustomTools.filter(tool => !discovery || tool.name !== "operatorCapabilities"),
|
|
1169
|
+
...(discovery ? [discovery] : []),
|
|
1170
|
+
...scheduledGoalTools,
|
|
1531
1171
|
...exploreCustomTools,
|
|
1532
1172
|
...(questionTool ? [questionTool] : []),
|
|
1533
1173
|
...(todoTool ? [todoTool] : []),
|
|
1534
1174
|
...goalTools,
|
|
1175
|
+
...terminalTools,
|
|
1176
|
+
...scmTools,
|
|
1177
|
+
...browserTools,
|
|
1178
|
+
...sqlTools,
|
|
1179
|
+
...(agentTool ? [agentTool] : []),
|
|
1535
1180
|
];
|
|
1536
1181
|
}
|
|
1537
|
-
loadOperatorCustomTools() {
|
|
1182
|
+
loadOperatorCustomTools(sessionId, sessionMode) {
|
|
1538
1183
|
if (!this.options.actionContext)
|
|
1539
1184
|
return Promise.resolve([]);
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1185
|
+
const cacheKey = `${sessionId}:${sessionMode}`;
|
|
1186
|
+
const cached = this.operatorCustomToolsBySession.get(cacheKey);
|
|
1187
|
+
if (cached)
|
|
1188
|
+
return cached;
|
|
1189
|
+
const promise = buildCustomOperatorTools({
|
|
1190
|
+
actionContext: this.options.actionContext,
|
|
1191
|
+
sessionId,
|
|
1192
|
+
sessionMode,
|
|
1193
|
+
}).catch((error) => {
|
|
1194
|
+
process.stderr.write(`[console] chat custom-tools build failed: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
1195
|
+
// Allow a later create/reopen to retry after a transient failure.
|
|
1196
|
+
this.operatorCustomToolsBySession.delete(cacheKey);
|
|
1197
|
+
return [];
|
|
1198
|
+
});
|
|
1199
|
+
this.operatorCustomToolsBySession.set(cacheKey, promise);
|
|
1200
|
+
return promise;
|
|
1551
1201
|
}
|
|
1552
1202
|
loadExploreCustomTools() {
|
|
1553
1203
|
if (!this.exploreCustomToolsPromise) {
|
|
@@ -1565,18 +1215,22 @@ export class ConsolePiRuntime {
|
|
|
1565
1215
|
if (!this.bindings.forkSessionManager)
|
|
1566
1216
|
throw new Error("SESSION_FORK_UNSUPPORTED");
|
|
1567
1217
|
const sessionId = `operator-chat-${randomBytes(12).toString("hex")}`;
|
|
1218
|
+
const sessionMode = this.rememberSessionMode(sessionId, init.sessionMode ?? DEFAULT_CONSOLE_CHAT_SESSION_MODE);
|
|
1568
1219
|
const sessionManager = await this.bindings.forkSessionManager({
|
|
1569
1220
|
sourcePath: init.sourceSessionFile,
|
|
1570
1221
|
targetCwd: this.options.cwd,
|
|
1571
1222
|
targetSessionDir: this.options.sessionDir,
|
|
1572
1223
|
targetSessionId: sessionId,
|
|
1573
1224
|
});
|
|
1225
|
+
if (init.throughUserMessageIndex !== undefined) {
|
|
1226
|
+
branchForkedSessionManager(sessionManager, init.throughUserMessageIndex);
|
|
1227
|
+
}
|
|
1574
1228
|
const built = await this.buildSessionWithServices({
|
|
1575
1229
|
sessionId,
|
|
1576
1230
|
sessionManager,
|
|
1577
1231
|
model: init.model,
|
|
1232
|
+
sessionMode,
|
|
1578
1233
|
});
|
|
1579
|
-
built.session.setActiveToolsByName(computeOperatorChatActiveToolNames(built.session));
|
|
1580
1234
|
this.sessions.set(sessionId, built.session);
|
|
1581
1235
|
this.sessionManagers.set(sessionId, sessionManager);
|
|
1582
1236
|
this.modelRuntimes.set(sessionId, built.modelRuntime);
|
|
@@ -1592,6 +1246,7 @@ export class ConsolePiRuntime {
|
|
|
1592
1246
|
createdAt: new Date().toISOString(),
|
|
1593
1247
|
model: init.model,
|
|
1594
1248
|
activeTools: built.session.getActiveToolNames(),
|
|
1249
|
+
sessionMode,
|
|
1595
1250
|
};
|
|
1596
1251
|
}
|
|
1597
1252
|
async branchSession(input) {
|
|
@@ -1608,6 +1263,7 @@ export class ConsolePiRuntime {
|
|
|
1608
1263
|
const entry = input.summary
|
|
1609
1264
|
? manager.branchWithSummary?.(input.branchFromEntryId, input.summary)
|
|
1610
1265
|
: (manager.branch(input.branchFromEntryId), undefined);
|
|
1266
|
+
this.pinSessionTools(input.sessionId, session);
|
|
1611
1267
|
return {
|
|
1612
1268
|
branchedFromEntryId: input.branchFromEntryId,
|
|
1613
1269
|
...(entry?.id ? { branchSummaryEntryId: entry.id } : {}),
|
|
@@ -1619,6 +1275,9 @@ export class ConsolePiRuntime {
|
|
|
1619
1275
|
throw new Error(`chat session not active: ${sessionId}`);
|
|
1620
1276
|
manager.branch(this.mainlineLeaves.get(sessionId));
|
|
1621
1277
|
this.mainlineLeaves.delete(sessionId);
|
|
1278
|
+
const session = this.sessions.get(sessionId);
|
|
1279
|
+
if (session)
|
|
1280
|
+
this.pinSessionTools(sessionId, session);
|
|
1622
1281
|
}
|
|
1623
1282
|
getBranchContext(sessionId) {
|
|
1624
1283
|
const manager = this.sessionManagers.get(sessionId);
|
|
@@ -1629,12 +1288,69 @@ export class ConsolePiRuntime {
|
|
|
1629
1288
|
entries: manager.getBranch?.() ?? [],
|
|
1630
1289
|
};
|
|
1631
1290
|
}
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
1636
|
-
|
|
1637
|
-
|
|
1291
|
+
/**
|
|
1292
|
+
* Workspace-scoped model catalog. A live session's ModelRuntime is reused
|
|
1293
|
+
* when present; otherwise services are created without opening the Pi
|
|
1294
|
+
* conversation JSONL so the picker is not blocked on cold reopen.
|
|
1295
|
+
*/
|
|
1296
|
+
workspaceModelRuntime;
|
|
1297
|
+
workspaceInspection;
|
|
1298
|
+
async getWorkspaceModelRuntime() {
|
|
1299
|
+
if (!this.workspaceModelRuntime) {
|
|
1300
|
+
this.workspaceModelRuntime = (async () => {
|
|
1301
|
+
const agentDir = await safeGetAgentDir(this.bindings);
|
|
1302
|
+
const { services } = await this.bindings.createServices({
|
|
1303
|
+
cwd: this.options.cwd,
|
|
1304
|
+
agentDir,
|
|
1305
|
+
resourceLoaderOptions: { ...CATALOG_RESOURCE_LOADER_OPTIONS },
|
|
1306
|
+
});
|
|
1307
|
+
return services.modelRuntime;
|
|
1308
|
+
})().catch((error) => {
|
|
1309
|
+
this.workspaceModelRuntime = undefined;
|
|
1310
|
+
throw error;
|
|
1311
|
+
});
|
|
1312
|
+
}
|
|
1313
|
+
return this.workspaceModelRuntime;
|
|
1314
|
+
}
|
|
1315
|
+
/**
|
|
1316
|
+
* Full OPEN-surface services for inspect UIs. No SessionManager / JSONL.
|
|
1317
|
+
* Cached without sessionId so todo/goal extensions stay off the shared scope.
|
|
1318
|
+
*/
|
|
1319
|
+
async getWorkspaceInspectionServices() {
|
|
1320
|
+
if (!this.workspaceInspection) {
|
|
1321
|
+
this.workspaceInspection = (async () => {
|
|
1322
|
+
const agentDir = await safeGetAgentDir(this.bindings);
|
|
1323
|
+
const appendSystemPrompt = composeChatSystemPromptParts({
|
|
1324
|
+
sessionMode: DEFAULT_CONSOLE_CHAT_SESSION_MODE,
|
|
1325
|
+
workflowPrompt: OPERATOR_CHAT_SYSTEM_PROMPT_BASE,
|
|
1326
|
+
});
|
|
1327
|
+
const { services } = await this.bindings.createServices({
|
|
1328
|
+
cwd: this.options.cwd,
|
|
1329
|
+
agentDir,
|
|
1330
|
+
resourceLoaderOptions: await this.buildResourceLoaderOptions({
|
|
1331
|
+
appendSystemPrompt,
|
|
1332
|
+
}),
|
|
1333
|
+
});
|
|
1334
|
+
return {
|
|
1335
|
+
modelRuntime: services.modelRuntime,
|
|
1336
|
+
resourceLoader: services
|
|
1337
|
+
.resourceLoader,
|
|
1338
|
+
settingsManager: services.settingsManager,
|
|
1339
|
+
};
|
|
1340
|
+
})().catch((error) => {
|
|
1341
|
+
this.workspaceInspection = undefined;
|
|
1342
|
+
throw error;
|
|
1343
|
+
});
|
|
1344
|
+
}
|
|
1345
|
+
return this.workspaceInspection;
|
|
1346
|
+
}
|
|
1347
|
+
async listModels(sessionId) {
|
|
1348
|
+
const live = this.modelRuntimes.get(sessionId);
|
|
1349
|
+
if (live && this.sessions.has(sessionId)) {
|
|
1350
|
+
return this.bindings.listAvailableModels({ modelRuntime: live });
|
|
1351
|
+
}
|
|
1352
|
+
const modelRuntime = await this.getWorkspaceModelRuntime();
|
|
1353
|
+
return this.bindings.listAvailableModels({ modelRuntime });
|
|
1638
1354
|
}
|
|
1639
1355
|
async applyModel(sessionId, model) {
|
|
1640
1356
|
await this.ensureSessionReady(sessionId);
|
|
@@ -1770,15 +1486,22 @@ export class ConsolePiRuntime {
|
|
|
1770
1486
|
async getRuntimeSystemPrompt(sessionId) {
|
|
1771
1487
|
await this.ensureSessionReady(sessionId).catch(() => undefined);
|
|
1772
1488
|
const session = this.sessions.get(sessionId);
|
|
1773
|
-
if (!session)
|
|
1774
|
-
return
|
|
1489
|
+
if (!session) {
|
|
1490
|
+
return composeChatSystemPrompt({
|
|
1491
|
+
sessionMode: this.sessionModeOf(sessionId),
|
|
1492
|
+
workflowPrompt: OPERATOR_CHAT_SYSTEM_PROMPT_BASE,
|
|
1493
|
+
});
|
|
1494
|
+
}
|
|
1775
1495
|
const fromState = session.state?.systemPrompt;
|
|
1776
1496
|
const fromGetter = session.systemPrompt;
|
|
1777
1497
|
const loader = this.serviceScopes.get(sessionId)?.resourceLoader;
|
|
1778
1498
|
return (fromState ||
|
|
1779
1499
|
fromGetter ||
|
|
1780
1500
|
loader?.getSystemPrompt?.() ||
|
|
1781
|
-
|
|
1501
|
+
composeChatSystemPrompt({
|
|
1502
|
+
sessionMode: this.sessionModeOf(sessionId),
|
|
1503
|
+
workflowPrompt: OPERATOR_CHAT_SYSTEM_PROMPT_BASE,
|
|
1504
|
+
}));
|
|
1782
1505
|
}
|
|
1783
1506
|
/**
|
|
1784
1507
|
* Read the RAW system prompt for the snapshot, converting any projection
|
|
@@ -1869,8 +1592,9 @@ export class ConsolePiRuntime {
|
|
|
1869
1592
|
await session.reload();
|
|
1870
1593
|
const services = this.serviceScopes.get(sessionId);
|
|
1871
1594
|
if (services)
|
|
1872
|
-
this.
|
|
1595
|
+
this.applySessionRecoveryOverrides(sessionId, services, session);
|
|
1873
1596
|
await this.refreshModelConfiguration(sessionId, "force");
|
|
1597
|
+
this.pinSessionTools(sessionId, session);
|
|
1874
1598
|
}
|
|
1875
1599
|
catch (error) {
|
|
1876
1600
|
return {
|
|
@@ -1888,11 +1612,11 @@ export class ConsolePiRuntime {
|
|
|
1888
1612
|
return { ok: true, revision: this.revisions.get(sessionId) ?? 0 };
|
|
1889
1613
|
}
|
|
1890
1614
|
/**
|
|
1891
|
-
* Project the unified
|
|
1892
|
-
*
|
|
1893
|
-
*
|
|
1894
|
-
*
|
|
1895
|
-
*
|
|
1615
|
+
* Project the unified runtime snapshot (design §2.2). A live Pi session is
|
|
1616
|
+
* the source of truth when present. Inspect GETs may pass
|
|
1617
|
+
* `workspaceProjection` to render ResourceLoader inventories without
|
|
1618
|
+
* opening the conversation JSONL. Unknown ids without that hint stay
|
|
1619
|
+
* undefined so callers fail closed.
|
|
1896
1620
|
*/
|
|
1897
1621
|
/**
|
|
1898
1622
|
* ConsolePiRuntime.listSlashCommands
|
|
@@ -1901,105 +1625,37 @@ export class ConsolePiRuntime {
|
|
|
1901
1625
|
* Never returns prompt/skill file bodies.
|
|
1902
1626
|
*/
|
|
1903
1627
|
async listSlashCommands(sessionId) {
|
|
1904
|
-
const scrub = (value) => {
|
|
1905
|
-
const raw = String(value ?? "");
|
|
1906
|
-
return raw
|
|
1907
|
-
.replace(/\/Users\/[^\s]+/gi, "~")
|
|
1908
|
-
.replace(/[A-Za-z]:\\Users\\[^\s]+/gi, "~")
|
|
1909
|
-
.slice(0, 240);
|
|
1910
|
-
};
|
|
1911
1628
|
// Fail soft at the HTTP layer: bubble readiness errors so routes can attach
|
|
1912
1629
|
// a compact warning while the UI keeps local Operator/Pi Web commands.
|
|
1913
1630
|
await this.ensureSessionReady(sessionId);
|
|
1914
1631
|
const session = this.sessions.get(sessionId);
|
|
1915
1632
|
if (!session)
|
|
1916
1633
|
return { commands: [] };
|
|
1917
|
-
|
|
1918
|
-
|
|
1919
|
-
|
|
1920
|
-
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
1925
|
-
const sourceWarnings = [];
|
|
1926
|
-
const push = (command, label, description, source) => {
|
|
1927
|
-
const name = command.startsWith("/") ? command : `/${command}`;
|
|
1928
|
-
const key = name.toLowerCase();
|
|
1929
|
-
if (!key || key === "/")
|
|
1930
|
-
return;
|
|
1931
|
-
const next = {
|
|
1932
|
-
command: name,
|
|
1933
|
-
label: (label || name).slice(0, 80),
|
|
1934
|
-
description: scrub(description),
|
|
1935
|
-
source,
|
|
1936
|
-
};
|
|
1937
|
-
const existing = byKey.get(key);
|
|
1938
|
-
if (!existing || SOURCE_RANK[source] < SOURCE_RANK[existing.source]) {
|
|
1939
|
-
byKey.set(key, next);
|
|
1940
|
-
}
|
|
1941
|
-
};
|
|
1942
|
-
try {
|
|
1943
|
-
const cmds = session.extensionRunner?.getRegisteredCommands?.() ?? [];
|
|
1944
|
-
for (const cmd of cmds) {
|
|
1945
|
-
const name = cmd.invocationName || cmd.name;
|
|
1946
|
-
if (!name)
|
|
1947
|
-
continue;
|
|
1948
|
-
push(String(name), String(cmd.name || name), String(cmd.description || ""), "extension");
|
|
1634
|
+
const resourceLoader = this.serviceScopes.get(sessionId)?.resourceLoader;
|
|
1635
|
+
return collectSlashCommands({ session, resourceLoader });
|
|
1636
|
+
}
|
|
1637
|
+
async getRuntimeSnapshot(sessionId, options) {
|
|
1638
|
+
const initializing = this.sessionInit.get(sessionId)?.status === "initializing";
|
|
1639
|
+
if (this.sessions.has(sessionId) || initializing) {
|
|
1640
|
+
try {
|
|
1641
|
+
await this.ensureSessionReady(sessionId);
|
|
1949
1642
|
}
|
|
1950
|
-
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
for (const tpl of session.promptTemplates ?? []) {
|
|
1958
|
-
if (!tpl?.name)
|
|
1959
|
-
continue;
|
|
1960
|
-
push(String(tpl.name), String(tpl.name), String(tpl.description || ""), "prompt");
|
|
1643
|
+
catch (error) {
|
|
1644
|
+
if (error instanceof PiSessionInitFailedError)
|
|
1645
|
+
throw error;
|
|
1646
|
+
if (options?.workspaceProjection) {
|
|
1647
|
+
return this.projectWorkspaceRuntimeSnapshot(sessionId, options);
|
|
1648
|
+
}
|
|
1649
|
+
return undefined;
|
|
1961
1650
|
}
|
|
1962
1651
|
}
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
const services = this.serviceScopes.get(sessionId);
|
|
1968
|
-
const resourceLoader = services?.resourceLoader;
|
|
1969
|
-
const skills = resourceLoader?.getSkills?.()?.skills ?? [];
|
|
1970
|
-
for (const skill of skills) {
|
|
1971
|
-
if (!skill?.name)
|
|
1972
|
-
continue;
|
|
1973
|
-
const command = skill.name.startsWith("skill:")
|
|
1974
|
-
? `/${skill.name}`
|
|
1975
|
-
: `/skill:${skill.name}`;
|
|
1976
|
-
push(command, skill.name, String(skill.description || ""), "skill");
|
|
1652
|
+
const session = this.sessions.get(sessionId);
|
|
1653
|
+
if (!session) {
|
|
1654
|
+
if (options?.workspaceProjection) {
|
|
1655
|
+
return this.projectWorkspaceRuntimeSnapshot(sessionId, options);
|
|
1977
1656
|
}
|
|
1978
|
-
}
|
|
1979
|
-
catch (error) {
|
|
1980
|
-
sourceWarnings.push(`skill: ${scrub(error instanceof Error ? error.message : String(error))}`);
|
|
1981
|
-
}
|
|
1982
|
-
const warning = sourceWarnings.length > 0
|
|
1983
|
-
? sourceWarnings.join("; ").slice(0, 160)
|
|
1984
|
-
: undefined;
|
|
1985
|
-
return {
|
|
1986
|
-
commands: [...byKey.values()],
|
|
1987
|
-
...(warning ? { warning } : {}),
|
|
1988
|
-
};
|
|
1989
|
-
}
|
|
1990
|
-
async getRuntimeSnapshot(sessionId, options) {
|
|
1991
|
-
try {
|
|
1992
|
-
await this.ensureSessionReady(sessionId);
|
|
1993
|
-
}
|
|
1994
|
-
catch (error) {
|
|
1995
|
-
if (error instanceof PiSessionInitFailedError)
|
|
1996
|
-
throw error;
|
|
1997
|
-
// Inactive / unknown session: fail closed with undefined (no fabricated snapshot).
|
|
1998
1657
|
return undefined;
|
|
1999
1658
|
}
|
|
2000
|
-
const session = this.sessions.get(sessionId);
|
|
2001
|
-
if (!session)
|
|
2002
|
-
return undefined;
|
|
2003
1659
|
const services = this.serviceScopes.get(sessionId);
|
|
2004
1660
|
const modelRuntime = this.modelRuntimes.get(sessionId);
|
|
2005
1661
|
const resourceLoader = services?.resourceLoader;
|
|
@@ -2029,9 +1685,6 @@ export class ConsolePiRuntime {
|
|
|
2029
1685
|
throw new RuntimeSnapshotUnavailableError(`model enumeration failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
2030
1686
|
}
|
|
2031
1687
|
}
|
|
2032
|
-
// Thinking options: auto is always offered; explicit levels only when the
|
|
2033
|
-
// runtime session supports setThinkingLevel (xhigh/max ship with the SDK
|
|
2034
|
-
// and therefore surface only when this runtime provides them).
|
|
2035
1688
|
const supportedLevels = typeof session.setThinkingLevel === "function"
|
|
2036
1689
|
? [...THINKING_LEVELS]
|
|
2037
1690
|
: [];
|
|
@@ -2039,220 +1692,25 @@ export class ConsolePiRuntime {
|
|
|
2039
1692
|
{ value: "auto" },
|
|
2040
1693
|
...supportedLevels.map((value) => ({ value })),
|
|
2041
1694
|
];
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
// Each subface is isolated (RF-02): a throwing subface keeps the other
|
|
2045
|
-
// inventories AND surfaces a structured retryable diagnostic instead of
|
|
2046
|
-
// silently dropping the whole resource projection.
|
|
2047
|
-
const contextFiles = [];
|
|
2048
|
-
const skills = [];
|
|
2049
|
-
const extensions = [];
|
|
2050
|
-
const diagnostics = [];
|
|
2051
|
-
const resolvedResources = [];
|
|
2052
|
-
const resourceFailure = (subface, error) => {
|
|
2053
|
-
diagnostics.push({
|
|
2054
|
-
type: "error",
|
|
2055
|
-
code: "RESOURCE_LOAD_FAILED",
|
|
2056
|
-
message: `${subface} inventory failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
2057
|
-
retryable: true,
|
|
2058
|
-
});
|
|
2059
|
-
};
|
|
1695
|
+
let skillPrefs = { schemaVersion: 1, skills: {} };
|
|
1696
|
+
let skillPrefsError;
|
|
2060
1697
|
if (resourceLoader) {
|
|
2061
|
-
try {
|
|
2062
|
-
const agentsFiles = resourceLoader.getAgentsFiles?.();
|
|
2063
|
-
for (const file of agentsFiles?.agentsFiles ?? []) {
|
|
2064
|
-
if (!file.path)
|
|
2065
|
-
continue;
|
|
2066
|
-
contextFiles.push({
|
|
2067
|
-
path: file.path,
|
|
2068
|
-
characters: file.content?.length ?? 0,
|
|
2069
|
-
});
|
|
2070
|
-
}
|
|
2071
|
-
}
|
|
2072
|
-
catch (error) {
|
|
2073
|
-
resourceFailure("context files", error);
|
|
2074
|
-
}
|
|
2075
|
-
// Preferences are the source of truth for UI auto-invocation state;
|
|
2076
|
-
// loader disableModelInvocation may also reflect frontmatter. Prefer
|
|
2077
|
-
// explicit preference (default on) when projecting autoInvocationEnabled.
|
|
2078
|
-
let skillPrefs = { schemaVersion: 1, skills: {} };
|
|
2079
1698
|
try {
|
|
2080
1699
|
skillPrefs = await this.loadSkillAutoInvocationPreferences();
|
|
2081
1700
|
}
|
|
2082
1701
|
catch (error) {
|
|
2083
|
-
|
|
2084
|
-
type: "error",
|
|
2085
|
-
code: "PI_RESOURCE_PREFERENCES_MALFORMED",
|
|
2086
|
-
message: error instanceof Error ? error.message : String(error),
|
|
2087
|
-
retryable: true,
|
|
2088
|
-
});
|
|
2089
|
-
}
|
|
2090
|
-
try {
|
|
2091
|
-
const skillsResult = resourceLoader.getSkills?.();
|
|
2092
|
-
for (const skill of skillsResult?.skills ?? []) {
|
|
2093
|
-
const resourceId = skillResourceId({
|
|
2094
|
-
name: skill.name,
|
|
2095
|
-
filePath: skill.filePath,
|
|
2096
|
-
});
|
|
2097
|
-
// Preference off always means autoInvocationEnabled=false even if
|
|
2098
|
-
// loader already applied disableModelInvocation. Frontmatter-only
|
|
2099
|
-
// disable (no preference) also surfaces as autoInvocationEnabled=false.
|
|
2100
|
-
const prefEnabled = isAutoInvocationEnabled(skillPrefs, resourceId);
|
|
2101
|
-
const autoInvocationEnabled = prefEnabled && skill.disableModelInvocation !== true;
|
|
2102
|
-
skills.push({
|
|
2103
|
-
name: skill.name,
|
|
2104
|
-
description: skill.description ?? "",
|
|
2105
|
-
path: skill.filePath,
|
|
2106
|
-
...(skill.baseDir ? { baseDir: skill.baseDir } : {}),
|
|
2107
|
-
scope: skill.sourceInfo?.scope ?? "unknown",
|
|
2108
|
-
source: skill.sourceInfo?.source ?? "",
|
|
2109
|
-
resourceId,
|
|
2110
|
-
autoInvocationEnabled,
|
|
2111
|
-
diagnostics: [],
|
|
2112
|
-
});
|
|
2113
|
-
resolvedResources.push({
|
|
2114
|
-
type: "skill",
|
|
2115
|
-
name: skill.name,
|
|
2116
|
-
path: skill.filePath,
|
|
2117
|
-
source: skill.sourceInfo?.source ?? "",
|
|
2118
|
-
scope: skill.sourceInfo?.scope ?? "unknown",
|
|
2119
|
-
});
|
|
2120
|
-
}
|
|
2121
|
-
for (const diag of skillsResult?.diagnostics ?? []) {
|
|
2122
|
-
if (!diag?.message)
|
|
2123
|
-
continue;
|
|
2124
|
-
diagnostics.push({
|
|
2125
|
-
type: diag.type ?? "warning",
|
|
2126
|
-
message: diag.message,
|
|
2127
|
-
...(diag.path ? { path: diag.path } : {}),
|
|
2128
|
-
});
|
|
2129
|
-
}
|
|
2130
|
-
}
|
|
2131
|
-
catch (error) {
|
|
2132
|
-
resourceFailure("skills", error);
|
|
2133
|
-
}
|
|
2134
|
-
try {
|
|
2135
|
-
const extResult = resourceLoader.getExtensions?.();
|
|
2136
|
-
for (const ext of extResult?.extensions ?? []) {
|
|
2137
|
-
const path = ext.resolvedPath ?? ext.path ?? "";
|
|
2138
|
-
extensions.push({
|
|
2139
|
-
name: ext.sourceInfo?.source ?? ext.path ?? "extension",
|
|
2140
|
-
path,
|
|
2141
|
-
...(ext.resolvedPath ? { resolvedPath: ext.resolvedPath } : {}),
|
|
2142
|
-
source: ext.sourceInfo?.source ?? "",
|
|
2143
|
-
scope: ext.sourceInfo?.scope ?? "unknown",
|
|
2144
|
-
...(ext.sourceInfo?.origin ? { origin: ext.sourceInfo.origin } : {}),
|
|
2145
|
-
enabled: true,
|
|
2146
|
-
});
|
|
2147
|
-
resolvedResources.push({
|
|
2148
|
-
type: "extension",
|
|
2149
|
-
name: ext.sourceInfo?.source ?? ext.path ?? "extension",
|
|
2150
|
-
path,
|
|
2151
|
-
source: ext.sourceInfo?.source ?? "",
|
|
2152
|
-
scope: ext.sourceInfo?.scope ?? "unknown",
|
|
2153
|
-
});
|
|
2154
|
-
}
|
|
2155
|
-
for (const err of extResult?.errors ?? []) {
|
|
2156
|
-
if (!err?.error)
|
|
2157
|
-
continue;
|
|
2158
|
-
diagnostics.push({
|
|
2159
|
-
type: "error",
|
|
2160
|
-
message: err.error,
|
|
2161
|
-
...(err.path ? { path: err.path } : {}),
|
|
2162
|
-
});
|
|
2163
|
-
}
|
|
2164
|
-
}
|
|
2165
|
-
catch (error) {
|
|
2166
|
-
resourceFailure("extensions", error);
|
|
1702
|
+
skillPrefsError = error;
|
|
2167
1703
|
}
|
|
2168
|
-
try {
|
|
2169
|
-
const promptsResult = resourceLoader.getPrompts?.();
|
|
2170
|
-
for (const prompt of promptsResult?.prompts ?? []) {
|
|
2171
|
-
resolvedResources.push({
|
|
2172
|
-
type: "prompt",
|
|
2173
|
-
name: prompt.name,
|
|
2174
|
-
path: prompt.filePath,
|
|
2175
|
-
source: prompt.sourceInfo?.source ?? "",
|
|
2176
|
-
scope: prompt.sourceInfo?.scope ?? "unknown",
|
|
2177
|
-
});
|
|
2178
|
-
}
|
|
2179
|
-
for (const diag of promptsResult?.diagnostics ?? []) {
|
|
2180
|
-
if (!diag?.message)
|
|
2181
|
-
continue;
|
|
2182
|
-
diagnostics.push({
|
|
2183
|
-
type: diag.type ?? "warning",
|
|
2184
|
-
message: diag.message,
|
|
2185
|
-
...(diag.path ? { path: diag.path } : {}),
|
|
2186
|
-
});
|
|
2187
|
-
}
|
|
2188
|
-
}
|
|
2189
|
-
catch (error) {
|
|
2190
|
-
resourceFailure("prompts", error);
|
|
2191
|
-
}
|
|
2192
|
-
try {
|
|
2193
|
-
const themesResult = resourceLoader.getThemes?.();
|
|
2194
|
-
for (const theme of themesResult?.themes ?? []) {
|
|
2195
|
-
if (!theme.path)
|
|
2196
|
-
continue;
|
|
2197
|
-
resolvedResources.push({
|
|
2198
|
-
type: "theme",
|
|
2199
|
-
name: theme.name ?? theme.path,
|
|
2200
|
-
path: theme.path,
|
|
2201
|
-
source: "",
|
|
2202
|
-
scope: "unknown",
|
|
2203
|
-
});
|
|
2204
|
-
}
|
|
2205
|
-
for (const diag of themesResult?.diagnostics ?? []) {
|
|
2206
|
-
if (!diag?.message)
|
|
2207
|
-
continue;
|
|
2208
|
-
diagnostics.push({
|
|
2209
|
-
type: diag.type ?? "warning",
|
|
2210
|
-
message: diag.message,
|
|
2211
|
-
...(diag.path ? { path: diag.path } : {}),
|
|
2212
|
-
});
|
|
2213
|
-
}
|
|
2214
|
-
}
|
|
2215
|
-
catch (error) {
|
|
2216
|
-
resourceFailure("themes", error);
|
|
2217
|
-
}
|
|
2218
|
-
}
|
|
2219
|
-
// Packages: Pi settings specs + resolved resource metadata. Fields the SDK
|
|
2220
|
-
// does not expose stay absent (real missing, never fabricated). A
|
|
2221
|
-
// readPackageInventory failure is a PARTIAL failure (RF-02): the snapshot
|
|
2222
|
-
// stays 200 with a structured retryable diagnostic — never a silent
|
|
2223
|
-
// fake-empty package list.
|
|
2224
|
-
const { readPackageInventory } = await import("./pi-console-config.js");
|
|
2225
|
-
let packages = [];
|
|
2226
|
-
try {
|
|
2227
|
-
packages = (await readPackageInventory(await safeGetAgentDir(this.bindings), this.options.cwd, resolvedResources));
|
|
2228
|
-
}
|
|
2229
|
-
catch (error) {
|
|
2230
|
-
packages = [];
|
|
2231
|
-
diagnostics.push({
|
|
2232
|
-
type: "error",
|
|
2233
|
-
code: "PACKAGE_INVENTORY_FAILED",
|
|
2234
|
-
message: error instanceof Error ? error.message : String(error),
|
|
2235
|
-
retryable: true,
|
|
2236
|
-
});
|
|
2237
|
-
}
|
|
2238
|
-
const { readMcpInventory } = await import("./mcp-inventory.js");
|
|
2239
|
-
let mcp = { servers: [], unassignedTools: [] };
|
|
2240
|
-
try {
|
|
2241
|
-
mcp = await readMcpInventory({
|
|
2242
|
-
agentDir: await safeGetAgentDir(this.bindings),
|
|
2243
|
-
cwd: this.options.cwd,
|
|
2244
|
-
tools: session.getAllTools?.() ?? [],
|
|
2245
|
-
activeToolNames: session.getActiveToolNames(),
|
|
2246
|
-
});
|
|
2247
|
-
}
|
|
2248
|
-
catch (error) {
|
|
2249
|
-
diagnostics.push({
|
|
2250
|
-
type: "error",
|
|
2251
|
-
code: "MCP_INVENTORY_FAILED",
|
|
2252
|
-
message: error instanceof Error ? error.message : String(error),
|
|
2253
|
-
retryable: true,
|
|
2254
|
-
});
|
|
2255
1704
|
}
|
|
1705
|
+
const inventories = await collectRuntimeInventories({
|
|
1706
|
+
resourceLoader,
|
|
1707
|
+
skillPrefs,
|
|
1708
|
+
skillPrefsError,
|
|
1709
|
+
agentDir: await safeGetAgentDir(this.bindings),
|
|
1710
|
+
cwd: this.options.cwd,
|
|
1711
|
+
tools: session.getAllTools?.() ?? [],
|
|
1712
|
+
activeToolNames: session.getActiveToolNames(),
|
|
1713
|
+
});
|
|
2256
1714
|
return projectRuntimeSnapshot({
|
|
2257
1715
|
sessionId,
|
|
2258
1716
|
revision: this.revisions.get(sessionId) ?? 0,
|
|
@@ -2277,19 +1735,134 @@ export class ConsolePiRuntime {
|
|
|
2277
1735
|
thinkingLevels,
|
|
2278
1736
|
systemPrompt: {
|
|
2279
1737
|
...(options?.includeRaw ? { raw: rawSystemPrompt } : {}),
|
|
2280
|
-
// The RAW prompt flows into the projection: text is scrubbed +
|
|
2281
|
-
// length-limited while sha256/characters stay RAW-based (design §2.2).
|
|
2282
1738
|
text: rawSystemPrompt,
|
|
2283
1739
|
sha256: createHash("sha256").update(rawSystemPrompt).digest("hex"),
|
|
2284
1740
|
characters: rawSystemPrompt.length,
|
|
2285
1741
|
},
|
|
2286
1742
|
activeTools: session.getActiveToolNames(),
|
|
2287
|
-
contextFiles,
|
|
2288
|
-
skills,
|
|
2289
|
-
extensions,
|
|
2290
|
-
packages,
|
|
2291
|
-
mcp,
|
|
2292
|
-
diagnostics
|
|
1743
|
+
contextFiles: inventories.contextFiles,
|
|
1744
|
+
skills: inventories.skills,
|
|
1745
|
+
extensions: inventories.extensions,
|
|
1746
|
+
packages: inventories.packages,
|
|
1747
|
+
mcp: inventories.mcp,
|
|
1748
|
+
diagnostics: [
|
|
1749
|
+
...inventories.diagnostics,
|
|
1750
|
+
...(this.toolExposures.has(sessionId) ? [{
|
|
1751
|
+
type: "info",
|
|
1752
|
+
code: "WORKFLOW_TOOL_EXPOSURE",
|
|
1753
|
+
message: JSON.stringify(this.toolExposures.get(sessionId).snapshot),
|
|
1754
|
+
}] : []),
|
|
1755
|
+
],
|
|
1756
|
+
hasBash: true,
|
|
1757
|
+
});
|
|
1758
|
+
}
|
|
1759
|
+
resolveWorkspaceThinkingSelection(sessionId, stored) {
|
|
1760
|
+
const live = this.thinkingSelections.get(sessionId);
|
|
1761
|
+
if (live)
|
|
1762
|
+
return live;
|
|
1763
|
+
if (!stored || stored === "auto")
|
|
1764
|
+
return "auto";
|
|
1765
|
+
if (THINKING_LEVELS.includes(stored)) {
|
|
1766
|
+
return stored;
|
|
1767
|
+
}
|
|
1768
|
+
return "auto";
|
|
1769
|
+
}
|
|
1770
|
+
/**
|
|
1771
|
+
* Inspect projection without SessionManager.open. Used only when the Agent
|
|
1772
|
+
* is not live and the caller confirmed a durable session record.
|
|
1773
|
+
*/
|
|
1774
|
+
async projectWorkspaceRuntimeSnapshot(sessionId, options) {
|
|
1775
|
+
const hint = options.workspaceProjection ?? {};
|
|
1776
|
+
const sessionMode = hint.sessionMode ?? this.sessionModeOf(sessionId);
|
|
1777
|
+
let inspection;
|
|
1778
|
+
try {
|
|
1779
|
+
inspection = await this.getWorkspaceInspectionServices();
|
|
1780
|
+
}
|
|
1781
|
+
catch (error) {
|
|
1782
|
+
throw new RuntimeSnapshotUnavailableError(`workspace runtime projection failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1783
|
+
}
|
|
1784
|
+
const resourceLoader = inspection.resourceLoader;
|
|
1785
|
+
const settingsManager = inspection.settingsManager;
|
|
1786
|
+
const thinkingSelection = this.resolveWorkspaceThinkingSelection(sessionId, hint.thinkingLevel);
|
|
1787
|
+
const effectiveThinkingLevel = settingsManager?.getDefaultThinkingLevel?.() ??
|
|
1788
|
+
(thinkingSelection === "auto" ? undefined : thinkingSelection);
|
|
1789
|
+
const rawSystemPrompt = resourceLoader?.getSystemPrompt?.() ||
|
|
1790
|
+
composeChatSystemPrompt({
|
|
1791
|
+
sessionMode,
|
|
1792
|
+
workflowPrompt: OPERATOR_CHAT_SYSTEM_PROMPT_BASE,
|
|
1793
|
+
});
|
|
1794
|
+
if (!rawSystemPrompt) {
|
|
1795
|
+
throw new RuntimeSnapshotUnavailableError("system prompt projection failed: workspace prompt was empty");
|
|
1796
|
+
}
|
|
1797
|
+
let models = [];
|
|
1798
|
+
try {
|
|
1799
|
+
models = this.bindings
|
|
1800
|
+
.listAvailableModels({ modelRuntime: inspection.modelRuntime })
|
|
1801
|
+
.map((entry) => ({
|
|
1802
|
+
provider: entry.provider,
|
|
1803
|
+
id: entry.id,
|
|
1804
|
+
...(entry.name ? { name: entry.name } : {}),
|
|
1805
|
+
hasCredentials: entry.hasCredentials,
|
|
1806
|
+
}));
|
|
1807
|
+
}
|
|
1808
|
+
catch (error) {
|
|
1809
|
+
throw new RuntimeSnapshotUnavailableError(`model enumeration failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1810
|
+
}
|
|
1811
|
+
const thinkingLevels = [
|
|
1812
|
+
{ value: "auto" },
|
|
1813
|
+
...THINKING_LEVELS.map((value) => ({ value })),
|
|
1814
|
+
];
|
|
1815
|
+
let skillPrefs = { schemaVersion: 1, skills: {} };
|
|
1816
|
+
let skillPrefsError;
|
|
1817
|
+
if (resourceLoader) {
|
|
1818
|
+
try {
|
|
1819
|
+
skillPrefs = await this.loadSkillAutoInvocationPreferences();
|
|
1820
|
+
}
|
|
1821
|
+
catch (error) {
|
|
1822
|
+
skillPrefsError = error;
|
|
1823
|
+
}
|
|
1824
|
+
}
|
|
1825
|
+
const activeTools = chatActiveToolBaseline(sessionMode);
|
|
1826
|
+
const inventories = await collectRuntimeInventories({
|
|
1827
|
+
resourceLoader,
|
|
1828
|
+
skillPrefs,
|
|
1829
|
+
skillPrefsError,
|
|
1830
|
+
agentDir: await safeGetAgentDir(this.bindings),
|
|
1831
|
+
cwd: this.options.cwd,
|
|
1832
|
+
tools: [],
|
|
1833
|
+
activeToolNames: activeTools,
|
|
1834
|
+
});
|
|
1835
|
+
const storedModel = this.sessionModels.get(sessionId);
|
|
1836
|
+
const provider = storedModel?.provider ?? hint.modelProvider;
|
|
1837
|
+
const modelId = storedModel?.modelId ?? hint.modelId;
|
|
1838
|
+
return projectRuntimeSnapshot({
|
|
1839
|
+
sessionId,
|
|
1840
|
+
revision: this.revisions.get(sessionId) ?? 0,
|
|
1841
|
+
loadedAt: new Date().toISOString(),
|
|
1842
|
+
selection: {
|
|
1843
|
+
...(provider && modelId
|
|
1844
|
+
? { model: { provider, id: modelId } }
|
|
1845
|
+
: {}),
|
|
1846
|
+
thinkingSelection,
|
|
1847
|
+
...(effectiveThinkingLevel
|
|
1848
|
+
? { effectiveThinkingLevel: effectiveThinkingLevel }
|
|
1849
|
+
: {}),
|
|
1850
|
+
},
|
|
1851
|
+
models,
|
|
1852
|
+
thinkingLevels,
|
|
1853
|
+
systemPrompt: {
|
|
1854
|
+
...(options.includeRaw ? { raw: rawSystemPrompt } : {}),
|
|
1855
|
+
text: rawSystemPrompt,
|
|
1856
|
+
sha256: createHash("sha256").update(rawSystemPrompt).digest("hex"),
|
|
1857
|
+
characters: rawSystemPrompt.length,
|
|
1858
|
+
},
|
|
1859
|
+
activeTools,
|
|
1860
|
+
contextFiles: inventories.contextFiles,
|
|
1861
|
+
skills: inventories.skills,
|
|
1862
|
+
extensions: inventories.extensions,
|
|
1863
|
+
packages: inventories.packages,
|
|
1864
|
+
mcp: inventories.mcp,
|
|
1865
|
+
diagnostics: inventories.diagnostics,
|
|
2293
1866
|
hasBash: true,
|
|
2294
1867
|
});
|
|
2295
1868
|
}
|
|
@@ -2308,6 +1881,21 @@ export class ConsolePiRuntime {
|
|
|
2308
1881
|
*/
|
|
2309
1882
|
async reopenSession(init) {
|
|
2310
1883
|
const sessionId = init.sessionId;
|
|
1884
|
+
const existing = this.reopenInFlight.get(sessionId);
|
|
1885
|
+
if (existing)
|
|
1886
|
+
return existing;
|
|
1887
|
+
const pending = this.reopenSessionExclusive(init).finally(() => {
|
|
1888
|
+
if (this.reopenInFlight.get(sessionId) === pending) {
|
|
1889
|
+
this.reopenInFlight.delete(sessionId);
|
|
1890
|
+
}
|
|
1891
|
+
});
|
|
1892
|
+
this.reopenInFlight.set(sessionId, pending);
|
|
1893
|
+
return pending;
|
|
1894
|
+
}
|
|
1895
|
+
async reopenSessionExclusive(init) {
|
|
1896
|
+
await this.syncAimaxAuthToken();
|
|
1897
|
+
const sessionId = init.sessionId;
|
|
1898
|
+
const sessionMode = this.rememberSessionMode(sessionId, init.sessionMode ?? this.sessionModeOf(sessionId));
|
|
2311
1899
|
// Wait for in-flight create materialization rather than racing reopen.
|
|
2312
1900
|
const initState = this.sessionInit.get(sessionId);
|
|
2313
1901
|
if (initState?.status === "initializing") {
|
|
@@ -2384,6 +1972,7 @@ export class ConsolePiRuntime {
|
|
|
2384
1972
|
sessionManager,
|
|
2385
1973
|
model: init.model,
|
|
2386
1974
|
systemPromptSuffix: init.systemPromptSuffix,
|
|
1975
|
+
sessionMode,
|
|
2387
1976
|
});
|
|
2388
1977
|
const session = built.session;
|
|
2389
1978
|
// Prefer the SessionManager id (from the JSONL header). Some SDK
|
|
@@ -2406,7 +1995,6 @@ export class ConsolePiRuntime {
|
|
|
2406
1995
|
message: `reopened Pi sessionId mismatch: expected ${sessionId}, got ${reportedId}`,
|
|
2407
1996
|
};
|
|
2408
1997
|
}
|
|
2409
|
-
session.setActiveToolsByName(computeOperatorChatActiveToolNames(session));
|
|
2410
1998
|
this.sessions.set(sessionId, session);
|
|
2411
1999
|
this.sessionManagers.set(sessionId, sessionManager);
|
|
2412
2000
|
this.modelRuntimes.set(sessionId, built.modelRuntime);
|
|
@@ -2424,6 +2012,7 @@ export class ConsolePiRuntime {
|
|
|
2424
2012
|
createdAt: new Date().toISOString(),
|
|
2425
2013
|
model: init.model,
|
|
2426
2014
|
activeTools: session.getActiveToolNames(),
|
|
2015
|
+
sessionMode,
|
|
2427
2016
|
},
|
|
2428
2017
|
};
|
|
2429
2018
|
}
|
|
@@ -2455,6 +2044,7 @@ export class ConsolePiRuntime {
|
|
|
2455
2044
|
createdAt: new Date().toISOString(),
|
|
2456
2045
|
model,
|
|
2457
2046
|
activeTools: session.getActiveToolNames(),
|
|
2047
|
+
sessionMode: this.sessionModeOf(sessionId),
|
|
2458
2048
|
};
|
|
2459
2049
|
}
|
|
2460
2050
|
/**
|
|
@@ -2463,46 +2053,22 @@ export class ConsolePiRuntime {
|
|
|
2463
2053
|
* before AgentSession is ready. Tool definitions reuse runtime-level caches.
|
|
2464
2054
|
*/
|
|
2465
2055
|
async buildSessionWithServices(init) {
|
|
2466
|
-
const
|
|
2467
|
-
const
|
|
2468
|
-
|
|
2469
|
-
OPERATOR_CHAT_SYSTEM_PROMPT_BASE,
|
|
2470
|
-
...(init.systemPromptSuffix ? [init.systemPromptSuffix] : []),
|
|
2471
|
-
];
|
|
2472
|
-
await this.refreshSkillPrefsCache().catch(() => undefined);
|
|
2473
|
-
const { services } = await this.bindings.createServices({
|
|
2474
|
-
cwd: this.options.cwd,
|
|
2475
|
-
agentDir,
|
|
2476
|
-
resourceLoaderOptions: await this.buildResourceLoaderOptions({ appendSystemPrompt }, init.sessionId),
|
|
2477
|
-
});
|
|
2478
|
-
const modelRuntime = services.modelRuntime;
|
|
2479
|
-
const resolvedModel = init.model
|
|
2480
|
-
? (this.bindings.resolveModel({
|
|
2481
|
-
modelRuntime,
|
|
2482
|
-
provider: init.model.provider,
|
|
2483
|
-
modelId: init.model.modelId,
|
|
2484
|
-
}) ?? undefined)
|
|
2485
|
-
: undefined;
|
|
2486
|
-
assertNoWriteToolInList(OPERATOR_CHAT_ALLOWED_TOOLS);
|
|
2487
|
-
const customTools = await this.loadCustomTools(init.sessionId);
|
|
2488
|
-
const { session } = await this.bindings.createSessionFromServices({
|
|
2489
|
-
services,
|
|
2056
|
+
const sessionMode = this.rememberSessionMode(init.sessionId, init.sessionMode ?? this.sessionModeOf(init.sessionId));
|
|
2057
|
+
const prepared = await this.prepareLiveSession({
|
|
2058
|
+
sessionId: init.sessionId,
|
|
2490
2059
|
sessionManager: init.sessionManager,
|
|
2491
|
-
|
|
2492
|
-
|
|
2493
|
-
|
|
2060
|
+
model: init.model,
|
|
2061
|
+
systemPromptSuffix: init.systemPromptSuffix,
|
|
2062
|
+
sessionMode,
|
|
2494
2063
|
});
|
|
2495
|
-
|
|
2496
|
-
|
|
2497
|
-
|
|
2064
|
+
if (!prepared) {
|
|
2065
|
+
throw new Error(`chat session preparation aborted: ${init.sessionId}`);
|
|
2066
|
+
}
|
|
2498
2067
|
return {
|
|
2499
|
-
session,
|
|
2500
|
-
modelRuntime,
|
|
2501
|
-
modelConfigFile,
|
|
2502
|
-
services:
|
|
2503
|
-
resourceLoader: services.resourceLoader,
|
|
2504
|
-
settingsManager: services.settingsManager,
|
|
2505
|
-
},
|
|
2068
|
+
session: prepared.session,
|
|
2069
|
+
modelRuntime: prepared.modelRuntime,
|
|
2070
|
+
modelConfigFile: prepared.modelConfigFile,
|
|
2071
|
+
services: prepared.services,
|
|
2506
2072
|
};
|
|
2507
2073
|
}
|
|
2508
2074
|
/** Re-open a previously created session (cross-request). */
|
|
@@ -2562,7 +2128,7 @@ export class ConsolePiRuntime {
|
|
|
2562
2128
|
}
|
|
2563
2129
|
/**
|
|
2564
2130
|
* Send a prompt and stream events. Gate 3: each tool invocation is
|
|
2565
|
-
* re-authorized by
|
|
2131
|
+
* re-authorized by authorizeChatSessionTool(mode) before the dispatcher runs it
|
|
2566
2132
|
* (the dispatcher is wired by the HTTP layer, see chat-session.ts).
|
|
2567
2133
|
*
|
|
2568
2134
|
* Prompt ownership is acquired synchronously before the first await so two
|
|
@@ -2595,6 +2161,7 @@ export class ConsolePiRuntime {
|
|
|
2595
2161
|
catch {
|
|
2596
2162
|
// ignore
|
|
2597
2163
|
}
|
|
2164
|
+
void this.exploreOrchestrator.abortByParent(sessionId);
|
|
2598
2165
|
};
|
|
2599
2166
|
try {
|
|
2600
2167
|
if (options?.turnId && this.options.questionRegistry) {
|
|
@@ -2624,11 +2191,11 @@ export class ConsolePiRuntime {
|
|
|
2624
2191
|
// existing closed interview allow/deny registry. The next ordinary turn
|
|
2625
2192
|
// explicitly restores the normal Operator Chat set (baseline + extension
|
|
2626
2193
|
// tools, ADR 0012).
|
|
2627
|
-
const
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
|
|
2631
|
-
|
|
2194
|
+
const sessionMode = this.sessionModeOf(sessionId);
|
|
2195
|
+
this.pinSessionTools(sessionId, session, options?.mode === "requirement-interview" && sessionMode === "workflow");
|
|
2196
|
+
if (sessionMode === "workflow" && isScheduledBookingTurn(text)) {
|
|
2197
|
+
pinScheduledBookingTurnTools(session);
|
|
2198
|
+
}
|
|
2632
2199
|
// Final pre-prompt fence: abort after tool pin must still skip session.prompt.
|
|
2633
2200
|
if (options?.signal?.aborted) {
|
|
2634
2201
|
return;
|
|
@@ -2665,6 +2232,14 @@ export class ConsolePiRuntime {
|
|
|
2665
2232
|
};
|
|
2666
2233
|
emitContextUsage();
|
|
2667
2234
|
await this.runPrePromptCompaction(sessionId, session, text, options?.images?.length ?? 0, onEvent);
|
|
2235
|
+
onEvent(buildRequestContextEvent({
|
|
2236
|
+
sessionId,
|
|
2237
|
+
turnId: options?.turnId ?? `${sessionId}:active`,
|
|
2238
|
+
session,
|
|
2239
|
+
text,
|
|
2240
|
+
imageCount: options?.images?.length ?? 0,
|
|
2241
|
+
}));
|
|
2242
|
+
let step = 0;
|
|
2668
2243
|
let stepStartedAt;
|
|
2669
2244
|
let firstTokenAt;
|
|
2670
2245
|
let pendingProviderError;
|
|
@@ -2673,12 +2248,24 @@ export class ConsolePiRuntime {
|
|
|
2673
2248
|
const emitPendingProviderError = () => {
|
|
2674
2249
|
if (!pendingProviderError)
|
|
2675
2250
|
return;
|
|
2676
|
-
|
|
2251
|
+
const error = pendingProviderError;
|
|
2252
|
+
onEvent(error);
|
|
2253
|
+
onEvent({
|
|
2254
|
+
type: "turn_error",
|
|
2255
|
+
sessionId,
|
|
2256
|
+
step: Math.max(1, step),
|
|
2257
|
+
...(error.providerError.code === undefined
|
|
2258
|
+
? {}
|
|
2259
|
+
: { code: String(error.providerError.code) }),
|
|
2260
|
+
message: error.message,
|
|
2261
|
+
});
|
|
2677
2262
|
pendingProviderError = undefined;
|
|
2678
2263
|
providerErrorEmitted = true;
|
|
2679
2264
|
};
|
|
2680
2265
|
unsub = session.subscribe((event) => {
|
|
2681
2266
|
const observedAt = Date.now();
|
|
2267
|
+
if (event.type === "turn_start")
|
|
2268
|
+
step += 1;
|
|
2682
2269
|
if (event.type === "message_start" && isUserSdkMessage(event.message)) {
|
|
2683
2270
|
if (!initialUserMessageStarted) {
|
|
2684
2271
|
// The first user message_start belongs to session.prompt(text), not
|
|
@@ -2709,7 +2296,7 @@ export class ConsolePiRuntime {
|
|
|
2709
2296
|
const compactionId = event.type === "compaction_start" || event.type === "compaction_end"
|
|
2710
2297
|
? activeCompaction?.compactionId ?? newCompactionId(sessionId)
|
|
2711
2298
|
: undefined;
|
|
2712
|
-
const mapped = mapSdkEvent(sessionId, event, compactionId);
|
|
2299
|
+
const mapped = mapSdkEvent(sessionId, event, compactionId, Math.max(1, step));
|
|
2713
2300
|
if (event.type === "compaction_end")
|
|
2714
2301
|
activeCompaction = undefined;
|
|
2715
2302
|
if (mapped?.type === "error") {
|
|
@@ -2734,7 +2321,7 @@ export class ConsolePiRuntime {
|
|
|
2734
2321
|
if (mapped?.type === "agent_settled") {
|
|
2735
2322
|
emitPendingProviderError();
|
|
2736
2323
|
}
|
|
2737
|
-
if (mapped?.type === "agent_start") {
|
|
2324
|
+
if (mapped?.type === "step_start" || mapped?.type === "agent_start") {
|
|
2738
2325
|
stepStartedAt = observedAt;
|
|
2739
2326
|
firstTokenAt = undefined;
|
|
2740
2327
|
}
|
|
@@ -2762,6 +2349,13 @@ export class ConsolePiRuntime {
|
|
|
2762
2349
|
: { outputTokens: usage.outputTokens }),
|
|
2763
2350
|
};
|
|
2764
2351
|
onEvent({ ...mapped, ...(timing ? { timing } : {}) });
|
|
2352
|
+
if (mapped.stopReason === "length") {
|
|
2353
|
+
onEvent({
|
|
2354
|
+
type: "turn_max_tokens",
|
|
2355
|
+
sessionId,
|
|
2356
|
+
step: mapped.step ?? Math.max(1, step),
|
|
2357
|
+
});
|
|
2358
|
+
}
|
|
2765
2359
|
if (usage)
|
|
2766
2360
|
onEvent({ type: "usage", sessionId, usage });
|
|
2767
2361
|
emitContextUsage();
|
|
@@ -2943,6 +2537,36 @@ export class ConsolePiRuntime {
|
|
|
2943
2537
|
const result = await session.compact(customInstructions);
|
|
2944
2538
|
return projectCompactSnapshot(result ?? {});
|
|
2945
2539
|
}
|
|
2540
|
+
listDatabaseConnections() {
|
|
2541
|
+
return this.dbConnections.list();
|
|
2542
|
+
}
|
|
2543
|
+
addDatabaseConnection(input) {
|
|
2544
|
+
return this.dbConnections.add(input);
|
|
2545
|
+
}
|
|
2546
|
+
updateDatabaseConnection(currentName, input) {
|
|
2547
|
+
return this.dbConnections.update(currentName, input);
|
|
2548
|
+
}
|
|
2549
|
+
removeDatabaseConnection(name) {
|
|
2550
|
+
return this.dbConnections.remove(name);
|
|
2551
|
+
}
|
|
2552
|
+
exportDatabaseConnections() {
|
|
2553
|
+
return this.dbConnections.exportConfig();
|
|
2554
|
+
}
|
|
2555
|
+
importDatabaseConnections(input, conflict) {
|
|
2556
|
+
return this.dbConnections.importConfig(input, conflict);
|
|
2557
|
+
}
|
|
2558
|
+
testDatabaseConnection(name) {
|
|
2559
|
+
return this.dbConnections.test(name);
|
|
2560
|
+
}
|
|
2561
|
+
listDatabaseDatabases(name) {
|
|
2562
|
+
return this.dbConnections.listDatabases(name);
|
|
2563
|
+
}
|
|
2564
|
+
listDatabaseTables(name, database) {
|
|
2565
|
+
return this.dbConnections.listTables(name, database);
|
|
2566
|
+
}
|
|
2567
|
+
browseDatabaseTable(name, table, page, pageSize, database) {
|
|
2568
|
+
return this.dbConnections.browseTable(name, table, page, pageSize, database);
|
|
2569
|
+
}
|
|
2946
2570
|
dispose(sessionId) {
|
|
2947
2571
|
// Mark disposed first so a late materialization never registers ready.
|
|
2948
2572
|
this.disposedSessions.add(sessionId);
|
|
@@ -2950,6 +2574,11 @@ export class ConsolePiRuntime {
|
|
|
2950
2574
|
this.sessionInit.delete(sessionId);
|
|
2951
2575
|
this.compactionControllers.delete(sessionId);
|
|
2952
2576
|
this.siftStates.delete(sessionId);
|
|
2577
|
+
for (const key of this.operatorCustomToolsBySession.keys()) {
|
|
2578
|
+
if (key.startsWith(`${sessionId}:`)) {
|
|
2579
|
+
this.operatorCustomToolsBySession.delete(key);
|
|
2580
|
+
}
|
|
2581
|
+
}
|
|
2953
2582
|
const session = this.sessions.get(sessionId);
|
|
2954
2583
|
if (session) {
|
|
2955
2584
|
try {
|
|
@@ -2961,22 +2590,30 @@ export class ConsolePiRuntime {
|
|
|
2961
2590
|
}
|
|
2962
2591
|
this.sessions.delete(sessionId);
|
|
2963
2592
|
this.sessionManagers.delete(sessionId);
|
|
2593
|
+
this.toolExposures.delete(sessionId);
|
|
2964
2594
|
this.mainlineLeaves.delete(sessionId);
|
|
2965
2595
|
this.modelRuntimes.delete(sessionId);
|
|
2966
2596
|
this.modelConfigFiles.delete(sessionId);
|
|
2967
2597
|
this.sessionModels.delete(sessionId);
|
|
2598
|
+
this.sessionModes.delete(sessionId);
|
|
2968
2599
|
this.serviceScopes.delete(sessionId);
|
|
2969
2600
|
this.revisions.delete(sessionId);
|
|
2970
2601
|
this.thinkingSelections.delete(sessionId);
|
|
2971
2602
|
this.reloadInFlight.delete(sessionId);
|
|
2972
2603
|
this.pendingSteering.delete(sessionId);
|
|
2604
|
+
void this.exploreOrchestrator.abortByParent(sessionId);
|
|
2973
2605
|
}
|
|
2974
2606
|
disposeAll() {
|
|
2975
2607
|
for (const id of [...this.sessions.keys()])
|
|
2976
2608
|
this.dispose(id);
|
|
2609
|
+
void this.exploreOrchestrator.abortAll();
|
|
2610
|
+
if (this.ownsBrowserAutomation)
|
|
2611
|
+
void this.browserAutomation.dispose();
|
|
2612
|
+
if (this.ownsDbConnections)
|
|
2613
|
+
this.dbConnections.dispose();
|
|
2977
2614
|
}
|
|
2978
2615
|
}
|
|
2979
|
-
function mapAssistantMessageEvent(type, sessionId, message) {
|
|
2616
|
+
function mapAssistantMessageEvent(type, sessionId, message, step) {
|
|
2980
2617
|
const record = message !== null && typeof message === "object"
|
|
2981
2618
|
? message
|
|
2982
2619
|
: undefined;
|
|
@@ -3000,6 +2637,10 @@ function mapAssistantMessageEvent(type, sessionId, message) {
|
|
|
3000
2637
|
sessionId,
|
|
3001
2638
|
text: extractAssistantText(message),
|
|
3002
2639
|
...(content.length > 0 ? { content } : {}),
|
|
2640
|
+
step,
|
|
2641
|
+
...(type === "message_end" && typeof record?.stopReason === "string"
|
|
2642
|
+
? { stopReason: record.stopReason }
|
|
2643
|
+
: {}),
|
|
3003
2644
|
};
|
|
3004
2645
|
}
|
|
3005
2646
|
function isUserSdkMessage(message) {
|
|
@@ -3007,10 +2648,12 @@ function isUserSdkMessage(message) {
|
|
|
3007
2648
|
typeof message === "object" &&
|
|
3008
2649
|
message.role === "user");
|
|
3009
2650
|
}
|
|
3010
|
-
function mapSdkEvent(sessionId, event, compactionId) {
|
|
2651
|
+
export function mapSdkEvent(sessionId, event, compactionId, step = 1) {
|
|
3011
2652
|
switch (event.type) {
|
|
3012
2653
|
case "agent_start":
|
|
3013
2654
|
return { type: "agent_start", sessionId };
|
|
2655
|
+
case "turn_start":
|
|
2656
|
+
return { type: "step_start", sessionId, step };
|
|
3014
2657
|
case "agent_end":
|
|
3015
2658
|
return {
|
|
3016
2659
|
type: "agent_end",
|
|
@@ -3020,15 +2663,50 @@ function mapSdkEvent(sessionId, event, compactionId) {
|
|
|
3020
2663
|
case "message_update":
|
|
3021
2664
|
if (!isAssistantSdkMessage(event.message))
|
|
3022
2665
|
return undefined;
|
|
3023
|
-
return mapAssistantMessageEvent("message_update", sessionId, event.message);
|
|
2666
|
+
return mapAssistantMessageEvent("message_update", sessionId, event.message, step);
|
|
3024
2667
|
case "message_end":
|
|
3025
2668
|
if (!isAssistantSdkMessage(event.message))
|
|
3026
2669
|
return undefined;
|
|
3027
|
-
return mapAssistantMessageEvent("message_end", sessionId, event.message);
|
|
3028
|
-
case "turn_end":
|
|
3029
|
-
|
|
3030
|
-
|
|
3031
|
-
|
|
2670
|
+
return mapAssistantMessageEvent("message_end", sessionId, event.message, step);
|
|
2671
|
+
case "turn_end": {
|
|
2672
|
+
const record = event.message && typeof event.message === "object"
|
|
2673
|
+
? event.message
|
|
2674
|
+
: undefined;
|
|
2675
|
+
const reason = record?.stopReason;
|
|
2676
|
+
return {
|
|
2677
|
+
type: "step_end",
|
|
2678
|
+
sessionId,
|
|
2679
|
+
step,
|
|
2680
|
+
outcome: reason === "error"
|
|
2681
|
+
? "failed"
|
|
2682
|
+
: reason === "aborted"
|
|
2683
|
+
? "interrupted"
|
|
2684
|
+
: "completed",
|
|
2685
|
+
};
|
|
2686
|
+
}
|
|
2687
|
+
case "auto_retry_start":
|
|
2688
|
+
return {
|
|
2689
|
+
type: "model_retry",
|
|
2690
|
+
sessionId,
|
|
2691
|
+
step,
|
|
2692
|
+
attempt: event.attempt,
|
|
2693
|
+
maxAttempts: event.maxAttempts,
|
|
2694
|
+
delayMs: event.delayMs,
|
|
2695
|
+
errorMessage: redactRuntimeText(event.errorMessage, 600),
|
|
2696
|
+
state: "scheduled",
|
|
2697
|
+
};
|
|
2698
|
+
case "auto_retry_end":
|
|
2699
|
+
return {
|
|
2700
|
+
type: "model_retry",
|
|
2701
|
+
sessionId,
|
|
2702
|
+
step,
|
|
2703
|
+
attempt: event.attempt,
|
|
2704
|
+
state: event.success ? "completed" : "failed",
|
|
2705
|
+
success: event.success,
|
|
2706
|
+
...(event.finalError
|
|
2707
|
+
? { errorMessage: redactRuntimeText(event.finalError, 600) }
|
|
2708
|
+
: {}),
|
|
2709
|
+
};
|
|
3032
2710
|
case "tool_execution_start":
|
|
3033
2711
|
return {
|
|
3034
2712
|
type: "tool_call",
|
|
@@ -3036,6 +2714,22 @@ function mapSdkEvent(sessionId, event, compactionId) {
|
|
|
3036
2714
|
toolCallId: event.toolCallId,
|
|
3037
2715
|
toolName: event.toolName,
|
|
3038
2716
|
args: event.args,
|
|
2717
|
+
step,
|
|
2718
|
+
...(event.parentToolCallId
|
|
2719
|
+
? { parentToolCallId: event.parentToolCallId }
|
|
2720
|
+
: {}),
|
|
2721
|
+
};
|
|
2722
|
+
case "tool_execution_update":
|
|
2723
|
+
return {
|
|
2724
|
+
type: "tool_update",
|
|
2725
|
+
sessionId,
|
|
2726
|
+
toolCallId: event.toolCallId,
|
|
2727
|
+
toolName: event.toolName,
|
|
2728
|
+
partialResult: event.partialResult,
|
|
2729
|
+
step,
|
|
2730
|
+
...(event.parentToolCallId
|
|
2731
|
+
? { parentToolCallId: event.parentToolCallId }
|
|
2732
|
+
: {}),
|
|
3039
2733
|
};
|
|
3040
2734
|
case "tool_execution_end":
|
|
3041
2735
|
return {
|
|
@@ -3045,6 +2739,10 @@ function mapSdkEvent(sessionId, event, compactionId) {
|
|
|
3045
2739
|
toolName: event.toolName,
|
|
3046
2740
|
result: event.result,
|
|
3047
2741
|
isError: event.isError,
|
|
2742
|
+
step,
|
|
2743
|
+
...(event.parentToolCallId
|
|
2744
|
+
? { parentToolCallId: event.parentToolCallId }
|
|
2745
|
+
: {}),
|
|
3048
2746
|
};
|
|
3049
2747
|
case "agent_settled":
|
|
3050
2748
|
return { type: "agent_settled", sessionId };
|
|
@@ -3091,8 +2789,19 @@ function mapSdkEvent(sessionId, event, compactionId) {
|
|
|
3091
2789
|
: {}),
|
|
3092
2790
|
};
|
|
3093
2791
|
}
|
|
3094
|
-
|
|
2792
|
+
case "message_start":
|
|
2793
|
+
case "queue_update":
|
|
3095
2794
|
return undefined;
|
|
2795
|
+
default:
|
|
2796
|
+
{
|
|
2797
|
+
const unknownEvent = event;
|
|
2798
|
+
return {
|
|
2799
|
+
type: "unknown",
|
|
2800
|
+
sessionId,
|
|
2801
|
+
eventType: String(unknownEvent.type ?? "unknown"),
|
|
2802
|
+
value: unknownEvent,
|
|
2803
|
+
};
|
|
2804
|
+
}
|
|
3096
2805
|
}
|
|
3097
2806
|
}
|
|
3098
2807
|
function newCompactionId(sessionId) {
|
|
@@ -3130,155 +2839,9 @@ async function waitForIdle(session, options) {
|
|
|
3130
2839
|
await new Promise((r) => setTimeout(r, 50));
|
|
3131
2840
|
}
|
|
3132
2841
|
}
|
|
3133
|
-
async function safeGetAgentDir(bindings) {
|
|
3134
|
-
try {
|
|
3135
|
-
return await bindings.getAgentDir();
|
|
3136
|
-
}
|
|
3137
|
-
catch {
|
|
3138
|
-
// Fall back to a Console-app-data scoped agent dir so we never accidentally
|
|
3139
|
-
// touch the user's real ~/.pi/agent config if getAgentDir throws.
|
|
3140
|
-
return path.join(process.cwd(), ".harness", "console", "pi-agent-dir");
|
|
3141
|
-
}
|
|
3142
|
-
}
|
|
3143
|
-
/**
|
|
3144
|
-
* Cached SDK module loader. The pi-coding-agent package is ESM-only, so we
|
|
3145
|
-
* must use dynamic import() (not require). Cached to avoid repeated imports.
|
|
3146
|
-
*/
|
|
3147
|
-
let cachedSdk;
|
|
3148
|
-
async function loadSdk() {
|
|
3149
|
-
if (!cachedSdk) {
|
|
3150
|
-
cachedSdk = import("@earendil-works/pi-coding-agent");
|
|
3151
|
-
}
|
|
3152
|
-
return cachedSdk;
|
|
3153
|
-
}
|
|
3154
|
-
/**
|
|
3155
|
-
* Default production bindings backed by the real Pi SDK (services mode).
|
|
3156
|
-
* Dynamically imported so the worker bundle does not hard-fail if the SDK is
|
|
3157
|
-
* absent at module load (discovered lazily by pi-readiness instead).
|
|
3158
|
-
*/
|
|
3159
|
-
export function createDefaultPiSdkBindings() {
|
|
3160
|
-
return {
|
|
3161
|
-
getAgentDir: async () => {
|
|
3162
|
-
const sdk = (await loadSdk());
|
|
3163
|
-
return sdk.getAgentDir();
|
|
3164
|
-
},
|
|
3165
|
-
createServices: async (opts) => {
|
|
3166
|
-
const sdk = (await loadSdk());
|
|
3167
|
-
// createAgentSessionServices returns the full AgentSessionServices object
|
|
3168
|
-
// directly (cwd/agentDir/modelRuntime/settingsManager/resourceLoader).
|
|
3169
|
-
// Wrap it so our type contract is satisfied.
|
|
3170
|
-
const result = await sdk.createAgentSessionServices({
|
|
3171
|
-
cwd: opts.cwd,
|
|
3172
|
-
agentDir: opts.agentDir,
|
|
3173
|
-
resourceLoaderOptions: opts.resourceLoaderOptions,
|
|
3174
|
-
});
|
|
3175
|
-
return { services: result };
|
|
3176
|
-
},
|
|
3177
|
-
createSessionFromServices: async (opts) => {
|
|
3178
|
-
const sdk = (await loadSdk());
|
|
3179
|
-
return sdk.createAgentSessionFromServices({
|
|
3180
|
-
services: opts.services,
|
|
3181
|
-
sessionManager: opts.sessionManager,
|
|
3182
|
-
...(opts.tools ? { tools: opts.tools } : {}),
|
|
3183
|
-
...(opts.noTools ? { noTools: opts.noTools } : {}),
|
|
3184
|
-
...(opts.excludeTools ? { excludeTools: opts.excludeTools } : {}),
|
|
3185
|
-
...(opts.customTools ? { customTools: opts.customTools } : {}),
|
|
3186
|
-
...(opts.model ? { model: opts.model } : {}),
|
|
3187
|
-
});
|
|
3188
|
-
},
|
|
3189
|
-
createSessionManager: async (opts) => {
|
|
3190
|
-
const sdk = (await loadSdk());
|
|
3191
|
-
return sdk.SessionManager.create(opts.cwd, opts.sessionDir, {
|
|
3192
|
-
id: opts.sessionId,
|
|
3193
|
-
});
|
|
3194
|
-
},
|
|
3195
|
-
materializeSessionShell: async (opts) => {
|
|
3196
|
-
const sdk = (await loadSdk());
|
|
3197
|
-
const manager = opts.sessionManager;
|
|
3198
|
-
if (typeof manager.setSessionFile !== "function") {
|
|
3199
|
-
throw new Error("Pi SessionManager cannot materialize a session file");
|
|
3200
|
-
}
|
|
3201
|
-
let created = false;
|
|
3202
|
-
try {
|
|
3203
|
-
await mkdir(path.dirname(opts.sessionFile), { recursive: true });
|
|
3204
|
-
// Match Pi's documented session header. Rebinding through the public
|
|
3205
|
-
// SessionManager API marks it flushed, so Pi appends the first user
|
|
3206
|
-
// entry instead of trying to create the already-present file later.
|
|
3207
|
-
await writeFile(opts.sessionFile, `${JSON.stringify({
|
|
3208
|
-
type: "session",
|
|
3209
|
-
version: typeof sdk.CURRENT_SESSION_VERSION === "number"
|
|
3210
|
-
? sdk.CURRENT_SESSION_VERSION
|
|
3211
|
-
: 3,
|
|
3212
|
-
id: opts.sessionId,
|
|
3213
|
-
timestamp: new Date().toISOString(),
|
|
3214
|
-
cwd: opts.cwd,
|
|
3215
|
-
})}\n`, { encoding: "utf8", flag: "wx", mode: 0o600 });
|
|
3216
|
-
created = true;
|
|
3217
|
-
manager.setSessionFile(opts.sessionFile);
|
|
3218
|
-
}
|
|
3219
|
-
catch (error) {
|
|
3220
|
-
if (created)
|
|
3221
|
-
await rm(opts.sessionFile, { force: true }).catch(() => undefined);
|
|
3222
|
-
throw error;
|
|
3223
|
-
}
|
|
3224
|
-
},
|
|
3225
|
-
createInMemorySessionManager: async (opts) => {
|
|
3226
|
-
const sdk = (await loadSdk());
|
|
3227
|
-
return sdk.SessionManager.inMemory(opts.cwd);
|
|
3228
|
-
},
|
|
3229
|
-
forkSessionManager: async (opts) => {
|
|
3230
|
-
const sdk = (await loadSdk());
|
|
3231
|
-
return sdk.SessionManager.forkFrom(opts.sourcePath, opts.targetCwd, opts.targetSessionDir, { id: opts.targetSessionId });
|
|
3232
|
-
},
|
|
3233
|
-
openSessionManager: async (opts) => {
|
|
3234
|
-
const sdk = (await loadSdk());
|
|
3235
|
-
try {
|
|
3236
|
-
// Pi SessionManager.open(missingPath) does NOT throw — it creates a
|
|
3237
|
-
// fresh in-memory session with a random UUID. That would reopen the
|
|
3238
|
-
// wrong conversation under the durable Console sessionId. Fail closed
|
|
3239
|
-
// before open when the persisted file is absent.
|
|
3240
|
-
await access(opts.sessionFile);
|
|
3241
|
-
}
|
|
3242
|
-
catch (error) {
|
|
3243
|
-
const code = error && typeof error === "object" && "code" in error
|
|
3244
|
-
? String(error.code ?? "")
|
|
3245
|
-
: "";
|
|
3246
|
-
if (code === "ENOENT") {
|
|
3247
|
-
throw Object.assign(new Error(`SESSION_FILE_MISSING: ${opts.sessionFile}`), { code: "SESSION_FILE_MISSING", cause: error });
|
|
3248
|
-
}
|
|
3249
|
-
// File exists but is unreadable (permissions / I/O) — caller maps
|
|
3250
|
-
// undefined to 503 rather than silently creating a fresh session.
|
|
3251
|
-
return undefined;
|
|
3252
|
-
}
|
|
3253
|
-
return sdk.SessionManager.open(opts.sessionFile);
|
|
3254
|
-
},
|
|
3255
|
-
resolveModel: (opts) => {
|
|
3256
|
-
const rt = opts.modelRuntime;
|
|
3257
|
-
if (typeof rt?.getModel !== "function")
|
|
3258
|
-
return undefined;
|
|
3259
|
-
try {
|
|
3260
|
-
return rt.getModel(opts.provider, opts.modelId);
|
|
3261
|
-
}
|
|
3262
|
-
catch {
|
|
3263
|
-
return undefined;
|
|
3264
|
-
}
|
|
3265
|
-
},
|
|
3266
|
-
listAvailableModels: (opts) => {
|
|
3267
|
-
const rt = opts.modelRuntime;
|
|
3268
|
-
const available = rt?.snapshot?.available ?? [];
|
|
3269
|
-
const configured = rt?.snapshot?.configuredProviders;
|
|
3270
|
-
const isConfigured = (provider) => configured instanceof Set ? configured.has(provider) : false;
|
|
3271
|
-
return available.map((m) => ({
|
|
3272
|
-
id: m.id,
|
|
3273
|
-
name: m.name,
|
|
3274
|
-
provider: m.provider,
|
|
3275
|
-
hasCredentials: isConfigured(m.provider),
|
|
3276
|
-
}));
|
|
3277
|
-
},
|
|
3278
|
-
};
|
|
3279
|
-
}
|
|
3280
2842
|
/**
|
|
3281
|
-
* Re-export the tool
|
|
3282
|
-
* (Gate 3) lives in exactly one place.
|
|
2843
|
+
* Re-export the tool gates for the dispatcher layer so the per-tool-call gate
|
|
2844
|
+
* (Gate 3) lives in exactly one place. authorizeChatSessionTool is the
|
|
2845
|
+
* mode-aware gate; the legacy name stays for workflow-only callers.
|
|
3283
2846
|
*/
|
|
3284
|
-
export { authorizeOperatorChatTool, assertNoWriteToolInList, OPERATOR_CHAT_ALLOWED_TOOLS, };
|
|
2847
|
+
export { authorizeChatSessionTool, authorizeOperatorChatTool, assertNoWriteToolInList, OPERATOR_CHAT_ALLOWED_TOOLS, };
|