zidane 9.1.1 → 9.1.3
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/dist/{acp-Di9WvMDF.js → acp-CeCavNlg.js} +7 -7
- package/dist/{acp-Di9WvMDF.js.map → acp-CeCavNlg.js.map} +1 -1
- package/dist/acp-cli.js +5 -5
- package/dist/acp.d.ts +2 -2
- package/dist/acp.js +1 -1
- package/dist/{agent-DJhpTS-B.js → agent-Dh_XZ7fj.js} +74 -19
- package/dist/agent-Dh_XZ7fj.js.map +1 -0
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +1 -1
- package/dist/{auth-store-port-DFgf22oo.js → auth-store-port-BKpjlJ8a.js} +2 -2
- package/dist/{auth-store-port-DFgf22oo.js.map → auth-store-port-BKpjlJ8a.js.map} +1 -1
- package/dist/{auto-update-restart-BFB7Ek87.js → auto-update-restart-CQJtndMG.js} +277 -41
- package/dist/auto-update-restart-CQJtndMG.js.map +1 -0
- package/dist/{browser-BcoCCB_n.js → browser-BkdeKnxO.js} +56 -2
- package/dist/browser-BkdeKnxO.js.map +1 -0
- package/dist/{browser-entry-ypi8CyE-.d.ts → browser-entry-BCwruqNa.d.ts} +10 -10
- package/dist/{browser-entry-ypi8CyE-.d.ts.map → browser-entry-BCwruqNa.d.ts.map} +1 -1
- package/dist/channels.d.ts +5 -5
- package/dist/chat/browser.d.ts +4 -4
- package/dist/chat/browser.js +6 -6
- package/dist/chat/pure.d.ts +5 -5
- package/dist/chat/pure.js +8 -8
- package/dist/chat.d.ts +5 -5
- package/dist/chat.js +55 -55
- package/dist/chat.js.map +1 -1
- package/dist/{cli-shared-CabruH8Z.js → cli-shared-DeRHgYvl.js} +4 -4
- package/dist/{cli-shared-CabruH8Z.js.map → cli-shared-DeRHgYvl.js.map} +1 -1
- package/dist/cli-style-DBEm6CyT.js +105 -0
- package/dist/cli-style-DBEm6CyT.js.map +1 -0
- package/dist/{client-core-CIixwznM.d.ts → client-core-C_4m_oL6.d.ts} +4 -4
- package/dist/{client-core-CIixwznM.d.ts.map → client-core-C_4m_oL6.d.ts.map} +1 -1
- package/dist/{client-CCaIXWue.d.ts → client-ygTASGis.d.ts} +2 -2
- package/dist/{client-CCaIXWue.d.ts.map → client-ygTASGis.d.ts.map} +1 -1
- package/dist/codemode-worker.js +8 -5
- package/dist/codemode-worker.js.map +1 -1
- package/dist/codemode.d.ts +16 -0
- package/dist/codemode.d.ts.map +1 -1
- package/dist/codemode.js +2 -2
- package/dist/{connection-loop-QmWL-fJf.d.ts → connection-loop-D_pRONCr.d.ts} +4 -4
- package/dist/{connection-loop-QmWL-fJf.d.ts.map → connection-loop-D_pRONCr.d.ts.map} +1 -1
- package/dist/contexts/daytona.d.ts +3 -3
- package/dist/contexts/docker.d.ts +1 -1
- package/dist/contexts/e2b.d.ts +2 -2
- package/dist/contexts/sandbox.d.ts +1 -1
- package/dist/{contexts-C72b0mMa.js → contexts-DLZTSRHU.js} +17 -106
- package/dist/contexts-DLZTSRHU.js.map +1 -0
- package/dist/contexts.d.ts +4 -4
- package/dist/contexts.js +2 -2
- package/dist/{credentials-wwETW8rI.js → credentials-Bqg-qNBM.js} +2 -2
- package/dist/{credentials-wwETW8rI.js.map → credentials-Bqg-qNBM.js.map} +1 -1
- package/dist/{cwd-picker-CcekODCt.js → cwd-picker-BsHA6HKv.js} +4 -4
- package/dist/{cwd-picker-CcekODCt.js.map → cwd-picker-BsHA6HKv.js.map} +1 -1
- package/dist/daemon-cli.js +4 -3
- package/dist/daemon-cli.js.map +1 -1
- package/dist/{decisions-CXmK0nz9.js → decisions-hsw5XS2g.js} +3 -1
- package/dist/decisions-hsw5XS2g.js.map +1 -0
- package/dist/{discovery-DycXFxdA.js → discovery-CX7nbMCn.js} +4 -4
- package/dist/{discovery-DycXFxdA.js.map → discovery-CX7nbMCn.js.map} +1 -1
- package/dist/durable/sqlite.d.ts +2 -2
- package/dist/durable.d.ts +1 -1
- package/dist/{engine-VQ86XGdG.js → engine-CxBGgU94.js} +6 -6
- package/dist/{engine-VQ86XGdG.js.map → engine-CxBGgU94.js.map} +1 -1
- package/dist/{eval-Bod0I1W_.js → eval-CfGUDAkN.js} +3 -3
- package/dist/{eval-Bod0I1W_.js.map → eval-CfGUDAkN.js.map} +1 -1
- package/dist/eval.d.ts +1 -1
- package/dist/eval.js +1 -1
- package/dist/{executor-C7RQrkEq.js → executor-j_LFRBwS.js} +4 -4
- package/dist/{executor-C7RQrkEq.js.map → executor-j_LFRBwS.js.map} +1 -1
- package/dist/{extension-mark-BqKdEZwF.js → extension-mark-_rhkDWL5.js} +9 -6
- package/dist/extension-mark-_rhkDWL5.js.map +1 -0
- package/dist/extensions/testing.d.ts +1 -1
- package/dist/extensions/testing.js +2 -2
- package/dist/{extensions-BCx4QuGB.js → extensions-ADlhBQ_1.js} +8 -8
- package/dist/{extensions-BCx4QuGB.js.map → extensions-ADlhBQ_1.js.map} +1 -1
- package/dist/{extensions-client-D8tEAcMw.d.ts → extensions-client-D4Q2XRKV.d.ts} +31 -5
- package/dist/extensions-client-D4Q2XRKV.d.ts.map +1 -0
- package/dist/extensions.d.ts +1 -1
- package/dist/extensions.js +6 -6
- package/dist/{fold-rules-DvLK8pbf.d.ts → fold-rules-1DpDwG9h.d.ts} +2 -2
- package/dist/{fold-rules-DvLK8pbf.d.ts.map → fold-rules-1DpDwG9h.d.ts.map} +1 -1
- package/dist/{google-Crva32sk.js → google-B-Dhmzzf.js} +2 -2
- package/dist/{google-Crva32sk.js.map → google-B-Dhmzzf.js.map} +1 -1
- package/dist/{headless-CCm-jLLT.js → headless-CQm19BL0.js} +4 -4
- package/dist/{headless-CCm-jLLT.js.map → headless-CQm19BL0.js.map} +1 -1
- package/dist/headless.d.ts +1 -1
- package/dist/headless.js +1 -1
- package/dist/history-worker.js +1 -1
- package/dist/{host-wO_6GW0y.js → host-C61ntFBC.js} +276 -103
- package/dist/host-C61ntFBC.js.map +1 -0
- package/dist/{host-BHMs9jsN.js → host-DEoEzQal.js} +13 -4
- package/dist/host-DEoEzQal.js.map +1 -0
- package/dist/{host-scoped-settings-CrbcqOkP.js → host-scoped-settings-WBYaCork.js} +2 -2
- package/dist/{host-scoped-settings-CrbcqOkP.js.map → host-scoped-settings-WBYaCork.js.map} +1 -1
- package/dist/{host-signals-Jsjd_-4g.js → host-signals-Cb2TlGtN.js} +5 -5
- package/dist/{host-signals-Jsjd_-4g.js.map → host-signals-Cb2TlGtN.js.map} +1 -1
- package/dist/{host-version-CNAr9pov.js → host-version-BIx4CuBM.js} +2 -2
- package/dist/{host-version-CNAr9pov.js.map → host-version-BIx4CuBM.js.map} +1 -1
- package/dist/{index-C6nnKu32.d.ts → index-B0PLo9jn.d.ts} +4 -4
- package/dist/{index-C6nnKu32.d.ts.map → index-B0PLo9jn.d.ts.map} +1 -1
- package/dist/{index-Djnc8Peh.d.ts → index-De4x-s76.d.ts} +14 -14
- package/dist/{index-Djnc8Peh.d.ts.map → index-De4x-s76.d.ts.map} +1 -1
- package/dist/{index-CGbOWa7y.d.ts → index-WlE93Q6d.d.ts} +411 -3
- package/dist/index-WlE93Q6d.d.ts.map +1 -0
- package/dist/{index-CCf_WeTQ.d.ts → index-f-XWIoYo.d.ts} +2 -2
- package/dist/{index-CCf_WeTQ.d.ts.map → index-f-XWIoYo.d.ts.map} +1 -1
- package/dist/index.d.ts +5 -5
- package/dist/index.js +17 -17
- package/dist/ipc/browser-types.d.ts +304 -7
- package/dist/ipc/browser-types.d.ts.map +1 -1
- package/dist/ipc/browser.d.ts +4 -4
- package/dist/ipc/browser.js +2 -2
- package/dist/ipc/remote.d.ts +6 -6
- package/dist/ipc/remote.js +3 -3
- package/dist/{ipc-BzWhIybr.js → ipc-DiH_P-wr.js} +4 -4
- package/dist/{ipc-BzWhIybr.js.map → ipc-DiH_P-wr.js.map} +1 -1
- package/dist/ipc.d.ts +10 -10
- package/dist/ipc.js +8 -8
- package/dist/{json-Dj-YATkZ.js → json-BjClr43H.js} +2 -20
- package/dist/json-BjClr43H.js.map +1 -0
- package/dist/{links-CJG_rFvf.js → links-BbC_lOnn.js} +9 -9
- package/dist/{links-CJG_rFvf.js.map → links-BbC_lOnn.js.map} +1 -1
- package/dist/{loaded-entry-DTURJo_R.js → loaded-entry-C0vkCVNQ.js} +2 -2
- package/dist/{loaded-entry-DTURJo_R.js.map → loaded-entry-C0vkCVNQ.js.map} +1 -1
- package/dist/mcp.d.ts +1 -1
- package/dist/{media-type-BtA0cbfI.d.ts → media-type-ZSmAGHvg.d.ts} +188 -7
- package/dist/media-type-ZSmAGHvg.d.ts.map +1 -0
- package/dist/{memory-DuVGrzbl.js → memory-C3w8nO8f.js} +132 -31
- package/dist/memory-C3w8nO8f.js.map +1 -0
- package/dist/model-test-CAtJ76kM.js.map +1 -1
- package/dist/{move-session-kylExJ5H.js → move-session-D7ILECs-.js} +4 -4
- package/dist/{move-session-kylExJ5H.js.map → move-session-D7ILECs-.js.map} +1 -1
- package/dist/{nested-call-record-DlzPeTB7.js → nested-call-record-OayszZBQ.js} +4 -3
- package/dist/nested-call-record-OayszZBQ.js.map +1 -0
- package/dist/output/stream-json.d.ts +1 -1
- package/dist/output/terminal.d.ts +1 -1
- package/dist/{path-display-COVV71Yu.js → path-display-DRAEpKOU.js} +3 -3
- package/dist/{path-display-COVV71Yu.js.map → path-display-DRAEpKOU.js.map} +1 -1
- package/dist/plugins.d.ts +1 -1
- package/dist/{prelude-CVKoUzV8.js → prelude-BwiSR1uA.js} +16 -5
- package/dist/prelude-BwiSR1uA.js.map +1 -0
- package/dist/{presets-CBt6rFfS.js → presets-CMY43nUP.js} +3 -3
- package/dist/{presets-CBt6rFfS.js.map → presets-CMY43nUP.js.map} +1 -1
- package/dist/presets.d.ts +1 -1
- package/dist/presets.js +1 -1
- package/dist/{protocol-CEVqBO-q.d.ts → protocol-C2lqKuMd.d.ts} +50 -7
- package/dist/protocol-C2lqKuMd.d.ts.map +1 -0
- package/dist/protocol-DOGyHgLQ.js.map +1 -1
- package/dist/protocol-NSllElLw.js.map +1 -1
- package/dist/providers/anthropic.d.ts +1 -1
- package/dist/providers/arcee.d.ts +1 -1
- package/dist/providers/baseten.d.ts +1 -1
- package/dist/providers/cerebras.d.ts +1 -1
- package/dist/providers/google.d.ts +1 -1
- package/dist/providers/google.js +1 -1
- package/dist/providers/local.d.ts +1 -1
- package/dist/providers/neuralwatt.d.ts +1 -1
- package/dist/providers/openai-compat.d.ts +1 -1
- package/dist/providers/openai.d.ts +1 -1
- package/dist/providers/openrouter.d.ts +1 -1
- package/dist/providers/xai.d.ts +1 -1
- package/dist/{providers-Z0TaBp1O.js → providers-CpXV_uLE.js} +5 -5
- package/dist/providers-CpXV_uLE.js.map +1 -0
- package/dist/providers.d.ts +1 -1
- package/dist/providers.js +1 -1
- package/dist/{readonly-db-D7Z-k0pQ.js → readonly-db-DrbT8tX6.js} +2 -2
- package/dist/{readonly-db-D7Z-k0pQ.js.map → readonly-db-DrbT8tX6.js.map} +1 -1
- package/dist/{registry-BKjeBnoy.js → registry-CJHvmvaP.js} +2 -2
- package/dist/{registry-BKjeBnoy.js.map → registry-CJHvmvaP.js.map} +1 -1
- package/dist/{registry-B6Ww76iW.js → registry-CN6JlZKj.js} +2 -2
- package/dist/{registry-B6Ww76iW.js.map → registry-CN6JlZKj.js.map} +1 -1
- package/dist/{registry-B9INJwJR.js → registry-CnnKaY9s.js} +324 -39
- package/dist/registry-CnnKaY9s.js.map +1 -0
- package/dist/{remote-hosts-BMWoHCWO.js → remote-hosts-DoO9CJUQ.js} +4 -4
- package/dist/{remote-hosts-BMWoHCWO.js.map → remote-hosts-DoO9CJUQ.js.map} +1 -1
- package/dist/{repo-url-D4Dr8NfZ.js → repo-url-DLjjuVk_.js} +169 -2
- package/dist/repo-url-DLjjuVk_.js.map +1 -0
- package/dist/restate.d.ts +2 -2
- package/dist/{sandbox-BwiPGKF7.d.ts → sandbox-B4OW6oNx.d.ts} +2 -2
- package/dist/{sandbox-BwiPGKF7.d.ts.map → sandbox-B4OW6oNx.d.ts.map} +1 -1
- package/dist/script-progress-CrZ507Qq.js +900 -0
- package/dist/script-progress-CrZ507Qq.js.map +1 -0
- package/dist/session/sqlite.d.ts +1 -1
- package/dist/session.d.ts +1 -1
- package/dist/{setting-BQBSyUq0.js → setting-D_FpKFMw.js} +6 -6
- package/dist/{setting-BQBSyUq0.js.map → setting-D_FpKFMw.js.map} +1 -1
- package/dist/{settings-catalog-4IU2i_jG.js → settings-catalog-DEZlXP51.js} +14 -2
- package/dist/settings-catalog-DEZlXP51.js.map +1 -0
- package/dist/{settings-keys-iI_Y-7MC.js → settings-keys-CW2UgHgb.js} +3 -3
- package/dist/{settings-keys-iI_Y-7MC.js.map → settings-keys-CW2UgHgb.js.map} +1 -1
- package/dist/{skills-CFXRItJ6.js → skills-CEbosUlM.js} +2 -2
- package/dist/{skills-CFXRItJ6.js.map → skills-CEbosUlM.js.map} +1 -1
- package/dist/skills.d.ts +1 -1
- package/dist/skills.js +1 -1
- package/dist/{source-Bl1Z501r.js → source-3ZnEPOSa.js} +3 -2
- package/dist/source-3ZnEPOSa.js.map +1 -0
- package/dist/{sqlite-runtime-BZ2L4RaG.d.ts → sqlite-runtime-CS_LBaAN.d.ts} +2 -2
- package/dist/sqlite-runtime-CS_LBaAN.d.ts.map +1 -0
- package/dist/{src-BY_ND2xn.js → src-BmTXDta8.js} +2 -2
- package/dist/{src-BY_ND2xn.js.map → src-BmTXDta8.js.map} +1 -1
- package/dist/{store-C6gI7FfZ.js → store-ByCDaKgJ.js} +14 -3
- package/dist/store-ByCDaKgJ.js.map +1 -0
- package/dist/{system-freeze-m5o1sGIM.js → system-freeze-XgDPIwQS.js} +3 -3
- package/dist/{system-freeze-m5o1sGIM.js.map → system-freeze-XgDPIwQS.js.map} +1 -1
- package/dist/{todo-edits-CbukbjyV.js → todo-edits-Dyj32ds6.js} +4 -3
- package/dist/todo-edits-Dyj32ds6.js.map +1 -0
- package/dist/tools/fetch-url.d.ts +1 -1
- package/dist/tools/web-search.d.ts +1 -1
- package/dist/{tools-CVTGhggj.js → tools-BsrGQ8K4.js} +2 -2
- package/dist/{tools-CVTGhggj.js.map → tools-BsrGQ8K4.js.map} +1 -1
- package/dist/tools.d.ts +1 -1
- package/dist/tools.js +3 -3
- package/dist/{transcript-anchors-CiSi_UBn.js → transcript-anchors-DMjvyUjk.js} +3 -3
- package/dist/{transcript-anchors-CiSi_UBn.js.map → transcript-anchors-DMjvyUjk.js.map} +1 -1
- package/dist/{transcript-reconcile-jbSBjLq2.js → transcript-reconcile-DpQO85wl.js} +3 -3
- package/dist/{transcript-reconcile-jbSBjLq2.js.map → transcript-reconcile-DpQO85wl.js.map} +1 -1
- package/dist/tui.d.ts +9 -9
- package/dist/tui.d.ts.map +1 -1
- package/dist/tui.js +289 -38
- package/dist/tui.js.map +1 -1
- package/dist/{types-bDQagoiL.d.ts → types-2HrgolQz.d.ts} +20 -8
- package/dist/types-2HrgolQz.d.ts.map +1 -0
- package/dist/types-4q1bFG53.js +122 -0
- package/dist/types-4q1bFG53.js.map +1 -0
- package/dist/{types-DnRd9_cA.d.ts → types-SXqk6hLD.d.ts} +3 -3
- package/dist/{types-DnRd9_cA.d.ts.map → types-SXqk6hLD.d.ts.map} +1 -1
- package/dist/types-myxheQkw.js.map +1 -1
- package/dist/types.d.ts +3 -3
- package/dist/{usage-summary-BfcXjiSM.js → usage-summary-BM7B3JdI.js} +2 -2
- package/dist/{usage-summary-BfcXjiSM.js.map → usage-summary-BM7B3JdI.js.map} +1 -1
- package/dist/{version-DqqqvHDP.js → version-szdW1Od9.js} +2 -2
- package/dist/{version-DqqqvHDP.js.map → version-szdW1Od9.js.map} +1 -1
- package/dist/{wait-task-BX4NcOOm.js → wait-task-BiI5UaZQ.js} +13 -3
- package/dist/wait-task-BiI5UaZQ.js.map +1 -0
- package/dist/{wire-CLm2rMK0.js → wire-C3l9jl9x.js} +2 -2
- package/dist/{wire-CLm2rMK0.js.map → wire-C3l9jl9x.js.map} +1 -1
- package/dist/{write-file-0E6TUJ9A.js → write-file-Dquu7MzB.js} +5 -3
- package/dist/write-file-Dquu7MzB.js.map +1 -0
- package/dist/{ws-DfGGYQ4W.js → ws-CEHi0CiB.js} +4 -4
- package/dist/{ws-DfGGYQ4W.js.map → ws-CEHi0CiB.js.map} +1 -1
- package/dist/{ws-client-CFMbhsNq.js → ws-client-t8XNWxcq.js} +2 -2
- package/dist/{ws-client-CFMbhsNq.js.map → ws-client-t8XNWxcq.js.map} +1 -1
- package/docs/CHAT.md +55 -0
- package/docs/CODEMODE.md +37 -0
- package/docs/EXTENSIONS.md +8 -6
- package/docs/RELEASE-NOTES-NEXT.md +48 -1
- package/docs/RELEASE.md +9 -1
- package/package.json +2 -3
- package/dist/agent-DJhpTS-B.js.map +0 -1
- package/dist/auto-update-restart-BFB7Ek87.js.map +0 -1
- package/dist/browser-BcoCCB_n.js.map +0 -1
- package/dist/contexts-C72b0mMa.js.map +0 -1
- package/dist/decisions-CXmK0nz9.js.map +0 -1
- package/dist/extension-mark-BqKdEZwF.js.map +0 -1
- package/dist/extensions-client-D8tEAcMw.d.ts.map +0 -1
- package/dist/host-BHMs9jsN.js.map +0 -1
- package/dist/host-wO_6GW0y.js.map +0 -1
- package/dist/index-CGbOWa7y.d.ts.map +0 -1
- package/dist/json-Dj-YATkZ.js.map +0 -1
- package/dist/media-type-BtA0cbfI.d.ts.map +0 -1
- package/dist/memory-DuVGrzbl.js.map +0 -1
- package/dist/nested-call-events-BYk8XvGX.js +0 -182
- package/dist/nested-call-events-BYk8XvGX.js.map +0 -1
- package/dist/nested-call-record-DlzPeTB7.js.map +0 -1
- package/dist/prelude-CVKoUzV8.js.map +0 -1
- package/dist/protocol-CEVqBO-q.d.ts.map +0 -1
- package/dist/providers-Z0TaBp1O.js.map +0 -1
- package/dist/registry-B9INJwJR.js.map +0 -1
- package/dist/repo-url-D4Dr8NfZ.js.map +0 -1
- package/dist/settings-catalog-4IU2i_jG.js.map +0 -1
- package/dist/source-Bl1Z501r.js.map +0 -1
- package/dist/sqlite-runtime-BZ2L4RaG.d.ts.map +0 -1
- package/dist/store-C6gI7FfZ.js.map +0 -1
- package/dist/todo-edits-CbukbjyV.js.map +0 -1
- package/dist/types-DTMEhKJO.js +0 -14
- package/dist/types-DTMEhKJO.js.map +0 -1
- package/dist/types-bDQagoiL.d.ts.map +0 -1
- package/dist/wait-task-BX4NcOOm.js.map +0 -1
- package/dist/write-file-0E6TUJ9A.js.map +0 -1
- package/scripts/eval.ts +0 -179
package/dist/chat.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat.js","names":[],"sources":["../src/chat/auto-update-cli.ts","../src/chat/git/repo-info.ts","../src/chat/todo-anchor.ts","../src/chat/workspace/local-entries.ts","../src/chat/workspace/media.ts"],"sourcesContent":["// ---------------------------------------------------------------------------\n// `zidane upgrade` subcommand — drop-in handler for consumer CLIs.\n//\n// Wraps `checkForUpdate` + `performSelfUpdate` + `performInPlaceSelfUpdate`\n// into a single function the host's `cli.ts` can call. The behavior layers:\n//\n// - no flags → check + run the package manager\n// - `--check` → check only, print the latest version + bail\n// - `--in-place` → skip the PM, download + atomic-rename the binary\n// - `--dry-run` → resolve everything but don't actually swap\n// - `--channel <tag>` → override dist-tag (defaults to `'latest'`)\n// - `--registry <url>`→ override the npm registry URL\n// - `--package-manager <pm>` (`--pm`) → force npm, pnpm, yarn, bun or volta\n// - `--force` → install even when already on latest or the registry check failed\n// - `--tui-only` → skip companion packages (see `companions`)\n// - `-h`, `--help` → print the usage text\n//\n// Companions: sibling globals released on the same version line (today\n// `zidane-gui`). When one is installed, `upgrade` checks and re-installs it\n// too — through the package manager that owns THAT install, which may differ\n// from the TUI's. Companion failures are reported and fail the exit code but\n// never block the TUI's own upgrade.\n//\n// I/O only: reads the registry, spawns the package manager, writes to\n// stdout/stderr and the update-applied marker, and returns the exit code the\n// caller should pass to `process.exit`. No React, no OpenTUI; safe to call\n// before / instead of `runTui`.\n// ---------------------------------------------------------------------------\n\nimport type { PackageManagerCommand, UpdateStatus } from './auto-update'\nimport type { CompanionSpec, InstalledCompanion } from './auto-update-companion'\nimport type { UpdateLockOptions } from './auto-update-lock'\nimport type { UpdateAppliedMarker } from './auto-update-restart'\nimport {\n checkForUpdate,\n checkTarballAvailable,\n compareSemver,\n detectPackageManager,\n overrideManager,\n performInPlaceSelfUpdate,\n performSelfUpdate,\n reinstallHint,\n resolvePlatformPackage,\n} from './auto-update'\nimport { clearFailedUpdate } from './auto-update-auto-install'\nimport { findInstalledCompanion } from './auto-update-companion'\nimport { acquireUpdateLock, describeUpdateLockHolder } from './auto-update-lock'\nimport { writeUpdateAppliedMarker } from './auto-update-restart'\n\n/** Options for {@link runUpdateCommand}. */\nexport interface RunUpdateCommandOptions {\n /** Top-level package the user installs (e.g. `'zidane-tui'`). */\n packageName: string\n /** Inlined at build time. */\n currentVersion: string\n /** Args passed after `upgrade` (typically `process.argv.slice(3)`). */\n argv: readonly string[]\n /** Where to persist the TTL cache. Usually `paths.userDir`. */\n cacheDir?: string\n /** Default channel when `--channel` isn't passed. Defaults to `'latest'`. */\n defaultChannel?: string\n /**\n * Override the platform-package-name prefix used by `--in-place`.\n * Defaults to `'<packageName>-'`, matching the `zidane-tui-<key>` layout.\n */\n platformPackagePrefix?: string\n /** Override registry. Defaults to npmjs. */\n registry?: string\n /** stdout. Defaults to `process.stdout`. */\n stdout?: NodeJS.WritableStream\n /** stderr. Defaults to `process.stderr`. */\n stderr?: NodeJS.WritableStream\n /**\n * Sibling packages to keep in step when installed (e.g. `zidane-gui`).\n * Absent companions are silently skipped; `--tui-only` skips them all.\n */\n companions?: readonly CompanionSpec[]\n /**\n * Reports the version now installed for `packageName` (e.g. by running the\n * bin with `--version`), `null` when nothing usable is there, `undefined`\n * to skip verification. The host wires this; the library cannot know how\n * its own bin is invoked.\n */\n verifyInstalled?: (packageName: string) => string | null | undefined\n /** Inject for tests. */\n findCompanion?: typeof findInstalledCompanion\n /** Inject for tests. */\n performSelfUpdate?: typeof performSelfUpdate\n /** Inject for tests. */\n checkTarballAvailable?: typeof checkTarballAvailable\n /** Inject for tests. */\n writeMarker?: typeof writeUpdateAppliedMarker\n /** Inject for tests: clock, liveness probe and pid of the install lock. */\n lock?: UpdateLockOptions\n /** The caller already holds the install lock (the update worker): don't take it again. */\n lockHeld?: boolean\n /** Appended to `--help`: how this host runs installs (e.g. in the background). */\n helpNote?: string\n}\n\n/** Result of {@link runUpdateCommand}. */\nexport interface RunUpdateCommandResult {\n /** Process exit code: `0` on success, `1` on failure, `2` for invalid arguments. */\n exitCode: number\n}\n\nconst UPGRADE_HELP = `Usage: zidane upgrade [options]\n\nUpdate the zidane CLI to the latest release. A globally installed\nzidane-gui is upgraded alongside it, through its own package manager.\n\nOptions:\n --check Print the latest version and exit (no install).\n --tui-only Leave companion packages (zidane-gui) alone.\n --in-place Download the platform binary directly from npm\n and atomic-rename over the running binary.\n Skips the package manager. Refused on Volta.\n --dry-run Resolve everything but don't actually install.\n --channel <tag> dist-tag to query (default: latest).\n --registry <url> Override the npm registry.\n --package-manager <pm> Force npm | pnpm | yarn | bun | volta.\n --force Run the install even if we're already on latest,\n or the registry check failed.\n -h, --help Print this help.\n\nEnvironment:\n NO_UPDATE_NOTIFIER Silence the background check (set to \"1\").\n ZIDANE_NO_UPDATE Same, project-specific.\n`\n\n/**\n * Run the `upgrade` subcommand. Exit code contract:\n * - `0` — update succeeded, `--check` reported no update, or `--check`\n * reported an update (informational only).\n * - `1` — update failed (PM exit non-zero, in-place download failed,\n * registry check failed without `--force`, release not\n * downloadable yet, or the installed version did not change).\n * - `2` — argv parse error (unknown flag).\n *\n * Output is a short ledger, one line per package, ASCII-only apart from the\n * arrow:\n * zidane-tui 7.0.7 → 7.0.8\n * $ volta install zidane-tui@latest\n * …\n * zidane-tui 7.0.8 ok\n * Diagnostics go to stderr and say what to do next.\n *\n * @param options - Package, version, argv and I/O settings for the command.\n */\nexport async function runUpdateCommand(options: RunUpdateCommandOptions): Promise<RunUpdateCommandResult> {\n const out = options.stdout ?? process.stdout\n const err = options.stderr ?? process.stderr\n const parsed = parseArgs(options.argv)\n if (parsed.kind === 'error') {\n err.write(`zidane upgrade: ${parsed.message}\\n`)\n err.write(UPGRADE_HELP)\n return { exitCode: 2 }\n }\n if (parsed.help) {\n out.write(options.helpNote ? `${UPGRADE_HELP}\\n${options.helpNote.trimEnd()}\\n` : UPGRADE_HELP)\n return { exitCode: 0 }\n }\n const flags: ParsedFlags = parsed\n\n const channel = flags.channel ?? options.defaultChannel ?? 'latest'\n const registry = flags.registry ?? options.registry\n const tarballAvailable = options.checkTarballAvailable ?? checkTarballAvailable\n const install = options.performSelfUpdate ?? performSelfUpdate\n\n // Always force the check — user typed `upgrade`, env opt-outs shouldn't\n // get in the way.\n const status = await checkForUpdate({\n packageName: options.packageName,\n currentVersion: options.currentVersion,\n channel,\n registry,\n cacheDir: options.cacheDir,\n force: true,\n timeoutMs: 8000,\n })\n const self: Entry = {\n name: options.packageName,\n current: options.currentVersion,\n status,\n outdated: status.latest !== null && compareSemver(status.latest, options.currentVersion) > 0,\n }\n\n // Companions: discovered locally, then checked on the registry with the\n // same channel. Only installed ones take part; nothing is printed for the\n // rest, so users without the GUI see the exact output they always did.\n const companions = flags.tuiOnly ? [] : await resolveCompanions(options, channel, registry)\n const entries: Entry[] = [self, ...companions]\n const label = (name: string) => name.padEnd(Math.max(...entries.map(e => e.name.length)))\n\n // `--check` is informational — degrade gracefully on registry errors\n // (offline laptop, restricted proxy) and exit 0 so the user can script\n // around it without quoting tricks.\n if (flags.check) {\n for (const e of entries)\n out.write(`${label(e.name)} ${statusText(e)}\\n`)\n return { exitCode: 0 }\n }\n\n // Install path — a registry error means we don't KNOW if we need an\n // update. Refuse to spawn the PM blindly unless the user explicitly\n // asks via `--force`.\n if (status.source === 'error') {\n err.write(`${self.name}: registry check failed: ${status.error ?? 'unknown error'}\\n`)\n if (!flags.force) {\n err.write('Use --force to install anyway.\\n')\n return { exitCode: 1 }\n }\n }\n for (const c of companions.filter(c => c.status.source === 'error' && !flags.force))\n err.write(`${c.name}: registry check failed: ${c.status.error ?? 'unknown error'}\\n`)\n\n const selfPending = flags.force || self.outdated\n const pendingCompanions = companions.filter(c => flags.force || c.outdated)\n for (const e of entries.filter(e => !e.outdated && e.status.source !== 'error'))\n out.write(`${label(e.name)} ${statusText(e)}\\n`)\n if (!selfPending && pendingCompanions.length === 0)\n return { exitCode: 0 }\n\n // The TUI's own install runs first (in-place or PM); companions follow.\n // A companion failure sets the exit code but never undoes or blocks the\n // TUI upgrade that already happened.\n // One install at a time: the desktop app or a running TUI may be\n // installing in the background. Racing two package managers over the same\n // global install breaks it, so say who holds the lock and stop.\n const lock = options.cacheDir && !flags.dryRun && !options.lockHeld ? acquireUpdateLock(options.cacheDir, 'zidane upgrade', options.lock) : null\n if (lock && !lock.acquired) {\n err.write(`zidane upgrade: another update is running: ${describeUpdateLockHolder(lock.holder, (options.lock?.now ?? Date.now)())}.\\n`)\n err.write('Wait for it to finish, then run zidane upgrade again.\\n')\n return { exitCode: 1 }\n }\n try {\n // A manual install is the retry for a failed automatic one.\n if (options.cacheDir && !flags.dryRun)\n clearFailedUpdate(options.cacheDir)\n let exitCode = 0\n const applied: UpdateAppliedMarker['packages'] = []\n if (selfPending) {\n exitCode = await upgradeSelf()\n if (exitCode === 0 && !flags.dryRun && status.latest)\n applied.push({ packageName: self.name, version: status.latest })\n }\n for (const c of pendingCompanions) {\n const code = await upgradeCompanion(c)\n if (code === 0 && !flags.dryRun && c.status.latest)\n applied.push({ packageName: c.name, version: c.status.latest })\n if (exitCode === 0)\n exitCode = code\n }\n // Wake running TUIs / GUIs: they watch this marker and offer a restart.\n if (applied.length > 0 && options.cacheDir)\n (options.writeMarker ?? writeUpdateAppliedMarker)(options.cacheDir, { at: Date.now(), packages: applied })\n return { exitCode }\n }\n finally {\n if (lock?.acquired)\n lock.release()\n }\n\n /**\n * Refuse to spawn the PM while the release is not fetchable yet: npm treats\n * a 404 on an `optionalDependencies` platform binary as \"skip\" and leaves\n * an empty install behind the bin. `--force` overrides (mirrors, offline\n * registries).\n */\n async function ready(packageName: string, version: string): Promise<boolean> {\n if (flags.force || flags.dryRun)\n return true\n const availability = await tarballAvailable({ packageName, version, registry })\n if (availability !== 'missing')\n return true\n err.write(`${packageName} ${version} is published but not downloadable yet. Try again in a few minutes.\\n`)\n return false\n }\n\n async function upgradeSelf(): Promise<number> {\n const target = status.latest ?? channel\n out.write(`${label(self.name)} ${self.current} → ${target}\\n`)\n\n if (flags.inPlace) {\n const platformPkg = resolvePlatformPackage({\n prefix: options.platformPackagePrefix ?? `${options.packageName}-`,\n })\n if (!platformPkg) {\n err.write(`${self.name}: no prebuilt binary for ${process.platform}/${process.arch}. Use your package manager instead.\\n`)\n return 1\n }\n if (status.latest && !await ready(platformPkg, status.latest))\n return 1\n const result = await performInPlaceSelfUpdate({ packageName: platformPkg, channel, registry, dryRun: flags.dryRun })\n if (result.status === 'success') {\n out.write(`${label(self.name)} ${result.installedVersion} ${flags.dryRun ? 'would install' : 'ok'}\\n`)\n return 0\n }\n err.write(`${self.name}: in-place update failed: ${result.reason ?? 'unknown error'}\\n`)\n if (result.status === 'refused')\n err.write('Drop --in-place to go through the package manager.\\n')\n return 1\n }\n\n // The platform binary is the part that can be missing from the CDN; the\n // meta package is tiny and published right after it.\n const platformPkg = resolvePlatformPackage({ prefix: options.platformPackagePrefix ?? `${options.packageName}-` })\n if (status.latest && !await ready(platformPkg ?? options.packageName, status.latest))\n return 1\n\n const command = flags.packageManager\n ? overrideManager(flags.packageManager, options.packageName, channel)\n : detectPackageManager({ packageName: options.packageName, channel })\n out.write(`$ ${command.argv.join(' ')}\\n`)\n if (flags.dryRun)\n return 0\n const result = await install({ packageName: options.packageName, channel, packageManager: flags.packageManager ?? 'auto' })\n if (result.spawnError) {\n err.write(`${self.name}: could not run ${result.command.argv[0]}: ${result.spawnError}\\n`)\n return 1\n }\n if (result.exitCode !== 0) {\n err.write(`${self.name}: ${result.command.argv[0]} exited with ${result.exitCode ?? 'unknown'}\\n`)\n return result.exitCode ?? 1\n }\n return verify(self.name, status.latest, options.verifyInstalled?.(options.packageName), result.command)\n }\n\n async function upgradeCompanion(c: CompanionEntry): Promise<number> {\n const target = c.status.latest ?? channel\n out.write(`${label(c.name)} ${c.current} → ${target}\\n`)\n if (c.status.latest && !await ready(c.name, c.status.latest))\n return 1\n // `--package-manager` is an override for the TUI's install; the\n // companion follows the PM that owns its own bin unless forced too.\n const command = flags.packageManager ? overrideManager(flags.packageManager, c.name, channel) : c.command\n out.write(`$ ${command.argv.join(' ')}\\n`)\n if (flags.dryRun)\n return 0\n const result = await install({ packageName: c.name, channel, packageManager: flags.packageManager ?? c.command.id })\n if (result.spawnError) {\n err.write(`${c.name}: could not run ${result.command.argv[0]}: ${result.spawnError}\\n`)\n return 1\n }\n if (result.exitCode !== 0) {\n err.write(`${c.name}: ${result.command.argv[0]} exited with ${result.exitCode ?? 'unknown'}\\n`)\n return 1\n }\n const find = options.findCompanion ?? findInstalledCompanion\n return verify(c.name, c.status.latest, find(c.spec)?.version, result.command)\n }\n\n /**\n * The PM exiting 0 is not proof: a skipped optional platform binary or a\n * Volta no-op (\"already installed\") both exit 0 and leave the old version\n * behind. Compare what is actually on disk with what we asked for.\n */\n function verify(name: string, expected: string | null, actual: string | undefined | null, command: PackageManagerCommand): number {\n if (!expected || actual === undefined) {\n out.write(`${label(name)} ${expected ?? channel} ok\\n`)\n return 0\n }\n if (actual !== null && compareSemver(actual, expected) >= 0) {\n out.write(`${label(name)} ${actual} ok\\n`)\n return 0\n }\n err.write(`${name}: install finished but ${actual ?? 'nothing'} is on disk, expected ${expected}.\\n`)\n err.write(`Reinstall: ${reinstallHint(command, name, channel)}\\n`)\n return 1\n }\n}\n\nfunction statusText(e: Entry): string {\n if (e.status.source === 'error')\n return `${e.current} (check failed: ${e.status.error ?? 'unknown error'})`\n if (!e.status.latest)\n return `${e.current} (latest unknown)`\n return e.outdated ? `${e.current} → ${e.status.latest} available` : `${e.current} up to date`\n}\n\n// ---------------------------------------------------------------------------\n// Ledger entries\n// ---------------------------------------------------------------------------\n\ninterface Entry {\n name: string\n /** Installed version. */\n current: string\n status: UpdateStatus\n /** Registry knows a newer version than the installed one. */\n outdated: boolean\n}\n\ninterface CompanionEntry extends Entry {\n spec: CompanionSpec\n installed: InstalledCompanion\n /** The PM that owns this install — from ITS bin path, not the TUI's. */\n command: PackageManagerCommand\n}\n\nasync function resolveCompanions(\n options: RunUpdateCommandOptions,\n channel: string,\n registry: string | undefined,\n): Promise<CompanionEntry[]> {\n const find = options.findCompanion ?? findInstalledCompanion\n const found = (options.companions ?? [])\n .map(spec => ({ spec, installed: find(spec) }))\n .filter((c): c is { spec: CompanionSpec, installed: InstalledCompanion } => c.installed !== null)\n return await Promise.all(found.map(async ({ spec, installed }) => {\n const status = await checkForUpdate({\n packageName: installed.packageName,\n currentVersion: installed.version,\n channel,\n registry,\n cacheDir: options.cacheDir,\n force: true,\n timeoutMs: 8000,\n })\n return {\n spec,\n installed,\n name: installed.packageName,\n current: installed.version,\n status,\n outdated: status.latest !== null && compareSemver(status.latest, installed.version) > 0,\n command: detectPackageManager({ packageName: installed.packageName, channel, binaryPath: installed.binaryPath }),\n }\n }))\n}\n\n// ---------------------------------------------------------------------------\n// Argv parser — minimal, just enough to drop into the consumer's `cli.ts`.\n// We deliberately don't pull in commander/yargs for a small flag surface.\n// ---------------------------------------------------------------------------\n\ntype ParsedFlags = Extract<ParseResult, { kind: 'ok' }>\n\ntype ParseResult\n = | {\n kind: 'ok'\n check: boolean\n inPlace: boolean\n dryRun: boolean\n force: boolean\n help: boolean\n tuiOnly: boolean\n channel?: string\n registry?: string\n packageManager?: 'npm' | 'pnpm' | 'yarn' | 'bun' | 'volta'\n }\n | { kind: 'error', message: string }\n\nfunction parseArgs(argv: readonly string[]): ParseResult {\n let check = false\n let inPlace = false\n let dryRun = false\n let force = false\n let help = false\n let tuiOnly = false\n let channel: string | undefined\n let registry: string | undefined\n let packageManager: 'npm' | 'pnpm' | 'yarn' | 'bun' | 'volta' | undefined\n\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i]!\n switch (a) {\n case '--check': check = true; break\n case '--in-place':\n case '--inplace': inPlace = true; break\n case '--dry-run':\n case '--dryrun': dryRun = true; break\n case '--force': force = true; break\n case '--tui-only': tuiOnly = true; break\n case '-h':\n case '--help': help = true; break\n case '--channel':\n channel = argv[++i]\n if (!channel)\n return { kind: 'error', message: '--channel requires a value' }\n break\n case '--registry':\n registry = argv[++i]\n if (!registry)\n return { kind: 'error', message: '--registry requires a value' }\n break\n case '--package-manager':\n case '--pm': {\n const v = argv[++i]\n if (!v)\n return { kind: 'error', message: '--package-manager requires a value' }\n if (v !== 'npm' && v !== 'pnpm' && v !== 'yarn' && v !== 'bun' && v !== 'volta')\n return { kind: 'error', message: `unknown package manager: ${v}` }\n packageManager = v\n break\n }\n default:\n return { kind: 'error', message: `unknown argument: ${a}` }\n }\n }\n\n return { kind: 'ok', check, inPlace, dryRun, force, help, tuiOnly, channel, registry, packageManager }\n}\n","/**\n * What the import dialog shows about a repository before it is cloned: for a\n * GitHub repository, its description, stars, language and default branch\n * (GitHub's REST API), with the owner's avatar and the repository's preview\n * image (`githubAvatarUrl`, `githubPreviewImageUrl`, as the skill browser\n * shows them). Another forge has no info: the dialog shows the parse alone.\n *\n * A failure (no network, a private repository without access, GitHub's rate\n * limit) answers `null`: the info is a nicety, never a reason to refuse.\n * Answers (a repository, or GitHub's \"not found\") are kept for 10 minutes\n * per repository and token.\n */\nimport type { RepoInfo } from './types'\nimport { createHash } from 'node:crypto'\nimport { githubAvatarUrl, githubPreviewImageUrl } from '../../skills/sources'\nimport { parseRepoInput } from './repo-url'\n\nconst API = 'https://api.github.com'\nconst CACHE_TTL_MS = 10 * 60_000\nconst TIMEOUT_MS = 8_000\n/** Repositories kept at once; the oldest goes first. */\nconst CACHE_MAX = 256\nconst cache = new Map<string, { at: number, info: RepoInfo | null }>()\n\n/**\n * The owner and repository of a GitHub clone URL (https, scp-like or ssh); `null` for another host.\n *\n * @param cloneUrl - The URL `git clone` takes.\n */\nexport function githubRepoOf(cloneUrl: string): { owner: string, repo: string } | null {\n // github.com must be the host: `https://evil.example/github.com/o/r` is not GitHub's `o/r`.\n const m = /^(?:(?:https?|ssh|git):\\/\\/(?:[^@/]+@)?|(?:[\\w.-]+@)?)github\\.com[/:]([\\w.-]+)\\/([\\w.-]+?)(?:\\.git)?\\/?$/i.exec(cloneUrl)\n return m ? { owner: m[1]!, repo: m[2]! } : null\n}\n\ninterface GithubRepo {\n full_name: string\n description: string | null\n stargazers_count: number\n language: string | null\n default_branch: string\n html_url: string\n private: boolean\n archived: boolean\n}\n\n/** Options of {@link fetchRepoInfo}. */\nexport interface FetchRepoInfoOptions {\n /** A GitHub token: private repositories, and 5,000 calls an hour instead of 60. */\n token?: string\n /** Test seam. Default: the global `fetch`. */\n fetch?: typeof fetch\n}\n\n/**\n * The info of the repository `input` names (what the import dialog would clone); `null` when there is none.\n *\n * @param input - What was pasted: a git or forge URL, or `owner/repo`.\n * @param options - A token, and the fetch to use.\n */\nexport async function fetchRepoInfo(input: string, options: FetchRepoInfoOptions = {}): Promise<RepoInfo | null> {\n const spec = parseRepoInput(input)\n const gh = spec ? githubRepoOf(spec.cloneUrl) : null\n if (!gh)\n return null\n const key = `${gh.owner}/${gh.repo}`.toLowerCase() + (options.token ? `\\u0000${createHash('sha256').update(options.token).digest('hex')}` : '')\n const hit = cache.get(key)\n if (hit && Date.now() - hit.at < CACHE_TTL_MS)\n return hit.info\n const doFetch = options.fetch ?? fetch\n let info: RepoInfo | null = null\n try {\n const res = await doFetch(`${API}/repos/${encodeURIComponent(gh.owner)}/${encodeURIComponent(gh.repo)}`, {\n headers: {\n 'Accept': 'application/vnd.github+json',\n 'X-GitHub-Api-Version': '2022-11-28',\n ...(options.token ? { Authorization: `Bearer ${options.token}` } : {}),\n },\n signal: AbortSignal.timeout(TIMEOUT_MS),\n })\n // A refusal for the rate limit is not an answer about the repository: not kept.\n if (!res.ok && res.status !== 404)\n return null\n if (res.ok) {\n const repo = await res.json() as GithubRepo\n const [owner = gh.owner, name = gh.repo] = repo.full_name.split('/')\n info = {\n owner,\n repo: name,\n url: repo.html_url,\n ...(repo.description ? { description: repo.description } : {}),\n stars: repo.stargazers_count,\n ...(repo.language ? { language: repo.language } : {}),\n defaultBranch: repo.default_branch,\n ...(repo.private ? { private: true } : {}),\n ...(repo.archived ? { archived: true } : {}),\n avatarUrl: githubAvatarUrl(owner),\n imageUrl: githubPreviewImageUrl(owner, name),\n }\n }\n }\n catch {\n // Offline or timed out: no info, and the next ask tries again.\n return null\n }\n const now = Date.now()\n // Re-inserted so the map stays ordered by `at`: expired entries lead.\n cache.delete(key)\n for (const [k, entry] of cache) {\n if (now - entry.at < CACHE_TTL_MS && cache.size < CACHE_MAX)\n break\n cache.delete(k)\n }\n cache.set(key, { at: now, info })\n return info\n}\n","import type { AgentHookMap } from '../agent'\nimport type { TodoItem } from './todos'\nimport { appendDynamicSection } from '../system-prompt'\nimport { selectActiveTodos } from './todos'\n\n/** Options for the active-todo system-prompt anchor. */\nexport interface ActiveTodoAnchorOptions {\n /**\n * Set to `false` to render nothing.\n *\n * @default true\n */\n enabled?: boolean\n /**\n * Maximum todos listed before a `... N more` line. Values below 1 count as 1.\n *\n * @default 6\n */\n maxItems?: number\n /**\n * Heading text of the section.\n *\n * @default 'Active Todo Anchor'\n */\n heading?: string\n}\n\n/**\n * Renders the active todos as a system-prompt section. Returns `''` when disabled or there are no todos.\n *\n * @param todos - Active todos in order.\n * @param options - Anchor options.\n */\nexport function renderActiveTodoAnchor(\n todos: readonly TodoItem[],\n options: ActiveTodoAnchorOptions = {},\n): string {\n if (options.enabled === false || todos.length === 0)\n return ''\n const maxItems = Math.max(1, Math.floor(options.maxItems ?? 6))\n const heading = options.heading ?? 'Active Todo Anchor'\n const visible = todos.slice(0, maxItems)\n const lines = [`# ${heading}`, '<active_todos>']\n for (const item of visible)\n lines.push(`- [${item.status}] ${item.content}`)\n if (todos.length > visible.length)\n lines.push(`- ... ${todos.length - visible.length} more`)\n lines.push('</active_todos>')\n return lines.join('\\n')\n}\n\n/**\n * Optional chat-layer hook that keeps the live `todowrite` list visible in the\n * dynamic system prompt. It reads only live todos, never the archive, so an\n * auto-cleared completed plan is not reintroduced on later turns.\n *\n * ## Prompt-cache cost — read before enabling\n *\n * This writes per-turn state into the system prompt, and the system prompt sits\n * ABOVE the entire conversation in the provider's cache prefix (Anthropic hashes\n * tools → system → messages, cumulatively). So every time the rendered anchor\n * changes by a single byte, the whole transcript stops matching the cache and\n * re-bills at the cache-write rate; only `tools` and the static system block\n * survive.\n *\n * That is an acceptable trade only because the anchor changes *rarely* — once\n * per `todowrite`, which in practice is a small fraction of turns. Two rules\n * follow, and breaking either one turns that occasional cost into a per-turn\n * one:\n *\n * 1. Never add anything to the anchor that ticks on its own — no counters, no\n * timestamps, no elapsed times, no per-turn indices.\n * 2. The render must stay a pure function of the todo list.\n * `renderActiveTodoAnchor` is deterministic today, so identical todos emit\n * identical bytes; keep it that way. Note this does NOT cover reordering —\n * todo order is semantically meaningful (it is the plan), so a reorder is\n * a real state change and costs one re-bill like any other `todowrite`.\n *\n * Moving the anchor onto the newest message instead does NOT avoid this: it is\n * wire-only, so the message that carried last turn's anchor re-renders without\n * it, and the prefix diverges at that point just the same. The only injection\n * that is genuinely free is one persisted into the transcript as immutable\n * history.\n *\n * @param options - Anchor options.\n */\nexport function createActiveTodoAnchorHooks(options: ActiveTodoAnchorOptions = {}): AgentHookMap {\n return {\n 'system:transform': (ctx) => {\n const state = selectActiveTodos(ctx.session)\n const anchor = renderActiveTodoAnchor(state.todos, options)\n\n if (anchor)\n ctx.system = appendDynamicSection(ctx.system, anchor)\n },\n }\n}\n","/**\n * Entry actions on a folder of this machine (the Files tab of a local folder\n * or worktree): `createEntryOps` over node's fs, every path confined to the\n * folder. A path may not leave it lexically, and the folder holding it must\n * real-path inside it (a symlinked folder pointing out is refused); the\n * entry itself is never followed, so a link is renamed or removed, not what\n * it points at.\n *\n * Also what a drop from the file manager needs: copying absolute paths of\n * this machine into the folder (`importPaths`), and reading them as import\n * items for a folder that lives elsewhere (`hostImportItems`).\n */\nimport type { EntryImportItem, EntryImportResult, EntryOps } from './entries'\nimport { cp, lstat, readdir, readFile, realpath } from 'node:fs/promises'\nimport { basename, dirname, isAbsolute, join, resolve, sep } from 'node:path'\nimport { nodeEntryPort } from '../../contexts/entries'\nimport { createEntryOps, ENTRY_IMPORT_MAX_BYTES, ENTRY_IMPORT_MAX_ENTRIES, entryPath, freeEntryName, joinEntry } from './entries'\n\nconst inside = (root: string, path: string): boolean => path === root || path.startsWith(root + sep)\n\n/** The real path of `path`'s nearest existing ancestor (itself included), with the rest appended. */\nasync function realAncestor(path: string): Promise<string> {\n const tail: string[] = []\n let at = path\n while (true) {\n const real = await realpath(at).catch(() => null)\n if (real)\n return tail.length ? join(real, ...tail) : real\n const parent = dirname(at)\n if (parent === at)\n return path\n tail.unshift(basename(at))\n at = parent\n }\n}\n\n/**\n * `path` (relative to `cwd`) as an absolute path inside it: refused (throws)\n * when it leaves the folder lexically or its parent folder real-paths out.\n *\n * @param cwd - The folder (absolute).\n * @param path - A path relative to it.\n */\nexport async function containedEntryPath(cwd: string, path: string): Promise<string> {\n if (!isAbsolute(cwd))\n throw new Error(`${cwd} is not an absolute folder.`)\n const root = await realpath(cwd)\n const target = resolve(root, path)\n if (!inside(root, target))\n throw Object.assign(new Error(`${path} is outside the folder.`), { code: 'EACCES' })\n if (target !== root && !inside(root, await realAncestor(dirname(target))))\n throw Object.assign(new Error(`${path} is outside the folder.`), { code: 'EACCES' })\n return target\n}\n\n/** The entry actions of a local folder, plus copying in paths of this machine. */\nexport interface LocalEntryOps extends EntryOps {\n /** Copies absolute paths of this machine (a drop from the file manager) into folder `dir`, each under a free name. */\n importPaths: (dir: string, paths: readonly string[]) => Promise<EntryImportResult>\n}\n\n/**\n * The entry actions of `cwd`, a folder of this machine.\n *\n * @param cwd - The folder (absolute).\n * @param options - Options.\n * @param options.trash - Removes recoverably (the system trash). Default: removed for good.\n */\nexport function workspaceEntryOps(cwd: string, options: { trash?: (absolute: string) => Promise<void> } = {}): LocalEntryOps {\n const port = nodeEntryPort({ resolve: path => containedEntryPath(cwd, path), ...(options.trash ? { trash: options.trash } : {}) })\n const ops = createEntryOps(port)\n return {\n ...ops,\n async importPaths(rawDir, sources) {\n const dir = entryPath(rawDir, true)\n if (dir === null)\n return { ok: false, reason: 'invalid', message: `\"${rawDir}\" is not a valid folder.`, paths: [] }\n if (dir !== '' && (await port.stat(dir)) !== 'dir')\n return { ok: false, reason: 'missing', message: `${dir} is not a folder.`, paths: [] }\n const paths: string[] = []\n for (const source of sources) {\n try {\n if (!isAbsolute(source))\n throw new Error(`${source} is not an absolute path.`)\n const kind = (await lstat(source)).isDirectory() ? 'dir' : 'file'\n const target = joinEntry(dir, await freeEntryName(port, dir, basename(source), kind))\n await cp(source, await containedEntryPath(cwd, target), { recursive: true, errorOnExist: true, force: false, verbatimSymlinks: true })\n paths.push(target)\n }\n catch (error) {\n return { ok: false, reason: 'denied', message: error instanceof Error ? error.message : String(error), paths }\n }\n }\n return { ok: true, paths }\n },\n }\n}\n\n/**\n * Absolute paths of this machine as import items (a drop headed for a folder\n * elsewhere: a sandbox, a server): files read when their turn comes, folders\n * walked one entry at a time. Symlinks and special files are left out.\n * The walk stops once the import limits are passed: what it returns then is\n * still over them, so `importEntries` refuses it without a whole tree read.\n *\n * @param paths - The dropped paths.\n * @param limits - When to stop walking.\n * @param limits.maxEntries - Entries (files and folders). Default {@link ENTRY_IMPORT_MAX_ENTRIES}.\n * @param limits.maxBytes - All files together. Default {@link ENTRY_IMPORT_MAX_BYTES}.\n */\nexport async function hostImportItems(\n paths: readonly string[],\n limits: { maxEntries?: number, maxBytes?: number } = {},\n): Promise<EntryImportItem[]> {\n const maxEntries = limits.maxEntries ?? ENTRY_IMPORT_MAX_ENTRIES\n const maxBytes = limits.maxBytes ?? ENTRY_IMPORT_MAX_BYTES\n let entries = 0\n let bytes = 0\n const over = (): boolean => entries > maxEntries || bytes > maxBytes\n const item = async (path: string): Promise<EntryImportItem | null> => {\n const info = await lstat(path)\n if (info.isDirectory()) {\n entries++\n const children: EntryImportItem[] = []\n for (const name of (await readdir(path)).sort()) {\n if (over())\n break\n const child = await item(join(path, name))\n if (child)\n children.push(child)\n }\n return { name: basename(path), children }\n }\n if (!info.isFile())\n return null\n entries++\n bytes += info.size\n return { name: basename(path), size: info.size, read: async () => new Uint8Array(await readFile(path)) }\n }\n const items: EntryImportItem[] = []\n for (const path of paths) {\n if (over())\n break\n const made = await item(path)\n if (made)\n items.push(made)\n }\n return items\n}\n","/**\n * The bytes of a workspace's media (an image, a video, audio), as a web\n * `Response`, for a viewer that plays them by address: the desktop app's\n * `zg-media:` scheme and zidane-server's `GET /zidane/media`.\n *\n * - a file of `cwd`, confined to it like every editor read (no `..`, no\n * symlink out), streamed with byte ranges so a video seeks without\n * loading whole;\n * - one side of a change (`side`), the path relative to the repository\n * holding `cwd` (git's names): `old` from the last commit (`git show`),\n * `new` from the working tree, confined to the repository.\n *\n * Only the media types of `mediaTypeOfPath` are served, under their own\n * content type. A file address carries its version (its mtime), so the bytes\n * of one address never change and are cached for good; a change's sides\n * change any time and are revalidated.\n */\nimport { Buffer } from 'node:buffer'\nimport { spawn } from 'node:child_process'\nimport { createReadStream } from 'node:fs'\nimport { stat } from 'node:fs/promises'\nimport { Readable } from 'node:stream'\nimport { confineToWorkspace } from './files'\nimport { mediaTypeOfPath } from './media-type'\n\n/** What to serve. */\nexport interface WorkspaceMediaRequest {\n /** The folder the path is in. */\n cwd: string\n /** Relative to `cwd`, or (with `side`) to the repository holding it. */\n path: string\n /** One side of the path's git change: the last commit's or the working tree's. Absent: the file now. */\n side?: 'old' | 'new'\n}\n\n/** Options of {@link serveWorkspaceMedia}. */\nexport interface WorkspaceMediaOptions {\n /** Most bytes one response carries: a longer range is cut short, a whole body over it refused (413). Default: no cap. */\n maxBytes?: number\n}\n\n/** A file address carries its mtime: a new version is a new address. */\nconst IMMUTABLE = 'private, max-age=31536000, immutable'\n\nconst notFound = (): Response => new Response(null, { status: 404 })\nconst tooLarge = (): Response => new Response(null, { status: 413 })\n\n/**\n * `bytes=a-b` within `size`, else `null` (the whole file).\n *\n * @param header - The request's `Range` header.\n * @param size - The file's size.\n */\nexport function parseRange(header: string | null, size: number): { start: number, end: number } | null {\n const m = header ? /^bytes=(\\d*)-(\\d*)$/.exec(header.trim()) : null\n if (!m || (m[1] === '' && m[2] === ''))\n return null\n let start: number\n let end: number\n if (m[1] === '') {\n // `bytes=-n`: the last n bytes.\n start = Math.max(0, size - Number(m[2]))\n end = size - 1\n }\n else {\n start = Number(m[1])\n end = m[2] === '' ? size - 1 : Math.min(Number(m[2]), size - 1)\n }\n return start <= end && start < size ? { start, end } : null\n}\n\n/** A well-formed range lying wholly past the end (or an empty suffix): 416, not the whole file. */\nfunction unsatisfiable(header: string, size: number): boolean {\n const m = /^bytes=(\\d*)-(\\d*)$/.exec(header.trim())\n if (!m)\n return false\n if (m[1] === '')\n return m[2] === '0'\n return Number(m[1]) >= size\n}\n\nasync function fileMedia(cwd: string, path: string, mime: string, range: string | null, cache: string, maxBytes: number): Promise<Response> {\n const real = await confineToWorkspace(cwd, path)\n if (!real)\n return notFound()\n const s = await stat(real)\n if (!s.isFile())\n return notFound()\n const span = parseRange(range, s.size)\n if (!span && range && unsatisfiable(range, s.size))\n return new Response(null, { status: 416, headers: { 'content-range': `bytes */${s.size}` } })\n if (!span && s.size > maxBytes)\n return tooLarge()\n const start = span?.start ?? 0\n const end = span ? Math.min(span.end, start + maxBytes - 1) : s.size - 1\n // The same stream at runtime; `node:stream/web`'s typing and the DOM's just don't overlap.\n const body = s.size === 0 ? null : Readable.toWeb(createReadStream(real, { start, end })) as unknown as ReadableStream\n return new Response(body, {\n status: span ? 206 : 200,\n headers: {\n 'content-type': mime,\n 'accept-ranges': 'bytes',\n 'content-length': String(s.size === 0 ? 0 : end - start + 1),\n ...(span ? { 'content-range': `bytes ${start}-${end}/${s.size}` } : {}),\n 'cache-control': cache,\n },\n })\n}\n\n/** Run git in `cwd`, its stdout as bytes; `null` when it fails. */\nasync function gitBytes(cwd: string, args: string[]): Promise<Buffer | null> {\n const child = spawn('git', args, { cwd, stdio: ['ignore', 'pipe', 'ignore'] })\n const chunks: Buffer[] = []\n const closed = new Promise<number | null>((done) => {\n child.once('close', done)\n child.once('error', () => done(null))\n })\n for await (const chunk of child.stdout)\n chunks.push(chunk as Buffer)\n return (await closed) === 0 ? Buffer.concat(chunks) : null\n}\n\nasync function diffMedia(cwd: string, path: string, mime: string, side: 'old' | 'new', range: string | null, maxBytes: number): Promise<Response> {\n const at = await confineToWorkspace(cwd, '.')\n if (!at || path.startsWith('-') || path.startsWith('/') || path.split('/').includes('..'))\n return notFound()\n const top = (await gitBytes(at, ['rev-parse', '--show-toplevel']))?.toString('utf8').trim()\n if (!top)\n return notFound()\n // Either side may change at any time: revalidated on every show.\n if (side === 'new')\n return fileMedia(top, path, mime, range, 'no-cache', maxBytes)\n // The old side is read whole: its size first.\n const size = Number((await gitBytes(top, ['cat-file', '-s', `HEAD:${path}`]))?.toString('utf8').trim())\n if (!Number.isFinite(size))\n return notFound()\n if (size > maxBytes)\n return tooLarge()\n const bytes = await gitBytes(top, ['show', `HEAD:${path}`])\n return bytes\n ? new Response(new Uint8Array(bytes), { headers: { 'content-type': mime, 'cache-control': 'no-cache' } })\n : notFound()\n}\n\n/**\n * The response for one media address: its bytes, a range of them (206), or\n * 404 (not media, not found, outside the folder), 413 (over `maxBytes`), 416\n * (a range past the end).\n *\n * @param request - The folder, the path and the side.\n * @param range - The request's `Range` header.\n * @param options - Options.\n */\nexport async function serveWorkspaceMedia(request: WorkspaceMediaRequest, range: string | null, options: WorkspaceMediaOptions = {}): Promise<Response> {\n const type = mediaTypeOfPath(request.path)\n if (!type)\n return notFound()\n const maxBytes = options.maxBytes ?? Infinity\n return request.side\n ? diffMedia(request.cwd, request.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C;CAC1D,OAAO,QACH,IAAI,SAAS,IAAI,WAAW,KAAK,GAAG,EAAE,SAAS;EAAE,gBAAgB;EAAM,iBAAiB;CAAW,EAAE,CAAC,IACtG,SAAS;AACf;;;;;;;;;;AAWA,eAAsB,oBAAoB,SAAgC,OAAsB,UAAiC,CAAC,GAAsB;CACtJ,MAAM,OAAO,gBAAgB,QAAQ,IAAI;CACzC,IAAI,CAAC,MACH,OAAO,SAAS;CAClB,MAAM,WAAW,QAAQ,YAAY;CACrC,OAAO,QAAQ,OACX,UAAU,QAAQ,KAAK,QAAQ,MAAM,KAAK,MAAM,QAAQ,MAAM,OAAO,QAAQ,IAC7E,UAAU,QAAQ,KAAK,QAAQ,MAAM,KAAK,MAAM,OAAO,WAAW,QAAQ;AAChF"}
|
|
1
|
+
{"version":3,"file":"chat.js","names":[],"sources":["../src/chat/auto-update-cli.ts","../src/chat/git/repo-info.ts","../src/chat/todo-anchor.ts","../src/chat/workspace/local-entries.ts","../src/chat/workspace/media.ts"],"sourcesContent":["// ---------------------------------------------------------------------------\n// `zidane upgrade` subcommand — drop-in handler for consumer CLIs.\n//\n// Wraps `checkForUpdate` + `performSelfUpdate` + `performInPlaceSelfUpdate`\n// into a single function the host's `cli.ts` can call. The behavior layers:\n//\n// - no flags → check + run the package manager\n// - `--check` → check only, print the latest version + bail\n// - `--in-place` → skip the PM, download + atomic-rename the binary\n// - `--dry-run` → resolve everything but don't actually swap\n// - `--channel <tag>` → override dist-tag (defaults to `'latest'`)\n// - `--registry <url>`→ override the npm registry URL\n// - `--package-manager <pm>` (`--pm`) → force npm, pnpm, yarn, bun or volta\n// - `--force` → install even when already on latest or the registry check failed\n// - `--tui-only` → skip companion packages (see `companions`)\n// - `-h`, `--help` → print the usage text\n//\n// Companions: sibling globals released on the same version line (today\n// `zidane-gui`). When one is installed, `upgrade` checks and re-installs it\n// too — through the package manager that owns THAT install, which may differ\n// from the TUI's. Companion failures are reported and fail the exit code but\n// never block the TUI's own upgrade.\n//\n// I/O only: reads the registry, spawns the package manager, writes to\n// stdout/stderr and the update-applied marker, and returns the exit code the\n// caller should pass to `process.exit`. No React, no OpenTUI; safe to call\n// before / instead of `runTui`.\n// ---------------------------------------------------------------------------\n\nimport type { CliStyle } from '../cli-style'\nimport type { PackageManagerCommand, UpdateStatus } from './auto-update'\nimport type { CompanionSpec, InstalledCompanion } from './auto-update-companion'\nimport type { UpdateLockOptions } from './auto-update-lock'\nimport type { UpdateAppliedMarker } from './auto-update-restart'\nimport { cliStyle } from '../cli-style'\nimport {\n checkForUpdate,\n checkTarballAvailable,\n compareSemver,\n detectPackageManager,\n overrideManager,\n performInPlaceSelfUpdate,\n performSelfUpdate,\n reinstallHint,\n resolvePlatformPackage,\n} from './auto-update'\nimport { clearFailedUpdate } from './auto-update-auto-install'\nimport { findInstalledCompanion } from './auto-update-companion'\nimport { acquireUpdateLock, describeUpdateLockHolder } from './auto-update-lock'\nimport { writeUpdateAppliedMarker } from './auto-update-restart'\n\n/** Options for {@link runUpdateCommand}. */\nexport interface RunUpdateCommandOptions {\n /** Top-level package the user installs (e.g. `'zidane-tui'`). */\n packageName: string\n /** Inlined at build time. */\n currentVersion: string\n /** Args passed after `upgrade` (typically `process.argv.slice(3)`). */\n argv: readonly string[]\n /** Where to persist the TTL cache. Usually `paths.userDir`. */\n cacheDir?: string\n /** Default channel when `--channel` isn't passed. Defaults to `'latest'`. */\n defaultChannel?: string\n /**\n * Override the platform-package-name prefix used by `--in-place`.\n * Defaults to `'<packageName>-'`, matching the `zidane-tui-<key>` layout.\n */\n platformPackagePrefix?: string\n /** Override registry. Defaults to npmjs. */\n registry?: string\n /** stdout. Defaults to `process.stdout`. */\n stdout?: NodeJS.WritableStream\n /** stderr. Defaults to `process.stderr`. */\n stderr?: NodeJS.WritableStream\n /**\n * Sibling packages to keep in step when installed (e.g. `zidane-gui`).\n * Absent companions are silently skipped; `--tui-only` skips them all.\n */\n companions?: readonly CompanionSpec[]\n /**\n * Reports the version now installed for `packageName` (e.g. by running the\n * bin with `--version`), `null` when nothing usable is there, `undefined`\n * to skip verification. The host wires this; the library cannot know how\n * its own bin is invoked.\n */\n verifyInstalled?: (packageName: string) => string | null | undefined\n /** Inject for tests. */\n findCompanion?: typeof findInstalledCompanion\n /** Inject for tests. */\n performSelfUpdate?: typeof performSelfUpdate\n /** Inject for tests. */\n checkTarballAvailable?: typeof checkTarballAvailable\n /** Inject for tests. */\n writeMarker?: typeof writeUpdateAppliedMarker\n /** Inject for tests: clock, liveness probe and pid of the install lock. */\n lock?: UpdateLockOptions\n /** The caller already holds the install lock (the update worker): don't take it again. */\n lockHeld?: boolean\n /** Appended to `--help`: how this host runs installs (e.g. in the background). */\n helpNote?: string\n}\n\n/** Result of {@link runUpdateCommand}. */\nexport interface RunUpdateCommandResult {\n /** Process exit code: `0` on success, `1` on failure, `2` for invalid arguments. */\n exitCode: number\n}\n\nconst UPGRADE_HELP = `Usage: zidane upgrade [options]\n\nUpdate the zidane CLI to the latest release. A globally installed\nzidane-gui is upgraded alongside it, through its own package manager.\n\nOptions:\n --check Print the latest version and exit (no install).\n --tui-only Leave companion packages (zidane-gui) alone.\n --in-place Download the platform binary directly from npm\n and atomic-rename over the running binary.\n Skips the package manager. Refused on Volta.\n --dry-run Resolve everything but don't actually install.\n --channel <tag> dist-tag to query (default: latest).\n --registry <url> Override the npm registry.\n --package-manager <pm> Force npm | pnpm | yarn | bun | volta.\n --force Run the install even if we're already on latest,\n or the registry check failed.\n -h, --help Print this help.\n\nEnvironment:\n NO_UPDATE_NOTIFIER Silence the background check (set to \"1\").\n ZIDANE_NO_UPDATE Same, project-specific.\n`\n\n/**\n * Run the `upgrade` subcommand. Exit code contract:\n * - `0` — update succeeded, `--check` reported no update, or `--check`\n * reported an update (informational only).\n * - `1` — update failed (PM exit non-zero, in-place download failed,\n * registry check failed without `--force`, release not\n * downloadable yet, or the installed version did not change).\n * - `2` — argv parse error (unknown flag).\n *\n * Output is a short ledger, one line per package, led by a status mark\n * (`src/cli-style.ts`):\n * · zidane-tui 7.0.7 → 7.0.8\n * $ volta install zidane-tui@latest\n * …\n * ✓ zidane-tui 7.0.8 installed\n * Diagnostics go to stderr and say what to do next.\n *\n * @param options - Package, version, argv and I/O settings for the command.\n */\nexport async function runUpdateCommand(options: RunUpdateCommandOptions): Promise<RunUpdateCommandResult> {\n const out = options.stdout ?? process.stdout\n const err = options.stderr ?? process.stderr\n const o = cliStyle(out)\n const e = cliStyle(err)\n const parsed = parseArgs(options.argv)\n if (parsed.kind === 'error') {\n err.write(`${e.error(`zidane upgrade: ${parsed.message}.`, undefined, 'zidane upgrade --help lists the flags.')}\\n`)\n return { exitCode: 2 }\n }\n if (parsed.help) {\n out.write(options.helpNote ? `${UPGRADE_HELP}\\n${options.helpNote.trimEnd()}\\n` : UPGRADE_HELP)\n return { exitCode: 0 }\n }\n const flags: ParsedFlags = parsed\n\n const channel = flags.channel ?? options.defaultChannel ?? 'latest'\n const registry = flags.registry ?? options.registry\n const tarballAvailable = options.checkTarballAvailable ?? checkTarballAvailable\n const install = options.performSelfUpdate ?? performSelfUpdate\n\n // Always force the check — user typed `upgrade`, env opt-outs shouldn't\n // get in the way.\n const status = await checkForUpdate({\n packageName: options.packageName,\n currentVersion: options.currentVersion,\n channel,\n registry,\n cacheDir: options.cacheDir,\n force: true,\n timeoutMs: 8000,\n })\n const self: Entry = {\n name: options.packageName,\n current: options.currentVersion,\n status,\n outdated: status.latest !== null && compareSemver(status.latest, options.currentVersion) > 0,\n }\n\n // Companions: discovered locally, then checked on the registry with the\n // same channel. Only installed ones take part; nothing is printed for the\n // rest, so users without the GUI see the exact output they always did.\n const companions = flags.tuiOnly ? [] : await resolveCompanions(options, channel, registry)\n const entries: Entry[] = [self, ...companions]\n const label = (name: string) => name.padEnd(Math.max(...entries.map(e => e.name.length)))\n\n // `--check` is informational — degrade gracefully on registry errors\n // (offline laptop, restricted proxy) and exit 0 so the user can script\n // around it without quoting tricks.\n if (flags.check) {\n for (const entry of entries)\n out.write(`${statusLine(entry, label, o)}\\n`)\n return { exitCode: 0 }\n }\n\n // Install path — a registry error means we don't KNOW if we need an\n // update. Refuse to spawn the PM blindly unless the user explicitly\n // asks via `--force`.\n if (status.source === 'error') {\n if (!flags.force) {\n err.write(`${e.error(`${self.name}: registry check failed.`, status.error ?? 'unknown error', 'run zidane upgrade --force to install anyway.')}\\n`)\n return { exitCode: 1 }\n }\n err.write(`${e.step('warn', `${self.name}: registry check failed: ${status.error ?? 'unknown error'}`)}\\n`)\n }\n for (const c of companions.filter(c => c.status.source === 'error' && !flags.force))\n err.write(`${e.step('warn', `${c.name}: registry check failed: ${c.status.error ?? 'unknown error'}`)}\\n`)\n\n const selfPending = flags.force || self.outdated\n const pendingCompanions = companions.filter(c => flags.force || c.outdated)\n for (const entry of entries.filter(entry => !entry.outdated && entry.status.source !== 'error'))\n out.write(`${statusLine(entry, label, o)}\\n`)\n if (!selfPending && pendingCompanions.length === 0)\n return { exitCode: 0 }\n\n // The TUI's own install runs first (in-place or PM); companions follow.\n // A companion failure sets the exit code but never undoes or blocks the\n // TUI upgrade that already happened.\n // One install at a time: the desktop app or a running TUI may be\n // installing in the background. Racing two package managers over the same\n // global install breaks it, so say who holds the lock and stop.\n const lock = options.cacheDir && !flags.dryRun && !options.lockHeld ? acquireUpdateLock(options.cacheDir, 'zidane upgrade', options.lock) : null\n if (lock && !lock.acquired) {\n err.write(`${e.error('zidane upgrade: another update is running.', `${describeUpdateLockHolder(lock.holder, (options.lock?.now ?? Date.now)())}.`, 'wait for it to finish, then run zidane upgrade again.')}\\n`)\n return { exitCode: 1 }\n }\n try {\n // A manual install is the retry for a failed automatic one.\n if (options.cacheDir && !flags.dryRun)\n clearFailedUpdate(options.cacheDir)\n let exitCode = 0\n const applied: UpdateAppliedMarker['packages'] = []\n if (selfPending) {\n exitCode = await upgradeSelf()\n if (exitCode === 0 && !flags.dryRun && status.latest)\n applied.push({ packageName: self.name, version: status.latest })\n }\n for (const c of pendingCompanions) {\n const code = await upgradeCompanion(c)\n if (code === 0 && !flags.dryRun && c.status.latest)\n applied.push({ packageName: c.name, version: c.status.latest })\n if (exitCode === 0)\n exitCode = code\n }\n // Wake running TUIs / GUIs: they watch this marker and offer a restart.\n if (applied.length > 0 && options.cacheDir)\n (options.writeMarker ?? writeUpdateAppliedMarker)(options.cacheDir, { at: Date.now(), packages: applied })\n return { exitCode }\n }\n finally {\n if (lock?.acquired)\n lock.release()\n }\n\n /**\n * Refuse to spawn the PM while the release is not fetchable yet: npm treats\n * a 404 on an `optionalDependencies` platform binary as \"skip\" and leaves\n * an empty install behind the bin. `--force` overrides (mirrors, offline\n * registries).\n */\n async function ready(packageName: string, version: string): Promise<boolean> {\n if (flags.force || flags.dryRun)\n return true\n const availability = await tarballAvailable({ packageName, version, registry })\n if (availability !== 'missing')\n return true\n err.write(`${e.error(`${packageName} ${version} is published but not downloadable yet.`, undefined, 'try again in a few minutes.')}\\n`)\n return false\n }\n\n async function upgradeSelf(): Promise<number> {\n const target = status.latest ?? channel\n out.write(`${o.step('info', `${label(self.name)} ${self.current} → ${target}`)}\\n`)\n\n if (flags.inPlace) {\n const platformPkg = resolvePlatformPackage({\n prefix: options.platformPackagePrefix ?? `${options.packageName}-`,\n })\n if (!platformPkg) {\n err.write(`${e.error(`${self.name}: no prebuilt binary for ${process.platform}/${process.arch}.`, undefined, 'drop --in-place to use your package manager instead.')}\\n`)\n return 1\n }\n if (status.latest && !await ready(platformPkg, status.latest))\n return 1\n const result = await performInPlaceSelfUpdate({ packageName: platformPkg, channel, registry, dryRun: flags.dryRun })\n if (result.status === 'success') {\n out.write(`${flags.dryRun ? o.step('info', `${label(self.name)} ${result.installedVersion} would install`) : o.step('ok', `${label(self.name)} ${result.installedVersion} installed`)}\\n`)\n return 0\n }\n err.write(`${e.error(`${self.name}: in-place update failed.`, result.reason ?? 'unknown error', result.status === 'refused' ? 'drop --in-place to go through the package manager.' : undefined)}\\n`)\n return 1\n }\n\n // The platform binary is the part that can be missing from the CDN; the\n // meta package is tiny and published right after it.\n const platformPkg = resolvePlatformPackage({ prefix: options.platformPackagePrefix ?? `${options.packageName}-` })\n if (status.latest && !await ready(platformPkg ?? options.packageName, status.latest))\n return 1\n\n const command = flags.packageManager\n ? overrideManager(flags.packageManager, options.packageName, channel)\n : detectPackageManager({ packageName: options.packageName, channel })\n out.write(`${o.hint(` $ ${command.argv.join(' ')}`)}\\n`)\n if (flags.dryRun)\n return 0\n const result = await install({ packageName: options.packageName, channel, packageManager: flags.packageManager ?? 'auto' })\n if (result.spawnError) {\n err.write(`${e.error(`${self.name}: could not run ${result.command.argv[0]}.`, result.spawnError, 'install it, or pick another with --package-manager.')}\\n`)\n return 1\n }\n if (result.exitCode !== 0) {\n err.write(`${e.error(`${self.name}: ${result.command.argv[0]} exited with ${result.exitCode ?? 'unknown'}.`, undefined, 'read its output above, then run zidane upgrade again.')}\\n`)\n return result.exitCode ?? 1\n }\n return verify(self.name, status.latest, options.verifyInstalled?.(options.packageName), result.command)\n }\n\n async function upgradeCompanion(c: CompanionEntry): Promise<number> {\n const target = c.status.latest ?? channel\n out.write(`${o.step('info', `${label(c.name)} ${c.current} → ${target}`)}\\n`)\n if (c.status.latest && !await ready(c.name, c.status.latest))\n return 1\n // `--package-manager` is an override for the TUI's install; the\n // companion follows the PM that owns its own bin unless forced too.\n const command = flags.packageManager ? overrideManager(flags.packageManager, c.name, channel) : c.command\n out.write(`${o.hint(` $ ${command.argv.join(' ')}`)}\\n`)\n if (flags.dryRun)\n return 0\n const result = await install({ packageName: c.name, channel, packageManager: flags.packageManager ?? c.command.id })\n if (result.spawnError) {\n err.write(`${e.error(`${c.name}: could not run ${result.command.argv[0]}.`, result.spawnError, 'install it, or pick another with --package-manager.')}\\n`)\n return 1\n }\n if (result.exitCode !== 0) {\n err.write(`${e.error(`${c.name}: ${result.command.argv[0]} exited with ${result.exitCode ?? 'unknown'}.`, undefined, 'read its output above, then run zidane upgrade again.')}\\n`)\n return 1\n }\n const find = options.findCompanion ?? findInstalledCompanion\n return verify(c.name, c.status.latest, find(c.spec)?.version, result.command)\n }\n\n /**\n * The PM exiting 0 is not proof: a skipped optional platform binary or a\n * Volta no-op (\"already installed\") both exit 0 and leave the old version\n * behind. Compare what is actually on disk with what we asked for.\n */\n function verify(name: string, expected: string | null, actual: string | undefined | null, command: PackageManagerCommand): number {\n if (!expected || actual === undefined) {\n out.write(`${o.step('ok', `${label(name)} ${expected ?? channel} installed`)}\\n`)\n return 0\n }\n if (actual !== null && compareSemver(actual, expected) >= 0) {\n out.write(`${o.step('ok', `${label(name)} ${actual} installed`)}\\n`)\n return 0\n }\n err.write(`${e.error(`${name}: install finished but ${actual ?? 'nothing'} is on disk, expected ${expected}.`, undefined, `reinstall: ${reinstallHint(command, name, channel)}`)}\\n`)\n return 1\n }\n}\n\nfunction statusLine(e: Entry, label: (name: string) => string, style: CliStyle): string {\n const name = label(e.name)\n if (e.status.source === 'error')\n return style.step('fail', `${name} ${e.current}`, `(check failed: ${e.status.error ?? 'unknown error'})`)\n if (!e.status.latest)\n return style.step('info', `${name} ${e.current}`, '(latest unknown)')\n return e.outdated ? style.step('info', `${name} ${e.current} → ${e.status.latest} available`) : style.step('ok', `${name} ${e.current} up to date`)\n}\n\n// ---------------------------------------------------------------------------\n// Ledger entries\n// ---------------------------------------------------------------------------\n\ninterface Entry {\n name: string\n /** Installed version. */\n current: string\n status: UpdateStatus\n /** Registry knows a newer version than the installed one. */\n outdated: boolean\n}\n\ninterface CompanionEntry extends Entry {\n spec: CompanionSpec\n installed: InstalledCompanion\n /** The PM that owns this install — from ITS bin path, not the TUI's. */\n command: PackageManagerCommand\n}\n\nasync function resolveCompanions(\n options: RunUpdateCommandOptions,\n channel: string,\n registry: string | undefined,\n): Promise<CompanionEntry[]> {\n const find = options.findCompanion ?? findInstalledCompanion\n const found = (options.companions ?? [])\n .map(spec => ({ spec, installed: find(spec) }))\n .filter((c): c is { spec: CompanionSpec, installed: InstalledCompanion } => c.installed !== null)\n return await Promise.all(found.map(async ({ spec, installed }) => {\n const status = await checkForUpdate({\n packageName: installed.packageName,\n currentVersion: installed.version,\n channel,\n registry,\n cacheDir: options.cacheDir,\n force: true,\n timeoutMs: 8000,\n })\n return {\n spec,\n installed,\n name: installed.packageName,\n current: installed.version,\n status,\n outdated: status.latest !== null && compareSemver(status.latest, installed.version) > 0,\n command: detectPackageManager({ packageName: installed.packageName, channel, binaryPath: installed.binaryPath }),\n }\n }))\n}\n\n// ---------------------------------------------------------------------------\n// Argv parser — minimal, just enough to drop into the consumer's `cli.ts`.\n// We deliberately don't pull in commander/yargs for a small flag surface.\n// ---------------------------------------------------------------------------\n\ntype ParsedFlags = Extract<ParseResult, { kind: 'ok' }>\n\ntype ParseResult\n = | {\n kind: 'ok'\n check: boolean\n inPlace: boolean\n dryRun: boolean\n force: boolean\n help: boolean\n tuiOnly: boolean\n channel?: string\n registry?: string\n packageManager?: 'npm' | 'pnpm' | 'yarn' | 'bun' | 'volta'\n }\n | { kind: 'error', message: string }\n\nfunction parseArgs(argv: readonly string[]): ParseResult {\n let check = false\n let inPlace = false\n let dryRun = false\n let force = false\n let help = false\n let tuiOnly = false\n let channel: string | undefined\n let registry: string | undefined\n let packageManager: 'npm' | 'pnpm' | 'yarn' | 'bun' | 'volta' | undefined\n\n for (let i = 0; i < argv.length; i++) {\n const a = argv[i]!\n switch (a) {\n case '--check': check = true; break\n case '--in-place':\n case '--inplace': inPlace = true; break\n case '--dry-run':\n case '--dryrun': dryRun = true; break\n case '--force': force = true; break\n case '--tui-only': tuiOnly = true; break\n case '-h':\n case '--help': help = true; break\n case '--channel':\n channel = argv[++i]\n if (!channel)\n return { kind: 'error', message: '--channel requires a value' }\n break\n case '--registry':\n registry = argv[++i]\n if (!registry)\n return { kind: 'error', message: '--registry requires a value' }\n break\n case '--package-manager':\n case '--pm': {\n const v = argv[++i]\n if (!v)\n return { kind: 'error', message: '--package-manager requires a value' }\n if (v !== 'npm' && v !== 'pnpm' && v !== 'yarn' && v !== 'bun' && v !== 'volta')\n return { kind: 'error', message: `unknown package manager: ${v}` }\n packageManager = v\n break\n }\n default:\n return { kind: 'error', message: `unknown argument: ${a}` }\n }\n }\n\n return { kind: 'ok', check, inPlace, dryRun, force, help, tuiOnly, channel, registry, packageManager }\n}\n","/**\n * What the import dialog shows about a repository before it is cloned: for a\n * GitHub repository, its description, stars, language and default branch\n * (GitHub's REST API), with the owner's avatar and the repository's preview\n * image (`githubAvatarUrl`, `githubPreviewImageUrl`, as the skill browser\n * shows them). Another forge has no info: the dialog shows the parse alone.\n *\n * A failure (no network, a private repository without access, GitHub's rate\n * limit) answers `null`: the info is a nicety, never a reason to refuse.\n * Answers (a repository, or GitHub's \"not found\") are kept for 10 minutes\n * per repository and token.\n */\nimport type { RepoInfo } from './types'\nimport { createHash } from 'node:crypto'\nimport { githubAvatarUrl, githubPreviewImageUrl } from '../../skills/sources'\nimport { parseRepoInput } from './repo-url'\n\nconst API = 'https://api.github.com'\nconst CACHE_TTL_MS = 10 * 60_000\nconst TIMEOUT_MS = 8_000\n/** Repositories kept at once; the oldest goes first. */\nconst CACHE_MAX = 256\nconst cache = new Map<string, { at: number, info: RepoInfo | null }>()\n\n/**\n * The owner and repository of a GitHub clone URL (https, scp-like or ssh); `null` for another host.\n *\n * @param cloneUrl - The URL `git clone` takes.\n */\nexport function githubRepoOf(cloneUrl: string): { owner: string, repo: string } | null {\n // github.com must be the host: `https://evil.example/github.com/o/r` is not GitHub's `o/r`.\n const m = /^(?:(?:https?|ssh|git):\\/\\/(?:[^@/]+@)?|(?:[\\w.-]+@)?)github\\.com[/:]([\\w.-]+)\\/([\\w.-]+?)(?:\\.git)?\\/?$/i.exec(cloneUrl)\n return m ? { owner: m[1]!, repo: m[2]! } : null\n}\n\ninterface GithubRepo {\n full_name: string\n description: string | null\n stargazers_count: number\n language: string | null\n default_branch: string\n html_url: string\n private: boolean\n archived: boolean\n}\n\n/** Options of {@link fetchRepoInfo}. */\nexport interface FetchRepoInfoOptions {\n /** A GitHub token: private repositories, and 5,000 calls an hour instead of 60. */\n token?: string\n /** Test seam. Default: the global `fetch`. */\n fetch?: typeof fetch\n}\n\n/**\n * The info of the repository `input` names (what the import dialog would clone); `null` when there is none.\n *\n * @param input - What was pasted: a git or forge URL, or `owner/repo`.\n * @param options - A token, and the fetch to use.\n */\nexport async function fetchRepoInfo(input: string, options: FetchRepoInfoOptions = {}): Promise<RepoInfo | null> {\n const spec = parseRepoInput(input)\n const gh = spec ? githubRepoOf(spec.cloneUrl) : null\n if (!gh)\n return null\n const key = `${gh.owner}/${gh.repo}`.toLowerCase() + (options.token ? `\\u0000${createHash('sha256').update(options.token).digest('hex')}` : '')\n const hit = cache.get(key)\n if (hit && Date.now() - hit.at < CACHE_TTL_MS)\n return hit.info\n const doFetch = options.fetch ?? fetch\n let info: RepoInfo | null = null\n try {\n const res = await doFetch(`${API}/repos/${encodeURIComponent(gh.owner)}/${encodeURIComponent(gh.repo)}`, {\n headers: {\n 'Accept': 'application/vnd.github+json',\n 'X-GitHub-Api-Version': '2022-11-28',\n ...(options.token ? { Authorization: `Bearer ${options.token}` } : {}),\n },\n signal: AbortSignal.timeout(TIMEOUT_MS),\n })\n // A refusal for the rate limit is not an answer about the repository: not kept.\n if (!res.ok && res.status !== 404)\n return null\n if (res.ok) {\n const repo = await res.json() as GithubRepo\n const [owner = gh.owner, name = gh.repo] = repo.full_name.split('/')\n info = {\n owner,\n repo: name,\n url: repo.html_url,\n ...(repo.description ? { description: repo.description } : {}),\n stars: repo.stargazers_count,\n ...(repo.language ? { language: repo.language } : {}),\n defaultBranch: repo.default_branch,\n ...(repo.private ? { private: true } : {}),\n ...(repo.archived ? { archived: true } : {}),\n avatarUrl: githubAvatarUrl(owner),\n imageUrl: githubPreviewImageUrl(owner, name),\n }\n }\n }\n catch {\n // Offline or timed out: no info, and the next ask tries again.\n return null\n }\n const now = Date.now()\n // Re-inserted so the map stays ordered by `at`: expired entries lead.\n cache.delete(key)\n for (const [k, entry] of cache) {\n if (now - entry.at < CACHE_TTL_MS && cache.size < CACHE_MAX)\n break\n cache.delete(k)\n }\n cache.set(key, { at: now, info })\n return info\n}\n","import type { AgentHookMap } from '../agent'\nimport type { TodoItem } from './todos'\nimport { appendDynamicSection } from '../system-prompt'\nimport { selectActiveTodos } from './todos'\n\n/** Options for the active-todo system-prompt anchor. */\nexport interface ActiveTodoAnchorOptions {\n /**\n * Set to `false` to render nothing.\n *\n * @default true\n */\n enabled?: boolean\n /**\n * Maximum todos listed before a `... N more` line. Values below 1 count as 1.\n *\n * @default 6\n */\n maxItems?: number\n /**\n * Heading text of the section.\n *\n * @default 'Active Todo Anchor'\n */\n heading?: string\n}\n\n/**\n * Renders the active todos as a system-prompt section. Returns `''` when disabled or there are no todos.\n *\n * @param todos - Active todos in order.\n * @param options - Anchor options.\n */\nexport function renderActiveTodoAnchor(\n todos: readonly TodoItem[],\n options: ActiveTodoAnchorOptions = {},\n): string {\n if (options.enabled === false || todos.length === 0)\n return ''\n const maxItems = Math.max(1, Math.floor(options.maxItems ?? 6))\n const heading = options.heading ?? 'Active Todo Anchor'\n const visible = todos.slice(0, maxItems)\n const lines = [`# ${heading}`, '<active_todos>']\n for (const item of visible)\n lines.push(`- [${item.status}] ${item.content}`)\n if (todos.length > visible.length)\n lines.push(`- ... ${todos.length - visible.length} more`)\n lines.push('</active_todos>')\n return lines.join('\\n')\n}\n\n/**\n * Optional chat-layer hook that keeps the live `todowrite` list visible in the\n * dynamic system prompt. It reads only live todos, never the archive, so an\n * auto-cleared completed plan is not reintroduced on later turns.\n *\n * ## Prompt-cache cost — read before enabling\n *\n * This writes per-turn state into the system prompt, and the system prompt sits\n * ABOVE the entire conversation in the provider's cache prefix (Anthropic hashes\n * tools → system → messages, cumulatively). So every time the rendered anchor\n * changes by a single byte, the whole transcript stops matching the cache and\n * re-bills at the cache-write rate; only `tools` and the static system block\n * survive.\n *\n * That is an acceptable trade only because the anchor changes *rarely* — once\n * per `todowrite`, which in practice is a small fraction of turns. Two rules\n * follow, and breaking either one turns that occasional cost into a per-turn\n * one:\n *\n * 1. Never add anything to the anchor that ticks on its own — no counters, no\n * timestamps, no elapsed times, no per-turn indices.\n * 2. The render must stay a pure function of the todo list.\n * `renderActiveTodoAnchor` is deterministic today, so identical todos emit\n * identical bytes; keep it that way. Note this does NOT cover reordering —\n * todo order is semantically meaningful (it is the plan), so a reorder is\n * a real state change and costs one re-bill like any other `todowrite`.\n *\n * Moving the anchor onto the newest message instead does NOT avoid this: it is\n * wire-only, so the message that carried last turn's anchor re-renders without\n * it, and the prefix diverges at that point just the same. The only injection\n * that is genuinely free is one persisted into the transcript as immutable\n * history.\n *\n * @param options - Anchor options.\n */\nexport function createActiveTodoAnchorHooks(options: ActiveTodoAnchorOptions = {}): AgentHookMap {\n return {\n 'system:transform': (ctx) => {\n const state = selectActiveTodos(ctx.session)\n const anchor = renderActiveTodoAnchor(state.todos, options)\n\n if (anchor)\n ctx.system = appendDynamicSection(ctx.system, anchor)\n },\n }\n}\n","/**\n * Entry actions on a folder of this machine (the Files tab of a local folder\n * or worktree): `createEntryOps` over node's fs, every path confined to the\n * folder. A path may not leave it lexically, and the folder holding it must\n * real-path inside it (a symlinked folder pointing out is refused); the\n * entry itself is never followed, so a link is renamed or removed, not what\n * it points at.\n *\n * Also what a drop from the file manager needs: copying absolute paths of\n * this machine into the folder (`importPaths`), and reading them as import\n * items for a folder that lives elsewhere (`hostImportItems`).\n */\nimport type { EntryImportItem, EntryImportResult, EntryOps } from './entries'\nimport { cp, lstat, readdir, readFile, realpath } from 'node:fs/promises'\nimport { basename, dirname, isAbsolute, join, resolve, sep } from 'node:path'\nimport { nodeEntryPort } from '../../contexts/entries'\nimport { createEntryOps, ENTRY_IMPORT_MAX_BYTES, ENTRY_IMPORT_MAX_ENTRIES, entryPath, freeEntryName, joinEntry } from './entries'\n\nconst inside = (root: string, path: string): boolean => path === root || path.startsWith(root + sep)\n\n/** The real path of `path`'s nearest existing ancestor (itself included), with the rest appended. */\nasync function realAncestor(path: string): Promise<string> {\n const tail: string[] = []\n let at = path\n while (true) {\n const real = await realpath(at).catch(() => null)\n if (real)\n return tail.length ? join(real, ...tail) : real\n const parent = dirname(at)\n if (parent === at)\n return path\n tail.unshift(basename(at))\n at = parent\n }\n}\n\n/**\n * `path` (relative to `cwd`) as an absolute path inside it: refused (throws)\n * when it leaves the folder lexically or its parent folder real-paths out.\n *\n * @param cwd - The folder (absolute).\n * @param path - A path relative to it.\n */\nexport async function containedEntryPath(cwd: string, path: string): Promise<string> {\n if (!isAbsolute(cwd))\n throw new Error(`${cwd} is not an absolute folder.`)\n const root = await realpath(cwd)\n const target = resolve(root, path)\n if (!inside(root, target))\n throw Object.assign(new Error(`${path} is outside the folder.`), { code: 'EACCES' })\n if (target !== root && !inside(root, await realAncestor(dirname(target))))\n throw Object.assign(new Error(`${path} is outside the folder.`), { code: 'EACCES' })\n return target\n}\n\n/** The entry actions of a local folder, plus copying in paths of this machine. */\nexport interface LocalEntryOps extends EntryOps {\n /** Copies absolute paths of this machine (a drop from the file manager) into folder `dir`, each under a free name. */\n importPaths: (dir: string, paths: readonly string[]) => Promise<EntryImportResult>\n}\n\n/**\n * The entry actions of `cwd`, a folder of this machine.\n *\n * @param cwd - The folder (absolute).\n * @param options - Options.\n * @param options.trash - Removes recoverably (the system trash). Default: removed for good.\n */\nexport function workspaceEntryOps(cwd: string, options: { trash?: (absolute: string) => Promise<void> } = {}): LocalEntryOps {\n const port = nodeEntryPort({ resolve: path => containedEntryPath(cwd, path), ...(options.trash ? { trash: options.trash } : {}) })\n const ops = createEntryOps(port)\n return {\n ...ops,\n async importPaths(rawDir, sources) {\n const dir = entryPath(rawDir, true)\n if (dir === null)\n return { ok: false, reason: 'invalid', message: `\"${rawDir}\" is not a valid folder.`, paths: [] }\n if (dir !== '' && (await port.stat(dir)) !== 'dir')\n return { ok: false, reason: 'missing', message: `${dir} is not a folder.`, paths: [] }\n const paths: string[] = []\n for (const source of sources) {\n try {\n if (!isAbsolute(source))\n throw new Error(`${source} is not an absolute path.`)\n const kind = (await lstat(source)).isDirectory() ? 'dir' : 'file'\n const target = joinEntry(dir, await freeEntryName(port, dir, basename(source), kind))\n await cp(source, await containedEntryPath(cwd, target), { recursive: true, errorOnExist: true, force: false, verbatimSymlinks: true })\n paths.push(target)\n }\n catch (error) {\n return { ok: false, reason: 'denied', message: error instanceof Error ? error.message : String(error), paths }\n }\n }\n return { ok: true, paths }\n },\n }\n}\n\n/**\n * Absolute paths of this machine as import items (a drop headed for a folder\n * elsewhere: a sandbox, a server): files read when their turn comes, folders\n * walked one entry at a time. Symlinks and special files are left out.\n * The walk stops once the import limits are passed: what it returns then is\n * still over them, so `importEntries` refuses it without a whole tree read.\n *\n * @param paths - The dropped paths.\n * @param limits - When to stop walking.\n * @param limits.maxEntries - Entries (files and folders). Default {@link ENTRY_IMPORT_MAX_ENTRIES}.\n * @param limits.maxBytes - All files together. Default {@link ENTRY_IMPORT_MAX_BYTES}.\n */\nexport async function hostImportItems(\n paths: readonly string[],\n limits: { maxEntries?: number, maxBytes?: number } = {},\n): Promise<EntryImportItem[]> {\n const maxEntries = limits.maxEntries ?? ENTRY_IMPORT_MAX_ENTRIES\n const maxBytes = limits.maxBytes ?? ENTRY_IMPORT_MAX_BYTES\n let entries = 0\n let bytes = 0\n const over = (): boolean => entries > maxEntries || bytes > maxBytes\n const item = async (path: string): Promise<EntryImportItem | null> => {\n const info = await lstat(path)\n if (info.isDirectory()) {\n entries++\n const children: EntryImportItem[] = []\n for (const name of (await readdir(path)).sort()) {\n if (over())\n break\n const child = await item(join(path, name))\n if (child)\n children.push(child)\n }\n return { name: basename(path), children }\n }\n if (!info.isFile())\n return null\n entries++\n bytes += info.size\n return { name: basename(path), size: info.size, read: async () => new Uint8Array(await readFile(path)) }\n }\n const items: EntryImportItem[] = []\n for (const path of paths) {\n if (over())\n break\n const made = await item(path)\n if (made)\n items.push(made)\n }\n return items\n}\n","/**\n * The bytes of a workspace's media (an image, a video, audio), as a web\n * `Response`, for a viewer that plays them by address: the desktop app's\n * `zg-media:` scheme and zidane-server's `GET /zidane/media`.\n *\n * - a file of `cwd`, confined to it like every editor read (no `..`, no\n * symlink out), streamed with byte ranges so a video seeks without\n * loading whole;\n * - one side of a change (`side`), the path relative to the repository\n * holding `cwd` (git's names): `old` from the last commit (`git show`),\n * `new` from the working tree, confined to the repository.\n *\n * Only the media types of `mediaTypeOfPath` are served, under their own\n * content type. A file address carries its version (its mtime), so the bytes\n * of one address never change and are cached for good; a change's sides\n * change any time and are revalidated.\n */\nimport { Buffer } from 'node:buffer'\nimport { spawn } from 'node:child_process'\nimport { createReadStream } from 'node:fs'\nimport { stat } from 'node:fs/promises'\nimport { Readable } from 'node:stream'\nimport { confineToWorkspace } from './files'\nimport { mediaTypeOfPath } from './media-type'\n\n/** What to serve. */\nexport interface WorkspaceMediaRequest {\n /** The folder the path is in. */\n cwd: string\n /** Relative to `cwd`, or (with `side`) to the repository holding it. */\n path: string\n /** One side of the path's git change: the last commit's or the working tree's. Absent: the file now. */\n side?: 'old' | 'new'\n}\n\n/** Options of {@link serveWorkspaceMedia}. */\nexport interface WorkspaceMediaOptions {\n /** Most bytes one response carries: a longer range is cut short, a whole body over it refused (413). Default: no cap. */\n maxBytes?: number\n}\n\n/** A file address carries its mtime: a new version is a new address. */\nconst IMMUTABLE = 'private, max-age=31536000, immutable'\n\nconst notFound = (): Response => new Response(null, { status: 404 })\nconst tooLarge = (): Response => new Response(null, { status: 413 })\n\n/**\n * `bytes=a-b` within `size`, else `null` (the whole file).\n *\n * @param header - The request's `Range` header.\n * @param size - The file's size.\n */\nexport function parseRange(header: string | null, size: number): { start: number, end: number } | null {\n const m = header ? /^bytes=(\\d*)-(\\d*)$/.exec(header.trim()) : null\n if (!m || (m[1] === '' && m[2] === ''))\n return null\n let start: number\n let end: number\n if (m[1] === '') {\n // `bytes=-n`: the last n bytes.\n start = Math.max(0, size - Number(m[2]))\n end = size - 1\n }\n else {\n start = Number(m[1])\n end = m[2] === '' ? size - 1 : Math.min(Number(m[2]), size - 1)\n }\n return start <= end && start < size ? { start, end } : null\n}\n\n/** A well-formed range lying wholly past the end (or an empty suffix): 416, not the whole file. */\nfunction unsatisfiable(header: string, size: number): boolean {\n const m = /^bytes=(\\d*)-(\\d*)$/.exec(header.trim())\n if (!m)\n return false\n if (m[1] === '')\n return m[2] === '0'\n return Number(m[1]) >= size\n}\n\nasync function fileMedia(cwd: string, path: string, mime: string, range: string | null, cache: string, maxBytes: number): Promise<Response> {\n const real = await confineToWorkspace(cwd, path)\n if (!real)\n return notFound()\n const s = await stat(real)\n if (!s.isFile())\n return notFound()\n const span = parseRange(range, s.size)\n if (!span && range && unsatisfiable(range, s.size))\n return new Response(null, { status: 416, headers: { 'content-range': `bytes */${s.size}` } })\n if (!span && s.size > maxBytes)\n return tooLarge()\n const start = span?.start ?? 0\n const end = span ? Math.min(span.end, start + maxBytes - 1) : s.size - 1\n // The same stream at runtime; `node:stream/web`'s typing and the DOM's just don't overlap.\n const body = s.size === 0 ? null : Readable.toWeb(createReadStream(real, { start, end })) as unknown as ReadableStream\n return new Response(body, {\n status: span ? 206 : 200,\n headers: {\n 'content-type': mime,\n 'accept-ranges': 'bytes',\n 'content-length': String(s.size === 0 ? 0 : end - start + 1),\n ...(span ? { 'content-range': `bytes ${start}-${end}/${s.size}` } : {}),\n 'cache-control': cache,\n },\n })\n}\n\n/** Run git in `cwd`, its stdout as bytes; `null` when it fails. */\nasync function gitBytes(cwd: string, args: string[]): Promise<Buffer | null> {\n const child = spawn('git', args, { cwd, stdio: ['ignore', 'pipe', 'ignore'] })\n const chunks: Buffer[] = []\n const closed = new Promise<number | null>((done) => {\n child.once('close', done)\n child.once('error', () => done(null))\n })\n for await (const chunk of child.stdout)\n chunks.push(chunk as Buffer)\n return (await closed) === 0 ? Buffer.concat(chunks) : null\n}\n\nasync function diffMedia(cwd: string, path: string, mime: string, side: 'old' | 'new', range: string | null, maxBytes: number): Promise<Response> {\n const at = await confineToWorkspace(cwd, '.')\n if (!at || path.startsWith('-') || path.startsWith('/') || path.split('/').includes('..'))\n return notFound()\n const top = (await gitBytes(at, ['rev-parse', '--show-toplevel']))?.toString('utf8').trim()\n if (!top)\n return notFound()\n // Either side may change at any time: revalidated on every show.\n if (side === 'new')\n return fileMedia(top, path, mime, range, 'no-cache', maxBytes)\n // The old side is read whole: its size first.\n const size = Number((await gitBytes(top, ['cat-file', '-s', `HEAD:${path}`]))?.toString('utf8').trim())\n if (!Number.isFinite(size))\n return notFound()\n if (size > maxBytes)\n return tooLarge()\n const bytes = await gitBytes(top, ['show', `HEAD:${path}`])\n return bytes\n ? new Response(new Uint8Array(bytes), { headers: { 'content-type': mime, 'cache-control': 'no-cache' } })\n : notFound()\n}\n\n/**\n * The response for one media address: its bytes, a range of them (206), or\n * 404 (not media, not found, outside the folder), 413 (over `maxBytes`), 416\n * (a range past the end).\n *\n * @param request - The folder, the path and the side.\n * @param range - The request's `Range` header.\n * @param options - Options.\n */\nexport async function serveWorkspaceMedia(request: WorkspaceMediaRequest, range: string | null, options: WorkspaceMediaOptions = {}): Promise<Response> {\n const type = mediaTypeOfPath(request.path)\n if (!type)\n return notFound()\n const maxBytes = options.maxBytes ?? Infinity\n return request.side\n ? diffMedia(request.cwd, request.path, type.mime, request.side, range, maxBytes)\n : fileMedia(request.cwd, request.path, type.mime, range, IMMUTABLE, maxBytes)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4GA,MAAM,eAAe;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CrB,eAAsB,iBAAiB,SAAmE;CACxG,MAAM,MAAM,QAAQ,UAAU,QAAQ;CACtC,MAAM,MAAM,QAAQ,UAAU,QAAQ;CACtC,MAAM,IAAI,SAAS,GAAG;CACtB,MAAM,IAAI,SAAS,GAAG;CACtB,MAAM,SAAS,UAAU,QAAQ,IAAI;CACrC,IAAI,OAAO,SAAS,SAAS;EAC3B,IAAI,MAAM,GAAG,EA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;CAClB,MAAM,OAAO,MAAM,SAAS,IAAI,CAAC,aAAa,iBAAiB,CAAC,EAAA,EAAI,SAAS,MAAM,CAAC,CAAC,KAAK;CAC1F,IAAI,CAAC,KACH,OAAO,SAAS;CAElB,IAAI,SAAS,OACX,OAAO,UAAU,KAAK,MAAM,MAAM,OAAO,YAAY,QAAQ;CAE/D,MAAM,OAAO,QAAQ,MAAM,SAAS,KAAK;EAAC;EAAY;EAAM,QAAQ;CAAM,CAAC,EAAA,EAAI,SAAS,MAAM,CAAC,CAAC,KAAK,CAAC;CACtG,IAAI,CAAC,OAAO,SAAS,IAAI,GACvB,OAAO,SAAS;CAClB,IAAI,OAAO,UACT,OAAO,SAAS;CAClB,MAAM,QAAQ,MAAM,SAAS,KAAK,CAAC,QAAQ,QAAQ,MAAM,CAAC;CAC1D,OAAO,QACH,IAAI,SAAS,IAAI,WAAW,KAAK,GAAG,EAAE,SAAS;EAAE,gBAAgB;EAAM,iBAAiB;CAAW,EAAE,CAAC,IACtG,SAAS;AACf;;;;;;;;;;AAWA,eAAsB,oBAAoB,SAAgC,OAAsB,UAAiC,CAAC,GAAsB;CACtJ,MAAM,OAAO,gBAAgB,QAAQ,IAAI;CACzC,IAAI,CAAC,MACH,OAAO,SAAS;CAClB,MAAM,WAAW,QAAQ,YAAY;CACrC,OAAO,QAAQ,OACX,UAAU,QAAQ,KAAK,QAAQ,MAAM,KAAK,MAAM,QAAQ,MAAM,OAAO,QAAQ,IAC7E,UAAU,QAAQ,KAAK,QAAQ,MAAM,KAAK,MAAM,OAAO,WAAW,QAAQ;AAChF"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { t as createProcessContext } from "./contexts-
|
|
1
|
+
import { t as createProcessContext } from "./contexts-DLZTSRHU.js";
|
|
2
2
|
import { createSandboxContext } from "./contexts/sandbox.js";
|
|
3
3
|
import { p as oauthAccountLabel, r as API_KEY_ACCOUNT_LABEL } from "./cred-keys-C0KaSRp7.js";
|
|
4
|
-
import { D as credKeyOf, d as readCredentials, x as storedCredentialsOf } from "./credentials-
|
|
5
|
-
import { i as integrationCredentialKey, r as fromEntries } from "./auth-store-port-
|
|
4
|
+
import { D as credKeyOf, d as readCredentials, x as storedCredentialsOf } from "./credentials-Bqg-qNBM.js";
|
|
5
|
+
import { i as integrationCredentialKey, r as fromEntries } from "./auth-store-port-BKpjlJ8a.js";
|
|
6
6
|
import { t as createDaytonaProvider } from "./daytona-CgC8wQzg.js";
|
|
7
7
|
import { n as hostWorkspaceMounts, t as createDockerContext } from "./docker-D3CARts8.js";
|
|
8
8
|
import { t as createE2BProvider } from "./e2b-4ByYdO1e.js";
|
|
@@ -256,4 +256,4 @@ function isRemoteSandboxContext(type) {
|
|
|
256
256
|
//#endregion
|
|
257
257
|
export { integrationCredentialsOf as a, detectAuth as i, isRemoteSandboxContext as n, isIntegrationCredentialKey as o, activeAccountOf as r, createCliExecution as t };
|
|
258
258
|
|
|
259
|
-
//# sourceMappingURL=cli-shared-
|
|
259
|
+
//# sourceMappingURL=cli-shared-DeRHgYvl.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli-shared-CabruH8Z.js","names":[],"sources":["../src/chat/providers-integration.ts","../src/chat/auth.ts","../src/cli-shared.ts"],"sourcesContent":["/**\n * Providers that sign in through an integration (`ProviderDescriptor.integration`):\n * their connections, read from the integration's entry in `credentials.json`\n * and shaped like provider credentials, for the code that asks \"is this\n * provider signed in, and as whom\" (`detectAuth`) and the usage probes.\n *\n * Read from the file, not from a registry: pickers and probes run in every\n * host and process, with or without the extension runtime that registered\n * the integration, and the file is what every runtime writes.\n */\n\nimport type { CredentialsFile, ProviderCredential } from './credentials'\nimport { fromEntries, integrationCredentialKey } from '../extensions/integrations/auth-store-port'\n\n/** One connection of a provider's integration, as a provider credential. */\nexport interface IntegrationProviderCredential {\n /** Identity of the connection for lists and caches (`integration:<id>@<account>`); not a credentials-file key. */\n key: string\n /** The connection's credential: an OAuth grant (its extras spread in), or an API key / token as `apikey`. `id` is the account. */\n credential: ProviderCredential\n /** The integration's default connection. */\n active: boolean\n /** The connection's account (its stable id). */\n account: string\n /** What to show for it. */\n label: string\n}\n\n/**\n * The connections of `integrationId` in a read credentials file, the default first.\n *\n * @param all - The parsed credentials file.\n * @param integrationId - The integration the provider signs in with.\n */\nexport function integrationCredentialsOf(all: CredentialsFile, integrationId: string): IntegrationProviderCredential[] {\n const fileKey = integrationCredentialKey(integrationId)\n const entry = all[fileKey]\n const stored = entry ? fromEntries(integrationId, entry) ?? [] : []\n return stored.map(({ connection, credential, refreshToken }, i) => {\n const label = connection.label ?? connection.account\n const asProvider: ProviderCredential = credential.type === 'oauth'\n ? {\n ...credential.extra,\n kind: 'oauth',\n access: credential.accessToken,\n ...(refreshToken ? { refresh: refreshToken } : {}),\n ...(credential.expiresAt !== undefined ? { expires: credential.expiresAt } : {}),\n label,\n id: connection.account,\n }\n : { kind: 'apikey', value: credential.type === 'apiKey' ? credential.key : credential.token, id: connection.account }\n return { key: `${fileKey}@${connection.account}`, credential: asProvider, active: i === 0, account: connection.account, label }\n })\n}\n\n/**\n * Whether a usage credential key names an integration connection (whose\n * refresh only the integration's registry can run).\n *\n * @param key - A {@link IntegrationProviderCredential.key} or a credentials-file key.\n */\nexport function isIntegrationCredentialKey(key: string): boolean {\n return key.startsWith(integrationCredentialKey(''))\n}\n","import type { ProviderCredential } from './credentials'\nimport type { ProviderDescriptor } from './providers'\nimport { API_KEY_ACCOUNT_LABEL } from './cred-keys'\nimport { oauthAccountLabel, readCredentials, storedCredentialsOf } from './credentials'\nimport { credKeyOf } from './providers'\nimport { integrationCredentialsOf } from './providers-integration'\n\nexport { API_KEY_ACCOUNT_LABEL } from './cred-keys'\n\n/**\n * Provider identifier as known to the TUI. Built-in keys include `anthropic`,\n * `openai`, `openrouter` and `cerebras`, and hosts can register additional\n * keys via {@link ProviderDescriptor} — so the type is open.\n */\nexport type ProviderKey = string\n\n/** One credential source detected for a provider. */\nexport interface AuthMethod {\n /** Where the credential comes from: an environment variable, a stored OAuth grant, or a stored API key. */\n source: 'env' | 'oauth' | 'apikey'\n /**\n * Human-readable detail: the env var name, the credentials file, or an\n * OAuth grant's expiry. The OAuth account name is in `label`, not here.\n */\n detail: string\n /**\n * True for the credential every reader actually resolves.\n *\n * Exactly one STORED credential is active: the one in the canonical file key\n * (see `alternateCredKey`). A provider can hold an API key and any number of\n * OAuth accounts, so the list alone does not say which one wins. `env` is\n * never marked active — it is an observable signal, not a stored credential\n * the user can promote.\n *\n * Optional so hosts that build `ProviderAuth` themselves (this type is public\n * via `zidane/chat`) keep compiling; absent reads as \"not active\".\n * {@link detectAuth} always sets it.\n */\n active?: boolean\n /**\n * Credentials-file key of a STORED credential — the identity to hand to\n * `setPreferredCredential({ key })` / `removeStoredCredential`. Several OAuth\n * accounts share `source: 'oauth'`, so `source` alone does not select one.\n * Absent for `env`.\n */\n key?: string\n /**\n * Account name — always set for stored OAuth credentials: the user-given one,\n * or `DEFAULT_OAUTH_ACCOUNT_LABEL` when the grant was never named.\n */\n label?: string\n /**\n * Set for a connection of the provider's integration\n * (`ProviderDescriptor.integration`): sign it in, out or make it the\n * default through the integration, not the provider's credential slots\n * (such a method has no {@link key}). `id` is its account.\n */\n integration?: { id: string, account: string }\n /**\n * Stable id of a STORED credential (`ProviderCredential.id`): unlike\n * {@link key}, it does not move when another account is promoted. What a\n * session pinned to this account stores. Absent for `env`, and for an entry\n * written before ids until its next write.\n */\n id?: string\n}\n\n/** One stored credential of a provider that a session can run on (see {@link ProviderAuth.accounts}). */\nexport interface ProviderAccount {\n /** The credential's stable id: what a session pins (`metadata.account`). */\n id: string\n /** Display name: the OAuth account's label, or `API key`. */\n label: string\n /** Whether the account is an OAuth grant or an API key. */\n kind: 'oauth' | 'apikey'\n /** The provider's active credential (what an unpinned session runs on). */\n active: boolean\n}\n\n/** Authentication state of one provider, as listed by {@link detectAuth}. */\nexport interface ProviderAuth {\n /** Provider key. */\n key: ProviderKey\n /** Display name of the provider. */\n label: string\n /** True when at least one credential source is present. */\n available: boolean\n /** Credential sources currently present, stored credentials first. */\n methods: AuthMethod[]\n /**\n * The stored credentials a session can be pinned to, active first — set\n * only when there is a choice: the provider's factory takes an account\n * (`ProviderDescriptor.accounts`) and at least two are stored. Absent:\n * one account (or none), so pickers show the provider as before.\n */\n accounts?: ProviderAccount[]\n /**\n * Env var this provider reads, when it declares one.\n *\n * Carried separately from {@link methods} because the settings list shows the\n * env slot even when it holds nothing. `methods` only ever lists sources that\n * are actually present, since `available` is derived from it.\n */\n envKey?: string\n}\n\n/** The stored, id-carrying credentials among `methods`, as accounts (order kept: active first). */\nfunction accountsOf(methods: readonly AuthMethod[]): ProviderAccount[] {\n const out: ProviderAccount[] = []\n for (const method of methods) {\n if (!method.id || (method.source !== 'oauth' && method.source !== 'apikey'))\n continue\n out.push({\n id: method.id,\n label: method.source === 'oauth' ? (method.label ?? 'Default') : API_KEY_ACCOUNT_LABEL,\n kind: method.source,\n active: method.active === true,\n })\n }\n return out\n}\n\n/**\n * Detect available auth for every registered provider.\n *\n * A method appears in `methods` for every layer that has a credential:\n *\n * - `kind: 'apikey'` from `credentials.json` (injected into env at TUI launch)\n * - explicit env var (descriptor's `envKey`)\n * - `kind: 'oauth'` from `credentials.json` (migrated on first read from a\n * legacy `.credentials.json`, see `readCredentials`), one per stored account\n *\n * The preferred credential lives in the canonical file key and is flagged\n * {@link AuthMethod.active}; the others sit in sibling slots and are reported\n * too, keyed by {@link AuthMethod.key}, so the UI can offer to promote or\n * remove them. Order within `methods` is presentational — active first — not a\n * resolution order, because the active flag answers that directly.\n *\n * Never refreshes tokens or rewrites existing credentials. The one write is\n * the first-read migration of a legacy `.credentials.json` when\n * `credentials.json` does not exist yet (see `readCredentials`).\n *\n * @param dataDir - Directory holding `credentials.json`.\n * @param registry - Provider descriptors keyed by id.\n * @param env - Environment used to look for ambient credentials. Defaults to `process.env`.\n */\nexport function detectAuth(\n dataDir: string,\n registry: Readonly<Record<string, ProviderDescriptor>>,\n env: Record<string, string | undefined> = process.env,\n): ProviderAuth[] {\n const creds = readCredentials(dataDir)\n\n return Object.values(registry).map((descriptor) => {\n const methods: AuthMethod[] = []\n const stored = storedCredentialsOf(creds, credKeyOf(descriptor))\n const fileEntry = stored.find(s => s.active)?.credential\n\n // 1. Stored API key / OAuth accounts, active first. Every slot goes through\n // the same description so a parked credential renders identically to the\n // preferred one, differing only in `active`.\n const describeStored = (key: string, entry: ProviderCredential, active: boolean): AuthMethod | undefined => {\n const id = typeof entry.id === 'string' && entry.id ? { id: entry.id } : {}\n if (entry.kind === 'apikey' && entry.value)\n return { source: 'apikey', detail: 'credentials.json', active, key, ...id }\n if (entry.kind === 'oauth' && entry.access) {\n const label = oauthAccountLabel(entry)\n const expiry = typeof entry.expires === 'number'\n ? `expires ${new Date(entry.expires).toLocaleString()}`\n : 'credentials.json'\n return { source: 'oauth', detail: expiry, active, key, label, ...id }\n }\n return undefined\n }\n\n for (const slot of stored) {\n const method = describeStored(slot.key, slot.credential, slot.active)\n if (method)\n methods.push(method)\n }\n\n // 1a. Connections of the integration the provider signs in with. The\n // default is active unless a slot of the provider's own already is.\n if (descriptor.integration) {\n const ownActive = methods.some(m => m.active)\n for (const connection of integrationCredentialsOf(creds, descriptor.integration)) {\n const method = describeStored(connection.key, connection.credential, connection.active && !ownActive)\n if (!method)\n continue\n const { key: _key, ...rest } = method\n methods.push({ ...rest, label: connection.label, id: connection.account, integration: { id: descriptor.integration, account: connection.account } })\n }\n }\n\n // 1b. customFields-only credential (descriptor has no `envKey` and is\n // authenticated entirely by configuration — e.g. the `local` provider,\n // where the auth signal is the configured base URL). The credential\n // is \"present\" when every required field has a stored value.\n if (\n fileEntry?.kind === 'apikey'\n && !fileEntry.value\n && descriptor.customFields\n && descriptor.customFields.length > 0\n ) {\n const stored = fileEntry.customFields ?? {}\n const required = descriptor.customFields.filter(f => f.required)\n const allRequiredPresent = required.every(\n f => typeof stored[f.key] === 'string' && (stored[f.key] as string).length > 0,\n )\n if (allRequiredPresent) {\n methods.push({ source: 'apikey', detail: 'credentials.json (configured)', active: true })\n }\n }\n\n // 1c. Env-only custom field configuration. This lets local/OpenAI-compatible\n // endpoints participate in auth/model detection when configured through\n // `LOCAL_LLM_BASE_URL` without first writing credentials.json.\n if (descriptor.customFields && descriptor.customFields.length > 0) {\n const required = descriptor.customFields.filter(f => f.required)\n const allRequiredPresent = required.length > 0 && required.every(\n f => typeof env[f.envVar] === 'string' && (env[f.envVar] as string).length > 0,\n )\n\n if (allRequiredPresent) {\n methods.push({ source: 'env', detail: required.map(f => f.envVar).join(', '), active: false })\n }\n }\n\n // 2. Env var (may be set by `applyApiKeyEnv` from a stored key, or by the\n // user's shell. Either way, treated as the same observable signal.)\n if (descriptor.envKey && env[descriptor.envKey])\n methods.push({ source: 'env', detail: descriptor.envKey, active: false })\n\n // Selection identity is the file key for stored credentials and `source`\n // for everything else. Two API-key rows cannot be a choice the user can\n // express (there is one API key per provider) — a customFields-configured\n // credential sitting beside a stored one, or a stale duplicate from an\n // older build, collapses to the FIRST, which the order above makes the\n // active one. OAuth accounts are distinct by key and all survive.\n const unique: AuthMethod[] = []\n for (const method of methods) {\n const duplicate = unique.some(seen =>\n method.source === 'oauth'\n ? seen.key !== undefined && seen.key === method.key\n : seen.source === method.source,\n )\n if (!duplicate)\n unique.push(method)\n }\n\n const accounts = descriptor.accounts === true ? accountsOf(unique) : []\n return {\n key: descriptor.key,\n label: descriptor.label,\n available: unique.length > 0,\n methods: unique,\n ...(accounts.length >= 2 ? { accounts } : {}),\n ...(descriptor.envKey ? { envKey: descriptor.envKey } : {}),\n }\n })\n}\n\n/**\n * The id of the account a provider's unpinned sessions run on: its active\n * stored credential, or its integration's default connection. `undefined`\n * when it has no stored account (env only, or signed out).\n *\n * @param dataDir - Directory holding `credentials.json`.\n * @param descriptor - The provider.\n * @param env - Environment used to look for ambient credentials. Defaults to `process.env`.\n */\nexport function activeAccountOf(dataDir: string, descriptor: ProviderDescriptor, env: Record<string, string | undefined> = process.env): string | undefined {\n const [auth] = detectAuth(dataDir, { [descriptor.key]: descriptor }, env)\n return auth?.methods.find(method => method.active === true && method.id)?.id\n}\n","/**\n * Shared glue for the CLI entrypoints (`start.ts` — human renderer,\n * `headless-cli.ts` — machine contract). Both build an execution context,\n * resolve a session (memory or sqlite), and parse `--mcp` config the same way;\n * this module is the single source of truth for that wiring so the two CLIs\n * stay in lockstep without duplicating it.\n */\n\nimport type { ExecutionContext } from './contexts'\nimport type { DurabilityMode } from './durable/setting'\nimport type { DurableOptions, DurableRuntime } from './durable/types'\nimport type { Session } from './session'\nimport { createProcessContext, createSandboxContext } from './contexts'\nimport { createDaytonaProvider } from './contexts/daytona'\nimport { createDockerContext, hostWorkspaceMounts } from './contexts/docker'\nimport { createE2BProvider } from './contexts/e2b'\nimport { LEASE_STALE_MS } from './durable/lease'\nimport { DEFAULT_DURABILITY } from './durable/setting'\nimport { sqliteRuntimeForStore } from './durable/sqlite-runtime'\nimport { createMemoryStore, createSession, loadSession } from './session'\n\nexport { parseMcpConfig } from './start/shared-options'\n\n/**\n * Build the execution context for a CLI run: `process` (default), `docker`,\n * `e2b`, or `daytona`.\n *\n * The `e2b` backend reads its `E2B_API_KEY` / `E2B_DOMAIN` / `E2B_TEMPLATE`\n * from the environment (point `E2B_DOMAIN` at a self-hosted cluster, and set\n * `E2B_TEMPLATE` to a template that exists there — the default `base` does\n * not); `--cwd` becomes the sandbox working directory.\n *\n * The Daytona backend reads `DAYTONA_API_KEY` / `DAYTONA_API_URL` /\n * `DAYTONA_TARGET` from the environment. `--cwd` becomes the sandbox working\n * directory.\n *\n * Docker: when `--cwd` is an existing host directory, its git worktree (and\n * the git common dir, for linked worktrees) is bind-mounted at the same\n * absolute path (git hooks/config read-only); otherwise, or when that tree\n * is `/`, `$HOME`, or an ancestor of it, `--cwd` is a container-only path.\n *\n * `env` (from `--env` / `--pass-env`) is forwarded to whichever context is\n * selected: baked into remote sandboxes at create time, set on the Docker\n * container, or merged into the in-process command environment.\n *\n * `pregame` (from `--pregame`) is supported by the remote sandbox providers:\n * a setup script uploaded and run in the sandbox once it's ready, before\n * prompting begins.\n *\n * `sandboxId` (from `--sandbox`) attaches to a pre-existing remote sandbox\n * instead of creating a fresh one.\n */\nexport function createCliExecution(type: string, opts: { image?: string, cwd?: string, env?: Record<string, string>, pregame?: { name: string, content: string }, sandboxId?: string, sandboxOnDestroy?: 'kill' | 'pause' | 'leave' }): ExecutionContext {\n switch (type) {\n case 'docker': {\n // An existing host dir is bind-mounted at the same path so the agent\n // works on the real checkout; a container-only path mounts nothing.\n const mounts = opts.cwd ? hostWorkspaceMounts(opts.cwd) : []\n return createDockerContext({ image: opts.image, cwd: opts.cwd, env: opts.env, ...(mounts.length > 0 ? { mounts } : {}) })\n }\n case 'e2b':\n return createSandboxContext(createE2BProvider({ cwd: opts.cwd, env: opts.env, ...(opts.pregame ? { pregame: opts.pregame } : {}), ...(opts.sandboxId ? { sandboxId: opts.sandboxId } : {}), ...(opts.sandboxOnDestroy ? { onDestroy: opts.sandboxOnDestroy } : {}) }))\n case 'daytona':\n return createSandboxContext(createDaytonaProvider({ cwd: opts.cwd, env: opts.env, ...(opts.pregame ? { pregame: opts.pregame } : {}), ...(opts.sandboxId ? { sandboxId: opts.sandboxId } : {}), ...(opts.sandboxOnDestroy ? { onDestroy: opts.sandboxOnDestroy } : {}) }))\n case 'process':\n default:\n return createProcessContext({ cwd: opts.cwd, env: opts.env })\n }\n}\n\n/**\n * Contexts whose filesystem is a remote sandbox: host paths don't exist\n * there, so host-derived cwds must not be forwarded.\n */\nexport function isRemoteSandboxContext(type: string): boolean {\n return type === 'e2b' || type === 'daytona'\n}\n\n/** The session of a CLI run, with what durability gives it. */\nexport interface CliSession {\n session: Session\n /**\n * `createAgent`'s `durable`: the SQLite runtime the session is stored on,\n * unless `durability` is `off` or the session lives in memory. `on`\n * resumes an interrupted run before a run; `resume-ask` heals it.\n */\n durable?: DurableOptions\n /** A checkpoint run a dead process left in the session, to continue (`agent.resume`) before the prompt. */\n resumeRunId?: string\n}\n\n/**\n * Resolve the session for a CLI run.\n * - `sessionDb` set → sqlite-backed; resume `sessionId` if it exists, else\n * create it (or a fresh id when `sessionId` is omitted).\n * - `sessionDb` absent → in-memory store (no durability).\n *\n * Fresh sessions are saved immediately so the store has a header row from\n * the start — incremental `appendTurns` against a header-less sqlite store\n * would otherwise be silent no-ops, and an error / Ctrl+C before the final\n * save would lose the whole run.\n *\n * Durability (`Settings.durability`, default `resume-ask`): unless `off`,\n * runs keep checkpoints on the session's SQLite file. An existing session\n * whose last run a dead process left is resumed (`on`), or resumed when\n * `ask` says so (`resume-ask`; without `ask`, nobody to ask, it is\n * not); otherwise its interrupted tool calls are healed\n * (`healInterruptedToolCalls`).\n * @param sessionDb - SQLite sessions file.\n * @param sessionId - Session to resume or create.\n * @param options - Durability of the run, and how to ask before resuming.\n * @param options.durability - `on`, `resume-ask` or `off`.\n * @param options.ask - Ask the user whether to resume an interrupted run.\n */\nexport async function createCliSession(sessionDb?: string, sessionId?: string, options: { durability?: DurabilityMode, ask?: () => Promise<boolean> } = {}): Promise<CliSession> {\n if (sessionDb) {\n const { createSqliteStore } = await import('./session/sqlite')\n const store = createSqliteStore({ path: sessionDb })\n const durability = options.durability ?? DEFAULT_DURABILITY\n const durable = durability === 'off' ? undefined : sqliteRuntimeForStore(store)\n const withDurable = (session: Session, resumeRunId?: string): CliSession => ({\n session,\n ...(durable ? { durable: { runtime: durable, onInterrupted: durability === 'on' ? 'resume' : 'heal' } } : {}),\n ...(resumeRunId !== undefined ? { resumeRunId } : {}),\n })\n if (sessionId) {\n const existing = await loadSession(store, sessionId)\n if (existing) {\n const resumeRunId = durable ? await interruptedRun(durable, sessionId, durability, options.ask) : undefined\n // No run claim on this path: resolving the session IS the run start,\n // so heal here (see `healInterruptedToolCalls`). A resumed run\n // dispatches its pending calls itself.\n if (resumeRunId === undefined)\n await existing.healInterruptedToolCalls()\n return withDurable(existing, resumeRunId)\n }\n const session = await createSession({ store, id: sessionId })\n await session.save()\n return withDurable(session)\n }\n const session = await createSession({ store })\n await session.save()\n return withDurable(session)\n }\n return { session: await createSession({ store: createMemoryStore() }) }\n}\n\n/** The run of `sessionId` a dead process left, when the durability says to resume it. */\nasync function interruptedRun(durable: DurableRuntime, sessionId: string, durability: DurabilityMode, ask: (() => Promise<boolean>) | undefined): Promise<string | undefined> {\n const pending = (await durable.lease?.resumable({ staleAt: Date.now() - LEASE_STALE_MS }) ?? []).filter(run => run.sessionId === sessionId).at(-1)\n if (!pending)\n return undefined\n if (durability === 'on' || (durability === 'resume-ask' && await ask?.()))\n return pending.runId\n return undefined\n}\n\n/**\n * Install SIGINT/SIGTERM handlers for a CLI run. The first signal aborts the\n * returned `AbortSignal` so the running agent can unwind cleanly (persist the\n * session, destroy execution contexts) and the process exits through the\n * normal path — which is what fires the `process.on('exit')` orphan reaper\n * for detached background process groups. A second signal force-exits\n * immediately (the synchronous 'exit' reaper still runs, but async cleanup\n * such as Docker container teardown is skipped).\n */\nexport function installCliSignalHandlers(): AbortSignal {\n const controller = new AbortController()\n const onSignal = (name: NodeJS.Signals): void => {\n if (controller.signal.aborted)\n process.exit(name === 'SIGTERM' ? 143 : 130) // 128 + signal number\n controller.abort(new Error(`Received ${name}, stopping the run`))\n }\n process.on('SIGINT', () => onSignal('SIGINT'))\n process.on('SIGTERM', () => onSignal('SIGTERM'))\n return controller.signal\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkCA,SAAgB,yBAAyB,KAAsB,eAAwD;CACrH,MAAM,UAAU,yBAAyB,aAAa;CACtD,MAAM,QAAQ,IAAI;CAElB,QADe,QAAQ,YAAY,eAAe,KAAK,KAAK,CAAC,IAAI,CAAC,EAAA,CACpD,KAAK,EAAE,YAAY,YAAY,gBAAgB,MAAM;EACjE,MAAM,QAAQ,WAAW,SAAS,WAAW;EAC7C,MAAM,aAAiC,WAAW,SAAS,UACvD;GACE,GAAG,WAAW;GACd,MAAM;GACN,QAAQ,WAAW;GACnB,GAAI,eAAe,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M;CACvP,QAAQ,MAAR;EACE,KAAK,UAAU;GAGb,MAAM,SAAS,KAAK,MAAM,oBAAoB,KAAK,GAAG,IAAI,CAAC;GAC3D,OAAO,oBAAoB;IAAE,OAAO,KAAK;IAAO,KAAK,KAAK;IAAK,KAAK,KAAK;IAAK,GAAI,OAAO,SAAS,IAAI,EAAE,OAAO,IAAI,CAAC;GAAG,CAAC;EAC1H;EACA,KAAK,OACH,OAAO,qBAAqB,kBAAkB;GAAE,KAAK,KAAK;GAAK,KAAK,KAAK;GAAK,GAAI,KAAK,UAAU,EAAE,SAAS,KAAK,QAAQ,IAAI,CAAC;GAAI,GAAI,KAAK,YAAY,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;GAAI,GAAI,KAAK,mBAAmB,EAAE,WAAW,KAAK,iBAAiB,IAAI,CAAC;EAAG,CAAC,CAAC;EACvQ,KAAK,WACH,OAAO,qBAAqB,sBAAsB;GAAE,KAAK,KAAK;GAAK,KAAK,KAAK;GAAK,GAAI,KAAK,UAAU,EAAE,SAAS,KAAK,QAAQ,IAAI,CAAC;GAAI,GAAI,KAAK,YAAY,EAAE,WAAW,KAAK,UAAU,IAAI,CAAC;GAAI,GAAI,KAAK,mBAAmB,EAAE,WAAW,KAAK,iBAAiB,IAAI,CAAC;EAAG,CAAC,CAAC;EAE3Q,SACE,OAAO,qBAAqB;GAAE,KAAK,KAAK;GAAK,KAAK,KAAK;EAAI,CAAC;CAChE;AACF;;;;;AAMA,SAAgB,uBAAuB,MAAuB;CAC5D,OAAO,SAAS,SAAS,SAAS;AACpC"}
|
|
1
|
+
{"version":3,"file":"cli-shared-DeRHgYvl.js","names":[],"sources":["../src/chat/providers-integration.ts","../src/chat/auth.ts","../src/cli-shared.ts"],"sourcesContent":["/**\n * Providers that sign in through an integration (`ProviderDescriptor.integration`):\n * their connections, read from the integration's entry in `credentials.json`\n * and shaped like provider credentials, for the code that asks \"is this\n * provider signed in, and as whom\" (`detectAuth`) and the usage probes.\n *\n * Read from the file, not from a registry: pickers and probes run in every\n * host and process, with or without the extension runtime that registered\n * the integration, and the file is what every runtime writes.\n */\n\nimport type { CredentialsFile, ProviderCredential } from './credentials'\nimport { fromEntries, integrationCredentialKey } from '../extensions/integrations/auth-store-port'\n\n/** One connection of a provider's integration, as a provider credential. */\nexport interface IntegrationProviderCredential {\n /** Identity of the connection for lists and caches (`integration:<id>@<account>`); not a credentials-file key. */\n key: string\n /** The connection's credential: an OAuth grant (its extras spread in), or an API key / token as `apikey`. `id` is the account. */\n credential: ProviderCredential\n /** The integration's default connection. */\n active: boolean\n /** The connection's account (its stable id). */\n account: string\n /** What to show for it. */\n label: string\n}\n\n/**\n * The connections of `integrationId` in a read credentials file, the default first.\n *\n * @param all - The parsed credentials file.\n * @param integrationId - The integration the provider signs in with.\n */\nexport function integrationCredentialsOf(all: CredentialsFile, integrationId: string): IntegrationProviderCredential[] {\n const fileKey = integrationCredentialKey(integrationId)\n const entry = all[fileKey]\n const stored = entry ? fromEntries(integrationId, entry) ?? [] : []\n return stored.map(({ connection, credential, refreshToken }, i) => {\n const label = connection.label ?? connection.account\n const asProvider: ProviderCredential = credential.type === 'oauth'\n ? {\n ...credential.extra,\n kind: 'oauth',\n access: credential.accessToken,\n ...(refreshToken ? { refresh: refreshToken } : {}),\n ...(credential.expiresAt !== undefined ? { expires: credential.expiresAt } : {}),\n label,\n id: connection.account,\n }\n : { kind: 'apikey', value: credential.type === 'apiKey' ? credential.key : credential.token, id: connection.account }\n return { key: `${fileKey}@${connection.account}`, credential: asProvider, active: i === 0, account: connection.account, label }\n })\n}\n\n/**\n * Whether a usage credential key names an integration connection (whose\n * refresh only the integration's registry can run).\n *\n * @param key - A {@link IntegrationProviderCredential.key} or a credentials-file key.\n */\nexport function isIntegrationCredentialKey(key: string): boolean {\n return key.startsWith(integrationCredentialKey(''))\n}\n","import type { ProviderCredential } from './credentials'\nimport type { ProviderDescriptor } from './providers'\nimport { API_KEY_ACCOUNT_LABEL } from './cred-keys'\nimport { oauthAccountLabel, readCredentials, storedCredentialsOf } from './credentials'\nimport { credKeyOf } from './providers'\nimport { integrationCredentialsOf } from './providers-integration'\n\nexport { API_KEY_ACCOUNT_LABEL } from './cred-keys'\n\n/**\n * Provider identifier as known to the TUI. Built-in keys include `anthropic`,\n * `openai`, `openrouter` and `cerebras`, and hosts can register additional\n * keys via {@link ProviderDescriptor} — so the type is open.\n */\nexport type ProviderKey = string\n\n/** One credential source detected for a provider. */\nexport interface AuthMethod {\n /** Where the credential comes from: an environment variable, a stored OAuth grant, or a stored API key. */\n source: 'env' | 'oauth' | 'apikey'\n /**\n * Human-readable detail: the env var name, the credentials file, or an\n * OAuth grant's expiry. The OAuth account name is in `label`, not here.\n */\n detail: string\n /**\n * True for the credential every reader actually resolves.\n *\n * Exactly one STORED credential is active: the one in the canonical file key\n * (see `alternateCredKey`). A provider can hold an API key and any number of\n * OAuth accounts, so the list alone does not say which one wins. `env` is\n * never marked active — it is an observable signal, not a stored credential\n * the user can promote.\n *\n * Optional so hosts that build `ProviderAuth` themselves (this type is public\n * via `zidane/chat`) keep compiling; absent reads as \"not active\".\n * {@link detectAuth} always sets it.\n */\n active?: boolean\n /**\n * Credentials-file key of a STORED credential — the identity to hand to\n * `setPreferredCredential({ key })` / `removeStoredCredential`. Several OAuth\n * accounts share `source: 'oauth'`, so `source` alone does not select one.\n * Absent for `env`.\n */\n key?: string\n /**\n * Account name — always set for stored OAuth credentials: the user-given one,\n * or `DEFAULT_OAUTH_ACCOUNT_LABEL` when the grant was never named.\n */\n label?: string\n /**\n * Set for a connection of the provider's integration\n * (`ProviderDescriptor.integration`): sign it in, out or make it the\n * default through the integration, not the provider's credential slots\n * (such a method has no {@link key}). `id` is its account.\n */\n integration?: { id: string, account: string }\n /**\n * Stable id of a STORED credential (`ProviderCredential.id`): unlike\n * {@link key}, it does not move when another account is promoted. What a\n * session pinned to this account stores. Absent for `env`, and for an entry\n * written before ids until its next write.\n */\n id?: string\n}\n\n/** One stored credential of a provider that a session can run on (see {@link ProviderAuth.accounts}). */\nexport interface ProviderAccount {\n /** The credential's stable id: what a session pins (`metadata.account`). */\n id: string\n /** Display name: the OAuth account's label, or `API key`. */\n label: string\n /** Whether the account is an OAuth grant or an API key. */\n kind: 'oauth' | 'apikey'\n /** The provider's active credential (what an unpinned session runs on). */\n active: boolean\n}\n\n/** Authentication state of one provider, as listed by {@link detectAuth}. */\nexport interface ProviderAuth {\n /** Provider key. */\n key: ProviderKey\n /** Display name of the provider. */\n label: string\n /** True when at least one credential source is present. */\n available: boolean\n /** Credential sources currently present, stored credentials first. */\n methods: AuthMethod[]\n /**\n * The stored credentials a session can be pinned to, active first — set\n * only when there is a choice: the provider's factory takes an account\n * (`ProviderDescriptor.accounts`) and at least two are stored. Absent:\n * one account (or none), so pickers show the provider as before.\n */\n accounts?: ProviderAccount[]\n /**\n * Env var this provider reads, when it declares one.\n *\n * Carried separately from {@link methods} because the settings list shows the\n * env slot even when it holds nothing. `methods` only ever lists sources that\n * are actually present, since `available` is derived from it.\n */\n envKey?: string\n}\n\n/** The stored, id-carrying credentials among `methods`, as accounts (order kept: active first). */\nfunction accountsOf(methods: readonly AuthMethod[]): ProviderAccount[] {\n const out: ProviderAccount[] = []\n for (const method of methods) {\n if (!method.id || (method.source !== 'oauth' && method.source !== 'apikey'))\n continue\n out.push({\n id: method.id,\n label: method.source === 'oauth' ? (method.label ?? 'Default') : API_KEY_ACCOUNT_LABEL,\n kind: method.source,\n active: method.active === true,\n })\n }\n return out\n}\n\n/**\n * Detect available auth for every registered provider.\n *\n * A method appears in `methods` for every layer that has a credential:\n *\n * - `kind: 'apikey'` from `credentials.json` (injected into env at TUI launch)\n * - explicit env var (descriptor's `envKey`)\n * - `kind: 'oauth'` from `credentials.json` (migrated on first read from a\n * legacy `.credentials.json`, see `readCredentials`), one per stored account\n *\n * The preferred credential lives in the canonical file key and is flagged\n * {@link AuthMethod.active}; the others sit in sibling slots and are reported\n * too, keyed by {@link AuthMethod.key}, so the UI can offer to promote or\n * remove them. Order within `methods` is presentational — active first — not a\n * resolution order, because the active flag answers that directly.\n *\n * Never refreshes tokens or rewrites existing credentials. The one write is\n * the first-read migration of a legacy `.credentials.json` when\n * `credentials.json` does not exist yet (see `readCredentials`).\n *\n * @param dataDir - Directory holding `credentials.json`.\n * @param registry - Provider descriptors keyed by id.\n * @param env - Environment used to look for ambient credentials. Defaults to `process.env`.\n */\nexport function detectAuth(\n dataDir: string,\n registry: Readonly<Record<string, ProviderDescriptor>>,\n env: Record<string, string | undefined> = process.env,\n): ProviderAuth[] {\n const creds = readCredentials(dataDir)\n\n return Object.values(registry).map((descriptor) => {\n const methods: AuthMethod[] = []\n const stored = storedCredentialsOf(creds, credKeyOf(descriptor))\n const fileEntry = stored.find(s => s.active)?.credential\n\n // 1. Stored API key / OAuth accounts, active first. Every slot goes through\n // the same description so a parked credential renders identically to the\n // preferred one, differing only in `active`.\n const describeStored = (key: string, entry: ProviderCredential, active: boolean): AuthMethod | undefined => {\n const id = typeof entry.id === 'string' && entry.id ? { id: entry.id } : {}\n if (entry.kind === 'apikey' && entry.value)\n return { source: 'apikey', detail: 'credentials.json', active, key, ...id }\n if (entry.kind === 'oauth' && entry.access) {\n const label = oauthAccountLabel(entry)\n const expiry = typeof entry.expires === 'number'\n ? `expires ${new Date(entry.expires).toLocaleString()}`\n : 'credentials.json'\n return { source: 'oauth', detail: expiry, active, key, label, ...id }\n }\n return undefined\n }\n\n for (const slot of stored) {\n const method = describeStored(slot.key, slot.credential, slot.active)\n if (method)\n methods.push(method)\n }\n\n // 1a. Connections of the integration the provider signs in with. The\n // default is active unless a slot of the provider's own already is.\n if (descriptor.integration) {\n const ownActive = methods.some(m => m.active)\n for (const connection of integrationCredentialsOf(creds, descriptor.integration)) {\n const method = describeStored(connection.key, connection.credential, connection.active && !ownActive)\n if (!method)\n continue\n const { key: _key, ...rest } = method\n methods.push({ ...rest, label: connection.label, id: connection.account, integration: { id: descriptor.integration, account: connection.account } })\n }\n }\n\n // 1b. customFields-only credential (descriptor has no `envKey` and is\n // authenticated entirely by configuration — e.g. the `local` provider,\n // where the auth signal is the configured base URL). The credential\n // is \"present\" when every required field has a stored value.\n if (\n fileEntry?.kind === 'apikey'\n && !fileEntry.value\n && descriptor.customFields\n && descriptor.customFields.length > 0\n ) {\n const stored = fileEntry.customFields ?? {}\n const required = descriptor.customFields.filter(f => f.required)\n const allRequiredPresent = required.every(\n f => typeof stored[f.key] === 'string' && (stored[f.key] as string).length > 0,\n )\n if (allRequiredPresent) {\n methods.push({ source: 'apikey', detail: 'credentials.json (configured)', active: true })\n }\n }\n\n // 1c. Env-only custom field configuration. This lets local/OpenAI-compatible\n // endpoints participate in auth/model detection when configured through\n // `LOCAL_LLM_BASE_URL` without first writing credentials.json.\n if (descriptor.customFields && descriptor.customFields.length > 0) {\n const required = descriptor.customFields.filter(f => f.required)\n const allRequiredPresent = required.length > 0 && required.every(\n f => typeof env[f.envVar] === 'string' && (env[f.envVar] as string).length > 0,\n )\n\n if (allRequiredPresent) {\n methods.push({ source: 'env', detail: required.map(f => f.envVar).join(', '), active: false })\n }\n }\n\n // 2. Env var (may be set by `applyApiKeyEnv` from a stored key, or by the\n // user's shell. Either way, treated as the same observable signal.)\n if (descriptor.envKey && env[descriptor.envKey])\n methods.push({ source: 'env', detail: descriptor.envKey, active: false })\n\n // Selection identity is the file key for stored credentials and `source`\n // for everything else. Two API-key rows cannot be a choice the user can\n // express (there is one API key per provider) — a customFields-configured\n // credential sitting beside a stored one, or a stale duplicate from an\n // older build, collapses to the FIRST, which the order above makes the\n // active one. OAuth accounts are distinct by key and all survive.\n const unique: AuthMethod[] = []\n for (const method of methods) {\n const duplicate = unique.some(seen =>\n method.source === 'oauth'\n ? seen.key !== undefined && seen.key === method.key\n : seen.source === method.source,\n )\n if (!duplicate)\n unique.push(method)\n }\n\n const accounts = descriptor.accounts === true ? accountsOf(unique) : []\n return {\n key: descriptor.key,\n label: descriptor.label,\n available: unique.length > 0,\n methods: unique,\n ...(accounts.length >= 2 ? { accounts } : {}),\n ...(descriptor.envKey ? { envKey: descriptor.envKey } : {}),\n }\n })\n}\n\n/**\n * The id of the account a provider's unpinned sessions run on: its active\n * stored credential, or its integration's default connection. `undefined`\n * when it has no stored account (env only, or signed out).\n *\n * @param dataDir - Directory holding `credentials.json`.\n * @param descriptor - The provider.\n * @param env - Environment used to look for ambient credentials. Defaults to `process.env`.\n */\nexport function activeAccountOf(dataDir: string, descriptor: ProviderDescriptor, env: Record<string, string | undefined> = process.env): string | undefined {\n const [auth] = detectAuth(dataDir, { [descriptor.key]: descriptor }, env)\n return auth?.methods.find(method => method.active === true && method.id)?.id\n}\n","/**\n * Shared glue for the CLI entrypoints (`start.ts` — human renderer,\n * `headless-cli.ts` — machine contract). Both build an execution context,\n * resolve a session (memory or sqlite), and parse `--mcp` config the same way;\n * this module is the single source of truth for that wiring so the two CLIs\n * stay in lockstep without duplicating it.\n */\n\nimport type { ExecutionContext } from './contexts'\nimport type { DurabilityMode } from './durable/setting'\nimport type { DurableOptions, DurableRuntime } from './durable/types'\nimport type { Session } from './session'\nimport { createProcessContext, createSandboxContext } from './contexts'\nimport { createDaytonaProvider } from './contexts/daytona'\nimport { createDockerContext, hostWorkspaceMounts } from './contexts/docker'\nimport { createE2BProvider } from './contexts/e2b'\nimport { LEASE_STALE_MS } from './durable/lease'\nimport { DEFAULT_DURABILITY } from './durable/setting'\nimport { sqliteRuntimeForStore } from './durable/sqlite-runtime'\nimport { createMemoryStore, createSession, loadSession } from './session'\n\nexport { parseMcpConfig } from './start/shared-options'\n\n/**\n * Build the execution context for a CLI run: `process` (default), `docker`,\n * `e2b`, or `daytona`.\n *\n * The `e2b` backend reads its `E2B_API_KEY` / `E2B_DOMAIN` / `E2B_TEMPLATE`\n * from the environment (point `E2B_DOMAIN` at a self-hosted cluster, and set\n * `E2B_TEMPLATE` to a template that exists there — the default `base` does\n * not); `--cwd` becomes the sandbox working directory.\n *\n * The Daytona backend reads `DAYTONA_API_KEY` / `DAYTONA_API_URL` /\n * `DAYTONA_TARGET` from the environment. `--cwd` becomes the sandbox working\n * directory.\n *\n * Docker: when `--cwd` is an existing host directory, its git worktree (and\n * the git common dir, for linked worktrees) is bind-mounted at the same\n * absolute path (git hooks/config read-only); otherwise, or when that tree\n * is `/`, `$HOME`, or an ancestor of it, `--cwd` is a container-only path.\n *\n * `env` (from `--env` / `--pass-env`) is forwarded to whichever context is\n * selected: baked into remote sandboxes at create time, set on the Docker\n * container, or merged into the in-process command environment.\n *\n * `pregame` (from `--pregame`) is supported by the remote sandbox providers:\n * a setup script uploaded and run in the sandbox once it's ready, before\n * prompting begins.\n *\n * `sandboxId` (from `--sandbox`) attaches to a pre-existing remote sandbox\n * instead of creating a fresh one.\n */\nexport function createCliExecution(type: string, opts: { image?: string, cwd?: string, env?: Record<string, string>, pregame?: { name: string, content: string }, sandboxId?: string, sandboxOnDestroy?: 'kill' | 'pause' | 'leave' }): ExecutionContext {\n switch (type) {\n case 'docker': {\n // An existing host dir is bind-mounted at the same path so the agent\n // works on the real checkout; a container-only path mounts nothing.\n const mounts = opts.cwd ? hostWorkspaceMounts(opts.cwd) : []\n return createDockerContext({ image: opts.image, cwd: opts.cwd, env: opts.env, ...(mounts.length > 0 ? { mounts } : {}) })\n }\n case 'e2b':\n return createSandboxContext(createE2BProvider({ cwd: opts.cwd, env: opts.env, ...(opts.pregame ? { pregame: opts.pregame } : {}), ...(opts.sandboxId ? { sandboxId: opts.sandboxId } : {}), ...(opts.sandboxOnDestroy ? { onDestroy: opts.sandboxOnDestroy } : {}) }))\n case 'daytona':\n return createSandboxContext(createDaytonaProvider({ cwd: opts.cwd, env: opts.env, ...(opts.pregame ? { pregame: opts.pregame } : {}), ...(opts.sandboxId ? { sandboxId: opts.sandboxId } : {}), ...(opts.sandboxOnDestroy ? { onDestroy: opts.sandboxOnDestroy } : {}) }))\n case 'process':\n default:\n return createProcessContext({ cwd: opts.cwd, env: opts.env })\n }\n}\n\n/**\n * Contexts whose filesystem is a remote sandbox: host paths don't exist\n * there, so host-derived cwds must not be forwarded.\n */\nexport function isRemoteSandboxContext(type: string): boolean {\n return type === 'e2b' || type === 'daytona'\n}\n\n/** The session of a CLI run, with what durability gives it. */\nexport interface CliSession {\n session: Session\n /**\n * `createAgent`'s `durable`: the SQLite runtime the session is stored on,\n * unless `durability` is `off` or the session lives in memory. `on`\n * resumes an interrupted run before a run; `resume-ask` heals it.\n */\n durable?: DurableOptions\n /** A checkpoint run a dead process left in the session, to continue (`agent.resume`) before the prompt. */\n resumeRunId?: string\n}\n\n/**\n * Resolve the session for a CLI run.\n * - `sessionDb` set → sqlite-backed; resume `sessionId` if it exists, else\n * create it (or a fresh id when `sessionId` is omitted).\n * - `sessionDb` absent → in-memory store (no durability).\n *\n * Fresh sessions are saved immediately so the store has a header row from\n * the start — incremental `appendTurns` against a header-less sqlite store\n * would otherwise be silent no-ops, and an error / Ctrl+C before the final\n * save would lose the whole run.\n *\n * Durability (`Settings.durability`, default `resume-ask`): unless `off`,\n * runs keep checkpoints on the session's SQLite file. An existing session\n * whose last run a dead process left is resumed (`on`), or resumed when\n * `ask` says so (`resume-ask`; without `ask`, nobody to ask, it is\n * not); otherwise its interrupted tool calls are healed\n * (`healInterruptedToolCalls`).\n * @param sessionDb - SQLite sessions file.\n * @param sessionId - Session to resume or create.\n * @param options - Durability of the run, and how to ask before resuming.\n * @param options.durability - `on`, `resume-ask` or `off`.\n * @param options.ask - Ask the user whether to resume an interrupted run.\n */\nexport async function createCliSession(sessionDb?: string, sessionId?: string, options: { durability?: DurabilityMode, ask?: () => Promise<boolean> } = {}): Promise<CliSession> {\n if (sessionDb) {\n const { createSqliteStore } = await import('./session/sqlite')\n const store = createSqliteStore({ path: sessionDb })\n const durability = options.durability ?? DEFAULT_DURABILITY\n const durable = durability === 'off' ? undefined : sqliteRuntimeForStore(store)\n const withDurable = (session: Session, resumeRunId?: string): CliSession => ({\n session,\n ...(durable ? { durable: { runtime: durable, onInterrupted: durability === 'on' ? 'resume' : 'heal' } } : {}),\n ...(resumeRunId !== undefined ? { resumeRunId } : {}),\n })\n if (sessionId) {\n const existing = await loadSession(store, sessionId)\n if (existing) {\n const resumeRunId = durable ? await interruptedRun(durable, sessionId, durability, options.ask) : undefined\n // No run claim on this path: resolving the session IS the run start,\n // so heal here (see `healInterruptedToolCalls`). A resumed run\n // dispatches its pending calls itself.\n if (resumeRunId === undefined)\n await existing.healInterruptedToolCalls()\n return withDurable(existing, resumeRunId)\n }\n const session = await createSession({ store, id: sessionId })\n await session.save()\n return withDurable(session)\n }\n const session = await createSession({ store })\n await session.save()\n return withDurable(session)\n }\n return { session: await createSession({ store: createMemoryStore() }) }\n}\n\n/** The run of `sessionId` a dead process left, when the durability says to resume it. */\nasync function interruptedRun(durable: DurableRuntime, sessionId: string, durability: DurabilityMode, ask: (() => Promise<boolean>) | undefined): Promise<string | undefined> {\n const pending = (await durable.lease?.resumable({ staleAt: Date.now() - LEASE_STALE_MS }) ?? []).filter(run => run.sessionId === sessionId).at(-1)\n if (!pending)\n return undefined\n if (durability === 'on' || (durability === 'resume-ask' && await ask?.()))\n return pending.runId\n return undefined\n}\n\n/**\n * Install SIGINT/SIGTERM handlers for a CLI run. The first signal aborts the\n * returned `AbortSignal` so the running agent can unwind cleanly (persist the\n * session, destroy execution contexts) and the process exits through the\n * normal path — which is what fires the `process.on('exit')` orphan reaper\n * for detached background process groups. A second signal force-exits\n * immediately (the synchronous 'exit' reaper still runs, but async cleanup\n * such as Docker container teardown is skipped).\n */\nexport function installCliSignalHandlers(): AbortSignal {\n const controller = new AbortController()\n const onSignal = (name: NodeJS.Signals): void => {\n if (controller.signal.aborted)\n process.exit(name === 'SIGTERM' ? 143 : 130) // 128 + signal number\n controller.abort(new Error(`Received ${name}, stopping the run`))\n }\n process.on('SIGINT', () => onSignal('SIGINT'))\n process.on('SIGTERM', () => onSignal('SIGTERM'))\n return controller.signal\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkCA,SAAgB,yBAAyB,KAAsB,eAAwD;CACrH,MAA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C5D,OAAO,SAAS,SAAS,SAAS;AACpC"}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import process from "node:process";
|
|
2
|
+
//#region src/cli-style.ts
|
|
3
|
+
/**
|
|
4
|
+
* The look of zidane's human-facing CLI output (`zidane upgrade`, `server`,
|
|
5
|
+
* `machine`, `extension`): a status mark per line, aligned rows, a dim hint,
|
|
6
|
+
* a `Next:` line and a three-line error. Colors are the default theme's
|
|
7
|
+
* (`src/chat/theme.ts`), as truecolor when the terminal says it takes it,
|
|
8
|
+
* else basic ANSI. No color when the stream is not a TTY or NO_COLOR is set;
|
|
9
|
+
* FORCE_COLOR turns it on (FORCE_COLOR=0 turns it off). Never use it for
|
|
10
|
+
* machine-readable output (`--json`, headless, protocols).
|
|
11
|
+
*
|
|
12
|
+
* Kept free of other modules: the CLI dispatcher loads it before anything heavy.
|
|
13
|
+
*/
|
|
14
|
+
/** The default theme's tones (`DEFAULT_THEME.colors` in `src/chat/theme.ts`; a test keeps them equal). */
|
|
15
|
+
const CLI_TONES = {
|
|
16
|
+
brand: "#2ba6ff",
|
|
17
|
+
success: "#22c55e",
|
|
18
|
+
warn: "#53c4ff",
|
|
19
|
+
error: "#ef4444",
|
|
20
|
+
dim: "#a3a3ac",
|
|
21
|
+
mute: "#525258"
|
|
22
|
+
};
|
|
23
|
+
/** Basic ANSI fallbacks for each tone. */
|
|
24
|
+
const BASIC = {
|
|
25
|
+
brand: 94,
|
|
26
|
+
success: 32,
|
|
27
|
+
warn: 36,
|
|
28
|
+
error: 31,
|
|
29
|
+
dim: 37,
|
|
30
|
+
mute: 90
|
|
31
|
+
};
|
|
32
|
+
const MARKS = {
|
|
33
|
+
ok: "✓",
|
|
34
|
+
fail: "✗",
|
|
35
|
+
warn: "!",
|
|
36
|
+
info: "·"
|
|
37
|
+
};
|
|
38
|
+
const MARK_TONE = {
|
|
39
|
+
ok: "success",
|
|
40
|
+
fail: "error",
|
|
41
|
+
warn: "warn",
|
|
42
|
+
info: "mute"
|
|
43
|
+
};
|
|
44
|
+
/** The stream is a terminal (whatever the color settings say). */
|
|
45
|
+
function isTerminal(stream) {
|
|
46
|
+
return stream?.isTTY === true;
|
|
47
|
+
}
|
|
48
|
+
/** How much color a stream takes, from its TTY flag and the environment. */
|
|
49
|
+
function colorLevel(stream, env = process.env) {
|
|
50
|
+
const force = env.FORCE_COLOR;
|
|
51
|
+
const truecolor = env.COLORTERM === "truecolor" || env.COLORTERM === "24bit";
|
|
52
|
+
if (force !== void 0) {
|
|
53
|
+
if (force === "0" || force === "false") return 0;
|
|
54
|
+
return force === "3" || truecolor ? 3 : 1;
|
|
55
|
+
}
|
|
56
|
+
if (env.NO_COLOR !== void 0 && env.NO_COLOR !== "") return 0;
|
|
57
|
+
if (!isTerminal(stream) || env.TERM === "dumb") return 0;
|
|
58
|
+
return truecolor ? 3 : 1;
|
|
59
|
+
}
|
|
60
|
+
function rgb(hex) {
|
|
61
|
+
const n = Number.parseInt(hex.slice(1), 16);
|
|
62
|
+
return [
|
|
63
|
+
n >> 16 & 255,
|
|
64
|
+
n >> 8 & 255,
|
|
65
|
+
n & 255
|
|
66
|
+
];
|
|
67
|
+
}
|
|
68
|
+
/** The style for one output stream (`process.stdout`, `process.stderr`, or a test's writer). */
|
|
69
|
+
function cliStyle(stream, env = process.env) {
|
|
70
|
+
const level = colorLevel(stream, env);
|
|
71
|
+
const wrap = (open, close, text) => level === 0 || text === "" ? text : `\x1B[${open}m${text}\x1B[${close}m`;
|
|
72
|
+
const tone = (name, text) => {
|
|
73
|
+
if (level === 3) return wrap(`38;2;${rgb(CLI_TONES[name]).join(";")}`, "39", text);
|
|
74
|
+
return wrap(String(BASIC[name]), "39", text);
|
|
75
|
+
};
|
|
76
|
+
const bold = (text) => wrap("1", "22", text);
|
|
77
|
+
const mark = (status) => tone(MARK_TONE[status], MARKS[status]);
|
|
78
|
+
return {
|
|
79
|
+
level,
|
|
80
|
+
tone,
|
|
81
|
+
bold,
|
|
82
|
+
title: (text) => bold(text),
|
|
83
|
+
step: (status, text, detail) => `${mark(status)} ${text}${detail ? ` ${tone("dim", detail)}` : ""}`,
|
|
84
|
+
rows: (pairs, indent = "") => {
|
|
85
|
+
const width = Math.max(0, ...pairs.map(([key]) => key.length));
|
|
86
|
+
return pairs.map(([key, value]) => `${indent}${tone("dim", key.padEnd(width))} ${value}`.trimEnd()).join("\n");
|
|
87
|
+
},
|
|
88
|
+
hint: (text) => tone("dim", text),
|
|
89
|
+
next: (text) => `${tone("brand", "Next:")} ${text}`,
|
|
90
|
+
error: (what, cause, fix) => [
|
|
91
|
+
`${mark("fail")} ${what}`,
|
|
92
|
+
...cause ? cause.split("\n").map((line) => ` ${line}`) : [],
|
|
93
|
+
...fix ? [` ${tone("dim", "Fix:")} ${fix}`] : []
|
|
94
|
+
].join("\n"),
|
|
95
|
+
paint: (line) => {
|
|
96
|
+
const status = Object.keys(MARKS).find((s) => line.startsWith(`${MARKS[s]} `));
|
|
97
|
+
return status ? `${mark(status)}${line.slice(1)}` : line;
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
cliStyle(void 0, {});
|
|
102
|
+
//#endregion
|
|
103
|
+
export { cliStyle as t };
|
|
104
|
+
|
|
105
|
+
//# sourceMappingURL=cli-style-DBEm6CyT.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cli-style-DBEm6CyT.js","names":[],"sources":["../src/cli-style.ts"],"sourcesContent":["/**\n * The look of zidane's human-facing CLI output (`zidane upgrade`, `server`,\n * `machine`, `extension`): a status mark per line, aligned rows, a dim hint,\n * a `Next:` line and a three-line error. Colors are the default theme's\n * (`src/chat/theme.ts`), as truecolor when the terminal says it takes it,\n * else basic ANSI. No color when the stream is not a TTY or NO_COLOR is set;\n * FORCE_COLOR turns it on (FORCE_COLOR=0 turns it off). Never use it for\n * machine-readable output (`--json`, headless, protocols).\n *\n * Kept free of other modules: the CLI dispatcher loads it before anything heavy.\n */\nimport process from 'node:process'\n\n/** The default theme's tones (`DEFAULT_THEME.colors` in `src/chat/theme.ts`; a test keeps them equal). */\nexport const CLI_TONES = {\n brand: '#2ba6ff',\n success: '#22c55e',\n warn: '#53c4ff',\n error: '#ef4444',\n dim: '#a3a3ac',\n mute: '#525258',\n} as const\n\nexport type CliTone = keyof typeof CLI_TONES\n\n/** Basic ANSI fallbacks for each tone. */\nconst BASIC: Record<CliTone, number> = { brand: 94, success: 32, warn: 36, error: 31, dim: 37, mute: 90 }\n\nexport type StepStatus = 'ok' | 'fail' | 'warn' | 'info'\n\nexport const MARKS: Record<StepStatus, string> = { ok: '✓', fail: '✗', warn: '!', info: '·' }\nconst MARK_TONE: Record<StepStatus, CliTone> = { ok: 'success', fail: 'error', warn: 'warn', info: 'mute' }\n\n/** 0: none, 1: basic ANSI, 3: truecolor. */\nexport type ColorLevel = 0 | 1 | 3\n\ntype Env = Readonly<Record<string, string | undefined>>\n\n/** The stream is a terminal (whatever the color settings say). */\nexport function isTerminal(stream: object | undefined): boolean {\n return (stream as { isTTY?: unknown } | undefined)?.isTTY === true\n}\n\n/** How much color a stream takes, from its TTY flag and the environment. */\nexport function colorLevel(stream: object | undefined, env: Env = process.env): ColorLevel {\n const force = env.FORCE_COLOR\n const truecolor = env.COLORTERM === 'truecolor' || env.COLORTERM === '24bit'\n if (force !== undefined) {\n if (force === '0' || force === 'false')\n return 0\n return force === '3' || truecolor ? 3 : 1\n }\n if (env.NO_COLOR !== undefined && env.NO_COLOR !== '')\n return 0\n if (!isTerminal(stream) || env.TERM === 'dumb')\n return 0\n return truecolor ? 3 : 1\n}\n\nfunction rgb(hex: string): [number, number, number] {\n const n = Number.parseInt(hex.slice(1), 16)\n return [(n >> 16) & 255, (n >> 8) & 255, n & 255]\n}\n\nexport interface CliStyle {\n level: ColorLevel\n /** Text in one theme tone (plain without color). */\n tone: (tone: CliTone, text: string) => string\n bold: (text: string) => string\n /** A heading line: what this output is about. */\n title: (text: string) => string\n /** `✓ text`, `✗ text`, `! text` or `· text`, with an optional dim detail after. */\n step: (status: StepStatus, text: string, detail?: string) => string\n /** `key value` rows, the keys padded to one width and dim. */\n rows: (pairs: ReadonlyArray<readonly [string, string]>, indent?: string) => string\n /** A dim line: context the user may skip. */\n hint: (text: string) => string\n /** `Next: text`: the one thing to do now. */\n next: (text: string) => string\n /** `✗ what`, then the cause (each of its lines) and `Fix: …` indented below, each optional. */\n error: (what: string, cause?: string, fix?: string) => string\n /** Colors the leading mark of a line already rendered without color (`✓ …`). */\n paint: (line: string) => string\n}\n\n/** The style for one output stream (`process.stdout`, `process.stderr`, or a test's writer). */\nexport function cliStyle(stream?: object, env: Env = process.env): CliStyle {\n const level = colorLevel(stream, env)\n const wrap = (open: string, close: string, text: string): string => (level === 0 || text === '' ? text : `\\x1B[${open}m${text}\\x1B[${close}m`)\n const tone = (name: CliTone, text: string): string => {\n if (level === 3)\n return wrap(`38;2;${rgb(CLI_TONES[name]).join(';')}`, '39', text)\n return wrap(String(BASIC[name]), '39', text)\n }\n const bold = (text: string): string => wrap('1', '22', text)\n const mark = (status: StepStatus): string => tone(MARK_TONE[status], MARKS[status])\n return {\n level,\n tone,\n bold,\n title: text => bold(text),\n step: (status, text, detail) => `${mark(status)} ${text}${detail ? ` ${tone('dim', detail)}` : ''}`,\n rows: (pairs, indent = '') => {\n const width = Math.max(0, ...pairs.map(([key]) => key.length))\n return pairs.map(([key, value]) => `${indent}${tone('dim', key.padEnd(width))} ${value}`.trimEnd()).join('\\n')\n },\n hint: text => tone('dim', text),\n next: text => `${tone('brand', 'Next:')} ${text}`,\n error: (what, cause, fix) => [\n `${mark('fail')} ${what}`,\n ...(cause ? cause.split('\\n').map(line => ` ${line}`) : []),\n ...(fix ? [` ${tone('dim', 'Fix:')} ${fix}`] : []),\n ].join('\\n'),\n paint: (line) => {\n const status = (Object.keys(MARKS) as StepStatus[]).find(s => line.startsWith(`${MARKS[s]} `))\n return status ? `${mark(status)}${line.slice(1)}` : line\n },\n }\n}\n\n/** No color, whatever the environment: for p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M,IAAI,KAAK,MAAM,CAAC,MAAM;EACtD;CACF;AACF;AAGoC,SAAS,KAAA,GAAW,CAAC,CAAC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { ss as HostSignal } from "./media-type-
|
|
2
|
-
import "./types-
|
|
3
|
-
import { D as IpcParams, H as SignalMeta, O as IpcResult, T as IpcMethodName, s as HelloResult } from "./protocol-
|
|
1
|
+
import { ss as HostSignal } from "./media-type-ZSmAGHvg.js";
|
|
2
|
+
import "./types-SXqk6hLD.js";
|
|
3
|
+
import { D as IpcParams, H as SignalMeta, O as IpcResult, T as IpcMethodName, s as HelloResult } from "./protocol-C2lqKuMd.js";
|
|
4
4
|
//#region src/ipc/transports/client-core.d.ts
|
|
5
5
|
/** A connected host client, shared by every transport. Requests are checked against {@link IpcMethods}. */
|
|
6
6
|
interface IpcClient {
|
|
@@ -35,4 +35,4 @@ declare class IpcVersionMismatchError extends Error {
|
|
|
35
35
|
}
|
|
36
36
|
//#endregion
|
|
37
37
|
export { IpcVersionMismatchError as n, IpcClient as t };
|
|
38
|
-
//# sourceMappingURL=client-core-
|
|
38
|
+
//# sourceMappingURL=client-core-C_4m_oL6.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client-core-
|
|
1
|
+
{"version":3,"file":"client-core-C_4m_oL6.d.ts","names":[],"sources":["../src/ipc/transports/client-core.ts"],"mappings":";;;;;UAeiB;;EAEf,OAAO;;;;;EAKP,UAAU,UAAU,eAAe,QAAQ,GAAG,QAAQ,UAAU,OAAO,QAAQ,UAAU;;;;;;;EAOzF,SAAS,UAAU,eAAe,QAAQ,GAAG,QAAQ,UAAU;;EAE/D,WAAW,IAAI;;EAEf;;KAGU,kBAAkB,QAAQ,YAAY,OAAO;;cAG5C,gCAAgC;WAKL,SAAS;;;;;EAAnC,YAAA,iBAA0B,SAAS"}
|