@link-assistant/router 0.0.0-stage → 1.25.6

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 (159) hide show
  1. package/README.md +35 -2
  2. package/catalog.json +68422 -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 +61 -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/sensitive-data-sse.mjs +121 -0
  149. package/src/sensitive-data.mjs +254 -0
  150. package/src/server.mjs +552 -0
  151. package/src/storage.mjs +367 -0
  152. package/src/streams.mjs +232 -0
  153. package/src/token-import.mjs +68 -0
  154. package/src/token-reservation.mjs +8 -0
  155. package/src/tokens.mjs +172 -0
  156. package/src/usage.mjs +54 -0
  157. package/src/websocket-relay.mjs +131 -0
  158. package/testing.d.ts +7 -0
  159. package/testing.js +57 -0
@@ -0,0 +1,19 @@
1
+ /** Native-compatible reversible config state; all file destinations are derived. */
2
+ import {createHash} from 'node:crypto';
3
+ import {optionalClientText,clientFailure} from './client-files.mjs';
4
+ import {decodeLino} from './storage.mjs';
5
+ export const globalClientDigest=(source)=>createHash('sha256').update(source??'').digest('hex');
6
+ export function globalClientPaths(paths){return {config:paths.config+'.with-router.bak',marker:paths.config+'.with-router-marker.bak',state:paths.config+'.with-router-state.json'};}
7
+ export async function readGlobalClientState(paths){
8
+ const files=globalClientPaths(paths),source=await optionalClientText(files.state);if(source===null)return null;let state;
9
+ try{state=source.trimStart().startsWith('{')?JSON.parse(source):decodeLino(source);}catch{throw clientFailure('Global undo state is malformed');}
10
+ const fields=['config_existed','config_mode','config_hash_after_setup','marker_existed','marker_mode','marker_hash_after_setup','marker_path','setup_backup'];
11
+ if(!state||typeof state!=='object'||Array.isArray(state)||Object.keys(state).some(key=>!fields.includes(key))||typeof state.config_existed!=='boolean'||typeof state.marker_existed!=='boolean'||typeof state.config_hash_after_setup!=='string'||!/^[a-f0-9]{64}$/u.test(state.config_hash_after_setup))throw clientFailure('Global undo state fields are invalid');
12
+ for(const key of ['config_mode','marker_mode'])if(state[key]!==undefined&&state[key]!==null&&(!Number.isSafeInteger(state[key])||state[key]<0||state[key]>4294967295))throw clientFailure('Global undo file mode is invalid');
13
+ if(state.marker_path!==null&&state.marker_path!==paths.marker||state.marker_existed&&state.marker_path===null||state.marker_hash_after_setup!=null&&(typeof state.marker_hash_after_setup!=='string'||!/^[a-f0-9]{64}$/u.test(state.marker_hash_after_setup)))throw clientFailure('Global undo marker does not match this client');
14
+ if(state.setup_backup!=null){const prefix=paths.config+'.link-assistant-router.';if(typeof state.setup_backup!=='string'||!state.setup_backup.startsWith(prefix)||!/^\d+\.[a-f0-9]{32}\.bak$/u.test(state.setup_backup.slice(prefix.length)))throw clientFailure('Global undo backup is outside its owned filename namespace');}
15
+ return {source,state:{...state,config_mode:state.config_mode??null,marker_mode:state.marker_mode??null,marker_hash_after_setup:state.marker_hash_after_setup??null,setup_backup:state.setup_backup??null},files};
16
+ }
17
+ export async function globalClientTransactionFiles(paths){
18
+ const files=globalClientPaths(paths),saved=await readGlobalClientState(paths);return [files.config,files.marker,files.state,...(saved?.state.setup_backup?[saved.state.setup_backup]:[])];
19
+ }
@@ -0,0 +1,43 @@
1
+ /** Exact native global configuration inverses under the existing private transaction. */
2
+ import {open,lstat,mkdir,chmod} from 'node:fs/promises';
3
+ import {dirname} from 'node:path';
4
+ import {clientFailure,optionalClientText,removeClientFile} from './client-files.mjs';
5
+ import {atomicWrite,encodeLino} from './storage.mjs';
6
+ import {requireNativePath} from './operation-input.mjs';
7
+ import {clientFileTransaction} from './client-transaction.mjs';
8
+ import {setupClientJSON} from './client-json.mjs';
9
+ import {setupPersistentClient} from './client-persistent.mjs';
10
+ import {globalClientPaths,readGlobalClientState,globalClientDigest} from './client-global-state.mjs';
11
+ async function exclusive(path,source){
12
+ await requireNativePath(path);await mkdir(dirname(path),{recursive:true,mode:0o700});const file=await open(path,'wx',0o600);try{await file.writeFile(source,'utf8');await file.sync();}finally{await file.close();}
13
+ }
14
+ async function mode(path,source){return source===null?null:(await lstat(path)).mode&0o7777;}
15
+ export async function applyGlobalClientConfiguration(paths,endpoint,catalog,options={}){
16
+ const constraint=await inspectCodexCatalogConstraint(paths,{cwd:options.cwd}),files=globalClientPaths(paths);let setupBackup=null,originalConfig=null;
17
+ try{return await clientFileTransaction(paths,async(txn)=>{
18
+ if(await readGlobalClientState(paths)!==null)throw clientFailure('A global backup already exists; undo it before a new takeover');
19
+ if(paths.info.client==='grok'){await options.afterConfigure?.(txn);return {path:paths.config,backup:null,changed:false};}
20
+ const config=await optionalClientText(paths.config),marker=await optionalClientText(paths.marker),configMode=await mode(paths.config,config),markerMode=paths.marker?await mode(paths.marker,marker):null;originalConfig=config;
21
+ for(const path of [files.config,files.marker,files.state]){await txn.verify(path);if(await optionalClientText(path)!==null)throw clientFailure('An existing global backup must be reconciled before takeover');}
22
+ if(config!==null){await exclusive(files.config,config);await txn.advance([files.config]);}if(marker!==null){await exclusive(files.marker,marker);await txn.advance([files.marker]);}
23
+ if(constraint){await removeCodexCatalogConstraint(paths,txn,{cwd:options.cwd,expected:constraint});originalConfig=await optionalClientText(paths.config);}
24
+ await txn.verify(paths.config);if(paths.marker)await txn.verify(paths.marker);const codec=['claude','codex'].includes(paths.info.client)?setupPersistentClient:setupClientJSON;
25
+ const 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]);}});
26
+ const markerAfter=await optionalClientText(paths.marker),state={config_existed:config!==null,config_mode:configMode,config_hash_after_setup:globalClientDigest(await optionalClientText(paths.config)),marker_existed:marker!==null,marker_mode:markerMode,marker_hash_after_setup:markerAfter===null?null:globalClientDigest(markerAfter),marker_path:paths.marker,setup_backup:setupBackup};
27
+ await exclusive(files.state,encodeLino(state)+'\n');await txn.advance([files.state]);await txn.checkpoint('config');await options.afterConfigure?.(txn);return result;
28
+ },{checkpoint:options.checkpoint});}catch(error){if(setupBackup){const source=await optionalClientText(setupBackup);if(source!==null&&source===originalConfig)await removeClientFile(setupBackup);}throw error;}
29
+ }
30
+ export async function undoGlobalClientConfiguration(paths,options={}){
31
+ return clientFileTransaction(paths,async(txn)=>{
32
+ const saved=await readGlobalClientState(paths);if(saved===null){await options.afterRestore?.(txn);return {restored:false,path:null};}const {state,files}=saved;
33
+ for(const path of [paths.config,...(paths.marker?[paths.marker]:[]),files.config,files.marker,files.state,...(state.setup_backup?[state.setup_backup]:[])])await txn.verify(path);
34
+ const current=await optionalClientText(paths.config),marker=await optionalClientText(paths.marker);if(globalClientDigest(current)!==state.config_hash_after_setup)throw clientFailure('Client config changed after configuration; its edits were preserved');
35
+ if(paths.marker&&(state.marker_hash_after_setup===null?marker!==null:globalClientDigest(marker)!==state.marker_hash_after_setup))throw clientFailure('Client marker changed after configuration; its edits were preserved');
36
+ const beforeConfig=state.config_existed?await optionalClientText(files.config):null,beforeMarker=state.marker_existed?await optionalClientText(files.marker):null;if(state.config_existed&&beforeConfig===null||state.marker_existed&&beforeMarker===null)throw clientFailure('Global undo backup is missing');
37
+ const restore=async(path,source,permissions)=>{await txn.verify(path);if(source===null)await removeClientFile(path);else{await atomicWrite(path,source);if(permissions!==null)await chmod(path,permissions&0o7777);}await txn.advance([path]);};
38
+ if(paths.marker)await restore(paths.marker,beforeMarker,state.marker_mode);await restore(paths.config,beforeConfig,state.config_mode);await txn.checkpoint('restore');await options.afterRestore?.(txn);
39
+ for(const path of [...(state.setup_backup?[state.setup_backup]:[]),files.config,files.marker,files.state]){await txn.verify(path);await removeClientFile(path);await txn.advance([path]);}return {restored:true,path:paths.config};
40
+ },{checkpoint:options.checkpoint});
41
+ }
42
+
43
+ import {inspectCodexCatalogConstraint,removeCodexCatalogConstraint} from './client-codex-catalog.mjs';
@@ -0,0 +1,54 @@
1
+ /** Surgical ownership-aware JSON setup/removal matching src/clients/json_config.rs. */
2
+ import {optionalClientText,clientObject,objectProperty,clientFailure,renderClientJSON,writeClientFile,writeClientMarker,removeClientFile,sameClientValue} from './client-files.mjs';
3
+ const managedQwen=value=>value?.envKey==='LINK_ASSISTANT_TOKEN' && typeof value.name==='string' && value.name.startsWith('Link.Assistant.Router');
4
+ function qwenModels(document) {
5
+ const providers=objectProperty(document,'modelProviders');providers.openai ??=[];
6
+ if (!Array.isArray(providers.openai)) throw clientFailure('modelProviders.openai must be a JSON array');return providers.openai;
7
+ }
8
+ export async function setupClientJSON(paths,endpoint,catalog,{onWrite=async()=>{}}={}) {
9
+ if (!['opencode','agent','qwen'].includes(paths.info.client)) throw clientFailure('Client does not use an OpenCode/Qwen JSON provider');
10
+ if (!catalog.length) throw clientFailure('Router catalog contains no models from healthy subscriptions');
11
+ const source=await optionalClientText(paths.config),document=clientObject(source);
12
+ const markerSource=await optionalClientText(paths.marker);let marker=markerSource===null ? null : clientObject(markerSource,'Ownership marker');
13
+ if (paths.info.client==='qwen') {
14
+ const models=qwenModels(document),previous=marker?.managed_models ?? (marker?.managed_model ? [marker.managed_model] : []);
15
+ if (!Array.isArray(previous)) throw clientFailure('Invalid ownership marker');
16
+ const managed=catalog.map(({id})=>({id,name:'Link.Assistant.Router',baseUrl:endpoint,envKey:'LINK_ASSISTANT_TOKEN'}));
17
+ const current=models.filter(value=>managedQwen(value) || previous.some(old=>sameClientValue(old,value)));
18
+ if(sameClientValue(current,managed) && sameClientValue(marker?.managed_models,managed)) return {path:paths.config,backup:null,changed:false};
19
+ document.modelProviders.openai=[...models.filter(value=>!managedQwen(value) && !previous.some(old=>sameClientValue(old,value))),...managed];
20
+ marker={...(marker ?? {}),managed_models:managed};delete marker.managed_model;
21
+ } else {
22
+ const providers=objectProperty(document,'provider'),previous=providers['link-assistant'];
23
+ const managed=previous===undefined ? {} : structuredClone(previous);
24
+ if (!managed || typeof managed!=='object' || Array.isArray(managed)) throw clientFailure('provider.link-assistant must be a JSON object');
25
+ Object.assign(managed,{npm:'@ai-sdk/openai-compatible',name:'Link.Assistant.Router',options:{baseURL:endpoint,apiKey:'{env:LINK_ASSISTANT_TOKEN}'}});
26
+ const models=objectProperty(managed,'models');
27
+ for(const id of marker?.managed_model_ids ?? []) if (!catalog.some(model=>model.id===id)) delete models[id];
28
+ for(const {id} of catalog) if(!Object.hasOwn(models,id)) Object.defineProperty(models,id,{value:{name:`Router (${id})`},writable:true,enumerable:true,configurable:true});
29
+ if(sameClientValue(previous,managed) && sameClientValue(marker?.managed_provider,managed)) return {path:paths.config,backup:null,changed:false};
30
+ providers['link-assistant']=managed;
31
+ marker=marker ?? {had_previous_provider:previous!==undefined,previous_provider:previous ?? null};
32
+ Object.assign(marker,{managed_provider:managed,managed_model_ids:catalog.map(({id})=>id)});
33
+ }
34
+ const result=await writeClientFile(paths.config,source,renderClientJSON(document));await onWrite(paths.config,result);await writeClientMarker(paths.marker,marker);await onWrite(paths.marker);return result;
35
+ }
36
+ export async function removeClientJSON(paths,{onWrite=async()=>{}}={}) {
37
+ const source=await optionalClientText(paths.config);if(source===null || !source.trim()) return {path:paths.config,backup:null,changed:false};
38
+ const markerSource=await optionalClientText(paths.marker);if(markerSource===null || !markerSource.trim()) return {path:paths.config,backup:null,changed:false};
39
+ const marker=clientObject(markerSource,'Ownership marker'),document=clientObject(source);let changed=false;
40
+ if(paths.info.client==='qwen') {
41
+ const managed=marker.managed_models ?? (marker.managed_model ? [marker.managed_model] : null);
42
+ if(!Array.isArray(managed)) throw clientFailure('Invalid ownership marker');const models=qwenModels(document);
43
+ document.modelProviders.openai=models.filter(model=>!managed.some(old=>sameClientValue(old,model)));changed=models.length!==document.modelProviders.openai.length;
44
+ } else {
45
+ if(!Object.hasOwn(marker,'managed_provider')) throw clientFailure('Invalid ownership marker');
46
+ const providers=document.provider;
47
+ if(providers && sameClientValue(providers['link-assistant'],marker.managed_provider)) {
48
+ if(marker.had_previous_provider) {if(!Object.hasOwn(marker,'previous_provider')) throw clientFailure('Invalid ownership marker');providers['link-assistant']=marker.previous_provider;}
49
+ else delete providers['link-assistant'];changed=true;
50
+ }
51
+ }
52
+ const result=changed ? await writeClientFile(paths.config,source,renderClientJSON(document)) : {path:paths.config,backup:null,changed:false};
53
+ if(changed) await onWrite(paths.config);await removeClientFile(paths.marker);await onWrite(paths.marker);return result;
54
+ }
@@ -0,0 +1,28 @@
1
+ /** Native launch policy DATA and argv planning; this module never spawns a process. */
2
+ import {clientIntegration,clientFailure} from './client-files.mjs';
3
+ const rules={"clients":{"codex":{"commands":["agents","exec","e","review","login","logout","mcp","plugin","mcp-server","app-server","remote-control","app","completion","update","doctor","sandbox","debug","apply","a","resume","queue","archive","delete","migrate-rollouts","unarchive","fork","cloud","cloud-tasks","exec-server","features"],"modelFlag":"--model","mode":"exec","aliases":[],"modeTakesValue":false},"claude":{"commands":["agents","attach","auth","auto-mode","doctor","gateway","import","install","logs","mcp","plugin","plugins","project","respawn","rm","setup-token","stop","kill","ultrareview","update","upgrade"],"modelFlag":"--model","mode":"--print","aliases":["-p"],"modeTakesValue":false},"cursor-agent":{"commands":[],"modelFlag":null,"mode":null,"aliases":[],"modeTakesValue":false},"gemini":{"commands":["mcp","extensions","extension","skills","skill","hooks","hook","gemma"],"modelFlag":"--model","mode":"-p","aliases":["--prompt"],"modeTakesValue":true},"grok":{"commands":["git","mcp"],"modelFlag":"--model","mode":"-p","aliases":["--prompt"],"modeTakesValue":true},"opencode":{"commands":["completion","acp","mcp","attach","run","debug","providers","auth","agent","upgrade","uninstall","serve","web","models","stats","export","import","github","pr","session","plugin","plug","db"],"modelFlag":"--model","mode":"run","aliases":[],"modeTakesValue":false},"qwen":{"commands":["mcp","extensions"],"modelFlag":"--model","mode":"-p","aliases":["--prompt"],"modeTakesValue":true},"agent":{"commands":["auth"],"modelFlag":"--model","mode":"--prompt","aliases":["-p"],"modeTakesValue":true}},"codexValueOptions":["-c","--config","--enable","--disable","-i","--image","-m","--model","--local-provider","--profile","-s","--sandbox","-a","--ask-for-approval","-C","--cd","--add-dir"],"codexBooleanOptions":["--oss","--search","--full-auto","--dangerously-bypass-approvals-and-sandbox","--no-alt-screen","-h","--help","-V","--version"],"claudeNativeServiceError":"this Claude.ai operation cannot be routed because released Claude Code (checked through 2.1.283) has no supported split-auth mechanism; run it directly with Claude.ai authentication instead; no Router token was minted and no client was launched","codexCloudError":"Codex Cloud tasks cannot be routed: the official Codex client does not support a split credential or custom backend for Cloud; no Router token was minted and no client was launched","noPromptNote":"note: this client's one-shot mode takes the prompt as an argument and none was given, so it is launched as an ordinary session"};
4
+ function argumentsData(value){if(!Array.isArray(value)||value.length>10000||value.some(row=>typeof row!=='string'||row.includes('\0'))||Buffer.byteLength(value.join('\0'))>2097152)throw clientFailure('Client argv must contain bounded strings without NUL');return [...value];}
5
+ export function forwardedClientModel(value){
6
+ const args=argumentsData(value);let found=null;
7
+ for(let at=0;at<args.length;at++){const word=args[at];let next=null;if(word==='-m'||word==='--model'){if(++at===args.length)throw clientFailure(word+' requires a model id');next=args[at];}else if(word.startsWith('--model='))next=word.slice(8);if(next!==null){if(!next)throw clientFailure('forwarded model id must not be empty');if(found!==null&&found!==next)throw clientFailure('conflicting forwarded model arguments');found=next;}}return found;
8
+ }
9
+ function codexCommand(args){
10
+ let at=0;while(at<args.length){const word=args[at];if(word==='--')return args[at+1]??null;if(!word.startsWith('-')||word==='-')return word;if(rules.codexBooleanOptions.includes(word)){at++;continue;}if(rules.codexValueOptions.includes(word)){if(at+1>=args.length)return null;at+=2;continue;}if(word.startsWith('--')&&word.includes('=')&&rules.codexValueOptions.includes(word.split('=')[0])){at++;continue;}if(['-c','-i','-m','-s','-a','-C'].some(prefix=>word.startsWith(prefix)&&word.length>prefix.length)){at++;continue;}return null;}return null;
11
+ }
12
+ export function unsupportedClientNativeCommand(client,value){
13
+ const name=clientIntegration(client).client,args=argumentsData(value),words=args[0]==='--'?args.slice(1):args;
14
+ if(name==='claude'&&(['remote-control','ultrareview'].includes(words[0])||words.some(word=>['--cloud','--environment','--remote-control','--rc','--teleport'].includes(word.split('=')[0]))))return rules.claudeNativeServiceError;
15
+ if(name==='codex'&&['cloud','cloud-tasks'].includes(codexCommand(args)))return rules.codexCloudError;return null;
16
+ }
17
+ export function nativeClientRequiresModel(client){return ['opencode','qwen','agent'].includes(clientIntegration(client).client);}
18
+ export function planNativeClientLaunch(client,options={},resolvedModel=null,attachedToTerminal=false){
19
+ const info=clientIntegration(client),rule=rules.clients[info.client],forwarded=argumentsData(options.client_args??[]),exact=forwarded[0]==='--';if(exact)forwarded.shift();if(options.interactive&&options.non_interactive)throw clientFailure('interactive and non_interactive conflict');if(resolvedModel!==null&&(typeof resolvedModel!=='string'||!resolvedModel||resolvedModel.includes('\0')))throw clientFailure('Resolved model must be a nonempty string without NUL');
20
+ const native=exact||rule.commands.includes(forwarded[0]),prompt=forwarded.length>0&&!forwarded[0].startsWith('-')&&!rule.commands.includes(forwarded[0]),oneShot=!native&&(options.non_interactive?true:options.interactive?false:prompt||!attachedToTerminal),commandMode=['codex','opencode'].includes(info.client),hasMode=rule.mode!==null&&(commandMode?[rule.mode,...rule.aliases].includes(forwarded[0]):forwarded.some(word=>[rule.mode,...rule.aliases].includes(word))),result=[];let note=null;
21
+ if(commandMode&&hasMode){const first=forwarded.shift();if(first!==undefined)result.push(first);}else if(commandMode&&oneShot&&rule.mode)result.push(rule.mode);
22
+ if(resolvedModel!==null&&rule.modelFlag&&!forwarded.some(word=>word==='-m'||word==='--model'||word.startsWith('--model='))){result.push(rule.modelFlag,['opencode','agent'].includes(info.client)&&!resolvedModel.includes('/')?'link-assistant/'+resolvedModel:resolvedModel);}
23
+ if(!commandMode&&oneShot&&!hasMode&&rule.mode){if(rule.modeTakesValue&&!prompt)note=rules.noPromptNote;else result.push(rule.mode);}
24
+ result.push(...forwarded);return {arguments:result,one_shot:oneShot,note};
25
+ }
26
+ export function preflightNativeClientLaunch(client,options={}){
27
+ const args=argumentsData(options.client_args??[]),error=unsupportedClientNativeCommand(client,args);if(error)throw clientFailure(error);const forwarded=forwardedClientModel(args);if(options.model!==undefined&&forwarded!==null&&options.model!==forwarded)throw clientFailure('Router model conflicts with forwarded model');return {forwardedModel:forwarded,requiresModel:nativeClientRequiresModel(client)};
28
+ }
@@ -0,0 +1,35 @@
1
+ /** Actual temporary with composition: target -> credential -> bridge -> profile -> owned process. */
2
+ import {clientIntegration,clientFailure} from './client-files.mjs';import {resolve} from 'node:path';import {randomUUID} from 'node:crypto';
3
+ import {withSelectedNativeClientTarget} from './client-configure.mjs';import {requestNativeRunModelPolicy,withNativeRunCredential} from './client-run-credential.mjs';import {planNativeClientLaunch} from './client-launch-plan.mjs';
4
+ import {withClientProcessProfile,clientProcessEnvironment} from './client-process-profile.mjs';import {runOwnedClientProcess} from './client-process.mjs';
5
+ import {startCodexLoopbackTransport,codexLoopbackRequired} from './codex-loopback-transport.mjs';
6
+ const minimumClaude=[2, 1, 255];
7
+ export function nativeClaudeGatewayVersionSupported(output){
8
+ if(typeof output!=='string'||Buffer.byteLength(output)>2097152)return false;
9
+ for(const part of output.split(/[^0-9.]+/u)){const pieces=part.split('.').slice(0,3);if(pieces.length!==3||pieces.some(value=>!/^\d+$/u.test(value)))continue;const normalized=pieces.map(value=>value.replace(/^0+(?=\d)/u,''));if(normalized.some(value=>value.length>20))continue;const values=normalized.map(value=>BigInt(value));if(values.some(value=>value>18446744073709551615n))continue;for(let at=0;at<3;at++){if(values[at]>BigInt(minimumClaude[at]))return true;if(values[at]<BigInt(minimumClaude[at]))return false;}return true;}return false;
10
+ }
11
+ async function requireClaudeVersion(context){
12
+ let answer;try{answer=await runOwnedClientProcess({command:'claude',args:['--version'],env:clientProcessEnvironment(context.env),cwd:resolve(context.invocation.cwd??process.cwd()),timeoutMs:5000,maxOutputBytes:1048576,signal:context.invocation.signal});}catch(error){if(context.invocation.signal?.aborted)throw error;return;}
13
+ if(answer.client_exit_code!==0||!nativeClaudeGatewayVersionSupported(answer.stdout+answer.stderr))throw clientFailure('Claude Code '+minimumClaude.join('.')+' or newer is required for Router gateway discovery and alias resolution');
14
+ }
15
+ async function withProcessBridge(client,origin,operation,caCert=null,cwd=process.cwd()){
16
+ if(client!=='codex'||!codexLoopbackRequired(origin))return operation(null);const bridge=await startCodexLoopbackTransport({upstreamOrigin:origin,nonce:randomUUID().replaceAll('-',''),upstreamCaCert:caCert,cwd});try{return await operation(bridge.backendBaseURL);}finally{await bridge.close();}
17
+ }
18
+ export async function executeNativeWith(context={}){
19
+ const original=context.options??{},options={...original,client_args:Array.isArray(original.client_args)?[...original.client_args]:original.client_args??[],allowed_models:Array.isArray(original.allowed_models)?[...original.allowed_models]:original.allowed_models},env={...(context.env??{})},invocation={...(context.invocation??{})},info=clientIntegration(options.client);requestNativeRunModelPolicy(info.client,options);
20
+ if(options.global||options.undo)throw clientFailure('Temporary launch entry does not perform global configure or undo');if(options.all)throw clientFailure('Temporary launch requires one client');if(info.client==='cursor-agent')throw clientFailure(info.unsupported);
21
+ if(options.isolated_config&&options.extend_global_config)throw clientFailure('isolated_config conflicts with extend_global_config');if(options.reset_to_default_configuration&&info.client!=='claude')throw clientFailure('Profile reset is available only for Claude');if(options.reset_to_default_configuration&&(options.isolated_config||options.extend_global_config))throw clientFailure('Profile reset requires the Router-owned Claude profile');await confirmClaudeProcessReset(options,invocation);
22
+ const current={...context,options,env,invocation},notes=[];if(info.client==='claude'){await requireClaudeVersion(current);notes.push("released Claude Code (checked through 2.1.283) has no supported split-auth mechanism: Router inference and /v1/models discovery use only the Router token, while the stored Claude.ai login remains untouched; Claude.ai connectors, Remote Control and /remote-control, /schedule, notification preferences, cloud sessions (--cloud, --environment, --teleport, and ultrareview), remote managed settings, and organization policy are unavailable in this Router-directed process");}
23
+ return withSelectedNativeClientTarget({...current,retainOnSuccess:false},async target=>{
24
+ const suppliedToken=options.token_stdin?String(invocation.stdin??'').trim():options.token??target.token;if(typeof suppliedToken!=='string'||!suppliedToken.trim())throw clientFailure('Selected Router requires a token for temporary launch');
25
+ return withNativeRunCredential({client:info.client,options,origin:target.server,managementServer:target.managementServer,suppliedToken,config:context.core.config,env,invocation,fetch:context.fetch,notes},async credential=>{
26
+ const attached=invocation.attachedToTerminal??Boolean(process.stdin.isTTY&&process.stdout.isTTY),plan=planNativeClientLaunch(info.client,options,credential.selectedModel,attached);if(plan.note)notes.push(plan.note);
27
+ return withProcessBridge(info.client,target.server,backendBaseURL=>withClientProcessProfile({client:info.client,options,env,cwd:invocation.cwd??process.cwd(),origin:target.server,token:credential.token,catalog:credential.catalog,selectedModel:credential.selectedModel,oneShot:plan.one_shot,backendBaseURL,caCert:target.caCert},async profile=>{
28
+ notes.push(...profile.notes);const child=await runOwnedClientProcess({command:profile.command,args:[...profile.argsPrefix,...plan.arguments],cwd:profile.cwd,env:profile.env,onSpawn:profile.commitLaunch,signal:invocation.signal,stdin:options.token_stdin?undefined:invocation.stdin,timeoutMs:invocation.deadlineMs??60000,maxOutputBytes:invocation.maxOutputBytes??8388608,interactive:attached&&!plan.one_shot&&invocation.stdin===undefined,forwardSignals:invocation.forwardSignals??attached}),result={...child,output:[...notes,...(child.stdout?[child.stdout]:[]) ]};
29
+ if(child.client_exit_code!==0){const failure=clientFailure('Client exited with status '+child.client_exit_code);Object.assign(failure,{exitCode:child.client_exit_code,data:result});throw failure;}return result;
30
+ }),target.caCert??null,invocation.cwd??process.cwd());
31
+ });
32
+ });
33
+ }
34
+
35
+ import {confirmClaudeProcessReset} from './claude-process-session.mjs';
@@ -0,0 +1,66 @@
1
+ /** Persistent client codecs share the native ownership/restore contracts. */
2
+ import {clientObject,objectProperty,clientFailure,optionalClientText,renderClientJSON,writeClientFile,writeClientMarker,removeClientFile,sameClientValue} from './client-files.mjs';
3
+ import {nativeClientModelAuthorized} from './client-catalog.mjs';
4
+ import {editClientTomlSource,parseClientTomlSource} from './client-toml-cst.mjs';
5
+ const MODEL_KEYS=['ANTHROPIC_MODEL','ANTHROPIC_DEFAULT_OPUS_MODEL','ANTHROPIC_DEFAULT_SONNET_MODEL','ANTHROPIC_DEFAULT_HAIKU_MODEL','CLAUDE_CODE_SUBAGENT_MODEL'];
6
+ const TARGET_KEYS=['ANTHROPIC_MODEL','CLAUDE_CODE_SUBAGENT_MODEL'];
7
+ const text=(value)=>typeof value==='string'?value:null;
8
+ const has=(value,key)=>Object.hasOwn(value,key);
9
+ const set=(object,key,value)=>{if(value===null)delete object[key];else Object.defineProperty(object,key,{value,writable:true,enumerable:true,configurable:true});};
10
+ function ownership(source,client){
11
+ const marker=source===null?null:clientObject(source,'Ownership marker');if(marker===null)return null;
12
+ if(client==='claude'){
13
+ if(typeof marker.anthropic_base_url!=='string')throw clientFailure('Claude ownership marker has no managed endpoint');
14
+ const entries=marker.gateway_env??{};if(!entries||typeof entries!=='object'||Array.isArray(entries))throw clientFailure('Claude ownership marker has invalid environment entries');
15
+ for(const key of Object.keys(entries)){const row=entries[key];if(!row||typeof row!=='object'||Array.isArray(row)||!['string','undefined'].includes(typeof row.managed)&&row.managed!==null||!['string','undefined'].includes(typeof row.previous)&&row.previous!==null)throw clientFailure('Claude ownership marker has invalid environment values');}
16
+ }
17
+ return marker;
18
+ }
19
+ export function persistentClaudeGatewayModel(catalog){
20
+ if(catalog.some(row=>row.owned_by==='anthropic'))return null;
21
+ const rows=catalog.filter(row=>row.owned_by==='z.ai');const flagship=rows.find(row=>row.id==='glm-5.3'&&row.router_unavailable_reason==null);if(flagship)return flagship.id;
22
+ return rows.sort((left,right)=>Number(left.router_unavailable_reason==null)-Number(right.router_unavailable_reason==null)||(left.provider_created_at??-1)-(right.provider_created_at??-1)||(left.id<right.id?-1:left.id>right.id?1:0)).at(-1)?.id??null;
23
+ }
24
+ function claudePlan(source,markerSource,endpoint,catalog){
25
+ const document=clientObject(source),marker=ownership(markerSource,'claude'),saved=text(document.model),semanticDefault=saved!==null&&saved.trim().toLowerCase()==='default',anthropic=catalog.some(row=>row.owned_by==='anthropic');
26
+ if(saved!==null&&!semanticDefault&&!nativeClientModelAuthorized('claude',catalog,saved.trim())&&!(anthropic&&['opus','sonnet','haiku'].includes(saved.trim().split('[')[0].toLowerCase())))throw clientFailure('The saved Claude model is no longer authorized; choose an advertised model explicitly');
27
+ const env=objectProperty(document,'env'),old=marker?.gateway_env??{},legacy=old.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC;if(legacy?.managed==='0'&&env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC==='0')set(env,'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC',text(legacy.previous));
28
+ const previous=marker!==null?text(marker.previous_anthropic_base_url):text(env.ANTHROPIC_BASE_URL)!==endpoint?text(env.ANTHROPIC_BASE_URL):null;
29
+ const users=MODEL_KEYS.filter(key=>has(env,key)&&!(has(old,key)&&typeof old[key].managed==='string'&&env[key]===old[key].managed)),gateway={};
30
+ const manage=(key,value)=>{const previous=has(old,key)?text(old[key].previous):text(env[key]);set(env,key,value);Object.defineProperty(gateway,key,{value:{managed:value,previous},enumerable:true,writable:true,configurable:true});};
31
+ set(env,'ANTHROPIC_BASE_URL',endpoint);manage('CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY','1');manage('ANTHROPIC_AUTH_TOKEN',null);manage('ANTHROPIC_API_KEY',null);
32
+ const model=persistentClaudeGatewayModel(catalog);for(const key of MODEL_KEYS)if(!users.includes(key))manage(key,saved!==null&&!semanticDefault?null:TARGET_KEYS.includes(key)?model:null);
33
+ return {contents:renderClientJSON(document),marker:{anthropic_base_url:endpoint,previous_anthropic_base_url:previous,gateway_env:gateway,user_model_keys:users}};
34
+ }
35
+ function codexDocument(source){try{return parseClientTomlSource(source??'');}catch{throw clientFailure('Client configuration contains invalid TOML');}}
36
+ function table(document,key){const value=document[key];if(value!==undefined&&(!value||typeof value!=='object'||Array.isArray(value)||value instanceof Date))throw clientFailure('Codex provider configuration requires a TOML table');return value??{};}
37
+ function codexPlan(source,markerSource,endpoint,catalog,options){
38
+ const document=codexDocument(source),marker=ownership(markerSource,'codex'),providers=table(document,'model_providers');table(providers,'link-assistant');
39
+ const backend=options.backendBaseURL??endpoint.replace(/\/v1$/u,'')+'/backend-api',selected=options.model,websockets=selected?catalog.some(row=>row.id===selected&&row.owned_by!=='z.ai'):!catalog.some(row=>row.owned_by==='z.ai');
40
+ const changes=[{path:['model_provider'],action:'set',value:'link-assistant'},{path:['chatgpt_base_url'],action:'set',value:backend},{path:['experimental_realtime_ws_base_url'],action:'set',value:endpoint},{path:['experimental_realtime_webrtc_call_base_url'],action:'set',value:endpoint}];
41
+ const fields={name:'OpenAI',base_url:endpoint,wire_api:'responses',requires_openai_auth:true,supports_websockets:websockets,supports_standalone_web_search:true};for(const key of Object.keys(fields))changes.push({path:['model_providers','link-assistant',key],action:'set',value:fields[key]});changes.push({path:['model_providers','link-assistant','env_key'],action:'delete'});
42
+ const previous=(key,managed,prior)=>marker&&text(document[key])===text(marker[managed])?text(marker[prior]):text(document[key]);
43
+ return {contents:editClientTomlSource(source??'',changes).after,marker:{previous_provider:marker?text(marker.previous_provider):document.model_provider==='link-assistant'?null:text(document.model_provider),managed_chatgpt_base_url:backend,previous_chatgpt_base_url:previous('chatgpt_base_url','managed_chatgpt_base_url','previous_chatgpt_base_url'),managed_realtime_base_url:endpoint,previous_realtime_ws_base_url:previous('experimental_realtime_ws_base_url','managed_realtime_base_url','previous_realtime_ws_base_url'),previous_realtime_call_base_url:previous('experimental_realtime_webrtc_call_base_url','managed_realtime_base_url','previous_realtime_call_base_url')}};
44
+ }
45
+ export function planPersistentClient(client,source,markerSource,endpoint,catalog,options={}){
46
+ if(!['claude','codex'].includes(client))throw clientFailure('Persistent codec requires Claude or Codex');if(typeof endpoint!=='string'||!Array.isArray(catalog))throw clientFailure('Persistent client requires an endpoint and live catalog');return client==='claude'?claudePlan(source,markerSource,endpoint,catalog):codexPlan(source,markerSource,endpoint,catalog,options);
47
+ }
48
+ export function planRemovePersistentClient(client,source,markerSource){
49
+ if(source===null||!source.trim()||markerSource===null||!markerSource.trim())return {contents:source,removeMarker:false};const marker=ownership(markerSource,client);
50
+ if(client==='claude'){
51
+ const document=clientObject(source),env=document.env;if(env&&typeof env==='object'&&!Array.isArray(env)){
52
+ if(env.ANTHROPIC_BASE_URL===marker.anthropic_base_url)set(env,'ANTHROPIC_BASE_URL',text(marker.previous_anthropic_base_url));
53
+ for(const key of Object.keys(marker.gateway_env??{})){const row=marker.gateway_env[key],managed=text(row.managed),owns=managed===null?!has(env,key):env[key]===managed;if(owns)set(env,key,text(row.previous));}
54
+ }return {contents:renderClientJSON(document),removeMarker:true};
55
+ }
56
+ if(client!=='codex')throw clientFailure('Persistent codec requires Claude or Codex');const document=codexDocument(source),changes=[];
57
+ const restore=(key,managed,previous)=>{if(text(document[key])===text(managed))changes.push(previous===null?{path:[key],action:'delete'}:{path:[key],action:'set',value:previous});};
58
+ restore('model_provider','link-assistant',text(marker.previous_provider));restore('chatgpt_base_url',marker.managed_chatgpt_base_url,text(marker.previous_chatgpt_base_url));restore('experimental_realtime_ws_base_url',marker.managed_realtime_base_url,text(marker.previous_realtime_ws_base_url));restore('experimental_realtime_webrtc_call_base_url',marker.managed_realtime_base_url,text(marker.previous_realtime_call_base_url));changes.push({path:['model_providers','link-assistant'],action:'delete'});return {contents:editClientTomlSource(source,changes).after,removeMarker:true};
59
+ }
60
+ export async function setupPersistentClient(paths,endpoint,catalog,options={}){
61
+ const source=await optionalClientText(paths.config),before=await optionalClientText(paths.marker),plan=planPersistentClient(paths.info.client,source,before,endpoint,catalog,options),onWrite=options.onWrite??(async()=>{});
62
+ const result=await writeClientFile(paths.config,source,plan.contents);await onWrite(paths.config,result);if(before===null||!sameClientValue(clientObject(before,'Ownership marker'),plan.marker)){await writeClientMarker(paths.marker,plan.marker);await onWrite(paths.marker);}return result;
63
+ }
64
+ export async function removePersistentClient(paths,options={}){
65
+ const source=await optionalClientText(paths.config),marker=await optionalClientText(paths.marker),plan=planRemovePersistentClient(paths.info.client,source,marker),onWrite=options.onWrite??(async()=>{});const result=plan.contents===source?{path:paths.config,backup:null,changed:false}:await writeClientFile(paths.config,source,plan.contents);if(result.changed)await onWrite(paths.config,result);if(plan.removeMarker){await removeClientFile(paths.marker);await onWrite(paths.marker);}return result;
66
+ }
@@ -0,0 +1,52 @@
1
+ /** Private Router-owned profiles; caller profile contents and credentials are never copied. */
2
+ import {mkdtemp,mkdir,chmod,lstat,rm,realpath,readdir} from 'node:fs/promises';
3
+ import {join,resolve} from 'node:path';import {tmpdir} from 'node:os';import {randomUUID} from 'node:crypto';
4
+ import {clientPaths,clientFailure,clientObject,optionalClientText} from './client-files.mjs';
5
+ import {requireNativePath,readNativeText} from './operation-input.mjs';
6
+ import {withNativeFileLock,atomicWrite} from './storage.mjs';
7
+ import {setupClientJSON} from './client-json.mjs';import {setupPersistentClient} from './client-persistent.mjs';import {parseClientTomlSource} from './client-toml-cst.mjs';
8
+ import {usableProcessModels,codexProcessCatalog,codexProcessOverrides,claudeProcessSettings,claudeProcessEnvironment,claudeProcessPrivacyWarnings} from './client-process-settings.mjs';
9
+ export function processExtendsUserConfiguration(client,options={}){
10
+ if(options.isolated_config)return false;if(client==='claude')return options.extend_global_config===true;return ['codex','grok'].includes(client);
11
+ }
12
+ async function prepare(context,directory,extendsUser){
13
+ const {options={},env={},cwd=process.cwd(),token,backendBaseURL=null,selectedModel=null,oneShot=false}=context,origin=normalizeManagedOrigin(context.origin),info=clientPaths(context.client,{home:options.home,env,cwd}).info,models=usableProcessModels(info.client,context.catalog),paths=clientPaths(info.client,{home:directory,env:{HOME:directory},cwd}),environment=clientProcessEnvironment(env),prefix=[],notes=[];
14
+ if(typeof token!=='string'||!token.startsWith('la_sk_')||token.includes('\0'))throw clientFailure('Prepared process credential requires a Router token');
15
+ if(info.client==='cursor-agent')throw clientFailure('Cursor process routing is unsupported');
16
+ if(!extendsUser){if(info.client==='claude')environment.CLAUDE_CONFIG_DIR=directory;else if(info.client==='gemini'){environment.HOME=directory;environment.GEMINI_CLI_HOME=directory;if(oneShot)environment.GEMINI_CLI_TRUST_WORKSPACE='true';}else if(info.client==='opencode'){environment.OPENCODE_CONFIG=paths.config;environment.OPENCODE_CONFIG_DIR=resolve(paths.config,'..');}else{environment.HOME=directory;delete environment.CODEX_HOME;delete environment.QWEN_HOME;}}
17
+ if(info.token)environment[info.token]=token;if(info.base)environment[info.base]=origin+info.suffix;
18
+ if(context.caCert){await readNativeText(context.caCert,{cwd,maxBytes:1048576});environment.NODE_EXTRA_CA_CERTS=resolve(cwd,context.caCert);}
19
+ if(info.client==='claude'){
20
+ const settings=extendsUser?clientPaths('claude',{home:options.home,env,cwd}).config:join(directory,'settings.json'),source=await optionalClientText(settings),saved=source===null?null:clientObject(source).model;
21
+ if(saved!==undefined&&saved!==null&&typeof saved!=='string')throw clientFailure('Saved Claude model must be a string');Object.assign(environment,claudeProcessEnvironment(env,models,selectedModel,saved??null));notes.push(...claudeProcessPrivacyWarnings(env));prefix.push('--settings',JSON.stringify(claudeProcessSettings(models)));
22
+ }else if(info.client==='codex'){
23
+ const current=options.isolated_config?null:await optionalClientText(clientPaths('codex',{home:options.home,env,cwd}).config),document=current===null?{}:parseClientTomlSource(current),effort=document.model_reasoning_effort??null;if(effort!==null&&typeof effort!=='string')throw clientFailure('Configured Codex reasoning effort must be a string');
24
+ const catalog=codexProcessCatalog(models,effort,selectedModel),path=join(directory,'router-codex-models.json');await atomicWrite(path,JSON.stringify(catalog.document)+'\n');if(catalog.omitted.length)notes.push('omitted inconsistent Codex reasoning metadata: '+catalog.omitted.join(', '));
25
+ const backend=backendBaseURL??origin+'/api/services/codex/backend-api';if(options.isolated_config)await setupPersistentClient(paths,origin+info.suffix,models,{backendBaseURL:backend,model:selectedModel});prefix.push(...codexProcessOverrides(origin,backend,path,'link-assistant-run-'+randomUUID().replaceAll('-',''),models,selectedModel));
26
+ const alias='at-'+token.slice(6);environment.CODEX_ACCESS_TOKEN=alias;environment.CODEX_CONNECTORS_TOKEN=alias;environment.CODEX_AUTHAPI_BASE_URL=origin+'/api/services/codex';
27
+ }else if(info.client==='gemini'){await atomicWrite(paths.config,JSON.stringify({security:{auth:{selectedType:'gemini-api-key'}}})+'\n');environment.GEMINI_DEFAULT_AUTH_TYPE='gemini-api-key';}
28
+ else if(['opencode','agent','qwen'].includes(info.client)){
29
+ await setupClientJSON(paths,origin+info.suffix,models);if(['opencode','agent'].includes(info.client)&&selectedModel){const document=clientObject(await optionalClientText(paths.config));document.model=selectedModel.includes('/')?selectedModel:'link-assistant/'+selectedModel;await atomicWrite(paths.config,JSON.stringify(document)+'\n');}
30
+ if(info.client==='agent')environment.LINK_ASSISTANT_AGENT_CONFIG_CONTENT=await readNativeText(paths.config,{maxBytes:8388608});if(info.client==='qwen'){environment.OPENAI_API_KEY=token;environment.OPENAI_BASE_URL=origin+info.suffix;if(selectedModel)environment.OPENAI_MODEL=selectedModel;}
31
+ }
32
+ return {command:info.client,argsPrefix:prefix,env:environment,cwd:resolve(cwd),directory,extendsUser,notes};
33
+ }
34
+ async function disposableTreeBudget(directory){
35
+ let count=0;const visit=async(path,depth)=>{if(++count>10000||depth>32)throw clientFailure('Disposable profile exceeds cleanup entry/depth budget; retained for explicit cleanup');const item=await lstat(path);if(item.isDirectory())for(const name of await readdir(path))await visit(join(path,name),depth+1);};await visit(directory,0);
36
+ }
37
+ export async function withClientProcessProfile(context,operation){
38
+ const options=context.options??{},cwd=context.cwd??process.cwd(),normal=clientPaths(context.client,{home:options.home,env:context.env,cwd}),client=normal.info.client,extendsUser=processExtendsUserConfiguration(client,options),persistent=!options.isolated_config&&!extendsUser;
39
+ if(options.reset_to_default_configuration&&(client!=='claude'||!persistent))throw clientFailure('Reset requires the persistent Router-owned Claude profile');
40
+ if(client==='cursor-agent')throw clientFailure('Cursor process routing is unsupported');
41
+ const run=async(directory)=>operation(await prepare({...context,client},directory,extendsUser));
42
+ if(persistent&&client==='claude'){const directory=join(normal.configHome,'link-assistant-router','clients',client,'home');return withClaudeProcessSession({configHome:normal.configHome,reset:options.reset_to_default_configuration===true,checkpoint:context.checkpoint},directory,async lease=>{const profile=await prepare({...context,client},directory,extendsUser);if(lease.backup)profile.notes.push('Router-owned Claude settings reset; verified backup: '+lease.backup);profile.commitLaunch=lease.commitLaunch;return operation(profile);});}
43
+ if(persistent){const directory=join(normal.configHome,'link-assistant-router','clients',client,'home');await requireNativePath(directory);await mkdir(directory,{recursive:true,mode:0o700});await chmod(directory,0o700);return withNativeFileLock(directory,()=>run(directory),1000);}
44
+ const base=context.temporaryRoot===undefined?await realpath(tmpdir()):resolve(context.temporaryRoot);await requireNativePath(base);const directory=await mkdtemp(join(base,'router-client-'+client+'-'));await chmod(directory,0o700);const original=await lstat(directory);
45
+ try{return await run(directory);}finally{const current=await lstat(directory);await requireNativePath(directory);if(!current.isDirectory()||current.dev!==original.dev||current.ino!==original.ino)throw clientFailure('Disposable client profile identity changed; replacement preserved');await disposableTreeBudget(directory);await rm(directory,{recursive:true,force:true,maxRetries:2,retryDelay:100});}
46
+ }
47
+
48
+ import {normalizeManagedOrigin} from './managed-server.mjs';
49
+
50
+ export function clientProcessEnvironment(env){const result={...env};delete result.LINK_ASSISTANT_ROUTER_TOKEN;delete result.LINK_ASSISTANT_TOKEN;delete result.TOKEN_SECRET;return result;}
51
+
52
+ import {withClaudeProcessSession} from './claude-process-session.mjs';
@@ -0,0 +1,36 @@
1
+ /** Process-local settings projected from actual native contracts; catalog rows remain DATA. */
2
+ import {clientFailure,clientIntegration} from './client-files.mjs';
3
+ import {persistentClaudeGatewayModel} from './client-persistent.mjs';
4
+ import {nativeClientModelAuthorized} from './client-catalog.mjs';
5
+ const privacyDefaults=["DISABLE_ERROR_REPORTING","DISABLE_AUTOUPDATER","DISABLE_FEEDBACK_COMMAND"];
6
+ export function usableProcessModels(client,models){
7
+ if(!Array.isArray(models)||models.length>10000)throw clientFailure('Process catalog requires bounded rows');const info=clientIntegration(client),preferred=info.owners.flatMap(owner=>models.filter(row=>row.owned_by===owner));return info.owners.length&&(preferred.length||info.strict)?preferred:[...models];
8
+ }
9
+ export function codexProcessCatalog(models,effort=null,selected=null){
10
+ if(!models.length)throw clientFailure('The Router advertised no models for Codex');const listed=[],omitted=[];
11
+ for(const model of models){const levels=model.supported_reasoning_levels;if(levels!=null&&model.default_reasoning_level!=null&&!levels.some((row)=>row.effort===model.default_reasoning_level)){if(selected===model.id)throw clientFailure('Selected Codex model has inconsistent reasoning metadata');omitted.push(model.id);}else listed.push(model);}
12
+ const compatible=(model)=>effort===null||model.supported_reasoning_levels==null||model.supported_reasoning_levels.some((row)=>row.effort===effort);
13
+ if(selected!==null&&effort!==null){const model=listed.find(row=>row.id===selected);if(!model||!compatible(model))throw clientFailure('Selected Codex model does not support configured reasoning effort');}
14
+ const rows=listed.filter(compatible);if(!rows.length)throw clientFailure('Live Codex catalog has no compatible reasoning metadata');
15
+ return {omitted,document:{models:rows.map((model,index)=>({slug:model.id,display_name:model.id,description:model.owned_by+' via Link.Assistant.Router'+(model.supported_reasoning_levels==null?'; reasoning metadata unavailable, so Codex keeps your configured reasoning effort':''),default_reasoning_level:model.supported_reasoning_levels==null?effort:model.default_reasoning_level??null,supported_reasoning_levels:model.supported_reasoning_levels??[],shell_type:'unified_exec',visibility:'list',supported_in_api:true,priority:Math.min(index,2147483647),availability_nux:null,upgrade:null,support_verbosity:false,default_verbosity:null,apply_patch_tool_type:'freeform',truncation_policy:{mode:'tokens',limit:10000},experimental_supported_tools:[],base_instructions:''}))}};
16
+ }
17
+ export function claudeProcessSettings(models){
18
+ const usable=usableProcessModels('claude',models),anthropic=usable.some(row=>row.owned_by==='anthropic'),rows=new Map(),unavailable=new Set(usable.filter(row=>row.router_unavailable_reason!=null).map(row=>row.id));
19
+ const candidates=usable.filter(row=>typeof row.id==='string'&&row.id.trim()&&!['default','opus','sonnet','haiku'].includes(row.id.trim().toLowerCase())).sort((left,right)=>Number(left.owned_by!=='anthropic')-Number(right.owned_by!=='anthropic')||(left.id<right.id?-1:left.id>right.id?1:0));
20
+ for(const model of candidates){const capability=model.client_capabilities?.claude,behaves=typeof capability?.behaves_as==='string'&&capability.behaves_as.trim()&&typeof capability.source==='string'&&capability.source.trim()?capability.behaves_as:null;if(!rows.has(model.id))rows.set(model.id,{model:model.id,label:model.id+(unavailable.has(model.id)?' (unavailable)':''),behaves});else if(rows.get(model.id).behaves!==behaves)rows.get(model.id).behaves=null;}
21
+ const options=[...rows.values()].map(({model,label,behaves})=>({model,label,...(behaves===null?{}:{behavesAs:behaves})}));return {verbose:true,...(options.length?{modelPicker:{options,replaceBuiltInOptions:!anthropic}}:{})};
22
+ }
23
+ export function claudeProcessEnvironment(env,models,selected=null,savedModel=null){
24
+ const result={ANTHROPIC_API_KEY:'',CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY:'1'},anthropic=models.some(row=>row.owned_by==='anthropic'),gateway=selected!==null&&models.some(row=>row.id===selected&&row.owned_by==='z.ai')?selected:persistentClaudeGatewayModel(models),chosen=env.ANTHROPIC_MODEL?.trim()||(selected===null?savedModel?.trim():null);
25
+ for(const key of privacyDefaults)if(env[key]===undefined)result[key]='1';
26
+ const family=(value)=>['default','opus','sonnet','haiku'].includes(value.trim().split('[')[0].toLowerCase());
27
+ let suppress=false;if(chosen){const semanticDefault=chosen.toLowerCase()==='default';if(!(semanticDefault&&!anthropic)){if(!nativeClientModelAuthorized('claude',models,chosen)&&!(anthropic&&family(chosen)))throw clientFailure('Saved or inherited Claude model is not authorized by the live catalog');suppress=true;}}
28
+ if(!anthropic&&gateway)for(const key of ['ANTHROPIC_DEFAULT_OPUS_MODEL','ANTHROPIC_DEFAULT_SONNET_MODEL','ANTHROPIC_DEFAULT_HAIKU_MODEL'])result[key]=models.some(row=>row.id===env[key])?env[key]:gateway;
29
+ if(!suppress&&gateway)for(const key of ['ANTHROPIC_MODEL','CLAUDE_CODE_SUBAGENT_MODEL'])result[key]=gateway;return result;
30
+ }
31
+ export function codexProcessOverrides(origin,backend,catalogPath,provider,models,selected=null){
32
+ const endpoint=origin+'/api/services/codex/v1',websockets=selected!==null?models.some(row=>row.id===selected&&row.owned_by!=='z.ai'):!usableProcessModels('codex',models).some(row=>row.owned_by==='z.ai'),definition='{ name = "OpenAI", base_url = '+JSON.stringify(endpoint)+', wire_api = "responses", requires_openai_auth = true, supports_websockets = '+websockets+', supports_standalone_web_search = true }',result=[];
33
+ for(const [key,value]of [['model_provider',JSON.stringify(provider)],['model_catalog_json',JSON.stringify(catalogPath)],['model_providers.'+provider,definition],['chatgpt_base_url',JSON.stringify(backend)],['experimental_realtime_ws_base_url',JSON.stringify(endpoint)],['experimental_realtime_webrtc_call_base_url',JSON.stringify(endpoint)]])result.push('-c',key+'='+value);return result;
34
+ }
35
+
36
+ export function claudeProcessPrivacyWarnings(env){const blockers=["CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC","DISABLE_TELEMETRY","DO_NOT_TRACK"].filter((key)=>key==='DO_NOT_TRACK'?env[key]==='1'||env[key]?.toLowerCase()==='true':env[key]!==undefined&&env[key]!=='');return blockers.length?['inherited '+blockers.join(' and ')+' preserves user privacy choices and disables Claude feature-flag evaluation']:[];}
@@ -0,0 +1,44 @@
1
+ /** One operation owns one actual spawned child. No PID from disk is signalled. */
2
+ import {spawn} from 'node:child_process';
3
+ import {isAbsolute} from 'node:path';
4
+ import {constants} from 'node:os';
5
+ import {clientFailure} from './client-files.mjs';
6
+ function boundedInteger(value,maximum,label){if(!Number.isSafeInteger(value)||Number(value)<1||Number(value)>maximum)throw clientFailure(label+' exceeds its finite bound');return Number(value);}
7
+ function launchInput(context){
8
+ const {command,args=[],env={},cwd}=context;if(typeof command!=='string'||!command||command.includes('\0')||Buffer.byteLength(command)>4096)throw clientFailure('Client command requires a bounded executable name');
9
+ if(!Array.isArray(args)||args.length>10000||args.some(value=>typeof value!=='string'||value.includes('\0'))||Buffer.byteLength(args.join('\0'))>2097152)throw clientFailure('Client argv requires bounded NUL-free strings');
10
+ if(typeof cwd!=='string'||!isAbsolute(cwd)||cwd.includes('\0'))throw clientFailure('Client launch requires an absolute working directory');
11
+ if(context.stdin!==undefined&&(typeof context.stdin!=='string'||Buffer.byteLength(context.stdin)>8388608))throw clientFailure('Client stdin requires bounded text');
12
+ const environment=Object.create(null);let bytes=0;const entries=Object.entries(env);if(entries.length>4096)throw clientFailure('Client environment exceeds its entry bound');
13
+ for(const [key,value]of entries){if(!key||key.includes('=')||key.includes('\0')||typeof value!=='string'||value.includes('\0'))throw clientFailure('Client environment requires NUL-free string entries');bytes+=Buffer.byteLength(key)+Buffer.byteLength(value)+2;if(bytes>2097152)throw clientFailure('Client environment exceeds its byte bound');environment[key]=value;}
14
+ return {command,args:[...args],cwd,env:environment,stdin:context.stdin,timeout:boundedInteger(context.timeoutMs??60000,86400000,'Client deadline'),limit:boundedInteger(context.maxOutputBytes??8388608,8388608,'Client output cap'),interactive:context.interactive===true};
15
+ }
16
+ export async function runOwnedClientProcess(context){
17
+ const input=launchInput(context),signal=context.signal;if(signal?.aborted)throw clientFailure('Client launch cancelled before spawn');
18
+ let child;try{child=spawn(input.command,input.args,{cwd:input.cwd,env:input.env,shell:false,windowsHide:!input.interactive,stdio:input.interactive?'inherit':[input.stdin===undefined?'ignore':'pipe','pipe','pipe']});}catch{throw clientFailure('Client executable could not be started');}
19
+ const stdout=[],stderr=[];let stdoutBytes=0,stderrBytes=0,failure=null,settled=false,exited=false,code=null,exitSignal=null;
20
+ let deadline,grace,drain,lastResort;
21
+ let complete=()=>{};const finished=new Promise(done=>{complete=done;});
22
+ const finish=()=>{if(settled)return;settled=true;complete();};
23
+ const stop=(message,requestedSignal='SIGTERM')=>{
24
+ failure??=clientFailure(message);if(settled)return;if(!exited){try{child.kill(requestedSignal);}catch{}if(!grace)grace=setTimeout(()=>{if(!exited)try{child.kill('SIGKILL');}catch{}},3000);}
25
+ if(!lastResort)lastResort=setTimeout(()=>{child.stdout?.destroy();child.stderr?.destroy();child.unref();finish();},5000);
26
+ };
27
+ const cancel=()=>stop('Client launch cancelled'),interrupt=()=>stop('Client launch interrupted','SIGINT'),terminate=()=>stop('Client launch terminated','SIGTERM');
28
+ const collect=(destination,chunk,channel)=>{
29
+ if(channel==='stdout')stdoutBytes+=chunk.length;else stderrBytes+=chunk.length;
30
+ if((channel==='stdout'?stdoutBytes:stderrBytes)>input.limit){stop('Client '+channel+' exceeds its output cap');return;}destination.push(Buffer.from(chunk));
31
+ };
32
+ child.stdout?.on('data',(chunk)=>collect(stdout,chunk,'stdout'));child.stderr?.on('data',(chunk)=>collect(stderr,chunk,'stderr'));
33
+ child.stdout?.on('error',()=>stop('Client stdout could not be read'));child.stderr?.on('error',()=>stop('Client stderr could not be read'));
34
+ child.once('error',(error)=>{failure=clientFailure(error.code==='ENOENT'?'Client executable is not installed or not on PATH':'Client executable could not be started');});
35
+ child.once('exit',(status,reason)=>{exited=true;code=status;exitSignal=reason;clearTimeout(grace);drain=setTimeout(()=>{failure??=clientFailure('Client output streams did not close after exit');child.stdout?.destroy();child.stderr?.destroy();finish();},1000);});
36
+ child.once('close',(status,reason)=>{if(code===null)code=status;if(exitSignal===null)exitSignal=reason;finish();});
37
+ child.stdin?.on('error',error=>{if(Object(error).code!=='EPIPE')stop('Client stdin could not be written');});if(input.stdin!==undefined)child.stdin?.end(input.stdin);
38
+ deadline=setTimeout(()=>stop('Client execution deadline exceeded'),input.timeout);signal?.addEventListener('abort',cancel,{once:true});if(context.forwardSignals===true){process.on('SIGINT',interrupt);process.on('SIGTERM',terminate);}if(signal?.aborted)cancel();
39
+ try{
40
+ if(typeof context.onSpawn==='function'&&typeof child.pid==='number')try{await context.onSpawn(child.pid);}catch{stop('Client profile launch registration failed');}
41
+ await finished;const result={client_exit_code:code??(exitSignal?128+(Object( constants.signals )[exitSignal]??0):1),signal:exitSignal,stdout:Buffer.concat(stdout).toString('utf8'),stderr:Buffer.concat(stderr).toString('utf8')};
42
+ if(failure){Object.assign(failure,{data:result});throw failure;}return result;
43
+ }finally{clearTimeout(deadline);clearTimeout(grace);clearTimeout(drain);clearTimeout(lastResort);signal?.removeEventListener('abort',cancel);if(context.forwardSignals===true){process.off('SIGINT',interrupt);process.off('SIGTERM',terminate);}child.stdin?.destroy();child.stdout?.destroy();child.stderr?.destroy();}
44
+ }
@@ -0,0 +1,29 @@
1
+ /** Bounded verified profile copies using the native version-one backup manifest shape. */
2
+ import {open,lstat,mkdir,chmod,readdir,copyFile,rename,rm,statfs} from 'node:fs/promises';import {constants} from 'node:fs';import {createHash,randomUUID} from 'node:crypto';import {join,relative,resolve,isAbsolute,dirname} from 'node:path';
3
+ import {clientFailure} from './client-files.mjs';import {requireNativePath,readNativeText} from './operation-input.mjs';import {atomicWrite} from './storage.mjs';
4
+ const hash=(bytes)=>createHash('sha256').update(bytes).digest('hex'),disposable=new Set(['cache','Cache','CachedData','node_modules']);
5
+ function credential(name){name=name.toLowerCase();return ['.claude.json','auth.json','oauth_creds.json','.credentials.json','credentials.json','.env'].includes(name)||['secret','token','keychain'].some(word=>name.includes(word));}
6
+ async function digest(path){
7
+ const file=await open(path,constants.O_RDONLY|(constants.O_NOFOLLOW??0));try{const before=await file.stat();if(!before.isFile()||before.size>67108864)throw clientFailure('Profile file exceeds its 64 MiB backup bound');const value=createHash('sha256'),buffer=Buffer.alloc(65536);let size=0;for(;;){const part=await file.read(buffer,0,buffer.length,null);if(!part.bytesRead)break;size+=part.bytesRead;if(size>67108864)throw clientFailure('Profile file grew beyond its backup bound');value.update(buffer.subarray(0,part.bytesRead));}const after=await file.stat();if(size!==before.size||after.size!==before.size||after.mtimeMs!==before.mtimeMs||after.ctimeMs!==before.ctimeMs)throw clientFailure('Profile file changed during backup hashing');return {sha256:value.digest('hex'),size,mode:before.mode&0o7777};}finally{await file.close();}
8
+ }
9
+ export async function snapshotClientProfile(root,selection={client:'claude',scope:'router',store:'home'},options={}){
10
+ selection={client:selection.client,scope:selection.scope,store:selection.store};await requireNativePath(root);const entries=[];let count=0,total=0,omitted=0;
11
+ const visit=async(path,depth)=>{if(++count>10000||depth>32)throw clientFailure('Profile backup exceeds its entry/depth bound');const name=relative(root,path).split('\\').join('/'),item=await lstat(path);if(!options.allEntries&&name&&name.split('/').some(part=>disposable.has(part)))return;if(!options.allEntries&&item.isFile()&&credential(name?name.split('/').at(-1):path.split('/').at(-1))){omitted++;return;}if(item.isSocket())return;if(item.isSymbolicLink())throw clientFailure('Profile symlink requires the remaining qualified link-copy boundary');if(!item.isFile()&&!item.isDirectory())throw clientFailure('Unsupported special profile entry');if(item.isFile()&&['-wal','-shm','-journal'].some(suffix=>name.endsWith(suffix)))throw clientFailure('Live SQLite sidecar requires the client to close before backup');const row={...selection,path:name,kind:item.isDirectory()?'directory':'file',size:0,sha256:null,link:null,backup_link:null,mode:item.mode&0o7777};if(item.isFile()){Object.assign(row,await digest(path));total+=row.size;if(total>67108864)throw clientFailure('Profile backup exceeds its total 64 MiB bound');}entries.push(row);if(item.isDirectory()){const names=await readdir(path,{encoding:'buffer'});names.sort(Buffer.compare);for(const bytes of names){let child;try{child=new TextDecoder('utf8',{fatal:true}).decode(bytes);}catch{throw clientFailure('Non-UTF8 profile filename is unsupported');}await visit(join(path,child),depth+1);}}};
12
+ await visit(root,0);return {entries,total,omitted};
13
+ }
14
+ function selectedPath(root,path){if(typeof path!=='string'||isAbsolute(path)||path.includes('\\')||path.split('/').some(word=>word==='.'||word==='..')||path.startsWith('/'))throw clientFailure('Backup entry requires a safe relative path');return join(root,path);}
15
+ export async function verifyClientProfileBackup(directory){
16
+ const text=await readNativeText(join(directory,'manifest.json'),{maxBytes:8388608}),checksum=await readNativeText(join(directory,'manifest.sha256'),{maxBytes:128});if(hash(Buffer.from(text))!==checksum)throw clientFailure('Profile backup manifest checksum differs');let manifest;try{manifest=JSON.parse(text);}catch{throw clientFailure('Profile backup manifest is invalid JSON');}
17
+ if(manifest.version!==1||typeof manifest.id!=='string'||!/^[a-f0-9]{32}$/u.test(manifest.id)||!Array.isArray(manifest.entries)||manifest.entries.length>10000||manifest.stores?.length!==1||manifest.credentials_included!==false)throw clientFailure('Profile backup manifest shape differs');const store=manifest.stores[0];if(!['client','scope','store'].every(key=>typeof store[key]==='string'&&/^[a-z0-9-]+$/u.test(store[key])))throw clientFailure('Profile backup store labels differ');const data=join(directory,'data',store.client,store.scope,store.store),seen=new Set();
18
+ for(const row of manifest.entries){if(row.client!==store.client||row.scope!==store.scope||row.store!==store.store||seen.has(row.path))throw clientFailure('Profile backup entries differ');seen.add(row.path);const path=selectedPath(data,row.path);await requireNativePath(path);const item=await lstat(path);if(row.kind==='file'){const actual=await digest(path);if(actual.size!==row.size||actual.sha256!==row.sha256||actual.mode!==row.mode)throw clientFailure('Profile backup file verification failed');}else if(row.kind!=='directory'||!item.isDirectory()||(item.mode&0o7777)!==row.mode)throw clientFailure('Profile backup directory verification failed');}
19
+ const actual=await snapshotClientProfile(data,{client:store.client,scope:store.scope,store:store.store},{allEntries:true});if(JSON.stringify(actual.entries)!==JSON.stringify(manifest.entries))throw clientFailure('Profile backup contains missing or unlisted entries');return manifest;
20
+ }
21
+ export async function createVerifiedClientProfileBackup(profile,backupRoot,selection={client:'claude',scope:'router',store:'home'}){
22
+ profile=resolve(profile);backupRoot=resolve(backupRoot);if(backupRoot===profile||backupRoot.startsWith(profile+'/'))throw clientFailure('Backup destination is inside the selected profile');if(!['client','scope','store'].every(key=>typeof selection[key]==='string'&&/^[a-z0-9-]+$/u.test(selection[key])))throw clientFailure('Profile backup selection requires fixed labels');await requireNativePath(backupRoot);await mkdir(backupRoot,{recursive:true,mode:0o700});await chmod(backupRoot,0o700);
23
+ const before=await snapshotClientProfile(profile,selection),space=await statfs(backupRoot,{bigint:true});if(space.bavail*space.bsize<BigInt(before.total+1048576))throw clientFailure('Profile backup destination lacks space');const id=randomUUID().replaceAll('-',''),temporary=join(backupRoot,'.incomplete-'+id),destination=join(backupRoot,id);await mkdir(temporary,{mode:0o700});const original=await lstat(temporary),data=join(temporary,'data',selection.client,selection.scope,selection.store);
24
+ try{
25
+ for(const row of before.entries){const source=selectedPath(profile,row.path),output=selectedPath(data,row.path);await requireNativePath(source);if(row.kind==='directory'){await mkdir(output,{recursive:true,mode:0o700});}else{await mkdir(dirname(output),{recursive:true,mode:0o700});await copyFile(source,output,constants.COPYFILE_FICLONE);await chmod(output,row.mode);const actual=await digest(output);if(actual.sha256!==row.sha256||actual.size!==row.size)throw clientFailure('Profile changed while copying backup');}}
26
+ for(const row of [...before.entries].reverse())if(row.kind==='directory')await chmod(selectedPath(data,row.path),row.mode);
27
+ if(JSON.stringify(await snapshotClientProfile(profile,selection))!==JSON.stringify(before))throw clientFailure('Profile changed during complete backup');const manifest={version:1,id,created:new Date().toISOString(),credentials_included:false,stores:[{...selection,source:profile}],entries:before.entries,unavailable:[],omitted_credentials:before.omitted},text=JSON.stringify(manifest,null,2);await atomicWrite(join(temporary,'manifest.json'),text);await atomicWrite(join(temporary,'manifest.sha256'),hash(Buffer.from(text)));await verifyClientProfileBackup(temporary);await rename(temporary,destination);return {id,directory:destination,snapshot:before};
28
+ }catch(error){const current=await lstat(temporary).catch(()=>null);if(current&&current.dev===original.dev&&current.ino===original.ino&&!current.isSymbolicLink())await rm(temporary,{recursive:true,force:true,maxRetries:2,retryDelay:100});throw error;}
29
+ }
@@ -0,0 +1,7 @@
1
+ /** Current Router health identity before minting; never sends an admin token. */
2
+ import {sendRemoteManagement} from './remote-operations.mjs';
3
+ import {clientFailure} from './client-files.mjs';
4
+ export async function verifyRemoteClientHealth(context,target){
5
+ const answer=await sendRemoteManagement({server:target.server,managementServer:target.server,managementCaCert:target.caCert},{method:'GET',path:'/api/health',response:'router-health'},{fetch:context.fetch,signal:context.invocation?.signal,deadlineMs:context.healthDeadlineMs??10000,maxOutputBytes:65536,cwd:context.invocation?.cwd});
6
+ if(answer?.status!=='ok'&&typeof answer?.version!=='string')throw clientFailure('Selected inference origin does not identify a Router');
7
+ }
@@ -0,0 +1,55 @@
1
+ /** Persistent remote credentials: live authority, exact client binding, bounded transport. */
2
+ import {clientFailure,clientIntegration} from './client-files.mjs';
3
+ import {parseNativeClientCatalog} from './client-catalog.mjs';
4
+ import {selectedManagedTarget,normalizeManagedOrigin} from './managed-server.mjs';
5
+ import {sendRemoteManagement} from './remote-operations.mjs';
6
+ function tokenClaims(token){
7
+ if(typeof token!=='string'||Buffer.byteLength(token)>65536||!token.startsWith('la_sk_'))throw clientFailure('Remote client token encoding is invalid');const parts=token.slice(6).split('.');if(parts.length!==3||parts.some(part=>!part||!/^[A-Za-z0-9_-]+$/u.test(part)))throw clientFailure('Remote client token encoding is invalid');
8
+ let claims;try{claims=JSON.parse(new TextDecoder('utf-8',{fatal:true}).decode(Buffer.from(parts[1],'base64url')));}catch{throw clientFailure('Remote client token claims are invalid');}
9
+ if(!claims||typeof claims!=='object'||Array.isArray(claims)||typeof claims.sub!=='string'||!claims.sub)throw clientFailure('Remote client token subject is invalid');return claims;
10
+ }
11
+ export function remoteClientTokenBinding(token,client){
12
+ const claims=tokenClaims(token);
13
+ if(claims.scope==='admin'||claims.client_kind!==client||typeof claims.sub!=='string'||!claims.sub||typeof claims.principal_id!=='string'||!claims.principal_id.trim())throw clientFailure('Remote token requires the exact canonical client and subscriber principal');
14
+ // Decoding grants no trust. The live, client-tagged catalog must authenticate it.
15
+ return {token_id:claims.sub,principal_id:claims.principal_id};
16
+ }
17
+ async function remoteTarget(context){
18
+ const {origin,managementServer,config={},env={},invocation={},suppliedToken}=context;const server=normalizeManagedOrigin(origin),management=normalizeManagedOrigin(managementServer);
19
+ const target=await selectedManagedTarget({name:'clients.setup',options:{server,management_server:management},config,env,cwd:invocation.cwd});if(!target)throw clientFailure('Remote client requires a selected Router');
20
+ const token=suppliedToken||target.token;if(typeof token!=='string'||!token.trim()||/[\r\n]/u.test(token)||Buffer.byteLength(token)>65536)throw clientFailure('Remote client requires an administrative or exact client credential');return {...target,token};
21
+ }
22
+ async function catalog(context,target,token){
23
+ const info=clientIntegration(context.client),answer=await sendRemoteManagement({server:target.server,managementServer:target.server,managementCaCert:target.caCert,token},{method:'GET',path:'/api/models',client:info.client},{fetch:context.fetch,signal:context.invocation?.signal,deadlineMs:15000,cwd:context.invocation?.cwd});return parseNativeClientCatalog(answer.data);
24
+ }
25
+ function preferred(client,all){const info=clientIntegration(client),rows=info.owners.flatMap(owner=>all.filter(row=>row.owned_by===owner));return info.owners.length&&(rows.length||info.strict)?rows:all;}
26
+ async function revoke(target,id,context){
27
+ if(typeof id!=='string'||!id||Buffer.byteLength(id)>65536)throw clientFailure('Remote managed token ID is invalid');await sendRemoteManagement(target,{method:'POST',path:'/api/management/tokens/revoke',body:{id}},{fetch:context.fetch,deadlineMs:10000,cwd:context.invocation?.cwd});
28
+ }
29
+ export async function reuseRemoteClientCredential(context,record,token){
30
+ if(record?.router!==normalizeManagedOrigin(context.origin)||record?.management_server!==normalizeManagedOrigin(context.managementServer))return false;
31
+ try{const actual=await authenticateRemoteClientCredential(context,token);return record.client===context.client&&record.token_id===actual.binding.token_id&&record.principal_id===actual.binding.principal_id;}catch(error){if(context.invocation?.signal?.aborted)throw error;return false;}
32
+ }
33
+ async function prepareRemoteCredential(context,run=false){
34
+ const policy=run?validateModelPolicy(context.modelPolicy??{}):{allowed_models:[],allow_substitution:false,substitution_source:null},label=run?(context.label??'with-'+context.client+'-'+randomUUID()):'client-'+context.client;if(typeof label!=='string'||Buffer.byteLength(label)>65536)throw clientFailure('Run label requires bounded text');if(run&&context.maxRequests!=null&&(!Number.isSafeInteger(context.maxRequests)||context.maxRequests<0))throw clientFailure('Run request budget must be a nonnegative safe integer');const target=await remoteTarget(context),ttl=context.ttlHours===undefined?(run?1:24):Number(context.ttlHours);if(!Number.isSafeInteger(ttl)||ttl<1)throw clientFailure('Remote client TTL requires positive safe integer hours');await verifyRemoteClientHealth(context,target);let mint=false;
35
+ try{await sendRemoteManagement(target,{method:'GET',path:'/api/management/tokens'},{fetch:context.fetch,signal:context.invocation?.signal,cwd:context.invocation?.cwd});mint=true;}catch(error){const status=Object(error).status;if(![401,403,404].includes(status))throw error;}
36
+ if(!mint&&run&&policy.allowed_models.length)throw clientFailure('Exact model run policy requires an administrator credential that can mint it');
37
+ let token=target.token,binding,minted=false;
38
+ if(mint){const answer=await sendRemoteManagement(target,{method:'POST',path:'/api/management/tokens/client',body:{ttl_hours:ttl,label,client_kind:context.client,max_requests:run?(context.maxRequests??null):null,sliding_expiry:run&&context.slidingExpiry!==false,ephemeral:run,run_lease:run,allowed_models:policy.allowed_models??[],allow_model_substitution:policy.allow_substitution??false,model_substitution_source:policy.substitution_source??null}},{fetch:context.fetch,signal:context.invocation?.signal,cwd:context.invocation?.cwd});token=answer.token;const claims=tokenClaims(token);try{binding=remoteClientTokenBinding(token,context.client);}catch(error){try{await revoke(target,claims.sub,context);}catch{throw clientFailure('Remote mint returned an invalid client binding; revocation also failed');}throw error;}minted=true;}else binding=remoteClientTokenBinding(token,context.client);
39
+ let cleaned=false;const cleanup=async()=>{if(minted&&!cleaned){await revoke(target,binding.token_id,context);cleaned=true;}};
40
+ try{const models=preferred(context.client,await catalog(context,target,token));return {token,catalog:models,record:{client:context.client,source:minted?'minted':'supplied',...binding,label,issued_at:context.nowUnix??Math.floor(Date.now()/1000),router:target.server,management_server:target.managementServer,config_sha256:null},cleanup,...(run?{runLease:minted,origin:target.server,caCert:target.caCert}:{})};}catch(error){try{await cleanup();}catch{throw clientFailure('Remote client preparation failed; unused minted credential revocation also failed');}throw error;}
41
+ }
42
+ export async function revokeRemoteClientCredential(record,context){
43
+ const target=await remoteTarget({...context,origin:record.router,managementServer:record.management_server});await revoke(target,record.token_id,context);
44
+ }
45
+
46
+ import {verifyRemoteClientHealth} from './client-remote-health.mjs';
47
+
48
+ export async function authenticateRemoteClientCredential(context,token){
49
+ const binding=remoteClientTokenBinding(token,context.client),target=await remoteTarget({...context,suppliedToken:token}),models=preferred(context.client,await catalog(context,target,token));return {binding,catalog:models};
50
+ }
51
+
52
+ import {randomUUID} from 'node:crypto';
53
+ import {validateModelPolicy} from './tokens.mjs';
54
+ export async function prepareRemoteClientCredential(context){return prepareRemoteCredential(context,false);}
55
+ export async function prepareRemoteRunCredential(context){return prepareRemoteCredential(context,true);}