@link-assistant/router 0.0.0-stage → 1.26.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.
Files changed (161) hide show
  1. package/README.md +35 -2
  2. package/catalog.json +68542 -0
  3. package/index.d.ts +5932 -0
  4. package/index.js +224 -0
  5. package/native.d.ts +106 -0
  6. package/package.json +62 -4
  7. package/portable/policy.mjs +117 -0
  8. package/schemas/accounts-list.v1.json +323 -0
  9. package/schemas/accounts-pause.v1.json +97 -0
  10. package/schemas/accounts-policy.v1.json +214 -0
  11. package/schemas/accounts-resume.v1.json +97 -0
  12. package/schemas/auth-claude.v1.json +97 -0
  13. package/schemas/auth-clear.v1.json +97 -0
  14. package/schemas/auth-codex.v1.json +97 -0
  15. package/schemas/auth-gh.v1.json +97 -0
  16. package/schemas/auth-import.v1.json +167 -0
  17. package/schemas/auth-status.v1.json +387 -0
  18. package/schemas/cli-error.v1.json +97 -0
  19. package/schemas/clients-backup-create.v1.json +97 -0
  20. package/schemas/clients-backup-list.v1.json +234 -0
  21. package/schemas/clients-backup-restore.v1.json +97 -0
  22. package/schemas/clients-backup-verify.v1.json +125 -0
  23. package/schemas/clients-doctor.v1.json +249 -0
  24. package/schemas/clients-install.v1.json +164 -0
  25. package/schemas/clients-list.v1.json +194 -0
  26. package/schemas/clients-reinstall.v1.json +164 -0
  27. package/schemas/clients-remove.v1.json +97 -0
  28. package/schemas/clients-repair.v1.json +109 -0
  29. package/schemas/clients-reset.v1.json +113 -0
  30. package/schemas/clients-setup.v1.json +97 -0
  31. package/schemas/clients-show.v1.json +191 -0
  32. package/schemas/clients-update.v1.json +164 -0
  33. package/schemas/configure.v1.json +97 -0
  34. package/schemas/contracts.v1.json +106 -0
  35. package/schemas/data-backup.v1.json +32 -0
  36. package/schemas/deploy.v1.json +546 -0
  37. package/schemas/doctor.v1.json +324 -0
  38. package/schemas/local-deployment.v1.json +364 -0
  39. package/schemas/logs-anomalies.v1.json +112 -0
  40. package/schemas/logs-show.v1.json +127 -0
  41. package/schemas/logs-summary.v1.json +129 -0
  42. package/schemas/model-catalog.v1.json +117 -0
  43. package/schemas/models-explain.v1.json +325 -0
  44. package/schemas/preservation.v1.json +47 -0
  45. package/schemas/providers-add.v1.json +185 -0
  46. package/schemas/providers-import.v1.json +97 -0
  47. package/schemas/providers-list.v1.json +182 -0
  48. package/schemas/providers-remove.v1.json +97 -0
  49. package/schemas/providers-show.v1.json +179 -0
  50. package/schemas/serve.v1.json +97 -0
  51. package/schemas/server-claim.v1.json +97 -0
  52. package/schemas/server-reap.v1.json +97 -0
  53. package/schemas/server-remove.v1.json +97 -0
  54. package/schemas/server-start.v1.json +97 -0
  55. package/schemas/server-status.v1.json +197 -0
  56. package/schemas/server-stop.v1.json +97 -0
  57. package/schemas/server-use.v1.json +97 -0
  58. package/schemas/staging.v1.json +47 -0
  59. package/schemas/tls-ca.v1.json +97 -0
  60. package/schemas/tls-generate.v1.json +97 -0
  61. package/schemas/tokens-expire.v1.json +97 -0
  62. package/schemas/tokens-import.v1.json +192 -0
  63. package/schemas/tokens-issue.v1.json +94 -0
  64. package/schemas/tokens-list.v1.json +272 -0
  65. package/schemas/tokens-recover-admin.v1.json +116 -0
  66. package/schemas/tokens-revoke.v1.json +97 -0
  67. package/schemas/tokens-rotate.v1.json +94 -0
  68. package/schemas/tokens-show.v1.json +269 -0
  69. package/schemas/tunnel-down.v1.json +97 -0
  70. package/schemas/tunnel-status.v1.json +165 -0
  71. package/schemas/tunnel-up.v1.json +97 -0
  72. package/schemas/usage.v1.json +621 -0
  73. package/schemas/verification.v1.json +254 -0
  74. package/schemas/verify.v1.json +338 -0
  75. package/schemas/version.v1.json +103 -0
  76. package/schemas/with.v1.json +105 -0
  77. package/src/accounts.mjs +233 -0
  78. package/src/activitypub.mjs +23 -0
  79. package/src/admin-assets.mjs +16 -0
  80. package/src/admin.mjs +108 -0
  81. package/src/affinities.mjs +180 -0
  82. package/src/affinity-schema-descriptor.mjs +2 -0
  83. package/src/affinity-schema.mjs +185 -0
  84. package/src/assets/admin/assets/app.js +1 -0
  85. package/src/assets/admin/assets/react.js +9 -0
  86. package/src/assets/admin/assets/rolldown-runtime.js +1 -0
  87. package/src/assets/admin/assets/ui-vendor.js +3 -0
  88. package/src/assets/admin/index.html +16 -0
  89. package/src/auth-service.mjs +149 -0
  90. package/src/claude-process-session.mjs +26 -0
  91. package/src/cli-output.mjs +21 -0
  92. package/src/cli.mjs +84 -0
  93. package/src/client-ca.mjs +8 -0
  94. package/src/client-catalog.mjs +52 -0
  95. package/src/client-codex-catalog.mjs +18 -0
  96. package/src/client-configure.mjs +72 -0
  97. package/src/client-files.mjs +82 -0
  98. package/src/client-global-repair.mjs +19 -0
  99. package/src/client-global-state.mjs +19 -0
  100. package/src/client-global.mjs +43 -0
  101. package/src/client-json.mjs +54 -0
  102. package/src/client-launch-plan.mjs +28 -0
  103. package/src/client-launch.mjs +35 -0
  104. package/src/client-persistent.mjs +66 -0
  105. package/src/client-process-profile.mjs +52 -0
  106. package/src/client-process-settings.mjs +36 -0
  107. package/src/client-process.mjs +44 -0
  108. package/src/client-profile-backup.mjs +29 -0
  109. package/src/client-remote-health.mjs +7 -0
  110. package/src/client-remote.mjs +55 -0
  111. package/src/client-run-credential.mjs +38 -0
  112. package/src/client-setup.mjs +97 -0
  113. package/src/client-status.mjs +102 -0
  114. package/src/client-toml-cst.mjs +71 -0
  115. package/src/client-transaction.mjs +48 -0
  116. package/src/codex-login.mjs +121 -0
  117. package/src/codex-loopback-transport.mjs +34 -0
  118. package/src/codex-loopback.mjs +60 -0
  119. package/src/config.mjs +198 -0
  120. package/src/core.mjs +198 -0
  121. package/src/credential-operations.mjs +119 -0
  122. package/src/doublets.mjs +157 -0
  123. package/src/emergency-auth.mjs +91 -0
  124. package/src/file-lock.mjs +107 -0
  125. package/src/gemini-protocol.mjs +133 -0
  126. package/src/geolocation.mjs +46 -0
  127. package/src/git-proxy.mjs +52 -0
  128. package/src/github-proxy.mjs +74 -0
  129. package/src/http-management.mjs +36 -0
  130. package/src/http-route-contract.mjs +479 -0
  131. package/src/index.mjs +4 -0
  132. package/src/local-router-discovery.mjs +31 -0
  133. package/src/managed-server.mjs +411 -0
  134. package/src/management-access.mjs +76 -0
  135. package/src/native-service.mjs +392 -0
  136. package/src/oauth.mjs +547 -0
  137. package/src/operation-input.mjs +20 -0
  138. package/src/operations.mjs +378 -0
  139. package/src/protocols.mjs +229 -0
  140. package/src/provider-manifest.mjs +46 -0
  141. package/src/provider-provision.mjs +24 -0
  142. package/src/remote-operations.mjs +166 -0
  143. package/src/request-log.mjs +99 -0
  144. package/src/resources.mjs +290 -0
  145. package/src/response-contracts.mjs +147 -0
  146. package/src/responses.mjs +103 -0
  147. package/src/routing.mjs +40 -0
  148. package/src/runtime-config.mjs +133 -0
  149. package/src/runtime-payload.mjs +190 -0
  150. package/src/sensitive-data-sse.mjs +121 -0
  151. package/src/sensitive-data.mjs +254 -0
  152. package/src/server.mjs +552 -0
  153. package/src/storage.mjs +367 -0
  154. package/src/streams.mjs +232 -0
  155. package/src/token-import.mjs +68 -0
  156. package/src/token-reservation.mjs +8 -0
  157. package/src/tokens.mjs +172 -0
  158. package/src/usage.mjs +54 -0
  159. package/src/websocket-relay.mjs +131 -0
  160. package/testing.d.ts +7 -0
  161. package/testing.js +57 -0
