@cortexkit/opencode-openai-auth 1.23.1 → 1.23.2
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/bin.js +7 -7
- package/dist/{index-7hy72nfy.js → index-by5wfvqm.js} +2 -2
- package/dist/index-nd2ks7er.js +2 -0
- package/dist/index-t876xhkr.js +60 -0
- package/dist/{index-p81hxfe6.js → index-v8w8j1wx.js} +1 -1
- package/dist/{index-3ya2s179.js → index-v8wrmhyp.js} +1 -1
- package/dist/{index-bd18sfjj.js → index-x00sxt2w.js} +10 -10
- package/dist/index.d.ts +3 -2
- package/dist/index.js +1 -1
- package/dist/{runtime-layout-B07ApQZL.d.ts → internal-DacVgEWs.d.ts} +86 -663
- package/dist/rpc/port-file.js +1 -1
- package/dist/runtime-layout-Dcbj_Rq3.d.ts +650 -0
- package/dist/{sidebar-state--OTpRzFd.d.ts → sidebar-state-L--CdbLi.d.ts} +4 -15
- package/dist/sidebar-state.d.ts +1 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/tui.d.ts +5 -2
- package/dist/v2/server.d.ts +2 -1
- package/dist/v2/server.js +4 -4
- package/package.json +1 -1
- package/src/tui-compiled/raw/shared/054118b2705fdc20-ansi.js +98 -0
- package/src/tui-compiled/raw/shared/0895e780489c494d-window.js +33 -0
- package/src/tui-compiled/raw/shared/0b7d24474e2f33e9-credential-redaction.js +424 -0
- package/src/tui-compiled/raw/shared/0c9533222cb4380c-namespace.js +224 -0
- package/src/tui-compiled/raw/shared/112607e46a5b5f58-accounts.js +393 -0
- package/src/tui-compiled/raw/shared/136fa4abe48ad69d-cachekeep.js +411 -0
- package/src/tui-compiled/raw/shared/1547bd74f4214d2d-index.js +28 -0
- package/src/tui-compiled/raw/shared/1567207f323dc733-codex-http.js +44 -0
- package/src/tui-compiled/raw/shared/15f402885cbb2fb3-envelope-loss.js +151 -0
- package/src/tui-compiled/raw/shared/18df43cab4563acf-families.js +149 -0
- package/src/tui-compiled/raw/shared/1a4c289eec261e04-codex-instructions.js +59 -0
- package/src/tui-compiled/raw/shared/1afd446e190ef85c-vault-messages.js +12 -0
- package/src/tui-compiled/raw/shared/1b06ec96856ff8b9-codex-endpoint.js +17 -0
- package/src/tui-compiled/raw/shared/1e2f1a89bb34a773-vault-adapter.js +110 -0
- package/src/tui-compiled/raw/shared/2194fb8e8b42d7d5-insula-quota.js +73 -0
- package/src/tui-compiled/raw/shared/22b2bce42f2d6806-handle.js +10 -0
- package/src/tui-compiled/raw/shared/2577ec69f9973ae9-quota-normalize.js +13 -14
- package/src/tui-compiled/raw/shared/26055d4e5ad5e71f-codex-request.js +198 -0
- package/src/tui-compiled/raw/shared/26b57ac4c3b0c3f6-unconfirmed-retain-counter.js +41 -0
- package/src/tui-compiled/raw/shared/2bb681e99c2721d7-registry.js +538 -0
- package/src/tui-compiled/raw/shared/2dce6e9613993329-quota-manager.js +13 -20
- package/src/tui-compiled/raw/shared/2ec33b3e2b8ac38a-terminal.js +168 -0
- package/src/tui-compiled/raw/shared/30bcca1d1b4240a0-pool-session-pins.js +32 -0
- package/src/tui-compiled/raw/shared/3af9a210aa2ccdf2-codex-call-status.js +21 -0
- package/src/tui-compiled/raw/shared/3b31b36bf0877602-wording.js +120 -0
- package/src/tui-compiled/raw/shared/3c4c1a2d3fc92726-failure.js +59 -0
- package/src/tui-compiled/raw/shared/3dfe71eec6e0487d-presets.js +240 -0
- package/src/tui-compiled/raw/shared/43de3a5c4845cfc1-pool-adapter.js +149 -0
- package/src/tui-compiled/raw/shared/49353b63a833c8fb-session-cache-policy.js +60 -0
- package/src/tui-compiled/raw/shared/4adf46e07e025363-axes.js +7 -0
- package/src/tui-compiled/raw/shared/4ba847b77580b1eb-confirm.js +21 -0
- package/src/tui-compiled/raw/shared/4d05c2d7a531aece-oauth.js +48 -36
- package/src/tui-compiled/raw/shared/5018d4665e969588-limit-policy.js +159 -0
- package/src/tui-compiled/raw/shared/595bdf3fff13ba79-limit-identity.js +49 -0
- package/src/tui-compiled/raw/shared/59def9e82b61204a-session-cache-activity.js +35 -0
- package/src/tui-compiled/raw/shared/5d806e1a305d14f5-commands.js +879 -0
- package/src/tui-compiled/raw/shared/5fc39320fa8bd3a0-limit-registry.js +473 -0
- package/src/tui-compiled/raw/shared/63c1ee7e70e85e8d-vault.js +1 -0
- package/src/tui-compiled/raw/shared/6545ab7f757314b7-refresh-all-quota.js +237 -0
- package/src/tui-compiled/raw/shared/66937534c260d20b-stable-json.js +11 -0
- package/src/tui-compiled/raw/shared/7056acef1b021f19-bridge.js +10 -0
- package/src/tui-compiled/raw/shared/72d2ca42883809b4-marker.js +107 -0
- package/src/tui-compiled/raw/shared/775431e21f469203-record.js +3 -0
- package/src/tui-compiled/raw/shared/799f3ade4efbd1ea-opencode-v1.js +47 -0
- package/src/tui-compiled/raw/shared/7b2a0471b29e4f5e-wake.js +47 -0
- package/src/tui-compiled/raw/shared/7b5d6afff4ff32b9-select.js +159 -0
- package/src/tui-compiled/raw/shared/7bf96bf4d9249b3d-vault-billing.js +108 -0
- package/src/tui-compiled/raw/shared/7c98bde36aad4819-input-transformations.js +34 -0
- package/src/tui-compiled/raw/shared/7fb0418303f20a10-index.js +3 -0
- package/src/tui-compiled/raw/shared/806e12ccbad34388-pi-wait.js +51 -0
- package/src/tui-compiled/raw/shared/81ae201b724cac14-menu.js +73 -0
- package/src/tui-compiled/raw/shared/8349ed25dc629e97-scope.js +10 -0
- package/src/tui-compiled/raw/shared/86da3379973780b9-limit-provenance.js +60 -0
- package/src/tui-compiled/raw/shared/8aba66ed486d30a7-decide.js +425 -0
- package/src/tui-compiled/raw/shared/8c0c8df25a5dca1f-manager.js +735 -0
- package/src/tui-compiled/raw/shared/8c42bbec02f59636-vault-routing.js +212 -0
- package/src/tui-compiled/raw/shared/8ca6175bfae53e13-envelope.js +123 -0
- package/src/tui-compiled/raw/shared/8d0245e41049d83f-header-classifier.js +121 -0
- package/src/tui-compiled/raw/shared/9c162809179c7560-login.js +89 -0
- package/src/tui-compiled/raw/shared/a1f495296a4b756f-frame-turn.js +72 -0
- package/src/tui-compiled/raw/shared/a37138dcbd893f55-hold-bounds.js +5 -0
- package/src/tui-compiled/raw/shared/aa7fb10d77a2cccd-vault-account-menu.js +133 -0
- package/src/tui-compiled/raw/shared/adc5eeb5a8d28280-persistence.js +9 -0
- package/src/tui-compiled/raw/shared/b301c79e6378d1fb-vault.js +678 -0
- package/src/tui-compiled/raw/shared/b3c11de5f36e617a-reset.js +44 -0
- package/src/tui-compiled/raw/shared/ba6535c610d1edb3-pool-source-state.js +100 -0
- package/src/tui-compiled/raw/shared/bd4aef685681048c-duration.js +20 -0
- package/src/tui-compiled/raw/shared/bd5977eca210d2b8-index.js +662 -0
- package/src/tui-compiled/raw/shared/bfc46d34f4c9db33-limit-recovery.js +127 -0
- package/src/tui-compiled/raw/shared/c66495424ad84aee-hold.js +25 -0
- package/src/tui-compiled/raw/shared/c6a67b836bd5afcd-vault-command-menu.js +300 -0
- package/src/tui-compiled/raw/shared/c9340fb545c4e5de-internal.js +73 -0
- package/src/tui-compiled/raw/shared/c954c6447b7b9b64-activity.js +52 -0
- package/src/tui-compiled/raw/shared/cba8b0aee46b8526-codex-lite.js +85 -0
- package/src/tui-compiled/raw/shared/cec39ccddab4fe9c-labels.js +11 -0
- package/src/tui-compiled/raw/shared/cef0f2346957e83c-index.js +552 -0
- package/src/tui-compiled/raw/shared/cf7dedf24f902d68-dump-size.js +41 -0
- package/src/tui-compiled/raw/shared/d422d6dbc4e35199-background-quota-refresh.js +107 -0
- package/src/tui-compiled/raw/shared/d5b268767d330507-doctor.js +81 -0
- package/src/tui-compiled/raw/shared/d7ac5ca41f49121b-index.js +12 -0
- package/src/tui-compiled/raw/shared/d7fa77560855dee2-jitter.js +9 -0
- package/src/tui-compiled/raw/shared/de7f7d8803624369-path.js +31 -0
- package/src/tui-compiled/raw/shared/df0bdc74fb0c0db0-limit-mark.js +27 -0
- package/src/tui-compiled/raw/shared/e26c2bb5722ab047-routing-hold.js +23 -0
- package/src/tui-compiled/raw/shared/e2ae081583adfce3-dump.js +80 -0
- package/src/tui-compiled/raw/shared/e44ba1b3a9903f5d-reset-credits.js +483 -0
- package/src/tui-compiled/raw/shared/e5229952fc12f647-codex-models.js +34 -0
- package/src/tui-compiled/raw/shared/e8fda84e90176436-uuid-v7.js +13 -0
- package/src/tui-compiled/raw/shared/ea56007991dbf068-terminal.js +19 -0
- package/src/tui-compiled/raw/shared/ec6f1d96e7d70174-quota-refusal.js +145 -0
- package/src/tui-compiled/raw/shared/f03d7b43a214a4a1-canonical-input.js +42 -0
- package/src/tui-compiled/raw/shared/f1012265b3a768c7-merge-laws.js +31 -0
- package/src/tui-compiled/raw/shared/f2ca864fe967415a-cache-policy.js +198 -0
- package/src/tui-compiled/raw/shared/f317a4740f9d76f8-identity.js +21 -0
- package/src/tui-compiled/raw/shared/f607353c4126272a-routing-wait.js +19 -0
- package/src/tui-compiled/raw/shared/f6189f5c9aee31eb-decision.js +55 -0
- package/src/tui-compiled/raw/shared/f6d728f5e601f98b-request-history.js +120 -0
- package/src/tui-compiled/raw/shared/f981e6b15fb76cdb-codex-body.js +28 -0
- package/src/tui-compiled/raw/shared/fda579e5a0a54165-codex-effort.js +60 -0
- package/src/tui-compiled/raw/sidebar-state.js +54 -4
- package/src/tui-compiled/raw/tui/v2-dialog.js +1 -1
- package/src/tui-compiled/raw/tui.tsx +27 -5
- package/src/tui-compiled/runtime/shared/054118b2705fdc20-ansi.js +98 -0
- package/src/tui-compiled/runtime/shared/0895e780489c494d-window.js +33 -0
- package/src/tui-compiled/runtime/shared/0b7d24474e2f33e9-credential-redaction.js +424 -0
- package/src/tui-compiled/runtime/shared/0c9533222cb4380c-namespace.js +224 -0
- package/src/tui-compiled/runtime/shared/112607e46a5b5f58-accounts.js +393 -0
- package/src/tui-compiled/runtime/shared/136fa4abe48ad69d-cachekeep.js +411 -0
- package/src/tui-compiled/runtime/shared/1547bd74f4214d2d-index.js +28 -0
- package/src/tui-compiled/runtime/shared/1567207f323dc733-codex-http.js +44 -0
- package/src/tui-compiled/runtime/shared/15f402885cbb2fb3-envelope-loss.js +151 -0
- package/src/tui-compiled/runtime/shared/18df43cab4563acf-families.js +149 -0
- package/src/tui-compiled/runtime/shared/1a4c289eec261e04-codex-instructions.js +59 -0
- package/src/tui-compiled/runtime/shared/1afd446e190ef85c-vault-messages.js +12 -0
- package/src/tui-compiled/runtime/shared/1b06ec96856ff8b9-codex-endpoint.js +17 -0
- package/src/tui-compiled/runtime/shared/1e2f1a89bb34a773-vault-adapter.js +110 -0
- package/src/tui-compiled/runtime/shared/2194fb8e8b42d7d5-insula-quota.js +73 -0
- package/src/tui-compiled/runtime/shared/22b2bce42f2d6806-handle.js +10 -0
- package/src/tui-compiled/runtime/shared/2577ec69f9973ae9-quota-normalize.js +13 -14
- package/src/tui-compiled/runtime/shared/26055d4e5ad5e71f-codex-request.js +198 -0
- package/src/tui-compiled/runtime/shared/26b57ac4c3b0c3f6-unconfirmed-retain-counter.js +41 -0
- package/src/tui-compiled/runtime/shared/2bb681e99c2721d7-registry.js +538 -0
- package/src/tui-compiled/runtime/shared/2dce6e9613993329-quota-manager.js +13 -20
- package/src/tui-compiled/runtime/shared/2ec33b3e2b8ac38a-terminal.js +168 -0
- package/src/tui-compiled/runtime/shared/30bcca1d1b4240a0-pool-session-pins.js +32 -0
- package/src/tui-compiled/runtime/shared/3af9a210aa2ccdf2-codex-call-status.js +21 -0
- package/src/tui-compiled/runtime/shared/3b31b36bf0877602-wording.js +120 -0
- package/src/tui-compiled/runtime/shared/3c4c1a2d3fc92726-failure.js +59 -0
- package/src/tui-compiled/runtime/shared/3dfe71eec6e0487d-presets.js +240 -0
- package/src/tui-compiled/runtime/shared/43de3a5c4845cfc1-pool-adapter.js +149 -0
- package/src/tui-compiled/runtime/shared/49353b63a833c8fb-session-cache-policy.js +60 -0
- package/src/tui-compiled/runtime/shared/4adf46e07e025363-axes.js +7 -0
- package/src/tui-compiled/runtime/shared/4ba847b77580b1eb-confirm.js +21 -0
- package/src/tui-compiled/runtime/shared/4d05c2d7a531aece-oauth.js +48 -36
- package/src/tui-compiled/runtime/shared/5018d4665e969588-limit-policy.js +159 -0
- package/src/tui-compiled/runtime/shared/595bdf3fff13ba79-limit-identity.js +49 -0
- package/src/tui-compiled/runtime/shared/59def9e82b61204a-session-cache-activity.js +35 -0
- package/src/tui-compiled/runtime/shared/5d806e1a305d14f5-commands.js +879 -0
- package/src/tui-compiled/runtime/shared/5fc39320fa8bd3a0-limit-registry.js +473 -0
- package/src/tui-compiled/runtime/shared/63c1ee7e70e85e8d-vault.js +1 -0
- package/src/tui-compiled/runtime/shared/6545ab7f757314b7-refresh-all-quota.js +237 -0
- package/src/tui-compiled/runtime/shared/66937534c260d20b-stable-json.js +11 -0
- package/src/tui-compiled/runtime/shared/7056acef1b021f19-bridge.js +10 -0
- package/src/tui-compiled/runtime/shared/72d2ca42883809b4-marker.js +107 -0
- package/src/tui-compiled/runtime/shared/775431e21f469203-record.js +3 -0
- package/src/tui-compiled/runtime/shared/799f3ade4efbd1ea-opencode-v1.js +47 -0
- package/src/tui-compiled/runtime/shared/7b2a0471b29e4f5e-wake.js +47 -0
- package/src/tui-compiled/runtime/shared/7b5d6afff4ff32b9-select.js +159 -0
- package/src/tui-compiled/runtime/shared/7bf96bf4d9249b3d-vault-billing.js +108 -0
- package/src/tui-compiled/runtime/shared/7c98bde36aad4819-input-transformations.js +34 -0
- package/src/tui-compiled/runtime/shared/7fb0418303f20a10-index.js +3 -0
- package/src/tui-compiled/runtime/shared/806e12ccbad34388-pi-wait.js +51 -0
- package/src/tui-compiled/runtime/shared/81ae201b724cac14-menu.js +73 -0
- package/src/tui-compiled/runtime/shared/8349ed25dc629e97-scope.js +10 -0
- package/src/tui-compiled/runtime/shared/86da3379973780b9-limit-provenance.js +60 -0
- package/src/tui-compiled/runtime/shared/8aba66ed486d30a7-decide.js +425 -0
- package/src/tui-compiled/runtime/shared/8c0c8df25a5dca1f-manager.js +735 -0
- package/src/tui-compiled/runtime/shared/8c42bbec02f59636-vault-routing.js +212 -0
- package/src/tui-compiled/runtime/shared/8ca6175bfae53e13-envelope.js +123 -0
- package/src/tui-compiled/runtime/shared/8d0245e41049d83f-header-classifier.js +121 -0
- package/src/tui-compiled/runtime/shared/9c162809179c7560-login.js +89 -0
- package/src/tui-compiled/runtime/shared/a1f495296a4b756f-frame-turn.js +72 -0
- package/src/tui-compiled/runtime/shared/a37138dcbd893f55-hold-bounds.js +5 -0
- package/src/tui-compiled/runtime/shared/aa7fb10d77a2cccd-vault-account-menu.js +133 -0
- package/src/tui-compiled/runtime/shared/adc5eeb5a8d28280-persistence.js +9 -0
- package/src/tui-compiled/runtime/shared/b301c79e6378d1fb-vault.js +678 -0
- package/src/tui-compiled/runtime/shared/b3c11de5f36e617a-reset.js +44 -0
- package/src/tui-compiled/runtime/shared/ba6535c610d1edb3-pool-source-state.js +100 -0
- package/src/tui-compiled/runtime/shared/bd4aef685681048c-duration.js +20 -0
- package/src/tui-compiled/runtime/shared/bd5977eca210d2b8-index.js +662 -0
- package/src/tui-compiled/runtime/shared/bfc46d34f4c9db33-limit-recovery.js +127 -0
- package/src/tui-compiled/runtime/shared/c66495424ad84aee-hold.js +25 -0
- package/src/tui-compiled/runtime/shared/c6a67b836bd5afcd-vault-command-menu.js +300 -0
- package/src/tui-compiled/runtime/shared/c9340fb545c4e5de-internal.js +73 -0
- package/src/tui-compiled/runtime/shared/c954c6447b7b9b64-activity.js +52 -0
- package/src/tui-compiled/runtime/shared/cba8b0aee46b8526-codex-lite.js +85 -0
- package/src/tui-compiled/runtime/shared/cec39ccddab4fe9c-labels.js +11 -0
- package/src/tui-compiled/runtime/shared/cef0f2346957e83c-index.js +552 -0
- package/src/tui-compiled/runtime/shared/cf7dedf24f902d68-dump-size.js +41 -0
- package/src/tui-compiled/runtime/shared/d422d6dbc4e35199-background-quota-refresh.js +107 -0
- package/src/tui-compiled/runtime/shared/d5b268767d330507-doctor.js +81 -0
- package/src/tui-compiled/runtime/shared/d7ac5ca41f49121b-index.js +12 -0
- package/src/tui-compiled/runtime/shared/d7fa77560855dee2-jitter.js +9 -0
- package/src/tui-compiled/runtime/shared/de7f7d8803624369-path.js +31 -0
- package/src/tui-compiled/runtime/shared/df0bdc74fb0c0db0-limit-mark.js +27 -0
- package/src/tui-compiled/runtime/shared/e26c2bb5722ab047-routing-hold.js +23 -0
- package/src/tui-compiled/runtime/shared/e2ae081583adfce3-dump.js +80 -0
- package/src/tui-compiled/runtime/shared/e44ba1b3a9903f5d-reset-credits.js +483 -0
- package/src/tui-compiled/runtime/shared/e5229952fc12f647-codex-models.js +34 -0
- package/src/tui-compiled/runtime/shared/e8fda84e90176436-uuid-v7.js +13 -0
- package/src/tui-compiled/runtime/shared/ea56007991dbf068-terminal.js +19 -0
- package/src/tui-compiled/runtime/shared/ec6f1d96e7d70174-quota-refusal.js +145 -0
- package/src/tui-compiled/runtime/shared/f03d7b43a214a4a1-canonical-input.js +42 -0
- package/src/tui-compiled/runtime/shared/f1012265b3a768c7-merge-laws.js +31 -0
- package/src/tui-compiled/runtime/shared/f2ca864fe967415a-cache-policy.js +198 -0
- package/src/tui-compiled/runtime/shared/f317a4740f9d76f8-identity.js +21 -0
- package/src/tui-compiled/runtime/shared/f607353c4126272a-routing-wait.js +19 -0
- package/src/tui-compiled/runtime/shared/f6189f5c9aee31eb-decision.js +55 -0
- package/src/tui-compiled/runtime/shared/f6d728f5e601f98b-request-history.js +120 -0
- package/src/tui-compiled/runtime/shared/f981e6b15fb76cdb-codex-body.js +28 -0
- package/src/tui-compiled/runtime/shared/fda579e5a0a54165-codex-effort.js +60 -0
- package/src/tui-compiled/runtime/sidebar-state.js +54 -4
- package/src/tui-compiled/runtime/tui/v2-dialog.js +1 -1
- package/src/tui-compiled/runtime/tui.js +11 -4
- package/dist/index-0p8r7cpy.js +0 -60
- package/dist/index-px1t650b.js +0 -2
- package/dist/map-D5PHhv4z.d.ts +0 -72
package/dist/bin.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{c as
|
|
3
|
-
`);return J<0?"":z.slice(J+1)}class r extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(z){super(
|
|
4
|
-
`)}`:""}`}var
|
|
2
|
+
import{c as q0}from"./index-v8w8j1wx.js";import{Ba as t2,Ca as l,Da as F,Ea as u,Gc as G0,Yc as j0,jd as D0,na as F2,oa as s,pa as H2,qa as a,ra as $0}from"./index-by5wfvqm.js";import{Ce as g,De as e,Fe as y2,He as r2,Ie as n,Je as A,Ke as n2,Le as i,Me as C2,Ne as f2,kf as W0}from"./index-x00sxt2w.js";import"./index-49ncs7dr.js";import"./index-v8wrmhyp.js";import"./index-drm4dk5y.js";import{ih as x2,kh as U2,nh as X0}from"./index-wjp3q15r.js";import{ph as R2,th as A2}from"./index-td4g5dc9.js";import"./index-4ktepxn1.js";import"./index-j700j6at.js";import"./index-q2czrasr.js";import{spawn as B0}from"node:child_process";var N=4096,V0=1048576;class O2{buffer=Buffer.alloc(N);start=0;length=0;truncated=!1;get didTruncate(){return this.truncated}push(z){if(z.length>=N){if(z.length>N||this.length>0)this.truncated=!0;z.copy(this.buffer,0,z.length-N),this.start=0,this.length=N;return}let J=Math.max(0,this.length+z.length-N);if(J>0)this.truncated=!0;this.start=(this.start+J)%N,this.length-=J;let Z=(this.start+this.length)%N,$=Math.min(z.length,N-Z);if(z.copy(this.buffer,Z,0,$),$<z.length)z.copy(this.buffer,0,$);this.length+=z.length}toString(){let z=Buffer.alloc(this.length),J=Math.min(this.length,N-this.start);if(this.buffer.copy(z,0,this.start,this.start+J),J<this.length)this.buffer.copy(z,J,0,this.length-J);let Z=0;while(Z<z.length){let $=z[Z];if($===void 0||($&192)!==128)break;Z++}return z.subarray(Z).toString("utf8")}}var w={run(z,J,Z={}){return new Promise(($)=>{let K=performance.now(),Q=Z.timeoutMs??15000,W=new O2,G=[],V=0,X=!1,q=!1,b=!1,x;try{x=B0(z,[...J],{env:Z.env??process.env,windowsHide:!0,windowsVerbatimArguments:Z.windowsVerbatimArguments,stdio:["ignore","pipe","pipe"]})}catch{$({exitCode:1,stdout:"",stderr:"",spawnError:!0,signal:null,timedOut:!1,durationMs:performance.now()-K});return}let Y=Q>0?setTimeout(()=>{b=!0,x.kill("SIGTERM")},Q):void 0;x.stdout?.on("data",(j)=>{let U=V0-V,O=Math.min(U,j.length);if(O>0)G.push(j.subarray(0,O)),V+=O;if(j.length>U)X=!0,x.kill("SIGTERM")}),x.stderr?.on("data",(j)=>W.push(j));let H=!1,D=(j,U)=>{if(H)return;if(H=!0,Y)clearTimeout(Y);$({exitCode:q?1:X?1:j??1,stdout:Buffer.concat(G,V).toString("utf8"),stderr:W.toString(),stderrTruncated:W.didTruncate,...q?{spawnError:!0}:{},signal:U??null,timedOut:b,durationMs:performance.now()-K})};x.once("error",()=>{if(q=!0,x.pid===void 0)D(null,null)}),x.once("close",(j,U)=>D(j,U))})}};function o(z,J,Z,$,K,Q=15000){if(J==="win32"&&/\.(cmd|bat)$/i.test(Z)){if(/["%!\r\n]/.test(Z)||$.some((W)=>!/^[a-zA-Z0-9@:/._+-]+$/.test(W)))throw Error("Unsafe batch launcher or argument; use an executable instead.");return z.run("cmd.exe",["/d","/s","/c",`""${Z}" ${$.join(" ")}"`],{env:K,timeoutMs:Q,windowsVerbatimArguments:!0})}return z.run(Z,$,{env:K,timeoutMs:Q})}function I2(z){if(/^[a-zA-Z0-9_:@./-]+$/.test(z))return z;return process.platform==="win32"?`'${z.replaceAll("'","''")}'`:`'${z.replaceAll("'","'\\''")}'`}async function h(z,J,Z,$){let K=J.requestedGrants??$;if(!K)return;let Q=K.map((G)=>({grant:G,...J.approvedName!==void 0&&{grantCommand:`ck auth grant --principal ${I2(`enrolled:${J.approvedName}`)} --selector-kind ${G.selector.exact===void 0?"category":"exact"} --selector ${I2(G.selector.exact??G.selector.category)} --operation ${G.operation}`}})),W={grants:Q,...J.requestedGrantsStatus!==void 0&&{requestedGrantsStatus:J.requestedGrantsStatus}};if(J.requestedGrantsStatus==="dropped")return{...W,state:"older-vault"};try{if(!z.listScoped)return{...W,state:"unconfirmed"};let{token:G}=await C2(Z),V=await z.listScoped(G),X=Q.map((q)=>({...q,reachableLogins:V.rows.filter((b)=>b.operations.includes(q.grant.operation)&&(q.grant.selector.exact!==void 0?b.id===q.grant.selector.exact:b.categories.includes(q.grant.selector.category))).length}));return{...W,state:X.every((q)=>q.reachableLogins>0)?"reachable":X.some((q)=>q.reachableLogins>0)?"partial":"no-logins",grants:X.map((q)=>{if(q.reachableLogins===0)return q;let{grantCommand:b,...x}=q;return x})}}catch{return{...W,state:"unconfirmed"}}}function m(z,J="setup"){if(J==="plugin"&&z.requestedGrantsStatus!=="sent")return[];let Z=[],$=z.grants.some((K)=>K.grantCommand)?"run:":"check ck auth status for the approved name before granting access.";if(z.state==="older-vault")Z.push(`Approved. This vault is too old to grant access with the approval; ${$}`);else if(z.state==="no-logins")Z.push(`Approved, but no logins are reachable yet; ${$}`);else if(z.state==="partial")Z.push(`Approved, but some requested access has no reachable logins yet; ${$}`);else if(z.state==="unconfirmed")Z.push(`Approved, but access could not be confirmed; ${z.grants.some((K)=>K.grantCommand)?"check ck auth status or run:":$}`);for(let{grant:K,reachableLogins:Q,grantCommand:W}of z.grants){if(Q!==void 0&&Q>0){let G=K.selector.exact===void 0?`the vault's ${JSON.stringify(K.selector.category)} accounts`:`credential ${JSON.stringify(K.selector.exact)}`;Z.push(`Confirmed ${K.operation} access to ${G} (${Q} reachable ${Q===1?"login":"logins"}).`)}if(W)Z.push(` ${W}`)}return Z}var x0="Pi install failed; run pi install after checking your npm connection.";function U0(z){let J=Buffer.from(z,"utf8");if(J.length<=N)return z;let Z=J.length-N;while(Z<J.length){let $=J[Z];if($===void 0||($&192)!==128)break;Z++}return J.subarray(Z).toString("utf8")}function F0(z){let J=z.indexOf(`
|
|
3
|
+
`);return J<0?"":z.slice(J+1)}class r extends Error{step="pi-install";exitCode;signal;stderrTail;constructor(z){super(x0);this.name="SetupCommandError",this.exitCode=z.exitCode,this.signal=z.signal;let J=z.stderrTruncated?F0(z.stderrTail):z.stderrTail,Z=R2(J);this.stderrTail=U0(typeof Z==="string"?Z:"")}}var H0={opencode:"OpenCode",pi:"Pi"},M0={enrolled:"connected to the vault","not-enrolled":"not connected",unknown:"unknown, check with ck auth status"};function N2({host:z,outcome:J,access:Z},$="setup"){let K=Z?m(Z,$):[];return`${H0[z]}: ${M0[J]}${K.length?` — ${K.join(`
|
|
4
|
+
`)}`:""}`}var O0=new WeakMap;function k2(z,J){if(typeof z!=="object"&&typeof z!=="function"||!z)return;O0.set(z,Object.freeze(J.map((Z)=>Object.freeze({...Z}))))}import{accessSync as k0,constants as _0,existsSync as T0,readFileSync as P0,realpathSync as A0,statSync as L0}from"node:fs";import{mkdtemp as w0,rm as S0}from"node:fs/promises";import{tmpdir as v0}from"node:os";import{join as E0}from"node:path";import{parse as y0}from"jsonc-parser";import{homedir as I0}from"node:os";import{posix as C0,win32 as R0}from"node:path";import{fileURLToPath as N0}from"node:url";function k(z={}){let J=z.env??process.env,Z=z.platform??process.platform,$=Z==="win32"?R0:C0,K=z.home??(Z==="win32"?J.USERPROFILE:J.HOME)??I0(),Q=z.cwd??process.cwd(),W=(q)=>$.resolve(Q,q),G=J.OPENCODE_CONFIG_DIR?.trim(),V=J.XDG_CONFIG_HOME?.trim(),X=J.PI_CODING_AGENT_DIR?.trim()||$.join(K,".pi","agent");if(X==="~")X=K;else if(/^~[/\\]/.test(X))X=$.join(K,X.slice(2));if(X.startsWith("file://"))X=N0(X);return{env:J,platform:Z,path:$,home:K,cwd:Q,opencode:G?W(G):V?$.join(W(V),"opencode"):$.join(K,".config","opencode"),pi:W(X)}}function K2(z,J){try{return L0(z)[J]()}catch{return!1}}var S={exists:T0,isFile:(z)=>K2(z,"isFile"),isDirectory:(z)=>K2(z,"isDirectory"),isExecutable(z){try{return k0(z,_0.X_OK),K2(z,"isFile")}catch{return!1}},readText:(z)=>P0(z,"utf8"),realpath:A0};function P(z,J={}){let{env:Z,platform:$,path:K,cwd:Q}=k(J),W=J.fs??S,G=Object.entries(Z).find(([X])=>$==="win32"?X.toUpperCase()==="PATH":X==="PATH")?.[1]??"",V=$==="win32"?[".exe",".cmd",".bat",""]:[""];for(let X of G.split($==="win32"?";":":")){let q=X.trim().replace(/^"|"$/g,"");if(!q)continue;for(let b of V){let x=K.resolve(Q,q,z+b);if($==="win32"?W.isFile(x):W.isExecutable(x))return x}}return null}function _2(z={}){let{platform:J,home:Z,env:$,path:K}=k(z);if(J==="darwin")return["/Applications/OpenCode.app","/Applications/OpenCode Beta.app",K.join(Z,"Applications","OpenCode.app"),K.join(Z,"Applications","OpenCode Beta.app")];if(J==="win32"){let Q=$.LOCALAPPDATA||K.join(Z,"AppData","Local");return[K.join(Q,"Programs","opencode"),K.join(Q,"opencode")]}return["/opt/OpenCode","/usr/lib/opencode",K.join(Z,".local","share","applications","opencode.desktop")]}function Q2(z,J){let Z=J.fs??S,{path:$}=k(J);try{let K=Z.readText(z);if(K.length>65536)return z;let Q=[...K.matchAll(/"%~?dp0%?\\([^"%\r\n]+)"/g)];if(!Q.length)Q.push(...K.matchAll(/"\$basedir\/([^"$\r\n]+)"/g));let W=Q.at(-1)?.[1];if(W){let G=$.join($.dirname(z),...W.split(/[/\\]+/));if(Z.isFile(G))return Z.realpath(G)}return Z.realpath(z)}catch{return z}}function f0(z,J){let Z=J.fs??S,{path:$}=k(J),K=$.dirname(Q2(z,J));for(;;){try{let W=JSON.parse(Z.readText($.join(K,"package.json")));if(["@opencode/cli","@opencode-ai/cli"].includes(W.name))return"2";if(W.name==="opencode-ai")return/^(?:[2-9]\d*|1\d+)\.|^0\.0\.0-(?:beta|dev)-/.test(W.version??"")?"2":"1"}catch{}let Q=$.dirname(K);if(Q===K)return null;K=Q}}function T2(z={}){let J=P("opencode",z),Z=P("opencode2",z),$=J&&Z&&Q2(J,z)===Q2(Z,z),K=z.fs??S,{path:Q,opencode:W}=k(z),G="1";for(let X of["jsonc","json"]){let q=Q.join(W,`opencode.${X}`);if(!K.exists(q))continue;try{if(Object.hasOwn(y0(K.readText(q))??{},"plugins"))G="2"}catch{}break}let V=J?f0(J,z)??($?"2":G):null;if(Z&&V==="1"&&!$)return"ambiguous";return Z||$?"2":V??G}async function W2(z,J={}){let Z=J.fs??S,{env:$,platform:K,opencode:Q,pi:W}=k(J),G=J.runner??w,V=P("opencode",J)??P("opencode2",J),X=P("pi",J),q=P("ck",J),b=async(D)=>{if(!D)return null;let j;try{j=await w0(E0(v0(),"common-auth-setup-version-"));let U={...$,HOME:j,USERPROFILE:j,XDG_CONFIG_HOME:j,XDG_DATA_HOME:j,XDG_STATE_HOME:j,XDG_CACHE_HOME:j,OPENCODE_CONFIG_DIR:j,OPENCODE_CONFIG:void 0,OPENCODE_CONFIG_CONTENT:void 0,OPENCODE_AUTH_CONTENT:void 0,PI_CODING_AGENT_DIR:j},O=await o(G,K,D,["--version"],U,2000);return O.exitCode===0?/\b\d+\.\d+\.\d+(?:-[\w.-]+)?/.exec(O.stdout)?.[0]??null:null}catch{return null}finally{if(j)await S0(j,{recursive:!0,force:!0}).catch(()=>{})}},x=!1;if(q&&Z.exists(z.vault.connectionFile))try{(await(J.connect??n)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000})).close(),x=!0}catch{x=!1}let[Y,H]=await Promise.all([b(V),b(X)]);return{opencode:{installed:Z.isDirectory(Q)||_2(J).some((D)=>Z.exists(D))||V!==null,executable:V,version:Y,directory:Q,generation:T2(J)},pi:{installed:X!==null||Z.isDirectory(W),executable:X,version:H,directory:W},claustrum:{available:x,executable:q}}}import{setTimeout as r0}from"node:timers/promises";import{writeEnrollmentTokenFile as n0}from"@cortexkit/claustrum-client";import{statSync as g0}from"node:fs";import{win32 as t}from"node:path";var h0=45000,m0=A2("setup-process-fence"),d0=90000;function p0(z){try{return g0(z).isFile()}catch{return!1}}function d(z,J){return Object.entries(z).find(([Z])=>Z.toUpperCase()===J.toUpperCase())?.[1]}var X2=new Set(["opencode","litecode","opencode2","pi"]),L2=new Set(["node","bun"]),c0=[...X2,...L2].map((z)=>`Name LIKE '${z}%'`).join(" OR "),u0=`$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${c0}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`,l0=/(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;function i0(z){return[...z.matchAll(/"([^"]*)"|(\S+)/g)].map((J)=>J[1]??J[2]??"")}function P2(z){return(z.split(/[/\\]/).pop()??"").toLowerCase().replace(/\.(?:exe|cmd|bat|m?js)$/,"")}var a0=new Set(["-r","--require","--import","--loader","--experimental-loader","-C","--conditions","--env-file","--title","--input-type","--preload","--cwd","-c","--config","--tsconfig-override","-d","--define","-l","--main-fields"]),s0=new Set(["-e","--eval","-p","--print"]);function o0(z,J){for(let Z=0;Z<J.length;Z++){let $=J[Z]??"";if($==="--")return J[Z+1];if(s0.has($))return;if($.startsWith("-")){if(!$.includes("=")&&a0.has($))Z++;continue}if(z==="bun"&&$==="run")continue;return $}return}function w2(z){let[J,...Z]=i0(z);if(J===void 0)return null;let $=P2(J);if(X2.has($))return $;if(!L2.has($))return null;let K=o0($,Z);if(K===void 0)return null;let Q=P2(K);if(X2.has(Q))return Q;return l0.test(K)?"pi":null}class R extends Error{code="process-inspection-failed";step;program;exitCode;signal;timedOut;durationMs;constructor(z){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError",this.step=z.step,this.program=z.program,this.exitCode=z.exitCode,this.signal=z.signal,this.timedOut=z.timedOut,this.durationMs=z.durationMs}get refusalText(){let z=this.timedOut?"timed out":this.signal?`signal ${this.signal}`:this.exitCode===null?"could not start or complete":this.exitCode===0?"invalid output (exit code 0)":`exit code ${this.exitCode}`;return`${this.message} ${this.step}: ${z} after ${Math.round(this.durationMs)} ms.`}}class y extends Error{activeHosts;constructor(z){let J=z.map((Z)=>({pid:Z.pid,command:w2(Z.command)??"host"}));super(`OpenCode or Pi processes are currently running:
|
|
5
5
|
${J.map((Z)=>` - PID ${Z.pid}: ${Z.command}`).join(`
|
|
6
6
|
`)}
|
|
7
7
|
|
|
8
|
-
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=J,this.name="ProcessFenceViolationError"}}async function G2(z=w,J={}){let Z=(J.platform??process.platform)==="win32",$=J.env??process.env,K=Z?t.resolve(d($,"SystemRoot")??d($,"windir")??"C:\\Windows","System32"):"",Q=J.selfPid??process.pid,W={step:Z?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},G=async(X,q,b,x,Y)=>{let H=performance.now();W={step:X,...Y&&{program:Y},exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let D=await z.run(q,b,{env:J.env,timeoutMs:x});return W={step:X,...Y&&{program:Y},exitCode:D.exitCode,signal:D.signal??null,timedOut:D.timedOut??!1,durationMs:D.durationMs??performance.now()-H},D}finally{if(W.exitCode===null)W.durationMs=performance.now()-H;J.onStep?.({...W})}},V=async(X)=>{let q=t.resolve(d($,"ProgramFiles")??"C:\\Program Files","PowerShell","7","pwsh.exe"),b=(J.isFile??p1)(q)?"pwsh":"powershell",x=(d($,"PROCESSOR_ARCHITEW6432")??d($,"PROCESSOR_ARCHITECTURE"))?.toUpperCase()==="ARM64",Y=b==="powershell"&&x;if(Y)J.onProgress?.("Checking that OpenCode and Pi are not running. Without PowerShell 7 this can take up to a minute on Windows ARM; installing PowerShell 7 makes it fast.");let H=b==="pwsh"?q:t.resolve(K,"WindowsPowerShell","v1.0","powershell.exe"),D=Y?d1:h1,j=performance.now(),U=await G("CIM",H,X,D,b),O=Math.floor(D-(performance.now()-j));if((U.exitCode===3221225477||U.exitCode===-1073741819)&&!U.timedOut&&!U.signal&&!U.spawnError&&O>0)return m1.warn("Windows process query crashed with an access violation; retrying once"),G("CIM",H,X,O,b);return U};try{if(Z&&J.hostImagesOnly){let x=await V(["-NoProfile","-NonInteractive","-Command",u1]);if(x.exitCode!==0)throw new R(W);let Y=JSON.parse(x.stdout);if(!Y||typeof Y!=="object"||!("complete"in Y)||Y.complete!==!0||!("processes"in Y))throw new R(W);let H=Y.processes,D=H===null?[]:Array.isArray(H)?H:[H],j=[];for(let U of D){if(!U||typeof U!=="object"||!("Name"in U)||typeof U.Name!=="string"||!("ProcessId"in U)||!Number.isSafeInteger(U.ProcessId)||U.ProcessId<0||!("CommandLine"in U))throw new R(W);let O=U.ProcessId;if(!/^(?:node|bun)\.exe$/i.test(U.Name))j.push({pid:O,command:U.Name});else if(typeof U.CommandLine==="string")j.push({pid:O,command:U.CommandLine});else if(O!==Q)throw new R(W)}return j}let X=await G(Z?"tasklist":"ps",Z?t.resolve(K,"tasklist.exe"):"ps",Z?["/fo","csv","/nh"]:["-eo","pid,command"]);if(X.exitCode!==0)throw new R(W);let q=[];for(let x of X.stdout.split(/\r?\n/)){let Y=x.trim();if(!Y)continue;let H,D;if(Z){let j=/^"([^"]+)","(\d+)"(?:,|$)/.exec(Y);if(!j)throw new R(W);D=j[1]??"",H=Number(j[2])}else{let j=/^(\d+)\s+(.+)$/.exec(Y);if(!j){if(/^PID\s+COMMAND$/i.test(Y))continue;throw new R(W)}H=Number(j[1]),D=j[2]??""}if(!Number.isSafeInteger(H)||H<0)throw new R(W);q.push({pid:H,command:D})}if(!q.length)throw new R(W);let b=q.filter((x)=>x.pid!==Q&&/^(?:node|bun)\.exe$/i.test(x.command));if(Z&&b.length&&J.inspectRuntimes!==!1){let x=await V(["-NoProfile","-NonInteractive","-Command",`$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process -Filter "Name = 'node.exe' OR Name = 'bun.exe'" | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress`]);if(x.exitCode!==0)throw new R(W);let Y=JSON.parse(x.stdout||"null"),H=Y===null?[]:Array.isArray(Y)?Y:[Y],D=new Map;for(let j of H){if(!j||typeof j!=="object"||!("ProcessId"in j)||!("CommandLine"in j)||!Number.isSafeInteger(j.ProcessId))throw new R(W);if(typeof j.CommandLine==="string")D.set(Number(j.ProcessId),j.CommandLine);else if(b.some((U)=>U.pid===j.ProcessId))throw new R(W)}for(let j of b)j.command=D.get(j.pid)??""}return q}catch(X){if(X instanceof R)throw X;throw new R(W)}}function p(z=w,J={}){let Z=J.selfPid??process.pid,$=(K)=>K.pid!==Z&&w2(K.command)!==null;return{async listRunningHosts(K){return(await G2(z,{...J,env:K,hostImagesOnly:!0})).filter($)},async previewRunningHosts(K){let Q=await G2(z,{...J,env:K,inspectRuntimes:!1}),W=(J.platform??process.platform)==="win32";return{hosts:Q.filter($),uncheckedRuntimes:W?Q.filter((G)=>G.pid!==Z&&/^(?:node|bun)\.exe$/i.test(G.command)).length:0}}}}async function c(z,J){let Z=await z.listRunningHosts(J);if(Z.length)throw new y(Z)}class f{inspect;now;#z;constructor(z,J=()=>performance.now()){this.inspect=z,this.now=J}async check(z={}){if(z.reuse&&this.#z!==void 0){let J=this.now()-this.#z;if(J>=0&&J<5000)return}this.#z=void 0,await this.inspect(),this.#z=this.now()}async step(z){this.#z=void 0;try{return await z()}finally{this.#z=void 0}}}var t1="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",g2='This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), or run setup without --claustrum to use local accounts.',h2=300000,S2=1000,v2=[1000,2000,4000,8000,16000,30000];function j2(z){return z&&/^[a-z][a-z0-9_]{0,63}$/.test(z)?z:"unknown"}class _ extends Error{reason;lastErrorCode;constructor(z,J){super(z);if(this.name="HostNotEnrolledError",this.reason=J.reason,J.lastErrorCode!==void 0)this.lastErrorCode=j2(J.lastErrorCode)}}function E2(z,J){return`ck auth enroll approve --request-id ${z} --name ${J}`}async function m2(z,J,Z,$,K){if(e())throw Error(g);let{name:Q,displayName:W,requestedGrants:G,grantFallback:V,paths:X}=z.vault.hosts[J],q=A(X),b=typeof K==="function"?new f(K,Z.now):K;await b.check({reuse:!0});let x=await(Z.connect??n)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw new _("Claustrum connection failed; start ck and rerun setup.",{reason:"connection-failed"})}),Y=Z.now??(()=>performance.now()),H=Z.wait??r1;try{let D=new f2({proposedName:Q,displayName:W,requestedGrants:G,paths:q,client:x,writeTokenFile:async(M,L)=>{await b.check(),await b.step(()=>n1(M,L))}}),j=await D.status();if(j.state==="approved"){F($,`Already connected as ${j.approvedName??j.proposedName}.`);let M=await h(x,j,q.tokenPath,G);if(M)for(let L of m(M,V))F($,L);return M}F($,`Asking the vault to connect ${Q}…`);let U=Y()+h2,O,B,I,T=0;for(;;){await b.check({reuse:!0});let M=await b.step(()=>D.reconcile());if(M.state==="approved"){F($,`Connected ${J} to Claustrum.`);let E=await h(x,M,q.tokenPath,G);if(E)for(let b1 of m(E,V))F($,b1);return E}if(M.state==="unavailable"&&M.code===y2)throw new _(g2,{reason:"unsupported-vault",lastErrorCode:M.code});if(M.state!=="pending"&&M.state!=="busy")throw new _("Claustrum enrollment refused; inspect its status with ck before rerunning setup.",{reason:"refused",..."code"in M&&{lastErrorCode:M.code}});let L=S2;if(M.state==="busy")B="busy";else if(M.retryCode)B=M.retryCode;if(M.state==="pending"&&M.requestId){if(T=0,M.requestId!==O){if(!/^[a-zA-Z0-9_-]+$/.test(M.requestId))throw new _("Invalid enrollment request id.",{reason:"invalid-request"});O=M.requestId,F($,"Waiting for approval. In another terminal, run:"),F($,` ${E2(M.requestId,Q)}`),F($,`Enrollment files: ${q.statePath}, ${q.tokenPath}`)}}else if(M.state==="pending"&&M.retryCode){L=v2[Math.min(T,v2.length-1)]??S2,T++;let E=j2(M.retryCode);if(E!==I)I=E,F($,`The vault has not created the request yet (${E}); retrying.`)}let M2=U-Y();if(M2<=0)break;await b.step(()=>H(Math.min(L,M2))),await b.check()}if(O)throw new _(`Claustrum approval is still pending. In another terminal, run: ${E2(O,Q)} and then rerun setup.`,{reason:"approval-pending",...B!==void 0&&{lastErrorCode:B}});let C=j2(B);throw new _(`The vault never created the enrollment request (last error: ${C}). Check that ck is running, then rerun setup.`,{reason:"request-not-created",lastErrorCode:C})}catch(D){if(D instanceof y||D instanceof R||D instanceof _)throw D;let j=D?.code;throw new _(t1,{reason:"incomplete",...typeof j==="string"&&{lastErrorCode:j}})}finally{x.close()}}var d2="Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",e1=[{name:"--yes",key:"yes",description:"Run without questions and set up every found host. Does not choose the vault."},{name:"--dry-run",key:"dryRun",description:"Print what setup would do without changing anything."},{name:"--host",key:"hosts",values:["opencode","pi"],spaceForm:!0,invalid:"Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",description:"Set up only this host; repeat the flag for both. Also written --host=<host>."},{name:"--opencode",key:"opencode",values:["1","2","both"],description:"Register for this OpenCode generation."},{name:"--claustrum",key:"claustrum",description:"Connect the hosts to the Claustrum vault."},{name:"--no-claustrum",key:"noClaustrum",description:"Do not offer the Claustrum vault; sign in locally."},{name:"--login",key:"login",description:"Sign in locally instead of using the Claustrum vault."},{name:"--enroll-only",key:"enrollOnly",description:"Only connect the hosts to the Claustrum vault; register nothing and migrate nothing."}];function z2(z){return Error(`Unknown setup argument: ${z}. Run the plugin's own setup --help to list the flags setup accepts.`)}function p2(z){let J={yes:!1,dryRun:!1,claustrum:!1,noClaustrum:!1,login:!1,enrollOnly:!1,hosts:[],opencode:void 0};for(let Z=0;Z<z.length;Z++){let $=z[Z],K=$.indexOf("="),Q=K===-1?$:$.slice(0,K),W=e1.find((V)=>V.name===Q);if(!W)throw z2($);if(!("values"in W)){if(K!==-1)throw z2($);J[W.key]=!0;continue}let G;if(K!==-1)G=$.slice(K+1);else if(W.spaceForm)G=z[++Z];else throw z2($);if(G===void 0||!W.values.includes(G))throw W.invalid?Error(W.invalid):z2($);if(W.key==="hosts")J.hosts.push(G);else J.opencode=G}if(J.claustrum&&J.noClaustrum)throw Error("--claustrum and --no-claustrum cannot be used together.");if(J.login&&J.claustrum)throw Error("--login and --claustrum cannot be used together.");if(J.enrollOnly&&J.login)throw Error("--enroll-only and --login cannot be used together.");if(J.enrollOnly&&J.noClaustrum)throw Error("--enroll-only and --no-claustrum cannot be used together.");return J}async function c2(z,J){let Z=new Set(J);for(;;){let $=await u(z,[...["opencode","pi"].map((K)=>({value:K,label:`[${Z.has(K)?"x":" "}] ${K==="opencode"?"OpenCode":"Pi"}`,hint:J.includes(K)?"found":"not found"})),{value:"done",label:"Continue with selected hosts"}],{message:"Select hosts to set up",subtitle:"Enter toggles a host; choose Continue when ready."});if($===null)return null;if($==="done")return[...Z];if(Z.has($))Z.delete($);else Z.add($)}}import{rename as q0}from"node:fs/promises";import{setTimeout as Y0}from"node:timers/promises";import{domainToUnicode as D0}from"node:url";import{applyEdits as q2,createScanner as b0,findNodeAtLocation as B0,modify as l2,parse as V0,parseTree as x0}from"jsonc-parser";import{randomUUID as z0}from"node:crypto";import{mkdir as J0,open as Z0,rename as $0,stat as K0,unlink as Q0}from"node:fs/promises";import{basename as W0,dirname as X0,join as G0}from"node:path";import{setTimeout as j0}from"node:timers/promises";async function u2(z,J,Z={}){let $=(Z.platform??process.platform)==="win32",K=X0(z);await J0(K,{recursive:!0});let Q;if(!$)try{Q=(await K0(z)).mode&4095}catch(V){if(V.code!=="ENOENT")throw V}let W=G0(K,`.${W0(z)}.${(Z.stageName??z0)()}.tmp`),G=!1;try{let V=await Z0(W,"wx",Q??438);G=!0;try{if(await V.writeFile(J,"utf8"),Q!==void 0)await V.chmod(Q)}finally{await V.close()}let X=Z.now??(()=>performance.now()),q=X();for(let b=0;;b++){await Z.beforeRename?.();try{await(Z.rename??$0)(W,z),G=!1;return}catch(x){let Y=x.code,H=2000-(X()-q);if(!$||!["EPERM","EBUSY","EACCES"].includes(Y??"")||H<=0||b>=40)throw Error(`Unable to replace host config ${z}. Close editors or other programs using the file, then rerun setup.`);await(Z.wait??j0)(Math.min(H,25*2**Math.min(b,2)))}}}finally{if(G)await Q0(W).catch(()=>{})}}function a2(z){let J=typeof z==="string"?z:Array.isArray(z)?z[0]:z&&typeof z==="object"&&("package"in z)?z.package:null;return typeof J==="string"?J:null}function Y2(z){let J=a2(z);if(J===null)return null;let Z=J.indexOf("@",J.startsWith("@")?1:0);return Z<0?J:J.slice(0,Z)}function U0(z,J){let Z=new URL(z);if(/%2f/i.test(Z.pathname)||J&&/%5c/i.test(Z.pathname))throw Error("Encoded path separators are not valid in a file URL.");let $=decodeURIComponent(Z.pathname);if(!J){if(Z.hostname)throw Error("A POSIX file URL must be local.");return $}let K=$.replaceAll("/","\\");if(Z.hostname)return`\\\\${D0(Z.hostname)}${K}`;if(!/^\\[a-z]:/i.test(K))throw Error("A Windows file URL must have an absolute drive path.");return K.slice(1)}function F0(z,J,Z){let{path:$,platform:K}=k(Z);try{let Q=/^file:\/\//i.test(z)?U0(z,K==="win32"):$.isAbsolute(z)||z.startsWith(".")?$.resolve($.dirname(J),z):null;if(Q===null)return null;let W=JSON.parse((Z.fs??S).readText($.join(Q,"package.json")));return W&&typeof W==="object"&&"name"in W&&typeof W.name==="string"?W.name:null}catch{return null}}function s2(z,J){let Z=[],$=V0(z,Z,{allowTrailingComma:!0});if(Z.length||!$||typeof $!=="object"||Array.isArray($))throw Error("Invalid OpenCode config; refusing to overwrite it.");if($[J]!==void 0&&!Array.isArray($[J]))throw Error(`OpenCode ${J} must be an array.`);return $}function i2(z,J,Z){let $=x0(z),K=$&&B0($,[J]),Q=K?.children??[],W=Q[Z];if(!W||!K)throw Error("Invalid plugin array edit.");let G=[{offset:W.offset,length:W.length,content:""}],V=(X,q)=>{let b=b0(z.slice(X,q),!0);if(b.scan(),z[X+b.getTokenOffset()]===",")G.push({offset:X+b.getTokenOffset(),length:1,content:""})};if(Z===Q.length-1){let X=Q[Z-1];if(X)V(X.offset+X.length,W.offset);V(W.offset+W.length,K.offset+K.length-1)}else V(W.offset+W.length,Q[Z+1]?.offset??W.offset+W.length);return q2(z,G)}function o2(z,J,Z,$){let K=s2(z,J),Q={formattingOptions:{insertSpaces:!/^\t+/m.test(z),tabSize:/^([ ]+)"/m.exec(z)?.[1]?.length??2,eol:z.includes(`\r
|
|
8
|
+
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=J,this.name="ProcessFenceViolationError"}}async function G2(z=w,J={}){let Z=(J.platform??process.platform)==="win32",$=J.env??process.env,K=Z?t.resolve(d($,"SystemRoot")??d($,"windir")??"C:\\Windows","System32"):"",Q=J.selfPid??process.pid,W={step:Z?"tasklist":"ps",exitCode:null,signal:null,timedOut:!1,durationMs:0},G=async(X,q,b,x,Y)=>{let H=performance.now();W={step:X,...Y&&{program:Y},exitCode:null,signal:null,timedOut:!1,durationMs:0};try{let D=await z.run(q,b,{env:J.env,timeoutMs:x});return W={step:X,...Y&&{program:Y},exitCode:D.exitCode,signal:D.signal??null,timedOut:D.timedOut??!1,durationMs:D.durationMs??performance.now()-H},D}finally{if(W.exitCode===null)W.durationMs=performance.now()-H;J.onStep?.({...W})}},V=async(X)=>{let q=t.resolve(d($,"ProgramFiles")??"C:\\Program Files","PowerShell","7","pwsh.exe"),b=(J.isFile??p0)(q)?"pwsh":"powershell",x=(d($,"PROCESSOR_ARCHITEW6432")??d($,"PROCESSOR_ARCHITECTURE"))?.toUpperCase()==="ARM64",Y=b==="powershell"&&x;if(Y)J.onProgress?.("Checking that OpenCode and Pi are not running. Without PowerShell 7 this can take up to a minute on Windows ARM; installing PowerShell 7 makes it fast.");let H=b==="pwsh"?q:t.resolve(K,"WindowsPowerShell","v1.0","powershell.exe"),D=Y?d0:h0,j=performance.now(),U=await G("CIM",H,X,D,b),O=Math.floor(D-(performance.now()-j));if((U.exitCode===3221225477||U.exitCode===-1073741819)&&!U.timedOut&&!U.signal&&!U.spawnError&&O>0)return m0.warn("Windows process query crashed with an access violation; retrying once"),G("CIM",H,X,O,b);return U};try{if(Z&&J.hostImagesOnly){let x=await V(["-NoProfile","-NonInteractive","-Command",u0]);if(x.exitCode!==0)throw new R(W);let Y=JSON.parse(x.stdout);if(!Y||typeof Y!=="object"||!("complete"in Y)||Y.complete!==!0||!("processes"in Y))throw new R(W);let H=Y.processes,D=H===null?[]:Array.isArray(H)?H:[H],j=[];for(let U of D){if(!U||typeof U!=="object"||!("Name"in U)||typeof U.Name!=="string"||!("ProcessId"in U)||!Number.isSafeInteger(U.ProcessId)||U.ProcessId<0||!("CommandLine"in U))throw new R(W);let O=U.ProcessId;if(!/^(?:node|bun)\.exe$/i.test(U.Name))j.push({pid:O,command:U.Name});else if(typeof U.CommandLine==="string")j.push({pid:O,command:U.CommandLine});else if(O!==Q)throw new R(W)}return j}let X=await G(Z?"tasklist":"ps",Z?t.resolve(K,"tasklist.exe"):"ps",Z?["/fo","csv","/nh"]:["-eo","pid,command"]);if(X.exitCode!==0)throw new R(W);let q=[];for(let x of X.stdout.split(/\r?\n/)){let Y=x.trim();if(!Y)continue;let H,D;if(Z){let j=/^"([^"]+)","(\d+)"(?:,|$)/.exec(Y);if(!j)throw new R(W);D=j[1]??"",H=Number(j[2])}else{let j=/^(\d+)\s+(.+)$/.exec(Y);if(!j){if(/^PID\s+COMMAND$/i.test(Y))continue;throw new R(W)}H=Number(j[1]),D=j[2]??""}if(!Number.isSafeInteger(H)||H<0)throw new R(W);q.push({pid:H,command:D})}if(!q.length)throw new R(W);let b=q.filter((x)=>x.pid!==Q&&/^(?:node|bun)\.exe$/i.test(x.command));if(Z&&b.length&&J.inspectRuntimes!==!1){let x=await V(["-NoProfile","-NonInteractive","-Command",`$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process -Filter "Name = 'node.exe' OR Name = 'bun.exe'" | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress`]);if(x.exitCode!==0)throw new R(W);let Y=JSON.parse(x.stdout||"null"),H=Y===null?[]:Array.isArray(Y)?Y:[Y],D=new Map;for(let j of H){if(!j||typeof j!=="object"||!("ProcessId"in j)||!("CommandLine"in j)||!Number.isSafeInteger(j.ProcessId))throw new R(W);if(typeof j.CommandLine==="string")D.set(Number(j.ProcessId),j.CommandLine);else if(b.some((U)=>U.pid===j.ProcessId))throw new R(W)}for(let j of b)j.command=D.get(j.pid)??""}return q}catch(X){if(X instanceof R)throw X;throw new R(W)}}function p(z=w,J={}){let Z=J.selfPid??process.pid,$=(K)=>K.pid!==Z&&w2(K.command)!==null;return{async listRunningHosts(K){return(await G2(z,{...J,env:K,hostImagesOnly:!0})).filter($)},async previewRunningHosts(K){let Q=await G2(z,{...J,env:K,inspectRuntimes:!1}),W=(J.platform??process.platform)==="win32";return{hosts:Q.filter($),uncheckedRuntimes:W?Q.filter((G)=>G.pid!==Z&&/^(?:node|bun)\.exe$/i.test(G.command)).length:0}}}}async function c(z,J){let Z=await z.listRunningHosts(J);if(Z.length)throw new y(Z)}class f{inspect;now;#z;constructor(z,J=()=>performance.now()){this.inspect=z,this.now=J}async check(z={}){if(z.reuse&&this.#z!==void 0){let J=this.now()-this.#z;if(J>=0&&J<5000)return}this.#z=void 0,await this.inspect(),this.#z=this.now()}async step(z){this.#z=void 0;try{return await z()}finally{this.#z=void 0}}}var t0="Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.",g2='This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), or run setup without --claustrum to use local accounts.',h2=300000,S2=1000,v2=[1000,2000,4000,8000,16000,30000];function j2(z){return z&&/^[a-z][a-z0-9_]{0,63}$/.test(z)?z:"unknown"}class _ extends Error{reason;lastErrorCode;constructor(z,J){super(z);if(this.name="HostNotEnrolledError",this.reason=J.reason,J.lastErrorCode!==void 0)this.lastErrorCode=j2(J.lastErrorCode)}}function E2(z,J){return`ck auth enroll approve --request-id ${z} --name ${J}`}async function m2(z,J,Z,$,K){if(e())throw Error(g);let{name:Q,displayName:W,requestedGrants:G,grantFallback:V,paths:X}=z.vault.hosts[J],q=A(X),b=typeof K==="function"?new f(K,Z.now):K;await b.check({reuse:!0});let x=await(Z.connect??n)({connectionFile:z.vault.connectionFile,handshakeTimeoutMs:2000}).catch(()=>{throw new _("Claustrum connection failed; start ck and rerun setup.",{reason:"connection-failed"})}),Y=Z.now??(()=>performance.now()),H=Z.wait??r0;try{let D=new f2({proposedName:Q,displayName:W,requestedGrants:G,paths:q,client:x,writeTokenFile:async(M,L)=>{await b.check(),await b.step(()=>n0(M,L))}}),j=await D.status();if(j.state==="approved"){F($,`Already connected as ${j.approvedName??j.proposedName}.`);let M=await h(x,j,q.tokenPath,G);if(M)for(let L of m(M,V))F($,L);return M}F($,`Asking the vault to connect ${Q}…`);let U=Y()+h2,O,B,I,T=0;for(;;){await b.check({reuse:!0});let M=await b.step(()=>D.reconcile());if(M.state==="approved"){F($,`Connected ${J} to Claustrum.`);let E=await h(x,M,q.tokenPath,G);if(E)for(let b0 of m(E,V))F($,b0);return E}if(M.state==="unavailable"&&M.code===y2)throw new _(g2,{reason:"unsupported-vault",lastErrorCode:M.code});if(M.state!=="pending"&&M.state!=="busy")throw new _("Claustrum enrollment refused; inspect its status with ck before rerunning setup.",{reason:"refused",..."code"in M&&{lastErrorCode:M.code}});let L=S2;if(M.state==="busy")B="busy";else if(M.retryCode)B=M.retryCode;if(M.state==="pending"&&M.requestId){if(T=0,M.requestId!==O){if(!/^[a-zA-Z0-9_-]+$/.test(M.requestId))throw new _("Invalid enrollment request id.",{reason:"invalid-request"});O=M.requestId,F($,"Waiting for approval. In another terminal, run:"),F($,` ${E2(M.requestId,Q)}`),F($,`Enrollment files: ${q.statePath}, ${q.tokenPath}`)}}else if(M.state==="pending"&&M.retryCode){L=v2[Math.min(T,v2.length-1)]??S2,T++;let E=j2(M.retryCode);if(E!==I)I=E,F($,`The vault has not created the request yet (${E}); retrying.`)}let M2=U-Y();if(M2<=0)break;await b.step(()=>H(Math.min(L,M2))),await b.check()}if(O)throw new _(`Claustrum approval is still pending. In another terminal, run: ${E2(O,Q)} and then rerun setup.`,{reason:"approval-pending",...B!==void 0&&{lastErrorCode:B}});let C=j2(B);throw new _(`The vault never created the enrollment request (last error: ${C}). Check that ck is running, then rerun setup.`,{reason:"request-not-created",lastErrorCode:C})}catch(D){if(D instanceof y||D instanceof R||D instanceof _)throw D;let j=D?.code;throw new _(t0,{reason:"incomplete",...typeof j==="string"&&{lastErrorCode:j}})}finally{x.close()}}var d2="Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",e0=[{name:"--yes",key:"yes",description:"Run without questions and set up every found host. Does not choose the vault."},{name:"--dry-run",key:"dryRun",description:"Print what setup would do without changing anything."},{name:"--host",key:"hosts",values:["opencode","pi"],spaceForm:!0,invalid:"Requested setup host is unknown or unavailable. Use --host=opencode or --host=pi with a detected host.",description:"Set up only this host; repeat the flag for both. Also written --host=<host>."},{name:"--opencode",key:"opencode",values:["1","2","both"],description:"Register for this OpenCode generation."},{name:"--claustrum",key:"claustrum",description:"Connect the hosts to the Claustrum vault."},{name:"--no-claustrum",key:"noClaustrum",description:"Do not offer the Claustrum vault; sign in locally."},{name:"--login",key:"login",description:"Sign in locally instead of using the Claustrum vault."},{name:"--enroll-only",key:"enrollOnly",description:"Only connect the hosts to the Claustrum vault; register nothing and migrate nothing."}];function z2(z){return Error(`Unknown setup argument: ${z}. Run the plugin's own setup --help to list the flags setup accepts.`)}function p2(z){let J={yes:!1,dryRun:!1,claustrum:!1,noClaustrum:!1,login:!1,enrollOnly:!1,hosts:[],opencode:void 0};for(let Z=0;Z<z.length;Z++){let $=z[Z],K=$.indexOf("="),Q=K===-1?$:$.slice(0,K),W=e0.find((V)=>V.name===Q);if(!W)throw z2($);if(!("values"in W)){if(K!==-1)throw z2($);J[W.key]=!0;continue}let G;if(K!==-1)G=$.slice(K+1);else if(W.spaceForm)G=z[++Z];else throw z2($);if(G===void 0||!W.values.includes(G))throw W.invalid?Error(W.invalid):z2($);if(W.key==="hosts")J.hosts.push(G);else J.opencode=G}if(J.claustrum&&J.noClaustrum)throw Error("--claustrum and --no-claustrum cannot be used together.");if(J.login&&J.claustrum)throw Error("--login and --claustrum cannot be used together.");if(J.enrollOnly&&J.login)throw Error("--enroll-only and --login cannot be used together.");if(J.enrollOnly&&J.noClaustrum)throw Error("--enroll-only and --no-claustrum cannot be used together.");return J}async function c2(z,J){let Z=new Set(J);for(;;){let $=await u(z,[...["opencode","pi"].map((K)=>({value:K,label:`[${Z.has(K)?"x":" "}] ${K==="opencode"?"OpenCode":"Pi"}`,hint:J.includes(K)?"found":"not found"})),{value:"done",label:"Continue with selected hosts"}],{message:"Select hosts to set up",subtitle:"Enter toggles a host; choose Continue when ready."});if($===null)return null;if($==="done")return[...Z];if(Z.has($))Z.delete($);else Z.add($)}}import{rename as q1}from"node:fs/promises";import{setTimeout as Y1}from"node:timers/promises";import{domainToUnicode as D1}from"node:url";import{applyEdits as q2,createScanner as b1,findNodeAtLocation as B1,modify as l2,parse as V1,parseTree as x1}from"jsonc-parser";import{randomUUID as z1}from"node:crypto";import{mkdir as J1,open as Z1,rename as $1,stat as K1,unlink as Q1}from"node:fs/promises";import{basename as W1,dirname as X1,join as G1}from"node:path";import{setTimeout as j1}from"node:timers/promises";async function u2(z,J,Z={}){let $=(Z.platform??process.platform)==="win32",K=X1(z);await J1(K,{recursive:!0});let Q;if(!$)try{Q=(await K1(z)).mode&4095}catch(V){if(V.code!=="ENOENT")throw V}let W=G1(K,`.${W1(z)}.${(Z.stageName??z1)()}.tmp`),G=!1;try{let V=await Z1(W,"wx",Q??438);G=!0;try{if(await V.writeFile(J,"utf8"),Q!==void 0)await V.chmod(Q)}finally{await V.close()}let X=Z.now??(()=>performance.now()),q=X();for(let b=0;;b++){await Z.beforeRename?.();try{await(Z.rename??$1)(W,z),G=!1;return}catch(x){let Y=x.code,H=2000-(X()-q);if(!$||!["EPERM","EBUSY","EACCES"].includes(Y??"")||H<=0||b>=40)throw Error(`Unable to replace host config ${z}. Close editors or other programs using the file, then rerun setup.`);await(Z.wait??j1)(Math.min(H,25*2**Math.min(b,2)))}}}finally{if(G)await Q1(W).catch(()=>{})}}function a2(z){let J=typeof z==="string"?z:Array.isArray(z)?z[0]:z&&typeof z==="object"&&("package"in z)?z.package:null;return typeof J==="string"?J:null}function Y2(z){let J=a2(z);if(J===null)return null;let Z=J.indexOf("@",J.startsWith("@")?1:0);return Z<0?J:J.slice(0,Z)}function U1(z,J){let Z=new URL(z);if(/%2f/i.test(Z.pathname)||J&&/%5c/i.test(Z.pathname))throw Error("Encoded path separators are not valid in a file URL.");let $=decodeURIComponent(Z.pathname);if(!J){if(Z.hostname)throw Error("A POSIX file URL must be local.");return $}let K=$.replaceAll("/","\\");if(Z.hostname)return`\\\\${D1(Z.hostname)}${K}`;if(!/^\\[a-z]:/i.test(K))throw Error("A Windows file URL must have an absolute drive path.");return K.slice(1)}function F1(z,J,Z){let{path:$,platform:K}=k(Z);try{let Q=/^file:\/\//i.test(z)?U1(z,K==="win32"):$.isAbsolute(z)||z.startsWith(".")?$.resolve($.dirname(J),z):null;if(Q===null)return null;let W=JSON.parse((Z.fs??S).readText($.join(Q,"package.json")));return W&&typeof W==="object"&&"name"in W&&typeof W.name==="string"?W.name:null}catch{return null}}function s2(z,J){let Z=[],$=V1(z,Z,{allowTrailingComma:!0});if(Z.length||!$||typeof $!=="object"||Array.isArray($))throw Error("Invalid OpenCode config; refusing to overwrite it.");if($[J]!==void 0&&!Array.isArray($[J]))throw Error(`OpenCode ${J} must be an array.`);return $}function i2(z,J,Z){let $=x1(z),K=$&&B1($,[J]),Q=K?.children??[],W=Q[Z];if(!W||!K)throw Error("Invalid plugin array edit.");let G=[{offset:W.offset,length:W.length,content:""}],V=(X,q)=>{let b=b1(z.slice(X,q),!0);if(b.scan(),z[X+b.getTokenOffset()]===",")G.push({offset:X+b.getTokenOffset(),length:1,content:""})};if(Z===Q.length-1){let X=Q[Z-1];if(X)V(X.offset+X.length,W.offset);V(W.offset+W.length,K.offset+K.length-1)}else V(W.offset+W.length,Q[Z+1]?.offset??W.offset+W.length);return q2(z,G)}function o2(z,J,Z,$){let K=s2(z,J),Q={formattingOptions:{insertSpaces:!/^\t+/m.test(z),tabSize:/^([ ]+)"/m.exec(z)?.[1]?.length??2,eol:z.includes(`\r
|
|
9
9
|
`)?`\r
|
|
10
10
|
`:`
|
|
11
11
|
`}},W=z,G=K[J],V=Array.isArray(G)?[...G]:[],X=V.flatMap((x,Y)=>Y2(x)===Z?[Y]:[]),q=`${Z}@${$}`;if(!X.length)W=q2(W,l2(W,G===void 0?[J]:[J,V.length],G===void 0?[q]:q,Q));else{let x=X[0],Y=V[x],H=Array.isArray(Y)?[q,...Y.slice(1)]:Y&&typeof Y==="object"?{...Y,package:q}:q;if(JSON.stringify(Y)!==JSON.stringify(H))W=q2(W,l2(W,[J,x],H,Q));for(let D of X.slice(1).reverse())W=i2(W,J,D)}let b=J==="plugin"?"plugins":"plugin";if(Array.isArray(K[b])){let x=K[b];for(let Y=x.length-1;Y>=0;Y--)if(Y2(x[Y])===Z)W=i2(W,b,Y)}return W}function D2(z,J,Z={}){let $=Z.fs??S,{path:K,opencode:Q}=k(Z),W=J==="2"?"plugins":"plugin";return(J==="2"?["opencode"]:["opencode","tui"]).map((V)=>{let X=K.join(Q,`${V}.jsonc`),q=K.join(Q,`${V}.json`),b=$.exists(X)?X:$.exists(q)?q:X,x=$.exists(b),Y=x?$.readText(b):`${JSON.stringify({$schema:`https://opencode.ai/${V==="tui"?"tui":"config"}.json`},null,2)}
|
|
12
|
-
`,H=s2(Y,W),D=[],j=[];for(let O of["plugin","plugins"]){if(!Array.isArray(H[O]))continue;for(let B of H[O]){let I=a2(B);if(I===null)continue;if(
|
|
13
|
-
${B.content}`);if(!$.enrollOnly&&X.includes("pi"))F(K,`Would run ${Q.pi.executable} install npm:${z.packages.pi}@${z.version}`);if(!$.enrollOnly&&z.migrate)for(let B of X)F(K,`Would migrate ${B} using the plugin callback (provider-specific writes).`)}else{let B={opencodeGeneration:q,mode:U,hosts:Object.freeze([...X]),piAgentDir:Q.pi.directory},I=new Map,T=new Map;try{for(let C of X){if(z.beforeSignIn)await D.check({reuse:!0}),await D.step(()=>z.beforeSignIn?.(C,B));if(j){I.set(C,"unknown");try{let M=await m2(z,C,Z,K,D);if(M)T.set(C,M)}catch(M){if(M instanceof _)I.set(C,"not-enrolled");throw M}I.set(C,"enrolled")}else await D.check({reuse:!0}),await D.step(()=>z.signInLocal(C,B));if($.enrollOnly)continue;if(z.beforeRegister)await D.check({reuse:!0}),await D.step(()=>z.beforeRegister?.(C,U,B));if(C==="opencode")await b2(O,D);else await D.check({reuse:!0}),await D.step(()=>B2(z,Q.pi.executable,Z));if(z.migrate)await D.check({reuse:!0}),await D.step(()=>z.migrate?.(C,B))}}catch(C){if(I.size===0)throw C;try{let M=await
|
|
14
|
-
${Y.instructions}`);let D=await Y.completion;await c(Z),await K(Q),await G.set({...V,body:{type:"oauth",access:D.access,refresh:D.refresh,expires:D.expires,...D.accountId?{accountId:D.accountId}:{}}}),J("Signed in to OpenCode. The first plugin start adopts this login into the account pool.")},async migrate(Q){J(`${Q}: account migration runs on first plugin start; setup leaves existing credentials unchanged.`)}}}if(process.argv[2]!=="setup")console.log("Usage: opencode-openai-auth setup [options]");else try{await
|
|
12
|
+
`,H=s2(Y,W),D=[],j=[];for(let O of["plugin","plugins"]){if(!Array.isArray(H[O]))continue;for(let B of H[O]){let I=a2(B);if(I===null)continue;if(F1(I,b,Z)===z.packages.opencode)D.push(JSON.stringify(B));else if(Y2(B)===z.packages.opencode)j.push(JSON.stringify(B))}}if(D.length>0)return{path:b,content:Y,changed:!1,existingLocalEntries:D,existingNpmEntries:j};let U=o2(Y,W,z.packages.opencode,z.version);return{path:b,content:U,changed:!x||U!==Y}})}async function b2(z,J){let Z=typeof J==="function"?new f(J):J;for(let $ of z){if(!$.changed)continue;await u2($.path,$.content,{beforeRename:Z?()=>Z.check({reuse:!0}):void 0,rename:Z?(K,Q)=>Z.step(()=>q1(K,Q)):void 0,wait:Z?(K)=>Z.step(()=>Y1(K)):void 0})}}async function B2(z,J,Z={}){let{platform:$,env:K}=k(Z),Q=await o(Z.runner??w,$,J,["install",`npm:${z.packages.pi}@${z.version}`],K);if(Q.exitCode!==0||Q.timedOut)throw new r({exitCode:Q.spawnError?null:Q.exitCode,signal:Q.signal??null,stderrTail:Q.stderr,stderrTruncated:Q.stderrTruncated??!1})}var e2="Multiple OpenCode generations found. Choose --opencode=1|2|both before running noninteractive setup.";function H1(z){for(let J of Object.values(z.packages))if(!/^(?:@[a-z0-9._-]+\/)?[a-z0-9._-]+$/.test(J))throw Error("Setup requires npm package names.");if(!/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?$/.test(z.version))throw Error("Setup requires a concrete package version.");for(let J of Object.values(z.vault.hosts)){if(!/^[a-z0-9][a-z0-9-]*$/.test(J.name))throw Error("Setup requires lowercase vault names containing only letters, digits and dashes.");if(J.requestedGrants!==void 0&&!r2(J.requestedGrants))throw Error("invalid Claustrum enrollment requested grants");if(J.grantFallback!==void 0&&J.grantFallback!=="setup"&&J.grantFallback!=="plugin")throw Error("invalid Claustrum enrollment grant fallback")}}async function M1(z,J,Z,$){let K=[];for(let Q of J){let W=Z.get(Q)??"not-enrolled",G=$.get(Q);if(W==="unknown"){let{name:V,paths:X}=z.vault.hosts[Q],q=await i(A(X),V).catch(()=>"unreadable");if(q==="vault"||q==="host")W="enrolled";else if(q==="local")W="not-enrolled";if(W==="enrolled"){let b=await n2(A(X),V).catch(()=>{return});if(b?.state==="approved")G=await h({},b,A(X).tokenPath,z.vault.hosts[Q].requestedGrants)}}K.push({host:Q,outcome:W,...G&&{access:G}})}return K}async function V2(z,J=[],Z={}){let $=p2(J);if(e())throw Error(g);H1(z);let K=Z.terminal??t2(),Q=await W2(z,Z);F(K,`${z.displayName} setup`);for(let[B,I]of[["OpenCode",Q.opencode],["Pi",Q.pi]])F(K,`${B}: ${I.installed?`found (version ${I.version??"unknown"})`:"not found"} — ${I.directory}`);F(K,`Claustrum: ${Q.claustrum.available?"available":"not available"}`);let W=Q.pi.installed&&!Q.pi.executable;if(W)F(K,"Pi: skipped, because its folder exists but pi is not on PATH. Install the Pi CLI and rerun setup to add it.");let G=["opencode","pi"].filter((B)=>Q[B].installed&&!(B==="pi"&&W));if($.hosts.some((B)=>!G.includes(B)))throw Error(d2);let V=$.yes||$.dryRun&&!l(K);if(!V&&!l(K))throw Error("Setup requires a TTY or --yes.");let X=$.hosts.length?G.filter((B)=>$.hosts.includes(B)):V?G:await c2(K,G)??[],q=$.opencode??(Q.opencode.generation==="ambiguous"?"1":Q.opencode.generation);if(X.includes("opencode")&&!$.opencode&&Q.opencode.generation==="ambiguous"){if(V||!l(K))throw Error(e2);let B=await u(K,[{value:"1",label:"OpenCode 1"},{value:"2",label:"OpenCode 2"},{value:"both",label:"Both (one compatible registration)"}],{message:"Which OpenCode generation should be registered?"});if(B===null)return{hosts:[],dryRun:$.dryRun,mode:"local",detection:Q};q=B}if(!X.length)return F(K,"No hosts selected. Install OpenCode or Pi and rerun setup."),{hosts:X,dryRun:$.dryRun,mode:"local",detection:Q};let{env:b,platform:x}=k(Z),Y=Z.fence??p(Z.runner??w,{platform:x,isFile:Z.fs?.isFile.bind(Z.fs),onProgress:(B)=>F(K,B)}),D=new f(async()=>{try{await c(Y,b)}catch(B){if(B instanceof R)F(K,B.refusalText);throw B}},Z.now);if(F(K,"Checking that OpenCode and Pi are not running…"),$.dryRun)try{let B=Y.previewRunningHosts?await Y.previewRunningHosts(b):{hosts:await Y.listRunningHosts(b),uncheckedRuntimes:0},I=B.hosts;if(B.uncheckedRuntimes>0)F(K,"Node or Bun programs are running; a real run checks whether any of them is OpenCode or Pi.");let T=new Set(new y(I).activeHosts.map((C)=>C.command.toLowerCase()==="pi"?"Pi":"OpenCode"));for(let C of T)F(K,`${C} is running; setup will ask you to quit it.`)}catch(B){if(F(K,"Process inspection failed; real setup will require successful inspection and stopped OpenCode/Pi hosts."),B instanceof R)F(K,B.refusalText)}else await D.check();if(($.claustrum||$.enrollOnly)&&!Q.claustrum.available)throw Error("Claustrum is not available. Start ck, or omit vault-only flags and use --no-claustrum for local sign-in.");let j=$.claustrum||$.enrollOnly;if(!j&&!$.login&&!$.noClaustrum&&!V&&Q.claustrum.available&&l(K)){let B=await D.step(()=>u(K,[{label:"No",value:!1},{label:"Yes",value:!0}],{message:"Connect these hosts to the Claustrum vault?"}));if(B===null)return F(K,"Setup cancelled. Nothing was changed."),{hosts:[],dryRun:$.dryRun,mode:"local",detection:Q};j=B===!0}let U=j?"claustrum":"local",O=!$.enrollOnly&&X.includes("opencode")?D2(z,q,Z):[];for(let B of O){for(let T of B.existingLocalEntries??[])F(K,`OpenCode: already registered from ${T} in ${B.path}.`);let I=[...B.existingLocalEntries??[],...B.existingNpmEntries??[]];if(I.length>1)F(K,`Warning: ${z.displayName} may load twice in ${B.path}: ${I.join(", ")}. Entries were left unchanged.`)}if($.dryRun){F(K,"Dry run: no registrations, enrollment, sign-in or migration will be performed.");for(let B of X){if(z.beforeSignIn)F(K,`Would run beforeSignIn(${B}, ${U}).`);if(j){let I=A(z.vault.hosts[B].paths);F(K,`Would Connect ${B}: write ${I.statePath} and ${I.tokenPath}; wait for ck auth enroll approve.`)}else F(K,`Would sign in locally for ${B}.`);if(!$.enrollOnly&&z.beforeRegister)F(K,`Would run beforeRegister(${B}, ${U}).`)}for(let B of O)F(K,`${B.changed?"Would write":"Unchanged"} ${B.path}:
|
|
13
|
+
${B.content}`);if(!$.enrollOnly&&X.includes("pi"))F(K,`Would run ${Q.pi.executable} install npm:${z.packages.pi}@${z.version}`);if(!$.enrollOnly&&z.migrate)for(let B of X)F(K,`Would migrate ${B} using the plugin callback (provider-specific writes).`)}else{let B={opencodeGeneration:q,mode:U,hosts:Object.freeze([...X]),piAgentDir:Q.pi.directory},I=new Map,T=new Map;try{for(let C of X){if(z.beforeSignIn)await D.check({reuse:!0}),await D.step(()=>z.beforeSignIn?.(C,B));if(j){I.set(C,"unknown");try{let M=await m2(z,C,Z,K,D);if(M)T.set(C,M)}catch(M){if(M instanceof _)I.set(C,"not-enrolled");throw M}I.set(C,"enrolled")}else await D.check({reuse:!0}),await D.step(()=>z.signInLocal(C,B));if($.enrollOnly)continue;if(z.beforeRegister)await D.check({reuse:!0}),await D.step(()=>z.beforeRegister?.(C,U,B));if(C==="opencode")await b2(O,D);else await D.check({reuse:!0}),await D.step(()=>B2(z,Q.pi.executable,Z));if(z.migrate)await D.check({reuse:!0}),await D.step(()=>z.migrate?.(C,B))}}catch(C){if(I.size===0)throw C;try{let M=await M1(z,X,I,T);k2(C,M);for(let L of M)F(K,N2(L,z.vault.hosts[L.host].grantFallback))}catch{}throw C}}if(F(K,`${$.dryRun?"Planned":$.enrollOnly?"Enrolled":"Configured"} ${z.displayName} for ${X.join(", ")} (${U}).`),$.enrollOnly)F(K,`Enroll-only: no host config or plugin registration ${$.dryRun?"will be":"was"} written.`),F(K,"Next: register the plugin yourself in each selected host and enable vault access as required by the plugin.");else F(K,`Next: ${X.includes("opencode")?"start OpenCode":"start Pi"} and run ${z.slashCommand}.`);return{hosts:X,dryRun:$.dryRun,mode:U,detection:Q}}var v={name:"@cortexkit/opencode-openai-auth",version:"1.23.2",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/opencode"},main:"./dist/index.js",types:"./dist/index.d.ts",bin:{"opencode-openai-auth":"./dist/bin.js"},exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"},"./tui":{types:"./dist/tui.d.ts",import:"./src/tui/entry.mjs"},"./tui-prefs":{types:"./dist/tui-preferences.d.ts",import:"./dist/tui-preferences.js"},"./server":{types:"./dist/v2/server.d.ts",import:"./dist/v2/server.js"}},"oc-plugin":["server","tui"],engines:{bun:"1.3.14"},files:["dist","src/tui/entry.mjs","src/tui-compiled","README.md","LICENSE"],scripts:{build:"rm -rf dist && bun build src/index.ts src/v2/server.ts src/sidebar-state.ts src/tui-preferences.ts src/rpc/rpc-client.ts src/rpc/port-file.ts src/rpc/protocol.ts src/rpc/rpc-dir.ts src/bin.ts --root src --outdir dist --target node --format esm --splitting --external @opencode-ai/plugin --external @opencode/plugin --external @cortexkit/private-files --external jsonc-parser --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types && bun run build:tui && cp ../core/openai-auth.schema.json dist/openai-auth.schema.json","build:tui":"bun scripts/build-tui.ts","build:types":"cd ../core && bun run build && cd ../opencode && tsdown --config tsdown.config.ts --config-loader native","build:dev":"rm -rf dist && tsc -p tsconfig.build.json",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},peerDependencies:{"@opencode-ai/plugin":"*","@opencode/plugin":">=2.0.21"},peerDependenciesMeta:{"@opencode/plugin":{optional:!0}},devDependencies:{"@ai-sdk/openai":"3.0.88","@cortexkit/common-auth":"^0.59.1","@cortexkit/openai-auth-core":"workspace:*","@cortexkit/opencode-sidebar":"0.3.0","@opencode/plugin":"2.3.2"},dependencies:{"@cortexkit/claustrum-client":"^0.22.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.26.8","@opentui/core":">=0.9.7","@opentui/solid":">=0.9.7",ai:"^7.0.179","jsonc-parser":"^3.3.1","solid-js":"1.9.18"}};import{basename as k1}from"node:path";import{resolveClaustrumConnectionPath as _1}from"@cortexkit/claustrum-client";var z0={name:"@cortexkit/pi-openai-auth",version:"1.23.2",license:"MIT",type:"module",repository:{type:"git",url:"git+https://github.com/cortexkit/openai-auth.git",directory:"packages/pi"},main:"./dist/index.js",types:"./dist/index.d.ts",exports:{".":{import:"./dist/index.js",types:"./dist/index.d.ts"}},files:["dist","README.md","LICENSE"],keywords:["pi-package"],pi:{extensions:["./dist/index.js"]},scripts:{build:"rm -rf dist && bun build src/index.ts --outdir dist --target node --format esm --external '@earendil-works/pi-ai' --external '@earendil-works/pi-ai/*' --external '@earendil-works/pi-coding-agent' --external '@earendil-works/pi-coding-agent/*' --external '@earendil-works/pi-tui' --external '@earendil-works/pi-tui/*' --external @cortexkit/private-files --external jsonc-parser --external @cortexkit/claustrum-client --external @cortexkit/subc-client --minify && bun run build:types && cp ../core/openai-auth.schema.json dist/openai-auth.schema.json","build:types":"cd ../core && bun run build && cd ../pi && tsdown --config tsdown.config.ts --config-loader native",test:"bun test src/tests",typecheck:"tsc",types:"tsc",prepublishOnly:"bun run build"},devDependencies:{"@cortexkit/common-auth":"^0.59.1","@cortexkit/openai-auth-core":"workspace:*"},dependencies:{"@cortexkit/claustrum-client":"^0.22.0","@cortexkit/private-files":"^0.2.2","@cortexkit/subc-client":"^0.26.8","jsonc-parser":"^3.3.1"},peerDependencies:{"@earendil-works/pi-ai":">=1.0.1","@earendil-works/pi-coding-agent":">=1.0.1","@earendil-works/pi-tui":">=1.0.1"}};import{existsSync as J2}from"node:fs";import{homedir as Z2}from"node:os";import{join as $2,resolve as J0}from"node:path";import{fileURLToPath as C1}from"node:url";var Z0=new Set;function R1(){let z=process.env.PI_CODING_AGENT_DIR;if(!z)return $2(Z2(),".pi","agent");if(process.platform==="win32"&&z.startsWith("/")&&!z.startsWith("//")&&!z.includes("\\")){let J=z.match(/^\/(?:mnt\/|cygdrive\/)?([a-z])(?:\/(.*))?$/i);if(J?.[1])z=`${J[1].toUpperCase()}:\\${J[2]?.replaceAll("/","\\")??""}`}if(z==="~")return Z2();if(z.startsWith("~/")||process.platform==="win32"&&z.startsWith("~\\"))return $2(Z2(),z.slice(2));return z.startsWith("file://")?C1(z):z}function K0(z=R1()){let J=process.env.PI_OPENAI_AUTH_FILE?.trim();if(J)return J;let Z=$2(z,x2),$=$2(Z2(),".pi","agent",x2),K=(W)=>{let G=U2(W),V=$0(a(G),"pi");return J2(W)||J2(G)||J2(V.tokenPath)||J2(V.statePath)};if(J0(Z)===J0($)||K(Z)||!K($))return Z;let Q=`${Z}\x00${$}`;if(!Z0.has(Q))Z0.add(Q),console.warn(`openai-auth is using its store in the legacy Pi agent directory: ${$} (${Z} has no store). Credentials were not copied or moved. Set PI_OPENAI_AUTH_FILE to choose a store explicitly.`);return $}function N1(z=K0()){return process.env.PI_OPENAI_AUTH_STATE_FILE?.trim()||U2(z)}function Q0(z=K0()){return{configPath:z,statePath:N1(z)}}function Y0(z={}){let J=z.print??console.log,Z=z.fence??(z.createFence??p)(void 0,{onProgress:J}),$={opencode:{stateDir:a(G0().statePath),host:"opencode"},pi:{stateDir:a(Q0().statePath),host:"pi"}},K=async(Q)=>{let W=await i(A($[Q]),s(Q));if(W==="host")throw Error(g);if(W!=="local")throw Error(`${Q} is enrolled in Claustrum or its enrollment is unreadable. Disconnect it from the vault before using local sign-in.`)};return{packages:{opencode:v.name,pi:z0.name},version:v.version,displayName:"OpenAI Auth",slashCommand:"/openai",vault:{connectionFile:_1(),hosts:{opencode:{name:s("opencode"),displayName:H2("opencode"),requestedGrants:F2,paths:$.opencode},pi:{name:s("pi"),displayName:H2("pi"),requestedGrants:F2,paths:$.pi}}},async beforeRegister(Q,W){if(await i(A($[Q]),s(Q))==="host")throw Error(g);if(W==="claustrum"){if(Q==="opencode")J("Then run opencode auth login and choose ChatGPT accounts in the vault to activate vault routing without local sign-in.");return}await K(Q)},async signInLocal(Q,W){if(await K(Q),Q==="pi"){J("Start Pi and run /login openai-codex to sign in with Pi itself.");return}if(W.opencodeGeneration!=="1"){let j=k1(P("opencode2",z.io)??P("opencode",z.io)??"opencode");J(`In OpenCode 2, run ${j} auth login openai and choose "ChatGPT (openai-auth pool, browser)" or "ChatGPT (openai-auth pool, headless)" to sign in to the account pool and activate it.`)}if(W.opencodeGeneration==="2")return;if(j0(process.env))throw Error("Unset OPENCODE_AUTH_CONTENT before local setup sign-in.");let G=q0(),V={path:{id:"openai"}};if(await G.get(V)!==void 0){J("OpenCode already has an OpenAI login. Use opencode auth login to change it.");return}let X=z.beginLogin??W0,q=new AbortController,b=Boolean(process.env.SSH_CONNECTION||process.env.SSH_TTY||process.platform==="linux"&&!process.env.DISPLAY&&!process.env.WAYLAND_DISPLAY),x={version:v.version,signal:q.signal},Y,H=!b;try{Y=await X({...x,headless:b})}catch(j){if(b)throw j;H=!1,J("Browser callback unavailable; using device-code sign-in."),Y=await X({version:v.version,headless:!0})}if(H){if(!(z.openBrowser??X0)(Y.url))q.abort(),await Y.completion.catch(()=>{}),J("Browser unavailable; using device-code sign-in."),Y=await X({version:v.version,headless:!0})}J(`${Y.url}
|
|
14
|
+
${Y.instructions}`);let D=await Y.completion;await c(Z),await K(Q),await G.set({...V,body:{type:"oauth",access:D.access,refresh:D.refresh,expires:D.expires,...D.accountId?{accountId:D.accountId}:{}}}),J("Signed in to OpenCode. The first plugin start adopts this login into the account pool.")},async migrate(Q){J(`${Q}: account migration runs on first plugin start; setup leaves existing credentials unchanged.`)}}}if(process.argv[2]!=="setup")console.log("Usage: opencode-openai-auth setup [options]");else try{await D0({version:v.version}),await V2(Y0(),process.argv.slice(3))}catch(z){console.error(z instanceof Error?z.message:String(z)),process.exitCode=1}
|