chainlesschain 0.162.189 → 0.162.197
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/README.md +84 -11
- package/bin/chainlesschain.js +7 -52
- package/completions/_cc +209 -0
- package/completions/cc.bash +18 -0
- package/completions/cc.fish +13 -0
- package/completions/cc.ps1 +226 -0
- package/package.json +10 -2
- package/src/assets/web-panel/assets/{AIOps-DbZft8w0.js → AIOps-D3Gu1a5d.js} +1 -1
- package/src/assets/web-panel/assets/{ActionButton-DoOZpwfN.js → ActionButton-DrwAoKaz.js} +1 -1
- package/src/assets/web-panel/assets/{Analytics-B0J0KLTW.js → Analytics-C7Q-gd_3.js} +3 -3
- package/src/assets/web-panel/assets/{AppLayout-D9eIR0qq.js → AppLayout-DgBtae-n.js} +4 -4
- package/src/assets/web-panel/assets/{Artifacts-BnZXEVeo.js → Artifacts-pQ6LcA-W.js} +1 -1
- package/src/assets/web-panel/assets/{Audit-X1ce4Bjn.js → Audit-DK61tocB.js} +1 -1
- package/src/assets/web-panel/assets/{BackgroundAgents-BvWR-y5v.js → BackgroundAgents-BOKgDFRh.js} +1 -1
- package/src/assets/web-panel/assets/{Backup-BublSGEd.js → Backup-Bo9G4vTP.js} +1 -1
- package/src/assets/web-panel/assets/{BaseInput-CR_77Hso.js → BaseInput-Do_dE9_v.js} +1 -1
- package/src/assets/web-panel/assets/{Chat-DixW52tq.js → Chat-COVvZzOL.js} +6 -6
- package/src/assets/web-panel/assets/ChatBubbleRenderer-BUUyJ5QO.js +1 -0
- package/src/assets/web-panel/assets/{Checkbox-CCv1C87K.js → Checkbox-Z9MJMolt.js} +1 -1
- package/src/assets/web-panel/assets/{Codegen-B03Cc3dd.js → Codegen-BVzWKVbf.js} +1 -1
- package/src/assets/web-panel/assets/{Col-CA06-6pU.js → Col-C8MnYcbT.js} +1 -1
- package/src/assets/web-panel/assets/{Community-Bj881J52.js → Community-DQxqw15l.js} +1 -1
- package/src/assets/web-panel/assets/{Compact-UZLTPoaL.js → Compact-BAUmrh3y.js} +1 -1
- package/src/assets/web-panel/assets/{Compliance-kGwzRb_0.js → Compliance-jPAkQ3zK.js} +1 -1
- package/src/assets/web-panel/assets/{Cowork-KundoYM8.js → Cowork-BBQyxbh8.js} +2 -2
- package/src/assets/web-panel/assets/{Cron-BYZyoqDe.js → Cron-W5koq8Z5.js} +2 -2
- package/src/assets/web-panel/assets/{Crosschain-BhrrppBX.js → Crosschain-BQhnu5hS.js} +1 -1
- package/src/assets/web-panel/assets/{DID-CdC6EguZ.js → DID-DD7PlI18.js} +2 -2
- package/src/assets/web-panel/assets/{Dashboard-CcQx3J4y.js → Dashboard-w_ILuwKI.js} +2 -2
- package/src/assets/web-panel/assets/{Dropdown-BpijtEzQ.js → Dropdown-qiDUAyAo.js} +1 -1
- package/src/assets/web-panel/assets/{EmailListRenderer-DfZjeZTe.js → EmailListRenderer-PDeBcI5H.js} +1 -1
- package/src/assets/web-panel/assets/{FamilyGuardDashboard-BFYSf69C.js → FamilyGuardDashboard-SuArscRM.js} +1 -1
- package/src/assets/web-panel/assets/{Federation-Okdi3pJm.js → Federation-BCovZaUn.js} +1 -1
- package/src/assets/web-panel/assets/{FormItemContext-mH-HebKW.js → FormItemContext-DjlFdVFk.js} +1 -1
- package/src/assets/web-panel/assets/{GenericCardRenderer-xivV69x7.js → GenericCardRenderer-DoEZ7fcS.js} +1 -1
- package/src/assets/web-panel/assets/{Git-1rh_YBwg.js → Git-CV0-6GPI.js} +2 -2
- package/src/assets/web-panel/assets/{Governance-eAXkNxdY.js → Governance-B_SFN50w.js} +1 -1
- package/src/assets/web-panel/assets/{Inference-CS6dMVTN.js → Inference-heI0Eo6k.js} +1 -1
- package/src/assets/web-panel/assets/{KnowledgeGraph-Bq_TnkvD.js → KnowledgeGraph-Cz5INS5p.js} +1 -1
- package/src/assets/web-panel/assets/{Logs-KchHtiHt.js → Logs-BSFxiHkg.js} +2 -2
- package/src/assets/web-panel/assets/MarkdownRenderer-1mNozZ8v.js +1 -0
- package/src/assets/web-panel/assets/{Marketplace-CsmGcX5X.js → Marketplace-0TWTpE7k.js} +1 -1
- package/src/assets/web-panel/assets/{McpTools-BaPFnnyz.js → McpTools-CV4-wBLm.js} +4 -4
- package/src/assets/web-panel/assets/{Memory-2m-sUUf7.js → Memory-x5bH5rw5.js} +2 -2
- package/src/assets/web-panel/assets/{MobileBridge-D5nVZBRu.js → MobileBridge-DaBmUu9G.js} +1 -1
- package/src/assets/web-panel/assets/{MobileProjects-Bo8MLZvT.js → MobileProjects-DqnoFPgR.js} +1 -1
- package/src/assets/web-panel/assets/{Mtc-3GDvamGa.js → Mtc-B_zKEBif.js} +4 -4
- package/src/assets/web-panel/assets/{MtcAudit-D2zGuZCH.js → MtcAudit-BCfKD2yg.js} +4 -4
- package/src/assets/web-panel/assets/{Multisig-BBVQ4t6t.js → Multisig-DgYfj6c_.js} +3 -3
- package/src/assets/web-panel/assets/{NLProgramming-BIOCyOGp.js → NLProgramming-Dz09lFUm.js} +1 -1
- package/src/assets/web-panel/assets/{Notes-DVwBGpzc.js → Notes-Cuj6ugBE.js} +3 -3
- package/src/assets/web-panel/assets/{NotificationSettings-BDnHfIfX.js → NotificationSettings-DK2WXjhg.js} +1 -1
- package/src/assets/web-panel/assets/{OrderTableRenderer-C7Ek20ag.js → OrderTableRenderer-D1IAOQoo.js} +1 -1
- package/src/assets/web-panel/assets/{Organization-D3SRKaa7.js → Organization-9fqnPvTw.js} +4 -4
- package/src/assets/web-panel/assets/{Overflow-C2B8ahyn.js → Overflow-n5xHkhow.js} +1 -1
- package/src/assets/web-panel/assets/{P2P-2iwQzG65.js → P2P-B5AUWwH-.js} +2 -2
- package/src/assets/web-panel/assets/{PdhVaultBrowser-CoPiWqMN.js → PdhVaultBrowser-CoUDV6dy.js} +4 -4
- package/src/assets/web-panel/assets/{Permissions-yV5XNXo5.js → Permissions-DPRmQf_H.js} +4 -4
- package/src/assets/web-panel/assets/{PersonalDataHub-uCDJhMUF.js → PersonalDataHub-B37bsbEN.js} +4 -4
- package/src/assets/web-panel/assets/{Pipeline-hN7ucMOA.js → Pipeline-CCAuPqu9.js} +1 -1
- package/src/assets/web-panel/assets/{Privacy-CgU0ptN4.js → Privacy-B81msZdv.js} +1 -1
- package/src/assets/web-panel/assets/{ProjectInit-CfYPiT6j.js → ProjectInit-B-Py2NbF.js} +2 -2
- package/src/assets/web-panel/assets/{ProjectSettings-B0A2C4nw.js → ProjectSettings-CYsneiRB.js} +2 -2
- package/src/assets/web-panel/assets/{Projects-BE5C0ajn.js → Projects-Y975Mh6R.js} +1 -1
- package/src/assets/web-panel/assets/{Providers-CstQPf8W.js → Providers-uO-10aP1.js} +1 -1
- package/src/assets/web-panel/assets/{QrScannerModal-Co3z_ynk.js → QrScannerModal-Bj_6gJ0l.js} +1 -1
- package/src/assets/web-panel/assets/{QuickAsk-DMTS6pQ6.js → QuickAsk-BgpBCMPE.js} +1 -1
- package/src/assets/web-panel/assets/{Recommend-ETw4odUa.js → Recommend-DhUW3YUA.js} +1 -1
- package/src/assets/web-panel/assets/RemoteSession-DdeyfbkA.js +5 -0
- package/src/assets/web-panel/assets/{Reputation-BTVqQgKq.js → Reputation-fxW421xd.js} +1 -1
- package/src/assets/web-panel/assets/{Row-CBKKwwtO.js → Row-De73w1og.js} +1 -1
- package/src/assets/web-panel/assets/{RssFeed-BHUQ438I.js → RssFeed-3US_Q_lj.js} +2 -2
- package/src/assets/web-panel/assets/{Search-B4NqeUsF.js → Search-DbZ_DU74.js} +1 -1
- package/src/assets/web-panel/assets/{Security-BRjoYG5_.js → Security-DoIU1vMF.js} +4 -4
- package/src/assets/web-panel/assets/{Services-CxQzu3p3.js → Services-DB_RGqpc.js} +2 -2
- package/src/assets/web-panel/assets/{Skeleton-BKzwwmWO.js → Skeleton-DnzLaayC.js} +1 -1
- package/src/assets/web-panel/assets/{Skills-DrsFcgth.js → Skills-VzVXHENF.js} +1 -1
- package/src/assets/web-panel/assets/{Sla-D21tmXCH.js → Sla-DMfvjCAI.js} +1 -1
- package/src/assets/web-panel/assets/{SpeechSettings-CjyjLfp8.js → SpeechSettings-DQQOYWbF.js} +1 -1
- package/src/assets/web-panel/assets/{SyncSettings-Cu45-tnx.js → SyncSettings-Bmx3FG1P.js} +2 -2
- package/src/assets/web-panel/assets/{Tasks-oMcILYOj.js → Tasks-DOQyfb-2.js} +1 -1
- package/src/assets/web-panel/assets/{Templates-Bh-Zcr5R.js → Templates-D6hTRT7c.js} +1 -1
- package/src/assets/web-panel/assets/{Tenant-68ns63aI.js → Tenant-CTPQZAzs.js} +1 -1
- package/src/assets/web-panel/assets/{Terminal-BLJkFykE.js → Terminal-B7vII3oH.js} +2 -2
- package/src/assets/web-panel/assets/{TimelineRenderer-xcrJLq-O.js → TimelineRenderer-BkiFJeXV.js} +1 -1
- package/src/assets/web-panel/assets/{Tokens-C6PpFJtf.js → Tokens-BPPdQMNo.js} +1 -1
- package/src/assets/web-panel/assets/{Trigger-BaKA7tdM.js → Trigger-BxG8JAEI.js} +1 -1
- package/src/assets/web-panel/assets/{Trust-BzhA57Jc.js → Trust-DHD7nMpM.js} +1 -1
- package/src/assets/web-panel/assets/{UkeySign-4_U3JkIR.js → UkeySign-B4BJpU47.js} +1 -1
- package/src/assets/web-panel/assets/{VideoEditing-162AANxX.js → VideoEditing-CRiGpFx2.js} +1 -1
- package/src/assets/web-panel/assets/{Wallet-B1viuql_.js → Wallet-BSDSNiem.js} +4 -4
- package/src/assets/web-panel/assets/{WebAuthn-ZVWazhCy.js → WebAuthn-DLTUh5Zv.js} +5 -5
- package/src/assets/web-panel/assets/WorkflowEditor-tW2MwjhD.js +1 -0
- package/src/assets/web-panel/assets/{chat-DmrHNuwq.js → chat-SgsLQ3FC.js} +1 -1
- package/src/assets/web-panel/assets/{colors-DAJ_M-PK.js → colors-BHjjLIKO.js} +1 -1
- package/src/assets/web-panel/assets/{compact-item-uIzmYwLs.js → compact-item-VceErdKq.js} +1 -1
- package/src/assets/web-panel/assets/{createContext-D_ZmuLwb.js → createContext-BZ332MYl.js} +1 -1
- package/src/assets/web-panel/assets/devWarning-DosMaL-k.js +1 -0
- package/src/assets/web-panel/assets/{hasIn-CDt_shTL.js → hasIn-CBTjJOjn.js} +1 -1
- package/src/assets/web-panel/assets/index-0O5ePnUq.js +1 -0
- package/src/assets/web-panel/assets/{index-rXdwUeE3.js → index-1n7xjKDU.js} +1 -1
- package/src/assets/web-panel/assets/{index-BAvSmJXW.js → index-29wVzi-k.js} +1 -1
- package/src/assets/web-panel/assets/{index-C16fYKFD.js → index-B2u26AS3.js} +1 -1
- package/src/assets/web-panel/assets/{index-C5WcdJH2.js → index-B40dQn0G.js} +3 -3
- package/src/assets/web-panel/assets/{index-CaelyMgF.js → index-B5KAGxNo.js} +1 -1
- package/src/assets/web-panel/assets/{index-OzTxFIJP.js → index-BC1xuQgX.js} +1 -1
- package/src/assets/web-panel/assets/{index-CzXqvMuP.js → index-BETEjuNr.js} +1 -1
- package/src/assets/web-panel/assets/{index-clSX4PEc.js → index-BOtvPdHt.js} +1 -1
- package/src/assets/web-panel/assets/{index-saf3VNeP.js → index-BPXFLYdW.js} +1 -1
- package/src/assets/web-panel/assets/{index-DdUMcwRB.js → index-BQSmZGgs.js} +1 -1
- package/src/assets/web-panel/assets/{index-DfSSy9uy.js → index-BRWhLbWF.js} +1 -1
- package/src/assets/web-panel/assets/{index-GcKOHD_c.js → index-BTlc-Bve.js} +1 -1
- package/src/assets/web-panel/assets/{index-BHvlm0In.js → index-BY1wexYG.js} +1 -1
- package/src/assets/web-panel/assets/{index-Cvak6Oe2.js → index-BcUenmCX.js} +1 -1
- package/src/assets/web-panel/assets/{index-CKyd472S.js → index-BeiqkxJG.js} +1 -1
- package/src/assets/web-panel/assets/{index-DvFhhe6r.js → index-BhXZEUAc.js} +1 -1
- package/src/assets/web-panel/assets/{index-DBFmcaCQ.js → index-By5jBtkV.js} +1 -1
- package/src/assets/web-panel/assets/{index-DqDSF2RW.js → index-CLc19alH.js} +1 -1
- package/src/assets/web-panel/assets/{index-DeGBoLQA.js → index-CMVvxIS8.js} +1 -1
- package/src/assets/web-panel/assets/{index-FyplHuNt.js → index-C_B9rFQE.js} +1 -1
- package/src/assets/web-panel/assets/{index-CeUpKjvi.js → index-CaIS_TNX.js} +1 -1
- package/src/assets/web-panel/assets/{index-BRa4kJ_S.js → index-CawpdGTW.js} +1 -1
- package/src/assets/web-panel/assets/index-ChAzPigF.js +1 -0
- package/src/assets/web-panel/assets/{index-QsgfSZrV.js → index-CpumS98o.js} +1 -1
- package/src/assets/web-panel/assets/{index-BDF6EQBs.js → index-Cr4rjlW5.js} +1 -1
- package/src/assets/web-panel/assets/{index-rS3gl_68.js → index-CrUgDQkf.js} +1 -1
- package/src/assets/web-panel/assets/{index-D4n1lGTB.js → index-CtjLcCNU.js} +1 -1
- package/src/assets/web-panel/assets/{index-ifxmu8SY.js → index-DUkVN794.js} +1 -1
- package/src/assets/web-panel/assets/{index-BTCXf1t-.js → index-D_SePDWj.js} +1 -1
- package/src/assets/web-panel/assets/{index-Bbxjfstq.js → index-DaCCy6lq.js} +1 -1
- package/src/assets/web-panel/assets/{index-D9OE8B3d.js → index-DdefYBSw.js} +1 -1
- package/src/assets/web-panel/assets/{index-CG0lY4h3.js → index-DePOeMDM.js} +1 -1
- package/src/assets/web-panel/assets/{index-Bx4d6c1k.js → index-DgPvuIn2.js} +1 -1
- package/src/assets/web-panel/assets/{index-Z8P4BexE.js → index-FJ3zC9LK.js} +1 -1
- package/src/assets/web-panel/assets/{index-ByzGvpR9.js → index-_PHrIO4O.js} +1 -1
- package/src/assets/web-panel/assets/{index-DwfvPe-j.js → index-fU7wNHDB.js} +1 -1
- package/src/assets/web-panel/assets/{index-CcZ9xJI9.js → index-iYQNU9za.js} +1 -1
- package/src/assets/web-panel/assets/{index-CbD_WW_6.js → index-vIXOpcjD.js} +1 -1
- package/src/assets/web-panel/assets/{initDefaultProps-pmfaD-aK.js → initDefaultProps-D1oZNz0D.js} +1 -1
- package/src/assets/web-panel/assets/{motion-CaQ2CpYF.js → motion-C8k6doMO.js} +1 -1
- package/src/assets/web-panel/assets/{move-CkKTqNbI.js → move-DJ4qSbYt.js} +1 -1
- package/src/assets/web-panel/assets/{mtc-parser-Dd4xsgRI.js → mtc-parser-CdpJD85j.js} +1 -1
- package/src/assets/web-panel/assets/{omit-BFuA5YEs.js → omit-B0V4slKA.js} +1 -1
- package/src/assets/web-panel/assets/{pickAttrs-DDfxOAJc.js → pickAttrs-Di5NiW1F.js} +1 -1
- package/src/assets/web-panel/assets/{placementArrow-Be595JCp.js → placementArrow-B5OMHgEM.js} +1 -1
- package/src/assets/web-panel/assets/{responsiveObserve-7byljUM3.js → responsiveObserve-C6U9IWql.js} +1 -1
- package/src/assets/web-panel/assets/{slide-CTWfOTaY.js → slide-BMyTH3rN.js} +1 -1
- package/src/assets/web-panel/assets/{statusUtils-CNZOuIxM.js → statusUtils-C7d6BG7Z.js} +1 -1
- package/src/assets/web-panel/assets/{styleChecker-DwOcBV78.js → styleChecker-CR50QnQy.js} +1 -1
- package/src/assets/web-panel/assets/{useFlexGapSupport-B6MNwAO9.js → useFlexGapSupport-DBEeoMb8.js} +1 -1
- package/src/assets/web-panel/assets/{useFs-CzyQjH9r.js → useFs-3r099cjv.js} +1 -1
- package/src/assets/web-panel/assets/{usePersonalDataHub-Dxh3KiVA.js → usePersonalDataHub-C5IYNdTK.js} +1 -1
- package/src/assets/web-panel/assets/{vnode-DVfZiS5N.js → vnode-DmEOLRHf.js} +1 -1
- package/src/assets/web-panel/assets/{zoom-BYme7fbY.js → zoom-DnpUiVCB.js} +1 -1
- package/src/assets/web-panel/index.html +1 -1
- package/src/cli-help.js +181 -0
- package/src/command-help-index.json +181 -0
- package/src/command-manifest.json +1271 -175
- package/src/command-surface-policy.js +312 -0
- package/src/commands/agent.js +76 -33
- package/src/commands/artifacts.js +400 -2
- package/src/commands/background-session.js +41 -3
- package/src/commands/checkpoint-restore-recovery.js +1476 -0
- package/src/commands/checkpoint.js +947 -22
- package/src/commands/compact.js +101 -25
- package/src/commands/config.js +506 -20
- package/src/commands/doctor.js +4 -1
- package/src/commands/hub.js +1 -1
- package/src/commands/mcp.js +688 -24
- package/src/commands/pack.js +16 -2
- package/src/commands/plugin.js +20 -12
- package/src/commands/session-mcp-recovery.js +218 -0
- package/src/commands/session.js +470 -110
- package/src/commands/setup.js +36 -10
- package/src/commands/skill.js +181 -110
- package/src/commands/status.js +21 -5
- package/src/commands/update.js +68 -6
- package/src/constants.js +11 -0
- package/src/data/changelog.json +14 -1
- package/src/gateways/ws/action-protocol.js +10 -0
- package/src/gateways/ws/session-protocol.js +555 -27
- package/src/gateways/ws/ws-agent-handler.js +541 -14
- package/src/gateways/ws/ws-session-gateway.js +129 -22
- package/src/gateways/ws/ws-session-state.js +431 -0
- package/src/harness/background-task-manager.js +233 -36
- package/src/harness/jsonl-session-store.js +2551 -167
- package/src/harness/mcp-client.js +802 -61
- package/src/harness/prompt-compressor.js +227 -27
- package/src/harness/session-index.js +89 -38
- package/src/harness/session-list-index.js +254 -0
- package/src/harness/structured-handoff.js +410 -0
- package/src/lazy-dispatch.js +747 -84
- package/src/lib/__tests__/logger.test.js +50 -2
- package/src/lib/advisor-runtime.js +1047 -0
- package/src/lib/agent-core.js +1 -0
- package/src/lib/agent-sandbox.js +120 -26
- package/src/lib/agent-session-export.js +20 -0
- package/src/lib/agent-team/team-runner.js +230 -8
- package/src/lib/artifact-store.js +131 -8
- package/src/lib/background-agent-supervisor.js +185 -13
- package/src/lib/background-interaction-journal.js +37 -9
- package/src/lib/background-launch-profile.js +1058 -0
- package/src/lib/checkpoint-restore-already-completed-controller.js +902 -0
- package/src/lib/checkpoint-restore-orchestrator.js +987 -0
- package/src/lib/checkpoint-restore-partial-rollback-controller.js +1953 -0
- package/src/lib/checkpoint-restore-recovery-controller.js +689 -0
- package/src/lib/checkpoint-restore-recovery.js +884 -0
- package/src/lib/checkpoint-restore-retention.js +126 -0
- package/src/lib/checkpoint-restore-saga.js +5079 -0
- package/src/lib/checkpoint-restore-session-recovery.js +1178 -0
- package/src/lib/checkpoint-restore-workspace-target-verifier.js +270 -0
- package/src/lib/checkpoint-store.js +1688 -97
- package/src/lib/checkpoint-timeline-authority.js +522 -0
- package/src/lib/checkpoint-timeline.js +642 -0
- package/src/lib/config-keys.js +18 -119
- package/src/lib/config-manager.js +446 -27
- package/src/lib/config-redaction.js +57 -0
- package/src/lib/config-schema.js +853 -0
- package/src/lib/cowork-mcp-tools.js +5 -0
- package/src/lib/cowork-task-runner.js +458 -63
- package/src/lib/delivery-coordinator.js +1234 -0
- package/src/lib/delivery-evidence.js +450 -0
- package/src/lib/doctor-checkup.js +199 -14
- package/src/lib/executable-path.js +34 -0
- package/src/lib/fatal-handler.js +16 -0
- package/src/lib/file-checkpoint.js +4909 -186
- package/src/lib/file-lines.js +125 -0
- package/src/lib/headless-config-command.js +16 -5
- package/src/lib/hook-runner.cjs +139 -38
- package/src/lib/hooks-v2-workspace-context.js +10 -0
- package/src/lib/impacted-gate-selector.js +424 -0
- package/src/lib/interaction-adapter.js +62 -0
- package/src/lib/jsonl-session-store.js +1 -35
- package/src/lib/logger.js +66 -14
- package/src/lib/mcp-call-ledger-store.js +1069 -0
- package/src/lib/mcp-call-ledger.js +747 -0
- package/src/lib/mcp-client.js +5 -0
- package/src/lib/mcp-conflict-scheduler.js +468 -0
- package/src/lib/mcp-effect-contract.js +102 -0
- package/src/lib/mcp-headers-helper-trust.js +145 -0
- package/src/lib/mcp-headers-helper.js +616 -0
- package/src/lib/mcp-host-recovery-runtime.js +131 -0
- package/src/lib/mcp-ledger-recovery-admission.js +1065 -0
- package/src/lib/mcp-recovery-adjudication.js +443 -0
- package/src/lib/output-context.js +86 -0
- package/src/lib/packer/file-identity.js +170 -0
- package/src/lib/packer/index.js +3 -0
- package/src/lib/packer/native-update-state.js +277 -0
- package/src/lib/packer/pack-update-applier.js +1983 -136
- package/src/lib/packer/pack-update-checker.js +34 -0
- package/src/lib/packer/pack-update-downloader.js +875 -86
- package/src/lib/packer/pack-update-signature.js +86 -0
- package/src/lib/packer/pkg-config-generator.js +6 -0
- package/src/lib/paths.js +65 -10
- package/src/lib/plan-mode.js +831 -14
- package/src/lib/plan-persistence.js +540 -0
- package/src/lib/plugin-runtime/hooks.js +227 -69
- package/src/lib/plugin-runtime/plugin-options.js +189 -44
- package/src/lib/pr-automation-policy.js +146 -8
- package/src/lib/process-execution-broker/credential-agent.js +7 -0
- package/src/lib/process-execution-broker/index.js +53 -8
- package/src/lib/process-execution-broker/workspace-transaction.js +976 -73
- package/src/lib/project-instructions.js +165 -29
- package/src/lib/project-mcp-trust.js +67 -0
- package/src/lib/public-ide-capability-manifest.js +278 -0
- package/src/lib/public-ide-capability-validation.js +351 -0
- package/src/lib/secret-store.js +267 -43
- package/src/lib/secure-fs.js +1089 -0
- package/src/lib/security-audit.js +58 -0
- package/src/lib/service-manager.js +34 -13
- package/src/lib/session-budget-runtime.js +1452 -0
- package/src/lib/session-host-snapshot.js +388 -0
- package/src/lib/session-message-provenance.js +429 -0
- package/src/lib/session-projection.js +804 -0
- package/src/lib/session-resource-budget.js +1495 -0
- package/src/lib/settings-hooks.cjs +138 -22
- package/src/lib/settings-loader.cjs +25 -2
- package/src/lib/side-effect-ledger-store.js +45 -23
- package/src/lib/skill-execution-identity.js +217 -0
- package/src/lib/skill-loader.js +299 -18
- package/src/lib/sub-agent-context.js +236 -28
- package/src/lib/sub-agent-registry.js +5 -0
- package/src/lib/subagent-contract.js +94 -0
- package/src/lib/todo-manager.js +185 -18
- package/src/lib/todo-persistence.js +417 -0
- package/src/lib/turn-binding-store.js +41 -23
- package/src/lib/with-file-lock.js +25 -1
- package/src/lib/ws-chat-handler.js +21 -0
- package/src/program-base.js +18 -0
- package/src/repl/advisor-command.js +103 -0
- package/src/repl/agent-repl.js +2332 -154
- package/src/repl/btw-command.js +93 -10
- package/src/repl/clipboard-image.js +119 -0
- package/src/repl/config-summary.js +64 -108
- package/src/repl/prompt-editor.js +233 -0
- package/src/repl/prompt-interactions.js +404 -0
- package/src/repl/prompt-stash.js +354 -0
- package/src/repl/prompt-suggestions.js +312 -0
- package/src/repl/repl-keybindings.js +227 -0
- package/src/repl/session-recap.js +217 -0
- package/src/repl/slash-command-registry.js +25 -4
- package/src/repl/terminal-layout.js +88 -0
- package/src/runtime/agent-core.js +1264 -325
- package/src/runtime/coding-agent-contract-shared.cjs +13 -1
- package/src/runtime/coding-agent-managed-tool-policy.cjs +7 -2
- package/src/runtime/diagnostics.js +32 -13
- package/src/runtime/headless-runner.js +298 -118
- package/src/runtime/headless-stream.js +353 -95
- package/src/runtime/mcp-config.js +148 -14
- package/src/runtime/status-diagnostics-lite.js +137 -0
- package/src/assets/web-panel/assets/ChatBubbleRenderer-DDHDpBBA.js +0 -1
- package/src/assets/web-panel/assets/MarkdownRenderer-TabqHW9B.js +0 -1
- package/src/assets/web-panel/assets/RemoteSession-B0rkE09d.js +0 -5
- package/src/assets/web-panel/assets/WorkflowEditor-tzdyUk-1.js +0 -1
- package/src/assets/web-panel/assets/devWarning-DIrncrV1.js +0 -1
- package/src/assets/web-panel/assets/index-D-Swwqld.js +0 -1
- package/src/assets/web-panel/assets/index-FMZAMKy8.js +0 -1
package/src/repl/agent-repl.js
CHANGED
|
@@ -22,6 +22,8 @@ import chalk from "chalk";
|
|
|
22
22
|
import fs from "fs";
|
|
23
23
|
import os from "os";
|
|
24
24
|
import path from "path";
|
|
25
|
+
import { randomUUID } from "node:crypto";
|
|
26
|
+
import { isPromise, isProxy } from "node:util/types";
|
|
25
27
|
import { logger } from "../lib/logger.js";
|
|
26
28
|
import { getPlanModeManager, PlanState } from "../lib/plan-mode.js";
|
|
27
29
|
import { createVimState, feedNormalKey } from "../lib/repl-vim.js";
|
|
@@ -45,15 +47,35 @@ import {
|
|
|
45
47
|
startSession as jsonlStartSession,
|
|
46
48
|
appendUserMessage,
|
|
47
49
|
appendAssistantMessage,
|
|
48
|
-
|
|
50
|
+
appendCompactEventIfMessagesMatch,
|
|
49
51
|
appendTokenUsage,
|
|
50
52
|
appendToolCallCompact,
|
|
51
53
|
appendLlmRetryCompact,
|
|
52
54
|
appendEvent,
|
|
53
|
-
|
|
55
|
+
appendAuthorityEvent,
|
|
56
|
+
isUnsafeSessionId,
|
|
54
57
|
sessionExists,
|
|
58
|
+
forkSession,
|
|
55
59
|
} from "../harness/jsonl-session-store.js";
|
|
56
60
|
import { classifyStreamRetryReason } from "../lib/stream-retry.js";
|
|
61
|
+
import {
|
|
62
|
+
createSessionMcpLedgerSink,
|
|
63
|
+
formatMcpLedgerRecoveryNotice,
|
|
64
|
+
loadMcpLedgerRecovery,
|
|
65
|
+
} from "../lib/mcp-call-ledger-store.js";
|
|
66
|
+
import { createMcpHostRecoveryRuntime } from "../lib/mcp-host-recovery-runtime.js";
|
|
67
|
+
import {
|
|
68
|
+
isVerifiedSessionHostSnapshot,
|
|
69
|
+
readSessionHostResumeState,
|
|
70
|
+
} from "../lib/session-host-snapshot.js";
|
|
71
|
+
import {
|
|
72
|
+
preserveDurableSystemMessageProvenance,
|
|
73
|
+
projectCanonicalResumeMessages,
|
|
74
|
+
} from "../lib/session-message-provenance.js";
|
|
75
|
+
import {
|
|
76
|
+
MCP_RECOVERY_INVALID_CODE,
|
|
77
|
+
classifyMcpRecoveryAdmission,
|
|
78
|
+
} from "../lib/mcp-ledger-recovery-admission.js";
|
|
57
79
|
import { CLISkillLoader } from "../lib/skill-loader.js";
|
|
58
80
|
import { storeMemory, consolidateMemory } from "../lib/hierarchical-memory.js";
|
|
59
81
|
import { CLIContextEngineering } from "../lib/cli-context-engineering.js";
|
|
@@ -87,10 +109,11 @@ import {
|
|
|
87
109
|
import { HookEvents } from "../lib/hook-manager.js";
|
|
88
110
|
import { IterationBudget } from "../lib/iteration-budget.js";
|
|
89
111
|
import { resolveAgentMcp } from "../runtime/mcp-config.js";
|
|
90
|
-
import {
|
|
112
|
+
import { mergeConsecutiveMessages } from "../runtime/message-roles.js";
|
|
91
113
|
import {
|
|
92
114
|
AGENT_TOOLS,
|
|
93
115
|
buildSystemPrompt,
|
|
116
|
+
chatWithTools,
|
|
94
117
|
executeTool as coreExecuteTool,
|
|
95
118
|
agentLoop as coreAgentLoop,
|
|
96
119
|
formatToolArgs,
|
|
@@ -100,7 +123,7 @@ import {
|
|
|
100
123
|
} from "../runtime/agent-core.js";
|
|
101
124
|
import { formatBackgroundTasks } from "./tasks-status.js";
|
|
102
125
|
import { expandFileRefsAsync } from "../runtime/file-ref-expander.js";
|
|
103
|
-
import { prepareVisionTurn } from "../lib/image-input.js";
|
|
126
|
+
import { prepareVisionTurn, resolveVisionLlm } from "../lib/image-input.js";
|
|
104
127
|
import { composeSystemPrompt } from "../runtime/system-prompt.js";
|
|
105
128
|
import { installPipeSafety } from "../runtime/pipe-safety.js";
|
|
106
129
|
import {
|
|
@@ -113,9 +136,19 @@ import { newCostStore, addUsage } from "./session-cost.js";
|
|
|
113
136
|
import { extractPluginUsageAttribution } from "../lib/plugin-usage-attribution.js";
|
|
114
137
|
import { formatManagedCheckpointEvent } from "../lib/managed-checkpoint-render.js";
|
|
115
138
|
import { parseThinkCommand, parseEffortCommand } from "./think-command.js";
|
|
116
|
-
import {
|
|
139
|
+
import {
|
|
140
|
+
parseBtwCommand,
|
|
141
|
+
parseNoteNextCommand,
|
|
142
|
+
runBtwQuestion,
|
|
143
|
+
buildAsideBlock,
|
|
144
|
+
applyAside,
|
|
145
|
+
} from "./btw-command.js";
|
|
117
146
|
import { shouldStreamLive } from "./stream-decision.js";
|
|
118
147
|
import { emptyTurnNotice } from "./empty-turn-notice.js";
|
|
148
|
+
import {
|
|
149
|
+
createPromptInteractionSurface,
|
|
150
|
+
mergeClipboardImageChips,
|
|
151
|
+
} from "./prompt-interactions.js";
|
|
119
152
|
import {
|
|
120
153
|
buildPermissionPrompt,
|
|
121
154
|
resolveAskIdleTimeoutMs,
|
|
@@ -296,11 +329,11 @@ export async function agentLoop(messages, options) {
|
|
|
296
329
|
// IN PLACE: `coreAgentLoop` mutates this same array (appending assistant/tool
|
|
297
330
|
// turns), and the REPL reuses it across turns, so folding a copy would leave
|
|
298
331
|
// the degenerate `[user, user]` pair in the persistent history and re-break
|
|
299
|
-
// the next turn.
|
|
300
|
-
//
|
|
301
|
-
//
|
|
332
|
+
// the next turn. The tail helper validates the complete raw transcript first
|
|
333
|
+
// and folds only an exact plain `{role, content}` pair, so recovery authority
|
|
334
|
+
// can never disappear during this live one-shot normalization.
|
|
302
335
|
if (options.mergeRoles) {
|
|
303
|
-
|
|
336
|
+
collapseValidatedPlainReplTailInPlace(messages);
|
|
304
337
|
}
|
|
305
338
|
const usageEvents = [];
|
|
306
339
|
// Visible cross-vendor fallback notice: a silent switch from the configured
|
|
@@ -478,21 +511,1563 @@ export async function agentLoop(messages, options) {
|
|
|
478
511
|
} else if (event.type === "response-complete") {
|
|
479
512
|
return { content: event.content, usageEvents, thinking: event.thinking };
|
|
480
513
|
}
|
|
481
|
-
}
|
|
482
|
-
return { content: "", usageEvents };
|
|
514
|
+
}
|
|
515
|
+
return { content: "", usageEvents };
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
const REPL_MCP_RECOVERY_CANDIDATES = new WeakSet();
|
|
519
|
+
const REPL_JSONL_RESUME_CANDIDATES = new WeakSet();
|
|
520
|
+
const REPL_JSONL_RESUME_ABSENCE_CANDIDATES = new WeakSet();
|
|
521
|
+
const REPL_NATIVE_PROMISE = Promise;
|
|
522
|
+
const REPL_NATIVE_PROMISE_PROTOTYPE = Promise.prototype;
|
|
523
|
+
const REPL_NATIVE_PROMISE_THEN = Promise.prototype.then;
|
|
524
|
+
const REPL_NATIVE_PROMISE_CONSTRUCTOR_DESCRIPTOR = Object.freeze({
|
|
525
|
+
...Object.getOwnPropertyDescriptor(Promise.prototype, "constructor"),
|
|
526
|
+
});
|
|
527
|
+
const REPL_NATIVE_PROMISE_SPECIES_DESCRIPTOR = Object.freeze({
|
|
528
|
+
...Object.getOwnPropertyDescriptor(Promise, Symbol.species),
|
|
529
|
+
});
|
|
530
|
+
const REPL_SAFE_PROMISE_CONSTRUCTOR = Object.freeze(
|
|
531
|
+
Object.defineProperty(Object.create(null), Symbol.species, {
|
|
532
|
+
configurable: false,
|
|
533
|
+
enumerable: false,
|
|
534
|
+
writable: false,
|
|
535
|
+
value: null,
|
|
536
|
+
}),
|
|
537
|
+
);
|
|
538
|
+
const REPL_NATIVE_PROMISE_REJECTION_HANDLER = () => {};
|
|
539
|
+
const REPL_PAYLOAD_DIGEST = /^sha256:[0-9a-f]{64}$/;
|
|
540
|
+
const REPL_AUTHORITY_HASH = /^[0-9a-f]{64}$/;
|
|
541
|
+
const REPL_RESUME_SESSION_ID_MAX_BYTES = 128;
|
|
542
|
+
const REPL_RESUME_SESSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._@-]*$/;
|
|
543
|
+
const REPL_WINDOWS_DEVICE_NAME =
|
|
544
|
+
/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i;
|
|
545
|
+
const REPL_RESUME_ROLES = new Set(["system", "user", "assistant", "tool"]);
|
|
546
|
+
const REPL_MCP_EFFECTS = new Set(["read", "unknown", "write", "destructive"]);
|
|
547
|
+
const REPL_REPLAY_DENY_FIELDS = new Set([
|
|
548
|
+
"ledgerId",
|
|
549
|
+
"serverName",
|
|
550
|
+
"toolName",
|
|
551
|
+
"inputBytes",
|
|
552
|
+
"replayDigest",
|
|
553
|
+
]);
|
|
554
|
+
const REPL_MCP_REMEDIATIONS = new Set([
|
|
555
|
+
"inspect_transcript",
|
|
556
|
+
"adjudicate_started_calls",
|
|
557
|
+
"exact_replay_denied",
|
|
558
|
+
]);
|
|
559
|
+
|
|
560
|
+
function invalidReplRecovery(message, code = MCP_RECOVERY_INVALID_CODE) {
|
|
561
|
+
const error = new TypeError(message);
|
|
562
|
+
error.code = code;
|
|
563
|
+
return error;
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
function validateReplResumeSessionId(sessionId) {
|
|
567
|
+
if (
|
|
568
|
+
isUnsafeSessionId(sessionId) ||
|
|
569
|
+
Buffer.byteLength(sessionId, "utf8") > REPL_RESUME_SESSION_ID_MAX_BYTES ||
|
|
570
|
+
!REPL_RESUME_SESSION_ID_PATTERN.test(sessionId) ||
|
|
571
|
+
REPL_WINDOWS_DEVICE_NAME.test(sessionId) ||
|
|
572
|
+
sessionId.endsWith(".") ||
|
|
573
|
+
sessionId.normalize("NFC") !== sessionId
|
|
574
|
+
) {
|
|
575
|
+
throw invalidReplRecovery(
|
|
576
|
+
"REPL resume session id is invalid",
|
|
577
|
+
"CC_REPL_SESSION_ID_INVALID",
|
|
578
|
+
);
|
|
579
|
+
}
|
|
580
|
+
return sessionId;
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
function brandedFrozenCandidate(brand, value) {
|
|
584
|
+
const candidate = Object.freeze(value);
|
|
585
|
+
brand.add(candidate);
|
|
586
|
+
return candidate;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
function safeRecoveryErrorValue(error, key, fallback) {
|
|
590
|
+
try {
|
|
591
|
+
if (error && !isProxy(error)) {
|
|
592
|
+
const descriptor = Object.getOwnPropertyDescriptor(error, key);
|
|
593
|
+
if (descriptor && "value" in descriptor) return descriptor.value;
|
|
594
|
+
}
|
|
595
|
+
} catch {
|
|
596
|
+
// Malformed errors are diagnostic input, never recovery authority.
|
|
597
|
+
}
|
|
598
|
+
return fallback;
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
function replMcpRecoveryError(error, fallbackCode) {
|
|
602
|
+
const message = safeRecoveryErrorValue(
|
|
603
|
+
error,
|
|
604
|
+
"message",
|
|
605
|
+
"REPL session recovery failed",
|
|
606
|
+
);
|
|
607
|
+
let cause = new Error("REPL session recovery failed");
|
|
608
|
+
try {
|
|
609
|
+
if (!isProxy(error) && error instanceof Error) cause = error;
|
|
610
|
+
} catch {
|
|
611
|
+
// Keep the inert fallback cause for hostile diagnostic objects.
|
|
612
|
+
}
|
|
613
|
+
const wrapped = new Error(
|
|
614
|
+
typeof message === "string" && message
|
|
615
|
+
? message
|
|
616
|
+
: "REPL session recovery failed",
|
|
617
|
+
{ cause },
|
|
618
|
+
);
|
|
619
|
+
const code = safeRecoveryErrorValue(error, "code", fallbackCode);
|
|
620
|
+
wrapped.code = typeof code === "string" && code ? code : fallbackCode;
|
|
621
|
+
return wrapped;
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
function samePropertyDescriptor(actual, expected) {
|
|
625
|
+
if (!actual || !expected) return actual === expected;
|
|
626
|
+
if (
|
|
627
|
+
actual.configurable !== expected.configurable ||
|
|
628
|
+
actual.enumerable !== expected.enumerable
|
|
629
|
+
) {
|
|
630
|
+
return false;
|
|
631
|
+
}
|
|
632
|
+
if ("value" in expected) {
|
|
633
|
+
return (
|
|
634
|
+
"value" in actual &&
|
|
635
|
+
actual.value === expected.value &&
|
|
636
|
+
actual.writable === expected.writable
|
|
637
|
+
);
|
|
638
|
+
}
|
|
639
|
+
return (
|
|
640
|
+
!("value" in actual) &&
|
|
641
|
+
actual.get === expected.get &&
|
|
642
|
+
actual.set === expected.set
|
|
643
|
+
);
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
function unconsumableNativePromise(subject) {
|
|
647
|
+
return invalidReplRecovery(
|
|
648
|
+
`${subject} is a native Promise with an unsafe non-configurable constructor; ` +
|
|
649
|
+
"its producer must observe the rejection",
|
|
650
|
+
"CC_REPL_NATIVE_PROMISE_UNCONSUMABLE",
|
|
651
|
+
);
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
function consumeNativeReplPromise(value, subject) {
|
|
655
|
+
const prototype = Object.getPrototypeOf(value);
|
|
656
|
+
if (isProxy(prototype)) throw unconsumableNativePromise(subject);
|
|
657
|
+
|
|
658
|
+
const constructorDescriptor = Object.getOwnPropertyDescriptor(
|
|
659
|
+
value,
|
|
660
|
+
"constructor",
|
|
661
|
+
);
|
|
662
|
+
const intrinsicSpeciesIntact = samePropertyDescriptor(
|
|
663
|
+
Object.getOwnPropertyDescriptor(REPL_NATIVE_PROMISE, Symbol.species),
|
|
664
|
+
REPL_NATIVE_PROMISE_SPECIES_DESCRIPTOR,
|
|
665
|
+
);
|
|
666
|
+
const inheritedIntrinsicConstructor =
|
|
667
|
+
!constructorDescriptor &&
|
|
668
|
+
prototype === REPL_NATIVE_PROMISE_PROTOTYPE &&
|
|
669
|
+
samePropertyDescriptor(
|
|
670
|
+
Object.getOwnPropertyDescriptor(
|
|
671
|
+
REPL_NATIVE_PROMISE_PROTOTYPE,
|
|
672
|
+
"constructor",
|
|
673
|
+
),
|
|
674
|
+
REPL_NATIVE_PROMISE_CONSTRUCTOR_DESCRIPTOR,
|
|
675
|
+
) &&
|
|
676
|
+
intrinsicSpeciesIntact;
|
|
677
|
+
const ownIntrinsicConstructor =
|
|
678
|
+
constructorDescriptor &&
|
|
679
|
+
"value" in constructorDescriptor &&
|
|
680
|
+
(constructorDescriptor.value === undefined ||
|
|
681
|
+
(constructorDescriptor.value === REPL_NATIVE_PROMISE &&
|
|
682
|
+
intrinsicSpeciesIntact));
|
|
683
|
+
|
|
684
|
+
if (inheritedIntrinsicConstructor || ownIntrinsicConstructor) {
|
|
685
|
+
Reflect.apply(REPL_NATIVE_PROMISE_THEN, value, [
|
|
686
|
+
undefined,
|
|
687
|
+
REPL_NATIVE_PROMISE_REJECTION_HANDLER,
|
|
688
|
+
]);
|
|
689
|
+
return;
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
const canShadow = constructorDescriptor
|
|
693
|
+
? constructorDescriptor.configurable === true
|
|
694
|
+
: Object.isExtensible(value);
|
|
695
|
+
if (!canShadow) {
|
|
696
|
+
// Promise.prototype.then necessarily performs SpeciesConstructor, which
|
|
697
|
+
// would execute this hostile constructor/accessor. ECMAScript exposes no
|
|
698
|
+
// separate hook-free operation that marks a rejection handled. Fail closed
|
|
699
|
+
// without pretending the Promise was consumed; the producer must have
|
|
700
|
+
// attached its own rejection observer before returning this invalid value.
|
|
701
|
+
throw unconsumableNativePromise(subject);
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
Object.defineProperty(value, "constructor", {
|
|
705
|
+
configurable: true,
|
|
706
|
+
enumerable: constructorDescriptor?.enumerable ?? false,
|
|
707
|
+
writable: false,
|
|
708
|
+
value: REPL_SAFE_PROMISE_CONSTRUCTOR,
|
|
709
|
+
});
|
|
710
|
+
try {
|
|
711
|
+
Reflect.apply(REPL_NATIVE_PROMISE_THEN, value, [
|
|
712
|
+
undefined,
|
|
713
|
+
REPL_NATIVE_PROMISE_REJECTION_HANDLER,
|
|
714
|
+
]);
|
|
715
|
+
} finally {
|
|
716
|
+
if (constructorDescriptor) {
|
|
717
|
+
Object.defineProperty(value, "constructor", constructorDescriptor);
|
|
718
|
+
} else {
|
|
719
|
+
Reflect.deleteProperty(value, "constructor");
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
function synchronousReplRecoveryValue(value, subject) {
|
|
725
|
+
if (
|
|
726
|
+
value === null ||
|
|
727
|
+
value === undefined ||
|
|
728
|
+
(typeof value !== "object" && typeof value !== "function")
|
|
729
|
+
) {
|
|
730
|
+
return value;
|
|
731
|
+
}
|
|
732
|
+
if (isProxy(value)) {
|
|
733
|
+
throw invalidReplRecovery(`${subject} must not be a Proxy`);
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
// Consume a genuine Promise before inspecting any user-controlled `then`
|
|
737
|
+
// descriptor. A Promise can shadow `then` with an accessor or data property;
|
|
738
|
+
// reading that descriptor first would leave an already-rejected Promise
|
|
739
|
+
// unobserved even though the recovery boundary correctly rejected it.
|
|
740
|
+
if (isPromise(value)) {
|
|
741
|
+
consumeNativeReplPromise(value, subject);
|
|
742
|
+
throw invalidReplRecovery(`${subject} must be returned synchronously`);
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
let prototype = value;
|
|
746
|
+
while (prototype) {
|
|
747
|
+
// An ordinary object can hide a Proxy in its prototype chain. Check every
|
|
748
|
+
// level before reflection so no getOwnPropertyDescriptor/getPrototypeOf
|
|
749
|
+
// trap is executed while rejecting untrusted recovery evidence.
|
|
750
|
+
if (isProxy(prototype)) {
|
|
751
|
+
throw invalidReplRecovery(`${subject} must not inherit from a Proxy`);
|
|
752
|
+
}
|
|
753
|
+
const thenDescriptor = Object.getOwnPropertyDescriptor(prototype, "then");
|
|
754
|
+
if (thenDescriptor) {
|
|
755
|
+
if (!("value" in thenDescriptor)) {
|
|
756
|
+
throw invalidReplRecovery(`${subject}.then must not be an accessor`);
|
|
757
|
+
}
|
|
758
|
+
if (typeof thenDescriptor.value === "function") {
|
|
759
|
+
// Never invoke an arbitrary user-supplied thenable capability.
|
|
760
|
+
throw invalidReplRecovery(`${subject} must be returned synchronously`);
|
|
761
|
+
}
|
|
762
|
+
break;
|
|
763
|
+
}
|
|
764
|
+
prototype = Object.getPrototypeOf(prototype);
|
|
765
|
+
}
|
|
766
|
+
return value;
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
function plainDataDescriptors(value, subject) {
|
|
770
|
+
synchronousReplRecoveryValue(value, subject);
|
|
771
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
772
|
+
throw invalidReplRecovery(`${subject} must be a plain data object`);
|
|
773
|
+
}
|
|
774
|
+
const prototype = Object.getPrototypeOf(value);
|
|
775
|
+
if (prototype !== Object.prototype && prototype !== null) {
|
|
776
|
+
throw invalidReplRecovery(`${subject} must have a plain prototype`);
|
|
777
|
+
}
|
|
778
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
779
|
+
for (const key of Reflect.ownKeys(descriptors)) {
|
|
780
|
+
if (typeof key === "symbol" || !("value" in descriptors[key])) {
|
|
781
|
+
throw invalidReplRecovery(`${subject} contains an accessor or symbol`);
|
|
782
|
+
}
|
|
783
|
+
}
|
|
784
|
+
return descriptors;
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
function dataDescriptorValue(
|
|
788
|
+
descriptors,
|
|
789
|
+
key,
|
|
790
|
+
subject,
|
|
791
|
+
{ required = true, fallback = null } = {},
|
|
792
|
+
) {
|
|
793
|
+
const descriptor = descriptors[key];
|
|
794
|
+
if (!descriptor) {
|
|
795
|
+
if (!required) return fallback;
|
|
796
|
+
throw invalidReplRecovery(`${subject}.${key} is missing`);
|
|
797
|
+
}
|
|
798
|
+
if (!("value" in descriptor)) {
|
|
799
|
+
throw invalidReplRecovery(`${subject}.${key} must be a data property`);
|
|
800
|
+
}
|
|
801
|
+
return descriptor.value;
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
function snapshotDataArray(value, subject, mapper) {
|
|
805
|
+
synchronousReplRecoveryValue(value, subject);
|
|
806
|
+
if (!Array.isArray(value) || isProxy(value)) {
|
|
807
|
+
throw invalidReplRecovery(`${subject} must be a non-Proxy array`);
|
|
808
|
+
}
|
|
809
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
810
|
+
for (const key of Reflect.ownKeys(descriptors)) {
|
|
811
|
+
if (typeof key === "symbol" || !("value" in descriptors[key])) {
|
|
812
|
+
throw invalidReplRecovery(`${subject} contains an accessor or symbol`);
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
const length = descriptors.length?.value;
|
|
816
|
+
if (!Number.isSafeInteger(length) || length < 0) {
|
|
817
|
+
throw invalidReplRecovery(`${subject}.length is invalid`);
|
|
818
|
+
}
|
|
819
|
+
const snapshots = [];
|
|
820
|
+
for (let index = 0; index < length; index += 1) {
|
|
821
|
+
const descriptor = descriptors[String(index)];
|
|
822
|
+
if (!descriptor || !("value" in descriptor)) {
|
|
823
|
+
throw invalidReplRecovery(`${subject}[${index}] is not plain data`);
|
|
824
|
+
}
|
|
825
|
+
snapshots.push(mapper(descriptor.value, index));
|
|
826
|
+
}
|
|
827
|
+
return Object.freeze(snapshots);
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
function requiredRecoveryString(value, subject, { nullable = false } = {}) {
|
|
831
|
+
if (value === null && nullable) return null;
|
|
832
|
+
if (typeof value !== "string" || (!nullable && !value)) {
|
|
833
|
+
throw invalidReplRecovery(`${subject} must be a string`);
|
|
834
|
+
}
|
|
835
|
+
return value;
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
function snapshotReplMcpRecord(record, index) {
|
|
839
|
+
const subject = `MCP recovery unsettled[${index}]`;
|
|
840
|
+
const descriptors = plainDataDescriptors(record, subject);
|
|
841
|
+
const effectContract = dataDescriptorValue(
|
|
842
|
+
descriptors,
|
|
843
|
+
"effectContract",
|
|
844
|
+
subject,
|
|
845
|
+
);
|
|
846
|
+
const effectDescriptors = plainDataDescriptors(
|
|
847
|
+
effectContract,
|
|
848
|
+
`${subject}.effectContract`,
|
|
849
|
+
);
|
|
850
|
+
const effect = requiredRecoveryString(
|
|
851
|
+
dataDescriptorValue(
|
|
852
|
+
effectDescriptors,
|
|
853
|
+
"effect",
|
|
854
|
+
`${subject}.effectContract`,
|
|
855
|
+
),
|
|
856
|
+
`${subject}.effectContract.effect`,
|
|
857
|
+
);
|
|
858
|
+
if (!REPL_MCP_EFFECTS.has(effect)) {
|
|
859
|
+
throw invalidReplRecovery(`${subject}.effectContract.effect is invalid`);
|
|
860
|
+
}
|
|
861
|
+
return Object.freeze({
|
|
862
|
+
ledgerId: requiredRecoveryString(
|
|
863
|
+
dataDescriptorValue(descriptors, "ledgerId", subject),
|
|
864
|
+
`${subject}.ledgerId`,
|
|
865
|
+
),
|
|
866
|
+
serverName: requiredRecoveryString(
|
|
867
|
+
dataDescriptorValue(descriptors, "serverName", subject),
|
|
868
|
+
`${subject}.serverName`,
|
|
869
|
+
),
|
|
870
|
+
toolName: requiredRecoveryString(
|
|
871
|
+
dataDescriptorValue(descriptors, "toolName", subject),
|
|
872
|
+
`${subject}.toolName`,
|
|
873
|
+
),
|
|
874
|
+
effectContract: Object.freeze({ effect }),
|
|
875
|
+
});
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
function snapshotReplMcpIncident(incident, index) {
|
|
879
|
+
const subject = `MCP recovery incidents[${index}]`;
|
|
880
|
+
const descriptors = plainDataDescriptors(incident, subject);
|
|
881
|
+
return Object.freeze({
|
|
882
|
+
code: requiredRecoveryString(
|
|
883
|
+
dataDescriptorValue(descriptors, "code", subject),
|
|
884
|
+
`${subject}.code`,
|
|
885
|
+
),
|
|
886
|
+
ledgerId: requiredRecoveryString(
|
|
887
|
+
dataDescriptorValue(descriptors, "ledgerId", subject, {
|
|
888
|
+
required: false,
|
|
889
|
+
fallback: null,
|
|
890
|
+
}),
|
|
891
|
+
`${subject}.ledgerId`,
|
|
892
|
+
{ nullable: true },
|
|
893
|
+
),
|
|
894
|
+
});
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
function snapshotReplReplayDeny(entry, index) {
|
|
898
|
+
const subject = `MCP recovery replayDenied[${index}]`;
|
|
899
|
+
const descriptors = plainDataDescriptors(entry, subject);
|
|
900
|
+
const fields = Object.keys(descriptors);
|
|
901
|
+
if (
|
|
902
|
+
fields.length !== REPL_REPLAY_DENY_FIELDS.size ||
|
|
903
|
+
fields.some((field) => !REPL_REPLAY_DENY_FIELDS.has(field))
|
|
904
|
+
) {
|
|
905
|
+
throw invalidReplRecovery(`${subject} has an invalid exact schema`);
|
|
906
|
+
}
|
|
907
|
+
const snapshot = Object.freeze({
|
|
908
|
+
ledgerId: requiredRecoveryString(
|
|
909
|
+
dataDescriptorValue(descriptors, "ledgerId", subject),
|
|
910
|
+
`${subject}.ledgerId`,
|
|
911
|
+
),
|
|
912
|
+
serverName: requiredRecoveryString(
|
|
913
|
+
dataDescriptorValue(descriptors, "serverName", subject),
|
|
914
|
+
`${subject}.serverName`,
|
|
915
|
+
),
|
|
916
|
+
toolName: requiredRecoveryString(
|
|
917
|
+
dataDescriptorValue(descriptors, "toolName", subject),
|
|
918
|
+
`${subject}.toolName`,
|
|
919
|
+
),
|
|
920
|
+
inputBytes: dataDescriptorValue(descriptors, "inputBytes", subject),
|
|
921
|
+
replayDigest: requiredRecoveryString(
|
|
922
|
+
dataDescriptorValue(descriptors, "replayDigest", subject),
|
|
923
|
+
`${subject}.replayDigest`,
|
|
924
|
+
),
|
|
925
|
+
});
|
|
926
|
+
if (
|
|
927
|
+
!Number.isInteger(snapshot.inputBytes) ||
|
|
928
|
+
snapshot.inputBytes < 0 ||
|
|
929
|
+
!REPL_PAYLOAD_DIGEST.test(snapshot.replayDigest)
|
|
930
|
+
) {
|
|
931
|
+
throw invalidReplRecovery(`${subject} has an invalid exact identity`);
|
|
932
|
+
}
|
|
933
|
+
return snapshot;
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
function strictReplMcpRecoverySnapshot(recovery, sessionId) {
|
|
937
|
+
const descriptors = plainDataDescriptors(recovery, "MCP recovery");
|
|
938
|
+
const recoverySessionId = requiredRecoveryString(
|
|
939
|
+
dataDescriptorValue(descriptors, "sessionId", "MCP recovery"),
|
|
940
|
+
"MCP recovery.sessionId",
|
|
941
|
+
);
|
|
942
|
+
if (recoverySessionId !== sessionId) {
|
|
943
|
+
throw invalidReplRecovery("MCP recovery session does not match the target");
|
|
944
|
+
}
|
|
945
|
+
if (dataDescriptorValue(descriptors, "verified", "MCP recovery") !== true) {
|
|
946
|
+
throw invalidReplRecovery("MCP recovery was not verified");
|
|
947
|
+
}
|
|
948
|
+
const unsettled = snapshotDataArray(
|
|
949
|
+
dataDescriptorValue(descriptors, "unsettled", "MCP recovery"),
|
|
950
|
+
"MCP recovery.unsettled",
|
|
951
|
+
snapshotReplMcpRecord,
|
|
952
|
+
);
|
|
953
|
+
const incidents = snapshotDataArray(
|
|
954
|
+
dataDescriptorValue(descriptors, "incidents", "MCP recovery"),
|
|
955
|
+
"MCP recovery.incidents",
|
|
956
|
+
snapshotReplMcpIncident,
|
|
957
|
+
);
|
|
958
|
+
// Exact-replay denies are authority, not presentation samples. Preserve and
|
|
959
|
+
// freeze every entry: truncation would silently re-enable a denied call.
|
|
960
|
+
const replayDenied = snapshotDataArray(
|
|
961
|
+
dataDescriptorValue(descriptors, "replayDenied", "MCP recovery"),
|
|
962
|
+
"MCP recovery.replayDenied",
|
|
963
|
+
snapshotReplReplayDeny,
|
|
964
|
+
);
|
|
965
|
+
const headHash = requiredRecoveryString(
|
|
966
|
+
dataDescriptorValue(descriptors, "headHash", "MCP recovery"),
|
|
967
|
+
"MCP recovery.headHash",
|
|
968
|
+
{ nullable: true },
|
|
969
|
+
);
|
|
970
|
+
const recoveryDigest = requiredRecoveryString(
|
|
971
|
+
dataDescriptorValue(descriptors, "recoveryDigest", "MCP recovery"),
|
|
972
|
+
"MCP recovery.recoveryDigest",
|
|
973
|
+
);
|
|
974
|
+
const remediation = requiredRecoveryString(
|
|
975
|
+
dataDescriptorValue(descriptors, "remediation", "MCP recovery"),
|
|
976
|
+
"MCP recovery.remediation",
|
|
977
|
+
{ nullable: true },
|
|
978
|
+
);
|
|
979
|
+
if (
|
|
980
|
+
(headHash !== null && !REPL_AUTHORITY_HASH.test(headHash)) ||
|
|
981
|
+
!REPL_PAYLOAD_DIGEST.test(recoveryDigest) ||
|
|
982
|
+
(remediation !== null && !REPL_MCP_REMEDIATIONS.has(remediation))
|
|
983
|
+
) {
|
|
984
|
+
throw invalidReplRecovery("MCP recovery authority metadata is invalid");
|
|
985
|
+
}
|
|
986
|
+
const expectedRemediation =
|
|
987
|
+
incidents.length > 0
|
|
988
|
+
? "inspect_transcript"
|
|
989
|
+
: unsettled.length > 0
|
|
990
|
+
? "adjudicate_started_calls"
|
|
991
|
+
: replayDenied.length > 0
|
|
992
|
+
? "exact_replay_denied"
|
|
993
|
+
: null;
|
|
994
|
+
if (remediation !== expectedRemediation) {
|
|
995
|
+
throw invalidReplRecovery("MCP recovery remediation is inconsistent");
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
const snapshot = Object.freeze({
|
|
999
|
+
sessionId: recoverySessionId,
|
|
1000
|
+
verified: true,
|
|
1001
|
+
unsettled,
|
|
1002
|
+
incidents,
|
|
1003
|
+
replayDenied,
|
|
1004
|
+
headHash,
|
|
1005
|
+
recoveryDigest,
|
|
1006
|
+
remediation,
|
|
1007
|
+
});
|
|
1008
|
+
const admission = classifyMcpRecoveryAdmission(snapshot);
|
|
1009
|
+
if (admission.reasonCode) {
|
|
1010
|
+
throw invalidReplRecovery(
|
|
1011
|
+
"MCP recovery projection is malformed",
|
|
1012
|
+
admission.reasonCode,
|
|
1013
|
+
);
|
|
1014
|
+
}
|
|
1015
|
+
return snapshot;
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
function dependencyDataFunction(dependencies, key, fallback) {
|
|
1019
|
+
if (dependencies == null) return fallback;
|
|
1020
|
+
if (typeof dependencies !== "object" || isProxy(dependencies)) {
|
|
1021
|
+
throw invalidReplRecovery("REPL recovery dependencies are invalid");
|
|
1022
|
+
}
|
|
1023
|
+
const descriptor = Object.getOwnPropertyDescriptor(dependencies, key);
|
|
1024
|
+
if (!descriptor) return fallback;
|
|
1025
|
+
if (!("value" in descriptor) || typeof descriptor.value !== "function") {
|
|
1026
|
+
throw invalidReplRecovery(`REPL recovery dependency ${key} is invalid`);
|
|
1027
|
+
}
|
|
1028
|
+
return descriptor.value;
|
|
1029
|
+
}
|
|
1030
|
+
|
|
1031
|
+
function replMcpRecoveryFailureNotice(error, subject = "MCP call ledger") {
|
|
1032
|
+
return (
|
|
1033
|
+
`MCP recovery notice — the durable ${subject} could not be verified. ` +
|
|
1034
|
+
"Do not execute or retry MCP tools until the session transcript has " +
|
|
1035
|
+
`been inspected (${error?.code || "CC_MCP_LEDGER_EVENT_READ_FAILED"}).`
|
|
1036
|
+
);
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
function failClosedReplMcpRecoveryCandidate(
|
|
1040
|
+
sessionId,
|
|
1041
|
+
error,
|
|
1042
|
+
fallbackCode = "CC_MCP_LEDGER_EVENT_READ_FAILED",
|
|
1043
|
+
subject = "MCP call ledger",
|
|
1044
|
+
) {
|
|
1045
|
+
const recoveryError = replMcpRecoveryError(error, fallbackCode);
|
|
1046
|
+
return brandedFrozenCandidate(REPL_MCP_RECOVERY_CANDIDATES, {
|
|
1047
|
+
sessionId,
|
|
1048
|
+
recovery: null,
|
|
1049
|
+
recoveryError,
|
|
1050
|
+
notice: replMcpRecoveryFailureNotice(recoveryError, subject),
|
|
1051
|
+
});
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
/**
|
|
1055
|
+
* Read one target session's verified MCP recovery projection without mutating
|
|
1056
|
+
* the active REPL. Callers commit the returned candidate only after the rest
|
|
1057
|
+
* of a session switch (notably message rebuild) has succeeded.
|
|
1058
|
+
*/
|
|
1059
|
+
export function readReplMcpRecoveryCandidate(sessionId, dependencies = {}) {
|
|
1060
|
+
try {
|
|
1061
|
+
const loadRecovery = dependencyDataFunction(
|
|
1062
|
+
dependencies,
|
|
1063
|
+
"loadMcpLedgerRecovery",
|
|
1064
|
+
loadMcpLedgerRecovery,
|
|
1065
|
+
);
|
|
1066
|
+
const formatNotice = dependencyDataFunction(
|
|
1067
|
+
dependencies,
|
|
1068
|
+
"formatMcpLedgerRecoveryNotice",
|
|
1069
|
+
formatMcpLedgerRecoveryNotice,
|
|
1070
|
+
);
|
|
1071
|
+
return createReplMcpRecoveryCandidate(
|
|
1072
|
+
sessionId,
|
|
1073
|
+
synchronousReplRecoveryValue(
|
|
1074
|
+
loadRecovery(sessionId),
|
|
1075
|
+
"MCP recovery loader result",
|
|
1076
|
+
),
|
|
1077
|
+
formatNotice,
|
|
1078
|
+
);
|
|
1079
|
+
} catch (error) {
|
|
1080
|
+
return failClosedReplMcpRecoveryCandidate(sessionId, error);
|
|
1081
|
+
}
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
function createReplMcpRecoveryCandidate(
|
|
1085
|
+
sessionId,
|
|
1086
|
+
recoveryValue,
|
|
1087
|
+
formatNotice = formatMcpLedgerRecoveryNotice,
|
|
1088
|
+
) {
|
|
1089
|
+
try {
|
|
1090
|
+
const recovery = strictReplMcpRecoverySnapshot(recoveryValue, sessionId);
|
|
1091
|
+
let notice = synchronousReplRecoveryValue(
|
|
1092
|
+
formatNotice(recovery),
|
|
1093
|
+
"MCP recovery formatter result",
|
|
1094
|
+
);
|
|
1095
|
+
if (notice !== null && typeof notice !== "string") {
|
|
1096
|
+
throw invalidReplRecovery(
|
|
1097
|
+
"MCP recovery formatter must return a string or null",
|
|
1098
|
+
);
|
|
1099
|
+
}
|
|
1100
|
+
if (
|
|
1101
|
+
!notice &&
|
|
1102
|
+
(recovery.unsettled.length > 0 ||
|
|
1103
|
+
recovery.incidents.length > 0 ||
|
|
1104
|
+
recovery.replayDenied.length > 0)
|
|
1105
|
+
) {
|
|
1106
|
+
notice =
|
|
1107
|
+
"MCP recovery notice — interrupted MCP calls, ledger incidents, " +
|
|
1108
|
+
"or exact replay denies require explicit inspection before replay.";
|
|
1109
|
+
}
|
|
1110
|
+
return brandedFrozenCandidate(REPL_MCP_RECOVERY_CANDIDATES, {
|
|
1111
|
+
sessionId,
|
|
1112
|
+
recovery,
|
|
1113
|
+
recoveryError: null,
|
|
1114
|
+
notice: notice || null,
|
|
1115
|
+
});
|
|
1116
|
+
} catch (error) {
|
|
1117
|
+
return failClosedReplMcpRecoveryCandidate(sessionId, error);
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
function snapshotReplMessageValue(value, subject, ancestors = new WeakSet()) {
|
|
1122
|
+
if (
|
|
1123
|
+
value === null ||
|
|
1124
|
+
value === undefined ||
|
|
1125
|
+
typeof value === "string" ||
|
|
1126
|
+
typeof value === "boolean" ||
|
|
1127
|
+
(typeof value === "number" && Number.isFinite(value))
|
|
1128
|
+
) {
|
|
1129
|
+
return value;
|
|
1130
|
+
}
|
|
1131
|
+
if (!value || typeof value !== "object" || isProxy(value)) {
|
|
1132
|
+
throw invalidReplRecovery(
|
|
1133
|
+
`${subject} contains a non-serializable value`,
|
|
1134
|
+
"CC_REPL_SESSION_REBUILD_FAILED",
|
|
1135
|
+
);
|
|
1136
|
+
}
|
|
1137
|
+
if (ancestors.has(value)) {
|
|
1138
|
+
throw invalidReplRecovery(
|
|
1139
|
+
`${subject} contains a cycle`,
|
|
1140
|
+
"CC_REPL_SESSION_REBUILD_FAILED",
|
|
1141
|
+
);
|
|
1142
|
+
}
|
|
1143
|
+
ancestors.add(value);
|
|
1144
|
+
try {
|
|
1145
|
+
if (Array.isArray(value)) {
|
|
1146
|
+
return snapshotDataArray(value, subject, (item, index) =>
|
|
1147
|
+
snapshotReplMessageValue(item, `${subject}[${index}]`, ancestors),
|
|
1148
|
+
);
|
|
1149
|
+
}
|
|
1150
|
+
const descriptors = plainDataDescriptors(value, subject);
|
|
1151
|
+
const snapshot = {};
|
|
1152
|
+
for (const key of Object.keys(descriptors)) {
|
|
1153
|
+
snapshot[key] = snapshotReplMessageValue(
|
|
1154
|
+
descriptors[key].value,
|
|
1155
|
+
`${subject}.${key}`,
|
|
1156
|
+
ancestors,
|
|
1157
|
+
);
|
|
1158
|
+
}
|
|
1159
|
+
return Object.freeze(snapshot);
|
|
1160
|
+
} finally {
|
|
1161
|
+
ancestors.delete(value);
|
|
1162
|
+
}
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
function snapshotReplMessages(messages) {
|
|
1166
|
+
try {
|
|
1167
|
+
return snapshotDataArray(
|
|
1168
|
+
messages,
|
|
1169
|
+
"REPL session rebuild",
|
|
1170
|
+
(message, index) => {
|
|
1171
|
+
const snapshot = snapshotReplMessageValue(
|
|
1172
|
+
message,
|
|
1173
|
+
`REPL session rebuild[${index}]`,
|
|
1174
|
+
);
|
|
1175
|
+
if (
|
|
1176
|
+
!snapshot ||
|
|
1177
|
+
Array.isArray(snapshot) ||
|
|
1178
|
+
typeof snapshot.role !== "string"
|
|
1179
|
+
) {
|
|
1180
|
+
throw invalidReplRecovery(
|
|
1181
|
+
`REPL session rebuild[${index}] is not a message`,
|
|
1182
|
+
"CC_REPL_SESSION_REBUILD_FAILED",
|
|
1183
|
+
);
|
|
1184
|
+
}
|
|
1185
|
+
return preserveDurableSystemMessageProvenance(message, snapshot);
|
|
1186
|
+
},
|
|
1187
|
+
);
|
|
1188
|
+
} catch (cause) {
|
|
1189
|
+
const error = invalidReplRecovery(
|
|
1190
|
+
safeRecoveryErrorValue(cause, "message", "REPL session rebuild failed"),
|
|
1191
|
+
"CC_REPL_SESSION_REBUILD_FAILED",
|
|
1192
|
+
);
|
|
1193
|
+
error.cause = cause;
|
|
1194
|
+
throw error;
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
function canonicalPersistentReplMessages(messages) {
|
|
1199
|
+
return snapshotReplMessages(
|
|
1200
|
+
projectCanonicalResumeMessages(snapshotReplMessages(messages), {
|
|
1201
|
+
strict: true,
|
|
1202
|
+
}),
|
|
1203
|
+
);
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
/**
|
|
1207
|
+
* Track the exact replay projection this REPL has persisted. Compact writes
|
|
1208
|
+
* compare it with the store's verified active messages under one lock, so a
|
|
1209
|
+
* second host's unseen turn can never be hidden by a local auto/session-end
|
|
1210
|
+
* checkpoint.
|
|
1211
|
+
*/
|
|
1212
|
+
export function createReplCompactPersistence(
|
|
1213
|
+
initialMessages = [],
|
|
1214
|
+
dependencies = {},
|
|
1215
|
+
) {
|
|
1216
|
+
const appendCompact = dependencyDataFunction(
|
|
1217
|
+
dependencies,
|
|
1218
|
+
"appendCompactEventIfMessagesMatch",
|
|
1219
|
+
appendCompactEventIfMessagesMatch,
|
|
1220
|
+
);
|
|
1221
|
+
let persistedMessages = canonicalPersistentReplMessages(initialMessages);
|
|
1222
|
+
const replace = (messages) => {
|
|
1223
|
+
persistedMessages = canonicalPersistentReplMessages(messages);
|
|
1224
|
+
return persistedMessages;
|
|
1225
|
+
};
|
|
1226
|
+
return Object.freeze({
|
|
1227
|
+
record(message) {
|
|
1228
|
+
const projected = canonicalPersistentReplMessages([message]);
|
|
1229
|
+
if (projected.length !== 1) {
|
|
1230
|
+
throw new TypeError("Persisted REPL message is not canonical");
|
|
1231
|
+
}
|
|
1232
|
+
persistedMessages = Object.freeze([...persistedMessages, projected[0]]);
|
|
1233
|
+
return projected[0];
|
|
1234
|
+
},
|
|
1235
|
+
replace,
|
|
1236
|
+
persist(sessionId, payload) {
|
|
1237
|
+
const canonicalMessages = canonicalPersistentReplMessages(
|
|
1238
|
+
payload?.messages || [],
|
|
1239
|
+
);
|
|
1240
|
+
const canonicalPayload = { ...payload, messages: canonicalMessages };
|
|
1241
|
+
const result = appendCompact(
|
|
1242
|
+
sessionId,
|
|
1243
|
+
canonicalPayload,
|
|
1244
|
+
persistedMessages,
|
|
1245
|
+
);
|
|
1246
|
+
replace(canonicalMessages);
|
|
1247
|
+
return result;
|
|
1248
|
+
},
|
|
1249
|
+
snapshot() {
|
|
1250
|
+
return snapshotReplMessages(persistedMessages);
|
|
1251
|
+
},
|
|
1252
|
+
});
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
function validateRawReplReplayMessages(rebuiltMessages) {
|
|
1256
|
+
for (let index = 0; index < rebuiltMessages.length; index += 1) {
|
|
1257
|
+
const message = rebuiltMessages[index];
|
|
1258
|
+
if (!REPL_RESUME_ROLES.has(message.role)) {
|
|
1259
|
+
throw invalidReplRecovery(
|
|
1260
|
+
`REPL session message[${index}] has an unsupported role`,
|
|
1261
|
+
"CC_REPL_SESSION_ROLE_INVALID",
|
|
1262
|
+
);
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
const hasToolCalls = Object.prototype.hasOwnProperty.call(
|
|
1266
|
+
message,
|
|
1267
|
+
"tool_calls",
|
|
1268
|
+
);
|
|
1269
|
+
const hasToolCallId = Object.prototype.hasOwnProperty.call(
|
|
1270
|
+
message,
|
|
1271
|
+
"tool_call_id",
|
|
1272
|
+
);
|
|
1273
|
+
if (message.role !== "assistant" && hasToolCalls) {
|
|
1274
|
+
throw invalidReplRecovery(
|
|
1275
|
+
`REPL session message[${index}] carries tool calls on the wrong role`,
|
|
1276
|
+
"CC_REPL_SESSION_TOOL_PAIR_INVALID",
|
|
1277
|
+
);
|
|
1278
|
+
}
|
|
1279
|
+
if (message.role !== "tool" && hasToolCallId) {
|
|
1280
|
+
throw invalidReplRecovery(
|
|
1281
|
+
`REPL session message[${index}] carries a tool result id on the wrong role`,
|
|
1282
|
+
"CC_REPL_SESSION_TOOL_PAIR_INVALID",
|
|
1283
|
+
);
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
if (message.role === "tool") {
|
|
1287
|
+
if (
|
|
1288
|
+
!hasToolCallId ||
|
|
1289
|
+
typeof message.tool_call_id !== "string" ||
|
|
1290
|
+
message.tool_call_id.length === 0
|
|
1291
|
+
) {
|
|
1292
|
+
throw invalidReplRecovery(
|
|
1293
|
+
`REPL session tool result[${index}] has an invalid call id`,
|
|
1294
|
+
"CC_REPL_SESSION_TOOL_PAIR_INVALID",
|
|
1295
|
+
);
|
|
1296
|
+
}
|
|
1297
|
+
continue;
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1300
|
+
if (message.role !== "assistant" || !hasToolCalls) continue;
|
|
1301
|
+
if (!Array.isArray(message.tool_calls)) {
|
|
1302
|
+
throw invalidReplRecovery(
|
|
1303
|
+
`REPL session assistant message[${index}] has invalid tool calls`,
|
|
1304
|
+
"CC_REPL_SESSION_TOOL_PAIR_INVALID",
|
|
1305
|
+
);
|
|
1306
|
+
}
|
|
1307
|
+
const batchToolCallIds = new Set();
|
|
1308
|
+
for (const toolCall of message.tool_calls) {
|
|
1309
|
+
const toolCallId =
|
|
1310
|
+
toolCall && typeof toolCall === "object" && !Array.isArray(toolCall)
|
|
1311
|
+
? toolCall.id
|
|
1312
|
+
: null;
|
|
1313
|
+
if (
|
|
1314
|
+
typeof toolCallId !== "string" ||
|
|
1315
|
+
toolCallId.length === 0 ||
|
|
1316
|
+
batchToolCallIds.has(toolCallId)
|
|
1317
|
+
) {
|
|
1318
|
+
throw invalidReplRecovery(
|
|
1319
|
+
`REPL session assistant message[${index}] has ambiguous tool call ids`,
|
|
1320
|
+
"CC_REPL_SESSION_TOOL_PAIR_INVALID",
|
|
1321
|
+
);
|
|
1322
|
+
}
|
|
1323
|
+
batchToolCallIds.add(toolCallId);
|
|
1324
|
+
}
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
|
|
1328
|
+
function isPlainReplMergeMessage(message) {
|
|
1329
|
+
if (message.role !== "user" && message.role !== "assistant") return false;
|
|
1330
|
+
const keys = Object.keys(message);
|
|
1331
|
+
return (
|
|
1332
|
+
Object.prototype.hasOwnProperty.call(message, "content") &&
|
|
1333
|
+
keys.every((key) => key === "role" || key === "content")
|
|
1334
|
+
);
|
|
1335
|
+
}
|
|
1336
|
+
|
|
1337
|
+
function mergePlainReplRoleRuns(rebuiltMessages) {
|
|
1338
|
+
const mergedMessages = [];
|
|
1339
|
+
for (const message of rebuiltMessages) {
|
|
1340
|
+
const previous = mergedMessages.at(-1);
|
|
1341
|
+
if (
|
|
1342
|
+
previous &&
|
|
1343
|
+
previous.role === message.role &&
|
|
1344
|
+
isPlainReplMergeMessage(previous) &&
|
|
1345
|
+
isPlainReplMergeMessage(message)
|
|
1346
|
+
) {
|
|
1347
|
+
// The shared role helper is safe only after raw authority validation and
|
|
1348
|
+
// only for exact {role, content} records. This prevents a later record's
|
|
1349
|
+
// tool/identity authority from disappearing behind object spread.
|
|
1350
|
+
mergedMessages[mergedMessages.length - 1] = mergeConsecutiveMessages([
|
|
1351
|
+
previous,
|
|
1352
|
+
message,
|
|
1353
|
+
])[0];
|
|
1354
|
+
} else {
|
|
1355
|
+
mergedMessages.push(message);
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
return snapshotReplMessages(mergedMessages);
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
function collapseValidatedPlainReplTailInPlace(messages) {
|
|
1362
|
+
const rawSnapshot = snapshotReplMessages(messages);
|
|
1363
|
+
validateRawReplReplayMessages(rawSnapshot);
|
|
1364
|
+
const previous = rawSnapshot.at(-2);
|
|
1365
|
+
const current = rawSnapshot.at(-1);
|
|
1366
|
+
if (
|
|
1367
|
+
!previous ||
|
|
1368
|
+
previous.role !== current?.role ||
|
|
1369
|
+
!isPlainReplMergeMessage(previous) ||
|
|
1370
|
+
!isPlainReplMergeMessage(current)
|
|
1371
|
+
) {
|
|
1372
|
+
return false;
|
|
1373
|
+
}
|
|
1374
|
+
const merged = mergeConsecutiveMessages([previous, current]);
|
|
1375
|
+
if (merged.length !== 1) return false;
|
|
1376
|
+
messages.splice(messages.length - 2, 2, merged[0]);
|
|
1377
|
+
return true;
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
function normalizeReplReplayMessages(rebuiltMessages) {
|
|
1381
|
+
// Validate the immutable raw snapshot before any normalization. In
|
|
1382
|
+
// particular, never let a same-role merge hide malformed tool authority.
|
|
1383
|
+
validateRawReplReplayMessages(rebuiltMessages);
|
|
1384
|
+
|
|
1385
|
+
// Stable-partition verified canonical systems ahead of conversation. Their
|
|
1386
|
+
// relative order is preserved exactly, without inspecting content. This
|
|
1387
|
+
// keeps a trailing migration/fork marker from separating a dangling user
|
|
1388
|
+
// turn from the next live user turn after providers extract system prompts.
|
|
1389
|
+
const canonicalSystemMessages = snapshotReplMessages(
|
|
1390
|
+
rebuiltMessages.filter((message) => message.role === "system"),
|
|
1391
|
+
);
|
|
1392
|
+
const conversationMessages = mergePlainReplRoleRuns(
|
|
1393
|
+
rebuiltMessages.filter((message) => message.role !== "system"),
|
|
1394
|
+
);
|
|
1395
|
+
let phase = "expect-initial-conversation-message";
|
|
1396
|
+
let pendingToolCallIds = null;
|
|
1397
|
+
|
|
1398
|
+
for (let index = 0; index < conversationMessages.length; index += 1) {
|
|
1399
|
+
const message = conversationMessages[index];
|
|
1400
|
+
const hasToolCalls = Object.prototype.hasOwnProperty.call(
|
|
1401
|
+
message,
|
|
1402
|
+
"tool_calls",
|
|
1403
|
+
);
|
|
1404
|
+
|
|
1405
|
+
if (message.role === "tool") {
|
|
1406
|
+
const toolCallId = message.tool_call_id;
|
|
1407
|
+
if (phase !== "expect-tools" || !pendingToolCallIds?.delete(toolCallId)) {
|
|
1408
|
+
throw invalidReplRecovery(
|
|
1409
|
+
`REPL session tool result[${index}] has no matching pending call`,
|
|
1410
|
+
"CC_REPL_SESSION_TOOL_PAIR_INVALID",
|
|
1411
|
+
);
|
|
1412
|
+
}
|
|
1413
|
+
if (pendingToolCallIds.size === 0) {
|
|
1414
|
+
pendingToolCallIds = null;
|
|
1415
|
+
phase = "expect-assistant-after-tools";
|
|
1416
|
+
}
|
|
1417
|
+
continue;
|
|
1418
|
+
}
|
|
1419
|
+
|
|
1420
|
+
if (message.role === "user") {
|
|
1421
|
+
if (
|
|
1422
|
+
phase !== "expect-user" &&
|
|
1423
|
+
phase !== "expect-initial-conversation-message"
|
|
1424
|
+
) {
|
|
1425
|
+
throw invalidReplRecovery(
|
|
1426
|
+
`REPL session user message[${index}] breaks role alternation`,
|
|
1427
|
+
"CC_REPL_SESSION_ROLE_ALTERNATION_INVALID",
|
|
1428
|
+
);
|
|
1429
|
+
}
|
|
1430
|
+
phase = "expect-assistant";
|
|
1431
|
+
continue;
|
|
1432
|
+
}
|
|
1433
|
+
|
|
1434
|
+
if (
|
|
1435
|
+
phase !== "expect-assistant" &&
|
|
1436
|
+
phase !== "expect-assistant-after-tools" &&
|
|
1437
|
+
phase !== "expect-initial-conversation-message"
|
|
1438
|
+
) {
|
|
1439
|
+
throw invalidReplRecovery(
|
|
1440
|
+
`REPL session assistant message[${index}] breaks role alternation`,
|
|
1441
|
+
"CC_REPL_SESSION_ROLE_ALTERNATION_INVALID",
|
|
1442
|
+
);
|
|
1443
|
+
}
|
|
1444
|
+
|
|
1445
|
+
const toolCalls = hasToolCalls ? message.tool_calls : [];
|
|
1446
|
+
if (toolCalls.length === 0) {
|
|
1447
|
+
phase = "expect-user";
|
|
1448
|
+
continue;
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
// IDs are unique only within this pending assistant batch. A later, fully
|
|
1452
|
+
// settled fallback round may legitimately reuse a deterministic ID such as
|
|
1453
|
+
// call_<toolName>.
|
|
1454
|
+
pendingToolCallIds = new Set(toolCalls.map((toolCall) => toolCall.id));
|
|
1455
|
+
phase = "expect-tools";
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
if (phase === "expect-tools" || phase === "expect-assistant-after-tools") {
|
|
1459
|
+
throw invalidReplRecovery(
|
|
1460
|
+
"REPL session ends with an incomplete tool call/result exchange",
|
|
1461
|
+
"CC_REPL_SESSION_TOOL_PAIR_INVALID",
|
|
1462
|
+
);
|
|
1463
|
+
}
|
|
1464
|
+
return Object.freeze({
|
|
1465
|
+
canonicalSystemMessages,
|
|
1466
|
+
conversationMessages,
|
|
1467
|
+
replayMessages: Object.freeze([
|
|
1468
|
+
...canonicalSystemMessages,
|
|
1469
|
+
...conversationMessages,
|
|
1470
|
+
]),
|
|
1471
|
+
});
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
function failedReplJsonlResumeCandidate(sessionId, error, sessionSnapshot) {
|
|
1475
|
+
const observedCode = safeRecoveryErrorValue(
|
|
1476
|
+
error,
|
|
1477
|
+
"code",
|
|
1478
|
+
"CC_SESSION_HOST_SNAPSHOT_UNVERIFIED",
|
|
1479
|
+
);
|
|
1480
|
+
const resumeError = replMcpRecoveryError(
|
|
1481
|
+
error,
|
|
1482
|
+
typeof observedCode === "string" && observedCode
|
|
1483
|
+
? observedCode
|
|
1484
|
+
: "CC_SESSION_HOST_SNAPSHOT_UNVERIFIED",
|
|
1485
|
+
);
|
|
1486
|
+
return brandedFrozenCandidate(REPL_JSONL_RESUME_CANDIDATES, {
|
|
1487
|
+
ok: false,
|
|
1488
|
+
sessionId,
|
|
1489
|
+
rebuiltMessages: null,
|
|
1490
|
+
replayMessages: null,
|
|
1491
|
+
canonicalSystemMessages: null,
|
|
1492
|
+
conversationMessages: null,
|
|
1493
|
+
sessionSnapshot: sessionSnapshot || null,
|
|
1494
|
+
mcp: failClosedReplMcpRecoveryCandidate(
|
|
1495
|
+
sessionId,
|
|
1496
|
+
resumeError,
|
|
1497
|
+
resumeError.code,
|
|
1498
|
+
"session transcript",
|
|
1499
|
+
),
|
|
1500
|
+
error: resumeError,
|
|
1501
|
+
});
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
function absentReplJsonlResumeCandidate(sessionId) {
|
|
1505
|
+
const error = new Error(`Session not found: ${sessionId}`);
|
|
1506
|
+
error.code = "CC_REPL_SESSION_NOT_FOUND";
|
|
1507
|
+
const candidate = failedReplJsonlResumeCandidate(sessionId, error, null);
|
|
1508
|
+
REPL_JSONL_RESUME_ABSENCE_CANDIDATES.add(candidate);
|
|
1509
|
+
return candidate;
|
|
1510
|
+
}
|
|
1511
|
+
|
|
1512
|
+
/**
|
|
1513
|
+
* Prepare a JSONL resume transaction from exactly one fully verified sample.
|
|
1514
|
+
* Messages, the public snapshot, and MCP recovery authority are derived by the
|
|
1515
|
+
* shared reader from that same event array. A present-but-invalid transcript is
|
|
1516
|
+
* an inert structured refusal and cannot be committed into the active REPL.
|
|
1517
|
+
*/
|
|
1518
|
+
export function prepareReplJsonlResumeCandidate(sessionId, dependencies = {}) {
|
|
1519
|
+
let sessionSnapshot = null;
|
|
1520
|
+
try {
|
|
1521
|
+
validateReplResumeSessionId(sessionId);
|
|
1522
|
+
const readResumeState = dependencyDataFunction(
|
|
1523
|
+
dependencies,
|
|
1524
|
+
"readSessionHostResumeState",
|
|
1525
|
+
readSessionHostResumeState,
|
|
1526
|
+
);
|
|
1527
|
+
const formatNotice = dependencyDataFunction(
|
|
1528
|
+
dependencies,
|
|
1529
|
+
"formatMcpLedgerRecoveryNotice",
|
|
1530
|
+
formatMcpLedgerRecoveryNotice,
|
|
1531
|
+
);
|
|
1532
|
+
const state = synchronousReplRecoveryValue(
|
|
1533
|
+
readResumeState(sessionId),
|
|
1534
|
+
"REPL session host resume state",
|
|
1535
|
+
);
|
|
1536
|
+
if (state === null) return absentReplJsonlResumeCandidate(sessionId);
|
|
1537
|
+
const stateDescriptors = plainDataDescriptors(
|
|
1538
|
+
state,
|
|
1539
|
+
"REPL session host resume state",
|
|
1540
|
+
);
|
|
1541
|
+
sessionSnapshot = snapshotReplMessageValue(
|
|
1542
|
+
dataDescriptorValue(
|
|
1543
|
+
stateDescriptors,
|
|
1544
|
+
"snapshot",
|
|
1545
|
+
"REPL session host resume state",
|
|
1546
|
+
),
|
|
1547
|
+
"REPL session host snapshot",
|
|
1548
|
+
);
|
|
1549
|
+
if (
|
|
1550
|
+
!isVerifiedSessionHostSnapshot(sessionSnapshot) ||
|
|
1551
|
+
sessionSnapshot.sessionId !== sessionId
|
|
1552
|
+
) {
|
|
1553
|
+
const error = new Error(
|
|
1554
|
+
"Canonical JSONL session is not fully verified; resume was refused",
|
|
1555
|
+
);
|
|
1556
|
+
error.code = "CC_SESSION_HOST_SNAPSHOT_UNVERIFIED";
|
|
1557
|
+
throw error;
|
|
1558
|
+
}
|
|
1559
|
+
const rawRebuiltMessages = snapshotReplMessages(
|
|
1560
|
+
dataDescriptorValue(
|
|
1561
|
+
stateDescriptors,
|
|
1562
|
+
"messages",
|
|
1563
|
+
"REPL session host resume state",
|
|
1564
|
+
),
|
|
1565
|
+
);
|
|
1566
|
+
// The injected host seam may supply plain persisted fields. Only the
|
|
1567
|
+
// runtime-only provenance already established by the verified store is
|
|
1568
|
+
// canonical; unmarked host prompts and forged wire tags are removed before
|
|
1569
|
+
// REPL normalization or any side effect.
|
|
1570
|
+
const rebuiltMessages = snapshotReplMessages(
|
|
1571
|
+
projectCanonicalResumeMessages(rawRebuiltMessages),
|
|
1572
|
+
);
|
|
1573
|
+
const normalizedReplay = normalizeReplReplayMessages(rebuiltMessages);
|
|
1574
|
+
const mcp = createReplMcpRecoveryCandidate(
|
|
1575
|
+
sessionId,
|
|
1576
|
+
dataDescriptorValue(
|
|
1577
|
+
stateDescriptors,
|
|
1578
|
+
"recovery",
|
|
1579
|
+
"REPL session host resume state",
|
|
1580
|
+
),
|
|
1581
|
+
formatNotice,
|
|
1582
|
+
);
|
|
1583
|
+
if (
|
|
1584
|
+
mcp.recoveryError ||
|
|
1585
|
+
mcp.recovery.headHash !== sessionSnapshot.head.hash ||
|
|
1586
|
+
mcp.recovery.recoveryDigest !==
|
|
1587
|
+
sessionSnapshot.recoveryAuthority.recoveryDigest
|
|
1588
|
+
) {
|
|
1589
|
+
const error = new Error(
|
|
1590
|
+
"Canonical JSONL messages and MCP recovery authority do not share one head",
|
|
1591
|
+
);
|
|
1592
|
+
error.code = "CC_REPL_SESSION_AUTHORITY_MISMATCH";
|
|
1593
|
+
throw error;
|
|
1594
|
+
}
|
|
1595
|
+
return brandedFrozenCandidate(REPL_JSONL_RESUME_CANDIDATES, {
|
|
1596
|
+
ok: true,
|
|
1597
|
+
sessionId,
|
|
1598
|
+
rebuiltMessages,
|
|
1599
|
+
replayMessages: normalizedReplay.replayMessages,
|
|
1600
|
+
canonicalSystemMessages: normalizedReplay.canonicalSystemMessages,
|
|
1601
|
+
conversationMessages: normalizedReplay.conversationMessages,
|
|
1602
|
+
sessionSnapshot,
|
|
1603
|
+
mcp,
|
|
1604
|
+
error: null,
|
|
1605
|
+
});
|
|
1606
|
+
} catch (error) {
|
|
1607
|
+
return failedReplJsonlResumeCandidate(sessionId, error, sessionSnapshot);
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
|
|
1611
|
+
/**
|
|
1612
|
+
* Resolve startup storage only after a requested canonical JSONL session has
|
|
1613
|
+
* been sampled and verified. A present canonical session is authoritative;
|
|
1614
|
+
* feature/config reads are reserved for new sessions or the legacy DB
|
|
1615
|
+
* fallback when no JSONL transcript exists.
|
|
1616
|
+
*/
|
|
1617
|
+
export function prepareReplStartupResume(sessionId, dependencies = {}) {
|
|
1618
|
+
if (sessionId !== null && sessionId !== undefined) {
|
|
1619
|
+
const candidate = prepareReplJsonlResumeCandidate(sessionId, dependencies);
|
|
1620
|
+
if (candidate.ok) {
|
|
1621
|
+
return Object.freeze({ useJsonl: true, candidate });
|
|
1622
|
+
}
|
|
1623
|
+
if (!REPL_JSONL_RESUME_ABSENCE_CANDIDATES.has(candidate)) {
|
|
1624
|
+
return Object.freeze({ useJsonl: true, candidate });
|
|
1625
|
+
}
|
|
1626
|
+
}
|
|
1627
|
+
|
|
1628
|
+
const readFeature = dependencyDataFunction(dependencies, "feature", feature);
|
|
1629
|
+
return Object.freeze({
|
|
1630
|
+
useJsonl: Boolean(readFeature("JSONL_SESSION")),
|
|
1631
|
+
candidate: null,
|
|
1632
|
+
});
|
|
1633
|
+
}
|
|
1634
|
+
|
|
1635
|
+
function assertReplStartupAdmission(value) {
|
|
1636
|
+
synchronousReplRecoveryValue(value, "REPL startup admission");
|
|
1637
|
+
const descriptors = plainDataDescriptors(value, "REPL startup admission");
|
|
1638
|
+
const useJsonl = dataDescriptorValue(
|
|
1639
|
+
descriptors,
|
|
1640
|
+
"useJsonl",
|
|
1641
|
+
"REPL startup admission",
|
|
1642
|
+
);
|
|
1643
|
+
const candidate = dataDescriptorValue(
|
|
1644
|
+
descriptors,
|
|
1645
|
+
"candidate",
|
|
1646
|
+
"REPL startup admission",
|
|
1647
|
+
);
|
|
1648
|
+
if (
|
|
1649
|
+
typeof useJsonl !== "boolean" ||
|
|
1650
|
+
!Object.isFrozen(value) ||
|
|
1651
|
+
(candidate !== null &&
|
|
1652
|
+
(!REPL_JSONL_RESUME_CANDIDATES.has(candidate) ||
|
|
1653
|
+
!Object.isFrozen(candidate))) ||
|
|
1654
|
+
(candidate !== null && useJsonl !== true)
|
|
1655
|
+
) {
|
|
1656
|
+
throw invalidReplRecovery(
|
|
1657
|
+
"REPL startup admission capability is invalid",
|
|
1658
|
+
"CC_REPL_STARTUP_ADMISSION_INVALID",
|
|
1659
|
+
);
|
|
1660
|
+
}
|
|
1661
|
+
return value;
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
function refuseReplStartupResume(options, candidate) {
|
|
1665
|
+
const observedCode = safeRecoveryErrorValue(
|
|
1666
|
+
candidate?.error,
|
|
1667
|
+
"code",
|
|
1668
|
+
"CC_SESSION_HOST_SNAPSHOT_UNVERIFIED",
|
|
1669
|
+
);
|
|
1670
|
+
const refusal = Object.freeze({
|
|
1671
|
+
started: false,
|
|
1672
|
+
exitCode: 1,
|
|
1673
|
+
code:
|
|
1674
|
+
typeof observedCode === "string" && observedCode
|
|
1675
|
+
? observedCode
|
|
1676
|
+
: "CC_SESSION_HOST_SNAPSHOT_UNVERIFIED",
|
|
1677
|
+
sessionId: options.sessionId,
|
|
1678
|
+
sessionSnapshot: candidate?.sessionSnapshot || null,
|
|
1679
|
+
});
|
|
1680
|
+
logger.error(
|
|
1681
|
+
JSON.stringify({
|
|
1682
|
+
type: "session.resume.refused",
|
|
1683
|
+
...refusal,
|
|
1684
|
+
}),
|
|
1685
|
+
);
|
|
1686
|
+
process.exitCode = 1;
|
|
1687
|
+
return refusal;
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1690
|
+
function commitPreparedReplResume(prepared, commit, rollback) {
|
|
1691
|
+
if (!prepared || typeof commit !== "function") return false;
|
|
1692
|
+
try {
|
|
1693
|
+
commit(prepared);
|
|
1694
|
+
return true;
|
|
1695
|
+
} catch (commitError) {
|
|
1696
|
+
if (typeof rollback === "function") {
|
|
1697
|
+
try {
|
|
1698
|
+
rollback(prepared, commitError);
|
|
1699
|
+
} catch (rollbackError) {
|
|
1700
|
+
const error = new AggregateError(
|
|
1701
|
+
[commitError, rollbackError],
|
|
1702
|
+
"REPL session resume and rollback both failed",
|
|
1703
|
+
);
|
|
1704
|
+
error.code = "CC_REPL_SESSION_RESUME_ROLLBACK_FAILED";
|
|
1705
|
+
throw error;
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
throw commitError;
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
|
|
1712
|
+
/** Commit a fully prepared JSONL switch; forged/failed candidates are inert. */
|
|
1713
|
+
export function commitPreparedReplJsonlResume(candidate, commit, rollback) {
|
|
1714
|
+
if (
|
|
1715
|
+
!candidate ||
|
|
1716
|
+
!REPL_JSONL_RESUME_CANDIDATES.has(candidate) ||
|
|
1717
|
+
!candidate.ok
|
|
1718
|
+
) {
|
|
1719
|
+
return false;
|
|
1720
|
+
}
|
|
1721
|
+
return commitPreparedReplResume(candidate, commit, rollback);
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
/** Commit the already parsed and snapshotted legacy-DB resume state. */
|
|
1725
|
+
export function commitPreparedReplDbResume(preparedState, commit, rollback) {
|
|
1726
|
+
return commitPreparedReplResume(preparedState, commit, rollback);
|
|
1727
|
+
}
|
|
1728
|
+
|
|
1729
|
+
/**
|
|
1730
|
+
* Own the exact mutable state switched by the interactive `/session resume`
|
|
1731
|
+
* command. Both JSONL and legacy-DB paths use this controller, which also gives
|
|
1732
|
+
* tests a behavioral seam for failures at each real apply stage.
|
|
1733
|
+
*/
|
|
1734
|
+
export function createReplResumeStateController(bindings) {
|
|
1735
|
+
const snapshots = new WeakSet();
|
|
1736
|
+
const hostSystemMessagePrefixes = new WeakSet();
|
|
1737
|
+
let registeredHostSystemMessages = null;
|
|
1738
|
+
const replaceArray = (target, values) => {
|
|
1739
|
+
target.length = 0;
|
|
1740
|
+
for (const value of values) target.push(value);
|
|
1741
|
+
};
|
|
1742
|
+
const invalidHostPrefix = (message) =>
|
|
1743
|
+
invalidReplRecovery(message, "CC_REPL_HOST_SYSTEM_PREFIX_INVALID");
|
|
1744
|
+
const assertHostSystemMessages = (candidate) => {
|
|
1745
|
+
if (
|
|
1746
|
+
!candidate ||
|
|
1747
|
+
!hostSystemMessagePrefixes.has(candidate) ||
|
|
1748
|
+
!Array.isArray(candidate) ||
|
|
1749
|
+
!Object.isFrozen(candidate) ||
|
|
1750
|
+
candidate.length === 0 ||
|
|
1751
|
+
candidate.some(
|
|
1752
|
+
(message) =>
|
|
1753
|
+
!message || message.role !== "system" || !Object.isFrozen(message),
|
|
1754
|
+
)
|
|
1755
|
+
) {
|
|
1756
|
+
throw invalidHostPrefix("REPL host system prefix capability is invalid");
|
|
1757
|
+
}
|
|
1758
|
+
return candidate;
|
|
1759
|
+
};
|
|
1760
|
+
const createHostSystemMessages = (sourceMessages) => {
|
|
1761
|
+
const snapshot = snapshotReplMessages(sourceMessages);
|
|
1762
|
+
const leadingSystems = [];
|
|
1763
|
+
for (const message of snapshot) {
|
|
1764
|
+
if (message.role !== "system") break;
|
|
1765
|
+
leadingSystems.push(message);
|
|
1766
|
+
}
|
|
1767
|
+
if (leadingSystems.length === 0) {
|
|
1768
|
+
throw invalidHostPrefix("REPL host system prefix is empty");
|
|
1769
|
+
}
|
|
1770
|
+
const capability = Object.freeze(leadingSystems);
|
|
1771
|
+
hostSystemMessagePrefixes.add(capability);
|
|
1772
|
+
return capability;
|
|
1773
|
+
};
|
|
1774
|
+
const registerHostSystemMessages = () => {
|
|
1775
|
+
if (registeredHostSystemMessages !== null) {
|
|
1776
|
+
throw invalidHostPrefix("REPL host system prefix is already registered");
|
|
1777
|
+
}
|
|
1778
|
+
registeredHostSystemMessages = createHostSystemMessages(bindings.messages);
|
|
1779
|
+
return registeredHostSystemMessages;
|
|
1780
|
+
};
|
|
1781
|
+
const refreshHostSystemMessages = () => {
|
|
1782
|
+
const registered = assertHostSystemMessages(registeredHostSystemMessages);
|
|
1783
|
+
const currentBase = snapshotReplMessages([bindings.messages[0]])[0];
|
|
1784
|
+
if (currentBase.role !== "system") {
|
|
1785
|
+
throw invalidHostPrefix("REPL current host base system is invalid");
|
|
1786
|
+
}
|
|
1787
|
+
const capability = Object.freeze([currentBase, ...registered.slice(1)]);
|
|
1788
|
+
hostSystemMessagePrefixes.add(capability);
|
|
1789
|
+
registeredHostSystemMessages = capability;
|
|
1790
|
+
return capability;
|
|
1791
|
+
};
|
|
1792
|
+
const materializeHostSystemMessages = (candidate) =>
|
|
1793
|
+
assertHostSystemMessages(candidate).map((message) => ({ ...message }));
|
|
1794
|
+
|
|
1795
|
+
const capture = () => {
|
|
1796
|
+
const hostSystemMessages = assertHostSystemMessages(
|
|
1797
|
+
registeredHostSystemMessages,
|
|
1798
|
+
);
|
|
1799
|
+
const mcpRuntime = bindings.runtimeManager.current;
|
|
1800
|
+
if (!mcpRuntime) {
|
|
1801
|
+
const error = new Error("Active MCP recovery runtime is unavailable");
|
|
1802
|
+
error.code = "CC_REPL_MCP_RUNTIME_UNAVAILABLE";
|
|
1803
|
+
throw error;
|
|
1804
|
+
}
|
|
1805
|
+
const snapshot = Object.freeze({
|
|
1806
|
+
sessionId: bindings.sessionId,
|
|
1807
|
+
messages: Object.freeze(bindings.messages.slice()),
|
|
1808
|
+
recovery: bindings.recovery,
|
|
1809
|
+
recoveryError: bindings.recoveryError,
|
|
1810
|
+
sanitizeRolesNextTurn: bindings.sanitizeRolesNextTurn,
|
|
1811
|
+
turnBindingProducer: bindings.turnBindingProducer,
|
|
1812
|
+
turnBindingCriticalError: bindings.turnBindingCriticalError,
|
|
1813
|
+
checkpointMarks: Object.freeze(bindings.checkpointMarks.slice()),
|
|
1814
|
+
clearedConversation: bindings.clearedConversation,
|
|
1815
|
+
hostSystemMessages,
|
|
1816
|
+
mcpRuntime,
|
|
1817
|
+
});
|
|
1818
|
+
snapshots.add(snapshot);
|
|
1819
|
+
return snapshot;
|
|
1820
|
+
};
|
|
1821
|
+
|
|
1822
|
+
const restore = (snapshot) => {
|
|
1823
|
+
if (!snapshot || !snapshots.has(snapshot)) {
|
|
1824
|
+
throw new TypeError("REPL resume snapshot is invalid");
|
|
1825
|
+
}
|
|
1826
|
+
bindings.sessionId = snapshot.sessionId;
|
|
1827
|
+
replaceArray(bindings.messages, snapshot.messages);
|
|
1828
|
+
bindings.recovery = snapshot.recovery;
|
|
1829
|
+
bindings.recoveryError = snapshot.recoveryError;
|
|
1830
|
+
bindings.sanitizeRolesNextTurn = snapshot.sanitizeRolesNextTurn;
|
|
1831
|
+
bindings.turnBindingProducer = snapshot.turnBindingProducer;
|
|
1832
|
+
bindings.turnBindingCriticalError = snapshot.turnBindingCriticalError;
|
|
1833
|
+
replaceArray(bindings.checkpointMarks, snapshot.checkpointMarks);
|
|
1834
|
+
bindings.clearedConversation = snapshot.clearedConversation;
|
|
1835
|
+
registeredHostSystemMessages = assertHostSystemMessages(
|
|
1836
|
+
snapshot.hostSystemMessages,
|
|
1837
|
+
);
|
|
1838
|
+
if (bindings.runtimeManager.current !== snapshot.mcpRuntime) {
|
|
1839
|
+
bindings.runtimeManager.commit(snapshot.mcpRuntime);
|
|
1840
|
+
}
|
|
1841
|
+
};
|
|
1842
|
+
|
|
1843
|
+
const apply = (preparedState) => {
|
|
1844
|
+
const hostSystemMessages = assertHostSystemMessages(
|
|
1845
|
+
preparedState.hostSystemMessages,
|
|
1846
|
+
);
|
|
1847
|
+
const activeHostSystemMessages =
|
|
1848
|
+
materializeHostSystemMessages(hostSystemMessages);
|
|
1849
|
+
const canonicalSystemMessages = snapshotReplMessages(
|
|
1850
|
+
preparedState.canonicalSystemMessages,
|
|
1851
|
+
);
|
|
1852
|
+
const conversationMessages = snapshotReplMessages(
|
|
1853
|
+
preparedState.conversationMessages,
|
|
1854
|
+
);
|
|
1855
|
+
if (
|
|
1856
|
+
canonicalSystemMessages.some((message) => message.role !== "system") ||
|
|
1857
|
+
conversationMessages.some((message) => message.role === "system")
|
|
1858
|
+
) {
|
|
1859
|
+
throw invalidHostPrefix(
|
|
1860
|
+
"REPL prepared resume message partition is invalid",
|
|
1861
|
+
);
|
|
1862
|
+
}
|
|
1863
|
+
bindings.sessionId = preparedState.sessionId;
|
|
1864
|
+
replaceArray(bindings.messages, activeHostSystemMessages);
|
|
1865
|
+
registeredHostSystemMessages = hostSystemMessages;
|
|
1866
|
+
for (const message of canonicalSystemMessages) {
|
|
1867
|
+
bindings.messages.push(message);
|
|
1868
|
+
}
|
|
1869
|
+
bindings.applyMcpRecoveryCommit(bindings.messages, preparedState.mcpCommit);
|
|
1870
|
+
for (const message of conversationMessages) {
|
|
1871
|
+
bindings.messages.push(message);
|
|
1872
|
+
}
|
|
1873
|
+
bindings.sanitizeRolesNextTurn = preparedState.sanitizeRolesNextTurn;
|
|
1874
|
+
bindings.turnBindingProducer = null;
|
|
1875
|
+
bindings.turnBindingCriticalError = null;
|
|
1876
|
+
bindings.checkpointMarks.length = 0;
|
|
1877
|
+
bindings.clearedConversation = null;
|
|
1878
|
+
bindings.runtimeManager.commit(preparedState.mcpRuntime);
|
|
1879
|
+
bindings.logMcpRecoveryCommit(preparedState.mcpCommit);
|
|
1880
|
+
bindings.logger.info(preparedState.logMessage);
|
|
1881
|
+
};
|
|
1882
|
+
|
|
1883
|
+
return Object.freeze({
|
|
1884
|
+
capture,
|
|
1885
|
+
restore,
|
|
1886
|
+
apply,
|
|
1887
|
+
registerHostSystemMessages,
|
|
1888
|
+
refreshHostSystemMessages,
|
|
1889
|
+
});
|
|
1890
|
+
}
|
|
1891
|
+
|
|
1892
|
+
/**
|
|
1893
|
+
* Own the single recovery runtime for the active REPL session/client pair.
|
|
1894
|
+
* Session switches are prepared without mutating the active runtime, then
|
|
1895
|
+
* committed only after the transcript switch succeeds.
|
|
1896
|
+
*/
|
|
1897
|
+
export function createReplMcpHostRuntimeManager(dependencies = {}) {
|
|
1898
|
+
const createRuntime =
|
|
1899
|
+
dependencies.createMcpHostRecoveryRuntime || createMcpHostRecoveryRuntime;
|
|
1900
|
+
const createLedgerSink =
|
|
1901
|
+
dependencies.createSessionMcpLedgerSink || createSessionMcpLedgerSink;
|
|
1902
|
+
const appendLedgerEvent =
|
|
1903
|
+
dependencies.appendAuthorityEvent || appendAuthorityEvent;
|
|
1904
|
+
const candidates = new WeakSet();
|
|
1905
|
+
let current = null;
|
|
1906
|
+
|
|
1907
|
+
const prepare = ({
|
|
1908
|
+
adhocMcp = null,
|
|
1909
|
+
bundleMcpClient = null,
|
|
1910
|
+
sessionId = null,
|
|
1911
|
+
persistent = false,
|
|
1912
|
+
recovery = null,
|
|
1913
|
+
recoveryError = null,
|
|
1914
|
+
verifiedRecovery = false,
|
|
1915
|
+
} = {}) => {
|
|
1916
|
+
const bundle = adhocMcp?.mcpClient
|
|
1917
|
+
? adhocMcp
|
|
1918
|
+
: bundleMcpClient
|
|
1919
|
+
? { mcpClient: bundleMcpClient }
|
|
1920
|
+
: null;
|
|
1921
|
+
const rawClient = bundle?.mcpClient || null;
|
|
1922
|
+
const persistLedger = Boolean(persistent && sessionId);
|
|
1923
|
+
|
|
1924
|
+
if (
|
|
1925
|
+
!verifiedRecovery &&
|
|
1926
|
+
current &&
|
|
1927
|
+
current.rawClient === rawClient &&
|
|
1928
|
+
current.sessionId === sessionId &&
|
|
1929
|
+
current.persistent === persistLedger &&
|
|
1930
|
+
current.recovery === recovery &&
|
|
1931
|
+
current.recoveryError === recoveryError
|
|
1932
|
+
) {
|
|
1933
|
+
return current;
|
|
1934
|
+
}
|
|
1935
|
+
|
|
1936
|
+
const sink = persistLedger
|
|
1937
|
+
? createLedgerSink(sessionId, { appendEvent: appendLedgerEvent })
|
|
1938
|
+
: null;
|
|
1939
|
+
const sharedController =
|
|
1940
|
+
!verifiedRecovery && current?.sessionId === sessionId
|
|
1941
|
+
? current.runtime.controller
|
|
1942
|
+
: null;
|
|
1943
|
+
const runtime = createRuntime({
|
|
1944
|
+
bundle,
|
|
1945
|
+
rawClient,
|
|
1946
|
+
sessionId,
|
|
1947
|
+
sink,
|
|
1948
|
+
recovery,
|
|
1949
|
+
recoveryError,
|
|
1950
|
+
...(sharedController ? { controller: sharedController } : {}),
|
|
1951
|
+
});
|
|
1952
|
+
const candidate = Object.freeze({
|
|
1953
|
+
runtime,
|
|
1954
|
+
rawClient,
|
|
1955
|
+
hostMcp: bundle
|
|
1956
|
+
? Object.freeze({
|
|
1957
|
+
...bundle,
|
|
1958
|
+
mcpClient: runtime.client,
|
|
1959
|
+
})
|
|
1960
|
+
: null,
|
|
1961
|
+
sessionId,
|
|
1962
|
+
persistent: persistLedger,
|
|
1963
|
+
recovery,
|
|
1964
|
+
recoveryError,
|
|
1965
|
+
verifiedRecovery: Boolean(verifiedRecovery),
|
|
1966
|
+
});
|
|
1967
|
+
candidates.add(candidate);
|
|
1968
|
+
return candidate;
|
|
1969
|
+
};
|
|
1970
|
+
|
|
1971
|
+
const commit = (candidate) => {
|
|
1972
|
+
if (!candidate || !candidates.has(candidate)) {
|
|
1973
|
+
throw new TypeError("MCP host runtime candidate is invalid");
|
|
1974
|
+
}
|
|
1975
|
+
current = candidate;
|
|
1976
|
+
return current;
|
|
1977
|
+
};
|
|
1978
|
+
|
|
1979
|
+
return Object.freeze({
|
|
1980
|
+
prepare,
|
|
1981
|
+
commit,
|
|
1982
|
+
activate(options) {
|
|
1983
|
+
return commit(prepare(options));
|
|
1984
|
+
},
|
|
1985
|
+
get current() {
|
|
1986
|
+
return current;
|
|
1987
|
+
},
|
|
1988
|
+
});
|
|
483
1989
|
}
|
|
484
1990
|
|
|
485
1991
|
/**
|
|
486
|
-
*
|
|
1992
|
+
* Execute the startup boundary with explicit host-owned dependencies. Exported
|
|
1993
|
+
* for behavior tests; callers cannot obtain the private workspace starter, and
|
|
1994
|
+
* the public startAgentRepl() below always supplies the real fixed bindings.
|
|
487
1995
|
*/
|
|
488
|
-
export async function
|
|
489
|
-
const
|
|
490
|
-
|
|
491
|
-
|
|
1996
|
+
export async function runReplStartupBoundary(options, startupDependencies) {
|
|
1997
|
+
const prepareStartup = dependencyDataFunction(
|
|
1998
|
+
startupDependencies,
|
|
1999
|
+
"prepareReplStartupResume",
|
|
2000
|
+
null,
|
|
2001
|
+
);
|
|
2002
|
+
if (typeof prepareStartup !== "function") {
|
|
2003
|
+
throw invalidReplRecovery(
|
|
2004
|
+
"REPL startup admission dependency is missing",
|
|
2005
|
+
"CC_REPL_STARTUP_DEPENDENCY_INVALID",
|
|
2006
|
+
);
|
|
2007
|
+
}
|
|
2008
|
+
const startupAdmission = assertReplStartupAdmission(
|
|
2009
|
+
synchronousReplRecoveryValue(
|
|
2010
|
+
prepareStartup(options.sessionId),
|
|
2011
|
+
"REPL startup admission",
|
|
2012
|
+
),
|
|
492
2013
|
);
|
|
2014
|
+
const startupCandidate = startupAdmission.candidate;
|
|
2015
|
+
if (startupCandidate && !startupCandidate.ok) {
|
|
2016
|
+
const refuseStartup = dependencyDataFunction(
|
|
2017
|
+
startupDependencies,
|
|
2018
|
+
"refuseReplStartupResume",
|
|
2019
|
+
null,
|
|
2020
|
+
);
|
|
2021
|
+
if (typeof refuseStartup !== "function") {
|
|
2022
|
+
throw invalidReplRecovery(
|
|
2023
|
+
"REPL startup refusal dependency is missing",
|
|
2024
|
+
"CC_REPL_STARTUP_DEPENDENCY_INVALID",
|
|
2025
|
+
);
|
|
2026
|
+
}
|
|
2027
|
+
return refuseStartup(options, startupCandidate);
|
|
2028
|
+
}
|
|
2029
|
+
|
|
2030
|
+
// Only a frozen, branded admission capability may cross into workspace,
|
|
2031
|
+
// pipe, config, plugin, hook, MCP, model, or tool initialization.
|
|
2032
|
+
const readCwd = dependencyDataFunction(startupDependencies, "cwd", null);
|
|
2033
|
+
const enterWorkspace = dependencyDataFunction(
|
|
2034
|
+
startupDependencies,
|
|
2035
|
+
"runWithHostHooksV2Workspace",
|
|
2036
|
+
null,
|
|
2037
|
+
);
|
|
2038
|
+
const startWorkspace = dependencyDataFunction(
|
|
2039
|
+
startupDependencies,
|
|
2040
|
+
"startAgentReplInWorkspace",
|
|
2041
|
+
null,
|
|
2042
|
+
);
|
|
2043
|
+
if (
|
|
2044
|
+
typeof readCwd !== "function" ||
|
|
2045
|
+
typeof enterWorkspace !== "function" ||
|
|
2046
|
+
typeof startWorkspace !== "function"
|
|
2047
|
+
) {
|
|
2048
|
+
throw invalidReplRecovery(
|
|
2049
|
+
"REPL host startup dependency is missing",
|
|
2050
|
+
"CC_REPL_STARTUP_DEPENDENCY_INVALID",
|
|
2051
|
+
);
|
|
2052
|
+
}
|
|
2053
|
+
const trustedWorkspaceRoot = readCwd();
|
|
2054
|
+
return enterWorkspace(trustedWorkspaceRoot, () =>
|
|
2055
|
+
startWorkspace(options, startupAdmission),
|
|
2056
|
+
);
|
|
2057
|
+
}
|
|
2058
|
+
|
|
2059
|
+
/** Start the agentic REPL with non-overridable production bindings. */
|
|
2060
|
+
export async function startAgentRepl(options = {}) {
|
|
2061
|
+
return runReplStartupBoundary(options, {
|
|
2062
|
+
prepareReplStartupResume,
|
|
2063
|
+
refuseReplStartupResume,
|
|
2064
|
+
cwd: () => process.cwd(),
|
|
2065
|
+
runWithHostHooksV2Workspace,
|
|
2066
|
+
startAgentReplInWorkspace,
|
|
2067
|
+
});
|
|
493
2068
|
}
|
|
494
2069
|
|
|
495
|
-
async function startAgentReplInWorkspace(options = {}) {
|
|
2070
|
+
async function startAgentReplInWorkspace(options = {}, startupAdmission) {
|
|
496
2071
|
// EPIPE guard: if the REPL's stdout is piped and the consumer closes (e.g.
|
|
497
2072
|
// `cc agent | head`), the async stream `error` would otherwise crash the
|
|
498
2073
|
// process. Route a broken pipe into the REPL's own graceful shutdown (the
|
|
@@ -514,6 +2089,7 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
514
2089
|
}
|
|
515
2090
|
process.exit(0);
|
|
516
2091
|
});
|
|
2092
|
+
const { useJsonl, candidate: _startupJsonlResume } = startupAdmission;
|
|
517
2093
|
let model = options.model || "qwen2.5:7b";
|
|
518
2094
|
let provider = options.provider || "ollama";
|
|
519
2095
|
// Extended thinking (Anthropic; opt-in via --think/--ultrathink). Carried from
|
|
@@ -523,12 +2099,15 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
523
2099
|
// (--thinking-budget) is the companion legacy-model budget_tokens override.
|
|
524
2100
|
let thinking = options.thinking || null;
|
|
525
2101
|
const thinkingBudget = options.thinkingBudget || null;
|
|
526
|
-
// `/
|
|
527
|
-
//
|
|
528
|
-
//
|
|
529
|
-
// the injection after the turn (or as a backstop at the next submit on throw).
|
|
2102
|
+
// `/note-next` one-shot guidance rides ONLY the next main turn, then is
|
|
2103
|
+
// stripped so it never persists or carries forward. `/btw` itself is an
|
|
2104
|
+
// immediate independent side question handled below.
|
|
530
2105
|
let pendingBtw = [];
|
|
531
2106
|
let _btwRestore = null;
|
|
2107
|
+
// Provider-neutral, tool-free Advisor/Critic. Initialized lazily after the
|
|
2108
|
+
// durable session and resumed transcript are available; null means the
|
|
2109
|
+
// optional surface could not be initialized. Default is off via config.
|
|
2110
|
+
let _advisorRuntime = null;
|
|
532
2111
|
// Current permission mode (strict|trusted|autopilot|auto), mirrored here so
|
|
533
2112
|
// Shift+Tab can cycle it and `/permissions <tier>` can set it. Kept in sync
|
|
534
2113
|
// with _approvalGate.setSessionPolicy below. "auto" rides the trusted gate
|
|
@@ -559,6 +2138,8 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
559
2138
|
// an auto-detected image path so the REPL switches to a vision-capable model
|
|
560
2139
|
// for that turn only (resolveVisionLlm falls back to the default when unset).
|
|
561
2140
|
let _visionModel;
|
|
2141
|
+
let _promptInteractionConfig = {};
|
|
2142
|
+
let _persistPromptSuggestionsEnabled = null;
|
|
562
2143
|
// Hard stream inactivity timeout override (config.llm.streamStallTimeoutMs,
|
|
563
2144
|
// ms): a stream silent that long is aborted + retried instead of hanging.
|
|
564
2145
|
// Unset → agent-core's 180s default (matches cc chat/ask). Set to 0 to
|
|
@@ -573,8 +2154,11 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
573
2154
|
// CC_PERMISSION_ASK_TIMEOUT_MS env > config permissions.askTimeoutMs > off.
|
|
574
2155
|
let _askIdleTimeoutMs = resolveAskIdleTimeoutMs();
|
|
575
2156
|
try {
|
|
576
|
-
const
|
|
577
|
-
const _cfg = loadConfig();
|
|
2157
|
+
const configManager = await import("../lib/config-manager.js");
|
|
2158
|
+
const _cfg = configManager.loadConfig();
|
|
2159
|
+
_promptInteractionConfig = _cfg || {};
|
|
2160
|
+
_persistPromptSuggestionsEnabled = (enabled) =>
|
|
2161
|
+
configManager.setConfigValue("cli.promptSuggestions", enabled === true);
|
|
578
2162
|
_visionModel = _cfg?.llm?.visionModel || undefined;
|
|
579
2163
|
_autoPinCfgValue = _cfg?.context?.autoPin;
|
|
580
2164
|
_askIdleTimeoutMs = resolveAskIdleTimeoutMs({
|
|
@@ -631,7 +2215,10 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
631
2215
|
// Bootstrap runtime (best-effort, DB not required)
|
|
632
2216
|
let db = null;
|
|
633
2217
|
let contextEngine = null;
|
|
634
|
-
let sessionId = null;
|
|
2218
|
+
let sessionId = _startupJsonlResume?.sessionId || null;
|
|
2219
|
+
const _replCompactPersistence = createReplCompactPersistence(
|
|
2220
|
+
_startupJsonlResume?.ok ? _startupJsonlResume.rebuiltMessages : [],
|
|
2221
|
+
);
|
|
635
2222
|
|
|
636
2223
|
try {
|
|
637
2224
|
const ctx = await bootstrap({ verbose: false });
|
|
@@ -642,7 +2229,30 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
642
2229
|
|
|
643
2230
|
// Initialize prompt compressor (adaptive to model's context window)
|
|
644
2231
|
if (feature("PROMPT_COMPRESSOR")) {
|
|
645
|
-
_compressor = new PromptCompressor({
|
|
2232
|
+
_compressor = new PromptCompressor({
|
|
2233
|
+
model,
|
|
2234
|
+
provider,
|
|
2235
|
+
llmQuery: async (prompt) => {
|
|
2236
|
+
const response = await chatWithTools(
|
|
2237
|
+
[{ role: "user", content: prompt }],
|
|
2238
|
+
{
|
|
2239
|
+
provider,
|
|
2240
|
+
model,
|
|
2241
|
+
baseUrl,
|
|
2242
|
+
apiKey,
|
|
2243
|
+
enabledToolNames: [],
|
|
2244
|
+
extraToolDefinitions: [],
|
|
2245
|
+
maxOutputTokens: 2048,
|
|
2246
|
+
},
|
|
2247
|
+
);
|
|
2248
|
+
return {
|
|
2249
|
+
summary: response?.message?.content || "",
|
|
2250
|
+
usage: response?.usage || null,
|
|
2251
|
+
provider,
|
|
2252
|
+
model,
|
|
2253
|
+
};
|
|
2254
|
+
},
|
|
2255
|
+
});
|
|
646
2256
|
}
|
|
647
2257
|
const _autoPinOpt = resolveAutoPinOption({ config: _autoPinCfgValue });
|
|
648
2258
|
// Compaction options shared by /compact + auto-compact. Adds the
|
|
@@ -908,16 +2518,18 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
908
2518
|
// PostToolUse). The interactive _permissionConfirm above doubles as the
|
|
909
2519
|
// confirmer for a hook `ask` decision.
|
|
910
2520
|
try {
|
|
911
|
-
const { loadHooks, projectHookTrustNotice } =
|
|
2521
|
+
const { loadHooks, projectHookTrustNotice, attachAuthorityErrors } =
|
|
912
2522
|
await import("../lib/settings-hooks.cjs");
|
|
913
2523
|
const loaded = loadHooks({ cwd: process.cwd() });
|
|
914
2524
|
// Fold in installed plugins' hooks/hooks.json (Phase 3.3c).
|
|
915
2525
|
const { mergePluginHooks } = await import("../lib/plugin-runtime/hooks.js");
|
|
916
|
-
const effectiveHooks = mergePluginHooks(
|
|
917
|
-
|
|
918
|
-
|
|
2526
|
+
const effectiveHooks = mergePluginHooks(
|
|
2527
|
+
attachAuthorityErrors(loaded.hooks, loaded.authorityErrors),
|
|
2528
|
+
{ cwd: process.cwd() },
|
|
2529
|
+
);
|
|
919
2530
|
_settingsHooks =
|
|
920
|
-
|
|
2531
|
+
Object.keys(effectiveHooks).length > 0 ||
|
|
2532
|
+
effectiveHooks._authorityErrors.length > 0
|
|
921
2533
|
? effectiveHooks
|
|
922
2534
|
: null;
|
|
923
2535
|
// First-run trust notice for an untrusted/cloned repo's shell-running
|
|
@@ -929,7 +2541,16 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
929
2541
|
/* trust notice is best-effort */
|
|
930
2542
|
}
|
|
931
2543
|
} catch (_err) {
|
|
932
|
-
_settingsHooks =
|
|
2544
|
+
_settingsHooks = {};
|
|
2545
|
+
Object.defineProperty(_settingsHooks, "_authorityErrors", {
|
|
2546
|
+
value: Object.freeze([
|
|
2547
|
+
Object.freeze({
|
|
2548
|
+
sourceFile: null,
|
|
2549
|
+
code: _err?.code || "CC_HOOK_AUTHORITY_LOAD_FAILED",
|
|
2550
|
+
}),
|
|
2551
|
+
]),
|
|
2552
|
+
enumerable: false,
|
|
2553
|
+
});
|
|
933
2554
|
}
|
|
934
2555
|
|
|
935
2556
|
// Start installed plugins' background monitors (Phase 3.3i). Trust-gated
|
|
@@ -987,19 +2608,10 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
987
2608
|
_pluginSettingsRestore = null;
|
|
988
2609
|
}
|
|
989
2610
|
|
|
990
|
-
// Resume existing session or create new one
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
if (useJsonl && options.sessionId) {
|
|
994
|
-
// JSONL resume: check if session file exists
|
|
995
|
-
try {
|
|
996
|
-
if (sessionExists(options.sessionId)) {
|
|
997
|
-
sessionId = options.sessionId;
|
|
998
|
-
}
|
|
999
|
-
} catch (_err) {
|
|
1000
|
-
// Non-critical
|
|
1001
|
-
}
|
|
1002
|
-
} else if (db && options.sessionId) {
|
|
2611
|
+
// Resume existing session or create new one. JSONL resumes were admitted
|
|
2612
|
+
// before bootstrap/config/plugin/hook initialization and use that exact
|
|
2613
|
+
// verified sample below; do not re-read the transcript here.
|
|
2614
|
+
if (!useJsonl && db && options.sessionId) {
|
|
1003
2615
|
try {
|
|
1004
2616
|
const existing = getSession(db, options.sessionId);
|
|
1005
2617
|
if (existing && existing.messages) {
|
|
@@ -1159,6 +2771,56 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
1159
2771
|
let _replBaseSystem = _buildReplBaseSystem();
|
|
1160
2772
|
let _activeOutputStyle = null; // { name, body }
|
|
1161
2773
|
const messages = [{ role: "system", content: _replBaseSystem }];
|
|
2774
|
+
let _mcpLedgerRecovery = null;
|
|
2775
|
+
let _mcpLedgerRecoveryError = null;
|
|
2776
|
+
const _prepareJsonlResumeCandidate = (targetSessionId) =>
|
|
2777
|
+
prepareReplJsonlResumeCandidate(targetSessionId);
|
|
2778
|
+
const _prepareMcpRecoveryCommit = (candidate) => {
|
|
2779
|
+
const authorized =
|
|
2780
|
+
candidate && REPL_MCP_RECOVERY_CANDIDATES.has(candidate)
|
|
2781
|
+
? candidate
|
|
2782
|
+
: failClosedReplMcpRecoveryCandidate(
|
|
2783
|
+
sessionId,
|
|
2784
|
+
invalidReplRecovery(
|
|
2785
|
+
"MCP recovery candidate capability is invalid",
|
|
2786
|
+
"CC_REPL_MCP_RECOVERY_CANDIDATE_INVALID",
|
|
2787
|
+
),
|
|
2788
|
+
"CC_REPL_MCP_RECOVERY_CANDIDATE_INVALID",
|
|
2789
|
+
);
|
|
2790
|
+
const recovery = authorized.recovery;
|
|
2791
|
+
const recoveryError = authorized.recoveryError;
|
|
2792
|
+
const noticeMessage = authorized.notice
|
|
2793
|
+
? Object.freeze({ role: "system", content: authorized.notice })
|
|
2794
|
+
: null;
|
|
2795
|
+
const warning = recoveryError
|
|
2796
|
+
? "⚠ MCP ledger recovery failed closed; inspect the transcript before using MCP tools."
|
|
2797
|
+
: authorized.notice
|
|
2798
|
+
? `⚠ ${recovery.unsettled.length} interrupted MCP call(s), ${recovery.incidents.length} ledger incident(s), and ${recovery.replayDenied.length} exact replay deny/denies require inspection before replay.`
|
|
2799
|
+
: null;
|
|
2800
|
+
return Object.freeze({
|
|
2801
|
+
recovery,
|
|
2802
|
+
recoveryError,
|
|
2803
|
+
noticeMessage,
|
|
2804
|
+
warning,
|
|
2805
|
+
});
|
|
2806
|
+
};
|
|
2807
|
+
const _applyMcpRecoveryCommit = (targetMessages, preparedCommit) => {
|
|
2808
|
+
_mcpLedgerRecovery = preparedCommit.recovery;
|
|
2809
|
+
_mcpLedgerRecoveryError = preparedCommit.recoveryError;
|
|
2810
|
+
if (preparedCommit.noticeMessage) {
|
|
2811
|
+
targetMessages.push(preparedCommit.noticeMessage);
|
|
2812
|
+
}
|
|
2813
|
+
return Boolean(preparedCommit.noticeMessage);
|
|
2814
|
+
};
|
|
2815
|
+
const _logMcpRecoveryCommit = (preparedCommit) => {
|
|
2816
|
+
if (preparedCommit.warning) logger.warn(preparedCommit.warning);
|
|
2817
|
+
};
|
|
2818
|
+
const _commitMcpRecoveryCandidate = (targetMessages, candidate) => {
|
|
2819
|
+
const preparedCommit = _prepareMcpRecoveryCommit(candidate);
|
|
2820
|
+
const addedNotice = _applyMcpRecoveryCommit(targetMessages, preparedCommit);
|
|
2821
|
+
_logMcpRecoveryCommit(preparedCommit);
|
|
2822
|
+
return addedNotice;
|
|
2823
|
+
};
|
|
1162
2824
|
// Resume-degenerate role sanitation (Claude Code 2.1.187 parity): a one-shot
|
|
1163
2825
|
// flag armed when a resumed transcript ends with a bare `user` turn (the prior
|
|
1164
2826
|
// run produced no assistant response). Consumed by the first model call so the
|
|
@@ -1435,6 +3097,89 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
1435
3097
|
}
|
|
1436
3098
|
_persistReplContextSources();
|
|
1437
3099
|
|
|
3100
|
+
const _mcpHostRuntimeManager = createReplMcpHostRuntimeManager();
|
|
3101
|
+
const _mcpRuntimeInputs = ({
|
|
3102
|
+
targetSessionId = sessionId,
|
|
3103
|
+
recovery = _mcpLedgerRecovery,
|
|
3104
|
+
recoveryError = _mcpLedgerRecoveryError,
|
|
3105
|
+
} = {}) => ({
|
|
3106
|
+
adhocMcp: _adhocMcp,
|
|
3107
|
+
bundleMcpClient: _bundleMcpClient,
|
|
3108
|
+
sessionId: targetSessionId,
|
|
3109
|
+
persistent: useJsonl && Boolean(targetSessionId),
|
|
3110
|
+
recovery,
|
|
3111
|
+
recoveryError,
|
|
3112
|
+
});
|
|
3113
|
+
const _activateMcpHostRuntime = () =>
|
|
3114
|
+
_mcpHostRuntimeManager.activate(_mcpRuntimeInputs());
|
|
3115
|
+
const _prepareMcpHostRuntime = (targetSessionId, mcpCandidate = {}) =>
|
|
3116
|
+
_mcpHostRuntimeManager.prepare({
|
|
3117
|
+
..._mcpRuntimeInputs({
|
|
3118
|
+
targetSessionId,
|
|
3119
|
+
recovery: mcpCandidate.recovery ?? null,
|
|
3120
|
+
recoveryError: mcpCandidate.recoveryError ?? null,
|
|
3121
|
+
}),
|
|
3122
|
+
verifiedRecovery: true,
|
|
3123
|
+
});
|
|
3124
|
+
const _getReplHostMcp = () => _activateMcpHostRuntime().hostMcp;
|
|
3125
|
+
const _resumeStateController = createReplResumeStateController({
|
|
3126
|
+
get sessionId() {
|
|
3127
|
+
return sessionId;
|
|
3128
|
+
},
|
|
3129
|
+
set sessionId(value) {
|
|
3130
|
+
sessionId = value;
|
|
3131
|
+
},
|
|
3132
|
+
messages,
|
|
3133
|
+
get recovery() {
|
|
3134
|
+
return _mcpLedgerRecovery;
|
|
3135
|
+
},
|
|
3136
|
+
set recovery(value) {
|
|
3137
|
+
_mcpLedgerRecovery = value;
|
|
3138
|
+
},
|
|
3139
|
+
get recoveryError() {
|
|
3140
|
+
return _mcpLedgerRecoveryError;
|
|
3141
|
+
},
|
|
3142
|
+
set recoveryError(value) {
|
|
3143
|
+
_mcpLedgerRecoveryError = value;
|
|
3144
|
+
},
|
|
3145
|
+
get sanitizeRolesNextTurn() {
|
|
3146
|
+
return _sanitizeRolesNextTurn;
|
|
3147
|
+
},
|
|
3148
|
+
set sanitizeRolesNextTurn(value) {
|
|
3149
|
+
_sanitizeRolesNextTurn = value;
|
|
3150
|
+
},
|
|
3151
|
+
get turnBindingProducer() {
|
|
3152
|
+
return _turnBindingProducer;
|
|
3153
|
+
},
|
|
3154
|
+
set turnBindingProducer(value) {
|
|
3155
|
+
_turnBindingProducer = value;
|
|
3156
|
+
},
|
|
3157
|
+
get turnBindingCriticalError() {
|
|
3158
|
+
return _turnBindingCriticalError;
|
|
3159
|
+
},
|
|
3160
|
+
set turnBindingCriticalError(value) {
|
|
3161
|
+
_turnBindingCriticalError = value;
|
|
3162
|
+
},
|
|
3163
|
+
checkpointMarks: _checkpointMarks,
|
|
3164
|
+
get clearedConversation() {
|
|
3165
|
+
return _clearedConversation;
|
|
3166
|
+
},
|
|
3167
|
+
set clearedConversation(value) {
|
|
3168
|
+
_clearedConversation = value;
|
|
3169
|
+
},
|
|
3170
|
+
runtimeManager: _mcpHostRuntimeManager,
|
|
3171
|
+
applyMcpRecoveryCommit: _applyMcpRecoveryCommit,
|
|
3172
|
+
logMcpRecoveryCommit: _logMcpRecoveryCommit,
|
|
3173
|
+
logger,
|
|
3174
|
+
});
|
|
3175
|
+
const _captureResumeState = _resumeStateController.capture;
|
|
3176
|
+
const _restoreResumeState = _resumeStateController.restore;
|
|
3177
|
+
const _applyPreparedResumeState = _resumeStateController.apply;
|
|
3178
|
+
const _registerHostSystemMessages =
|
|
3179
|
+
_resumeStateController.registerHostSystemMessages;
|
|
3180
|
+
const _refreshHostSystemMessages =
|
|
3181
|
+
_resumeStateController.refreshHostSystemMessages;
|
|
3182
|
+
|
|
1438
3183
|
// Seed connected MCP servers with the startup workspace roots when the session
|
|
1439
3184
|
// began with extra `--add-dir` roots — otherwise `roots/list` would only ever
|
|
1440
3185
|
// return the cwd until the first mid-session /add-dir. No-op (byte-unchanged)
|
|
@@ -1515,35 +3260,37 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
1515
3260
|
}
|
|
1516
3261
|
}
|
|
1517
3262
|
|
|
3263
|
+
// Seal the complete host-owned leading system prefix exactly once, after
|
|
3264
|
+
// startup hooks, bundle context, and optional memory injection, but before
|
|
3265
|
+
// any canonical/legacy replay is appended. Later live switches refresh only
|
|
3266
|
+
// entry 0 from the active base prompt; they never re-scan old session systems.
|
|
3267
|
+
_registerHostSystemMessages();
|
|
3268
|
+
|
|
3269
|
+
let _startupResumeCommitted = false;
|
|
1518
3270
|
// Load resumed session messages
|
|
1519
3271
|
if (options.sessionId && sessionId) {
|
|
1520
3272
|
try {
|
|
1521
3273
|
if (useJsonl) {
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
if (trust.status === "tampered") {
|
|
1530
|
-
logger.warn(
|
|
1531
|
-
`⚠ Transcript integrity check FAILED (${trust.reason}) — restored context is untrusted. Run 'cc session verify ${sessionId}'.`,
|
|
1532
|
-
);
|
|
1533
|
-
}
|
|
1534
|
-
} catch (_err) {
|
|
1535
|
-
// verification is best-effort in the interactive path
|
|
3274
|
+
const prepared = _startupJsonlResume;
|
|
3275
|
+
if (!prepared?.ok) {
|
|
3276
|
+
const error = new Error(
|
|
3277
|
+
"Startup JSONL resume lost its verified admission capability",
|
|
3278
|
+
);
|
|
3279
|
+
error.code = "CC_REPL_SESSION_RESUME_NOT_PREPARED";
|
|
3280
|
+
throw error;
|
|
1536
3281
|
}
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
3282
|
+
messages.push(...prepared.canonicalSystemMessages);
|
|
3283
|
+
_commitMcpRecoveryCandidate(messages, prepared.mcp);
|
|
3284
|
+
if (prepared.replayMessages.length > 0) {
|
|
3285
|
+
messages.push(...prepared.conversationMessages);
|
|
1540
3286
|
// Arm the resume role-merge if the prior run left a dangling user turn.
|
|
1541
3287
|
_sanitizeRolesNextTurn =
|
|
1542
|
-
|
|
3288
|
+
prepared.conversationMessages.at(-1)?.role === "user";
|
|
1543
3289
|
logger.info(
|
|
1544
|
-
`Resumed JSONL session ${sessionId} (${
|
|
3290
|
+
`Resumed JSONL session ${sessionId} (${prepared.rebuiltMessages.length} messages)`,
|
|
1545
3291
|
);
|
|
1546
3292
|
}
|
|
3293
|
+
_startupResumeCommitted = true;
|
|
1547
3294
|
} else if (db) {
|
|
1548
3295
|
const existing = getSession(db, sessionId);
|
|
1549
3296
|
if (existing && existing.messages) {
|
|
@@ -1557,15 +3304,26 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
1557
3304
|
logger.info(
|
|
1558
3305
|
`Resumed session ${sessionId} (${parsed.length} messages)`,
|
|
1559
3306
|
);
|
|
3307
|
+
_startupResumeCommitted = true;
|
|
1560
3308
|
}
|
|
1561
3309
|
}
|
|
1562
|
-
} catch (
|
|
1563
|
-
|
|
3310
|
+
} catch (error) {
|
|
3311
|
+
if (useJsonl) {
|
|
3312
|
+
_commitMcpRecoveryCandidate(
|
|
3313
|
+
messages,
|
|
3314
|
+
failClosedReplMcpRecoveryCandidate(
|
|
3315
|
+
sessionId,
|
|
3316
|
+
error,
|
|
3317
|
+
"CC_REPL_SESSION_REBUILD_FAILED",
|
|
3318
|
+
"session transcript",
|
|
3319
|
+
),
|
|
3320
|
+
);
|
|
3321
|
+
}
|
|
1564
3322
|
}
|
|
1565
3323
|
// settings.json SessionResume hooks: a persisted transcript was just
|
|
1566
3324
|
// replayed into this interactive session (distinct from SessionStart).
|
|
1567
3325
|
// Observe-only, best-effort — never blocks entering the REPL.
|
|
1568
|
-
if (_settingsHooks &&
|
|
3326
|
+
if (_settingsHooks && _startupResumeCommitted) {
|
|
1569
3327
|
try {
|
|
1570
3328
|
const { runObserveHooks } =
|
|
1571
3329
|
await import("../lib/settings-hook-events.js");
|
|
@@ -1597,6 +3355,50 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
1597
3355
|
}
|
|
1598
3356
|
}
|
|
1599
3357
|
|
|
3358
|
+
// Create the active session-scoped runtime only after startup recovery has
|
|
3359
|
+
// been loaded. Subsequent turns reuse this controller and ledger so a
|
|
3360
|
+
// settlement-failure latch cannot be cleared by starting another turn.
|
|
3361
|
+
_activateMcpHostRuntime();
|
|
3362
|
+
|
|
3363
|
+
// Advisor is independent from the main agent loop: it gets a redacted
|
|
3364
|
+
// transcript snapshot and ZERO tools. Compact call/outcome metadata shares
|
|
3365
|
+
// the session hash chain, while advice text itself is never persisted.
|
|
3366
|
+
try {
|
|
3367
|
+
const { createConfiguredAdvisorRuntime } =
|
|
3368
|
+
await import("../lib/advisor-runtime.js");
|
|
3369
|
+
const advisorOverrides = {};
|
|
3370
|
+
if (options.advisorEnabled !== undefined) {
|
|
3371
|
+
advisorOverrides.enabled = options.advisorEnabled === true;
|
|
3372
|
+
}
|
|
3373
|
+
_advisorRuntime = await createConfiguredAdvisorRuntime({
|
|
3374
|
+
cwd: process.cwd(),
|
|
3375
|
+
settingsFile: options.settingsFile || null,
|
|
3376
|
+
managedSettingsFile: options.managedSettingsFile || null,
|
|
3377
|
+
mainProvider: provider,
|
|
3378
|
+
mainModel: model,
|
|
3379
|
+
baseUrl,
|
|
3380
|
+
apiKey,
|
|
3381
|
+
overrides: advisorOverrides,
|
|
3382
|
+
onEvent: (event) => {
|
|
3383
|
+
if (!useJsonl || !sessionId) return;
|
|
3384
|
+
try {
|
|
3385
|
+
appendEvent(sessionId, event.type, event.data);
|
|
3386
|
+
} catch {
|
|
3387
|
+
// Advisor observability is best-effort and cannot fail a main turn.
|
|
3388
|
+
}
|
|
3389
|
+
},
|
|
3390
|
+
});
|
|
3391
|
+
// A resumed transcript may contain old tool results. Mark them observed so
|
|
3392
|
+
// the first new turn cannot trigger an Advisor call for historical work.
|
|
3393
|
+
_advisorRuntime.primeMessages(messages);
|
|
3394
|
+
} catch (error) {
|
|
3395
|
+
if (error?.code === "CC_MANAGED_SETTINGS_INVALID") throw error;
|
|
3396
|
+
_advisorRuntime = null;
|
|
3397
|
+
if (options.advisorEnabled === true) {
|
|
3398
|
+
logger.warn(`Advisor unavailable: ${error.message}`);
|
|
3399
|
+
}
|
|
3400
|
+
}
|
|
3401
|
+
|
|
1600
3402
|
// Vim mode (Claude-Code `/vim` parity): opt-in modal line editing. `_vim`
|
|
1601
3403
|
// holds the NORMAL-mode engine state while normal mode is active (readline's
|
|
1602
3404
|
// own key handling is suspended then); it is null in INSERT mode (readline
|
|
@@ -1766,6 +3568,7 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
1766
3568
|
: [
|
|
1767
3569
|
"/add-dir",
|
|
1768
3570
|
"/agents",
|
|
3571
|
+
"/advisor",
|
|
1769
3572
|
"/auto",
|
|
1770
3573
|
"/btw",
|
|
1771
3574
|
"/cd",
|
|
@@ -1791,13 +3594,16 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
1791
3594
|
"/memory",
|
|
1792
3595
|
"/microcompact",
|
|
1793
3596
|
"/model",
|
|
3597
|
+
"/note-next",
|
|
1794
3598
|
"/output-style",
|
|
1795
3599
|
"/permissions",
|
|
3600
|
+
"/paste-image",
|
|
1796
3601
|
"/plan",
|
|
1797
3602
|
"/pr-comments",
|
|
1798
3603
|
"/profile",
|
|
1799
3604
|
"/provider",
|
|
1800
3605
|
"/quit",
|
|
3606
|
+
"/recap",
|
|
1801
3607
|
"/reindex",
|
|
1802
3608
|
"/release-notes",
|
|
1803
3609
|
"/reload-plugins",
|
|
@@ -1811,7 +3617,9 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
1811
3617
|
"/stats",
|
|
1812
3618
|
"/status",
|
|
1813
3619
|
"/statusline",
|
|
3620
|
+
"/stash",
|
|
1814
3621
|
"/sub-agents",
|
|
3622
|
+
"/suggestions",
|
|
1815
3623
|
"/task",
|
|
1816
3624
|
"/tasks",
|
|
1817
3625
|
"/terminal-setup",
|
|
@@ -1822,6 +3630,7 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
1822
3630
|
"/ultrathink",
|
|
1823
3631
|
"/vim",
|
|
1824
3632
|
"/voice",
|
|
3633
|
+
"/editor",
|
|
1825
3634
|
],
|
|
1826
3635
|
// User/project custom commands (.claude/commands/*.md) join TAB completion
|
|
1827
3636
|
// alongside the built-ins above. Sync + best-effort; the completer
|
|
@@ -1836,12 +3645,13 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
1836
3645
|
}
|
|
1837
3646
|
},
|
|
1838
3647
|
getIdeOpenFiles: async () => {
|
|
1839
|
-
const
|
|
1840
|
-
|
|
3648
|
+
const hostMcp = _getReplHostMcp();
|
|
3649
|
+
const exec = hostMcp?.externalToolExecutors?.mcp__ide__getOpenEditors;
|
|
3650
|
+
if (!exec || exec.kind !== "mcp" || !hostMcp?.mcpClient?.callTool) {
|
|
1841
3651
|
return [];
|
|
1842
3652
|
}
|
|
1843
3653
|
const { parseToolResultJson } = await import("../lib/ide-context.js");
|
|
1844
|
-
const res = await
|
|
3654
|
+
const res = await hostMcp.mcpClient.callTool(
|
|
1845
3655
|
exec.serverName,
|
|
1846
3656
|
exec.toolName,
|
|
1847
3657
|
{},
|
|
@@ -1864,6 +3674,28 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
1864
3674
|
// "close" cleanup instead of a bare exit.
|
|
1865
3675
|
_replRl = rl;
|
|
1866
3676
|
|
|
3677
|
+
// Prompt-side interaction modules share the production readline surface.
|
|
3678
|
+
// A per-REPL registry avoids singleton handlers retaining an old session.
|
|
3679
|
+
const _promptInteractionSurface = createPromptInteractionSurface({
|
|
3680
|
+
readline: rl,
|
|
3681
|
+
config: _promptInteractionConfig,
|
|
3682
|
+
keybindings: _promptInteractionConfig,
|
|
3683
|
+
getSessionId: () => sessionId,
|
|
3684
|
+
getSuggestionContext: () => ({ messages: messages.slice() }),
|
|
3685
|
+
persistSuggestionEnabled: _persistPromptSuggestionsEnabled,
|
|
3686
|
+
clipboardBinding: options.clipboardBinding || null,
|
|
3687
|
+
generateSuggestions: options.generatePromptSuggestions,
|
|
3688
|
+
suggestionDebounceMs: options.promptSuggestionDebounceMs,
|
|
3689
|
+
screenReader: _screenReaderMode,
|
|
3690
|
+
write: (text) => process.stdout.write(String(text)),
|
|
3691
|
+
writeError: (text) => process.stderr.write(String(text)),
|
|
3692
|
+
getColumns: () => process.stdout.columns || 80,
|
|
3693
|
+
});
|
|
3694
|
+
const _promptInteractions = _promptInteractionSurface.controller;
|
|
3695
|
+
for (const diagnostic of _promptInteractions.diagnostics().keybindingErrors) {
|
|
3696
|
+
logger.warn(`prompt keybinding ignored: ${diagnostic}`);
|
|
3697
|
+
}
|
|
3698
|
+
|
|
1867
3699
|
// MCP elicitation in the interactive REPL uses the same readline surface as
|
|
1868
3700
|
// approvals, while MCPClient retains the protocol-level response shape.
|
|
1869
3701
|
const mcpElicitationClients = [_adhocMcp?.mcpClient, _bundleMcpClient].filter(
|
|
@@ -1961,9 +3793,34 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
1961
3793
|
// Vim-mode plumbing: capture readline's OWN keypress listeners now so we can
|
|
1962
3794
|
// suspend them while in NORMAL mode (the engine drives editing then) and
|
|
1963
3795
|
// reattach them for INSERT mode (readline's rich editing/history/completion).
|
|
1964
|
-
const
|
|
3796
|
+
const _nativeReadlineKeypressListeners = process.stdin.isTTY
|
|
1965
3797
|
? process.stdin.listeners("keypress").slice()
|
|
1966
3798
|
: [];
|
|
3799
|
+
const _consumedReadlineKeypresses = new WeakSet();
|
|
3800
|
+
const _consumeReadlineKeypress = (key) => {
|
|
3801
|
+
if (key && typeof key === "object") _consumedReadlineKeypresses.add(key);
|
|
3802
|
+
};
|
|
3803
|
+
const _rlKeypressListeners = _nativeReadlineKeypressListeners.map(
|
|
3804
|
+
(listener) =>
|
|
3805
|
+
function guardedReadlineKeypress(input, key) {
|
|
3806
|
+
if (
|
|
3807
|
+
key &&
|
|
3808
|
+
typeof key === "object" &&
|
|
3809
|
+
_consumedReadlineKeypresses.has(key)
|
|
3810
|
+
) {
|
|
3811
|
+
return;
|
|
3812
|
+
}
|
|
3813
|
+
return listener.call(this, input, key);
|
|
3814
|
+
},
|
|
3815
|
+
);
|
|
3816
|
+
if (process.stdin.isTTY) {
|
|
3817
|
+
for (const listener of _nativeReadlineKeypressListeners) {
|
|
3818
|
+
process.stdin.removeListener("keypress", listener);
|
|
3819
|
+
}
|
|
3820
|
+
for (const listener of _rlKeypressListeners) {
|
|
3821
|
+
process.stdin.on("keypress", listener);
|
|
3822
|
+
}
|
|
3823
|
+
}
|
|
1967
3824
|
const _suspendReadlineKeys = () => {
|
|
1968
3825
|
for (const l of _rlKeypressListeners)
|
|
1969
3826
|
process.stdin.removeListener("keypress", l);
|
|
@@ -2013,11 +3870,13 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
2013
3870
|
// sequences (arrows etc.) never reach here as bare "escape".
|
|
2014
3871
|
let _turnAbort = null;
|
|
2015
3872
|
let _lastIdleEscAt = 0;
|
|
3873
|
+
let _replKeypressHandler = null;
|
|
2016
3874
|
if (process.stdin.isTTY) {
|
|
2017
|
-
|
|
3875
|
+
_replKeypressHandler = (_str, key) => {
|
|
2018
3876
|
const k = key || {};
|
|
2019
3877
|
// 1) Turn abort always wins, regardless of vim mode.
|
|
2020
3878
|
if (k.name === "escape" && !k.meta && _turnAbort) {
|
|
3879
|
+
_consumeReadlineKeypress(key);
|
|
2021
3880
|
process.stdout.write(chalk.yellow("\n⎋ interrupting…\n"));
|
|
2022
3881
|
try {
|
|
2023
3882
|
_turnAbort.abort();
|
|
@@ -2053,6 +3912,7 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
2053
3912
|
const isShiftTab =
|
|
2054
3913
|
(k.name === "tab" && k.shift) || k.sequence === "\u001b[Z";
|
|
2055
3914
|
if (isShiftTab) {
|
|
3915
|
+
_consumeReadlineKeypress(key);
|
|
2056
3916
|
if (
|
|
2057
3917
|
_approvalGate &&
|
|
2058
3918
|
sessionId &&
|
|
@@ -2081,14 +3941,30 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
2081
3941
|
return;
|
|
2082
3942
|
}
|
|
2083
3943
|
|
|
3944
|
+
// 1.75) Prompt interaction keybindings share the controller used by
|
|
3945
|
+
// slash commands. They are idle-only and stay out of Vim NORMAL mode,
|
|
3946
|
+
// where the modal editor owns every key.
|
|
3947
|
+
if (
|
|
3948
|
+
!_turnAbort &&
|
|
3949
|
+
(!_vimEnabled || !_vim) &&
|
|
3950
|
+
_promptInteractions.handleKeypress(_str, k)
|
|
3951
|
+
) {
|
|
3952
|
+
_consumeReadlineKeypress(key);
|
|
3953
|
+
return;
|
|
3954
|
+
}
|
|
3955
|
+
|
|
2084
3956
|
// 2) Vim mode: modal editing on the current input line.
|
|
2085
3957
|
if (_vimEnabled && !_turnAbort) {
|
|
2086
3958
|
if (!_vim) {
|
|
2087
3959
|
// INSERT mode — readline owns the keys; Esc switches to NORMAL.
|
|
2088
|
-
if (k.name === "escape" && !k.meta)
|
|
3960
|
+
if (k.name === "escape" && !k.meta) {
|
|
3961
|
+
_consumeReadlineKeypress(key);
|
|
3962
|
+
_vimEnterNormal();
|
|
3963
|
+
}
|
|
2089
3964
|
return;
|
|
2090
3965
|
}
|
|
2091
3966
|
// NORMAL mode — readline suspended; the engine interprets every key.
|
|
3967
|
+
_consumeReadlineKeypress(key);
|
|
2092
3968
|
const res = feedNormalKey(_vim, _str || "", k);
|
|
2093
3969
|
if (res.submit) {
|
|
2094
3970
|
// Hand the line to readline as a normal Enter (fires 'line', clears).
|
|
@@ -2110,6 +3986,7 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
2110
3986
|
|
|
2111
3987
|
// 3) Non-vim: double-Esc while idle → rewind picker shortcut.
|
|
2112
3988
|
if (k.name !== "escape" || k.meta) return;
|
|
3989
|
+
_consumeReadlineKeypress(key);
|
|
2113
3990
|
const nowTs = Date.now();
|
|
2114
3991
|
if (nowTs - _lastIdleEscAt < 600) {
|
|
2115
3992
|
_lastIdleEscAt = 0;
|
|
@@ -2134,7 +4011,8 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
2134
4011
|
} else {
|
|
2135
4012
|
_lastIdleEscAt = nowTs;
|
|
2136
4013
|
}
|
|
2137
|
-
}
|
|
4014
|
+
};
|
|
4015
|
+
process.stdin.prependListener("keypress", _replKeypressHandler);
|
|
2138
4016
|
}
|
|
2139
4017
|
|
|
2140
4018
|
logger.log(chalk.bold("\nChainlessChain Agent"));
|
|
@@ -2246,9 +4124,61 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
2246
4124
|
|
|
2247
4125
|
// Steering (Claude-Code parity): typing while a turn is running QUEUES the
|
|
2248
4126
|
// line instead of racing a second concurrent turn; the queue drains FIFO
|
|
2249
|
-
// when the current turn finishes.
|
|
4127
|
+
// when the current turn finishes. `/btw` is the deliberate exception: its
|
|
4128
|
+
// tool-free snapshot call may run concurrently without mutating main state.
|
|
2250
4129
|
let _processingLine = false;
|
|
2251
4130
|
const _pendingLines = [];
|
|
4131
|
+
|
|
4132
|
+
const runBtwSideQuestion = async (btw, { concurrent = false } = {}) => {
|
|
4133
|
+
if (!btw || btw.error) {
|
|
4134
|
+
const message = btw?.error || "usage: /btw [--fork] <question>";
|
|
4135
|
+
if (concurrent) process.stderr.write(`\n${message}\n`);
|
|
4136
|
+
else logger.info(message);
|
|
4137
|
+
return { ok: false, error: message };
|
|
4138
|
+
}
|
|
4139
|
+
try {
|
|
4140
|
+
const chatFn = createChatFn({ provider, model, baseUrl, apiKey });
|
|
4141
|
+
const { answer } = await runBtwQuestion({
|
|
4142
|
+
messages,
|
|
4143
|
+
question: btw.text,
|
|
4144
|
+
chatFn,
|
|
4145
|
+
model,
|
|
4146
|
+
});
|
|
4147
|
+
let forkedId = null;
|
|
4148
|
+
let forkNotice = "";
|
|
4149
|
+
if (btw.fork) {
|
|
4150
|
+
if (useJsonl && sessionId && sessionExists(sessionId)) {
|
|
4151
|
+
forkedId = forkSession(sessionId, {
|
|
4152
|
+
requestId: `btw-${randomUUID()}`,
|
|
4153
|
+
});
|
|
4154
|
+
if (forkedId) {
|
|
4155
|
+
appendUserMessage(forkedId, btw.text);
|
|
4156
|
+
appendAssistantMessage(forkedId, answer);
|
|
4157
|
+
forkNotice = `\nForked side thread: ${forkedId}`;
|
|
4158
|
+
}
|
|
4159
|
+
}
|
|
4160
|
+
if (!forkedId) {
|
|
4161
|
+
forkNotice =
|
|
4162
|
+
"\nSide answer was not persisted: the parent has no durable JSONL session.";
|
|
4163
|
+
}
|
|
4164
|
+
}
|
|
4165
|
+
const block =
|
|
4166
|
+
`┌─ btw${btw.fork ? " --fork" : ""}\n` +
|
|
4167
|
+
`${answer || "(empty response)"}\n` +
|
|
4168
|
+
`└─ ephemeral · no tools · parent history unchanged${forkNotice}`;
|
|
4169
|
+
// A concurrent answer must not corrupt the main streamed stdout payload.
|
|
4170
|
+
// stderr also keeps headless/JSON consumers isolated from the overlay.
|
|
4171
|
+
if (concurrent) process.stderr.write(`\n${block}\n`);
|
|
4172
|
+
else logger.log(`\n${block}\n`);
|
|
4173
|
+
return { ok: true, answer, forkedId };
|
|
4174
|
+
} catch (error) {
|
|
4175
|
+
const message = `/btw failed: ${error.message}`;
|
|
4176
|
+
if (concurrent) process.stderr.write(`\n${message}\n`);
|
|
4177
|
+
else logger.error(message);
|
|
4178
|
+
return { ok: false, error: message };
|
|
4179
|
+
}
|
|
4180
|
+
};
|
|
4181
|
+
|
|
2252
4182
|
// Multiline input (Claude-Code parity): a physical line ending in a
|
|
2253
4183
|
// continuation backslash keeps the prompt open; `_mlBuffer` accumulates the
|
|
2254
4184
|
// pieces and the whole block submits when a line does not continue.
|
|
@@ -2358,6 +4288,19 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
2358
4288
|
return;
|
|
2359
4289
|
}
|
|
2360
4290
|
|
|
4291
|
+
// The interaction commands are registered through the shared registry,
|
|
4292
|
+
// while the mature REPL handlers below remain on their existing direct
|
|
4293
|
+
// paths. --disable-slash-commands replaces `trimmed` with a sentinel, so
|
|
4294
|
+
// it cannot accidentally reach this dispatcher.
|
|
4295
|
+
if (trimmed.startsWith("/")) {
|
|
4296
|
+
const commandName = trimmed.split(/\s+/, 1)[0];
|
|
4297
|
+
if (_promptInteractionSurface.commandNames.has(commandName)) {
|
|
4298
|
+
await _promptInteractionSurface.dispatchSlash(trimmed);
|
|
4299
|
+
prompt();
|
|
4300
|
+
return;
|
|
4301
|
+
}
|
|
4302
|
+
}
|
|
4303
|
+
|
|
2361
4304
|
if (trimmed === "/help") {
|
|
2362
4305
|
logger.log(chalk.bold("\nCommands:"));
|
|
2363
4306
|
logger.log(
|
|
@@ -2383,7 +4326,13 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
2383
4326
|
` ${chalk.cyan("/effort")} Reasoning effort (/effort low|medium|high|xhigh; Anthropic)`,
|
|
2384
4327
|
);
|
|
2385
4328
|
logger.log(
|
|
2386
|
-
` ${chalk.cyan("/btw")}
|
|
4329
|
+
` ${chalk.cyan("/btw")} Ask an immediate tool-free side question (/btw [--fork] <question>)`,
|
|
4330
|
+
);
|
|
4331
|
+
logger.log(
|
|
4332
|
+
` ${chalk.cyan("/advisor")} Independent tool-free critic (/advisor on|off|once [focus]|status)`,
|
|
4333
|
+
);
|
|
4334
|
+
logger.log(
|
|
4335
|
+
` ${chalk.cyan("/note-next")} Apply ephemeral guidance to the next main turn`,
|
|
2387
4336
|
);
|
|
2388
4337
|
logger.log(` ${chalk.cyan("/clear")} Clear conversation`);
|
|
2389
4338
|
logger.log(
|
|
@@ -2410,6 +4359,21 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
2410
4359
|
logger.log(
|
|
2411
4360
|
` ${chalk.cyan("/output-style")} Response persona (/output-style <name|list>; explanatory/learning built-in)`,
|
|
2412
4361
|
);
|
|
4362
|
+
logger.log(
|
|
4363
|
+
` ${chalk.cyan("/editor")} Edit a draft prompt in an external editor`,
|
|
4364
|
+
);
|
|
4365
|
+
logger.log(
|
|
4366
|
+
` ${chalk.cyan("/stash")} Stash/list/pop/clear draft prompts`,
|
|
4367
|
+
);
|
|
4368
|
+
logger.log(
|
|
4369
|
+
` ${chalk.cyan("/recap")} Show a lightweight session recap`,
|
|
4370
|
+
);
|
|
4371
|
+
logger.log(
|
|
4372
|
+
` ${chalk.cyan("/suggestions")} Prompt suggestions on|off|status|refresh`,
|
|
4373
|
+
);
|
|
4374
|
+
logger.log(
|
|
4375
|
+
` ${chalk.cyan("/paste-image")} Attach a clipboard image from a supporting host`,
|
|
4376
|
+
);
|
|
2413
4377
|
logger.log(
|
|
2414
4378
|
` ${chalk.cyan("/config")} Show config; ${chalk.cyan("/config <key>")} read, ${chalk.cyan("/config <key>=<val>")} set, ${chalk.cyan("/config --help")} keys`,
|
|
2415
4379
|
);
|
|
@@ -2922,22 +4886,52 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
2922
4886
|
}
|
|
2923
4887
|
}
|
|
2924
4888
|
|
|
2925
|
-
// `/btw
|
|
2926
|
-
//
|
|
4889
|
+
// `/btw` is an immediate, tool-free side question over a snapshot of the
|
|
4890
|
+
// current context. It never mutates or persists into the parent history.
|
|
2927
4891
|
{
|
|
2928
4892
|
const btw = parseBtwCommand(trimmed);
|
|
2929
4893
|
if (btw) {
|
|
2930
|
-
|
|
2931
|
-
|
|
2932
|
-
|
|
2933
|
-
|
|
4894
|
+
await runBtwSideQuestion(btw);
|
|
4895
|
+
prompt();
|
|
4896
|
+
return;
|
|
4897
|
+
}
|
|
4898
|
+
}
|
|
4899
|
+
|
|
4900
|
+
// `/advisor`: session-local enable/disable, one forced review, or status.
|
|
4901
|
+
// One-shot advice is queued as an ephemeral prepareCall suffix, requiring
|
|
4902
|
+
// the main agent to validate it locally on its next model/tool turn.
|
|
4903
|
+
{
|
|
4904
|
+
const { parseAdvisorCommand, executeAdvisorCommand } =
|
|
4905
|
+
await import("./advisor-command.js");
|
|
4906
|
+
const advisorCommand = parseAdvisorCommand(trimmed);
|
|
4907
|
+
if (advisorCommand) {
|
|
4908
|
+
const result = await executeAdvisorCommand(advisorCommand, {
|
|
4909
|
+
runtime: _advisorRuntime,
|
|
4910
|
+
messages,
|
|
4911
|
+
signal: _turnAbort?.signal || null,
|
|
4912
|
+
});
|
|
4913
|
+
if (result?.output) logger.log(result.output);
|
|
4914
|
+
if (result?.guidance) {
|
|
4915
|
+
_advisorRuntime?.queueGuidance(result.guidance);
|
|
4916
|
+
}
|
|
4917
|
+
prompt();
|
|
4918
|
+
return;
|
|
4919
|
+
}
|
|
4920
|
+
}
|
|
4921
|
+
|
|
4922
|
+
// Preserve the previous next-turn guidance behavior under an honest name.
|
|
4923
|
+
{
|
|
4924
|
+
const note = parseNoteNextCommand(trimmed);
|
|
4925
|
+
if (note) {
|
|
4926
|
+
if (note.error) logger.info(note.error);
|
|
4927
|
+
else {
|
|
4928
|
+
pendingBtw.push(note.text);
|
|
4929
|
+
logger.info(
|
|
4930
|
+
chalk.gray(
|
|
4931
|
+
`Next-turn note queued (${pendingBtw.length}); it will not be saved to history.`,
|
|
4932
|
+
),
|
|
4933
|
+
);
|
|
2934
4934
|
}
|
|
2935
|
-
pendingBtw.push(btw.text);
|
|
2936
|
-
logger.info(
|
|
2937
|
-
chalk.gray(
|
|
2938
|
-
`Aside noted (${pendingBtw.length}) — rides your next message only, not saved to history.`,
|
|
2939
|
-
),
|
|
2940
|
-
);
|
|
2941
4935
|
prompt();
|
|
2942
4936
|
return;
|
|
2943
4937
|
}
|
|
@@ -3680,6 +5674,11 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
3680
5674
|
logger.info(
|
|
3681
5675
|
`Compacted: ${stats.originalMessages} → ${stats.compressedMessages} messages, saved ${stats.saved} tokens (${stats.strategy})`,
|
|
3682
5676
|
);
|
|
5677
|
+
if (stats.degraded === true) {
|
|
5678
|
+
logger.warn(
|
|
5679
|
+
`Semantic compaction degraded to ${stats.summaryMode}: ${stats.degradedReason}`,
|
|
5680
|
+
);
|
|
5681
|
+
}
|
|
3683
5682
|
} else if (contextEngine && messages.length > 5) {
|
|
3684
5683
|
const compacted = contextEngine.smartCompact(messages);
|
|
3685
5684
|
messages.length = 0;
|
|
@@ -3747,39 +5746,40 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
3747
5746
|
if (sessionArg.startsWith("resume ")) {
|
|
3748
5747
|
const resumeId = sessionArg.slice(7).trim();
|
|
3749
5748
|
try {
|
|
3750
|
-
if (useJsonl
|
|
3751
|
-
|
|
3752
|
-
|
|
3753
|
-
|
|
3754
|
-
|
|
3755
|
-
|
|
3756
|
-
|
|
3757
|
-
|
|
3758
|
-
|
|
3759
|
-
|
|
3760
|
-
|
|
3761
|
-
|
|
3762
|
-
|
|
3763
|
-
|
|
3764
|
-
|
|
3765
|
-
|
|
3766
|
-
|
|
3767
|
-
|
|
3768
|
-
|
|
3769
|
-
|
|
3770
|
-
|
|
3771
|
-
|
|
3772
|
-
|
|
3773
|
-
|
|
3774
|
-
|
|
3775
|
-
// no longer map to this swapped-in history; keeping them would make
|
|
3776
|
-
// a later /rewind restore files from the WRONG session's snapshot.
|
|
3777
|
-
// Same reset /clear does on a context swap.
|
|
3778
|
-
_checkpointMarks.length = 0;
|
|
3779
|
-
_clearedConversation = null; // stash belongs to the swapped-out session
|
|
3780
|
-
logger.info(
|
|
3781
|
-
`Resumed JSONL session ${sessionId} (${rebuilt.length} messages)`,
|
|
5749
|
+
if (useJsonl) {
|
|
5750
|
+
const prepared = _prepareJsonlResumeCandidate(resumeId);
|
|
5751
|
+
if (!prepared.ok) throw prepared.error;
|
|
5752
|
+
const preparedMcpRuntime = _prepareMcpHostRuntime(
|
|
5753
|
+
prepared.sessionId,
|
|
5754
|
+
prepared.mcp,
|
|
5755
|
+
);
|
|
5756
|
+
const preparedMcpCommit = _prepareMcpRecoveryCommit(prepared.mcp);
|
|
5757
|
+
const hostSystemMessages = _refreshHostSystemMessages();
|
|
5758
|
+
const previousState = _captureResumeState();
|
|
5759
|
+
const preparedState = Object.freeze({
|
|
5760
|
+
sessionId: prepared.sessionId,
|
|
5761
|
+
hostSystemMessages,
|
|
5762
|
+
canonicalSystemMessages: prepared.canonicalSystemMessages,
|
|
5763
|
+
conversationMessages: prepared.conversationMessages,
|
|
5764
|
+
mcpCommit: preparedMcpCommit,
|
|
5765
|
+
mcpRuntime: preparedMcpRuntime,
|
|
5766
|
+
sanitizeRolesNextTurn:
|
|
5767
|
+
prepared.conversationMessages.at(-1)?.role === "user",
|
|
5768
|
+
logMessage: `Resumed JSONL session ${prepared.sessionId} (${prepared.rebuiltMessages.length} messages)`,
|
|
5769
|
+
});
|
|
5770
|
+
const committed = commitPreparedReplJsonlResume(
|
|
5771
|
+
prepared,
|
|
5772
|
+
() => _applyPreparedResumeState(preparedState),
|
|
5773
|
+
() => _restoreResumeState(previousState),
|
|
3782
5774
|
);
|
|
5775
|
+
if (!committed) {
|
|
5776
|
+
const error = new Error(
|
|
5777
|
+
"Prepared JSONL session resume was not committed",
|
|
5778
|
+
);
|
|
5779
|
+
error.code = "CC_REPL_SESSION_RESUME_NOT_COMMITTED";
|
|
5780
|
+
throw error;
|
|
5781
|
+
}
|
|
5782
|
+
_replCompactPersistence.replace(prepared.rebuiltMessages);
|
|
3783
5783
|
} else if (db) {
|
|
3784
5784
|
const existing = getSession(db, resumeId);
|
|
3785
5785
|
if (existing && existing.messages) {
|
|
@@ -3787,18 +5787,35 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
3787
5787
|
typeof existing.messages === "string"
|
|
3788
5788
|
? JSON.parse(existing.messages)
|
|
3789
5789
|
: existing.messages;
|
|
3790
|
-
|
|
3791
|
-
|
|
3792
|
-
|
|
3793
|
-
|
|
3794
|
-
|
|
3795
|
-
|
|
3796
|
-
|
|
3797
|
-
|
|
3798
|
-
|
|
3799
|
-
|
|
3800
|
-
|
|
3801
|
-
|
|
5790
|
+
const rebuiltMessages = snapshotReplMessages(parsed);
|
|
5791
|
+
const replayMessages = Object.freeze(
|
|
5792
|
+
rebuiltMessages.filter((message) => message.role !== "system"),
|
|
5793
|
+
);
|
|
5794
|
+
const preparedMcpRuntime = _prepareMcpHostRuntime(existing.id, {
|
|
5795
|
+
recovery: null,
|
|
5796
|
+
recoveryError: null,
|
|
5797
|
+
});
|
|
5798
|
+
const hostSystemMessages = _refreshHostSystemMessages();
|
|
5799
|
+
const previousState = _captureResumeState();
|
|
5800
|
+
const preparedState = Object.freeze({
|
|
5801
|
+
sessionId: existing.id,
|
|
5802
|
+
hostSystemMessages,
|
|
5803
|
+
canonicalSystemMessages: Object.freeze([]),
|
|
5804
|
+
conversationMessages: replayMessages,
|
|
5805
|
+
mcpCommit: Object.freeze({
|
|
5806
|
+
recovery: null,
|
|
5807
|
+
recoveryError: null,
|
|
5808
|
+
noticeMessage: null,
|
|
5809
|
+
warning: null,
|
|
5810
|
+
}),
|
|
5811
|
+
mcpRuntime: preparedMcpRuntime,
|
|
5812
|
+
sanitizeRolesNextTurn: replayMessages.at(-1)?.role === "user",
|
|
5813
|
+
logMessage: `Resumed session ${existing.id} (${rebuiltMessages.length} messages)`,
|
|
5814
|
+
});
|
|
5815
|
+
commitPreparedReplDbResume(
|
|
5816
|
+
preparedState,
|
|
5817
|
+
() => _applyPreparedResumeState(preparedState),
|
|
5818
|
+
() => _restoreResumeState(previousState),
|
|
3802
5819
|
);
|
|
3803
5820
|
} else {
|
|
3804
5821
|
logger.info(`Session not found: ${resumeId}`);
|
|
@@ -3807,7 +5824,14 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
3807
5824
|
logger.info("No session store available");
|
|
3808
5825
|
}
|
|
3809
5826
|
} catch (err) {
|
|
3810
|
-
logger.error(
|
|
5827
|
+
logger.error(
|
|
5828
|
+
JSON.stringify({
|
|
5829
|
+
type: "session.resume.refused",
|
|
5830
|
+
code: err?.code || "CC_REPL_SESSION_RESUME_FAILED",
|
|
5831
|
+
sessionId: resumeId,
|
|
5832
|
+
message: err?.message || "Session resume failed",
|
|
5833
|
+
}),
|
|
5834
|
+
);
|
|
3811
5835
|
}
|
|
3812
5836
|
} else {
|
|
3813
5837
|
logger.info(`Session ID: ${sessionId || "none"}`);
|
|
@@ -3856,15 +5880,30 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
3856
5880
|
|
|
3857
5881
|
// Re-merge plugin hooks onto the user's settings hooks (live session).
|
|
3858
5882
|
try {
|
|
3859
|
-
const { loadHooks } =
|
|
5883
|
+
const { loadHooks, attachAuthorityErrors } =
|
|
5884
|
+
await import("../lib/settings-hooks.cjs");
|
|
3860
5885
|
const { mergePluginHooks } =
|
|
3861
5886
|
await import("../lib/plugin-runtime/hooks.js");
|
|
3862
|
-
const
|
|
3863
|
-
const merged = mergePluginHooks(
|
|
5887
|
+
const loaded = loadHooks({ cwd });
|
|
5888
|
+
const merged = mergePluginHooks(
|
|
5889
|
+
attachAuthorityErrors(loaded.hooks, loaded.authorityErrors),
|
|
5890
|
+
{ cwd },
|
|
5891
|
+
);
|
|
3864
5892
|
_settingsHooks =
|
|
3865
|
-
|
|
3866
|
-
|
|
3867
|
-
|
|
5893
|
+
Object.keys(merged).length > 0 || merged._authorityErrors.length > 0
|
|
5894
|
+
? merged
|
|
5895
|
+
: null;
|
|
5896
|
+
} catch (error) {
|
|
5897
|
+
_settingsHooks = {};
|
|
5898
|
+
Object.defineProperty(_settingsHooks, "_authorityErrors", {
|
|
5899
|
+
value: Object.freeze([
|
|
5900
|
+
Object.freeze({
|
|
5901
|
+
sourceFile: null,
|
|
5902
|
+
code: error?.code || "CC_HOOK_AUTHORITY_LOAD_FAILED",
|
|
5903
|
+
}),
|
|
5904
|
+
]),
|
|
5905
|
+
enumerable: false,
|
|
5906
|
+
});
|
|
3868
5907
|
}
|
|
3869
5908
|
|
|
3870
5909
|
// settings.json ConfigChange hooks (Claude-Code parity): the live
|
|
@@ -4512,6 +6551,31 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
4512
6551
|
"Plan has no items yet. Let the AI analyze the task first.",
|
|
4513
6552
|
);
|
|
4514
6553
|
} else {
|
|
6554
|
+
// Review this immutable plan version before approval. Advisor output
|
|
6555
|
+
// cannot block or approve the plan and grants no extra authority; its
|
|
6556
|
+
// local-verification checklist is queued for the next main turn.
|
|
6557
|
+
if (_advisorRuntime?.status().enabled) {
|
|
6558
|
+
try {
|
|
6559
|
+
const result = await _advisorRuntime.reviewPlan(
|
|
6560
|
+
{
|
|
6561
|
+
id: planManager.currentPlan.id,
|
|
6562
|
+
title: planManager.currentPlan.title,
|
|
6563
|
+
description: planManager.currentPlan.description,
|
|
6564
|
+
summary: planManager.generatePlanSummary(),
|
|
6565
|
+
},
|
|
6566
|
+
{ messages, signal: _turnAbort?.signal || null },
|
|
6567
|
+
);
|
|
6568
|
+
if (result.ok) {
|
|
6569
|
+
const { renderAdvisorAdvice } =
|
|
6570
|
+
await import("./advisor-command.js");
|
|
6571
|
+
logger.log(renderAdvisorAdvice(result));
|
|
6572
|
+
} else if (result.effect !== "disabled") {
|
|
6573
|
+
logger.warn(result.error);
|
|
6574
|
+
}
|
|
6575
|
+
} catch (error) {
|
|
6576
|
+
logger.warn(`Advisor plan review skipped: ${error.message}`);
|
|
6577
|
+
}
|
|
6578
|
+
}
|
|
4515
6579
|
planManager.approvePlan();
|
|
4516
6580
|
logger.success(
|
|
4517
6581
|
`Plan approved! ${planManager.currentPlan.items.length} items ready for execution.`,
|
|
@@ -4688,7 +6752,7 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
4688
6752
|
|
|
4689
6753
|
// `/mcp` — overview of connected MCP servers' resources + prompts.
|
|
4690
6754
|
if (trimmed === "/mcp" || trimmed.startsWith("/mcp ")) {
|
|
4691
|
-
const mcpClient =
|
|
6755
|
+
const mcpClient = _getReplHostMcp()?.mcpClient;
|
|
4692
6756
|
logger.log(renderMcpSurface(mcpClient));
|
|
4693
6757
|
prompt();
|
|
4694
6758
|
return;
|
|
@@ -4715,7 +6779,12 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
4715
6779
|
} else if (cmd.action === "help") {
|
|
4716
6780
|
logger.log(renderConfigHelp());
|
|
4717
6781
|
} else if (cmd.action === "get") {
|
|
4718
|
-
logger.log(
|
|
6782
|
+
logger.log(
|
|
6783
|
+
renderConfigGet(
|
|
6784
|
+
cmd.key,
|
|
6785
|
+
cm.getConfigValue(cmd.key, { resolveSecrets: false }),
|
|
6786
|
+
),
|
|
6787
|
+
);
|
|
4719
6788
|
} else if (cmd.action === "set") {
|
|
4720
6789
|
cm.setConfigValue(cmd.key, cmd.value);
|
|
4721
6790
|
logger.log(
|
|
@@ -5127,7 +7196,7 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
5127
7196
|
try {
|
|
5128
7197
|
const expanded = await expandMcpPrompt(
|
|
5129
7198
|
promptText,
|
|
5130
|
-
|
|
7199
|
+
_getReplHostMcp()?.mcpClient,
|
|
5131
7200
|
);
|
|
5132
7201
|
if (expanded != null) {
|
|
5133
7202
|
promptText = expanded;
|
|
@@ -5200,7 +7269,7 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
5200
7269
|
}
|
|
5201
7270
|
|
|
5202
7271
|
// Backstop: if the previous turn's agentLoop threw before the success-path
|
|
5203
|
-
// restore ran, undo its /
|
|
7272
|
+
// restore ran, undo its /note-next guidance so it never leaks into this turn's
|
|
5204
7273
|
// history/model call. (Normal turns clear _btwRestore right after agentLoop.)
|
|
5205
7274
|
if (_btwRestore) {
|
|
5206
7275
|
_btwRestore.msg.content = _btwRestore.content;
|
|
@@ -5350,11 +7419,12 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
5350
7419
|
try {
|
|
5351
7420
|
const { buildIdePromptContext, expandIdeMentions } =
|
|
5352
7421
|
await import("../lib/ide-context.js");
|
|
5353
|
-
const
|
|
7422
|
+
const hostMcp = _getReplHostMcp();
|
|
7423
|
+
const ideCtx = await buildIdePromptContext(hostMcp);
|
|
5354
7424
|
if (ideCtx) userContent += `\n\n${ideCtx}`;
|
|
5355
7425
|
// Explicit @selection / @diagnostics mentions (Claude-Code parity);
|
|
5356
7426
|
// scan the user's original prompt, append the expansion ephemerally.
|
|
5357
|
-
const mentioned = await expandIdeMentions(effectivePrompt,
|
|
7427
|
+
const mentioned = await expandIdeMentions(effectivePrompt, hostMcp);
|
|
5358
7428
|
for (const w of mentioned.warnings) {
|
|
5359
7429
|
logger.info(chalk.yellow(`[@ide] ${w}`));
|
|
5360
7430
|
}
|
|
@@ -5404,7 +7474,36 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
5404
7474
|
return;
|
|
5405
7475
|
}
|
|
5406
7476
|
|
|
5407
|
-
//
|
|
7477
|
+
// Explicit clipboard attachment chips are consumed only when a real model
|
|
7478
|
+
// turn is about to start. They compose with auto-detected path images and
|
|
7479
|
+
// enter the same provider-neutral multimodal message/vision override.
|
|
7480
|
+
const clipboardImageChips = _promptInteractions.takeClipboardImageChips();
|
|
7481
|
+
const clipboardMerge = mergeClipboardImageChips(
|
|
7482
|
+
_userMessageContent,
|
|
7483
|
+
clipboardImageChips,
|
|
7484
|
+
);
|
|
7485
|
+
if (clipboardMerge.attached > 0) {
|
|
7486
|
+
_userMessageContent = clipboardMerge.content;
|
|
7487
|
+
if (!_visionLlm) {
|
|
7488
|
+
_visionLlm = resolveVisionLlm({
|
|
7489
|
+
hasImage: true,
|
|
7490
|
+
flags: {},
|
|
7491
|
+
llm: {
|
|
7492
|
+
provider,
|
|
7493
|
+
baseUrl,
|
|
7494
|
+
apiKey,
|
|
7495
|
+
visionModel: _visionModel,
|
|
7496
|
+
},
|
|
7497
|
+
});
|
|
7498
|
+
}
|
|
7499
|
+
logger.info(
|
|
7500
|
+
chalk.gray(
|
|
7501
|
+
`[image] ${clipboardMerge.attached} clipboard image(s) attached -> vision model ${_visionLlm.model}`,
|
|
7502
|
+
),
|
|
7503
|
+
);
|
|
7504
|
+
}
|
|
7505
|
+
|
|
7506
|
+
// Add user message (keep the object ref so /note-next can be injected for
|
|
5408
7507
|
// this turn's model call and then stripped before persistence).
|
|
5409
7508
|
const _userMsg = { role: "user", content: _userMessageContent };
|
|
5410
7509
|
messages.push(_userMsg);
|
|
@@ -5466,7 +7565,17 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
5466
7565
|
.map(([k, v]) => `${k}: ${v}`);
|
|
5467
7566
|
// Append context to the last user message
|
|
5468
7567
|
const lastMsg = messages[messages.length - 1];
|
|
5469
|
-
|
|
7568
|
+
const slotContext = `[Context - user provided: ${parts.join(", ")}]`;
|
|
7569
|
+
if (Array.isArray(lastMsg.content)) {
|
|
7570
|
+
const textPart = lastMsg.content.find(
|
|
7571
|
+
(part) => part?.type === "text",
|
|
7572
|
+
);
|
|
7573
|
+
if (textPart)
|
|
7574
|
+
textPart.text = `${textPart.text}\n\n${slotContext}`;
|
|
7575
|
+
else lastMsg.content.unshift({ type: "text", text: slotContext });
|
|
7576
|
+
} else {
|
|
7577
|
+
lastMsg.content = `${lastMsg.content}\n\n${slotContext}`;
|
|
7578
|
+
}
|
|
5470
7579
|
logger.info(chalk.gray(`[slot-fill] ${parts.join(", ")}`));
|
|
5471
7580
|
}
|
|
5472
7581
|
}
|
|
@@ -5544,6 +7653,28 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
5544
7653
|
/* goal binding is best-effort — fall back to defaultPrepareCall */
|
|
5545
7654
|
}
|
|
5546
7655
|
_turnAbort = new AbortController();
|
|
7656
|
+
if (_advisorRuntime) {
|
|
7657
|
+
_advisorRuntime.beginTurn(
|
|
7658
|
+
`${sessionId || "ephemeral"}:${_turnCount + 1}`,
|
|
7659
|
+
);
|
|
7660
|
+
prepareCall = _advisorRuntime.createPrepareCall({
|
|
7661
|
+
messages,
|
|
7662
|
+
basePrepareCall: prepareCall,
|
|
7663
|
+
subject: promptText,
|
|
7664
|
+
signal: _turnAbort.signal,
|
|
7665
|
+
onAdvice: async (result) => {
|
|
7666
|
+
if (!result.ok) {
|
|
7667
|
+
if (result.effect !== "disabled") {
|
|
7668
|
+
process.stderr.write(` Advisor: ${result.error}\n`);
|
|
7669
|
+
}
|
|
7670
|
+
return;
|
|
7671
|
+
}
|
|
7672
|
+
const { renderAdvisorAdvice } =
|
|
7673
|
+
await import("./advisor-command.js");
|
|
7674
|
+
process.stderr.write(`\n${renderAdvisorAdvice(result)}\n`);
|
|
7675
|
+
},
|
|
7676
|
+
});
|
|
7677
|
+
}
|
|
5547
7678
|
// Live streaming hooks: write the answer token-by-token, and stream the
|
|
5548
7679
|
// reasoning dimmed before it. Skipped (left undefined) in replay mode.
|
|
5549
7680
|
let _liveStreamed = false;
|
|
@@ -5568,7 +7699,7 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
5568
7699
|
}
|
|
5569
7700
|
: {};
|
|
5570
7701
|
if (_streamLive) process.stdout.write("\n");
|
|
5571
|
-
// Inject
|
|
7702
|
+
// Inject queued /note-next guidance into THIS turn just before
|
|
5572
7703
|
// the model call. We remember the pre-aside content so it's restored right
|
|
5573
7704
|
// after agentLoop returns — the aside steers this answer but is never
|
|
5574
7705
|
// persisted (saveMessages/JSONL) or carried into later turns. Consumed on
|
|
@@ -5580,7 +7711,7 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
5580
7711
|
_btwRestore = { msg: _userMsg, content: _userMsg.content };
|
|
5581
7712
|
_userMsg.content = applyAside(_userMsg.content, block);
|
|
5582
7713
|
logger.verbose(
|
|
5583
|
-
`[
|
|
7714
|
+
`[note-next] applied ${pendingBtw.length} note(s) to this turn`,
|
|
5584
7715
|
);
|
|
5585
7716
|
}
|
|
5586
7717
|
pendingBtw = [];
|
|
@@ -5597,6 +7728,8 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
5597
7728
|
await import("../lib/async-hook-supervisor.js");
|
|
5598
7729
|
_asyncHookSupervisor = new AsyncHookSupervisor({ persistStats: true });
|
|
5599
7730
|
}
|
|
7731
|
+
const activeMcpRuntime = _activateMcpHostRuntime();
|
|
7732
|
+
const activeRawMcpClient = activeMcpRuntime.rawClient || undefined;
|
|
5600
7733
|
const {
|
|
5601
7734
|
content: response,
|
|
5602
7735
|
usageEvents,
|
|
@@ -5701,16 +7834,21 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
5701
7834
|
interactiveApproval: true,
|
|
5702
7835
|
// MCP: --mcp-config (ad-hoc) wins; bundle MCP is the fallback. The 3
|
|
5703
7836
|
// tool channels expose --mcp-config servers' tools to the LLM directly.
|
|
5704
|
-
mcpClient:
|
|
7837
|
+
mcpClient: activeRawMcpClient,
|
|
7838
|
+
mcpHostClient: activeMcpRuntime.runtime.client,
|
|
5705
7839
|
extraToolDefinitions: _adhocMcp?.extraToolDefinitions,
|
|
5706
7840
|
externalToolExecutors: _adhocMcp?.externalToolExecutors,
|
|
5707
7841
|
externalToolDescriptors: _adhocMcp?.externalToolDescriptors,
|
|
7842
|
+
// The recovery controller is required even when this legacy/ephemeral
|
|
7843
|
+
// session has no durable sink. Otherwise an outcome-unknown call could
|
|
7844
|
+
// be retried in the same process after agent-core creates a plain ledger.
|
|
7845
|
+
mcpCallLedger: activeMcpRuntime.runtime.ledger,
|
|
5708
7846
|
chatFn: _fallbackChatFn,
|
|
5709
7847
|
});
|
|
5710
7848
|
_persistReplContextSources();
|
|
5711
7849
|
_turnAbort = null;
|
|
5712
7850
|
|
|
5713
|
-
// Strip
|
|
7851
|
+
// Strip one-shot /note-next guidance now the model has seen it so it is never
|
|
5714
7852
|
// persisted (DB saveMessages below) or carried into the next turn.
|
|
5715
7853
|
if (_btwRestore) {
|
|
5716
7854
|
_btwRestore.msg.content = _btwRestore.content;
|
|
@@ -5879,14 +8017,31 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
5879
8017
|
);
|
|
5880
8018
|
}
|
|
5881
8019
|
|
|
8020
|
+
// Generate follow-up suggestions from the settled assistant turn. The
|
|
8021
|
+
// controller snapshots the actual conversation context and debounces in
|
|
8022
|
+
// the background, so readline and persistence remain non-blocking.
|
|
8023
|
+
const suggestionRun = _promptInteractions.scheduleSuggestions({
|
|
8024
|
+
messages: messages.slice(),
|
|
8025
|
+
lastAssistantText: effectiveResponse || "",
|
|
8026
|
+
});
|
|
8027
|
+
void suggestionRun.promise;
|
|
8028
|
+
|
|
5882
8029
|
// Auto-save session
|
|
5883
8030
|
if (sessionId) {
|
|
5884
8031
|
try {
|
|
5885
8032
|
if (useJsonl) {
|
|
5886
8033
|
// Append incremental events (user + assistant)
|
|
5887
8034
|
appendUserMessage(sessionId, effectivePrompt);
|
|
8035
|
+
_replCompactPersistence.record({
|
|
8036
|
+
role: "user",
|
|
8037
|
+
content: effectivePrompt,
|
|
8038
|
+
});
|
|
5888
8039
|
if (effectiveResponse) {
|
|
5889
8040
|
appendAssistantMessage(sessionId, effectiveResponse);
|
|
8041
|
+
_replCompactPersistence.record({
|
|
8042
|
+
role: "assistant",
|
|
8043
|
+
content: effectiveResponse,
|
|
8044
|
+
});
|
|
5890
8045
|
}
|
|
5891
8046
|
} else if (db) {
|
|
5892
8047
|
saveMessages(db, sessionId, messages);
|
|
@@ -5921,16 +8076,21 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
5921
8076
|
logger.verbose(
|
|
5922
8077
|
`Auto-compacted: ${stats.strategy} (saved ${stats.saved} tokens)`,
|
|
5923
8078
|
);
|
|
8079
|
+
if (stats.degraded === true) {
|
|
8080
|
+
logger.warn(
|
|
8081
|
+
`Auto-compaction degraded to ${stats.summaryMode}: ${stats.degradedReason}`,
|
|
8082
|
+
);
|
|
8083
|
+
}
|
|
5924
8084
|
// Write compact checkpoint to JSONL for crash recovery
|
|
5925
8085
|
if (useJsonl && sessionId) {
|
|
5926
|
-
|
|
8086
|
+
_replCompactPersistence.persist(sessionId, {
|
|
5927
8087
|
...stats,
|
|
5928
8088
|
messages: compacted,
|
|
5929
8089
|
});
|
|
5930
8090
|
}
|
|
5931
8091
|
}
|
|
5932
8092
|
} catch (_e) {
|
|
5933
|
-
|
|
8093
|
+
logger.warn(`Auto-compaction failed: ${_e.message}`);
|
|
5934
8094
|
}
|
|
5935
8095
|
}
|
|
5936
8096
|
|
|
@@ -6011,6 +8171,15 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
6011
8171
|
|
|
6012
8172
|
rl.on("line", async (input) => {
|
|
6013
8173
|
if (_processingLine) {
|
|
8174
|
+
const concurrentBtw = _slashCommandsDisabled
|
|
8175
|
+
? null
|
|
8176
|
+
: parseBtwCommand(input.trim());
|
|
8177
|
+
if (concurrentBtw) {
|
|
8178
|
+
// Intentionally do not await: the main turn keeps streaming while this
|
|
8179
|
+
// independent, tool-free snapshot call runs alongside it.
|
|
8180
|
+
void runBtwSideQuestion(concurrentBtw, { concurrent: true });
|
|
8181
|
+
return;
|
|
8182
|
+
}
|
|
6014
8183
|
if (input.trim()) {
|
|
6015
8184
|
_pendingLines.push(input);
|
|
6016
8185
|
logger.log(
|
|
@@ -6035,6 +8204,15 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
6035
8204
|
});
|
|
6036
8205
|
|
|
6037
8206
|
rl.on("close", async () => {
|
|
8207
|
+
_promptInteractions.dispose();
|
|
8208
|
+
if (process.stdin.isTTY) {
|
|
8209
|
+
if (_replKeypressHandler) {
|
|
8210
|
+
process.stdin.removeListener("keypress", _replKeypressHandler);
|
|
8211
|
+
}
|
|
8212
|
+
for (const listener of _rlKeypressListeners) {
|
|
8213
|
+
process.stdin.removeListener("keypress", listener);
|
|
8214
|
+
}
|
|
8215
|
+
}
|
|
6038
8216
|
// Leave the alternate screen buffer first so the terminal is restored to
|
|
6039
8217
|
// the user's scrollback no matter how the REPL exits.
|
|
6040
8218
|
if (_tuiMode === "fullscreen" && process.stdout.isTTY) {
|
|
@@ -6075,7 +8253,7 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
6075
8253
|
if (useJsonl) {
|
|
6076
8254
|
_persistReplContextSources();
|
|
6077
8255
|
// JSONL: write final compact snapshot for fast rebuild
|
|
6078
|
-
|
|
8256
|
+
_replCompactPersistence.persist(sessionId, {
|
|
6079
8257
|
strategy: "session-end",
|
|
6080
8258
|
messages,
|
|
6081
8259
|
});
|
|
@@ -6083,7 +8261,7 @@ async function startAgentReplInWorkspace(options = {}) {
|
|
|
6083
8261
|
saveMessages(db, sessionId, messages);
|
|
6084
8262
|
}
|
|
6085
8263
|
} catch (_e) {
|
|
6086
|
-
|
|
8264
|
+
logger.warn(`Session-end compact not persisted: ${_e.message}`);
|
|
6087
8265
|
}
|
|
6088
8266
|
}
|
|
6089
8267
|
// Auto-summarize session into permanent memory
|