@@ -0,0 +1,16 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <meta name="robots" content="noindex, nofollow" />
7
+ <title>Link.Assistant.Router — Admin</title>
8
+ <script type="module" crossorigin src="/assets/app.js"></script>
9
+ <link rel="modulepreload" crossorigin href="/assets/rolldown-runtime.js">
10
+ <link rel="modulepreload" crossorigin href="/assets/react.js">
11
+ <link rel="modulepreload" crossorigin href="/assets/ui-vendor.js">
12
+ </head>
13
+ <body>
14
+ <div id="root"></div>
15
+ </body>
16
+ </html>
@@ -0,0 +1,149 @@
1
+ /** Provider-verified credential reports and bounded native login sessions. */
2
+ import { randomUUID } from 'node:crypto';
3
+ import { rm } from 'node:fs/promises';
4
+ import { join, resolve } from 'node:path';
5
+ import * as oauthPrimitives from './oauth.mjs';
6
+ import {CodexLogin} from './codex-login.mjs';
7
+
8
+ const {CredentialFileStore,OAuthManager,ClaudeLogin,importCredential,validateCredentialCatalog,subscriptionHome} = oauthPrimitives;
9
+ const fail = (code,message,status = 400) => Object.assign(new Error(message),{code,status});
10
+ const providers = ['claude','codex','gemini','qwen'];
11
+ const pending = new Set(['awaiting_code','awaiting_callback','awaiting_device']);
12
+ const integer = (value,fallback,name) => {
13
+ value = value ?? fallback;
14
+ if (!Number.isSafeInteger(value) || value <= 0) throw fail('invalid_login_config',`${name} must be a positive safe integer`);
15
+ return value;
16
+ };
17
+ function homeFor(core,provider,env = {}) {return subscriptionHome(provider,{config:core.config,env});}
18
+
19
+ function safeCode(error) {return /^[a-z0-9_-]{1,100}$/i.test(error?.code ?? '') ? error.code : 'authorization_failed';}
20
+
21
+ export async function nativeCredentialStatus(core,{env = {},fetch = core.oauth?.fetch ?? globalThis.fetch,validateCatalog = validateCredentialCatalog,catalogBaseURL,allowLoopback = false} = {}) {
22
+ const credentials = [],sources = [];
23
+ for (const provider of providers) {
24
+ const home = homeFor(core,provider,env);let held,store;
25
+ try {
26
+ store = new CredentialFileStore({provider,home,dataDir:core.config.data_dir,clock:core.clock});
27
+ held = await store.transaction(()=>store.reload());
28
+ if (!held) {credentials.push({provider,home,state:'absent'});sources.push({provider,source:{kind:'absent'}});continue;}
29
+ sources.push({provider,source:held.origin === 'adopted' ? {kind:'followed',source:held.path,present:true}
30
+ : held.origin === 'external' ? {kind:'externally-owned'} : {kind:'owned'}});
31
+ const token = await core.oauth.getFresh(store);
32
+ const models = await validateCatalog({provider,token,fetch,baseURL:typeof catalogBaseURL === 'object' ? catalogBaseURL[provider] : catalogBaseURL,allowLoopback});
33
+ if (!Array.isArray(models) || !models.some(model=>typeof model === 'string' && model.trim())) throw fail('catalog_unverified','Provider catalog did not verify an executable model',502);
34
+ credentials.push({provider,home,state:'usable'});
35
+ } catch (error) {
36
+ const code = safeCode(error),state = code === 'catalog_rejected' ? 'rejected' : /refresh|no_refresh_token|external_refresh_owner/.test(code) ? 'refresh-failed' : 'unverified';
37
+ credentials.push({provider,home,state,detail:`Credential inspection failed (${code})`});
38
+ }
39
+ }
40
+ return {credentials,sources,api_key_providers:(await core.providers.list()).map(provider=>({
41
+ name:provider.name,kind:provider.kind ?? 'openai-compatible',base_url:provider.base_url,
42
+ models:provider.models ?? [],supported_clients:provider.supported_clients ?? [],
43
+ has_encrypted_api_key:Boolean(provider.has_encrypted_api_key ?? provider.api_key),enabled:provider.enabled !== false,
44
+ intermediary_risk_acknowledged:Boolean(provider.intermediary_risk_acknowledged),unsupported_clients:provider.unsupported_clients ?? [],
45
+ ...Object.fromEntries(['api_key_env','default_model','subscriber_id'].filter(key=>provider[key] !== undefined).map(key=>[key,provider[key]])),
46
+ })),output:[]};
47
+ }
48
+
49
+ export class NativeLoginManager {
50
+ constructor(core,{env = {},fetch = core.oauth?.fetch ?? globalThis.fetch,clock = core.clock,loginFactories = {},validateCatalog = validateCredentialCatalog,...oauth} = {}) {
51
+ this.core = core;this.env = env;this.fetch = fetch;this.clock = clock;this.factories = loginFactories;this.validateCatalog = validateCatalog;this.oauth = oauth;
52
+ this.enabled = core.config.login?.enabled ?? core.config.disable_login_api !== true;
53
+ this.maxSessions = integer(core.config.login?.max_sessions ?? core.config.login_max_sessions,4,'max_sessions');
54
+ this.ttlSeconds = integer(core.config.login?.session_ttl_secs ?? core.config.login_session_ttl_secs,900,'session_ttl_secs');
55
+ this.retentionSeconds = integer(core.config.login?.terminal_retention_secs,60,'terminal_retention_secs');
56
+ this.sessions = new Map();
57
+ }
58
+ view(session) {
59
+ return {login_id:session.id,provider:session.provider,status:session.status,session_expires_at:new Date(session.expires * 1000).toISOString(),
60
+ ...(pending.has(session.status) && session.url ? {url:session.url} : {}),
61
+ ...(pending.has(session.status) && session.userCode ? {user_code:session.userCode} : {}),
62
+ ...(session.credentialExpiry !== undefined ? {expires_at:session.credentialExpiry} : {}),
63
+ ...(session.error ? {error:session.error} : {})};
64
+ }
65
+ async sweep() {
66
+ const now = this.clock();
67
+ for (const [id,session] of this.sessions) {
68
+ if (pending.has(session.status) && !session.promoting && session.expires <= now) {
69
+ session.status = 'expired';session.error = 'login session expired before authorization completed';session.settled = now;session.controller.abort();
70
+ if (!session.inFlight) await rm(session.stage,{recursive:true,force:true});
71
+ } else if (session.settled !== undefined && session.settled + this.retentionSeconds <= now) this.sessions.delete(id);
72
+ }
73
+ }
74
+ async begin(body = {}) {
75
+ if (!this.enabled) throw fail('login_disabled','the login API is disabled',403);
76
+ if (!body || typeof body !== 'object' || Array.isArray(body)) throw fail('invalid_login','login request must be an object');
77
+ const provider = body.provider ?? 'claude';
78
+ if (!providers.includes(provider)) throw fail('invalid_provider','unknown subscription provider');
79
+ await this.sweep();
80
+ if ([...this.sessions.values()].filter(session=>pending.has(session.status)).length >= this.maxSessions) throw fail('too_many_sessions',`too many pending logins (limit ${this.maxSessions}); cancel one first`,429);
81
+ const factory = this.factories[provider] ?? (provider === 'claude' ? async options=>ClaudeLogin.begin(options)
82
+ : provider === 'codex' ? async options=>CodexLogin.begin(options) : null);
83
+ if (!factory) throw fail('native_unsupported',`${provider} native login driver is unavailable`,501);
84
+ const id = randomUUID(),stage = join(this.core.config.data_dir,'native-login-sessions',id),home = join(stage,provider);
85
+ const session = {id,provider,stage,home,status:provider === 'claude' ? 'awaiting_code' : 'awaiting_device',expires:this.clock()+this.ttlSeconds,controller:new AbortController(),inFlight:false};
86
+ // Reserve before awaiting a driver so simultaneous begin calls cannot
87
+ // exceed the configured pending-session budget.
88
+ this.sessions.set(id,session);
89
+ try {
90
+ const fetch = (url,options = {})=>this.fetch(url,{...options,signal:options.signal ? AbortSignal.any([options.signal,session.controller.signal]) : session.controller.signal});
91
+ const manager = new OAuthManager({fetch,clock:this.clock,...this.oauth});
92
+ session.driver = await factory({provider,home,manager,clock:this.clock,signal:session.controller.signal,mode:body.mode,flow:body.flow,dataDir:this.core.config.data_dir,validateCatalog:this.validateCatalog,...this.oauth});
93
+ if (this.sessions.get(id) !== session || session.controller.signal.aborted) throw fail('login_cancelled','login session cancelled',409);
94
+ session.url = typeof session.driver.authorizationURL === 'function' ? session.driver.authorizationURL() : session.driver.url;
95
+ session.userCode = session.driver.userCode ?? session.driver.user_code;
96
+ if (session.driver.status) session.status = session.driver.status;
97
+ if (!pending.has(session.status) || typeof session.url !== 'string') throw fail('invalid_login_driver','login driver did not return a pending authorization URL',502);
98
+ if (session.status !== 'awaiting_code' && typeof session.driver.wait === 'function') {
99
+ session.inFlight = true;
100
+ session.background = this.finish(session,()=>session.driver.wait({signal:session.controller.signal})).finally(()=>{session.inFlight = false;});
101
+ }
102
+ return this.view(session);
103
+ } catch (error) {
104
+ this.sessions.delete(id);session.controller.abort();await rm(stage,{recursive:true,force:true});throw error;
105
+ }
106
+ }
107
+ async status(id) {await this.sweep();const session = this.sessions.get(id);return session ? this.view(session) : null;}
108
+ active(session) {
109
+ if (this.sessions.get(session.id) !== session || session.controller.signal.aborted || !pending.has(session.status) || !session.promoting && session.expires <= this.clock()) throw fail('login_cancelled','login no longer owns credential promotion',409);
110
+ }
111
+ async finish(session,complete) {
112
+ try {
113
+ await complete();this.active(session);
114
+ await importCredential({provider:session.provider,sourceHome:session.home,destinationHome:homeFor(this.core,session.provider,this.env),dataDir:this.core.config.data_dir,
115
+ fetch:this.fetch,clock:this.clock,validateCatalog:this.validateCatalog,owned:true,beforePromote:()=>{this.active(session);session.promoting = true;},...this.oauth});
116
+ this.active(session);
117
+ const credential = await new CredentialFileStore({provider:session.provider,home:homeFor(this.core,session.provider,this.env),dataDir:this.core.config.data_dir,clock:this.clock}).reload();
118
+ if (!credential) throw fail('credential_missing','login did not persist a readable credential',502);
119
+ session.status = 'authorized';session.promoting = false;session.settled = this.clock();
120
+ if (credential.token.expires_at_ms !== undefined) session.credentialExpiry = Math.floor(credential.token.expires_at_ms / 1000);
121
+ await rm(session.stage,{recursive:true,force:true});
122
+ } catch (error) {
123
+ session.promoting = false;
124
+ if (this.sessions.get(session.id) === session && session.status !== 'expired') {session.status = 'failed';session.error = `Authorization failed (${safeCode(error)})`;session.settled = this.clock();}
125
+ // Exchanged credentials stay in the private recovery stage if final
126
+ // promotion failed. A failed session never reports authorization.
127
+ session.controller.abort();
128
+ }
129
+ return this.view(session);
130
+ }
131
+ async submitCode(id,code) {
132
+ if (!this.enabled) throw fail('login_disabled','the login API is disabled',403);
133
+ await this.sweep();const session = this.sessions.get(id);
134
+ if (!session) throw fail('login_not_found','unknown login_id',404);
135
+ if (session.status !== 'awaiting_code' || session.inFlight) throw fail('login_not_pending',`login is not awaiting a code (status: ${session.status})`,409);
136
+ if (typeof code !== 'string' || !code.trim() || Buffer.byteLength(code) > 16384) throw fail('invalid_code','authorization code must be nonempty and within 16 KiB');
137
+ session.inFlight = true;
138
+ try {return await this.finish(session,()=>session.driver.complete(code.trim(),{dataDir:this.core.config.data_dir,validateCatalog:this.validateCatalog,...this.oauth}));}
139
+ finally {session.inFlight = false;}
140
+ }
141
+ async cancel(id) {
142
+ const session = this.sessions.get(id);if (!session) return false;
143
+ if (session.promoting) throw fail('login_promotion_in_progress','credential promotion has begun and cannot be cancelled',409);
144
+ this.sessions.delete(id);session.controller.abort();await session.driver?.cancel?.();
145
+ if (!session.inFlight) await rm(session.stage,{recursive:true,force:true});
146
+ return true;
147
+ }
148
+ async dispose() {await Promise.all([...this.sessions.keys()].map(id=>this.cancel(id)));}
149
+ }
@@ -0,0 +1,26 @@
1
+ /** Shared native activity markers and verified settings-only reset for Router Claude profiles. */
2
+ import {mkdir,chmod,lstat,readdir,unlink,rename} from 'node:fs/promises';import {join,dirname} from 'node:path';import {randomUUID} from 'node:crypto';import {createInterface} from 'node:readline/promises';
3
+ import {clientFailure} from './client-files.mjs';import {requireNativePath,readNativeText} from './operation-input.mjs';import {atomicWrite} from './storage.mjs';import {withAdvisoryFileLock} from './file-lock.mjs';
4
+ import {snapshotClientProfile,createVerifiedClientProfileBackup,verifyClientProfileBackup} from './client-profile-backup.mjs';
5
+ async function exists(path){try{return await lstat(path);}catch(error){if(Object(error).code==='ENOENT')return null;throw error;}}
6
+ function alive(pid){try{process.kill(pid,0);return true;}catch(error){if(Object(error).code==='ESRCH')return false;if(Object(error).code==='EPERM')return true;throw error;}}
7
+ async function inactive(active){
8
+ await requireNativePath(active);if(!await exists(active))return;const names=await readdir(active);if(names.length>1000)throw clientFailure('Claude activity marker inventory exceeds its bound');for(const name of names){const path=join(active,name),source=await readNativeText(path,{maxBytes:256}),lines=source.split(/\r?\n/u);if(lines.at(-1)==='')lines.pop();if(!lines.length||lines.some(line=>!/^\d{1,10}$/u.test(line)||Number(line)<1||Number(line)>4294967295))throw clientFailure('Claude activity marker is malformed; inspect it before reset');if(lines.some(line=>alive(Number(line))))throw clientFailure('Active Router-launched Claude session prevents reset');if(await readNativeText(path,{maxBytes:256})!==source)throw clientFailure('Claude activity marker changed during reset');await unlink(path);}
9
+ }
10
+ export async function confirmClaudeProcessReset(options,invocation={}){
11
+ if(!options.reset_to_default_configuration||options.yes)return;if(!process.stdin.isTTY||invocation.attachedToTerminal===false)throw clientFailure('Claude profile reset requires --yes for a noninteractive invocation');const input=createInterface({input:process.stdin,output:process.stderr});try{const answer=await input.question('Reset the Router-owned Claude settings and keep a verified backup? [y/N] ',{signal:invocation.signal});if(!['y','yes'].includes(answer.trim().toLowerCase()))throw clientFailure('Claude profile reset cancelled');}finally{input.close();}
12
+ }
13
+ async function resetSettings(profile,backupRoot,checkpoint){
14
+ if(!await exists(profile))return null;const before=await snapshotClientProfile(profile),selected=before.entries.filter((row)=>['settings.json','settings.local.json'].includes(row.path));for(const row of selected){if(row.kind!=='file')throw clientFailure('Claude settings require regular files before reset');JSON.parse(await readNativeText(join(profile,row.path),{maxBytes:8388608}));}
15
+ const backup=await createVerifiedClientProfileBackup(profile,backupRoot);await verifyClientProfileBackup(backup.directory);if(JSON.stringify(await snapshotClientProfile(profile))!==JSON.stringify(before))throw clientFailure('Profile changed after backup; nothing was reset; recovery backup '+backup.id);const moved=[],suffix=randomUUID().replaceAll('-','');
16
+ try{for(const row of selected){const path=join(profile,row.path),staged=join(profile,'.router-reset-'+suffix+'-'+row.path);if(await exists(staged))throw clientFailure('Reset staging path exists');await rename(path,staged);moved.push({path,staged,row});await checkpoint?.('settings-staged',row.path);}}
17
+ catch(error){const failures=[];for(const row of [...moved].reverse()){try{if(await exists(row.path))throw clientFailure('Replacement settings were preserved');if(((await lstat(row.staged)).mode&0o7777)!==row.row.mode||await readNativeText(row.staged,{maxBytes:8388608})!==await readNativeText(join(backup.directory,'data','claude','router','home',row.row.path),{maxBytes:8388608}))throw clientFailure('Staged settings changed; recovery files preserved');await rename(row.staged,row.path);}catch{failures.push(row.path);}}if(failures.length)throw clientFailure('Reset rollback incomplete; recovery backup '+backup.id);throw clientFailure('Reset rolled back; recovery backup '+backup.id);}
18
+ for(const row of moved){const actual=await readNativeText(row.staged,{maxBytes:8388608});if(actual!==await readNativeText(join(backup.directory,'data','claude','router','home',row.row.path),{maxBytes:8388608}))throw clientFailure('Staged settings changed; recovery backup '+backup.id);await unlink(row.staged);}return backup.id;
19
+ }
20
+ export async function withClaudeProcessSession(context,profile,operation){
21
+ const state=dirname(profile),active=join(state,'active'),lock=join(state,'profile-operation.lock'),backupRoot=join(context.configHome,'link-assistant-router','client-backups');await requireNativePath(state);await mkdir(state,{recursive:true,mode:0o700});await chmod(state,0o700);await requireNativePath(lock);let marker='',source='',backup=null;
22
+ const prepare=async()=>withAdvisoryFileLock(lock,async()=>{if(context.reset){await inactive(active);backup=await resetSettings(profile,backupRoot,context.checkpoint);}await requireNativePath(profile);await mkdir(profile,{recursive:true,mode:0o700});await chmod(profile,0o700);await requireNativePath(active);await mkdir(active,{recursive:true,mode:0o700});await chmod(active,0o700);marker=join(active,randomUUID().replaceAll('-','')+'.run');source=String(process.pid)+'\n';await atomicWrite(marker,source);},{timeout:10000});
23
+ if(context.reset){await requireNativePath(backupRoot);await mkdir(backupRoot,{recursive:true,mode:0o700});await withAdvisoryFileLock(join(backupRoot,'.operation.lock'),prepare,{timeout:1000});}else await prepare();
24
+ const commitLaunch=async(pid)=>{if(!Number.isInteger(pid)||pid<1||pid>4294967295)throw clientFailure('Actual child PID required for Claude marker');await withAdvisoryFileLock(lock,async()=>{if(await readNativeText(marker,{maxBytes:256})!==source)throw clientFailure('Claude activity marker changed before launch');const next=String(process.pid)+'\n'+pid+'\n';await atomicWrite(marker,next);source=next;},{timeout:10000});};
25
+ try{return await operation({commitLaunch,backup});}finally{await withAdvisoryFileLock(lock,async()=>{if(await readNativeText(marker,{maxBytes:256})!==source)throw clientFailure('Claude activity marker changed; replacement preserved');await unlink(marker);},{timeout:10000});}
26
+ }
@@ -0,0 +1,21 @@
1
+ /** CLI presentation shared by local and selected-remote operation results. */
2
+ const columns=(values,widths)=>values.map((value,index)=>String(value ?? '').padEnd(widths[index] ?? 0)).join(' ');
3
+ export function tokenTable(records) {
4
+ const widths=[36,10,10,8,13,15,9,8,6,0],rows=[columns(['id','issued_at','expires_at','revoked','requests','tokens','reserved','rpm','scope','label'],widths)];
5
+ for (const record of records) {
6
+ const number=key=>Number.isSafeInteger(record[key]) && record[key]>=0 ? record[key] : null;
7
+ const usage=(used,max)=>`${number(used) ?? 0}/${number(max) ?? '-'}`;
8
+ rows.push(columns([record.id ?? '',number('issued_at') ?? 0,number('expires_at') ?? 0,record.revoked ?? false,usage('used_requests','max_requests'),usage('used_tokens','max_tokens'),number('reserved_tokens') ?? 0,number('rate_limit_per_minute') ?? '-',record.scope || 'client',record.label ?? ''],widths));
9
+ }
10
+ return rows.join('\n');
11
+ }
12
+ export function renderNativeHuman(result) {
13
+ const {operation,data}=result;
14
+ if (Array.isArray(data?.output)) return data.output.join('\n');
15
+ if (!result.success) return '';
16
+ if (operation==='version') return `router ${data.version} (${data.source_commit})`;
17
+ if (['tokens.issue','tokens.rotate'].includes(operation)) return data.token;
18
+ if (operation==='tokens.list') return tokenTable(data);
19
+ if (operation==='clients.list') return [columns(['client','installed','ownership','dialect','config'],[12,9,16,19,0]),...data.map(row=>columns([row.client,row.installed,row.unreadable ? 'unreadable' : row.ownership_state,row.dialect,row.config_path],[12,9,16,19,0]))].join('\n');
20
+ return JSON.stringify(data,null,2);
21
+ }
package/src/cli.mjs ADDED
@@ -0,0 +1,84 @@
1
+ #!/usr/bin/env node
2
+ /** Standalone native CLI: structured contracts, never falls back to Rust. */
3
+ import { pathToFileURL } from 'node:url';
4
+ import {renderNativeHuman} from './cli-output.mjs';
5
+ import { NativeRouter, catalog, operationResult } from './operations.mjs';
6
+
7
+ export function parseNativeArguments(argv) {
8
+ const remaining = [...argv], global = {};
9
+ for (let index = 0; index < remaining.length; index++) {
10
+ if (remaining[index] === '--') break;
11
+ if (remaining[index] === '--json') { global.json = true;remaining.splice(index--, 1); continue; }
12
+ if (remaining[index].startsWith('--config=')) {global.configPath=remaining[index].slice(9);if (!global.configPath) throw new Error('--config requires a file');remaining.splice(index--,1);continue;}
13
+ if (remaining[index] === '--config') {
14
+ if (!remaining[index + 1]) throw new Error('--config requires a file');
15
+ global.configPath = remaining[index + 1]; remaining.splice(index, 2); index--;
16
+ }
17
+ }
18
+ const prefix=[],rootFlags=new Map(catalog.operations.find(operation=>operation.name==='version').options.filter(option=>option.flag).map(option=>[option.flag,option]));
19
+ while (remaining[0]?.startsWith('--')) {
20
+ const arg=remaining.shift(),equal=arg.indexOf('='),flag=arg.slice(2,equal<0 ? undefined : equal),option=rootFlags.get(flag);
21
+ if (!option) throw new Error(`Unknown global flag: --${flag}`);prefix.push(arg);
22
+ if (!option.boolean && equal<0) {
23
+ const value=remaining.shift();if (value===undefined || value.startsWith('--')) throw new Error(`--${flag} requires a value`);prefix.push(value);
24
+ }
25
+ }
26
+ const operation = [...catalog.operations].sort((a, b) => b.command.length - a.command.length)
27
+ .find(operation => operation.command.every((word, index) => remaining[index] === word));
28
+ if (!operation) throw new Error(`Unknown native command: ${remaining.slice(0, 3).join(' ')}`);
29
+ const options = {}, positionals = [], args = [...prefix,...remaining.slice(operation.command.length)];
30
+ const flags = new Map(operation.options.filter(option => option.flag).map(option => [option.flag, option]));
31
+ for (let index = 0; index < args.length; index++) {
32
+ const arg = args[index];
33
+ if (arg === '--') { positionals.push(...args.slice(index + 1)); break; }
34
+ if (!arg.startsWith('--')) { positionals.push(arg); continue; }
35
+ const equal = arg.indexOf('='), flag = arg.slice(2, equal < 0 ? undefined : equal);
36
+ const option = flags.get(flag);
37
+ if (!option) throw new Error(`Unknown ${operation.name} flag: --${flag}`);
38
+ if (option.secret && !(operation.name.startsWith('logs.') && option.name==='token')) throw new Error(`--${flag} is secret; use the catalog environment variable or stdin transport`);
39
+ let value;
40
+ if (option.boolean) {
41
+ if (equal < 0) value = true;
42
+ else if (['true', 'false'].includes(arg.slice(equal + 1))) value = arg.slice(equal + 1) === 'true';
43
+ else throw new Error(`--${flag} requires true or false`);
44
+ } else {
45
+ value = equal < 0 ? args[++index] : arg.slice(equal + 1);
46
+ if (value === undefined || value.startsWith('--')) throw new Error(`--${flag} requires a value`);
47
+ }
48
+ if (!option.multiple && Object.hasOwn(options, option.name)) throw new Error(`Duplicate --${flag}`);
49
+ if (option.multiple) (options[option.name] ??= []).push(value); else options[option.name] = value;
50
+ }
51
+ for (const option of operation.options.filter(option => option.positional)) {
52
+ if (option.multiple) options[option.name] = positionals.splice(0);
53
+ else if (positionals.length) options[option.name] = positionals.shift();
54
+ }
55
+ if (positionals.length) throw new Error(`Unexpected positional arguments for ${operation.name}`);
56
+ return { name: operation.name, options, global };
57
+ }
58
+ export async function runNativeCli(argv, { stdout = process.stdout, stderr = process.stderr, stdin = process.stdin, env = process.env, router } = {}) {
59
+ let result,json=argv.slice(0,argv.indexOf('--')<0 ? argv.length : argv.indexOf('--')).includes('--json');
60
+ try {
61
+ const parsed = parseNativeArguments(argv);
62
+ json=parsed.global.json ?? false;
63
+ router ??= new NativeRouter({ ...parsed.global, env });
64
+ let input = '';
65
+ if (parsed.options.api_key_stdin || parsed.options.token_stdin) {
66
+ for await (const chunk of stdin) {
67
+ input += chunk;
68
+ if (Buffer.byteLength(input) > 1_048_576) throw new Error('stdin exceeds 1 MiB limit');
69
+ }
70
+ }
71
+ result = await router.execute(parsed.name, parsed.options, { stdin: input,...(!json ? {onProgress:line=>stdout.write(line+'\n')} : {}) });
72
+ } catch (error) {
73
+ result = operationResult('cli-error', { output: [] }, [error.message], 2);
74
+ }
75
+ if (json) stdout.write(JSON.stringify(result)+'\n');
76
+ else {
77
+ const output=renderNativeHuman(result);if (output) stdout.write(output+'\n');
78
+ for (const diagnostic of result.diagnostics) stderr.write(`error: ${diagnostic}\n`);
79
+ }
80
+ return result.exit_code;
81
+ }
82
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
83
+ process.exitCode = await runNativeCli(process.argv.slice(2));
84
+ }
@@ -0,0 +1,8 @@
1
+ /** Fresh bounded selected-CA loading; normal chain/hostname verification remains enabled. */
2
+ import {X509Certificate} from 'node:crypto';import {rootCertificates} from 'node:tls';import {resolve} from 'node:path';
3
+ import {readNativeText} from './operation-input.mjs';import {clientFailure} from './client-files.mjs';
4
+ export async function readClientRouterCA(path,cwd=process.cwd()){
5
+ if(typeof path!=='string'||!path||path.includes('\0'))throw clientFailure('Selected Router CA requires a nonempty path');const filename=resolve(cwd,path),pem=await readNativeText(filename,{maxBytes:1048576}),blocks=pem.match(/-----BEGIN CERTIFICATE-----[\s\S]*?-----END CERTIFICATE-----/gu);
6
+ if(!blocks?.length||blocks.length>256)throw clientFailure('Selected Router CA requires a bounded certificate bundle');try{for(const block of blocks)new X509Certificate(block);}catch{throw clientFailure('Selected Router CA contains an invalid certificate');}
7
+ return {path:filename,ca:[...rootCertificates,pem]};
8
+ }
@@ -0,0 +1,52 @@
1
+ /** Exact live model identities and owner selection shared by setup, launch and doctor. */
2
+ import {clientIntegration,clientFailure} from './client-files.mjs';
3
+ const originSuffixes=['/api/services/anthropic','/api/services/openai/v1','/api/services/codex/v1','/api/services/qwen/v1','/api/services/gemini','/api/gemini','/api/qwen/v1','/api/codex/v1','/v1'];
4
+ export function clientRouterOrigin(baseURL) {
5
+ let url;try {url=new URL(String(baseURL).trim().replace(/\/+$/,''));}catch{throw clientFailure('Invalid Router base URL');}
6
+ if(!['http:','https:'].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw clientFailure('Router base URL requires HTTP(S) without embedded credentials, query or fragment');
7
+ const suffix=originSuffixes.find(suffix=>url.pathname.endsWith(suffix));if(suffix) url.pathname=url.pathname.slice(0,-suffix.length) || '/';
8
+ return url.href.replace(/\/+$/,'');
9
+ }
10
+ const optional=(row,key,predicate)=>{if(row[key]!==null && row[key]!==undefined && !predicate(row[key])) throw clientFailure(`Router model catalog row has invalid ${key}`);};
11
+ export function parseNativeClientCatalog(data) {
12
+ if(!Array.isArray(data)) throw clientFailure('Router model catalog data must be an array');
13
+ const rows=data.map((value,index)=>{
14
+ if(!value || typeof value!=='object' || Array.isArray(value) || typeof value.id!=='string') throw clientFailure(`Router model catalog row ${index} does not match this Router version`);
15
+ const row={...value};
16
+ if(row.owned_by!==undefined && typeof row.owned_by!=='string') throw clientFailure('Router model catalog row has invalid owned_by');optional(row,'default_reasoning_level',value=>typeof value==='string');
17
+ optional(row,'router_unavailable_reason',value=>typeof value==='string');optional(row,'provider_created_at',Number.isSafeInteger);
18
+ optional(row,'selector_kind',value=>typeof value==='string');
19
+ optional(row,'supported_reasoning_levels',value=>Array.isArray(value) && value.every(level=>level && typeof level==='object' && typeof level.effort==='string' && (level.description===undefined || typeof level.description==='string')));
20
+ if(row.client_capabilities===null) throw clientFailure('Router model catalog row has invalid client_capabilities');
21
+ optional(row,'client_capabilities',value=>value && typeof value==='object' && !Array.isArray(value) && (value.claude==null || typeof value.claude==='object' && typeof value.claude.behaves_as==='string' && typeof value.claude.source==='string'));
22
+ const selectors={concrete:'concrete',provider_advertised_exact_id:'concrete',provider_dynamic_alias:'provider_dynamic_alias',provider_advertised_alias:'provider_dynamic_alias',operator_alias:'operator_alias'};
23
+ row.owned_by ??='';row.selector_kind=Object.hasOwn(selectors,row.selector_kind) ? selectors[row.selector_kind] : 'unknown';return row;
24
+ }).filter(row=>row.id.trim().length>0).sort((a,b)=>a.id<b.id ? -1 : a.id>b.id ? 1 : a.owned_by<b.owned_by ? -1 : a.owned_by>b.owned_by ? 1 : 0);
25
+ const unique=rows.filter((row,index)=>index===0 || row.id!==rows[index-1].id || row.owned_by!==rows[index-1].owned_by);
26
+ if(!unique.length) throw clientFailure('Router catalog contains no models from healthy subscriptions');return unique;
27
+ }
28
+ export async function fetchNativeClientCatalog(client,baseURL,token,{fetch:fetcher=globalThis.fetch,signal,timeoutMs=15000,maxBytes=4*1024*1024}={}) {
29
+ const info=clientIntegration(client),url=clientRouterOrigin(baseURL)+'/api/models',controller=new AbortController();
30
+ const abort=()=>controller.abort();if(signal?.aborted) throw clientFailure('Client catalog operation cancelled');signal?.addEventListener('abort',abort,{once:true});
31
+ let timer;const deadline=new Promise((_,reject)=>{timer=setTimeout(()=>{controller.abort();reject(clientFailure('Client catalog deadline exceeded'));},timeoutMs);});
32
+ const cancelled=new Promise((_,reject)=>controller.signal.addEventListener('abort',()=>reject(clientFailure('Client catalog operation cancelled')),{once:true}));
33
+ const bounded=promise=>Promise.race([promise,deadline,cancelled]);let reader;
34
+ try {
35
+ const response=await bounded(Promise.resolve().then(()=>fetcher(url,{headers:{'x-link-assistant-client':info.client,...(info.client==='gemini' ? {'x-goog-api-key':token} : {authorization:`Bearer ${token}`})},redirect:'error',signal:controller.signal})));
36
+ if(!response.ok || response.url && new URL(response.url).origin!==new URL(url).origin) throw clientFailure(`Client catalog request failed (${response.status})`);
37
+ const declared=response.headers.get('content-length');if(declared!==null && Number(declared)>maxBytes) throw clientFailure('Client catalog exceeds its byte budget');
38
+ reader=response.body?.getReader();const chunks=[];let total=0;
39
+ if(reader) for(;;) {const {done,value}=await bounded(reader.read());if(done) break;total+=value.byteLength;if(total>maxBytes) throw clientFailure('Client catalog exceeds its byte budget');chunks.push(Buffer.from(value));}
40
+ let parsed;try{parsed=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(Buffer.concat(chunks,total)));}catch{throw clientFailure('Router returned an invalid model catalog');}
41
+ return parseNativeClientCatalog(parsed.data);
42
+ } finally {clearTimeout(timer);signal?.removeEventListener('abort',abort);void reader?.cancel().catch(()=>{});}
43
+ }
44
+ export function nativeClientModelAuthorized(client,catalog,requested) {
45
+ const info=clientIntegration(client);
46
+ if(info.client==='claude' && requested.endsWith('[1m]')) return catalog.some(row=>row.id===requested.slice(0,-4) && row.owned_by==='anthropic');
47
+ return catalog.some(row=>row.id===requested);
48
+ }
49
+ export function selectNativeClientModel(client,catalog) {
50
+ const info=clientIntegration(client);for(const owner of info.owners) {const row=catalog.find(row=>row.owned_by===owner);if(row) return row.id;}
51
+ return info.strict && catalog.some(row=>row.owned_by!=='') ? null : catalog[0]?.id ?? null;
52
+ }
@@ -0,0 +1,18 @@
1
+ /** Validate foreign Codex catalogue constraints before exact managed takeover. */
2
+ import {open,lstat} from 'node:fs/promises';
3
+ import {constants} from 'node:fs';
4
+ import {resolve} from 'node:path';
5
+ import {optionalClientText,clientFailure} from './client-files.mjs';
6
+ import {requireNativePath} from './operation-input.mjs';
7
+ import {atomicWrite} from './storage.mjs';
8
+ import {parseClientTomlSource,editClientTomlSource} from './client-toml-cst.mjs';
9
+ async function catalogue(path){
10
+ await requireNativePath(path);const before=await lstat(path);if(!before.isFile()||before.isSymbolicLink())throw clientFailure('Codex model_catalog_json requires a regular nonsymlink file');const file=await open(path,constants.O_RDONLY|(constants.O_NOFOLLOW??0)|(constants.O_NONBLOCK??0)),limit=8*1024*1024;
11
+ try{const stat=await file.stat();if(!stat.isFile()||stat.size>limit)throw clientFailure('Codex model_catalog_json exceeds its regular file bound');const chunks=[];let bytes=0;for(;;){const buffer=Buffer.alloc(Math.min(65536,limit-bytes+1)),part=await file.read(buffer,0,buffer.length,null);if(!part.bytesRead)break;bytes+=part.bytesRead;if(bytes>limit)throw clientFailure('Codex model_catalog_json exceeds its byte bound');chunks.push(buffer.subarray(0,part.bytesRead));}const source=new TextDecoder('utf8',{fatal:true,ignoreBOM:true}).decode(Buffer.concat(chunks,bytes));let data;try{data=JSON.parse(source);}catch{throw clientFailure('Codex model_catalog_json is not valid JSON');}if(!data||!Array.isArray(data.models))throw clientFailure('Codex model_catalog_json must contain a models array');return source;}finally{await file.close();}
12
+ }
13
+ export async function inspectCodexCatalogConstraint(paths,{cwd=process.cwd()}={}){
14
+ if(paths.info.client!=='codex')return null;const source=await optionalClientText(paths.config);if(source===null||!source.trim())return null;const document=parseClientTomlSource(source);if(!Object.hasOwn(document,'model_catalog_json'))return null;const value=document.model_catalog_json;if(typeof value!=='string'||!value)throw clientFailure('Codex model_catalog_json must be a file path string');const path=resolve(cwd,value),catalogSource=await catalogue(path);return {source,path,catalogSource,sourceAuthority:false,semanticAuthority:false};
15
+ }
16
+ export async function removeCodexCatalogConstraint(paths,txn,{cwd=process.cwd(),expected=null}={}){
17
+ const current=await inspectCodexCatalogConstraint(paths,{cwd});if(expected&&(current===null||current.source!==expected.source||current.path!==expected.path||current.catalogSource!==expected.catalogSource))throw clientFailure('Codex catalogue constraint changed before managed mutation');if(current===null)return {changed:false,sourceAuthority:false,semanticAuthority:false};await txn.verify(paths.config);const plan=editClientTomlSource(current.source,[{path:['model_catalog_json'],action:'delete'}]);if(await optionalClientText(paths.config)!==current.source||await catalogue(current.path)!==current.catalogSource)throw clientFailure('Codex catalogue constraint changed during source preparation');await atomicWrite(paths.config,plan.after);await txn.advance([paths.config]);return {changed:true,source:plan.before,after:plan.after,inverse:plan.inverse,stages:plan.stages,sourceAuthority:false,semanticAuthority:false};
18
+ }
@@ -0,0 +1,72 @@
1
+ /** Shared configure and legacy with --global workflow; all selection remains explicit. */
2
+ import {clientIntegrations,clientIntegration,clientPaths,clientFailure,clientObject,optionalClientText,preferredClientPath,readClientEnvironment,writeClientEnvironment,writeClientMarker,removeClientFile} from './client-files.mjs';
3
+ import {nativeClientStatus} from './client-status.mjs';
4
+ import {selectedManagedTarget,withNativeManagedConfigureTarget} from './managed-server.mjs';
5
+ import {prepareRemoteClientCredential,reuseRemoteClientCredential,revokeRemoteClientCredential} from './client-remote.mjs';
6
+ import {globalClientDigest,readGlobalClientState} from './client-global-state.mjs';
7
+ import {applyGlobalClientConfiguration,undoGlobalClientConfiguration} from './client-global.mjs';
8
+ async function withSelectedConfigureTarget(options,core,env,invocation,fetch,operation,retainOnSuccess=true){
9
+ if(options.managed&&(options.local||options.server||options.management_server))throw clientFailure('--managed conflicts with --local or explicit server origins');
10
+ if(!options.managed){const explicit=await selectedManagedTarget({name:'configure',options,config:core.config,env,cwd:invocation.cwd});if(explicit)return operation(explicit);}
11
+ const context={options,config:core.config,env,cwd:invocation.cwd,retainOnSuccess},known=await withNativeManagedConfigureTarget(context,operation);if(known!==null)return known;
12
+ if(!options.managed){const discovered=await discoverLocalRouter({env,invocation,fetch});if(discovered)return operation(discovered);if(invocation.signal?.aborted)throw clientFailure('Local Router discovery was cancelled');if(options.local)throw clientFailure('--local requires an already-running local Router');}
13
+ return withNativeManagedConfigureTarget({...context,create:true},operation);
14
+ }
15
+ async function undoOne(paths,context,output){
16
+ let hadCredential=false;const result=await undoGlobalClientConfiguration(paths,{checkpoint:context.checkpoint,afterRestore:async(txn)=>{
17
+ await txn.verify(txn.environment);await txn.verify(txn.metadata);const source=await optionalClientText(txn.metadata),record=source===null?null:clientObject(source,'Ownership metadata');hadCredential=await optionalClientText(txn.environment)!==null;
18
+ if(record&&record.client!==paths.info.client&&record.client!==paths.info.legacy)throw clientFailure('Undo credential belongs to another client');
19
+ if(record?.source==='minted'&&typeof record.token_id==='string'&&typeof record.router==='string'){
20
+ try{await revokeRemoteClientCredential({...record,management_server:record.management_server??record.router},{config:context.core.config,env:context.env,invocation:context.invocation,fetch:context.fetch,suppliedToken:context.options.token});output.push('revoked token '+record.token_id+' on '+record.router);}catch{output.push('note: token '+record.token_id+' on '+record.router+' may remain live; revoke it on its issuing Router');}
21
+ }
22
+ await removeClientFile(txn.environment);await txn.advance([txn.environment]);await removeClientFile(txn.metadata);await txn.advance([txn.metadata]);await txn.checkpoint('metadata');
23
+ }});await stopCodexNativeBridge(paths);if(result.restored)output.push('restored '+paths.config+' exactly');else if(hadCredential)output.push('removed the stored credential for '+paths.info.client);return result.restored||hadCredential;
24
+ }
25
+ async function configureOne(paths,target,context,output,backendBaseURL=null){
26
+ const {options,core,env,invocation,fetch}=context,source=await optionalClientText(await preferredClientPath(paths.metadata,paths.legacyMetadata)),record=source===null?null:clientObject(source,'Ownership metadata'),environment=await preferredClientPath(paths.environment,paths.legacyEnvironment),token=readClientEnvironment(await optionalClientText(environment),paths.info.token),status=await nativeClientStatus(paths.info.client,{home:options.home,env,cwd:invocation.cwd}),saved=await readGlobalClientState(paths),remote={client:paths.info.client,origin:target.server,managementServer:target.managementServer,config:core.config,env,invocation,fetch};
27
+ if(status.ownership_state==='managed-intact'&&(saved!==null||paths.info.client==='grok')&&token&&await codexNativeBackendMatches(paths,target.server,backendBaseURL)&&await reuseRemoteClientCredential(remote,record,token)){output.push(paths.info.client+' is already configured in '+paths.config);return;}
28
+ if(saved!==null){
29
+ if(!record||!token||record.client!==paths.info.client||record.router!==target.server||record.management_server!==target.managementServer||!['minted','supplied'].includes(record.source))throw clientFailure('Existing global credentials require exact undo before changing Router');const actual=await authenticateRemoteClientCredential(remote,token);if(record.token_id!==actual.binding.token_id||record.principal_id!==actual.binding.principal_id)throw clientFailure('Global credential metadata does not match its authenticated token');
30
+ const repaired=await repairGlobalClientConfiguration(paths,target.server+paths.info.suffix,actual.catalog,{backendBaseURL,cwd:invocation.cwd,checkpoint:context.checkpoint,afterConfigure:async(txn)=>{await txn.verify(txn.environment);await writeClientEnvironment(paths,target.server,token);await txn.advance([txn.environment]);await txn.checkpoint('environment');await txn.verify(txn.metadata);record.config_sha256=globalClientDigest(await optionalClientText(paths.config));await writeClientMarker(txn.metadata,record);await txn.advance([txn.metadata]);await txn.checkpoint('metadata');if(!await reuseRemoteClientCredential(remote,record,token))throw clientFailure('Post-repair catalog authentication failed');}});output.push('repaired '+paths.info.client+' in '+paths.config);if(repaired.backup)output.push('backup: '+repaired.backup);return;
31
+ }
32
+ const supplied=options.token_stdin?String(invocation.stdin??'').trim():options.token??target.token,candidate=await prepareRemoteClientCredential({...remote,suppliedToken:supplied,ttlHours:options.ttl_hours??8760,nowUnix:core.clock()});
33
+ try{await applyGlobalClientConfiguration(paths,target.server+paths.info.suffix,candidate.catalog,{backendBaseURL,cwd:invocation.cwd,checkpoint:context.checkpoint,afterConfigure:async(txn)=>{
34
+ await txn.verify(txn.environment);await writeClientEnvironment(paths,target.server,candidate.token);await txn.advance([txn.environment]);await txn.checkpoint('environment');await txn.verify(txn.metadata);candidate.record.config_sha256=globalClientDigest(await optionalClientText(paths.config));await writeClientMarker(txn.metadata,candidate.record);await txn.advance([txn.metadata]);await txn.checkpoint('metadata');if(!await reuseRemoteClientCredential(remote,candidate.record,candidate.token))throw clientFailure('Post-configuration catalog authentication failed');
35
+ }});}catch(error){try{await candidate.cleanup();}catch{throw clientFailure('Global configuration failed; its unused minted credential could not be revoked');}throw error;}
36
+ output.push('configured '+paths.info.client+' in '+paths.config,'credentials: '+environment+' (mode 0600)','undo: router configure --undo '+paths.info.client);
37
+ }
38
+ async function executeNativeConfigureAtTarget({name='configure',options={},invocation={},core,env={},fetch=globalThis.fetch,checkpoint,target}={}){
39
+ if(name==='with'&&!options.global&&!options.undo)throw clientFailure('Temporary client launch requires the remaining process/isolation lifecycle');if(!options.all&&!options.client)throw clientFailure('Configure requires a client or --all');if(options.all&&options.client)throw clientFailure('--all conflicts with a single client');
40
+ const output=[],failures=[],clients=options.all?clientIntegrations:[clientIntegration(options.client)],context={options:{...options,ttl_hours:name==='with'?8760:options.ttl_hours},invocation,core,env,fetch,checkpoint};let completed=0;
41
+ for(const info of clients){
42
+ if(info.unsupported){if(options.undo&&!options.all)throw clientFailure(info.unsupported);output.push('skipped '+info.client+': '+info.unsupported);continue;}
43
+ const paths=clientPaths(info.client,{home:options.home,env,cwd:invocation.cwd});try{
44
+ if(!options.undo&&options.all&&!(await nativeClientStatus(info.client,{home:options.home,env,cwd:invocation.cwd})).installed){output.push('skipped '+info.client+': not installed');continue;}
45
+ if(options.undo){const changed=await undoOne(paths,context,output);if(!changed&&!options.all)throw clientFailure('No saved global configuration or credential exists for '+info.client);if(changed)completed++;}
46
+ else{await inspectCodexCatalogConstraint(paths,{cwd:invocation.cwd});await withCodexNativeBridge(paths,target.server,backend=>configureOne(paths,target,context,output,backend),{caCert:target.caCert,config:core.config,env,cwd:invocation.cwd});completed++;target.retainManagedServer?.();}
47
+ }catch(error){if(!options.all)throw error;failures.push(info.client+': '+Object(error).message);}
48
+ }
49
+ if(options.all)output.push((options.undo?'restored ':'configured ')+completed+' client(s)');if(failures.length){const error=clientFailure('One or more client configurations failed');error.data={output:[...output,...failures.map(text=>'error: '+text)]};throw error;}return {output};
50
+ }
51
+
52
+ import {withCodexNativeBridge,stopCodexNativeBridge,codexNativeBackendMatches} from './codex-loopback.mjs';
53
+
54
+ import {authenticateRemoteClientCredential} from './client-remote.mjs';
55
+ import {repairGlobalClientConfiguration} from './client-global-repair.mjs';
56
+
57
+ import {inspectCodexCatalogConstraint} from './client-codex-catalog.mjs';
58
+
59
+ export async function executeNativeConfigure(context={}){
60
+ const {options={},core,env={},invocation={},fetch=globalThis.fetch}=context;
61
+ if(context.name==='with'&&!options.global&&!options.undo)return (await import('./client-launch.mjs')).executeNativeWith(context);
62
+ if(!options.all&&!options.client)throw clientFailure('Configure requires a client or --all');if(options.all&&options.client)throw clientFailure('--all conflicts with a single client');
63
+ if(!options.all)clientIntegration(options.client);
64
+ if(options.undo)return executeNativeConfigureAtTarget(context);
65
+ return withSelectedConfigureTarget(options,core,env,invocation,fetch,target=>executeNativeConfigureAtTarget({...context,target}));
66
+ }
67
+
68
+ import {discoverLocalRouter} from './local-router-discovery.mjs';
69
+
70
+ import {preflightNativeClientLaunch} from './client-launch-plan.mjs';
71
+
72
+ export async function withSelectedNativeClientTarget(context,operation){return withSelectedConfigureTarget(context.options??{},context.core,context.env??{},context.invocation??{},context.fetch??globalThis.fetch,operation,context.retainOnSuccess!==false);}
@@ -0,0 +1,82 @@
1
+ /** Bounded, owner-private client files; no shell or client executable is invoked. */
2
+ import {stat,unlink} from 'node:fs/promises';
3
+ import {join,isAbsolute,resolve,delimiter} from 'node:path';
4
+ import {randomUUID} from 'node:crypto';
5
+ import {isDeepStrictEqual} from 'node:util';
6
+ import {readNativeText,requireNativePath} from './operation-input.mjs';
7
+ import {atomicWrite} from './storage.mjs';
8
+
9
+ export const clientFailure=message=>Object.assign(new Error(message),{code:'client',exitCode:1});
10
+ export const clientIntegrations=Object.freeze([
11
+ {client:'codex',legacy:'codex',dialect:'OpenAI Responses',token:'LINK_ASSISTANT_TOKEN',base:null,suffix:'/api/services/codex/v1',owners:['openai','z.ai'],strict:true},
12
+ {client:'claude',legacy:'claude-code',dialect:'Anthropic Messages',token:'ANTHROPIC_AUTH_TOKEN',base:'ANTHROPIC_BASE_URL',suffix:'/api/services/anthropic',owners:['anthropic','z.ai'],strict:true},
13
+ {client:'cursor-agent',legacy:'cursor',dialect:'Cursor private',token:null,base:null,suffix:'',owners:[],strict:false,unsupported:'Cursor uses a private ConnectRPC API and has no supported Router setup'},
14
+ {client:'gemini',legacy:'gemini-cli',dialect:'Gemini native',token:'GEMINI_API_KEY',base:'GOOGLE_GEMINI_BASE_URL',suffix:'/api/services/gemini',owners:['google'],strict:false,unsupported:'Individual Gemini subscriptions are CodeAssistIneligibleTierError; use an isolated Gemini API-key launch'},
15
+ {client:'grok',legacy:'grok-cli',dialect:'OpenAI Chat',token:'GROK_API_KEY',base:'GROK_BASE_URL',suffix:'/api/services/openai/v1',owners:[],strict:false},
16
+ {client:'opencode',legacy:'opencode',dialect:'OpenAI Chat',token:'LINK_ASSISTANT_TOKEN',base:null,suffix:'/api/services/openai/v1',owners:[],strict:false},
17
+ {client:'qwen',legacy:'qwen-code',dialect:'OpenAI Chat',token:'LINK_ASSISTANT_TOKEN',base:'OPENAI_BASE_URL',suffix:'/api/services/qwen/v1',owners:['qwen'],strict:false},
18
+ {client:'agent',legacy:'agent',dialect:'OpenAI Chat',token:'LINK_ASSISTANT_TOKEN',base:null,suffix:'/api/services/openai/v1',owners:[],strict:false},
19
+ ]);
20
+ export function clientIntegration(name) {
21
+ const found=clientIntegrations.find(client=>client.client===name || client.legacy===name);
22
+ if (!found) throw clientFailure('Unknown client');return found;
23
+ }
24
+ const absolute=(path,label)=>{if (typeof path!=='string' || !path.trim() || !isAbsolute(path)) throw clientFailure(`${label} requires an absolute nonempty directory`);return resolve(path);};
25
+ export function clientPaths(name,{home,env=process.env,cwd=process.cwd()}={}) {
26
+ const info=clientIntegration(name),root=home!==undefined ? resolve(cwd,home) : absolute(env.HOME,'HOME');
27
+ const directory=(key,fallback)=>home!==undefined || !env[key] ? fallback : resolve(cwd,env[key]);
28
+ const configHome=directory('XDG_CONFIG_HOME',join(root,'.config'));
29
+ const roots={codex:directory('CODEX_HOME',join(root,'.codex')),claude:directory('CLAUDE_CONFIG_DIR',join(root,'.claude')),
30
+ 'cursor-agent':directory('CURSOR_CONFIG_DIR',join(root,'.cursor')),gemini:join(directory('GEMINI_CLI_HOME',root),'.gemini'),grok:join(root,'.grok'),
31
+ opencode:join(configHome,'opencode'),qwen:home===undefined && env.QWEN_HOME?.startsWith('~/') ? join(root,env.QWEN_HOME.slice(2)) : directory('QWEN_HOME',join(root,'.qwen')),agent:join(configHome,'link-assistant-agent')};
32
+ const filenames={codex:'config.toml',claude:'settings.json','cursor-agent':'cli-config.json',gemini:'settings.json',grok:'user-settings.json',opencode:'opencode.json',qwen:'settings.json',agent:'opencode.json'};
33
+ const owned=join(configHome,'link-assistant-router','clients');
34
+ return {info,home:root,configHome,config:join(roots[info.client],filenames[info.client]),environment:join(owned,`${info.client}.env`),metadata:join(owned,`${info.client}.credential.json`),
35
+ legacyEnvironment:join(owned,`${info.legacy}.env`),legacyMetadata:join(owned,`${info.legacy}.credential.json`),
36
+ marker:['codex','claude','opencode','qwen','agent'].includes(info.client) ? join(roots[info.client],'.link-assistant-router-client.json') : null};
37
+ }
38
+ export async function optionalClientText(path) {
39
+ if (!path) return null;
40
+ try {return await readNativeText(path,{maxBytes:8*1024*1024});}catch(error) {if (error.code==='ENOENT') return null;throw clientFailure(`Could not read client configuration (${error.code ?? 'invalid file'})`);}
41
+ }
42
+ export async function preferredClientPath(canonical,legacy) {return await optionalClientText(canonical)!==null || await optionalClientText(legacy)===null ? canonical : legacy;}
43
+ export function clientObject(source,label='Client configuration') {
44
+ if (source===null || !source.trim()) return {};
45
+ let value;try {value=JSON.parse(source);}catch {throw clientFailure(`${label} contains invalid JSON`);}
46
+ if (!value || typeof value!=='object' || Array.isArray(value)) throw clientFailure(`${label} must contain a JSON object`);return value;
47
+ }
48
+ export function objectProperty(document,key) {
49
+ if (!Object.hasOwn(document,key)) document[key]={};
50
+ const value=document[key];if (!value || typeof value!=='object' || Array.isArray(value)) throw clientFailure(`${key} must be a JSON object`);return value;
51
+ }
52
+ export const renderClientJSON=value=>JSON.stringify(value,null,2)+'\n';
53
+ export async function writeClientFile(path,source,contents) {
54
+ if (source===contents) return {path,backup:null,changed:false};
55
+ await requireNativePath(path);
56
+ let backup=null;if (source!==null) {backup=`${path}.link-assistant-router.${Date.now()*1000000}.${randomUUID().replaceAll('-','')}.bak`;await atomicWrite(backup,source);}
57
+ await atomicWrite(path,contents);return {path,backup,changed:true};
58
+ }
59
+ export async function writeClientMarker(path,document) {await requireNativePath(path);await atomicWrite(path,renderClientJSON(document));}
60
+ export async function removeClientFile(path) {await requireNativePath(path);try {await unlink(path);}catch(error) {if(error.code!=='ENOENT') throw error;}}
61
+ export function readClientEnvironment(source,key) {
62
+ const prefix=`export ${key}=`;const line=source?.split(/\r?\n/).find(line=>line.startsWith(prefix));if (line===undefined) return null;
63
+ const raw=line.slice(prefix.length).trim();return raw.startsWith("'") && raw.endsWith("'") ? raw.slice(1,-1).replaceAll("'\\''","'") : raw;
64
+ }
65
+ export const shellQuote=value=>"'"+String(value).replaceAll("'","'\\''")+"'";
66
+ export async function writeClientEnvironment(paths,origin,token) {
67
+ if (!paths.info.token) throw clientFailure('Client has no Router token environment');
68
+ const {info}=paths,lines=[];if(info.base) lines.push(`export ${info.base}=${shellQuote(origin+info.suffix)}`);
69
+ lines.push(`export ${info.token}=${shellQuote(token)}`);
70
+ if (info.client==='codex') {
71
+ if (!token.startsWith('la_sk_')) throw clientFailure('Codex requires a Router-issued la_sk_ token');
72
+ const alias='at-'+token.slice(6);lines.push(`export CODEX_ACCESS_TOKEN=${shellQuote(alias)}`,`export CODEX_CONNECTORS_TOKEN=${shellQuote(alias)}`,`export CODEX_AUTHAPI_BASE_URL=${shellQuote(origin+'/api/services/codex')}`);
73
+ }
74
+ if(info.client==='claude') lines.push('export CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1');
75
+ const path=await preferredClientPath(paths.environment,paths.legacyEnvironment);await requireNativePath(path);await atomicWrite(path,lines.join('\n')+'\n');return path;
76
+ }
77
+ export async function clientCommandExists(command,env=process.env) {
78
+ for(const directory of String(env.PATH ?? '').split(delimiter).filter(Boolean)) {
79
+ try {if((await stat(join(directory,command))).isFile()) return true;}catch{}
80
+ }return false;
81
+ }
82
+ export const sameClientValue=isDeepStrictEqual;
@@ -0,0 +1,19 @@
1
+ /** Advance only intact global config guards while preserving the first exact backup. */
2
+ import {clientFailure,optionalClientText,removeClientFile} from './client-files.mjs';
3
+ import {atomicWrite,encodeLino} from './storage.mjs';
4
+ import {clientFileTransaction} from './client-transaction.mjs';
5
+ import {setupClientJSON} from './client-json.mjs';
6
+ import {setupPersistentClient} from './client-persistent.mjs';
7
+ import {globalClientDigest,readGlobalClientState} from './client-global-state.mjs';
8
+ export async function repairGlobalClientConfiguration(paths,endpoint,catalog,options={}){
9
+ const constraint=await inspectCodexCatalogConstraint(paths,{cwd:options.cwd});let setupBackup=null,beforeConfig=null;
10
+ try{return await clientFileTransaction(paths,async(txn)=>{
11
+ const saved=await readGlobalClientState(paths);if(saved===null)throw clientFailure('Global repair requires its original undo state');for(const path of [paths.config,...(paths.marker?[paths.marker]:[]),saved.files.config,saved.files.marker,saved.files.state])await txn.verify(path);
12
+ beforeConfig=await optionalClientText(paths.config);const beforeMarker=await optionalClientText(paths.marker);if(globalClientDigest(beforeConfig)!==saved.state.config_hash_after_setup||paths.marker&&(saved.state.marker_hash_after_setup===null?beforeMarker!==null:globalClientDigest(beforeMarker)!==saved.state.marker_hash_after_setup))throw clientFailure('Global config or marker was edited; exact undo guards were preserved');
13
+ if(constraint)await removeCodexCatalogConstraint(paths,txn,{cwd:options.cwd,expected:constraint});beforeConfig=await optionalClientText(paths.config);
14
+ const codec=['claude','codex'].includes(paths.info.client)?setupPersistentClient:setupClientJSON,result=await codec(paths,endpoint,catalog,{backendBaseURL:options.backendBaseURL,model:options.model,onWrite:async(path,write)=>{if(write?.backup)setupBackup=write.backup;await txn.advance([path]);}}),marker=await optionalClientText(paths.marker),state={...saved.state,config_hash_after_setup:globalClientDigest(await optionalClientText(paths.config)),marker_hash_after_setup:marker===null?null:globalClientDigest(marker)};
15
+ await txn.verify(saved.files.state);await atomicWrite(saved.files.state,encodeLino(state)+'\n');await txn.advance([saved.files.state]);await txn.checkpoint('config');await options.afterConfigure?.(txn);return result;
16
+ },{checkpoint:options.checkpoint});}catch(error){if(setupBackup&&await optionalClientText(setupBackup)===beforeConfig)await removeClientFile(setupBackup);throw error;}
17
+ }
18
+
19
+ import {inspectCodexCatalogConstraint,removeCodexCatalogConstraint} from './client-codex-catalog.mjs';