@cortexkit/opencode-anthropic-auth 2.15.1 → 2.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/v2/tui.js CHANGED
@@ -1,4 +1,4 @@
1
- import{y as q}from"../index-2debh0ym.js";import"../index-0btjtgy5.js";import"../index-dpxaxyck.js";var N="Open this link in your browser and sign in. Then choose Finish OAuth sign-in in the Accounts menu and paste the code Claude shows you.";async function g(D,M={}){let B=D.client.rpc(q),Z=!0,V=!1,Y=new AbortController,$=()=>{let j=D.ui.router.current();return j.type==="session"?j.sessionID:void 0};function C(j){return new Promise((Q)=>{let z="",J=!1,G=D.keymap.mode.push("cortexkit-protected-entry"),X=(H,W=!0)=>{if(J)return;J=!0,D.renderer.keyInput.off("keypress",O),D.renderer.keyInput.off("paste",P),Y.signal.removeEventListener("abort",K),G();let F=H?z:void 0;if(z="",W)D.ui.dialog.clear();Q(F)},K=()=>X(!1),O=(H)=>{if(H.preventDefault(),H.stopPropagation(),H.name==="escape"||H.ctrl&&H.name==="c")return X(!1);if(H.name==="return"||H.name==="enter")return X(!0);if(H.name==="backspace"){z=Array.from(z).slice(0,-1).join("");return}if(!H.ctrl&&!H.meta&&!H.option&&Array.from(H.sequence).every((W)=>W.charCodeAt(0)>=32&&W.charCodeAt(0)!==127))z=(z+H.sequence).slice(0,4096)},P=(H)=>{H.preventDefault(),H.stopPropagation(),z=(z+Array.from(new TextDecoder().decode(H.bytes)).filter((W)=>W.charCodeAt(0)>=32&&W.charCodeAt(0)!==127).join("")).slice(0,4096)};if(D.renderer.keyInput.prependListener("keypress",O),D.renderer.keyInput.prependListener("paste",P),Y.signal.addEventListener("abort",K,{once:!0}),D.ui.dialog.alert({title:j,message:"Type or paste the value. Input is hidden. Enter accepts; Escape cancels."}).then(()=>X(!1,!1),()=>X(!1,!1)),Y.signal.aborted)K()})}async function E(j){let Q={};for(let z of j.knobs){if(!Z)return;if(z.kind==="choice"){let J=await D.ui.dialog.select({title:z.label,options:z.choices.map((G)=>({title:G.label,value:G.value})),current:z.value});if(J===void 0)return;Q[z.id]=J}else if(z.kind==="toggle"){let J=await D.ui.dialog.select({title:z.label,options:[{title:"On",value:!0},{title:"Off",value:!1}],current:z.value});if(J===void 0)return;Q[z.id]=J}else{let J=z.kind==="text"&&z.masked?await C(z.label):await D.ui.dialog.prompt({title:z.label,value:z.value===void 0?void 0:String(z.value),placeholder:z.kind==="text"?z.placeholder:void 0});if(J===void 0)return;Q[z.id]=J===""&&!z.required?null:z.kind==="number"?Number(J):J}}return Q}async function A(j){if(M.showSignInLink)try{await M.showSignInLink(D,j,Y.signal);return}catch{}await D.ui.dialog.alert({title:"Claude sign-in",message:`${N}
1
+ import{z as q}from"../index-b3nm4hn1.js";import"../index-pvvgy8yx.js";import"../index-k9d2hevp.js";var N="Open this link in your browser and sign in. Then choose Finish OAuth sign-in in the Accounts menu and paste the code Claude shows you.";async function g(D,M={}){let B=D.client.rpc(q),Z=!0,V=!1,Y=new AbortController,$=()=>{let j=D.ui.router.current();return j.type==="session"?j.sessionID:void 0};function C(j){return new Promise((Q)=>{let z="",J=!1,G=D.keymap.mode.push("cortexkit-protected-entry"),X=(H,W=!0)=>{if(J)return;J=!0,D.renderer.keyInput.off("keypress",O),D.renderer.keyInput.off("paste",P),Y.signal.removeEventListener("abort",K),G();let F=H?z:void 0;if(z="",W)D.ui.dialog.clear();Q(F)},K=()=>X(!1),O=(H)=>{if(H.preventDefault(),H.stopPropagation(),H.name==="escape"||H.ctrl&&H.name==="c")return X(!1);if(H.name==="return"||H.name==="enter")return X(!0);if(H.name==="backspace"){z=Array.from(z).slice(0,-1).join("");return}if(!H.ctrl&&!H.meta&&!H.option&&Array.from(H.sequence).every((W)=>W.charCodeAt(0)>=32&&W.charCodeAt(0)!==127))z=(z+H.sequence).slice(0,4096)},P=(H)=>{H.preventDefault(),H.stopPropagation(),z=(z+Array.from(new TextDecoder().decode(H.bytes)).filter((W)=>W.charCodeAt(0)>=32&&W.charCodeAt(0)!==127).join("")).slice(0,4096)};if(D.renderer.keyInput.prependListener("keypress",O),D.renderer.keyInput.prependListener("paste",P),Y.signal.addEventListener("abort",K,{once:!0}),D.ui.dialog.alert({title:j,message:"Type or paste the value. Input is hidden. Enter accepts; Escape cancels."}).then(()=>X(!1,!1),()=>X(!1,!1)),Y.signal.aborted)K()})}async function E(j){let Q={};for(let z of j.knobs){if(!Z)return;if(z.kind==="choice"){let J=await D.ui.dialog.select({title:z.label,options:z.choices.map((G)=>({title:G.label,value:G.value})),current:z.value});if(J===void 0)return;Q[z.id]=J}else if(z.kind==="toggle"){let J=await D.ui.dialog.select({title:z.label,options:[{title:"On",value:!0},{title:"Off",value:!1}],current:z.value});if(J===void 0)return;Q[z.id]=J}else{let J=z.kind==="text"&&z.masked?await C(z.label):await D.ui.dialog.prompt({title:z.label,value:z.value===void 0?void 0:String(z.value),placeholder:z.kind==="text"?z.placeholder:void 0});if(J===void 0)return;Q[z.id]=J===""&&!z.required?null:z.kind==="number"?Number(J):J}}return Q}async function A(j){if(M.showSignInLink)try{await M.showSignInLink(D,j,Y.signal);return}catch{}await D.ui.dialog.alert({title:"Claude sign-in",message:`${N}
2
2
 
3
3
  ${j}
4
4
  `})}async function T(j,Q){let z=`${Q.title} status`;if(M.showStatus)try{await M.showStatus(D,{title:z,lines:Q.lines,...Q.slot==="quota"&&{readQuota:(J)=>B.sidebar({sessionId:j},{signal:J,location:D.location})}},Y.signal);return}catch{}await D.ui.dialog.alert({title:z,message:Q.lines.join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cortexkit/opencode-anthropic-auth",
3
- "version": "2.15.1",
3
+ "version": "2.15.2",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -77,7 +77,7 @@
77
77
  },
78
78
  "dependencies": {
79
79
  "@clack/prompts": "^1.6.0",
80
- "@cortexkit/anthropic-auth-core": "2.15.1",
80
+ "@cortexkit/anthropic-auth-core": "2.15.2",
81
81
  "@cortexkit/claustrum-client": "0.18.0",
82
82
  "@cortexkit/private-files": "0.2.2",
83
83
  "@cortexkit/subc-client": "^0.24",
@@ -30,11 +30,30 @@ function pidAlive(pid: number): boolean {
30
30
  }
31
31
  }
32
32
 
33
+ /** Filesystem operations and retry delay; tests supply controlled races. */
34
+ export interface PortFileWriterIo {
35
+ mkdir(dir: string): Promise<void>
36
+ write(path: string, text: string): Promise<void>
37
+ rename(from: string, to: string): Promise<void>
38
+ sleep(ms: number): Promise<void>
39
+ }
40
+
41
+ const writerIo: PortFileWriterIo = {
42
+ mkdir: async (dir) => {
43
+ await mkdir(dir, { recursive: true })
44
+ },
45
+ write: (path, text) =>
46
+ writeFile(path, text, { encoding: 'utf8', mode: 0o600 }),
47
+ rename,
48
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
49
+ }
50
+
33
51
  export async function writePortFile(
34
52
  dir: string,
35
53
  entry: { port: number; token: string; pid: number },
54
+ overrides: Partial<PortFileWriterIo> = {},
36
55
  ): Promise<string> {
37
- await mkdir(dir, { recursive: true })
56
+ const io = { ...writerIo, ...overrides }
38
57
  const full: PortFileEntry = {
39
58
  ...entry,
40
59
  startedAt: Date.now(),
@@ -42,9 +61,19 @@ export async function writePortFile(
42
61
  }
43
62
  const target = join(dir, `port-${entry.pid}.json`)
44
63
  const tmp = `${target}.${process.pid}.tmp`
45
- await writeFile(tmp, JSON.stringify(full), { encoding: 'utf8', mode: 0o600 })
46
- await rename(tmp, target)
47
- return target
64
+ for (let attempt = 1; ; attempt++) {
65
+ await io.mkdir(dir)
66
+ try {
67
+ await io.write(tmp, JSON.stringify(full))
68
+ await io.rename(tmp, target)
69
+ return target
70
+ } catch (error) {
71
+ // A concurrent sweep or older process may remove an empty project folder.
72
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || attempt >= 5)
73
+ throw error
74
+ await io.sleep(25)
75
+ }
76
+ }
48
77
  }
49
78
 
50
79
  export async function discoverPortFile(
@@ -13,12 +13,16 @@ export function getRpcDir(projectDirectory: string): string {
13
13
  .update(projectDirectory)
14
14
  .digest('hex')
15
15
  .slice(0, 16)
16
+ return join(getRpcRoot(), hash)
17
+ }
18
+
19
+ export function getRpcRoot(): string {
16
20
  const root = anthropicAuthStateRoot({
17
21
  xdgStateHome: process.env.XDG_STATE_HOME,
18
22
  home: homedir(),
19
23
  acceptRelative: true,
20
24
  })
21
- return join(root, 'rpc', hash)
25
+ return join(root, 'rpc')
22
26
  }
23
27
 
24
28
  export { tmpdir }
@@ -15,6 +15,7 @@ import {
15
15
  import type { drainNotifications } from './notifications'
16
16
  import { writePortFile } from './port-file'
17
17
  import type { ApplyRequest, ApplyResult } from './protocol'
18
+ import { type RpcSweepOptions, sweepRpcState } from './sweep'
18
19
 
19
20
  export interface RpcServerHandle {
20
21
  port: number
@@ -29,6 +30,7 @@ export interface RpcServerOptions {
29
30
  apply?: (request: ApplyRequest) => Promise<ApplyResult>
30
31
  /** Run menu actions through the host's credential service, not legacy account-file writes. */
31
32
  applyMenu?: (request: CommandApplyRequest) => Promise<CommandApplyResult>
33
+ sweep?: RpcSweepOptions
32
34
  }
33
35
 
34
36
  function readBody(req: IncomingMessage): Promise<string> {
@@ -163,6 +165,7 @@ export async function startRpcServer(
163
165
  await closeServer()
164
166
  throw error
165
167
  }
168
+ void sweepRpcState(options.dir, options.sweep)
166
169
 
167
170
  return {
168
171
  port,
@@ -0,0 +1,179 @@
1
+ import { lstat, readdir, readFile, rmdir, unlink } from 'node:fs/promises'
2
+ import { basename, dirname, join, resolve } from 'node:path'
3
+ import { logger, processStartedAtMs } from '@cortexkit/anthropic-auth-core'
4
+ import { getRpcRoot } from './rpc-dir'
5
+
6
+ const SWEEP_STATE = Symbol.for('cortexkit.anthropic-auth.rpc-sweep')
7
+ const INTERVAL_MS = 60_000
8
+ const MANAGED_DIR = /^[0-9a-f]{16}$/
9
+
10
+ export interface RpcSweepState {
11
+ lastFull?: number
12
+ }
13
+
14
+ export interface RpcSweepOptions {
15
+ root?: string
16
+ now?: () => number
17
+ /** Signal-zero probe: only the OS "no such process" error proves a process dead. */
18
+ probe?: (pid: number) => void
19
+ processStartedAtMs?: (pid: number) => Promise<number | null>
20
+ state?: RpcSweepState
21
+ log?: (name: string) => void
22
+ }
23
+
24
+ function globalState(): RpcSweepState {
25
+ const shared = globalThis as typeof globalThis & {
26
+ [SWEEP_STATE]?: RpcSweepState
27
+ }
28
+ shared[SWEEP_STATE] ??= {}
29
+ return shared[SWEEP_STATE]
30
+ }
31
+
32
+ function code(error: unknown): unknown {
33
+ return (error as NodeJS.ErrnoException | null)?.code
34
+ }
35
+
36
+ function pidNumber(text: string): number | undefined {
37
+ const pid = Number(text)
38
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : undefined
39
+ }
40
+
41
+ /** Best-effort cleanup; callers may detach it without an unhandled rejection. */
42
+ export async function sweepRpcState(
43
+ activeDir: string,
44
+ options: RpcSweepOptions = {},
45
+ ): Promise<void> {
46
+ let failure: string | undefined
47
+ const failed = (name: string, error: unknown) => {
48
+ if (code(error) !== 'ENOENT') failure ??= name
49
+ }
50
+ try {
51
+ const root = resolve(options.root ?? getRpcRoot())
52
+ const active = resolve(activeDir)
53
+ // An override outside the managed root must not turn its parent into a sweep root.
54
+ if (dirname(active) !== root || !MANAGED_DIR.test(basename(active))) return
55
+ const now = (options.now ?? Date.now)()
56
+ const state = options.state ?? globalState()
57
+ const full =
58
+ state.lastFull === undefined || now - state.lastFull >= INTERVAL_MS
59
+ // Reserve before any await so simultaneous project starts share one sweep.
60
+ if (full) state.lastFull = now
61
+ const rootStat = await lstat(root)
62
+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) return
63
+ const probe = options.probe ?? ((pid: number) => process.kill(pid, 0))
64
+ const startTime = options.processStartedAtMs ?? processStartedAtMs
65
+ const dead = async (pid: number, written?: unknown): Promise<boolean> => {
66
+ try {
67
+ probe(pid)
68
+ } catch (error) {
69
+ // Permission failures and unknown errors are not proof of death.
70
+ return code(error) === 'ESRCH'
71
+ }
72
+ if (
73
+ typeof written !== 'number' ||
74
+ !Number.isFinite(written) ||
75
+ written < 0 ||
76
+ written > now
77
+ )
78
+ return false
79
+ try {
80
+ const start = await startTime(pid)
81
+ return (
82
+ start !== null && Number.isFinite(start) && start > written + 2_000
83
+ )
84
+ } catch {
85
+ return false
86
+ }
87
+ }
88
+ const names = full
89
+ ? await readdir(root)
90
+ : dirname(active) === root
91
+ ? [basename(active)]
92
+ : []
93
+ for (const dirName of names) {
94
+ if (!MANAGED_DIR.test(dirName)) continue
95
+ const dir = join(root, dirName)
96
+ try {
97
+ const stat = await lstat(dir)
98
+ if (!stat.isDirectory() || stat.isSymbolicLink()) continue
99
+ for (const name of await readdir(dir)) {
100
+ const record = /^port-(\d+)\.json$/.exec(name)
101
+ const temp = /^port-(\d+)\.json\.(\d+)\.tmp$/.exec(name)
102
+ const pid = pidNumber(temp?.[2] ?? record?.[1] ?? '')
103
+ if (pid === undefined || (!record && !temp)) continue
104
+ const path = join(dir, name)
105
+ try {
106
+ const file = await lstat(path)
107
+ if (!file.isFile() || file.isSymbolicLink()) continue
108
+ let written: unknown
109
+ let text: string | undefined
110
+ if (record) {
111
+ text = await readFile(path, 'utf8')
112
+ let value: unknown
113
+ let parsed = false
114
+ try {
115
+ value = JSON.parse(text)
116
+ parsed = true
117
+ } catch {}
118
+ if (parsed) {
119
+ if (
120
+ typeof value !== 'object' ||
121
+ value === null ||
122
+ !('pid' in value) ||
123
+ value.pid !== pid
124
+ )
125
+ continue
126
+ // An explicitly invalid time is not replaced by an older mtime.
127
+ written =
128
+ 'startedAt' in value
129
+ ? value.startedAt
130
+ : 'registeredAt' in value
131
+ ? value.registeredAt
132
+ : file.mtimeMs
133
+ } else written = file.mtimeMs
134
+ }
135
+ // Temporary files have no trustworthy record; only a dead writer clears them.
136
+ if (await dead(pid, written)) {
137
+ // A new writer may have replaced a stale record during the OS lookup.
138
+ if (record && (await readFile(path, 'utf8')) !== text) continue
139
+ const current = await lstat(path)
140
+ if (
141
+ current.isFile() &&
142
+ current.dev === file.dev &&
143
+ current.ino === file.ino &&
144
+ current.size === file.size &&
145
+ current.mtimeMs === file.mtimeMs &&
146
+ current.ctimeMs === file.ctimeMs
147
+ )
148
+ await unlink(path)
149
+ }
150
+ } catch (error) {
151
+ failed(`${dirName}/${name}`, error)
152
+ }
153
+ }
154
+ try {
155
+ // A writer can be between mkdir and its first temporary-file write.
156
+ const current = await lstat(dir)
157
+ if (current.isDirectory() && current.mtimeMs < now - INTERVAL_MS)
158
+ await rmdir(dir)
159
+ } catch (error) {
160
+ if (code(error) !== 'ENOTEMPTY' && code(error) !== 'EEXIST')
161
+ failed(dirName, error)
162
+ }
163
+ } catch (error) {
164
+ failed(dirName, error)
165
+ }
166
+ }
167
+ } catch (error) {
168
+ failed('.', error)
169
+ }
170
+ if (failure !== undefined) {
171
+ try {
172
+ const log =
173
+ options.log ??
174
+ ((name: string) =>
175
+ logger.debug('rpc', 'RPC state cleanup failed', { name }))
176
+ log(failure)
177
+ } catch {}
178
+ }
179
+ }
@@ -30,11 +30,30 @@ function pidAlive(pid: number): boolean {
30
30
  }
31
31
  }
32
32
 
33
+ /** Filesystem operations and retry delay; tests supply controlled races. */
34
+ export interface PortFileWriterIo {
35
+ mkdir(dir: string): Promise<void>
36
+ write(path: string, text: string): Promise<void>
37
+ rename(from: string, to: string): Promise<void>
38
+ sleep(ms: number): Promise<void>
39
+ }
40
+
41
+ const writerIo: PortFileWriterIo = {
42
+ mkdir: async (dir) => {
43
+ await mkdir(dir, { recursive: true })
44
+ },
45
+ write: (path, text) =>
46
+ writeFile(path, text, { encoding: 'utf8', mode: 0o600 }),
47
+ rename,
48
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
49
+ }
50
+
33
51
  export async function writePortFile(
34
52
  dir: string,
35
53
  entry: { port: number; token: string; pid: number },
54
+ overrides: Partial<PortFileWriterIo> = {},
36
55
  ): Promise<string> {
37
- await mkdir(dir, { recursive: true })
56
+ const io = { ...writerIo, ...overrides }
38
57
  const full: PortFileEntry = {
39
58
  ...entry,
40
59
  startedAt: Date.now(),
@@ -42,9 +61,19 @@ export async function writePortFile(
42
61
  }
43
62
  const target = join(dir, `port-${entry.pid}.json`)
44
63
  const tmp = `${target}.${process.pid}.tmp`
45
- await writeFile(tmp, JSON.stringify(full), { encoding: 'utf8', mode: 0o600 })
46
- await rename(tmp, target)
47
- return target
64
+ for (let attempt = 1; ; attempt++) {
65
+ await io.mkdir(dir)
66
+ try {
67
+ await io.write(tmp, JSON.stringify(full))
68
+ await io.rename(tmp, target)
69
+ return target
70
+ } catch (error) {
71
+ // A concurrent sweep or older process may remove an empty project folder.
72
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || attempt >= 5)
73
+ throw error
74
+ await io.sleep(25)
75
+ }
76
+ }
48
77
  }
49
78
 
50
79
  export async function discoverPortFile(
@@ -13,12 +13,16 @@ export function getRpcDir(projectDirectory: string): string {
13
13
  .update(projectDirectory)
14
14
  .digest('hex')
15
15
  .slice(0, 16)
16
+ return join(getRpcRoot(), hash)
17
+ }
18
+
19
+ export function getRpcRoot(): string {
16
20
  const root = anthropicAuthStateRoot({
17
21
  xdgStateHome: process.env.XDG_STATE_HOME,
18
22
  home: homedir(),
19
23
  acceptRelative: true,
20
24
  })
21
- return join(root, 'rpc', hash)
25
+ return join(root, 'rpc')
22
26
  }
23
27
 
24
28
  export { tmpdir }
@@ -1,2 +0,0 @@
1
- import{mkdir as I,readdir as J,readFile as K,rename as L,unlink as M,writeFile as N}from"node:fs/promises";import{join as H}from"node:path";import{writerStamp as Q}from"@cortexkit/anthropic-auth-core";function R(q){try{return process.kill(q,0),!0}catch(z){return z.code==="EPERM"}}async function X(q,z){await I(q,{recursive:!0});let G={...z,startedAt:Date.now(),writer:Q()},B=H(q,`port-${z.pid}.json`),D=`${B}.${process.pid}.tmp`;return await N(D,JSON.stringify(G),{encoding:"utf8",mode:384}),await L(D,B),B}async function Y(q,z){let G;try{G=await J(q)}catch{return null}let B=[];for(let C of G){if(!C.startsWith("port-")||!C.endsWith(".json"))continue;try{let E=JSON.parse(await K(H(q,C),"utf8"));if(Number.isFinite(E.port))if(R(E.pid))B.push(E);else M(H(q,C)).catch(()=>{})}catch{}}if(B.length===0)return null;let D=z&&z>=1?B.filter((C)=>C.pid===z):[];return(D.length>0?D:B).sort((C,E)=>E.startedAt-C.startedAt)[0]??null}
2
- export{X as ka,Y as la};
@@ -1 +0,0 @@
1
- import{createHash as z}from"node:crypto";import{homedir as F,tmpdir as T}from"node:os";import{join as G,resolve as J}from"node:path";import{anthropicAuthStateRoot as K}from"@cortexkit/anthropic-auth-core";var L="OPENCODE_ANTHROPIC_AUTH_RPC_DIR";function X(b){let g=process.env[L]?.trim();if(g)return J(b,g);let q=z("sha256").update(b).digest("hex").slice(0,16),w=K({xdgStateHome:process.env.XDG_STATE_HOME,home:F(),acceptRelative:!0});return G(w,"rpc",q)}export{T as w,X as x};