@cortexkit/opencode-anthropic-auth 1.22.0 → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +259 -198
- package/dist/billing-lineage.d.ts +51 -0
- package/dist/cli-failure.d.ts +69 -0
- package/dist/cli.d.ts +16 -10
- package/dist/cli.js +111 -6
- package/dist/custody-dimensions.d.ts +19 -0
- package/dist/custody-mode.d.ts +46 -0
- package/dist/effort-history.d.ts +11 -2
- package/dist/fable-fallback.d.ts +1 -1
- package/dist/index-1jkyhgyr.js +2 -0
- package/dist/{index-bx5hsgf8.js → index-2arfb1y3.js} +2 -2
- package/dist/{index-926t2bzc.js → index-4ya27n12.js} +1 -1
- package/dist/{index-cgez4m0h.js → index-aaajxwzd.js} +1 -1
- package/dist/index-ae3fq4n6.js +42 -0
- package/dist/index-fds0s2j4.js +2 -0
- package/dist/index-nngmvczq.js +450 -0
- package/dist/index-pn597b6f.js +2 -0
- package/dist/{index-7f57ewkp.js → index-rqync0pc.js} +1 -1
- package/dist/index.js +1 -33
- package/dist/native-command.d.ts +19 -0
- package/dist/prime-manager-registry.d.ts +5 -1
- package/dist/rpc/notifications.d.ts +4 -3
- package/dist/rpc/port-file.js +1 -1
- package/dist/rpc/protocol.d.ts +15 -4
- package/dist/rpc/protocol.js +1 -1
- package/dist/rpc/rpc-client.d.ts +3 -1
- package/dist/rpc/rpc-client.js +1 -1
- package/dist/rpc/rpc-dir.js +1 -1
- package/dist/rpc/rpc-server.d.ts +5 -1
- package/dist/rpc/server-registry.d.ts +10 -0
- package/dist/setup/activation.d.ts +7 -0
- package/dist/setup/claustrum.d.ts +26 -0
- package/dist/setup/command-runner.d.ts +2 -0
- package/dist/setup/command.d.ts +20 -0
- package/dist/setup/command.test.d.ts +1 -0
- package/dist/setup/detect.d.ts +5 -0
- package/dist/setup/jsonc.d.ts +9 -0
- package/dist/setup/native-activation.d.ts +29 -0
- package/dist/setup/native-enrollment.d.ts +26 -0
- package/dist/setup/native-enrollment.test.d.ts +1 -0
- package/dist/setup/native-local.d.ts +20 -0
- package/dist/setup/native-login.d.ts +3 -0
- package/dist/setup/native-paths.d.ts +15 -0
- package/dist/setup/native-paths.test.d.ts +1 -0
- package/dist/setup/opencode-config.d.ts +18 -0
- package/dist/setup/paths.d.ts +15 -0
- package/dist/setup/pi.d.ts +18 -0
- package/dist/setup/process-fence.d.ts +20 -0
- package/dist/setup/process-fence.test.d.ts +1 -0
- package/dist/setup/types.d.ts +37 -0
- package/dist/sidebar-state.d.ts +3 -1
- package/dist/sidebar-state.js +1 -1
- package/dist/transform.d.ts +5 -1
- package/dist/tui/command-dialogs.d.ts +32 -2
- package/dist/tui-preferences.js +2 -2
- package/dist/v2/activation.d.ts +7 -0
- package/dist/v2/adapter.d.ts +276 -0
- package/dist/v2/install.d.ts +13 -0
- package/dist/v2/lifecycle.d.ts +8 -0
- package/dist/v2/menu-contract.d.ts +8 -0
- package/dist/v2/menu.d.ts +10 -0
- package/dist/v2/models.d.ts +6 -0
- package/dist/v2/ownership.d.ts +11 -0
- package/dist/v2/prime.d.ts +12 -0
- package/dist/v2/rpc.d.ts +50 -0
- package/dist/v2/server.d.ts +8 -0
- package/dist/v2/server.js +4 -0
- package/dist/v2/setup.d.ts +58 -0
- package/dist/v2/source.d.ts +41 -0
- package/dist/v2/tui.d.ts +13 -0
- package/dist/v2/tui.js +2 -0
- package/dist/v2/wire.d.ts +36 -0
- package/package.json +26 -6
- package/src/rpc/notifications.ts +37 -26
- package/src/rpc/protocol.ts +24 -7
- package/src/rpc/rpc-client.ts +18 -1
- package/src/rpc/rpc-server.ts +38 -8
- package/src/rpc/server-registry.ts +61 -0
- package/src/sidebar-state.ts +26 -2
- package/src/tui/command-dialogs.tsx +537 -68
- package/src/tui/entry.mjs +44 -18
- package/src/tui-compiled/rpc/protocol.ts +24 -7
- package/src/tui-compiled/rpc/rpc-client.ts +18 -1
- package/src/tui-compiled/sidebar-state.ts +26 -2
- package/src/tui-compiled/tui/command-dialogs.tsx +488 -95
- package/src/tui-compiled/tui.tsx +25 -7
- package/src/tui.tsx +38 -9
- package/dist/index-8aga2zwv.js +0 -4
- package/dist/index-d3f8g6ve.js +0 -428
- package/dist/index-sh51yqxs.js +0 -2
- package/dist/logger-jrkranbz.js +0 -1
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
export declare const BILLING_LINEAGE_REQUEST_HEADER = "x-cortexkit-billing-lineage";
|
|
2
|
+
interface MessageLike {
|
|
3
|
+
info?: {
|
|
4
|
+
id?: unknown;
|
|
5
|
+
sessionID?: unknown;
|
|
6
|
+
sessionId?: unknown;
|
|
7
|
+
role?: unknown;
|
|
8
|
+
agent?: unknown;
|
|
9
|
+
synthetic?: unknown;
|
|
10
|
+
ignored?: unknown;
|
|
11
|
+
};
|
|
12
|
+
parts?: Array<{
|
|
13
|
+
type?: unknown;
|
|
14
|
+
text?: unknown;
|
|
15
|
+
synthetic?: unknown;
|
|
16
|
+
ignored?: unknown;
|
|
17
|
+
metadata?: Record<string, unknown>;
|
|
18
|
+
}>;
|
|
19
|
+
}
|
|
20
|
+
export interface BillingLineageContext {
|
|
21
|
+
sessionId: string;
|
|
22
|
+
messageId: string;
|
|
23
|
+
promptId: string;
|
|
24
|
+
previousRequestId?: string;
|
|
25
|
+
requestToken: string;
|
|
26
|
+
generation: number;
|
|
27
|
+
sequence: number;
|
|
28
|
+
}
|
|
29
|
+
export interface BillingLineageTrackerOptions {
|
|
30
|
+
createPromptId?: () => string;
|
|
31
|
+
createRequestToken?: () => string;
|
|
32
|
+
maxPrompts?: number;
|
|
33
|
+
maxRequests?: number;
|
|
34
|
+
maxSessions?: number;
|
|
35
|
+
}
|
|
36
|
+
export declare function extractAnthropicRequestId(headers: Headers): string | undefined;
|
|
37
|
+
export declare class BillingLineageTracker {
|
|
38
|
+
#private;
|
|
39
|
+
constructor(options?: BillingLineageTrackerOptions);
|
|
40
|
+
observeMessages(messages: MessageLike[]): void;
|
|
41
|
+
markHeaders(input: {
|
|
42
|
+
sessionId: string;
|
|
43
|
+
messageId: string;
|
|
44
|
+
agent?: string;
|
|
45
|
+
headers: Record<string, string>;
|
|
46
|
+
}): boolean;
|
|
47
|
+
resolveHeader(value: string | null | undefined): BillingLineageContext | undefined;
|
|
48
|
+
commit(context: BillingLineageContext | undefined, requestId: string | undefined): boolean;
|
|
49
|
+
clearSession(sessionId: string): void;
|
|
50
|
+
}
|
|
51
|
+
export {};
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { type ProviderErrorRedactor } from '@cortexkit/anthropic-auth-core';
|
|
2
|
+
declare const STAGE_LABELS: {
|
|
3
|
+
readonly 'setup-activation': 'Vault custody setup';
|
|
4
|
+
readonly 'setup-opencode-config': 'OpenCode configuration';
|
|
5
|
+
readonly 'setup-pi-install': 'Pi extension installation';
|
|
6
|
+
readonly 'setup-pi': 'Pi setup';
|
|
7
|
+
readonly 'setup-process-check': 'Host process check';
|
|
8
|
+
readonly 'cli-setup': 'Setup';
|
|
9
|
+
readonly 'cli-login': 'Login';
|
|
10
|
+
readonly 'cli-api-add': 'API route setup';
|
|
11
|
+
readonly 'cli-list': 'Account listing';
|
|
12
|
+
readonly 'cli-relay-setup': 'Relay setup';
|
|
13
|
+
readonly 'cli-relay-workers-dev': 'Workers.dev enablement';
|
|
14
|
+
readonly 'cli-command': 'Command';
|
|
15
|
+
};
|
|
16
|
+
export type CliFailureStage = keyof typeof STAGE_LABELS;
|
|
17
|
+
/** UTF-8 bytes of redacted detail kept per diagnostics file. */
|
|
18
|
+
export declare const CLI_FAILURE_DETAIL_MAX_BYTES: number;
|
|
19
|
+
export declare const CLI_FAILURE_OMITTED = "[output beyond the diagnostic limit omitted]";
|
|
20
|
+
export declare const CLI_FAILURE_WITHHELD = "[output withheld: no line break within the inspected window]";
|
|
21
|
+
export declare const CLI_FAILURE_SECRETS_UNREADABLE = "[detail withheld: the known credentials could not be read safely]";
|
|
22
|
+
/**
|
|
23
|
+
* The text to show for a known failure, or undefined when the thrown value is
|
|
24
|
+
* not one. A message counts only when it equals a text in CLOSED_MESSAGES,
|
|
25
|
+
* equals "OAuth metadata read failed: <status>" for its own integer HTTP
|
|
26
|
+
* `status`, or equals what `new ProcessFenceViolationError(activeHosts)`
|
|
27
|
+
* produces from its own validated `activeHosts`.
|
|
28
|
+
*/
|
|
29
|
+
export declare function knownFailureMessage(error: unknown): string | undefined;
|
|
30
|
+
/**
|
|
31
|
+
* Exact credentials a failing command may echo: the strings in `submitted`
|
|
32
|
+
* (the API key, OAuth code and tokens, or Cloudflare and relay tokens the CLI
|
|
33
|
+
* command handled) plus every environment value whose name Core's
|
|
34
|
+
* `isSecretKey` treats as secret (for example `*_TOKEN`, `*_API_KEY`,
|
|
35
|
+
* `*_SECRET`), since child processes receive that environment. Empty values are
|
|
36
|
+
* skipped; every other value counts, however short. Returns undefined when
|
|
37
|
+
* either input is a proxy, has accessors or non-string credentials, or is too
|
|
38
|
+
* large to inspect, so the caller can withhold detail instead of logging it
|
|
39
|
+
* with a credential left out.
|
|
40
|
+
*/
|
|
41
|
+
export declare function collectKnownSecrets(env: unknown, submitted?: unknown): string[] | undefined;
|
|
42
|
+
/**
|
|
43
|
+
* Redact first, bound second. Raw text is only ever cut at a line break and
|
|
44
|
+
* the partial line is dropped, so a credential is never split before the
|
|
45
|
+
* redactor sees it whole. The redacted lines are then kept up to the byte
|
|
46
|
+
* limit; cutting already-redacted text cannot reveal anything new.
|
|
47
|
+
*/
|
|
48
|
+
export declare function boundRedactedDetail(text: string, redactor: Pick<ProviderErrorRedactor, 'redactText'>, keep: 'head' | 'tail'): string[];
|
|
49
|
+
/**
|
|
50
|
+
* Private per-user directory for failure details:
|
|
51
|
+
* `$XDG_STATE_HOME/cortexkit/anthropic-auth/diagnostics`, falling back to
|
|
52
|
+
* `~/.local/state`, which also holds host enrollment files. Undefined when
|
|
53
|
+
* reading the environment would invoke caller code.
|
|
54
|
+
*/
|
|
55
|
+
export declare function cliDiagnosticsDirectory(env: unknown): string | undefined;
|
|
56
|
+
/**
|
|
57
|
+
* Screen text for a thrown failure. A known failure is returned word for word
|
|
58
|
+
* and not recorded; anything else is recorded in a private diagnostics file
|
|
59
|
+
* and replaced by a fixed line naming that file. `env` supplies both the
|
|
60
|
+
* secret-named values to scrub and the diagnostics location; `submitted`
|
|
61
|
+
* holds the credentials the failing command handled.
|
|
62
|
+
*/
|
|
63
|
+
export declare function reportThrownFailure(stage: CliFailureStage, error: unknown, env: unknown, submitted?: unknown): Promise<string>;
|
|
64
|
+
/** Screen text for a child process that exited unsuccessfully; its stderr tail goes to the diagnostics file. */
|
|
65
|
+
export declare function reportInstallerFailure(stage: CliFailureStage, result: {
|
|
66
|
+
exitCode: number;
|
|
67
|
+
stderr: string;
|
|
68
|
+
}, env: unknown): Promise<string>;
|
|
69
|
+
export {};
|
package/dist/cli.d.ts
CHANGED
|
@@ -15,29 +15,35 @@ type FetchLike = (input: string | URL | Request, init?: RequestInit) => Promise<
|
|
|
15
15
|
export interface RelaySetupDeps {
|
|
16
16
|
fetchImpl?: FetchLike;
|
|
17
17
|
prompt?: (message: string) => Promise<string>;
|
|
18
|
+
/** Receives each credential this command handles, for redacting failure detail. */
|
|
19
|
+
secrets?: string[];
|
|
20
|
+
/** Prints a non-fatal warning; defaults to console.warn. */
|
|
21
|
+
warn?: (message: string) => void;
|
|
18
22
|
}
|
|
19
23
|
export declare function relaySetup(deps?: RelaySetupDeps): Promise<void>;
|
|
20
24
|
/**
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
* unchanged; tests inject deterministic stubs to exercise the full login flow
|
|
25
|
-
* in-process without a subprocess, real network, or stdin.
|
|
25
|
+
* Tests can supply prompts and OAuth responses without opening a browser.
|
|
26
|
+
* Login stores exchanged tokens in the shared account pool after validating
|
|
27
|
+
* the account identity. It never writes OpenCode's auth.json or old sidecars.
|
|
26
28
|
*/
|
|
27
29
|
export interface LoginDeps {
|
|
28
30
|
prompt?: (message: string) => Promise<string>;
|
|
29
31
|
authorize?: typeof authorize;
|
|
30
32
|
exchange?: typeof exchange;
|
|
33
|
+
/** Receives each credential this command handles, for redacting failure detail. */
|
|
34
|
+
secrets?: string[];
|
|
31
35
|
}
|
|
32
36
|
export declare function login(labelArg?: string, deps?: LoginDeps): Promise<void>;
|
|
33
37
|
/**
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
* full route-add flow in-process without a subprocess or stdin.
|
|
38
|
+
* Tests can supply prompts to check API keys and proxy route settings.
|
|
39
|
+
* New keys go to the shared account pool after migration has committed;
|
|
40
|
+
* OpenCode's auth.json and the old sidecar files remain unchanged.
|
|
38
41
|
*/
|
|
39
42
|
export interface ApiAddDeps {
|
|
40
43
|
prompt?: (message: string) => Promise<string>;
|
|
44
|
+
/** Receives each credential this command handles, for redacting failure detail. */
|
|
45
|
+
secrets?: string[];
|
|
41
46
|
}
|
|
42
47
|
export declare function addApiRoute(labelArg?: string, deps?: ApiAddDeps): Promise<void>;
|
|
43
|
-
|
|
48
|
+
import { runSetupCommand } from './setup/command.ts';
|
|
49
|
+
export { runSetupCommand };
|
package/dist/cli.js
CHANGED
|
@@ -1,14 +1,119 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
2
|
+
import{A as C2,B as R2,C as S2,D as u2,u as k0,v as p0,w as q0,x as W1,y as P0,z as Y1}from"./index-pn597b6f.js";import{$ as v1,Ad as f0,Bd as O$,Ca as a2,Cd as z1,Dd as x$,Ed as v2,Fa as n2,Jb as S$,Ld as j1,Md as K3,Wb as y2,Xb as L$,Z as n0,_ as E0,be as o2,de as r2,hd as X1,id as b$,jd as s2,la as w$,ld as z0,ma as _$,pa as J1,pd as k$,ua as O1,va as I1,vd as X3,wb as c2,xa as G3,ya as P$}from"./index-nngmvczq.js";import{re as z2,se as Z4,te as x3}from"./index-aaajxwzd.js";var B3=Z4((e5,$2)=>{var L3={to($,Z){if(!Z)return`\x1B[${$+1}G`;return`\x1B[${Z+1};${$+1}H`},move($,Z){let J="";if($<0)J+=`\x1B[${-$}D`;else if($>0)J+=`\x1B[${$}C`;if(Z<0)J+=`\x1B[${-Z}A`;else if(Z>0)J+=`\x1B[${Z}B`;return J},up:($=1)=>`\x1B[${$}A`,down:($=1)=>`\x1B[${$}B`,forward:($=1)=>`\x1B[${$}C`,backward:($=1)=>`\x1B[${$}D`,nextLine:($=1)=>"\x1B[E".repeat($),prevLine:($=1)=>"\x1B[F".repeat($),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},J4={up:($=1)=>"\x1B[S".repeat($),down:($=1)=>"\x1B[T".repeat($)},Q4={screen:"\x1B[2J",up:($=1)=>"\x1B[1J".repeat($),down:($=1)=>"\x1B[J".repeat($),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines($){let Z="";for(let J=0;J<$;J++)Z+=this.line+(J<$-1?L3.up():"");if($)Z+=L3.left;return Z}};$2.exports={cursor:L3,scroll:J4,erase:Q4,beep:"\x07"}});import{stdin as a4,stdout as n4}from"node:process";import{createInterface as s4}from"node:readline/promises";import{randomUUID as U7}from"node:crypto";import{constants as K1}from"node:fs";import{lstat as q7,mkdir as V7,open as M7}from"node:fs/promises";import{homedir as D7}from"node:os";import{isAbsolute as R$,join as F3}from"node:path";import{types as U3}from"node:util";import{readFile as H7}from"node:fs/promises";import{appendFileSync as z9,chmodSync as W9,existsSync as R1,renameSync as y3,statSync as Y9}from"node:fs";var e2=/^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i,$9=/\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;function Z9($){return $ instanceof Error||Object.prototype.toString.call($)==="[object Error]"}function M0($={}){let Z=[$9,...$.extraValuePatterns??[]].map((W)=>new RegExp(W.source,W.flags.includes("g")?W.flags:`${W.flags}g`));function J(W){let G=W.toLowerCase().replace(/[-_]/g,"");return e2.test(W)||G.includes("apikey")||G.endsWith("secret")||G.endsWith("password")||G.endsWith("token")&&!G.endsWith("tokens")||!!$.extraSecretKeys?.(G)}function Q(W){let G=W,Y=[["name",W.name],["message",W.message],["stack",W.stack]];for(let j of["code","status","cause"])if(G[j]!==void 0)Y.push([j,G[j]]);let X=new Set(Y.map(([j])=>j));for(let j of Object.entries(W))if(!X.has(j[0]))Y.push(j);return Y}function z(W,G,Y,X=0){if(typeof W==="string")return Z.reduce((j,H)=>j.replace(H,"***REDACTED***"),W);if(!W||typeof W!=="object")return W;if(Y.has(W))return"[Circular]";Y.add(W);try{if(Array.isArray(W))return W.map((K)=>z(K,G,Y,X));let j=Z9(W);if(j&&X>=8)return"[Truncated]";let H=j?X+1:X;return Object.fromEntries((j?Q(W):Object.entries(W)).map(([K,U])=>[K,G&&J(K)?"***REDACTED***":z(U,G,Y,H)]))}finally{Y.delete(W)}}return{redact:(W)=>z(W,!0,new WeakSet),redactStrings:(W)=>z(W,!1,new WeakSet)}}var h3=M0(),J9=h3.redact,Q9=h3.redactStrings;var d0={error:0,warn:1,info:2,debug:3,trace:4},G9=5242880,X9=3;function A1($){try{W9($,384)}catch{}}function j9($){try{if(!(R1($)&&Y9($).size>=G9))return;for(let J=X9-1;J>=1;J--)if(R1(`${$}.${J}`)){let Q=`${$}.${J+1}`;y3(`${$}.${J}`,Q),A1(Q)}let Z=`${$}.1`;y3($,Z),A1(Z)}catch{}}function K9($){try{return` ${JSON.stringify($)}`}catch{return" [unserializable]"}}function H9($){let Z,J,Q,z=M0(),W,G=[],Y;function X(N){Z=N.file,J=N.level,z=M0(N),W=N.captureSink}function j(N){if(N===void 0||N in d0)Q=N}function H(){if(Z===void 0)return;return(typeof Z==="function"?Z():Z)||void 0}function K(){if(Q)return Q;let N=typeof J==="function"?J():J;if(N&&N in d0)return N;return"info"}function U(){if(Y)clearTimeout(Y),Y=void 0;if(!G.length)return;let N;try{N=H()}catch{G=[];return}let A=G.join("");if(G=[],!N)return;try{if(j9(N),R1(N))A1(N);z9(N,A,{encoding:"utf8",mode:384})}catch{}}function V(){if(!Y)Y=setTimeout(()=>{Y=void 0,U()},500)}function q(N,A,w,M){if(Z===void 0&&W===void 0)return;try{if(d0[A]>d0[K()])return;let D=z.redactStrings(w),R;try{R=z.redact(M)}catch{R="[unserializable]"}let k=`[${new Date().toISOString()}] ${A.toUpperCase()} [${N}] ${D}`+(M===void 0?"":K9(R))+`
|
|
3
|
+
`;try{W?.({channel:N,level:A,message:D,data:R})}catch{}if(Z===void 0)return;if(G.push(k),G.length>=50)U();else V()}catch{}}function B(N){return{error:(A,w)=>q(N,"error",A,w),warn:(A,w)=>q(N,"warn",A,w),info:(A,w)=>q(N,"info",A,w),debug:(A,w)=>q(N,"debug",A,w),trace:(A,w)=>q(N,"trace",A,w)}}function I(){if(G=[],Y)clearTimeout(Y),Y=void 0;Z=void 0,J=void 0,Q=void 0,z=M0(),W=void 0}if($)X($);return{configure:X,createLogger:B,setLogLevel:j,flushLogs:U,reset:I}}var F9=H9();function R0($){return F9.createLogger($)}function E1($){let Z=new AbortController,J=[],Q=!1,z=()=>{if(Q)return;Q=!0;for(let{source:Y,listener:X}of J)Y.removeEventListener("abort",X);J.length=0},W=(Y)=>{if(Q||Z.signal.aborted)return;Z.abort(Y),z()},G=$.find((Y)=>Y.aborted);if(G)return Z.abort(G.reason),{signal:Z.signal,dispose:z};for(let Y of $){if(Z.signal.aborted)break;let X=()=>W(Y.reason);if(J.push({source:Y,listener:X}),Y.addEventListener("abort",X,{once:!0}),Y.aborted)W(Y.reason)}return{signal:Z.signal,dispose:z}}import{createHash as I9,randomBytes as f9,randomUUID as b9}from"node:crypto";import{constants as i3}from"node:fs";import{chmod as k9,mkdir as C9,open as s3,readFile as a3,realpath as R9,rename as A9,stat as o3,unlink as r3}from"node:fs/promises";import{basename as E9,dirname as L0,extname as l8,isAbsolute as i8,join as w9,resolve as a8}from"node:path";import{randomUUID as U9}from"node:crypto";import{mkdir as q9,open as m3,rename as V9,rm as M9}from"node:fs/promises";import{dirname as v3}from"node:path";class w1 extends Error{constructor($){super("file or directory sync failed",{cause:$});this.name="AtomicSyncError"}}async function _1($,Z,J={}){await D9($,Z,J)}async function D9($,Z,J,Q){await q9(v3($),{recursive:!0});let z=`${$}.${(J.stageName??U9)()}.tmp`,W,G=!1;try{if(W=await m3(z,"wx",384),G=!0,await W.writeFile(J.serialize?J.serialize(Z):`${JSON.stringify(Z,null,2)}
|
|
4
|
+
`,"utf8"),await W.chmod(384),J.durable)try{await W.sync()}catch(Y){throw new w1(Y)}if(await W.close(),W=void 0,await J.beforeRename?.(),await V9(z,$),G=!1,Q?.(),J.durable){let Y=await m3(v3($),"r");try{await Y.sync()}catch(X){throw new w1(X)}finally{await Y.close()}}}finally{if(await W?.close().catch(()=>{}),G)await M9(z,{force:!0}).catch(()=>{})}}var L9=Object.freeze({sidebar:Object.freeze({name:"sidebar-write",ttlMs:1e4,timeoutMs:15000,renew:!0}),preferences:Object.freeze({name:"preferences",ttlMs:1e4,timeoutMs:2000,renew:!0})});import{randomUUID as l0}from"node:crypto";import{mkdir as p3,open as B9,readFile as T1,rename as c3,rm as D0,stat as d3,writeFile as h1}from"node:fs/promises";import{dirname as N9,join as u3}from"node:path";function S1($,Z){return`${$}.${Z}.lock`}class x1 extends Error{details;constructor($){super(`Timed out acquiring ${$.name} lock for ${$.target}`);this.name="LockContentionError",this.details=$}}class u0 extends Error{details;constructor($){super(`Lost ${$.name} lock for ${$.target}`);this.name="LockOwnershipError",this.details=$}}async function g1($,Z,J){let Q=performance.now();for(;;){let z=await e({path:$,name:Z.name,ttlMs:Z.ttlMs,renew:Z.renew??!1});if(z)try{return await J(z)}finally{await z.release()}let W=Z.timeoutMs-(performance.now()-Q);if(W<=0)throw new x1({target:$,name:Z.name,timeoutMs:Z.timeoutMs});await new Promise((G)=>setTimeout(G,Math.min(25,Math.ceil(W))))}}var P9=globalThis.setTimeout.bind(globalThis),O9=globalThis.clearTimeout.bind(globalThis);function l3($){let Z=$?.code;return Z==="ENOENT"||Z==="EINVAL"||Z==="ENOTDIR"}async function e($){let Z=S1($.path,$.name),J=u3(Z,"owner.json"),Q=l0(),z=$.now??Date.now,W=null,G=!1,Y,X,j=new Promise((L)=>{X=L});function H(L){try{let P=$.onRenewalTimer?.(L);if(P&&(typeof P==="object"||typeof P==="function")&&"then"in P&&typeof P.then==="function")Promise.resolve(P).catch(()=>{})}catch{}}function K(){if(!W)return;O9(W),W=null,H("cancelled")}function U(L,P){if(Y||G)return;Y=Object.freeze({reason:L,expectedOwnerId:Q,...typeof P?.ownerId==="string"?{observedOwnerId:P.ownerId}:{},...typeof P?.expiresAt==="number"?{observedExpiresAt:P.expiresAt}:{}}),K(),X(Y)}let V=null,q=`${Z}.evicting`,B=u3(q,"owner.json"),I=l0(),N=5000,A=8;async function w(){try{return JSON.parse(await T1(Z,"utf8"))}catch(L){if(L.code!=="EISDIR")throw L;return JSON.parse(await T1(J,"utf8"))}}async function M(){let L=`${Z}.${l0()}.tmp`,P,O=!1;try{P=await B9(L,"wx",384),O=!0,await P.writeFile(`${JSON.stringify({ownerId:Q,expiresAt:z()+$.ttlMs})}
|
|
5
|
+
`,"utf8"),await P.chmod(384),await P.close(),P=void 0,await c3(L,Z),O=!1}finally{if(await P?.close().catch(()=>{}),O)await D0(L,{force:!0}).catch(()=>{})}}async function D(){try{return await h1(Z,`${JSON.stringify({ownerId:Q,expiresAt:z()+$.ttlMs})}
|
|
6
|
+
`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(L){let P=L.code;if(P==="EEXIST"||P==="EISDIR")return!1;if(P==="ENOENT"){await p3(N9(Z),{recursive:!0});try{return await h1(Z,`${JSON.stringify({ownerId:Q,expiresAt:z()+$.ttlMs})}
|
|
7
|
+
`,{encoding:"utf8",mode:384,flag:"wx"}),!0}catch(O){let c=O.code;if(c==="EEXIST"||c==="EISDIR")return!1;throw O}}throw L}}async function R(){await new Promise((L)=>setTimeout(L,Math.floor(Math.random()*4)))}async function k(){try{let L=await w();return Number(L?.expiresAt)>z()}catch{try{return(await d3(Z)).mtimeMs+$.ttlMs>z()}catch{return!1}}}async function E(){try{return JSON.parse(await T1(B,"utf8"))?.ownerId===I}catch{return!1}}async function S(){if(await E())await D0(q,{recursive:!0,force:!0}).catch(()=>{})}async function m(){await p3(q);try{await h1(B,`${JSON.stringify({ownerId:I,createdAt:z()})}
|
|
8
|
+
`,{encoding:"utf8",mode:384,flag:"wx"})}catch(L){if(l3(L))return!1;throw await S(),L}if($.onStep)await $.onStep("eviction-marker-acquired");return!0}async function T(){let L;try{L=await d3(q)}catch(O){if(O.code==="ENOENT")return"missing";throw O}if(L.mtimeMs+N>z())return"fresh";if($.onStep)await $.onStep("stale-marker-stat");let P=`${q}.${l0()}`;try{await c3(q,P)}catch(O){if(O.code==="ENOENT")return"missing";throw O}if($.onStep)await $.onStep("stale-marker-claimed");return await D0(P,{recursive:!0,force:!0}).catch(()=>{}),"recovered"}async function C(L){try{if(!await m())return!1}catch(P){if(P.code==="EEXIST")return!1;throw P}try{await L()}finally{await S()}return!0}async function x(){for(let L=0;L<A;L++){if($.onStep)await $.onStep("relinquish-read");let P;try{P=await w()}catch{return}if(P?.ownerId!==Q)return;try{await D0(Z,{recursive:!0,force:!0});return}catch{await R()}}}function b(){if(!$.renew||G||Y)return;let L=$.renewIntervalMs??Math.max(1000,Math.floor($.ttlMs/3));if(W=P9(()=>{W=null;let P=(async()=>{let O=!G;try{if(!await C(async()=>{let c0=await w(),t2=z();if(G||Y){O=!1;return}if(c0?.ownerId!==Q){U("taken-over",c0),O=!1;return}if(!(Number(c0?.expiresAt)>t2)){U("expired",c0),O=!1;return}if($.onStep)await $.onStep("renewal-owner-confirmed");if(G||Y){O=!1;return}if(!await E())return;if($.onStep)await $.onStep("renewal-write-fenced");if(G||Y){O=!1;return}if(!await E())return;if($.onStep)await $.onStep("renewal-write-ready");if(G||Y){O=!1;return}if(await M(),!await E()){U("marker-lost"),O=!1,await x();return}})&&$.onStep)await $.onStep("renewal-marker-unavailable")}catch{try{let c=await w();if(c?.ownerId!==Q)U("taken-over",c);else if(!(Number(c?.expiresAt)>z()))U("expired",c)}catch{U("renewal-failed")}}finally{if($.onStep)try{await $.onStep("renewal-finished")}catch{}if(O&&!G&&!Y)b()}})();V=P,P.finally(()=>{if(V===P)V=null})},L),"unref"in W)W.unref();H("scheduled")}function y(){try{let L=$.onContended?.();if(L&&(typeof L==="object"||typeof L==="function")&&"then"in L&&typeof L.then==="function")Promise.resolve(L).catch(()=>{})}catch{}return null}let p=await D();if(!p)for(let L=0;L<A;L++){if(p=await D(),p)break;if(await k())return y();if($.onStep)await $.onStep("stale-lock-observed");try{if(!await m()){await R();continue}}catch(P){if(P.code!=="EEXIST")throw P;if(await T()==="fresh")return null;await R();continue}try{if(await k())return y();if(!await E())return null;if($.onStep)await $.onStep("stale-lock-confirmed");if(!await E())return null;if(await D0(Z,{recursive:!0,force:!0}).catch(()=>{}),!await E())return null;if($.onStep)await $.onStep("stale-lock-removed");if(p=await D(),!p)return null;if($.onStep)await $.onStep("stale-lock-recreated");if(!await E())return await x(),p=!1,null;break}finally{await S()}}if(!p)return null;return b(),{ownerId:Q,whenLost:()=>j,hasLost:()=>Y!==void 0,assertOwned:async()=>{let L;try{let P=await w();if(L=P,!G&&!Y&&P?.ownerId===Q&&Number(P?.expiresAt)>z())return;U(P?.ownerId!==Q?"taken-over":"expired",P)}catch{U("unreadable")}throw new u0({target:$.path,name:$.name,expectedOwnerId:Q,...typeof L?.ownerId==="string"?{observedOwnerId:L.ownerId}:{},...typeof L?.expiresAt==="number"?{observedExpiresAt:L.expiresAt}:{}})},release:async()=>{G=!0,K(),await V;for(let L=0;L<A;L++){try{if(await C(async()=>{if((await w())?.ownerId!==Q)return;if($.onStep)await $.onStep("release-owner-confirmed");if(!await E())return;await D0(Z,{recursive:!0,force:!0}).catch(()=>{})}))return;await T()}catch{return}await R()}}}}class f extends Error{kind;constructor($,Z){super(Z);this.name="ClaustrumConsumerError",this.kind=$}}var _9=1,y1=16384,t3=30000,p1=/^[0-9a-f]{64}$/,e3=new Set(["invalid_params","pending_exists","not_found","already_consumed","superseded","stale_generation"]),$$=new Set(["pending_queue_full"]);function m1($){if(!($ instanceof E0))return;if(e3.has($.code))return{code:$.code,disposition:"terminal"};if($$.has($.code))return{code:$.code,disposition:"retry"};return{code:$.code,disposition:$.action==="retry"?"retry":"terminal"}}function c1($){return v1.connect($)}function Z$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function i0($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function J$($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=1}function A0(){return new f("invalid-state","invalid Claustrum enrollment state")}function d1($){if(!Z$($)||$.version!==_9||typeof $.proposedName!=="string"||$.proposedName.length===0)throw A0();if($.phase==="pending"){if(!p1.test(String($.requestSecret??""))||$.requestId!==void 0&&(typeof $.requestId!=="string"||$.requestId.length===0)||!i0($.createdAt)||!i0($.updatedAt))throw A0();return{version:1,phase:"pending",proposedName:$.proposedName,requestSecret:$.requestSecret,...$.requestId!==void 0&&{requestId:$.requestId},createdAt:$.createdAt,updatedAt:$.updatedAt}}if($.phase==="approved"){if($.approvedName!==void 0&&(typeof $.approvedName!=="string"||$.approvedName.length===0)||!J$($.tokenGeneration)||!i0($.updatedAt))throw A0();return{version:1,phase:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration,updatedAt:$.updatedAt}}if($.phase==="denied"||$.phase==="blocked"){if($.errorCode!==void 0&&typeof $.errorCode!=="string"||!i0($.updatedAt))throw A0();return{version:1,phase:$.phase,proposedName:$.proposedName,...$.errorCode!==void 0&&{errorCode:$.errorCode},updatedAt:$.updatedAt}}throw A0()}function u1($){if(!Z$($)||!p1.test(String($.token??""))||!J$($.token_generation))throw new f("invalid-token","invalid Claustrum enrollment token file");return{token:$.token,token_generation:$.token_generation}}function S9($){if(!$.isFile())throw new f("unsafe-file","Claustrum enrollment file must be a regular file");if(($.mode&63)!==0)throw new f("unsafe-file","Claustrum enrollment file must be owner-only");let Z=process.geteuid?.();if(Z!==void 0&&$.uid!==Z)throw new f("unsafe-file","Claustrum enrollment file must be owned by the current user")}function x9($){try{return JSON.parse($)}catch{throw new f("invalid-state","Claustrum enrollment file is not valid JSON")}}async function H0($){let Z;try{Z=await s3($,i3.O_RDONLY|i3.O_NOFOLLOW)}catch(J){if(J.code==="ENOENT")return;throw new f("unsafe-file","Claustrum enrollment file could not be opened safely")}try{S9(await Z.stat());let J=Buffer.alloc(y1+1),{bytesRead:Q}=await Z.read(J,0,J.byteLength,0);if(Q>y1)throw new f("unsafe-file","Claustrum enrollment file is too large");return x9(J.subarray(0,Q).toString("utf8"))}finally{await Z.close()}}function n3($,Z){let J=[];for(let Q of $.split(`
|
|
9
|
+
`)){if(Q.trim()===""||Q.startsWith("#"))continue;let z=Q.split(":");if(z.length!==Z||!/^[^\s:,]+$/.test(z[0]??"")||!/^\d+$/.test(z[2]??"")||!Number.isSafeInteger(Number(z[2]))||Z===7&&(!/^\d+$/.test(z[3]??"")||!Number.isSafeInteger(Number(z[3])))||Z===4&&z[3]!==""&&!/^[^\s:,]+(?:,[^\s:,]+)*$/.test(z[3]??""))return;J.push(z)}return J}async function g9($,Z,J){try{let[Q,z]=await Promise.all([a3(J.passwdPath??"/etc/passwd","utf8"),a3(J.groupPath??"/etc/group","utf8")]),W=n3(Q,7),G=n3(z,4);if(!W||!G)return!1;let Y=W.filter((K)=>Number(K[2])===$),X=G.filter((K)=>Number(K[2])===Z);if(Y.length!==1||X.length!==1)return!1;let j=Y[0]?.[0],H=X[0]?.[3]??"";return(H===""||H.split(",").every((K)=>K===j))&&!W.some((K)=>Number(K[2])!==$&&Number(K[3])===Z)}catch{return!1}}async function Q$($,Z={}){let J=process.geteuid?.();if(J===void 0)return;let Q=process.getegid?.(),z;try{z=await R9($)}catch{return}let W;for(;;){let G=await o3(z).catch(()=>{return});if(G&&(G.mode&18)!==0&&(G.mode&512)===0){if(W===void 0)W=Q!==void 0&&await g9(J,Q,Z);if((G.mode&2)!==0||G.uid!==J||G.gid!==Q||!W)throw new f("unsafe-file",`Claustrum enrollment path has a writable ancestor: ${z}. Another user could replace it. Run: chmod g-w,o-w ${z}`)}let Y=L0(z);if(Y===z)return;z=Y}}async function a0($){await C9($,{recursive:!0,mode:448});let Z=await o3($),J=process.geteuid?.();if(J!==void 0&&Z.uid!==J)throw new f("unsafe-file","Claustrum enrollment directory must be owned by the current user");if((Z.mode&63)!==0)await k9($,448)}async function K0($,Z,J={}){let Q=L0($);await a0(Q),await Q$(Q,J);let z=`${JSON.stringify(Z)}
|
|
10
|
+
`;if(Buffer.byteLength(z)>y1)throw new f("invalid-state","Claustrum enrollment state is too large");let W=w9(Q,`.${E9($)}.${process.pid}.${b9()}.tmp`),G,Y=!1;try{G=await s3(W,"wx",384),Y=!0,await G.writeFile(z,"utf8"),await G.chmod(384),await G.sync(),await G.close(),G=void 0,await A9(W,$),Y=!1}finally{if(await G?.close().catch(()=>{}),Y)await r3(W).catch(()=>{})}}async function s0($,Z){let J=await H0($.tokenPath),Q=J===void 0?void 0:u1(J),z=await H0($.statePath),W=z===void 0?void 0:d1(z);if(Q)return{state:"approved",proposedName:W?.proposedName??Z,...W?.phase==="approved"&&W.approvedName!==void 0&&{approvedName:W.approvedName},tokenGeneration:Q.token_generation};if(!W)return{state:"idle"};if(W.phase==="approved")return{state:"blocked",proposedName:W.proposedName,code:"missing_token"};return $0(W)}async function l1($){let Z=await H0($);if(Z===void 0)throw new f("not-enrolled","Claustrum enrollment is not configured");return u1(Z)}function $0($){if($.phase==="pending")return{state:"pending",proposedName:$.proposedName,...$.requestId!==void 0&&{requestId:$.requestId}};if($.phase==="approved")return{state:"approved",proposedName:$.proposedName,...$.approvedName!==void 0&&{approvedName:$.approvedName},tokenGeneration:$.tokenGeneration};if($.phase==="denied")return{state:"denied",proposedName:$.proposedName};return{state:"blocked",proposedName:$.proposedName,code:$.errorCode??"unknown"}}function z$(){return new f("wrong-consumer","Claustrum enrollment state belongs to a different consumer")}class o0{#$;#J;#Z;#W;#X;#z;#Q;constructor($){this.#Q=$.ancestorOptions??{},this.#$=$.client,this.#J=$.paths,this.#Z=$.proposedName,this.#W=$.now??Date.now,this.#X=$.mintSecret??(()=>f9(32).toString("hex")),this.#z=$.writeTokenFile??n0}async status(){return s0(this.#J,this.#Z)}async resetTerminal(){return W$(this.#J,this.#Z)}async#Y($,Z){let J={version:1,phase:"blocked",proposedName:$.proposedName,errorCode:Z,updatedAt:this.#W()};return await K0(this.#J.statePath,J,this.#Q),$0(J)}async reconcile(){await a0(L0(this.#J.statePath));let $=await e({name:"ceremony",path:this.#J.statePath,ttlMs:t3,renew:!0});if(!$)return{state:"busy"};try{let Z=await H0(this.#J.tokenPath),J=Z===void 0?void 0:u1(Z),Q=await H0(this.#J.statePath),z=Q===void 0?void 0:d1(Q);if(z&&z.proposedName!==this.#Z)throw z$();if(J){if(!z||z.phase==="pending"){let G={version:1,phase:"approved",proposedName:z?.proposedName??this.#Z,tokenGeneration:J.token_generation,updatedAt:this.#W()};await K0(this.#J.statePath,G,this.#Q),z=G}return{state:"approved",proposedName:z.proposedName,...z.phase==="approved"&&z.approvedName!==void 0&&{approvedName:z.approvedName},tokenGeneration:J.token_generation}}if(z?.phase==="approved"){let G={version:1,phase:"blocked",proposedName:z.proposedName,errorCode:"missing_token",updatedAt:this.#W()};return await K0(this.#J.statePath,G,this.#Q),$0(G)}if(z&&z.phase!=="pending")return $0(z);if(!z){let G=this.#W();if(z={version:1,phase:"pending",proposedName:this.#Z,requestSecret:this.#X(),createdAt:G,updatedAt:G},!p1.test(z.requestSecret))throw new f("invalid-state","invalid minted Claustrum enrollment secret");await K0(this.#J.statePath,z,this.#Q)}if(!z.requestId)try{let G=I9("sha256").update(Buffer.from(z.requestSecret,"hex")).digest("hex"),Y=await this.#$.enrollPropose({name:z.proposedName,requestSecretHash:G});z={...z,requestId:Y.requestId,updatedAt:this.#W()},await K0(this.#J.statePath,z,this.#Q)}catch(G){let Y=m1(G);if(!Y)throw G;if(Y.disposition==="retry")return{state:"pending",proposedName:z.proposedName,retryCode:Y.code};return this.#Y(z,Y.code)}let W=z.requestId;if(!W)return $0(z);try{let G=await this.#$.enrollPoll({requestId:W,requestSecret:z.requestSecret});if(G.status==="pending")return $0(z);if(G.status==="denied"){let X={version:1,phase:"denied",proposedName:z.proposedName,updatedAt:this.#W()};return await K0(this.#J.statePath,X,this.#Q),$0(X)}await a0(L0(this.#J.tokenPath)),await Q$(L0(this.#J.tokenPath),this.#Q),await this.#z(this.#J.tokenPath,{token:G.token,token_generation:G.tokenGeneration});let Y={version:1,phase:"approved",proposedName:z.proposedName,approvedName:G.name,tokenGeneration:G.tokenGeneration,updatedAt:this.#W()};return await K0(this.#J.statePath,Y,this.#Q),$0(Y)}catch(G){let Y=m1(G);if(!Y)throw G;if(Y.disposition==="retry")return{state:"pending",proposedName:z.proposedName,requestId:W,retryCode:Y.code};return this.#Y(z,Y.code)}}finally{await $.release()}}}async function W$($,Z){await a0(L0($.statePath));let J=await e({name:"ceremony",path:$.statePath,ttlMs:t3,renew:!0});if(!J)return"busy";try{if(await H0($.tokenPath)!==void 0)return"refused-approved";let Q=await H0($.statePath);if(Q===void 0)return"idle";let z=d1(Q);if(z.proposedName!==Z)throw z$();if(z.phase==="pending")return"refused-pending";return await J.assertOwned(),await r3($.statePath),"reset"}finally{await J.release()}}var i1="claustrum-tombstone:v1:";function Y$($,Z){return Z!==void 0&&Z.credentialId===$.credentialId&&Z.accountIdentity===$.accountIdentity&&Z.recordVersion!==$.recordVersion}function T9($,Z){if(Z===void 0)return"reauthorize-failed";if(Z.credentialId!==$.credentialId)return"credential-changed";if(Z.accountIdentity!==$.accountIdentity)return"account-changed";if(Z.recordVersion===$.recordVersion)return"version-unchanged";return"rotated"}var G$=R0("claustrum");function s1($,Z,J,Q=G$){let z=Y$(Z,J);return Q.debug("scoped 401 re-authorized",{site:$,credentialId:Z.credentialId,servedVersion:Z.recordVersion,currentVersion:J?.recordVersion??null,retry:z,reason:T9(Z,J)}),z}var n1=300000;function a1(){return new f("invalid-material","Claustrum returned invalid credential material")}function h9($){let Z=$.trim();if(Z.startsWith("{")){let J;try{J=JSON.parse(Z)}catch{throw a1()}if(!J||typeof J!=="object")throw a1();let Q=J,z=Q.access_token??Q.access;Z=typeof z==="string"?z:""}if(!/^[\x21-\x7e]+$/.test(Z)||Z.startsWith(i1))throw a1();return Z}function y9($,Z){if(!$.operations.includes("read"))return;if(!$.categories.includes(Z.category))return;if($.credentialType==="oauth")return $.refreshAdapter===Z.refreshAdapter?"oauth":void 0;if($.credentialType==="api_key"&&Z.apiKeys)return $.refreshAdapter===void 0?"api_key":void 0;return}class r0{#$;#J;#Z;#W;#X;#z;#Q;#Y=new WeakMap;#H=new WeakMap;#G=!1;constructor($){let Z=$.tokenPath;if($.readToken)this.#J=$.readToken;else if(Z)this.#J=()=>l1(Z);else throw new f("not-enrolled","Claustrum enrollment token path is required");this.#$=$.client,this.#W=$.family,this.#X=$.parseIdentity,this.#z=$.requireAssertion??!1,this.#Z=$.now??Date.now,this.#Q=$.logger??G$}#j($){if(this.#G)throw new f("closed","Claustrum scoped custody is closed");$?.throwIfAborted()}async#K($){this.#j($);let Z=await this.#J();if(this.#j($),!/^[0-9a-f]{64}$/.test(Z.token)||!Number.isSafeInteger(Z.token_generation)||Z.token_generation<1)throw new f("invalid-token","Invalid Claustrum enrollment token");return Z.token}async#F($,Z){this.#j(Z);let J,Q;try{let z=$();J=Z?await Promise.race([z,new Promise((W,G)=>{let Y=()=>G(Z.reason);if(Z.addEventListener("abort",Y,{once:!0}),Q=()=>Z.removeEventListener("abort",Y),Z.aborted)Y()})]):await z}catch(z){if(this.#j(Z),z instanceof E0)throw z;throw new f("unavailable","Claustrum scoped operation unavailable")}finally{Q?.()}return this.#j(Z),J}async discover($){let Z=await this.#K($),J=await this.#F(()=>this.#$.listScoped(Z),$),Q=[],z=[],W=new Map;for(let Y of J.rows){let X=y9(Y,this.#W);if(!X)continue;z.push({row:Y,type:X}),W.set(Y.id,(W.get(Y.id)??0)+1)}let G=[];for(let{row:Y,type:X}of z){let j;if(!Y.id.trim())j="empty credential id";else if((W.get(Y.id)??0)>1)j="duplicate credential id";else if(Y.accountId!==void 0&&!Y.accountId.trim())j="blank account identity";else if(!Y.state.trim())j="empty state";if(j){Q.push({...Y.id.trim()&&{credentialId:Y.id},reason:j});continue}G.push(Object.freeze({credentialId:Y.id,credentialType:X,...Y.accountId!==void 0&&{accountIdentity:Y.accountId},state:Y.state,...Y.email!==void 0&&{email:Y.email},...Y.orgName!==void 0&&{orgName:Y.orgName}}))}for(let Y of Q)this.#Q.warn("skipped malformed vault record",Y);return{view:J.view,credentials:Object.freeze(G),skipped:Object.freeze(Q)}}async authorize($,Z){if(!$.credentialId)throw new f("route-unavailable","Claustrum dispatch requires a credential id");let{credentialId:J,credentialType:Q,accountIdentity:z}=$;if(this.#z&&z===void 0)throw new f("identity-unasserted","Claustrum dispatch requires a known account identity");let W=await this.#K(Z),G=await this.#F(()=>this.#$.getScoped({credentialId:J,enrollmentToken:W,...Q==="oauth"&&{minTtlMs:n1}}),Z);if(G.credentialId!==void 0&&G.credentialId!==J)throw new f("identity-changed","Claustrum served credential identity changed");let Y=G.expiresAtMs;if(!Number.isSafeInteger(G.recordVersion)||G.recordVersion<0||Y===null&&Q==="oauth"||Y!==null&&(!Number.isFinite(Y)||Y-this.#Z()<n1))throw new f("insufficient-validity","Claustrum served credential has insufficient validity");let X=h9(G.material),j=G.accountId?.trim()?G.accountId:void 0;if(this.#z&&(G.credentialId===void 0||j===void 0))throw new f("identity-unasserted","Claustrum served credential did not assert its identity");let H=j===void 0?this.#X?.(X):void 0,K=j??H;if(z!==void 0&&K!==void 0&&K!==z)throw new f("identity-changed","Claustrum served credential identity changed");let U=K??z,q=Object.freeze(Object.defineProperty({credentialId:J,credentialType:Q,...U!==void 0&&{accountIdentity:U},accountIdentitySource:j!==void 0?"asserted":H!==void 0?"parsed":z!==void 0?"expected":"none",...z!==void 0&&{expectedAccountIdentity:z},...G.credentialId!==void 0&&{assertedCredentialId:G.credentialId},...j!==void 0&&{assertedAccountIdentity:j},...G.projectId!==void 0&&{projectId:G.projectId},recordVersion:G.recordVersion,expiresAtMs:Y},"accessToken",{value:X,enumerable:!1}));return this.#Y.set(q,W),q}async reportFailure($,Z,J){if(Z!==401)return;this.#j();let Q=this.#Y.get($);if(!Q)throw new f("no-receipt","Claustrum failure report requires an original dispatch receipt");let z=this.#H.get($);if(z)return z;let W=this.#F(()=>this.#$.reportAuthFailureScoped({credentialId:$.credentialId,enrollmentToken:Q,providerStatus:401,recordVersion:$.recordVersion,reporterSource:J}));this.#H.set($,W);try{await W,this.#Q.debug("scoped 401 reported",{credentialId:$.credentialId,recordVersion:$.recordVersion,reporterSource:J})}catch(G){throw this.#H.delete($),G}}close(){if(this.#G)return;this.#G=!0,this.#$.close()}}import{createHash as s9}from"node:crypto";import{readFile as o9}from"node:fs/promises";var F0="all",m9=Object.freeze(["primary"]);function j$($){return $.kind==="retired"?$.retiredAt:$.checkedAt}function B0($,Z){return JSON.stringify([$,Z])}function r1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function n($){return typeof $==="number"&&Number.isFinite($)}function X$($){return typeof $==="string"&&$.length>0}function s($,Z,J){return $[Z]===void 0||J($[Z])}function v9($){return n($)&&$>0}function o1($){return typeof $==="string"}function p9($){if(!r1($)||!X$($.scope)||!X$($.label))return!1;switch($.kind){case"reading":return n($.checkedAt)&&n($.usedPercent)&&s($,"resetsAt",o1)&&s($,"windowMinutes",v9);case"retired":return n($.retiredAt);case"absent":return n($.checkedAt);default:return!1}}function c9($){if(!r1($)||!n($.checkedAt))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&s($,"remainingPercent",n)&&s($,"usedPercent",n)&&s($,"resetsAt",o1)&&s($,"limit",n)&&s($,"used",n)&&s($,"remaining",n)&&s($,"unit",o1)}function U0($){if(!r1($)||!Array.isArray($.limits))return!1;let Z=new Set;for(let J of $.limits){if(!p9(J))return!1;let Q=B0(J.scope,J.label);if(Z.has(Q))return!1;Z.add(Q)}return s($,"budget",c9)}class t0 extends TypeError{constructor($){super($);this.name="QuotaCodecError"}}function $1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function e0($){return typeof $==="number"&&Number.isFinite($)}function K$($){return $===void 0||typeof $==="string"&&$!==""}function H$($){return typeof $==="string"&&$!==""}function w0($,Z){return $[Z]===void 0||e0($[Z])}function t1($,Z){return $[Z]===void 0||typeof $[Z]==="string"}function d9($){return $1($)&&K$($.scope)&&H$($.label)&&e0($.usedPercent)&&t1($,"resetsAt")&&($.windowMinutes===void 0||e0($.windowMinutes)&&$.windowMinutes>0)}function u9($){return $1($)&&K$($.scope)&&H$($.label)}function l9($){if(!$1($))return!1;if($.kind==="cleared")return!0;return $.kind==="reading"&&typeof $.reached==="boolean"&&w0($,"remainingPercent")&&w0($,"usedPercent")&&t1($,"resetsAt")&&w0($,"limit")&&w0($,"used")&&w0($,"remaining")&&t1($,"unit")}function F$($){if(!$1($)||!e0($.checkedAt))return!1;let Z=$.readings??[],J=$.coverage??[];if(!Array.isArray(Z)||!Array.isArray(J))return!1;let Q=new Set;for(let z of Z){if(!d9(z))return!1;let W=B0(z.scope??F0,z.label);if(Q.has(W))return!1;Q.add(W)}if(!J.every(u9))return!1;return $.budget===void 0||l9($.budget)}function i9($,Z){if($.scope!==Z.scope)return $.scope<Z.scope?-1:1;if($.label!==Z.label)return $.label<Z.label?-1:1;return 0}function a9($,Z,J){if(Z===void 0)return $;if($!==void 0&&J<$.checkedAt)return $;return{...Z,checkedAt:J}}function _0($,Z){if($!==void 0&&!U0($))throw new t0("stored quota map is malformed");if(!F$(Z))throw new t0("quota observation is malformed");let J=$??{limits:[]},Q=Z.checkedAt,z=new Map;for(let K of J.limits)z.set(B0(K.scope,K.label),K);let W=(K)=>{let U=z.get(K);return U===void 0||Q>=j$(U)},G=new Set;for(let K of Z.readings??[]){let U=K.scope??F0,V=B0(U,K.label);if(G.add(V),!W(V))continue;z.set(V,{scope:U,label:K.label,kind:"reading",checkedAt:Q,usedPercent:K.usedPercent,...K.resetsAt===void 0?{}:{resetsAt:K.resetsAt},...K.windowMinutes===void 0?{}:{windowMinutes:K.windowMinutes}})}for(let K of Z.coverage??[]){let U=K.scope??F0,V=B0(U,K.label);if(G.has(V)||!W(V))continue;let q=z.get(V);z.set(V,q===void 0||q.kind==="absent"?{scope:U,label:K.label,kind:"absent",checkedAt:Q}:{scope:U,label:K.label,kind:"retired",retiredAt:Q})}let{limits:Y,budget:X,...j}=J,H=a9(J.budget,Z.budget,Q);return{...j,limits:[...z.values()].sort(i9),...H===void 0?{}:{budget:H}}}var n9=Object.freeze({validate:U0,merge:_0});function U$($,Z,J){if($.accountIdentity!==void 0&&J!==void 0)return $.accountIdentity===J;return $.credentialId===Z}function e1($,Z,J){return $.some((Q)=>U$(Q,Z,J))}function $3($,Z,J){let Q={credentialId:Z,...J!==void 0&&{accountIdentity:J}};return[...$.filter((z)=>z.credentialId!==Z||z.accountIdentity!==J),Q]}function Z3($,Z,J){return $.filter((Q)=>!Z.some((z)=>U$(Q,z,J)))}var V$="vault:";function r9($){return s9("sha256").update($).digest("hex")}function t9($){let Z=$.credentialId.split(":");return(Z.length>=3?Z.slice(2).join(":").trim():void 0)||$.email||$.credentialId}function e9($){return $.identity!==void 0?`identity:${$.identity}`:`credential:${$.credential.credentialId}`}function Z0($){return[$.credentialId,...$.aliases??[]]}function M$($,Z,J={}){let Q=J.now??Date.now(),z=J.routePrefix??V$,W=J.reservedRouteIds??new Set,G=$?.rows??[],Y=[...$?.declined??[]],X=Z.skipped.length===0,j=new Set(Z.credentials.map((M)=>M.credentialId)),H=new Set(Z.skipped.flatMap((M)=>M.credentialId===void 0?[]:[M.credentialId])),K=Z.skipped.some((M)=>M.credentialId===void 0),U=(M)=>!j.has(M)&&(H.has(M)||K),V=new Map;for(let M of G){if(M.accountIdentity===void 0)continue;for(let D of Z0(M))if(!V.has(D))V.set(D,M.accountIdentity)}let q=new Map;for(let M of Z.credentials){let D=M.accountIdentity!==void 0?{credential:M,identity:M.accountIdentity,claimed:!0}:{credential:M,identity:V.get(M.credentialId),claimed:!1},R=e9(D),k=q.get(R)??[];k.push(D),q.set(R,k)}let B=new Set,I=new Set(W),N=[],A=(M,D)=>M.credential.credentialId.localeCompare(D.credential.credentialId),w=[...q.values()].map((M)=>M.toSorted(A)).sort((M,D)=>M[0]&&D[0]?A(M[0],D[0]):0);for(let M of w){let D=M[0]?.identity,R=M.filter((O)=>O.credential.state==="active"),k=R.length?R:M,E=k.filter((O)=>O.claimed),S=E.length?E:k,m=new Set(M.map((O)=>O.credential.credentialId)),T=G.find((O)=>!B.has(O)&&Z0(O).some((c)=>m.has(c))&&(O.accountIdentity===void 0||O.accountIdentity===D)),C=S.find((O)=>O.credential.credentialId===T?.credentialId)??S[0];if(!C)continue;let x=C.credential,b=T??(D===void 0?void 0:G.find((O)=>!B.has(O)&&O.accountIdentity===D));if(b)B.add(b);let y=b?.routeId;if(!y||W.has(y)){let O=`${z}${x.credentialId}${D===void 0?"":`~${r9(D).slice(0,10)}`}`;y=O;for(let c=2;I.has(y);c++)y=`${O}~${c}`}I.add(y);let p=b?Z0(b).filter(U):[],L=[...new Set([...M.map((O)=>O.credential.credentialId),...p])].filter((O)=>O!==x.credentialId).sort((O,c)=>O.localeCompare(c)),P=J.mapAccount?.(x)??{};N.push({previousIndex:b?G.indexOf(b):1/0,row:{routeId:y,credentialId:x.credentialId,credentialType:x.credentialType,...D!==void 0&&{accountIdentity:D},...L.length&&{aliases:L},state:x.state,label:P.label?.trim()||t9(x),...x.email!==void 0&&{email:x.email},...x.orgName!==void 0&&{orgName:x.orgName},enabled:![x.credentialId,...L].some((O)=>e1(Y,O,D)),addedAt:b?.addedAt??Q,...b?.quota!==void 0&&{quota:b.quota},...!C.claimed&&D!==void 0&&{unclaimed:!0}}})}return G.forEach((M,D)=>{if(B.has(M)||!Z0(M).some(U))return;if(I.has(M.routeId))return;let[R,...k]=Z0(M).filter((m)=>!j.has(m));if(R===void 0)return;I.add(M.routeId);let{aliases:E,...S}=M;N.push({previousIndex:D,row:{...S,credentialId:R,...k.length&&{aliases:k},stale:!0}})}),N.sort((M,D)=>M.previousIndex===D.previousIndex?M.row.credentialId.localeCompare(D.row.credentialId):M.previousIndex-D.previousIndex),{version:1,view:Z.view,complete:X,...!X&&{rejected:Z.skipped.map((M)=>({...M.credentialId!==void 0&&{credentialId:M.credentialId},reason:M.reason}))},rows:N.map((M)=>M.row),declined:Y}}function J3($){return($?.rows??[]).filter((Z)=>Z.enabled&&Z.state==="active").map((Z)=>({id:Z.routeId,kind:Z.credentialType==="oauth"?"oauth":"api-key",...Z.quota!==void 0&&{quota:Z.quota}}))}function Z1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function N0($){return $===void 0||typeof $==="string"}function $7($){if(!Z1($)||typeof $.routeId!=="string"||typeof $.credentialId!=="string"||$.credentialType!=="oauth"&&$.credentialType!=="api_key"||typeof $.state!=="string"||typeof $.label!=="string"||typeof $.enabled!=="boolean"||typeof $.addedAt!=="number"||!N0($.accountIdentity)||!N0($.email)||!N0($.orgName)||$.aliases!==void 0&&(!Array.isArray($.aliases)||!$.aliases.every((Z)=>typeof Z==="string"))||$.quota!==void 0&&!U0($.quota)||$.stale!==void 0&&$.stale!==!0||$.unclaimed!==void 0&&$.unclaimed!==!0)return;return $}var Z7=new Set(["empty credential id","duplicate credential id","blank account identity","empty state"]);function q$($){if(!Array.isArray($))return;let Z=[];for(let J of $){if(!Z1(J)||!N0(J.credentialId)||typeof J.reason!=="string"||!Z7.has(J.reason))return;Z.push(J)}return Z}function J7($){if(!Z1($)||$.version!==1||!N0($.view)||!Array.isArray($.rows)||!Array.isArray($.declined)||$.complete!==void 0&&typeof $.complete!=="boolean"||$.rejected!==void 0&&!q$($.rejected))throw new f("invalid-state","Claustrum roster file is not valid");let Z=[];for(let z of $.rows){let W=$7(z);if(!W)throw new f("invalid-state","Claustrum roster file is not valid");Z.push(W)}let J=[];for(let z of $.declined){if(!Z1(z)||typeof z.credentialId!=="string"||!N0(z.accountIdentity))throw new f("invalid-state","Claustrum roster file is not valid");J.push(z)}let Q=q$($.rejected);return{version:1,...typeof $.view==="string"&&{view:$.view},complete:$.complete!==!1,...Q&&{rejected:Q},rows:Z,declined:J}}async function J0($){let Z;try{Z=await o9($,"utf8")}catch(Q){if(Q.code==="ENOENT")return;throw Q}let J;try{J=JSON.parse(Z)}catch{throw new f("invalid-state","Claustrum roster file is not valid")}return J7(J)}var Q7={name:"claustrum-roster-write",ttlMs:1e4,timeoutMs:5000},z7={name:"claustrum-roster",ttlMs:30000};async function S0($,Z,J={}){return g1($,Q7,async(Q)=>{let z=await J0($),{next:W,result:G}=await Z(z,{assertOwned:()=>Q.assertOwned()});if(W)await Q.assertOwned(),await _1($,W,{beforeRename:async()=>{await J.beforePublish?.(),await Q.assertOwned()}});return G})}function Q3($,Z){return S0($,(J)=>{let Q=J?.rows.find((W)=>W.routeId===Z);if(!J||!Q)throw new f("route-unavailable","Claustrum route is not in the roster");let z=$3(J.declined,Q.credentialId,Q.accountIdentity);return{next:{...J,declined:z,rows:J.rows.map((W)=>W===Q?{...W,enabled:!1}:W)},result:void 0}})}function z3($,Z){return S0($,(J)=>{let Q=J?.rows.find((z)=>z.routeId===Z);if(!J||!Q)throw new f("route-unavailable","Claustrum route is not in the roster");return{next:{...J,declined:Z3(J.declined,Z0(Q),Q.accountIdentity),rows:J.rows.map((z)=>z===Q?{...z,enabled:!0}:z)},result:void 0}})}function W7($,Z){if(!Z0($).includes(Z.credentialId))return"refuse";if($.unclaimed&&(Z.accountIdentitySource==="expected"||Z.accountIdentitySource==="none"))return"refuse";if($.accountIdentity===Z.accountIdentity)return"hold";if($.accountIdentity===void 0&&Z.expectedAccountIdentity===void 0&&Z.accountIdentity!==void 0&&(Z.accountIdentitySource==="asserted"||Z.accountIdentitySource==="parsed")&&Z0($).length===1)return"bind";return"refuse"}function W3($,Z){return S0($,(J)=>{let Q=J?.rows.find((Y)=>Y.routeId===Z.routeId),z=!J||!Q?"refuse":W7(Q,Z);if(!J||!Q||z==="refuse")return{result:!1};let W=_0(Q.quota,Z.observation),G=z==="bind"?{accountIdentity:Z.accountIdentity,unclaimed:!0}:{};return{next:{...J,rows:J.rows.map((Y)=>Y===Q?{...Y,...G,quota:W}:Y)},result:!0}})}async function Y3($){$.signal?.throwIfAborted();let Z=async()=>await $.isActive?.()??!0;if(!await Z())return;let J=await e({...z7,path:$.path,renew:!0});if(!J){let Q=await J0($.path);if($.signal?.throwIfAborted(),!Q?.view)throw new f("roster-busy","Claustrum account discovery is already in progress");return Q}try{let Q=await $.custody.discover($.signal);return $.signal?.throwIfAborted(),await S0($.path,async(z)=>{if(!await Z())return{result:void 0};$.signal?.throwIfAborted(),await J.assertOwned();let W=typeof $.projection==="function"?$.projection():$.projection,G=M$(z,Q,W);return{...JSON.stringify(z)!==JSON.stringify(G)&&{next:G},result:G}})}finally{await J.release()}}class D${#$;#J=new AbortController;#Z;#W;#X;#z;#Q;#Y;#H=!1;constructor($){this.#$=$,this.#Z=$.logger??R0("claustrum")}#G($){this.#J.signal.throwIfAborted(),$?.throwIfAborted()}async#j(){return await this.#$.isCustodyActive?.()??!0}#K($,Z){let J=E1([this.#J.signal,...Z?[Z]:[]]);return new Promise((Q,z)=>{let W=()=>{J.signal.removeEventListener("abort",G),J.dispose()},G=()=>{W(),z(J.signal.reason)};if(J.signal.addEventListener("abort",G,{once:!0}),$.then((Y)=>{if(W(),J.signal.aborted)z(J.signal.reason);else Q(Y)},(Y)=>{W(),z(Y)}),J.signal.aborted)G()})}async#F(){if(this.#G(),this.#W)return this.#W;if(!this.#X)this.#X=this.#$.connect().then(($)=>{if(this.#J.signal.aborted)$.close(),this.#G();return this.#W=new r0({client:$,family:this.#$.family,tokenPath:this.#$.tokenPath,parseIdentity:this.#$.parseIdentity,requireAssertion:this.#$.requireAssertion,now:this.#$.now,logger:this.#Z}),this.#W}).finally(()=>{this.#X=void 0});return this.#K(this.#X)}snapshot(){return this.#Q}routingRows(){return J3(this.#Q)}refresh(){if(this.#G(),this.#z)return this.#z;return this.#z=(async()=>{if(!await this.#j()){this.#Q=void 0,this.#W?.close(),this.#W=void 0;return}let $=await this.#F(),Z=await Y3({path:this.#$.rosterPath,custody:$,isActive:()=>this.#j(),signal:this.#J.signal,projection:()=>({reservedRouteIds:new Set(this.#$.reservedRouteIds?.()??[]),routePrefix:this.#$.routePrefix,mapAccount:this.#$.mapAccount,now:(this.#$.now??Date.now)()})});this.#G();let J=Z?.view!==this.#Q?.view;if(this.#Q=Z,Z&&J)this.#$.onRoster?.(Z);return Z})().finally(()=>{this.#z=void 0}),this.#z}start(){if(this.#H)return;this.#G(),this.#H=!0;let $=async()=>{try{await this.refresh()}catch(J){if(!this.#J.signal.aborted)this.#$.onError?.(J)}if(this.#J.signal.aborted)return;let Z=this.#$.pollIntervalMs??5000;if(Z<=0)return;this.#Y=(this.#$.setTimeoutImpl??setTimeout)(()=>{this.#Y=void 0,$()},Z),this.#Y.unref?.()};$()}async authorize($,Z){this.#G(Z);let J=this.#Q??await this.#K(this.refresh(),Z);if(!J||!await this.#j())throw new f("not-active","Claustrum scoped custody is not active");let Q=await J0(this.#$.rosterPath);this.#G(Z);let z=J.rows.find((X)=>X.routeId===$),W=Q?.rows.find((X)=>X.routeId===$);if(W&&!W.enabled)throw new f("route-declined","Claustrum route is disabled");if(!z||!W||W.state!=="active"||W.credentialId!==z.credentialId||W.accountIdentity!==z.accountIdentity)throw new f("route-unavailable","Claustrum route is disabled, removed or changed");let G=await this.#K(this.#F(),Z),Y=E1([this.#J.signal,...Z?[Z]:[]]);try{return await G.authorize({credentialId:W.credentialId,credentialType:W.credentialType,...W.accountIdentity!==void 0&&{accountIdentity:W.accountIdentity}},Y.signal)}finally{Y.dispose()}}async reportFailure($,Z,J){if(this.#G(),!this.#W)throw new f("no-receipt","Claustrum dispatch receipt has no active owner");await this.#W.reportFailure($,Z,J)}async send($,Z,J){let Q=J.signal,z=await this.authorize($,Q),W=await Z(z,Q);if(W.status===401&&!Q?.aborted){let G;try{G=await this.authorize($,Q)}catch{}if(s1(J.site,z,G,this.#Z))await W.body?.cancel().catch(()=>{}),z=G,W=await Z(G,Q)}if(W.status===401)await this.reportFailure(z,401,J.reporterSource??"direct").catch((G)=>this.#$.onError?.(G)),Promise.resolve().then(()=>this.refresh()).catch((G)=>{if(!this.#J.signal.aborted)this.#$.onError?.(G)});return W}async decline($){this.#G(),await Q3(this.#$.rosterPath,$),this.#Q=await J0(this.#$.rosterPath)}async accept($){this.#G(),await z3(this.#$.rosterPath,$),this.#Q=await J0(this.#$.rosterPath)}async recordQuota($,Z,J){this.#G();let Q=await W3(this.#$.rosterPath,{routeId:$,observation:Z,credentialId:J.credentialId,accountIdentitySource:J.accountIdentitySource,...J.accountIdentity!==void 0&&{accountIdentity:J.accountIdentity},...J.expectedAccountIdentity!==void 0&&{expectedAccountIdentity:J.expectedAccountIdentity}});if(Q)this.#Q=await J0(this.#$.rosterPath);return Q}close(){if(this.#J.signal.aborted)return;if(this.#J.abort(new f("closed","Claustrum consumer is closed")),this.#Y)(this.#$.clearTimeoutImpl??clearTimeout)(this.#Y);this.#Y=void 0,this.#W?.close(),this.#Q=void 0}}class o extends Error{code;constructor($){super(`Native vault setup: ${$}`);this.code=$;this.name="NativeVaultEnrollmentError"}}async function B$($,Z){let J={...Z.env},Q=Z.paths??L$($,J),z=`anthropic-auth-${$}`,W=Z.processFence,G=Z.runner,Y=Z.ckBinary??"ck",X,j=Z.client;try{await W();let H=await s0(Q,z),K=new Set(["superseded","not_found","already_consumed"]);if(H.state==="idle"||H.state==="pending"||H.state==="blocked"&&K.has(H.code)){if(!j)X=await c1({connectionFile:J1(Z.connectionFile??($==="pi"?J.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0),$==="pi"?{...J,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:void 0}:J)}),j=X;let V=j,q=new o0({paths:Q,proposedName:z,client:{enrollPropose:async(B)=>{return await W(),V.enrollPropose(B)},enrollPoll:async(B)=>{return await W(),V.enrollPoll(B)}},writeTokenFile:async(B,I)=>{await W(),await n0(B,I)}});if(H.state==="blocked"){if(await W(),await q.resetTerminal()!=="reset")throw new o("enrollment-refused");throw new o("enrollment-reset")}if(await W(),H=await q.reconcile(),H.state==="pending"&&H.requestId){if(await W(),(await G.run(Y,["auth","enroll","approve","--request-id",H.requestId,"--name",z],{env:J})).exitCode!==0)throw new o("approval-refused");await W(),H=await q.reconcile()}}if(H.state!=="approved")throw new o("enrollment-refused");if(await W(),(await G.run(Y,["auth","grant","--principal",`enrolled:${z}`,"--selector-kind","category","--selector","anthropic-native","--operation","read"],{env:J})).exitCode!==0)throw new o("permission-refused")}catch(H){if(H instanceof o)throw H;throw new o("enrollment-refused")}finally{X?.close()}}import{dirname as Y7,join as N$,resolve as Q1}from"node:path";async function O0($,Z){let J=$==="pi"?P0(Z):q0(Z),Q=$==="pi"?Z.PI_ANTHROPIC_AUTH_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_FILE?.trim(),z=Q1(Q||N$(J,G3)),W=Q1(Z.OPENCODE_ANTHROPIC_AUTH_STATE_FILE?.trim()||(z.endsWith(G3)?N$(Y7(z),P$):`${z}.state.json`)),G=await z1(z,W),Y=$==="pi"?Z.PI_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim():Z.OPENCODE_ANTHROPIC_AUTH_ROUTING_STATE_FILE?.trim();return{host:$,paths:G,legacyConfigPath:z,legacyStatePath:W,hostAuthPath:$==="pi"?Y1(Z):W1(Z),routingSourcePath:Q1(Y||X3(z)),routingDestinationPath:Q1(Y||X3(G.config))}}async function I$($){let Z=new Map;for(let J of $)for(let Q of[J.paths.legacyConfig,J.paths.legacyState,J.paths.config,J.paths.state,J.paths.runtime,J.paths.roster,J.paths.journal,J.hostAuthPath,J.routingSourcePath,J.routingDestinationPath]){let z=await O$(Q),W=Z.get(z);if(W!==void 0&&W!==J.host)throw Error("Native setup storage paths overlap between selected hosts");Z.set(z,J.host)}}import{execFile as G7}from"node:child_process";import{promisify as X7}from"node:util";var j7=X7(G7),l={async run($,Z,J={}){try{let Q=J.env?{...process.env,...J.env}:process.env,{stdout:z,stderr:W}=await j7($,Z,{env:Q,timeout:J.timeoutMs??15000,maxBuffer:10485760});return{exitCode:0,stdout:typeof z==="string"?z:String(z),stderr:typeof W==="string"?W:String(W)}}catch(Q){let z=Q;return{exitCode:typeof z?.code==="number"?z.code:1,stdout:typeof z?.stdout==="string"?z.stdout:z?.stdout!=null?String(z.stdout):"",stderr:typeof z?.stderr==="string"?z.stderr:z?.stderr!=null?String(z.stderr):String(z?.message??Q)}}}};var f$=/(?:^|[/\\])(opencode|litecode|opencode2|pi)(?:\.exe)?(?=$|\s|")/i;class Q0 extends Error{code="process-inspection-failed";constructor(){super("Process inspection failed; setup cannot prove hosts are stopped.");this.name="ProcessInspectionError"}}class G1 extends Error{activeHosts;constructor($){let Z=$.map((Q)=>({pid:Q.pid,command:f$.exec(Q.command)?.[1]??"host"})),J=Z.map((Q)=>` - PID ${Q.pid}: ${Q.command}`).join(`
|
|
11
|
+
`);super(`OpenCode or Pi processes are currently running:
|
|
12
|
+
${J}
|
|
13
|
+
|
|
14
|
+
Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);this.activeHosts=Z,this.name="ProcessFenceViolationError"}}function K7($=l,Z={}){let J=(Z.platform??process.platform)==="win32";return{async listRunningHosts(Q){let z=J?"tasklist":"ps",W=J?["/fo","csv","/nh"]:["-eo","pid,command"],G;try{G=await $.run(z,W,{env:Q})}catch{throw new Q0}if(G.exitCode!==0)throw new Q0;let Y=G.stdout.split(/\r?\n/),X=[],j=process.pid;for(let H of Y){let K=H.trim();if(!K)continue;let U,V;if(J){let q=K.split(",").map((B)=>B.replace(/^"|"$/g,""));if(q.length<2)throw new Q0;V=q[0]??"",U=Number(q[1])}else{let q=/^(\d+)\s+(.+)$/.exec(K);if(!q){if(/^PID\s+COMMAND$/i.test(K))continue;throw new Q0}U=Number(q[1]),V=q[2]??""}if(!Number.isInteger(U)||U<0)throw new Q0;if(U===j)continue;if(f$.test(V))X.push({pid:U,command:V})}return X}}}var j3=K7(l);async function I0($=j3){let Z=await $.listRunningHosts();if(Z.length>0)throw new G1(Z)}class V0 extends Error{code;constructor($){super({"auth-content-refused":"Run setup without OPENCODE_AUTH_CONTENT in the environment.","host-auth-invalid":"The host auth file could not be read safely.","primary-conflict":"Pi has a stored Anthropic API key, which would take precedence over the vault account. Remove it in Pi, then rerun setup.","consent-required":"Pi has stored Anthropic authentication. Explicit consent is required to move it aside for vault use.","primary-unverified":"The vault has no verified default Claude account. Sign in through the vault and rerun setup."}[$]);this.code=$;this.name="NativeVaultActivationError"}}async function F7($){try{return JSON.parse(await H7($,"utf8"))}catch(Z){if(Z.code==="ENOENT")return;throw new V0("host-auth-invalid")}}async function C$($,Z){let J={...Z.env},Q=async()=>{try{X1(J)}catch{throw new V0("auth-content-refused")}await I0(Z.fence)};await Q();let z=Z.paths??await O0($,J);if($==="pi"){let X=b$("pi",await F7(z.hostAuthPath)),j=await K3({env:J,authPath:z.hostAuthPath}).inspect();if(j.slot==="placeholder"&&j.stash==="missing")throw new j1("missing-stash");if(X.kind!=="absent"&&j.slot!=="placeholder"&&!Z.removePiAnthropicAuth)throw new V0("consent-required")}let W=await z0($,J);await B$($,{env:J,runner:Z.runner,processFence:Q,...Z.enrollment});let G=Z.discover??(()=>k$({paths:z.paths,host:$,env:$==="pi"?{...J,OPENCODE_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE:J.PI_ANTHROPIC_AUTH_CLAUSTRUM_CONNECTION_FILE}:J})),Y=f0({paths:z.paths,host:$,vault:{env:J,discover:G}});try{await Q(),await Y.vault.refresh();let X=await Y.read(),j=X.accounts.find((H)=>H.id==="main");if(X.mode!=="claustrum"||!j?.accountIdentity||j.source!=="vault")throw new V0("primary-unverified");if(await Q(),$==="pi")await K3({env:J,authPath:z.hostAuthPath}).enterVault();return W==="claustrum"?"already-vault":"committed"}finally{Y.close()}}var L7={"setup-activation":"Vault custody setup","setup-opencode-config":"OpenCode configuration","setup-pi-install":"Pi extension installation","setup-pi":"Pi setup","setup-process-check":"Host process check","cli-setup":"Setup","cli-login":"Login","cli-api-add":"API route setup","cli-list":"Account listing","cli-relay-setup":"Relay setup","cli-relay-workers-dev":"Workers.dev enablement","cli-command":"Command"};function x0(){return($)=>$}var B7=x0()(["auth-content-refused","host-auth-invalid","primary-conflict","consent-required","primary-unverified"]),N7=x0()(["enrollment-refused","enrollment-reset","approval-refused","permission-refused"]),P7=x0()(["invalid-source","unsafe-source","consent-required","primary-unverified","migration-busy","ownership-lost","retirement-refused"]),O7=x0()(["invalid-options","invalid-auth","invalid-stash","unsafe-path","missing-stash","conflict","lock-timeout","lock-compromised","io"]),I7=x0()(["closed","not-enrolled","invalid-token","unavailable","identity-changed","identity-unasserted","insufficient-validity","invalid-material","not-active","route-unavailable","route-declined","no-receipt","unsafe-file","invalid-state","wrong-consumer","roster-busy","host-slot-login","host-slot-placeholder","placeholder-refresh"]),f7=new Set([new Q0().message,...B7.map(($)=>new V0($).message),...N7.map(($)=>new o($).message),...P7.map(($)=>new x$($).message),...O7.map(($)=>new j1($).message),...I7.map(($)=>`Native custody refused: ${$}`),"Disconnect from the vault first.","Native account changes require offline setup without OPENCODE_AUTH_CONTENT","Local login cannot be verified while OPENCODE_AUTH_CONTENT is set","Authentication failed","API fallback base URL must be an http(s) URL without embedded credentials","API key is required","Vault routes cannot be replaced with a local API key","Cloudflare API token is required","Cloudflare account ID is required","Relay Worker URL is required","Claude sign-in did not establish an account UUID","Native setup storage paths overlap between selected hosts","Anthropic account storage paths overlap; migration requires separate files","Anthropic account migration is required. Stop OpenCode, LiteCode and Pi, then run bunx @cortexkit/opencode-anthropic-auth@2.0.0 setup","Anthropic account migration is incomplete; resume setup","Anthropic account migration journal is invalid","Anthropic account migration journal changed","Anthropic runtime state is invalid","Anthropic runtime file is not owner-only regular storage","Anthropic runtime storage is unavailable","Anthropic runtime observation is older than persisted state","Anthropic runtime publication was refused","OAuth metadata read failed"]),b7=new Set(["opencode","litecode","opencode2","pi","host"]),k7=64,C7=256,R7=4096,H3=65536,A7=4096,E7=3,A$="[output beyond the diagnostic limit omitted]",w7="[output withheld: no line break within the inspected window]",_7="[detail withheld: the known credentials could not be read safely]",q3=new TextEncoder,g$=new TextDecoder;function i($,Z){let J=Object.getOwnPropertyDescriptor($,Z);return J!==void 0&&"value"in J?J.value:void 0}function g0($){return $!==null&&(typeof $==="object"||typeof $==="function")&&!U3.isProxy($)}function T$($,Z){if(!g0($)||!Array.isArray($))return;let J=i($,"length");if(typeof J!=="number"||J>Z)return;let Q=[];for(let z=0;z<J;z+=1){let W=Object.getOwnPropertyDescriptor($,String(z));if(W===void 0||!("value"in W))return;Q.push(W.value)}return Q}function S7($){let Z=T$($,k7);if(Z===void 0||Z.length===0)return;let J=[];for(let Q of Z){if(!g0(Q))return;let z=i(Q,"pid"),W=i(Q,"command");if(typeof z!=="number"||!Number.isSafeInteger(z)||z<0)return;if(typeof W!=="string"||!b7.has(W.toLowerCase()))return;J.push({pid:z,command:W})}return J}function x7($){try{if(!g0($))return;let Z=i($,"message");if(typeof Z!=="string")return;if(f7.has(Z))return Z;let J=i($,"status");if(typeof J==="number"&&Number.isInteger(J)&&J>=100&&J<=599&&Z===`OAuth metadata read failed: ${J}`)return Z;let Q=S7(i($,"activeHosts"));if(Q&&Z===new G1(Q).message)return Z}catch{}return}function g7($,Z=[]){try{let J=new Set,Q=T$(Z,C7);if(Q===void 0)return;for(let W of Q){if(typeof W!=="string")return;if(W!=="")J.add(W)}if(!g0($))return;let z=Reflect.ownKeys($);if(z.length>R7)return;for(let W of z){if(typeof W!=="string"||!w$(W))continue;let G=Object.getOwnPropertyDescriptor($,W);if(G===void 0)continue;if(!("value"in G))return;if(G.value===void 0||G.value==="")continue;if(typeof G.value!=="string")return;J.add(G.value)}return[...J]}catch{return}}function T7($,Z){let J=q3.encode($);if(J.length<=Z)return $;let Q=Math.max(0,Z);while(Q>0&&((J[Q]??0)&192)===128)Q-=1;return g$.decode(J.subarray(0,Q))}function h7($,Z){let J=q3.encode($);if(J.length<=Z)return $;let Q=J.length-Math.max(0,Z);while(Q<J.length&&((J[Q]??0)&192)===128)Q+=1;return g$.decode(J.subarray(Q))}function y7($,Z,J){let Q=$,z=!1;if($.length>H3){if(z=!0,J==="tail"){let X=$.indexOf(`
|
|
15
|
+
`,$.length-H3);Q=X===-1?"":$.slice(X+1)}else{let X=$.lastIndexOf(`
|
|
16
|
+
`,H3);Q=X===-1?"":$.slice(0,X)}if(Q==="")return[w7]}let W=Z.redactText(Q).split(/\r?\n/);if(W.length>1&&W[W.length-1]==="")W.pop();if(J==="tail")W.reverse();let G=[],Y=A7;for(let X of W){let j=q3.encode(X).length+1;if(j<=Y){G.push(X),Y-=j;continue}if(G.length===0)G.push(J==="tail"?h7(X,Y-1):T7(X,Y-1));z=!0;break}if(J==="tail")G.reverse();if(z)if(J==="tail")G.unshift(A$);else G.push(A$);return G}function m7($){let Z=$;for(let J=0;Z!==null&&J<8;J+=1){if(U3.isProxy(Z))break;let Q=i(Z,"name");if(typeof Q==="string")return Q;Z=Object.getPrototypeOf(Z)}return"object"}function h$($,Z){if($===null||typeof $!=="object"&&typeof $!=="function")return[`thrown ${typeof $}: ${String($)}`];if(U3.isProxy($))return["thrown proxy (not inspected)"];let J=[],Q=m7($),z=i($,"message");J.push(typeof z==="string"?`${Q}: ${z}`:`${Q} (no message)`);let W=i($,"code");if(typeof W==="string"||typeof W==="number")J.push(`code: ${W}`);let G=i($,"stack");if(typeof G==="string")J.push(G);let Y=i($,"cause");if(Y!==void 0)if(Z>=E7)J.push("caused by: [not described]");else J.push("caused by:",...h$(Y,Z+1));return J}function E$($,Z){let J=i($,Z);return typeof J==="string"&&J!==""?J:void 0}function v7($){if(!g0($))return;let Z=E$($,"XDG_STATE_HOME"),J=E$($,"HOME"),Q=Z&&R$(Z)?Z:F3(J&&R$(J)?J:D7(),".local","state");return F3(Q,"cortexkit","anthropic-auth","diagnostics")}async function p7($,Z,J){try{let Q=v7($);if(Q===void 0)return;await V7(Q,{recursive:!0,mode:448});let z=await q7(Q);if(!z.isDirectory())return;if(process.platform!=="win32"){if((z.mode&63)!==0)return;if(z.uid!==process.getuid?.())return}let W=F3(Q,`${Z}-${Date.now()}-${process.pid}-${U7()}.log`),G=await M7(W,K1.O_WRONLY|K1.O_CREAT|K1.O_EXCL|(K1.O_NOFOLLOW??0),384);try{await G.writeFile(J,"utf8")}finally{await G.close()}return W}catch{return}}async function y$($,Z,J,Q,z,W){let G,Y=g7(J,Q);if(Y===void 0)G=[_7];else try{let K=S$(Y);try{let{text:U,keep:V}=W();G=y7(U,K,V)}finally{K.dispose()}}catch{G=["[failure detail could not be recorded]"]}let X=L7[$],j=_$("error","cli",`${X} failed`,{stage:$,code:Z,...z}),H=await p7(J,$,`${[j,...G].join(`
|
|
17
|
+
`)}
|
|
18
|
+
`);return H===void 0?`${X} failed (${Z}). Details could not be saved to a private diagnostics file.`:`${X} failed (${Z}). Details were written to ${H}`}async function W0($,Z,J,Q=[]){let z=x7(Z);if(z!==void 0)return z;return y$($,`${$}/unexpected-error`,J,Q,{},()=>({text:h$(Z,0).join(`
|
|
19
|
+
`),keep:"head"}))}async function m$($,Z,J){return y$($,`${$}/installer-exit`,J,[],{exitCode:Number.isInteger(Z.exitCode)?Z.exitCode:null},()=>({text:typeof Z.stderr==="string"?Z.stderr:"",keep:"tail"}))}import{styleText as V1}from"node:util";import{stdout as O3,stdin as W2}from"node:process";import*as Y0 from"node:readline";import z4 from"node:readline";var v$=(()=>{let $=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(Z)=>{let J=0;$.lastIndex=0;while($.test(Z))J+=1;return Z.length-J}})(),p$=($)=>{return $===12288||$>=65281&&$<=65376||$>=65504&&$<=65510},c$=($)=>{return $===8987||$===9001||$>=12272&&$<=12287||$>=12289&&$<=12350||$>=12441&&$<=12543||$>=12549&&$<=12591||$>=12593&&$<=12686||$>=12688&&$<=12771||$>=12783&&$<=12830||$>=12832&&$<=12871||$>=12880&&$<=19903||$>=65040&&$<=65049||$>=65072&&$<=65106||$>=65108&&$<=65126||$>=65128&&$<=65131||$>=127488&&$<=127490||$>=127504&&$<=127547||$>=127552&&$<=127560||$>=131072&&$<=196605||$>=196608&&$<=262141};var c7=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,d7=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,d$=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,u7=/\t{1,1000}/y,u$=/[\u{1F1E6}-\u{1F1FF}]{2}|\u{1F3F4}[\u{E0061}-\u{E007A}]{2}[\u{E0030}-\u{E0039}\u{E0061}-\u{E007A}]{1,3}\u{E007F}|(?:\p{Emoji}\uFE0F\u20E3?|\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation})(?:\u200D(?:\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F\u20E3?))*/yu,l7=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,i7=/\p{M}+/gu,a7={limit:1/0,ellipsis:""},l$=($,Z={},J={})=>{let Q=Z.limit??1/0,z=Z.ellipsis??"",W=Z?.ellipsisWidth??(z?l$(z,a7,J).width:0),G=0,Y=J.controlWidth??0,X=J.tabWidth??8,j=J.emojiWidth??2,H=2,K=J.regularWidth??1,U=J.wideWidth??2,V=[[l7,K],[c7,0],[d7,Y],[u7,X],[u$,j],[d$,U]],q=0,B=0,I=$.length,N=0,A=!1,w=I,M=Math.max(0,Q-W),D=0,R=0,k=0,E=0;$:while(!0){if(R>D||B>=I&&B>q){let S=$.slice(D,R)||$.slice(q,B);N=0;for(let m of S.replaceAll(i7,"")){let T=m.codePointAt(0)||0;if(p$(T))E=2;else if(c$(T))E=U;else E=K;if(k+E>M)w=Math.min(w,Math.max(D,q)+N);if(k+E>Q){A=!0;break $}N+=m.length,k+=E}D=R=0}if(B>=I)break $;for(let S=0,m=V.length;S<m;S++){let[T,C]=V[S];if(T.lastIndex=B,T.test($)){if(N=T===d$?v$($.slice(B,T.lastIndex)):T===u$?1:T.lastIndex-B,E=N*C,k+E>M)w=Math.min(w,B+Math.floor((M-k)/C));if(k+E>Q){A=!0;break $}k+=E,D=q,R=B,B=q=T.lastIndex;continue $}}B+=1}return{width:A?M:k,index:A?w:I,truncated:A,ellipsed:A&&Q>=W}},i$=l$;var n7={limit:1/0,ellipsis:"",ellipsisWidth:0},s7=($,Z={})=>{return i$($,n7,Z).width},u=s7;var H1="\x1B",r$="",o7=39,M3="\x07",t$="[",r7="]",e$="m",D3=`${r7}8;;`,a$=new RegExp(`(?:\\${t$}(?<code>\\d+)m|\\${D3}(?<uri>.*)${M3})`,"y"),n$=($)=>{if($>=30&&$<=37)return 39;if($>=90&&$<=97)return 39;if($>=40&&$<=47)return 49;if($>=100&&$<=107)return 49;if($===1||$===2)return 22;if($===3)return 23;if($===4)return 24;if($===7)return 27;if($===8)return 28;if($===9)return 29;if($===0)return 0;return},s$=($)=>`${H1}${t$}${$}${e$}`,o$=($)=>`${H1}${D3}${$}${M3}`,V3=($,Z,J)=>{let Q=Z[Symbol.iterator](),z=!1,W=!1,G=$.at(-1),Y=G===void 0?0:u(G),X=Q.next(),j=Q.next(),H=0;while(!X.done){let K=X.value,U=u(K);if(Y+U<=J)$[$.length-1]+=K;else $.push(K),Y=0;if(K===H1||K===r$)z=!0,W=Z.startsWith(D3,H+1);if(z){if(W){if(K===M3)z=!1,W=!1}else if(K===e$)z=!1}else if(Y+=U,Y===J&&!j.done)$.push(""),Y=0;X=j,j=Q.next(),H+=K.length}if(G=$.at(-1),!Y&&G!==void 0&&G.length&&$.length>1)$[$.length-2]+=$.pop()},t7=($)=>{let Z=$.split(" "),J=Z.length;while(J){if(u(Z[J-1]))break;J--}if(J===Z.length)return $;return Z.slice(0,J).join(" ")+Z.slice(J).join("")},e7=($,Z,J={})=>{if(J.trim!==!1&&$.trim()==="")return"";let Q="",z,W,G=$.split(" "),Y=[""],X=0;for(let K=0;K<G.length;K++){let U=G[K];if(J.trim!==!1){let q=Y.at(-1)??"",B=q.trimStart();if(q.length!==B.length)Y[Y.length-1]=B,X=u(B)}if(K!==0){if(X>=Z&&(J.wordWrap===!1||J.trim===!1))Y.push(""),X=0;if(X||J.trim===!1)Y[Y.length-1]+=" ",X++}let V=u(U);if(J.hard&&V>Z){let q=Z-X,B=1+Math.floor((V-q-1)/Z);if(Math.floor((V-1)/Z)<B)Y.push("");V3(Y,U,Z),X=u(Y.at(-1)??"");continue}if(X+V>Z&&X&&V){if(J.wordWrap===!1&&X<Z){V3(Y,U,Z),X=u(Y.at(-1)??"");continue}Y.push(""),X=0}if(X+V>Z&&J.wordWrap===!1){V3(Y,U,Z),X=u(Y.at(-1)??"");continue}Y[Y.length-1]+=U,X+=V}if(J.trim!==!1)Y=Y.map((K)=>t7(K));let j=Y.join(`
|
|
20
|
+
`),H=!1;for(let K=0;K<j.length;K++){let U=j[K];if(Q+=U,!H){if(H=U>="\uD800"&&U<="\uDBFF",H)continue}else H=!1;if(U===H1||U===r$){a$.lastIndex=K+1;let q=a$.exec(j)?.groups;if(q?.code!==void 0){let B=Number.parseFloat(q.code);z=B===o7?void 0:B}else if(q?.uri!==void 0)W=q.uri.length===0?void 0:q.uri}if(j[K+1]===`
|
|
21
|
+
`){if(W)Q+=o$("");let V=z?n$(z):void 0;if(z&&V)Q+=s$(V)}else if(U===`
|
|
22
|
+
`){if(z&&n$(z))Q+=s$(z);if(W)Q+=o$(W)}}return Q},$4=/\r?\n/;function r($,Z,J){return String($).normalize().split($4).map((Q)=>e7(Q,Z,J)).join(`
|
|
23
|
+
`)}var d=z2(B3(),1);import{ReadStream as Z2}from"node:tty";function b0($,Z,J){if(!J.some((G)=>!G.disabled))return $;let Q=$+Z,z=Math.max(J.length-1,0),W=Q<0?z:Q>z?0:Q;return J[W]?.disabled?b0(W,Z<0?-1:1,J):W}function F1($,Z,J,Q){let z=Q.split(`
|
|
24
|
+
`),W=0,G=$;for(let X of z){if(G<=X.length)break;G-=X.length+1,W++}for(W=Math.max(0,Math.min(z.length-1,W+J)),G=Math.min(G,z[W].length)+Z;G<0&&W>0;)W--,G+=z[W].length+1;for(;G>z[W].length&&W<z.length-1;)G-=z[W].length+1,W++;G=Math.max(0,Math.min(z[W].length,G));let Y=0;for(let X=0;X<W;X++)Y+=z[X].length+1;return Y+G}var W4=["up","down","left","right","space","enter","cancel"],Y4=["January","February","March","April","May","June","July","August","September","October","November","December"],v={actions:new Set(W4),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["\x03","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0,accessible:void 0,date:{monthNames:[...Y4],messages:{required:"Please enter a valid date",invalidMonth:"There are only 12 months in a year",invalidDay:($,Z)=>`There are only ${$} days in ${Z}`,afterMin:($)=>`Date must be on or after ${$.toISOString().slice(0,10)}`,beforeMax:($)=>`Date must be on or before ${$.toISOString().slice(0,10)}`}}};function G4($){if($!==void 0)return $;if(v.accessible!==void 0)return v.accessible;let Z=process.env.ACCESSIBLE;return Z!==void 0&&Z!==""&&Z!=="0"&&Z!=="false"}function I3($,Z){if(typeof $=="string")return v.aliases.get($)===Z;for(let J of $)if(J!==void 0&&I3(J,Z))return!0;return!1}function X4($,Z){if($===Z)return;let J=$.split(`
|
|
25
|
+
`),Q=Z.split(`
|
|
26
|
+
`),z=Math.max(J.length,Q.length),W=[];for(let G=0;G<z;G++)J[G]!==Q[G]&&W.push(G);return{lines:W,numLinesBefore:J.length,numLinesAfter:Q.length,numLines:z}}var j4=globalThis.process.platform.startsWith("win"),M1=Symbol("clack:cancel");function G0($){return $===M1}function U1($,Z){let J=$;J.isTTY&&J.setRawMode(Z)}function Y2({input:$=W2,output:Z=O3,overwrite:J=!0,hideCursor:Q=!0}={}){let z=Y0.createInterface({input:$,output:Z,prompt:"",tabSize:1});Y0.emitKeypressEvents($,z),$ instanceof Z2&&$.isTTY&&$.setRawMode(!0);let W=(G,{name:Y,sequence:X})=>{let j=String(G);if(I3([j,Y,X],"cancel")){Q&&Z.write(d.cursor.show),process.exit(0);return}if(!J)return;Y0.moveCursor(Z,Y==="return"?0:-1,Y==="return"?-1:0,()=>{Y0.clearLine(Z,1,()=>{$.once("keypress",W)})})};return Q&&Z.write(d.cursor.hide),$.once("keypress",W),()=>{$.off("keypress",W),Q&&Z.write(d.cursor.show),$ instanceof Z2&&$.isTTY&&!j4&&$.setRawMode(!1),z.terminal=!1,z.close()}}var T0=($)=>("columns"in $)&&typeof $.columns=="number"?$.columns:80,f3=($)=>("rows"in $)&&typeof $.rows=="number"?$.rows:20;function h0($,Z,J,Q=J,z=J,W){let G=T0($??O3);return r(Z,G-J.length,{hard:!0,trim:!1}).split(`
|
|
27
|
+
`).map((Y,X,j)=>{let H=W?W(Y,X):Y;return X===0?`${Q}${H}`:X===j.length-1?`${z}${H}`:`${J}${H}`}).join(`
|
|
28
|
+
`)}function G2($,Z){if("~standard"in $){let J=$["~standard"].validate(Z);return J instanceof Promise?J.then((Q)=>Q.issues?.at(0)?.message):J.issues?.at(0)?.message}return $(Z)}class X0{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";get accessible(){return G4(this.opts.accessible)}constructor($,Z=!0){let{input:J=W2,output:Q=O3,render:z,signal:W,...G}=$;this.opts=G,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=z.bind(this),this._track=Z,this._abortSignal=W,this.input=J,this.output=Q}unsubscribe(){this._subscribers.clear()}setSubscriber($,Z){let J=this._subscribers.get($)??[];J.push(Z),this._subscribers.set($,J)}on($,Z){this.setSubscriber($,{cb:Z})}once($,Z){this.setSubscriber($,{cb:Z,once:!0})}emit($,...Z){let J=this._subscribers.get($)??[],Q=[];for(let z of J)z.cb(...Z),z.once&&Q.push(()=>J.splice(J.indexOf(z),1));for(let z of Q)z()}prompt(){return new Promise(($)=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),$(M1);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=z4.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),U1(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(d.cursor.show),this.output.off("resize",this.render),U1(this.input,!1),$(this.value)}),this.once("cancel",()=>{this.output.write(d.cursor.show),this.output.off("resize",this.render),U1(this.input,!1),$(M1)})})}_isActionKey($,Z){return $==="\t"}_shouldSubmit($,Z){return!0}_setValue($){this.value=$,this.emit("value",this.value)}_setUserInput($,Z){this.userInput=$??"",this.emit("userInput",this.userInput),Z&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}async onKeypress($,Z){if(this.state!=="validating"){if(this._track&&Z.name!=="return"&&(Z.name&&this._isActionKey($,Z)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),Z?.name&&(!this._track&&v.aliases.has(Z.name)&&this.emit("cursor",v.aliases.get(Z.name)),v.actions.has(Z.name)&&this.emit("cursor",Z.name)),$&&($.toLowerCase()==="y"||$.toLowerCase()==="n")&&this.emit("confirm",$.toLowerCase()==="y"),this.emit("key",$,Z),Z?.name==="return"&&this._shouldSubmit($,Z)){if(this.opts.validate){let J=G2(this.opts.validate,this.value),Q;J instanceof Promise?(this.state="validating",this.render(),Q=await J):Q=J,Q&&(this.error=Q instanceof Error?Q.message:Q,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}I3([$,Z?.name,Z?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
|
|
29
|
+
`),U1(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let $=r(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
30
|
+
`).length-1;this.output.write(d.cursor.move(-999,$*-1))}render(){let $=r(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if($!==this._prevFrame){if(this.state==="initial")this.output.write(d.cursor.hide);else{let Z=X4(this._prevFrame,$),J=f3(this.output);if(this.restoreCursor(),Z){let Q=Math.max(0,Z.numLinesAfter-J),z=Math.max(0,Z.numLinesBefore-J),W=Z.lines.find((G)=>G>=Q);if(W===void 0){this._prevFrame=$;return}if(Z.lines.length===1){this.output.write(d.cursor.move(0,W-z)),this.output.write(d.erase.lines(1));let G=$.split(`
|
|
31
|
+
`);this.output.write(G[W]),this._prevFrame=$,this.output.write(d.cursor.move(0,G.length-W-1));return}else if(Z.lines.length>1){if(Q<z)W=Q;else{let Y=W-z;Y>0&&this.output.write(d.cursor.move(0,Y))}this.output.write(d.erase.down());let G=$.split(`
|
|
32
|
+
`).slice(W);this.output.write(G.join(`
|
|
33
|
+
`)),this._prevFrame=$;return}}this.output.write(d.erase.down())}this.output.write($),this.state==="initial"&&(this.state="active"),this._prevFrame=$}}}function K4($,Z){if($===void 0||Z.length===0)return 0;let J=Z.findIndex((Q)=>Q.value===$);return J!==-1?J:0}function H4($,Z){return(Z.label??String(Z.value)).toLowerCase().includes($.toLowerCase())}function F4($,Z){if(Z)return $?Z:Z[0]}var U4=class extends X0{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#$=0;#J="";#Z;#W;#X;#z;get cursor(){return this.#$}get userInputWithCursor(){if(!this.userInput)return V1(["inverse","hidden"],"_");if(this._cursor>=this.userInput.length)return`${this.userInput}█`;let Z=this.userInput.slice(0,this.cursor),J=this.userInput.slice(this.cursor,this.cursor+1),Q=this.userInput.slice(this.cursor+1);return`${Z}${V1("inverse",J)}${Q}`}get options(){return typeof this.#W=="function"?this.#W():this.#W}constructor(Z){super(Z),this.#W=Z.options,this.#X=Z.placeholder,this.#z=Z.completeOnTab===!0;let J=this.options;this.filteredOptions=[...J],this.multiple=Z.multiple===!0,this.#Z=typeof Z.options=="function"?Z.filter:Z.filter??H4;let Q;if(Z.initialValue&&Array.isArray(Z.initialValue)?this.multiple?Q=Z.initialValue:Q=Z.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(Q=[this.options[0]?.value]),Q)for(let z of Q){let W=J.findIndex((G)=>G.value===z);W!==-1&&(this.toggleSelected(z),this.#$=W)}this.focusedValue=this.options[this.#$]?.value,this.on("key",(z,W)=>this.#Q(z,W)),this.on("userInput",(z)=>this.#Y(z))}_isActionKey(Z,J){return Z==="\t"||this.multiple&&this.isNavigating&&J.name==="space"&&Z!==void 0&&Z!==""}#Q(Z,J){let Q=J.name==="up",z=J.name==="down",W=J.name==="return",G=this.userInput===""||this.userInput==="\t",Y=this.#X,X=this.options,j=Y!==void 0&&Y!==""&&X.some((H)=>!H.disabled&&(this.#Z?this.#Z(Y,H):!0));if(J.name==="tab"&&G&&j){this.userInput==="\t"&&this._clearUserInput(),this._setUserInput(Y,!0),this.isNavigating=!1;return}if(J.name==="tab"&&this.#z&&!this.multiple&&this.focusedValue!==void 0){let H=String(this.focusedValue);this._clearUserInput(),this._setUserInput(H,!0),this.isNavigating=!1;return}Q||z?(this.#$=b0(this.#$,Q?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#$]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):W?this.value=F4(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(J.name==="tab"||this.isNavigating&&J.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(Z){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(Z)?this.selectedValues=this.selectedValues.filter((J)=>J!==Z):this.selectedValues=[...this.selectedValues,Z]:this.selectedValues=[Z])}#Y(Z){if(Z!==this.#J){this.#J=Z;let J=this.options;Z&&this.#Z?this.filteredOptions=J.filter((W)=>this.#Z?.(Z,W)):this.filteredOptions=[...J];let Q=K4(this.focusedValue,this.filteredOptions);this.#$=b0(Q,0,this.filteredOptions);let z=this.filteredOptions[this.#$];z&&!z.disabled?this.focusedValue=z.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}};class b3 extends X0{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor($){super($,!1),this.value=!!$.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",(Z)=>{this.output.write(d.cursor.move(0,-1)),this.value=Z,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}}var q4={Y:{type:"year",len:4},M:{type:"month",len:2},D:{type:"day",len:2}};function J2($){return[...$].map((Z)=>q4[Z])}function V4($){let Z=new Intl.DateTimeFormat($,{year:"numeric",month:"2-digit",day:"2-digit"}).formatToParts(new Date(2000,0,15)),J=[],Q="/";for(let z of Z)z.type==="literal"?Q=z.value.trim()||z.value:(z.type==="year"||z.type==="month"||z.type==="day")&&J.push({type:z.type,len:z.type==="year"?4:2});return{segments:J,separator:Q}}function N3($){return Number.parseInt(($||"0").replace(/_/g,"0"),10)||0}function q1($){return{year:N3($.year),month:N3($.month),day:N3($.day)}}function P3($,Z){return new Date($||2001,Z||1,0).getDate()}function X2($){let{year:Z,month:J,day:Q}=q1($);if(!Z||Z<0||Z>9999||!J||J<1||J>12||!Q||Q<1)return;let z=new Date(Date.UTC(Z,J-1,Q));if(!(z.getUTCFullYear()!==Z||z.getUTCMonth()!==J-1||z.getUTCDate()!==Q))return{year:Z,month:J,day:Q}}function Q2($){let Z=X2($);return Z?new Date(Date.UTC(Z.year,Z.month-1,Z.day)):void 0}function M4($,Z,J,Q){let z=J?{year:J.getUTCFullYear(),month:J.getUTCMonth()+1,day:J.getUTCDate()}:null,W=Q?{year:Q.getUTCFullYear(),month:Q.getUTCMonth()+1,day:Q.getUTCDate()}:null;return $==="year"?{min:z?.year??1,max:W?.year??9999}:$==="month"?{min:z&&Z.year===z.year?z.month:1,max:W&&Z.year===W.year?W.month:12}:{min:z&&Z.year===z.year&&Z.month===z.month?z.day:1,max:W&&Z.year===W.year&&Z.month===W.month?W.day:P3(Z.year,Z.month)}}class j2 extends X0{#$;#J;#Z;#W;#X;#z={segmentIndex:0,positionInSegment:0};#Q=!0;#Y=null;inlineError="";get segmentCursor(){return{...this.#z}}get segmentValues(){return{...this.#Z}}get segments(){return this.#$}get separator(){return this.#J}get formattedValue(){return this.#H(this.#Z)}#H($){return this.#$.map((Z)=>$[Z.type]).join(this.#J)}#G(){this._setUserInput(this.#H(this.#Z)),this._setValue(Q2(this.#Z)??void 0)}constructor($){let Z=$.format?{segments:J2($.format),separator:$.separator??"/"}:V4($.locale),J=$.separator??Z.separator,Q=$.format?J2($.format):Z.segments,z=$.initialValue??$.defaultValue,W=z?{year:String(z.getUTCFullYear()).padStart(4,"0"),month:String(z.getUTCMonth()+1).padStart(2,"0"),day:String(z.getUTCDate()).padStart(2,"0")}:{year:"____",month:"__",day:"__"},G=Q.map((Y)=>W[Y.type]).join(J);super({...$,initialUserInput:G},!1),this.#$=Q,this.#J=J,this.#Z=W,this.#W=$.minDate,this.#X=$.maxDate,this.#G(),this.on("cursor",(Y)=>this.#q(Y)),this.on("key",(Y,X)=>this.#V(Y,X)),this.on("finalize",()=>this.#M($))}#j(){let $=Math.max(0,Math.min(this.#z.segmentIndex,this.#$.length-1)),Z=this.#$[$];if(Z)return this.#z.positionInSegment=Math.max(0,Math.min(this.#z.positionInSegment,Z.len-1)),{segment:Z,index:$}}#K($){this.inlineError="",this.#Y=null;let Z=this.#j();Z&&(this.#z.segmentIndex=Math.max(0,Math.min(this.#$.length-1,Z.index+$)),this.#z.positionInSegment=0,this.#Q=!0)}#F($){let Z=this.#j();if(!Z)return;let{segment:J}=Z,Q=this.#Z[J.type],z=!Q||Q.replace(/_/g,"")==="",W=Number.parseInt((Q||"0").replace(/_/g,"0"),10)||0,G=M4(J.type,q1(this.#Z),this.#W,this.#X),Y;z?Y=$===1?G.min:G.max:Y=Math.max(Math.min(G.max,W+$),G.min),this.#Z={...this.#Z,[J.type]:Y.toString().padStart(J.len,"0")},this.#Q=!0,this.#Y=null,this.#G()}#q($){if($)switch($){case"right":return this.#K(1);case"left":return this.#K(-1);case"up":return this.#F(1);case"down":return this.#F(-1)}}#V($,Z){if(Z?.name==="backspace"||Z?.sequence===""||Z?.sequence==="\b"||$===""||$==="\b"){this.inlineError="";let J=this.#j();if(!J)return;if(!this.#Z[J.segment.type].replace(/_/g,"")){this.#K(-1);return}this.#Z[J.segment.type]="_".repeat(J.segment.len),this.#Q=!0,this.#z.positionInSegment=0,this.#G();return}if(Z?.name==="tab"){this.inlineError="";let J=this.#j();if(!J)return;let Q=Z.shift?-1:1,z=J.index+Q;z>=0&&z<this.#$.length&&(this.#z.segmentIndex=z,this.#z.positionInSegment=0,this.#Q=!0);return}if($&&/^[0-9]$/.test($)){let J=this.#j();if(!J)return;let{segment:Q}=J,z=!this.#Z[Q.type].replace(/_/g,"");if(this.#Q&&this.#Y!==null&&!z){let U=this.#Y+$,V={...this.#Z,[Q.type]:U},q=this.#U(V,Q);if(q){this.inlineError=q,this.#Y=null,this.#Q=!1;return}this.inlineError="",this.#Z[Q.type]=U,this.#Y=null,this.#Q=!1,this.#G(),J.index<this.#$.length-1&&(this.#z.segmentIndex=J.index+1,this.#z.positionInSegment=0,this.#Q=!0);return}this.#Q&&!z&&(this.#Z[Q.type]="_".repeat(Q.len),this.#z.positionInSegment=0),this.#Q=!1,this.#Y=null;let W=this.#Z[Q.type],G=W.indexOf("_"),Y=G>=0?G:Math.min(this.#z.positionInSegment,Q.len-1);if(Y<0||Y>=Q.len)return;let X=W.slice(0,Y)+$+W.slice(Y+1),j=!1;if(Y===0&&W==="__"&&(Q.type==="month"||Q.type==="day")){let U=Number.parseInt($,10);X=`0${$}`,j=U<=(Q.type==="month"?1:2)}if(Q.type==="year"&&(X=(W.replace(/_/g,"")+$).padStart(Q.len,"_")),!X.includes("_")){let U={...this.#Z,[Q.type]:X},V=this.#U(U,Q);if(V){this.inlineError=V;return}}this.inlineError="",this.#Z[Q.type]=X;let H=X.includes("_")?void 0:X2(this.#Z);if(H){let{year:U,month:V}=H,q=P3(U,V);this.#Z={year:String(Math.max(0,Math.min(9999,U))).padStart(4,"0"),month:String(Math.max(1,Math.min(12,V))).padStart(2,"0"),day:String(Math.max(1,Math.min(q,H.day))).padStart(2,"0")}}this.#G();let K=X.indexOf("_");j?(this.#Q=!0,this.#Y=$):K>=0?this.#z.positionInSegment=K:G>=0&&J.index<this.#$.length-1?(this.#z.segmentIndex=J.index+1,this.#z.positionInSegment=0,this.#Q=!0):this.#z.positionInSegment=Math.min(Y+1,Q.len-1)}}#U($,Z){let{month:J,day:Q}=q1($);if(Z.type==="month"&&(J<0||J>12))return v.date.messages.invalidMonth;if(Z.type==="day"&&(Q<0||Q>31))return v.date.messages.invalidDay(31,"any month")}#M($){let{year:Z,month:J,day:Q}=q1(this.#Z);if(Z&&J&&Q){let z=P3(Z,J);this.#Z={...this.#Z,day:String(Math.min(Q,z)).padStart(2,"0")}}this.value=Q2(this.#Z)??$.defaultValue??void 0}}var D4=class extends X0{options;cursor=0;#$;getGroupItems(Z){return this.options.filter((J)=>J.group===Z)}isGroupSelected(Z){let J=this.getGroupItems(Z),Q=this.value;return Q===void 0?!1:J.every((z)=>Q.includes(z.value))}toggleValue(){let Z=this.options[this.cursor];if(Z!==void 0)if(this.value===void 0&&(this.value=[]),Z.group===!0){let J=Z.value,Q=this.getGroupItems(J);this.isGroupSelected(J)?this.value=this.value.filter((z)=>Q.findIndex((W)=>W.value===z)===-1):this.value=[...this.value,...Q.map((z)=>z.value)],this.value=Array.from(new Set(this.value))}else{let J=this.value.includes(Z.value);this.value=J?this.value.filter((Q)=>Q!==Z.value):[...this.value,Z.value]}}constructor(Z){super(Z,!1);let{options:J}=Z;this.#$=Z.selectableGroups!==!1,this.options=Object.entries(J).flatMap(([Q,z])=>[{value:Q,group:!0,label:Q},...z.map((W)=>({...W,group:Q}))]),this.value=[...Z.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:Q})=>Q===Z.cursorAt),this.#$?0:1),this.on("cursor",(Q)=>{switch(Q){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let z=this.options[this.cursor]?.group===!0;!this.#$&&z&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let z=this.options[this.cursor]?.group===!0;!this.#$&&z&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},L4=new Set(["up","down","left","right"]);class K2 extends X0{#$=!1;#J;focused="editor";get userInputWithCursor(){if(this.state==="submit")return this.userInput;let $=this.userInput;if(this.cursor>=$.length)return`${$}█`;let Z=$.slice(0,this.cursor),J=$.slice(this.cursor,this.cursor+1),Q=$.slice(this.cursor+1);return J===`
|
|
34
|
+
`?`${Z}█
|
|
35
|
+
${Q}`:`${Z}${V1("inverse",J)}${Q}`}get cursor(){return this._cursor}#Z($){if(this.userInput.length===0){this._setUserInput($);return}this._setUserInput(this.userInput.slice(0,this.cursor)+$+this.userInput.slice(this.cursor))}#W($){let Z=this.value??"";switch($){case"up":this._cursor=F1(this._cursor,0,-1,Z);return;case"down":this._cursor=F1(this._cursor,0,1,Z);return;case"left":this._cursor=F1(this._cursor,-1,0,Z);return;case"right":this._cursor=F1(this._cursor,1,0,Z);return}}_shouldSubmit($,Z){if(this.#J)return this.focused==="submit"?!0:(this.#Z(`
|
|
36
|
+
`),this._cursor++,!1);let J=this.#$;return this.#$=!0,J&&this.cursor===this.userInput.length?(this.userInput[this.cursor-1]===`
|
|
37
|
+
`&&(this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--),!0):(this.#Z(`
|
|
38
|
+
`),this._cursor++,!1)}constructor($){let Z=$.initialUserInput??$.initialValue;super({...$,initialUserInput:Z},!1),Z!==void 0&&(this._cursor=Z.length),this.#J=$.showSubmit??!1,this.on("key",(J,Q)=>{if(Q?.name&&L4.has(Q.name)){this.#$=!1,this.#W(Q.name);return}if(J==="\t"&&this.#J){this.focused=this.focused==="editor"?"submit":"editor";return}if(Q?.name!=="return"){if(this.#$=!1,Q?.name==="backspace"&&this.cursor>0){this._setUserInput(this.userInput.slice(0,this.cursor-1)+this.userInput.slice(this.cursor)),this._cursor--;return}if(Q?.name==="delete"&&this.cursor<this.userInput.length){this._setUserInput(this.userInput.slice(0,this.cursor)+this.userInput.slice(this.cursor+1));return}J&&(this.#J&&this.focused==="submit"&&(this.focused="editor"),this.#Z(J??""),this._cursor++)}}),this.on("userInput",(J)=>{this._setValue(J)}),this.on("finalize",()=>{this.value||(this.value=$.defaultValue),this.value===void 0&&(this.value="")})}}class k3 extends X0{options;cursor=0;get _value(){return this.options[this.cursor]?.value}get _enabledOptions(){return this.options.filter(($)=>$.disabled!==!0)}toggleAll(){let $=this._enabledOptions,Z=this.value!==void 0&&this.value.length===$.length;this.value=Z?[]:$.map((J)=>J.value)}toggleInvert(){let $=this.value;if(!$)return;let Z=this._enabledOptions.filter((J)=>!$.includes(J.value));this.value=Z.map((J)=>J.value)}toggleValue(){this.value===void 0&&(this.value=[]);let $=this.value.includes(this._value);this.value=$?this.value.filter((Z)=>Z!==this._value):[...this.value,this._value]}constructor($){super($,!1),this.options=$.options,this.value=[...$.initialValues??[]];let Z=Math.max(this.options.findIndex(({value:J})=>J===$.cursorAt),0);this.cursor=this.options[Z]?.disabled?b0(Z,1,this.options):Z,this.on("key",(J,Q)=>{Q.name==="a"&&this.toggleAll(),Q.name==="i"&&this.toggleInvert()}),this.on("cursor",(J)=>{switch(J){case"left":case"up":this.cursor=b0(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=b0(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}}class C3 extends X0{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let $=this.userInput;if(this.cursor>=$.length)return`${this.userInput}█`;let Z=$.slice(0,this.cursor),J=$.slice(this.cursor,this.cursor+1),Q=$.slice(this.cursor+1);return`${Z}${V1("inverse",J)}${Q}`}get cursor(){return this._cursor}constructor($){super({...$,initialUserInput:$.initialUserInput??$.initialValue}),this.on("userInput",(Z)=>{this._setValue(Z)}),this.on("finalize",()=>{this.value||(this.value=$.defaultValue),this.value===void 0&&(this.value="")})}}import{styleText as F,stripVTControlCharacters as FZ}from"node:util";import a from"node:process";var m0=z2(B3(),1);function B4(){if(a.platform!=="win32")return a.env.TERM!=="linux";return Boolean(a.env.CI)||Boolean(a.env.WT_SESSION)||Boolean(a.env.TERMINUS_SUBLIME)||a.env.ConEmuTask==="{cmd::Cmder}"||a.env.TERM_PROGRAM==="Terminus-Sublime"||a.env.TERM_PROGRAM==="vscode"||a.env.TERM==="xterm-256color"||a.env.TERM==="alacritty"||a.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var R3=B4(),N4=()=>process.env.CI==="true";var g=($,Z)=>R3?$:Z,H2=g("◆","*"),B2=g("■","x"),N2=g("▲","x"),D1=g("◇","o"),P4=g("┌","T"),_=g("│","|"),j0=g("└","—"),MZ=g("┐","T"),DZ=g("┘","—"),F2=g("●",">"),U2=g("○"," "),O4=g("◻","[•]"),q2=g("◼","[+]"),V2=g("◻","[ ]"),LZ=g("▪","•"),M2=g("─","-"),I4=g("╮","+"),f4=g("├","+"),b4=g("╯","+"),k4=g("╰","+"),BZ=g("╭","+"),C4=g("●","•"),R4=g("◆","*"),A4=g("▲","!"),E4=g("■","x"),A3=($)=>{switch($){case"initial":case"active":return F("cyan",H2);case"cancel":return F("red",B2);case"error":return F("yellow",N2);case"submit":return F("green",D1);case"validating":return F("dim",H2)}},w4=($)=>{switch($){case"initial":case"active":return F("cyan",_);case"cancel":return F("red",_);case"error":return F("yellow",_);case"submit":return F("green",_)}};function _4($,Z){let J=[`${Z?`${F("cyan",_)} `:""}${$.join(" • ")}`];return Z&&J.push(F("cyan",j0)),J}var D2=($,Z,J,Q,z,W=!1)=>{let G=Z,Y=0;if(W)for(let X=Q-1;X>=J;X--){let j=$[X];if(j&&(G-=j.length),Y++,G<=z)break}else for(let X=J;X<Q;X++){let j=$[X];if(j&&(G-=j.length),Y++,G<=z)break}return{lineCount:G,removals:Y}},L2=({cursor:$,options:Z,style:J,output:Q=process.stdout,maxItems:z=Number.POSITIVE_INFINITY,columnPadding:W=0,rowPadding:G=4})=>{let Y=T0(Q)-W,X=f3(Q),j=F("dim","..."),H=Math.max(X-G,0),K=Math.max(Math.min(z,H),5),U=0;$>=K-3&&(U=Math.max(Math.min($-K+3,Z.length-K),0));let V=K<Z.length&&U>0,q=K<Z.length&&U+K<Z.length,B=Math.min(U+K,Z.length),I=[],N=0;V&&N++,q&&N++;let A=U+(V?1:0),w=B-(q?1:0);for(let D=A;D<w;D++){let R=Z[D],k=R?J(R,D===$):"",E=r(k,Y,{hard:!0,trim:!1}).split(`
|
|
39
|
+
`);I.push(E),N+=E.length}if(N>H){let D=0,R=0,k=N,E=$-A,S=H,m=()=>D2(I,k,0,E,S),T=()=>D2(I,k,E+1,I.length,S,!0);V?({lineCount:k,removals:D}=m(),k>S&&(q||(S-=1),{lineCount:k,removals:R}=T())):(q||(S-=1),{lineCount:k,removals:R}=T(),k>S&&(S-=1,{lineCount:k,removals:D}=m())),D>0&&(V=!0,I.splice(0,D)),R>0&&(q=!0,I.splice(I.length-R,R))}let M=[];V&&M.push(j);for(let D of I)for(let R of D)M.push(R);return q&&M.push(j),M};var E3=($)=>{let Z=$.active??"Yes",J=$.inactive??"No";return new b3({active:Z,inactive:J,signal:$.signal,input:$.input,output:$.output,initialValue:$.initialValue??!0,render(){let Q=$.withGuide??v.withGuide,z=`${A3(this.state)} `,W=Q?`${F("gray",_)} `:"",G=h0($.output,$.message,W,z),Y=`${Q?`${F("gray",_)}
|
|
40
|
+
`:""}${G}
|
|
41
|
+
`,X=this.value?Z:J;switch(this.state){case"submit":{let j=Q?`${F("gray",_)} `:"";return`${Y}${j}${F("dim",X)}`}case"cancel":{let j=Q?`${F("gray",_)} `:"";return`${Y}${j}${F(["strikethrough","dim"],X)}${Q?`
|
|
42
|
+
${F("gray",_)}`:""}`}default:{let j=Q?`${F("cyan",_)} `:"",H=Q?F("cyan",j0):"";return`${Y}${j}${this.value?`${F("green",F2)} ${Z}`:`${F("dim",U2)} ${F("dim",Z)}`}${$.vertical?Q?`
|
|
43
|
+
${F("cyan",_)} `:`
|
|
44
|
+
`:` ${F("dim","/")} `}${this.value?`${F("dim",U2)} ${F("dim",J)}`:`${F("green",F2)} ${J}`}
|
|
45
|
+
${H}
|
|
46
|
+
`}}}}).prompt()};var S4=[`${F("dim","↑/↓")} to navigate`,`${F("dim","Space:")} select`,`${F("dim","Enter:")} confirm`],y0=($,Z)=>$.split(`
|
|
47
|
+
`).map((J)=>Z(J)).join(`
|
|
48
|
+
`),P2=($)=>{let Z=(z,W)=>{let G=z.label??String(z.value);return W==="disabled"?`${F("gray",V2)} ${y0(G,(Y)=>F(["strikethrough","gray"],Y))}${z.hint?` ${F("dim",`(${z.hint??"disabled"})`)}`:""}`:W==="active"?`${F("cyan",O4)} ${G}${z.hint?` ${F("dim",`(${z.hint})`)}`:""}`:W==="selected"?`${F("green",q2)} ${y0(G,(Y)=>F("dim",Y))}${z.hint?` ${F("dim",`(${z.hint})`)}`:""}`:W==="cancelled"?`${y0(G,(Y)=>F(["strikethrough","dim"],Y))}`:W==="active-selected"?`${F("green",q2)} ${G}${z.hint?` ${F("dim",`(${z.hint})`)}`:""}`:W==="submitted"?`${y0(G,(Y)=>F("dim",Y))}`:`${F("dim",V2)} ${y0(G,(Y)=>F("dim",Y))}`},J=$.required??!0,Q=$.showInstructions??!0;return new k3({options:$.options,signal:$.signal,input:$.input,output:$.output,initialValues:$.initialValues,required:J,cursorAt:$.cursorAt,validate(z){if(J&&(z===void 0||z.length===0))return`Please select at least one option.
|
|
49
|
+
${F("reset",F("dim",`Press ${F(["gray","bgWhite","inverse"]," space ")} to select, ${F("gray",F("bgWhite",F("inverse"," enter ")))} to submit`))}`},render(){let z=$.withGuide??v.withGuide,W=h0($.output,$.message,z?`${w4(this.state)} `:"",`${A3(this.state)} `),G=`${z?`${F("gray",_)}
|
|
50
|
+
`:""}${W}
|
|
51
|
+
`,Y=this.value??[],X=(j,H)=>{if(j.disabled)return Z(j,"disabled");let K=Y.includes(j.value);return H&&K?Z(j,"active-selected"):K?Z(j,"selected"):Z(j,H?"active":"inactive")};switch(this.state){case"submit":{let j=this.options.filter(({value:K})=>Y.includes(K)).map((K)=>Z(K,"submitted")).join(F("dim",", "))||F("dim","none"),H=h0($.output,j,z?`${F("gray",_)} `:"");return`${G}${H}`}case"cancel":{let j=this.options.filter(({value:K})=>Y.includes(K)).map((K)=>Z(K,"cancelled")).join(F("dim",", "));if(j.trim()==="")return`${G}${F("gray",_)}`;let H=h0($.output,j,z?`${F("gray",_)} `:"");return`${G}${H}${z?`
|
|
52
|
+
${F("gray",_)}`:""}`}case"error":{let j=z?`${F("yellow",_)} `:"",H=this.error.split(`
|
|
53
|
+
`).map((V,q)=>q===0?`${z?`${F("yellow",j0)} `:""}${F("yellow",V)}`:` ${V}`).join(`
|
|
54
|
+
`),K=G.split(`
|
|
55
|
+
`).length,U=H.split(`
|
|
56
|
+
`).length+1;return`${G}${j}${L2({output:$.output,options:this.options,cursor:this.cursor,maxItems:$.maxItems,columnPadding:j.length,rowPadding:K+U,style:X}).join(`
|
|
57
|
+
${j}`)}
|
|
58
|
+
${H}
|
|
59
|
+
`}default:{let j=z?`${F("cyan",_)} `:"",H=G.split(`
|
|
60
|
+
`).length,K=Q?_4(S4,z):z?[F("cyan",j0)]:[],U=K.join(`
|
|
61
|
+
`),V=K.length+1;return`${G}${j}${L2({output:$.output,options:this.options,cursor:this.cursor,maxItems:$.maxItems,columnPadding:j.length,rowPadding:H+V,style:X}).join(`
|
|
62
|
+
${j}`)}
|
|
63
|
+
${U}
|
|
64
|
+
`}}}}).prompt()};var h={message:($=[],{symbol:Z=F("gray",_),secondarySymbol:J=F("gray",_),output:Q=process.stdout,spacing:z=1,withGuide:W}={})=>{let G=[],Y=W??v.withGuide,X=Y?J:"",j=Y?`${Z} `:"",H=Y?`${J} `:"";for(let U=0;U<z;U++)G.push(X);let K=Array.isArray($)?$:$.split(`
|
|
65
|
+
`);if(K.length>0){let[U,...V]=K;U.length>0?G.push(`${j}${U}`):G.push(Y?Z:"");for(let q of V)q.length>0?G.push(`${H}${q}`):G.push(Y?J:"")}Q.write(`${G.join(`
|
|
66
|
+
`)}
|
|
67
|
+
`)},info:($,Z)=>{h.message($,{...Z,symbol:F("blue",C4)})},success:($,Z)=>{h.message($,{...Z,symbol:F("green",R4)})},step:($,Z)=>{h.message($,{...Z,symbol:F("green",D1)})},warn:($,Z)=>{h.message($,{...Z,symbol:F("yellow",A4)})},warning:($,Z)=>{h.warn($,Z)},error:($,Z)=>{h.message($,{...Z,symbol:F("red",E4)})}};var O2=($="",Z)=>{let J=Z?.output??process.stdout,Q=Z?.withGuide??v.withGuide?`${F("gray",P4)} `:"";J.write(`${Q}${$}
|
|
68
|
+
`)},t=($="",Z)=>{let J=Z?.output??process.stdout,Q=Z?.withGuide??v.withGuide?`${F("gray",_)}
|
|
69
|
+
${F("gray",j0)} `:"";J.write(`${Q}${$}
|
|
70
|
+
|
|
71
|
+
`)};var x4=($)=>$,g4=($,Z,J)=>{let Q={hard:!0,trim:!1},z=r($,Z,Q).split(`
|
|
72
|
+
`),W=z.reduce((X,j)=>Math.max(u(j),X),0),G=z.map(J).reduce((X,j)=>Math.max(u(j),X),0),Y=Z-(G-W);return r($,Y,Q)},L1=($="",Z="",J)=>{let Q=J?.output??a.stdout,z=J?.withGuide??v.withGuide,W=J?.format??x4,G=["",...g4($,T0(Q)-6,W).split(`
|
|
73
|
+
`).map(W),""],Y=u(Z),X=Math.max(G.reduce((U,V)=>{let q=u(V);return q>U?q:U},0),Y)+2,j=G.map((U)=>`${F("gray",_)} ${U}${" ".repeat(X-u(U))}${F("gray",_)}`).join(`
|
|
74
|
+
`),H=z?`${F("gray",_)}
|
|
75
|
+
`:"",K=z?f4:k4;Q.write(`${H}${F("green",D1)} ${F("reset",Z)} ${F("gray",M2.repeat(Math.max(X-Y-1,1))+I4)}
|
|
76
|
+
${j}
|
|
77
|
+
${F("gray",K+M2.repeat(X+2)+b4)}
|
|
78
|
+
`)};var T4=($)=>F("magenta",$),I2=({indicator:$="dots",onCancel:Z,output:J=process.stdout,cancelMessage:Q,errorMessage:z,frames:W=R3?["◒","◐","◓","◑"]:["•","o","O","0"],delay:G=R3?80:120,signal:Y,...X}={})=>{let j=N4(),H,K,U=!1,V=!1,q="",B,I=performance.now(),N=T0(J),A=X?.styleFrame??T4,w=(b)=>{let y=b>1?z??v.messages.error:Q??v.messages.cancel;V=b===1,U&&(x(y,b),V&&typeof Z=="function"&&Z())},M=()=>w(2),D=()=>w(1),R=()=>{process.on("uncaughtExceptionMonitor",M),process.on("unhandledRejection",M),process.on("SIGINT",D),process.on("SIGTERM",D),process.on("exit",w),Y&&Y.addEventListener("abort",D)},k=()=>{process.removeListener("uncaughtExceptionMonitor",M),process.removeListener("unhandledRejection",M),process.removeListener("SIGINT",D),process.removeListener("SIGTERM",D),process.removeListener("exit",w),Y&&Y.removeEventListener("abort",D)},E=()=>{if(B===void 0)return;j&&J.write(`
|
|
79
|
+
`);let b=r(B,N,{hard:!0,trim:!1}).split(`
|
|
80
|
+
`);b.length>1&&J.write(m0.cursor.up(b.length-1)),J.write(m0.cursor.to(0)),J.write(m0.erase.down())},S=(b)=>b.replace(/\.+$/,""),m=(b)=>{let y=(performance.now()-b)/1000,p=Math.floor(y/60),L=Math.floor(y%60);return p>0?`[${p}m ${L}s]`:`[${L}s]`},T=X.withGuide??v.withGuide,C=(b="")=>{U=!0,H=Y2({output:J}),q=S(b),I=performance.now(),T&&J.write(`${F("gray",_)}
|
|
81
|
+
`);let y=0,p=0;R(),K=setInterval(()=>{if(j&&q===B)return;E(),B=q;let L=A(W[y]),P;if(j)P=`${L} ${q}...`;else if($==="timer")P=`${L} ${q} ${m(I)}`;else{let c=".".repeat(Math.floor(p)).slice(0,3);P=`${L} ${q}${c}`}let O=r(P,N,{hard:!0,trim:!1});J.write(O),y=y+1<W.length?y+1:0,p=p<4?p+0.125:0},G)},x=(b="",y=0,p=!1)=>{if(!U)return;U=!1,clearInterval(K),E();let L=y===0?F("green",D1):y===1?F("red",B2):F("red",N2);q=b??q,p||($==="timer"?J.write(`${L} ${q} ${m(I)}
|
|
82
|
+
`):J.write(`${L} ${q}
|
|
83
|
+
`)),k(),H()};return{start:C,stop:(b="")=>x(b,0),message:(b="")=>{q=S(b??q)},cancel:(b="")=>x(b,1),error:(b="")=>x(b,2),clear:()=>x("",0,!0),get isCancelled(){return V}}},NZ={light:g("─","-"),heavy:g("━","="),block:g("█","#")};var PZ=[`${F("dim","↑/↓")} to navigate`,`${F("dim","Enter:")} confirm`];var OZ=`${F("gray",_)} `;var f2=($)=>new C3({validate:$.validate,placeholder:$.placeholder,defaultValue:$.defaultValue,initialValue:$.initialValue,output:$.output,signal:$.signal,input:$.input,render(){let Z=$?.withGuide??v.withGuide,J=`${`${Z?`${F("gray",_)}
|
|
84
|
+
`:""}${A3(this.state)} `}${$.message}
|
|
85
|
+
`,Q=$.placeholder&&$.placeholder.length>0?F("inverse",$.placeholder[0])+F("dim",$.placeholder.slice(1)):F(["inverse","hidden"],"_"),z=this.userInput?this.userInputWithCursor:Q,W=this.value??"";switch(this.state){case"validating":{let G=Z?`${F("cyan",_)} `:"",Y=Z?F("cyan",j0):"",X=F("dim",z),j=F("dim","Validating...");return`${J}${G}${X}
|
|
86
|
+
${Y} ${j}
|
|
87
|
+
`}case"error":{let G=this.error?` ${F("yellow",this.error)}`:"",Y=Z?`${F("yellow",_)} `:"",X=Z?F("yellow",j0):"";return`${J.trim()}
|
|
88
|
+
${Y}${z}
|
|
89
|
+
${X}${G}
|
|
90
|
+
`}case"submit":{let G=W?`${Z?" ":""}${F("dim",W)}`:"",Y=Z?F("gray",_):"";return`${J}${Y}${G}`}case"cancel":{let G=W?` ${F(["strikethrough","dim"],W)}`:"",Y=Z?F("gray",_):"";return`${J}${Y}${G}${W.trim()?`
|
|
91
|
+
${Y}`:""}`}default:{let G=Z?`${F("cyan",_)} `:"",Y=Z?F("cyan",j0):"";return`${J}${G}${z}
|
|
92
|
+
${Y}
|
|
93
|
+
`}}}}).prompt();import{existsSync as g3}from"node:fs";import{existsSync as h4,readFileSync as y4}from"node:fs";import{applyEdits as b2,format as m4,modify as w3,parse as k2}from"jsonc-parser";function v0($){if(!h4($))return{value:null,text:"",exists:!1};let Z=y4($,"utf8"),J=[],Q=k2(Z,J,{allowTrailingComma:!0});return{value:J.length===0?Q:null,text:Z,exists:!0}}function _3($,Z,J,Q){let W=k2($,[],{allowTrailingComma:!0})??{};for(let K of Z)if(typeof W==="object"&&W!==null)W=W[K];else{W=void 0;break}let G=Array.isArray(W)?W:[],Y=G.findIndex((K)=>typeof K==="string"&&Q(K));if(Y!==-1&&G[Y]===J)return{text:$,changed:!1};let X;if(Y!==-1)X=w3($,[...Z,Y],J,{formattingOptions:{insertSpaces:!0,tabSize:2}});else if(!Array.isArray(W))X=w3($,Z,[J],{formattingOptions:{insertSpaces:!0,tabSize:2}});else X=w3($,[...Z,G.length],J,{formattingOptions:{insertSpaces:!0,tabSize:2}});let j=b2($,X);return{text:b2(j,m4(j,void 0,{insertSpaces:!0,tabSize:2})),changed:!0}}import{existsSync as B1}from"node:fs";import{mkdir as A2,writeFile as N1}from"node:fs/promises";import{join as P1}from"node:path";function E2($){return $===k0||$.startsWith(`${k0}@`)}function S3($){let Z=P1($,"opencode.jsonc");if(B1(Z))return{path:Z,exists:!0};let J=P1($,"opencode.json");if(B1(J))return{path:J,exists:!0};return{path:Z,exists:!1}}function v4($){let Z=P1($,"tui.jsonc");if(B1(Z))return{path:Z,exists:!0};let J=P1($,"tui.json");if(B1(J))return{path:J,exists:!0};return{path:Z,exists:!1}}async function w2($,Z=process.env){let J=q0(Z);await A2(J,{recursive:!0});let{path:Q,exists:z}=S3(J),W=C2($);if(!z){let j=`{
|
|
94
|
+
"$schema": "https://opencode.ai/config.json",
|
|
95
|
+
"plugin": [
|
|
96
|
+
"${W}"
|
|
97
|
+
]
|
|
98
|
+
}
|
|
99
|
+
`;return await N1(Q,j,"utf8"),{configPath:Q,changed:!0,created:!0}}let{text:G}=v0(Q),{text:Y,changed:X}=_3(G,["plugin"],W,E2);if(X)await N1(Q,Y,"utf8");return{configPath:Q,changed:X,created:!1}}async function _2($,Z=process.env){let J=q0(Z);await A2(J,{recursive:!0});let{path:Q,exists:z}=v4(J),W=R2($);if(!z){let j=`{
|
|
100
|
+
"plugin": [
|
|
101
|
+
"${W}"
|
|
102
|
+
]
|
|
103
|
+
}
|
|
104
|
+
`;return await N1(Q,j,"utf8"),{configPath:Q,changed:!0,created:!0}}let{text:G}=v0(Q),{text:Y,changed:X}=_3(G,["plugin"],W,E2);if(X)await N1(Q,Y,"utf8");return{configPath:Q,changed:X,created:!1}}import{existsSync as x2}from"node:fs";import{readFile as p4,writeFile as TZ}from"node:fs/promises";import{join as c4}from"node:path";function g2($=process.env){let Z=c4(P0($),"settings.json");if(!x2(Z))return!1;try{let Q=JSON.parse(d4(Z))?.packages;if(!Array.isArray(Q))return!1;return Q.some((z)=>{let W=typeof z==="string"?z:typeof z==="object"&&z!==null?z.source:"";if(typeof W!=="string")return!1;return W===p0||W.startsWith(`${p0}@`)||W===`npm:${p0}`||W.startsWith(`npm:${p0}@`)})}catch{return!1}}function d4($){return x3("node:fs").readFileSync($,"utf8")}async function T2($=process.env){let Z=Y1($);if(!x2(Z))return!1;try{let J=await p4(Z,"utf8"),Q=JSON.parse(J);return Boolean(Q?.anthropic&&typeof Q.anthropic==="object")}catch{return!1}}async function h2($,Z=l,J=process.env){let Q=S2($),z=await Z.run("pi",["install",Q],{env:J});if(z.exitCode!==0)return{ok:!1,exitCode:z.exitCode,stderr:z.stderr};return{ok:!0,message:`Installed ${Q}`}}async function u4($=process.env,Z=l){let J=await Z.run("opencode",["--version"],{env:$}),Q=J.exitCode===0,z=Q?J.stdout.trim()||null:null,W=q0($),{path:G,exists:Y}=S3(W),X=!1;if(Y){let{value:H}=v0(G);if(Array.isArray(H?.plugin))X=H.plugin.some((K)=>typeof K==="string"&&(K===k0||K.startsWith(`${k0}@`)))}return{kind:"opencode",installed:Q||Y||g3(W1($)),version:z,configPath:G,pluginInstalled:X}}async function l4($=process.env,Z=l){let J=await Z.run("pi",["--version"],{env:$}),Q=J.exitCode===0,z=null;if(Q){let j=J.stdout.trim()||J.stderr.trim();z=j.split(/\r?\n/).find((K)=>/^\d+\.\d+\.\d+/.test(K.trim()))?.trim()??j??null}let W=P0($),G=Q||g3(W),Y=g2($),X=await T2($);return{kind:"pi",installed:G,version:z,configPath:W,pluginInstalled:Y,hasLocalAuth:X}}async function i4($=process.env,Z=l){let J=await Z.run("ck",["--version"],{env:$}),Q=J.exitCode===0,z=Q?J.stdout.trim()||null:null,W=null,G=!1;try{if(W=J1(void 0,$),W&&g3(W)){let Y=await y2({connectionFile:W,handshakeTimeoutMs:2000});G=!0,Y.close()}}catch{G=!1}return{ckInstalled:Q,ckVersion:z,daemonRunning:G,connectionPath:W}}async function m2($=process.env,Z=l){let[J,Q,z]=await Promise.all([u4($,Z),l4($,Z),i4($,Z)]);return{opencode:J,pi:Q,claustrum:z}}async function p2($,Z){let J={...Z.env},Q=async()=>{if(X1(J),await I0(Z.fence),await z0($,J)!=="local")throw Error("Disconnect from the vault first.")};await Q();let z=Z.paths??await O0($,J),W=await Z.login?.($);if(W&&!/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i.test(W.accountIdentity))throw Error("Claude sign-in did not establish an account UUID");if(await Q(),await v2({paths:z.paths,legacyConfigPath:z.legacyConfigPath,legacyStatePath:z.legacyStatePath,host:$,hostAuthPath:z.hostAuthPath,routingSourcePath:z.routingSourcePath,routingDestinationPath:z.routingDestinationPath,env:J,processFence:Q,removePiAnthropicAuth:Z.removePiAnthropicAuth}),W){let G=f0({paths:z.paths,host:$,vault:{env:J},beforePoolWrite:Q});try{if((await G.read()).mode!=="local")throw Error("Disconnect from the vault first.");await Q(),await G.loginOAuth({routeId:"main",replace:!0,...W})}finally{G.close()}}}async function d2($){let Z=await O1("max");L1(Z.url,`Claude sign-in for ${$==="pi"?"Pi":"OpenCode"}`);let J=await f2({message:"Paste the Claude callback URL or authorization code:"});if(G0(J))throw Error("Claude sign-in cancelled");let Q=await I1(J,Z.verifier,Z.redirectUri,Z.state);if(Q.type!=="success")throw Error("Claude sign-in failed");let z=await c2(Q.access,void 0,void 0);if(!z.accountUuid)throw Error("Claude sign-in did not establish an account UUID");return{accountIdentity:z.accountUuid,credential:{type:"oauth",access:Q.access,refresh:Q.refresh,expires:Q.expires}}}async function l2($=[],Z={}){let J=Z.env??process.env,Q=Z.runner??l,z=Z.fence??j3,W=Z.activate??C$,G=Z.migrateLocal??p2,Y={output:Z.output},X=$.includes("--yes")||$.includes("-y"),j=$.includes("--dry-run"),H=$.includes("--no-claustrum"),K=$.includes("--claustrum"),U=$.includes("--remove-pi-auth"),V=$.includes("--login"),q=V?Z.localLogin??d2:void 0;if(V&&K)return h.error("Local sign-in and vault setup are two separate choices. Use --login or --claustrum, not both.",Y),1;O2("CortexKit Anthropic Auth Setup",Y);let B=I2(Y);B.start("Detecting installed environments…");let I=await(Z.detect??m2)(J,Q);B.stop("Environment detection complete.");let N=I.opencode.installed?`detected (${I.opencode.version??"version unknown"}, ${I.opencode.pluginInstalled?"plugin already configured":"plugin not configured"})`:"not found",A=I.pi.installed?`detected (${I.pi.version??"version unknown"}, ${I.pi.pluginInstalled?"extension already installed":"extension not installed"})`:"not found",w=I.claustrum.daemonRunning?`daemon running (${I.claustrum.ckVersion??"ck ready"})`:I.claustrum.ckInstalled?"ck installed, daemon not running":"not installed";if(h.info(`OpenCode: ${N}`,Y),h.info(`Pi: ${A}`,Y),h.info(`Claustrum: ${w}`,Y),!I.opencode.installed&&!I.pi.installed)return h.error("Neither OpenCode nor Pi was detected on this system.",Y),t("Install OpenCode (https://opencode.ai) or Pi (https://github.com/badlogic/pi-mono) first.",Y),1;let M=[];if(X){if(I.opencode.installed)M.push("opencode");if(I.pi.installed)M.push("pi")}else{let C=[];if(I.opencode.installed)C.push({value:"opencode",label:"OpenCode",hint:I.opencode.pluginInstalled?"already configured":"configure plugin + TUI sidebar"});if(I.pi.installed)C.push({value:"pi",label:"Pi",hint:I.pi.pluginInstalled?"already installed":"install provider extension"});let x=await P2({message:"Select integrations to configure:",options:C,initialValues:C.map((b)=>b.value),required:!0,...Y});if(G0(x))return t("Setup cancelled.",Y),0;M=x}if(M.length===0)return t("No integrations selected.",Y),0;let D=!1;if(I.claustrum.daemonRunning&&I.claustrum.ckInstalled&&!H){if(K)D=!0;else if(!X){let C=await E3({message:"Use Claude accounts from the Claustrum vault? Local account files stay unchanged and are not used while connected.",initialValue:!1,...Y});if(G0(C))return t("Setup cancelled.",Y),0;D=C}}if(q&&D)return h.error("Local sign-in and vault setup are two separate choices. Use --login or --claustrum, not both.",Y),1;if(q||!D){for(let C of M)if(await z0(C,J)!=="local")return h.error("Disconnect from the vault first.",Y),1}let k=!1;if(M.includes("pi")&&I.pi.hasLocalAuth)if(X){if(!U)return h.error(D?"Pi has stored Anthropic authentication. Rerun with --remove-pi-auth to preserve it privately during vault use and restore it on disconnect.":"Pi has a stored Anthropic login. Rerun with --remove-pi-auth to move it into the native account pool.",Y),t("Setup aborted.",Y),1;k=!0}else{h.warn(D?"Pi has stored Anthropic authentication. Vault setup must preserve it privately and restore it on disconnect.":"Pi has a stored Anthropic OAuth token. Native account-pool setup moves credentials out of the host auth store.",Y);let C=await E3({message:D?"Move Pi authentication aside privately for vault use, then restore it on disconnect?":"Move the Pi Anthropic OAuth login into the native account pool and remove its stored copy?",initialValue:!1,...Y});if(G0(C)||!C)return h.error("Native account-pool setup cannot finish while the stored Pi OAuth token takes precedence.",Y),t("Setup aborted.",Y),1;k=!0}try{await I0(z)}catch(C){return h.error(await W0("setup-process-check",C,J),Y),t("Setup aborted — quit active hosts and rerun setup.",Y),1}let E=[];for(let C of M)E.push(await O0(C,J));if(await I$(E),j){if(h.info("[dry-run] Planned actions:",Y),h.info(` - Target integrations: ${M.join(", ")}`,Y),h.info(` - Claustrum custody: ${D?"enabled":"disabled"}`,Y),k)h.info(" - Pi local OAuth token will be removed",Y);return t("Dry run complete. No changes were made.",Y),0}let S=await u2(),m=async(C,x)=>{B.start(`Switching ${x} to Claustrum vault custody…`);try{let b=await W(C,{env:J,runner:Q,fence:z,removePiAnthropicAuth:C==="pi"&&k});return B.stop(b==="already-vault"?`${x} already uses Claustrum vault custody.`:`${x} now uses Claustrum vault custody.`),!0}catch(b){return B.stop(`${x} vault custody setup failed.`),h.error(await W0("setup-activation",b,J),Y),!1}};if(M.includes("opencode")){B.start("Configuring OpenCode plugin and TUI sidebar…");try{await w2(S,J),await _2(S,J),B.stop("OpenCode configuration updated.")}catch(C){return B.stop("OpenCode setup failed."),h.error(await W0("setup-opencode-config",C,J),Y),1}if(q||!D)await G("opencode",{env:J,fence:z,removePiAnthropicAuth:!1,login:q});if(D&&!await m("opencode","OpenCode"))return 1}if(M.includes("pi")){B.start("Installing Pi Anthropic extension…");try{let C=await h2(S,Q,J);if(!C.ok)return B.stop("Pi extension installation failed."),h.error(await m$("setup-pi-install",C,J),Y),1;B.stop("Pi Anthropic extension installed.")}catch(C){return B.stop("Pi setup failed."),h.error(await W0("setup-pi",C,J),Y),1}if(q||!D)await G("pi",{env:J,fence:z,removePiAnthropicAuth:k,login:q});if(D&&!await m("pi","Pi"))return 1}let T=[];if(M.includes("opencode"))T.push("• Start OpenCode normally (opencode).");if(M.includes("pi"))T.push("• Start Pi normally (pi).");if(D)T.push("• Manage accounts in Claustrum with: ck auth login --provider anthropic"),T.push(" Newly added accounts will be discovered automatically without restarting.");return L1(T.join(`
|
|
105
|
+
`),"Next Steps",Y),t("Setup complete!",Y),0}async function C0($){if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Native account changes require offline setup without OPENCODE_AUTH_CONTENT");let Z=await z1(),J=f0({paths:Z,host:"opencode"});try{return await J.read(),await $(J)}finally{J.close()}}async function f1(){if(await z0("opencode",process.env)!=="local")throw Error("Disconnect from the vault first.")}function i2(){console.log(`Usage:
|
|
106
|
+
opencode-anthropic-auth setup [--yes] [--dry-run]
|
|
3
107
|
opencode-anthropic-auth login [label]
|
|
4
108
|
opencode-anthropic-auth api add [label]
|
|
5
109
|
opencode-anthropic-auth list
|
|
6
110
|
opencode-anthropic-auth relay setup
|
|
7
111
|
|
|
8
|
-
|
|
9
|
-
|
|
112
|
+
Native credentials are managed by the offline setup migration.
|
|
113
|
+
Legacy import source:
|
|
114
|
+
${n2()}`)}function T3($,Z){let J=$?.trim();if(!J)throw Error(`${Z} is required`);return J}async function C1($){let J=await($.fetchImpl??fetch)(`https://api.cloudflare.com/client/v4${$.path}`,{method:$.method,headers:{authorization:`Bearer ${$.token}`,...$.body instanceof FormData?{}:{"content-type":"application/json"},...$.headers},body:$.body}),Q=await J.text(),z;try{z=JSON.parse(Q)}catch{throw Error(`Cloudflare API returned ${J.status}: ${Q}`)}if(!J.ok||z.success===!1){let W=z.errors?.map((G)=>G.message).filter(Boolean).join("; ");throw Error(W||`Cloudflare API returned ${J.status}`)}return z.result}async function o4($,Z,J,Q){return C1({token:$,method:"POST",path:`/accounts/${Z}/storage/kv/namespaces`,body:JSON.stringify({title:J}),fetchImpl:Q})}async function r4($){let Z={main_module:"worker.js",compatibility_date:"2026-04-28",bindings:[{type:"kv_namespace",name:"RELAY_STATE",namespace_id:$.kvNamespaceId},{type:"secret_text",name:"RELAY_TOKEN",text:$.relayToken}]},J=new FormData;return J.set("metadata",JSON.stringify(Z)),J.set("worker.js",new Blob([r2],{type:"application/javascript+module"}),"worker.js"),C1({token:$.token,method:"PUT",path:`/accounts/${$.accountId}/workers/scripts/${$.scriptName}`,body:J,fetchImpl:$.fetchImpl})}async function t4($,Z,J,Q){await C1({token:$,method:"POST",path:`/accounts/${Z}/workers/scripts/${J}/subdomain`,body:JSON.stringify({enabled:!0,previews_enabled:!1}),fetchImpl:Q})}async function e4($,Z,J){return C1({token:$,method:"GET",path:`/accounts/${Z}/workers/subdomain`,fetchImpl:J}).catch(()=>null)}async function $8($={}){await C0((V)=>V.read());let Z=$.fetchImpl??fetch,J=$.prompt??k1,Q=$.warn??((V)=>console.warn(V)),z=T3(process.env.CLOUDFLARE_API_TOKEN?.trim()||await J("Cloudflare API token: "),"Cloudflare API token");$.secrets?.push(z);let W=T3(process.env.CLOUDFLARE_ACCOUNT_ID||await J("Cloudflare account ID: "),"Cloudflare account ID"),G=await J("Worker name [opencode-anthropic-relay]: ")||"opencode-anthropic-relay",Y=`${G}-state`,X=o2();$.secrets?.push(X),console.log("Creating Cloudflare KV namespace...");let j=await o4(z,W,Y,Z);console.log("Uploading relay Worker..."),await r4({token:z,accountId:W,scriptName:G,kvNamespaceId:j.id,relayToken:X,fetchImpl:Z}),await t4(z,W,G,Z).catch(async(V)=>{Q(await W0("cli-relay-workers-dev",V,process.env,[z,X]))});let H=await e4(z,W,Z),U=(H?.subdomain?`https://${G}.${H.subdomain}.workers.dev`:"")||T3(await k1("Relay Worker URL: "),"Relay Worker URL");await C0((V)=>V.updateRelay({enabled:!0,url:U,token:X,fallbackToDirect:!0,transport:"http"})),console.log(`Relay enabled at ${U}`),console.log("Relay settings saved to the native account store.")}var b1=null;async function k1($){return b1??=s4({input:a4,output:n4}),(await b1.question($)).trim()}function Z8(){b1?.close(),b1=null}async function J8($,Z={}){if(process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Local login cannot be verified while OPENCODE_AUTH_CONTENT is set");let J=Z.prompt??k1,Q=Z.authorize??O1,z=Z.exchange??I1;await f1(),await C0(async(W)=>{let G=await W.read(),Y=$?.trim()||await J("Fallback account label (optional): "),X=await Q("max");console.log(`
|
|
10
115
|
Open this URL in your browser and complete Claude sign-in:
|
|
11
116
|
`),console.log(`${X.url}
|
|
12
|
-
`);let
|
|
13
|
-
Saved fallback account${
|
|
14
|
-
Saved API fallback route${
|
|
117
|
+
`);let j=await J("Paste the full callback URL or authorization code here: ");Z.secrets?.push(j);let H=await z(j,X.verifier,X.redirectUri,X.state);if(H.type==="failed")throw Error("Authentication failed");if(Z.secrets?.push(H.access,H.refresh),process.env.OPENCODE_AUTH_CONTENT!==void 0)throw Error("Local login cannot be verified while OPENCODE_AUTH_CONTENT is set");await f1();let K=Y&&Y!=="main"?Y:crypto.randomUUID(),U=G.accounts.some((V)=>V.id===K&&V.source==="local");await W.loginOAuth({routeId:K,replace:U,label:Y||void 0,credential:{access:H.access,refresh:H.refresh,expires:H.expires}}),console.log(`
|
|
118
|
+
Saved native fallback account${Y?` "${Y}"`:""}.`)})}async function Q8($,Z={}){await f1(),await C0((X)=>X.read());let J=Z.prompt??k1,Q=$?.trim()||await J("API fallback label (optional): "),z=process.env.OPENCODE_ANTHROPIC_AUTH_API_BASE_URL?.trim()||(await J("Anthropic-compatible base URL [https://api.kie.ai/claude]: ")).trim()||"https://api.kie.ai/claude";if(!a2(z))throw Error("API fallback base URL must be an http(s) URL without embedded credentials");let W=process.env.OPENCODE_ANTHROPIC_AUTH_API_KEY?.trim()||await J("API key: ");if(!W.trim())throw Error("API key is required");Z.secrets?.push(W.trim());let Y=(process.env.OPENCODE_ANTHROPIC_AUTH_API_AUTH_HEADER?.trim()||await J("Auth header [authorization-bearer|x-api-key] (default authorization-bearer): ")).trim().toLowerCase()==="x-api-key"?"x-api-key":"authorization-bearer";await C0(async(X)=>{await f1();let j=await X.read(),H=Q&&Q!=="main"?Q:crypto.randomUUID(),K=j.accounts.find((U)=>U.id===H);if(K?.source==="vault")throw Error("Vault routes cannot be replaced with a local API key");await X.addApi({routeId:H,replace:Boolean(K),label:Q||void 0,apiKey:W.trim(),baseURL:z,authHeader:Y})}),console.log(`
|
|
119
|
+
Saved API fallback route${Q?` "${Q}"`:""} (${z}).`)}async function z8(){await C0(async($)=>{let Z=(await $.read()).accounts.filter((J)=>J.id!=="main");if(!Z.length){console.log("No native fallback accounts found.");return}for(let[J,Q]of Z.entries()){let z=Q.label||Q.id,W=Q.enabled?"enabled":"disabled";if(Q.type==="api"){console.log(`${J+1}. ${z} (${W}) — API route ${Q.baseURL}`);continue}let G=Q.quota?.five_hour?.remainingPercent,Y=Q.quota?.seven_day?.remainingPercent,X=G===void 0&&Y===void 0?"quota unknown":`5h ${G??"?"}%, 1w ${Y??"?"}% remaining`;console.log(`${J+1}. ${z} (${W}) — ${X}${Q.state?` — ${s2(Q)}`:""}`)}})}async function W8($){let[Z,J,Q]=process.argv.slice(2);if(!Z||Z==="help"||Z==="--help"||Z==="-h"){i2();return}if(Z==="setup"){$.stage="cli-setup";let z=await l2(process.argv.slice(3));if(z!==0)process.exitCode=z;return}if(Z==="login"){$.stage="cli-login",await J8(J,{secrets:$.secrets});return}if(Z==="api"&&J==="add"){$.stage="cli-api-add",await Q8(Q,{secrets:$.secrets});return}if(Z==="list"){$.stage="cli-list",await z8();return}if(Z==="relay"&&J==="setup"){$.stage="cli-relay-setup",await $8({secrets:$.secrets});return}i2(),process.exitCode=1}if(x3.main==x3.module){let $={stage:"cli-command",secrets:[]};try{await W8($)}catch(Z){console.error(await W0($.stage,Z,process.env,$.secrets)),process.exitCode=1}finally{Z8()}}export{l2 as runSetupCommand,$8 as relaySetup,J8 as login,Q8 as addApiRoute};
|