@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,180 @@
1
+ import { join } from 'node:path';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { transactionalWrite, recoverTransactionalWrite, encodeLino, serialized } from './storage.mjs';
4
+ import { rustLockPath, withAdvisoryFileLock } from './file-lock.mjs';
5
+ import { RouterError } from './tokens.mjs';
6
+ import { decodeAffinityFile, validateAffinityValue, exactInteger, integerABI, affinityExpiry, U64_MAX } from './affinity-schema.mjs';
7
+
8
+ const resourceNames = {responses:'responses','chat/completions':'chat',conversations:'conversations',
9
+ 'conversations/items':'conversation_items','realtime/calls':'realtime_calls',files:'files',
10
+ 'messages/batches':'batches',skills:'skills','skills/versions':'skill_versions',
11
+ 'mcp/sessions':'mcp_sessions','plugins/installs':'plugin_installs','plugins/uploads':'plugin_uploads',
12
+ 'workspace/plugins':'workspace_plugins'};
13
+ export function affinityNamespace(namespace) {
14
+ if (typeof namespace !== 'string' || !namespace) throw new RouterError('invalid_argument','Resource namespace is required');
15
+ const codexBackend = /^\/api\/services\/codex\/backend-api\/(plugin-uploads|plugin-installs|public\/plugins\/workspace)$/.exec(namespace);
16
+ if (codexBackend) return { 'plugin-uploads':'codex_plugin_uploads','plugin-installs':'codex_plugin_installs','public/plugins/workspace':'codex_workspace_plugins' }[codexBackend[1]];
17
+ const match = /^\/api\/services\/(openai|anthropic|codex|qwen)\/v1\/(.+)$/.exec(namespace);
18
+ if (!match) return namespace;
19
+ const resource = resourceNames[match[2]];
20
+ if (!resource) throw new RouterError('invalid_argument','Unknown resource namespace');
21
+ return `${match[1] === 'openai' ? 'open_ai' : match[1]}_${resource}`;
22
+ }
23
+ function validId(value) {
24
+ return typeof value === 'string' && value.length > 0 && Buffer.byteLength(value) <= 256 && !/[\/\x00-\x1f\x7f-\x9f]/u.test(value);
25
+ }
26
+ function ownerValue(owner) {
27
+ if (typeof owner === 'object' && owner !== null && typeof owner.client_kind === 'string' && owner.client_kind.trim() &&
28
+ typeof owner.principal_id === 'string' && owner.principal_id.trim()) return {client_kind:owner.client_kind,principal_id:owner.principal_id};
29
+ throw new RouterError('invalid_argument','Resource affinity requires a stable managed-client owner');
30
+ }
31
+ function sameOwner(left, right) { return left.client_kind === right.client_kind && left.principal_id === right.principal_id; }
32
+ function destinationValue(destination) {
33
+ if (!destination || typeof destination.base_url !== 'string') throw new RouterError('invalid_argument','Resource destination is required');
34
+ if (destination.kind === 'stored_provider') return {kind:destination.kind,name:destination.name,provider_kind:persistedProviderKind(destination.provider_kind),base_url:destination.base_url};
35
+ if (destination.kind === 'subscription') return {kind:destination.kind,provider:destination.provider,account:destination.account,
36
+ ...(destination.upstream_account_id != null ? {upstream_account_id:destination.upstream_account_id} : {}),base_url:destination.base_url};
37
+ if (destination.destination_kind === 'stored_provider' || ['openai-compatible','lefine','z.ai-coding-plan'].includes(destination.provider_kind ?? destination.kind)) {
38
+ return {kind:'stored_provider',name:destination.provider,provider_kind:persistedProviderKind(destination.provider_kind ?? destination.kind),base_url:destination.base_url};
39
+ }
40
+ return {kind:'subscription',provider:destination.oauth_provider ?? destination.provider_kind ?? destination.provider,account:destination.account,
41
+ ...(destination.account_id != null ? {upstream_account_id:destination.account_id} : {}),base_url:destination.base_url};
42
+ }
43
+ function persistedProviderKind(kind) { return kind === 'z.ai-coding-plan' ? 'zai-coding-plan' : kind; }
44
+ function sameDestination(left, right) {
45
+ return left.kind === right.kind && left.base_url === right.base_url && (left.kind === 'stored_provider'
46
+ ? left.name === right.name && left.provider_kind === right.provider_kind
47
+ : left.provider === right.provider && left.account === right.account && left.upstream_account_id === right.upstream_account_id);
48
+ }
49
+ function matchesExpectedRecord(record, expected) {
50
+ if (!sameDestination(record.destination,destinationValue(expected.destination ?? expected))) return false;
51
+ // Rust remove_if_matches compares ResponseAffinity itself, including lifetime
52
+ // and owner fields. A view returned by get() carries those original fields;
53
+ // a later identical destination with a different lifetime is another record.
54
+ if (!Object.hasOwn(expected,'response_id')) return true;
55
+ return record.namespace === affinityNamespace(expected.namespace) && record.response_id === expected.response_id &&
56
+ sameOwner(record.owner,expected.owner) && (record.parent_id ?? null) === (expected.parent_id ?? null) &&
57
+ record.created_at === expected.created_at && record.expires_at === expected.expires_at;
58
+ }
59
+ function view(record) {
60
+ if (!record) return null;
61
+ const value = record.destination;
62
+ return {...structuredClone(record),id:record.response_id,destination:value.kind === 'stored_provider'
63
+ ? {provider:value.name,account:value.name,protocol:'openai',provider_kind:value.provider_kind === 'zai-coding-plan' ? 'z.ai-coding-plan' : value.provider_kind,destination_kind:value.kind,base_url:value.base_url}
64
+ : {provider:value.provider,account:value.account,protocol:value.provider === 'claude' ? 'anthropic' : 'responses',
65
+ provider_kind:value.provider,destination_kind:value.kind,base_url:value.base_url,...(value.upstream_account_id != null ? {account_id:value.upstream_account_id} : {})}};
66
+ }
67
+ /** Resource ownership uses Rust's versioned links-notation document. */
68
+ export class AffinityStore {
69
+ constructor({dataDir,persistent = true,clock = () => Math.floor(Date.now()/1000),ttl = 30*24*3600,maxRecords = 10000}) {
70
+ try { exactInteger(ttl,1n,U64_MAX); } catch { throw new RouterError('invalid_config','response-affinity TTL and capacity must be non-zero'); }
71
+ try { maxRecords=integerABI(exactInteger(maxRecords,1n,U64_MAX)); } catch { throw new RouterError('invalid_config','response-affinity TTL and capacity must be non-zero'); }
72
+ this.path = join(dataDir,'response-affinities.lino'); this.persistent = persistent;
73
+ this.clock = clock; this.ttl = ttl; this.maxRecords = maxRecords; this.records = [];
74
+ }
75
+ async load() {
76
+ if (!this.persistent) return validateAffinityValue({version:1,records:structuredClone(this.records)});
77
+ let source;
78
+ try { source = new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(await readFile(this.path)); }
79
+ catch (error) {
80
+ if(error.code === 'ENOENT') return {version:1,records:[]};
81
+ throw new RouterError('invalid_storage',`response-affinity storage failed: ${error.message}`,503);
82
+ }
83
+ let file;
84
+ try { file=decodeAffinityFile(source); }
85
+ catch (error) { throw new RouterError('invalid_storage',`response-affinity document is invalid: ${error.message}`,503); }
86
+ if(file.version!==1)throw new RouterError('invalid_storage',`unsupported response-affinity document version ${file.version}`,503);
87
+ return file;
88
+ }
89
+ async verify() { return this.transaction(() => undefined,{prune:false}); }
90
+ async transaction(operation,{prune=true,now:givenNow}={}) {
91
+ const execute = async () => {
92
+ if (this.persistent) {
93
+ try { await recoverTransactionalWrite(this.path); }
94
+ catch(error) { throw new RouterError('invalid_storage',`response-affinity storage failed: ${error.message}`,503); }
95
+ }
96
+ const file = await this.load();
97
+ const oldLength = file.records.length;
98
+ let now;
99
+ if(prune) {
100
+ now=exactInteger(givenNow ?? this.clock());
101
+ file.records=file.records.filter(record=>exactInteger(record.expires_at)>now);
102
+ }
103
+ const state = {records:file.records,changed:file.records.length !== oldLength,now};
104
+ const result = await operation(state);
105
+ if (state.changed && this.persistent) {
106
+ try { await transactionalWrite(this.path,encodeLino(validateAffinityValue({version:1,records:state.records}))); }
107
+ catch(error) { throw new RouterError('invalid_storage',`response-affinity storage failed: ${error.message}`,503); }
108
+ }
109
+ this.records = state.records;
110
+ return structuredClone(result);
111
+ };
112
+ return serialized(this.path,async () => {
113
+ try { return await (this.persistent ? withAdvisoryFileLock(rustLockPath(this.path),execute) : execute()); }
114
+ catch(error) {
115
+ if(error instanceof RouterError || !error.code)throw error;
116
+ throw new RouterError('invalid_storage',`response-affinity storage failed: ${error.message}`,503);
117
+ }
118
+ });
119
+ }
120
+ async get(namespace,owner,id,parentId) {
121
+ if (!validId(id) || parentId != null && !validId(parentId)) return null;
122
+ let normalized; try { normalized = ownerValue(owner); } catch { return null; }
123
+ namespace = affinityNamespace(namespace);
124
+ return this.transaction(({records}) => {
125
+ const matching = records.filter(record => record.namespace === namespace && record.response_id === id && sameOwner(record.owner,normalized) &&
126
+ (parentId === undefined || record.parent_id === parentId));
127
+ return matching.length === 1 ? view(matching[0]) : null;
128
+ });
129
+ }
130
+ async set(namespace,owner,id,{destination,parent_id,model} = {}) {
131
+ if (!validId(id) || parent_id != null && !validId(parent_id)) throw new RouterError('invalid_argument','Invalid resource id');
132
+ owner = ownerValue(owner); namespace = affinityNamespace(namespace); destination = validateAffinityValue(destinationValue(destination),'AffinityDestination');
133
+ const requestedNow=exactInteger(this.clock());
134
+ return this.transaction(state => {
135
+ const existing = state.records.find(record => record.namespace === namespace && record.response_id === id && sameOwner(record.owner,owner) && (record.parent_id ?? null) === (parent_id ?? null));
136
+ if (existing) {
137
+ if (!sameDestination(existing.destination,destination)) throw new RouterError('affinity_collision','Resource id is bound to another upstream',409);
138
+ // Original Existing returns before flush, including any in-memory prune.
139
+ state.changed=false;
140
+ return view(existing);
141
+ }
142
+ const now = integerABI(state.now);
143
+ const record = validateAffinityValue({namespace,response_id:id,owner,destination,...(parent_id != null ? {parent_id} : {}),created_at:now,expires_at:affinityExpiry(now,this.ttl)},'ResponseAffinity');
144
+ // Model is request metadata; Rust's persistent destination identity does not contain it.
145
+ if (model != null) Object.defineProperty(record,'model',{value:model,enumerable:false});
146
+ state.records.push(record); state.changed = true;
147
+ if (state.records.length > this.maxRecords) {
148
+ state.records.sort((left,right) => left.created_at<right.created_at ? -1 : left.created_at>right.created_at ? 1 : 0);
149
+ state.records.splice(0,state.records.length-this.maxRecords);
150
+ }
151
+ return view(record);
152
+ },{now:requestedNow});
153
+ }
154
+ async delete(namespace,owner,id,parentOrExpected,expected) {
155
+ owner = ownerValue(owner); namespace = affinityNamespace(namespace);
156
+ const parentId = typeof parentOrExpected === 'string' ? parentOrExpected : undefined;
157
+ expected ??= typeof parentOrExpected === 'object' ? parentOrExpected : undefined;
158
+ return this.transaction(state => {
159
+ const oldLength = state.records.length;
160
+ state.records = state.records.filter(record => record.namespace !== namespace || record.response_id !== id || !sameOwner(record.owner,owner) || parentId !== undefined && record.parent_id !== parentId ||
161
+ expected && !matchesExpectedRecord(record,expected));
162
+ state.changed ||= state.records.length !== oldLength;
163
+ return state.records.length !== oldLength;
164
+ },{prune:false});
165
+ }
166
+ async list(namespace,owner,parentId) {
167
+ owner = ownerValue(owner); namespace = affinityNamespace(namespace);
168
+ return this.transaction(({records}) => records.filter(record => record.namespace === namespace && sameOwner(record.owner,owner) &&
169
+ (parentId === undefined || record.parent_id === parentId)).map(view));
170
+ }
171
+ async deleteChildren(namespace,owner,parentId,destination) {
172
+ owner = ownerValue(owner); namespace = affinityNamespace(namespace); destination = destinationValue(destination);
173
+ return this.transaction(state => {
174
+ const oldLength = state.records.length;
175
+ state.records = state.records.filter(record => record.namespace !== namespace || record.parent_id !== parentId || !sameOwner(record.owner,owner) || !sameDestination(record.destination,destination));
176
+ state.changed ||= state.records.length !== oldLength;
177
+ return oldLength-state.records.length;
178
+ },{prune:false});
179
+ }
180
+ }
@@ -0,0 +1,2 @@
1
+ // Checked bounded original serialization schema; generated trait/runtime parity remains unproved.
2
+ export const affinitySchema = {["ProviderKind"]:{["kind"]:"enum",["source"]:"providers.rs::ProviderKind",["variants"]:["openai-compatible","lefine","zai-coding-plan"],["aliases"]:{["open-a-i-compatible"]:"openai-compatible"}},["AffinityDestination"]:{["kind"]:"tagged",["source"]:"response_affinity.rs::AffinityDestination",["tag"]:"kind",["variants"]:{["stored_provider"]:{["kind"]:"struct",["source"]:"response_affinity.rs::AffinityDestination::StoredProvider",["fields"]:[{["name"]:"name",["type"]:"String",["optional"]:false},{["name"]:"provider_kind",["type"]:"ProviderKind",["optional"]:false},{["name"]:"base_url",["type"]:"String",["optional"]:false}]},["subscription"]:{["kind"]:"struct",["source"]:"response_affinity.rs::AffinityDestination::Subscription",["fields"]:[{["name"]:"provider",["type"]:"SubscriptionProvider",["optional"]:false},{["name"]:"account",["type"]:"String",["optional"]:false},{["name"]:"upstream_account_id",["type"]:"String",["optional"]:true},{["name"]:"base_url",["type"]:"String",["optional"]:false}]}}},["AffinityFile"]:{["kind"]:"struct",["source"]:"response_affinity.rs::AffinityFile",["fields"]:[{["name"]:"version",["type"]:"u32",["optional"]:false},{["name"]:"records",["type"]:{["kind"]:"vec",["type"]:"ResponseAffinity"},["optional"]:false}]},["ResponseAffinity"]:{["kind"]:"struct",["source"]:"response_affinity.rs::ResponseAffinity",["fields"]:[{["name"]:"namespace",["type"]:"ResponseNamespace",["optional"]:false},{["name"]:"response_id",["type"]:"String",["optional"]:false},{["name"]:"owner",["type"]:"ResponseOwner",["optional"]:false},{["name"]:"destination",["type"]:"AffinityDestination",["optional"]:false},{["name"]:"parent_id",["type"]:"String",["optional"]:true},{["name"]:"created_at",["type"]:"i64",["optional"]:false},{["name"]:"expires_at",["type"]:"i64",["optional"]:false}]},["ResponseNamespace"]:{["kind"]:"enum",["source"]:"response_affinity.rs::ResponseNamespace",["variants"]:["open_ai_responses","codex_responses","qwen_responses","open_ai_chat","codex_chat","qwen_chat","open_ai_conversations","codex_conversations","qwen_conversations","open_ai_conversation_items","codex_conversation_items","qwen_conversation_items","open_ai_realtime_calls","codex_realtime_calls","anthropic_files","anthropic_batches","anthropic_skills","anthropic_skill_versions","codex_files","codex_mcp_sessions","codex_plugin_installs","codex_plugin_uploads","codex_workspace_plugins"]},["ResponseOwner"]:{["kind"]:"struct",["source"]:"response_affinity.rs::ResponseOwner",["fields"]:[{["name"]:"client_kind",["type"]:"String",["optional"]:false},{["name"]:"principal_id",["type"]:"String",["optional"]:false}]},["SubscriptionProvider"]:{["kind"]:"enum",["source"]:"subscription/types.rs::SubscriptionProvider",["variants"]:["claude","codex","gemini","qwen"]}};
@@ -0,0 +1,185 @@
1
+ import { decodeLino } from './storage.mjs';
2
+
3
+ // Data comes from the shared source-checked Rust serialization metadata.
4
+ import { affinitySchema } from './affinity-schema-descriptor.mjs';
5
+ export { affinitySchema };
6
+ function freezeSchema(node) {
7
+ if(node && typeof node==='object') {for(const child of Object.values(node))freezeSchema(child);Object.freeze(node);}
8
+ }
9
+ freezeSchema(affinitySchema);
10
+ export const I64_MIN = -(1n << 63n), I64_MAX = (1n << 63n)-1n, U64_MAX = (1n << 64n)-1n;
11
+ const SAFE_MIN = BigInt(Number.MIN_SAFE_INTEGER), SAFE_MAX = BigInt(Number.MAX_SAFE_INTEGER);
12
+ const pairs = new WeakMap();
13
+ class JsonNumber { constructor(raw) { this.raw = raw; } }
14
+ function fail(message) { throw new Error(message); }
15
+ // Pinned Rust 1.89 Unicode White_Space (same original table as whitespace-data.mjs).
16
+ const rustWhitespace=character=>typeof character==='string' && /^[\u0009-\u000d\u0020\u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]$/u.test(character);
17
+ export function exactInteger(value, minimum = I64_MIN, maximum = I64_MAX) {
18
+ if (typeof value === 'number' && !Number.isSafeInteger(value) || !['number','bigint'].includes(typeof value)) fail('expected an exact integer');
19
+ const integer = BigInt(value);
20
+ if (integer < minimum || integer > maximum) fail('integer is out of range');
21
+ return integer;
22
+ }
23
+ export function integerABI(value) { return value >= SAFE_MIN && value <= SAFE_MAX ? Number(value) : value; }
24
+ export function affinityExpiry(now, ttl) {
25
+ now = exactInteger(now); ttl = exactInteger(ttl,1n,U64_MAX);
26
+ // Duration.as_secs() is converted/clipped BEFORE saturating addition.
27
+ const sum = now + (ttl > I64_MAX ? I64_MAX : ttl);
28
+ return integerABI(sum > I64_MAX ? I64_MAX : sum);
29
+ }
30
+ function scalarString(value) {
31
+ if (typeof value !== 'string') fail('expected a string');
32
+ for (let i=0;i<value.length;i++) {
33
+ const unit=value.charCodeAt(i);
34
+ if (unit>=0xd800 && unit<=0xdbff) { const next=value.charCodeAt(++i); if (!(next>=0xdc00 && next<=0xdfff)) fail('lone leading surrogate in hex escape'); }
35
+ else if (unit>=0xdc00 && unit<=0xdfff) fail('lone trailing surrogate in hex escape');
36
+ }
37
+ return value;
38
+ }
39
+ function entries(value) {
40
+ if (!value || typeof value!=='object' || Array.isArray(value) || value instanceof JsonNumber) fail('expected a map');
41
+ return pairs.get(value) ?? Object.entries(value);
42
+ }
43
+
44
+ // An iterative JSON reader preserves number lexemes and duplicate fields.
45
+ // Unknown struct values can be ignored without IEEE conversion or a recursive
46
+ // JS parser stack. The generic schema applies the original typed depth limit.
47
+ function lexicalJson(text) {
48
+ let offset=0, root, assigned=false; const stack=[];
49
+ const whitespace=()=>{while(/[\x20\t\r\n]/.test(text[offset]??'') && offset<text.length) offset++;};
50
+ const string=()=>{
51
+ const start=offset++;
52
+ while(offset<text.length) {
53
+ const c=text[offset++];
54
+ if(c==='"') return JSON.parse(text.slice(start,offset));
55
+ if(c==='\\') { if(offset>=text.length)break; offset++; }
56
+ }
57
+ fail('EOF while parsing a string');
58
+ };
59
+ const attach=value=>{
60
+ const frame=stack.at(-1);
61
+ if(!frame) { if(assigned)fail('trailing characters');root=value;assigned=true;return; }
62
+ if(frame.array) frame.value.push(value);
63
+ else { pairs.get(frame.value).push([frame.key,value]);frame.value[frame.key]=value; }
64
+ frame.state='comma';
65
+ };
66
+ const value=()=>{
67
+ whitespace(); const c=text[offset];
68
+ if(c==='{' || c==='[') {
69
+ offset++;const array=c==='[', container=array?[]:Object.create(null);
70
+ if(!array)pairs.set(container,[]);
71
+ attach(container);stack.push({value:container,array,state:'first'});return;
72
+ }
73
+ if(c==='"') { attach(string());return; }
74
+ for(const [word,decoded] of [['null',null],['true',true],['false',false]]) if(text.startsWith(word,offset)) {offset+=word.length;attach(decoded);return;}
75
+ const number=/^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/.exec(text.slice(offset));
76
+ if(number) {offset+=number[0].length;attach(new JsonNumber(number[0]));return;}
77
+ fail('expected value');
78
+ };
79
+ value();
80
+ while(stack.length) {
81
+ whitespace();const frame=stack.at(-1),end=frame.array?']':'}',c=text[offset];
82
+ if(frame.state==='comma') {
83
+ if(c===end) {offset++;stack.pop();continue;}
84
+ if(c!==',')fail('expected comma or end');offset++;frame.state='next';continue;
85
+ }
86
+ if(frame.state==='first' && c===end) {offset++;stack.pop();continue;}
87
+ if(!frame.array) {
88
+ if(c!=='"')fail('key must be a string');frame.key=string();whitespace();
89
+ if(text[offset++]!==':')fail('expected colon');
90
+ }
91
+ value();
92
+ }
93
+ whitespace();if(offset!==text.length)fail('trailing characters');return root;
94
+ }
95
+
96
+ function integer(value,type) {
97
+ const min=type==='u32'?0n:I64_MIN,max=type==='u32'?4294967295n:I64_MAX;
98
+ if(value instanceof JsonNumber) {
99
+ // Pinned serde_json treats negative zero as f64, not the integer zero.
100
+ if(!/^-?\d+$/.test(value.raw) || value.raw==='-0')fail(`invalid type: floating point, expected ${type}`);
101
+ if(value.raw.length>20)fail(`invalid value, expected ${type}`);
102
+ value=BigInt(value.raw);
103
+ }
104
+ try {return integerABI(exactInteger(value,min,max));}
105
+ catch {fail(`invalid type or value, expected ${type}`);}
106
+ }
107
+ function buffered(value,depth,legacy) {
108
+ if(typeof value==='string')scalarString(value);
109
+ else if(value instanceof JsonNumber) {if(!Number.isFinite(Number(value.raw)))fail('number out of range');}
110
+ else if(value && typeof value==='object') {
111
+ if(legacy && depth>=128)fail('recursion limit exceeded');
112
+ if(Array.isArray(value))for(const child of value)buffered(child,depth+1,legacy);
113
+ else for(const [key,child] of entries(value)) {scalarString(key);buffered(child,depth+1,legacy);}
114
+ }
115
+ }
116
+ export function validateAffinityValue(value,type='AffinityFile',{legacy=false}={}) {
117
+ function apply(value,type,depth=1) {
118
+ if(type==='String')return scalarString(value);
119
+ if(type==='i64' || type==='u32')return integer(value,type);
120
+ const spec=typeof type==='string'?affinitySchema[type]:type;
121
+ if(!spec)fail('unknown schema type');
122
+ if(legacy && value && typeof value==='object' && !(value instanceof JsonNumber) && depth>=128)fail('recursion limit exceeded');
123
+ if(spec.kind==='vec') {
124
+ if(!Array.isArray(value))fail('expected a sequence');return value.map(child=>apply(child,spec.type,depth+1));
125
+ }
126
+ if(spec.kind==='enum') {
127
+ if(typeof value!=='string') {
128
+ const fields=entries(value);if(fields.length!==1 || fields[0][1]!==null)fail('expected a unit enum variant');value=fields[0][0];
129
+ }
130
+ scalarString(value);const canonical=spec.aliases?.[value] ?? value;
131
+ if(!spec.variants.includes(canonical))fail(`unknown variant \`${value}\``);return canonical;
132
+ }
133
+ if(spec.kind==='tagged') {
134
+ buffered(value,depth,legacy);
135
+ let tag,content;
136
+ if(Array.isArray(value)) { tag=value[0];content=value.slice(1); }
137
+ else {
138
+ const fields=entries(value),tags=fields.filter(([key])=>key===spec.tag);
139
+ if(tags.length>1)fail(`duplicate field \`${spec.tag}\``);
140
+ if(!tags.length)fail(`missing field \`${spec.tag}\``);
141
+ tag=tags[0][1];content=Object.create(null);pairs.set(content,fields.filter(([key])=>key!==spec.tag));
142
+ }
143
+ scalarString(tag);if(!Object.hasOwn(spec.variants,tag))fail(`unknown variant \`${tag}\``);
144
+ return {[spec.tag]:tag,...apply(content,spec.variants[tag],depth)};
145
+ }
146
+ if(spec.kind==='struct') {
147
+ const fields=spec.fields,result={};let selected;
148
+ if(Array.isArray(value)) {
149
+ if(value.length>fields.length)fail('invalid length for struct');selected=new Map(fields.slice(0,value.length).map((f,i)=>[f.name,value[i]]));
150
+ } else {
151
+ selected=new Map();
152
+ for(const [key,child] of entries(value)) {
153
+ scalarString(key);if(!fields.some(f=>f.name===key))continue;
154
+ if(selected.has(key))fail(`duplicate field \`${key}\``);selected.set(key,child);
155
+ }
156
+ }
157
+ for(const f of fields) {
158
+ if(!selected.has(f.name)) {if(f.optional)continue;fail(`missing field \`${f.name}\``);}
159
+ const child=selected.get(f.name);
160
+ if(f.optional && child===null)continue;
161
+ result[f.name]=apply(child,f.type,depth+1);
162
+ }
163
+ return result;
164
+ }
165
+ fail('unsupported schema node');
166
+ }
167
+ return apply(value,type);
168
+ }
169
+ export function decodeAffinityFile(text) {
170
+ let prefix=0;while(prefix<text.length && rustWhitespace(text[prefix]))prefix++;
171
+ const legacy=text[prefix]==='{' || text[prefix]==='[';
172
+ const value=legacy?lexicalJson(text):decodeLino(text,{scalar:raw=>{
173
+ if(raw==='null')return null;
174
+ if(raw==='true' || raw==='false')return raw==='true';
175
+ if(['NaN','Infinity','-Infinity'].includes(raw))return null;
176
+ // codec0.7 first tries i64::from_str; out-of-range bare decimals remain strings.
177
+ if(/^[+-]?\d+$/.test(raw)) {
178
+ const digits=raw.replace(/^[+-]?0*/,'') || '0';if(digits.length>19)return raw;
179
+ const n=BigInt((raw.startsWith('-')?'-':'')+digits);return n<I64_MIN || n>I64_MAX ? raw : integerABI(n);
180
+ }
181
+ if(/[.eE]/.test(raw) && /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/.test(raw))return Number.isFinite(Number(raw))?new JsonNumber(raw):null;
182
+ return raw;
183
+ },escaped:bytes=>new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(bytes),object:entries=>Object.fromEntries(entries),whitespace:rustWhitespace});
184
+ return validateAffinityValue(value,'AffinityFile',{legacy});
185
+ }
@@ -0,0 +1 @@
1
+ import{n as e}from"./rolldown-runtime.js";import{a as t,i as n,n as r,r as i}from"./react.js";import{A as a,B as o,C as s,D as c,E as l,F as u,G as d,H as f,I as p,L as m,M as h,N as g,O as _,P as v,R as y,S as b,T as x,U as S,V as C,W as w,_ as T,a as ee,b as E,c as D,d as O,f as k,g as A,h as j,i as te,j as M,k as N,l as P,m as F,n as I,o as L,p as R,r as z,s as B,t as V,u as H,v as U,w as W,x as G,y as ne,z as re}from"./ui-vendor.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var K=e(t(),1),q=r(),ie=n(),J=e=>{let{children:t,disabled:n}=e,[r,i]=(0,K.useState)(e.container?.current),a=(0,K.useSyncExternalStore)(oe,()=>!1,()=>!0),{getRootNode:o}=S();if((0,K.useEffect)(()=>{i(()=>e.container?.current)},[e.container]),a||n)return(0,q.jsx)(q.Fragment,{children:t});let s=r??ae(o);return(0,q.jsx)(q.Fragment,{children:K.Children.map(t,e=>(0,ie.createPortal)(e,s))})},ae=e=>{let t=e?.(),n=t.getRootNode();return f(n)?n:C(t).body},oe=()=>()=>{},se=i(),Y=`la_router_admin_token`;function ce(){try{return window.localStorage.getItem(`la_router_admin_token`)||``}catch{return``}}function X(e){try{return window.localStorage.setItem(Y,e),window.localStorage.getItem(Y)===e}catch{return!1}}function le(){try{window.localStorage.removeItem(Y)}catch{}}async function Z(e,{method:t=`GET`,body:n,token:r}={}){let i={};n!==void 0&&(i[`content-type`]=`application/json`),r&&(i.authorization=`Bearer ${r}`);let a=await fetch(e,{method:t,headers:i,body:n===void 0?void 0:JSON.stringify(n)}),o=await a.text(),s=null;if(o)try{s=JSON.parse(o)}catch{s={raw:o}}if(!a.ok){let e=s?.error?.message||s?.raw||a.statusText,t=Error(e);throw t.status=a.status,t.payload=s,t}return s}var Q={status:()=>Z(`/api/management/admin/status`),bootstrap:()=>Z(`/api/management/admin/bootstrap`,{method:`POST`}),confirm:(e,t)=>Z(`/api/management/admin/bootstrap/confirm`,{method:`POST`,body:{claim_id:e},token:t}),rotate:e=>Z(`/api/management/admin/rotate`,{method:`POST`,token:e}),summary:e=>Z(`/api/management/admin/summary`,{token:e}),usage:e=>Z(`/api/management/usage`,{token:e}),accounts:e=>Z(`/api/management/accounts`,{token:e}),listTokens:e=>Z(`/api/management/tokens`,{token:e}),issueToken:(e,t)=>Z(`/api/management/tokens`,{method:`POST`,body:t,token:e}),revokeToken:(e,t)=>Z(`/api/management/tokens/revoke`,{method:`POST`,body:{id:t},token:e}),rotateClientToken:(e,t)=>Z(`/api/management/tokens/rotate-client`,{method:`POST`,body:t,token:e})};function ue({onClaimed:e}){let[t,n]=(0,K.useState)(!1),[r,i]=(0,K.useState)(``),[s,c]=(0,K.useState)(``);async function d(){n(!0),i(``),c(``);try{let t=await Q.bootstrap();if(!X(t.token)){c(t.token),i(`This browser refused to store the token, so the claim was not confirmed. Copy the token below and paste it on the sign-in screen; bootstrap stays open until then.`);return}await Q.confirm(t.claim_id,t.token),e(t.token)}catch(e){i(e.message)}finally{n(!1)}}return(0,q.jsx)(w,{maxW:`640px`,mx:`auto`,mt:`16`,p:`6`,borderWidth:`1px`,borderRadius:`lg`,children:(0,q.jsxs)(W,{gap:`4`,children:[(0,q.jsx)(o,{size:`lg`,children:`Claim this router`}),(0,q.jsx)(u,{color:`fg.muted`,children:`No admin credential is configured yet. The first visitor who successfully stores the admin token becomes the administrator; everyone after that is asked for a token.`}),r?(0,q.jsxs)(h,{status:s?`warning`:`error`,children:[(0,q.jsx)(M,{}),(0,q.jsx)(N,{children:(0,q.jsx)(a,{children:r})})]}):null,s?(0,q.jsx)(x,{p:`3`,whiteSpace:`pre-wrap`,wordBreak:`break-all`,children:s}):null,(0,q.jsx)(l,{onClick:d,loading:t,alignSelf:`flex-start`,children:`Claim admin`}),(0,q.jsx)(u,{fontSize:`sm`,color:`fg.muted`,children:`The token is kept in this browser's localStorage, which any script on this origin can read. Keep the admin port bound to loopback and unshared with the proxy port.`})]})})}function de({onSignedIn:e,provisionedByEnvironment:t}){let[n,r]=(0,K.useState)(``),[i,s]=(0,K.useState)(!1),[c,d]=(0,K.useState)(``);async function f(t){t.preventDefault(),s(!0),d(``);try{await Q.summary(n),X(n),e(n)}catch(e){d(e.status===401?`That token was rejected.`:e.message)}finally{s(!1)}}return(0,q.jsx)(w,{maxW:`560px`,mx:`auto`,mt:`16`,p:`6`,borderWidth:`1px`,borderRadius:`lg`,children:(0,q.jsx)(`form`,{onSubmit:f,children:(0,q.jsxs)(W,{gap:`4`,children:[(0,q.jsx)(o,{size:`lg`,children:`Admin sign-in`}),(0,q.jsx)(u,{color:`fg.muted`,children:t?`This router uses the admin credential provisioned at deploy time (TOKEN_ADMIN_KEY).`:`This router has already been claimed. Present the admin token.`}),c?(0,q.jsxs)(h,{status:`error`,children:[(0,q.jsx)(M,{}),(0,q.jsx)(N,{children:(0,q.jsx)(a,{children:c})})]}):null,(0,q.jsxs)(H,{required:!0,children:[(0,q.jsx)(P,{children:`Admin token`}),(0,q.jsx)(B,{type:`password`,value:n,autoComplete:`off`,onChange:e=>r(e.target.value),placeholder:`la_sk_…`})]}),(0,q.jsx)(l,{type:`submit`,loading:i,disabled:!n,alignSelf:`flex-start`,children:`Sign in`})]})})})}function $({label:e,value:t}){return(0,q.jsxs)(ne,{children:[(0,q.jsx)(E,{children:e}),(0,q.jsx)(G,{children:t??`—`})]})}function fe({token:e}){let[t,n]=(0,K.useState)(null),[r,i]=(0,K.useState)(null),[a,s]=(0,K.useState)(null),[c,l]=(0,K.useState)(``);return(0,K.useEffect)(()=>{let t=!1;return Promise.all([Q.summary(e),Q.usage(e),Q.accounts(e)]).then(([e,r,a])=>{t||(n(e),i(r),s(a))}).catch(e=>!t&&l(e.message)),()=>{t=!0}},[e]),c?(0,q.jsx)(u,{color:`red.500`,children:c}):(0,q.jsxs)(W,{gap:`6`,children:[(0,q.jsxs)(w,{borderWidth:`1px`,borderRadius:`lg`,p:`5`,children:[(0,q.jsx)(o,{size:`md`,mb:`4`,children:`Router`}),(0,q.jsxs)(b,{orientation:`horizontal`,children:[(0,q.jsx)($,{label:`Version`,value:t?.version}),(0,q.jsx)($,{label:`Upstream provider`,value:t?.upstream_provider}),(0,q.jsx)($,{label:`Upstream base URL`,value:t?.upstream_base_url}),(0,q.jsx)($,{label:`Accounts configured`,value:t?.accounts}),(0,q.jsx)($,{label:`Claude credential`,value:t?.claude_credential?(0,q.jsx)(x,{children:t.claude_credential}):`not found`}),(0,q.jsx)($,{label:`Subscription credential`,value:t?.subscription?`${t.subscription.home} (${t.subscription.credential_found?`found`:`missing`})`:`n/a`}),(0,q.jsx)($,{label:`Login API`,value:t?.login_api_enabled?`enabled`:`disabled`}),(0,q.jsx)($,{label:`Admin credential`,value:(0,q.jsx)(_,{colorPalette:t?.admin?.provisioned_by_environment?`blue`:`green`,children:t?.admin?.provisioned_by_environment?`provisioned by env`:`claimed`})})]})]}),(0,q.jsxs)(w,{borderWidth:`1px`,borderRadius:`lg`,p:`5`,children:[(0,q.jsx)(o,{size:`md`,mb:`4`,children:`Usage`}),(0,q.jsx)(b,{orientation:`horizontal`,children:Object.entries(r??{}).map(([e,t])=>(0,q.jsx)($,{label:e,value:typeof t==`object`?JSON.stringify(t):String(t)},e))})]}),(0,q.jsxs)(w,{borderWidth:`1px`,borderRadius:`lg`,p:`5`,children:[(0,q.jsx)(o,{size:`md`,mb:`4`,children:`Accounts`}),a?.accounts?.length?(0,q.jsxs)(ee,{size:`sm`,variant:`outline`,children:[(0,q.jsx)(te,{children:(0,q.jsx)(L,{children:Object.keys(a.accounts[0]).map(e=>(0,q.jsx)(z,{children:e},e))})}),(0,q.jsx)(V,{children:a.accounts.map((e,t)=>(0,q.jsx)(L,{children:Object.values(e).map((e,t)=>(0,q.jsx)(I,{children:typeof e==`object`?JSON.stringify(e):String(e)},t))},e.name??t))})]}):(0,q.jsx)(u,{color:`fg.muted`,children:a?.note??`No accounts configured.`})]})]})}var pe={label:``,ttl_hours:`24`,max_requests:``,max_tokens:``,rate_limit_per_minute:``,account:``};function me(e){if(!e)return`—`;let t=new Date(Number(e)*1e3);return Number.isNaN(t.getTime())?String(e):t.toLocaleString()}function he(e){let t=e.used_requests??0;return e.max_requests?`${t} / ${e.max_requests}`:`${t} / ∞`}function ge(e){let t=e.used_tokens??0,n=e.max_tokens?`${t} / ${e.max_tokens}`:`${t} / ∞`;return e.reserved_tokens?`${n} (+${e.reserved_tokens} held)`:n}function _e(e){return e.revoked?{label:`revoked`,palette:`red`}:e.expires_at&&Number(e.expires_at)*1e3<=Date.now()?{label:`expired`,palette:`orange`}:{label:`active`,palette:`green`}}function ve(e){let t={};for(let n of[`max_requests`,`max_tokens`,`rate_limit_per_minute`])e[n]&&(t[n]=Number(e[n]));return e.account&&(t.account=e.account),t}function ye({token:e}){let[t,n]=(0,K.useState)([]),[r,i]=(0,K.useState)(``),[s,c]=(0,K.useState)(pe),[d,f]=(0,K.useState)(``),[p,m]=(0,K.useState)(!1),[v,y]=(0,K.useState)(null),[b,S]=(0,K.useState)(null),C=(0,K.useCallback)(async()=>{try{let t=await Q.listTokens(e);n(t?.data??[]),i(``)}catch(e){i(e.message)}},[e]);(0,K.useEffect)(()=>{C()},[C]);async function E(t){t.preventDefault(),m(!0);try{let t={label:s.label,ttl_hours:Number(s.ttl_hours)||24,...ve(s)},n=await Q.issueToken(e,t);f(n.token),c(pe),await C()}catch(e){i(e.message)}finally{m(!1)}}async function D(){let t=v;if(y(null),t)try{await Q.revokeToken(e,t.id),await C()}catch(e){i(e.message)}}async function G(){let t=b;if(S(null),t)try{let n=await Q.rotateClientToken(e,{id:t.id});f(n.token),await C()}catch(e){i(e.message)}}return(0,q.jsxs)(W,{gap:`6`,children:[r?(0,q.jsxs)(h,{status:`error`,children:[(0,q.jsx)(M,{}),(0,q.jsx)(N,{children:(0,q.jsx)(a,{children:r})})]}):null,(0,q.jsxs)(w,{borderWidth:`1px`,borderRadius:`lg`,p:`5`,children:[(0,q.jsx)(o,{size:`md`,mb:`4`,children:`Issue a token`}),(0,q.jsx)(`form`,{onSubmit:E,children:(0,q.jsxs)(W,{direction:{base:`column`,md:`row`},gap:`4`,align:`flex-end`,children:[(0,q.jsxs)(H,{children:[(0,q.jsx)(P,{children:`Label`}),(0,q.jsx)(B,{value:s.label,onChange:e=>c({...s,label:e.target.value}),placeholder:`ci-runner`})]}),(0,q.jsxs)(H,{children:[(0,q.jsx)(P,{children:`TTL (hours)`}),(0,q.jsx)(B,{value:s.ttl_hours,onChange:e=>c({...s,ttl_hours:e.target.value}),inputMode:`numeric`})]}),(0,q.jsxs)(H,{children:[(0,q.jsx)(P,{children:`Request cap`}),(0,q.jsx)(B,{value:s.max_requests,onChange:e=>c({...s,max_requests:e.target.value}),placeholder:`unlimited`,inputMode:`numeric`})]}),(0,q.jsxs)(H,{children:[(0,q.jsx)(P,{children:`Token cap`}),(0,q.jsx)(B,{value:s.max_tokens,onChange:e=>c({...s,max_tokens:e.target.value}),placeholder:`unlimited`,inputMode:`numeric`})]}),(0,q.jsxs)(H,{children:[(0,q.jsx)(P,{children:`Requests / minute`}),(0,q.jsx)(B,{value:s.rate_limit_per_minute,onChange:e=>c({...s,rate_limit_per_minute:e.target.value}),placeholder:`unlimited`,inputMode:`numeric`})]}),(0,q.jsxs)(H,{children:[(0,q.jsx)(P,{children:`Account pin`}),(0,q.jsx)(B,{value:s.account,onChange:e=>c({...s,account:e.target.value}),placeholder:`any`})]}),(0,q.jsx)(l,{type:`submit`,loading:p,children:`Issue`})]})}),d?(0,q.jsxs)(h,{status:`success`,mt:`4`,children:[(0,q.jsx)(M,{}),(0,q.jsxs)(N,{children:[(0,q.jsx)(g,{children:`Copy this token now — it is shown only once.`}),(0,q.jsx)(a,{children:(0,q.jsx)(x,{mt:`2`,p:`2`,whiteSpace:`pre-wrap`,wordBreak:`break-all`,children:d})})]})]}):null]}),(0,q.jsxs)(w,{borderWidth:`1px`,borderRadius:`lg`,p:`5`,children:[(0,q.jsx)(o,{size:`md`,mb:`4`,children:`Issued tokens`}),t.length===0?(0,q.jsx)(u,{color:`fg.muted`,children:`No tokens issued yet.`}):(0,q.jsxs)(ee,{size:`sm`,variant:`outline`,children:[(0,q.jsx)(te,{children:(0,q.jsxs)(L,{children:[(0,q.jsx)(z,{children:`ID`}),(0,q.jsx)(z,{children:`Label`}),(0,q.jsx)(z,{children:`Issued`}),(0,q.jsx)(z,{children:`Expires`}),(0,q.jsx)(z,{children:`Requests`}),(0,q.jsx)(z,{children:`Tokens`}),(0,q.jsx)(z,{children:`Req/min`}),(0,q.jsx)(z,{children:`Account`}),(0,q.jsx)(z,{children:`State`}),(0,q.jsx)(z,{})]})}),(0,q.jsx)(V,{children:t.map(e=>(0,q.jsxs)(L,{children:[(0,q.jsx)(I,{fontFamily:`mono`,children:e.id}),(0,q.jsx)(I,{children:e.label||`—`}),(0,q.jsx)(I,{children:me(e.issued_at)}),(0,q.jsx)(I,{children:me(e.expires_at)}),(0,q.jsx)(I,{children:he(e)}),(0,q.jsx)(I,{children:ge(e)}),(0,q.jsx)(I,{children:e.rate_limit_per_minute??`∞`}),(0,q.jsx)(I,{children:e.account||`any`}),(0,q.jsx)(I,{children:(0,q.jsx)(_,{colorPalette:_e(e).palette,children:_e(e).label})}),(0,q.jsx)(I,{children:(0,q.jsxs)(W,{direction:`row`,gap:`2`,children:[(0,q.jsx)(l,{size:`xs`,variant:`outline`,disabled:e.revoked||e.scope===`admin`,onClick:()=>S(e),children:`Rotate`}),(0,q.jsx)(l,{size:`xs`,variant:`outline`,colorPalette:`red`,disabled:e.revoked,onClick:()=>y(e),children:`Revoke`})]})})]},e.id))})]})]}),(0,q.jsx)(T,{open:!!b,onOpenChange:()=>S(null),children:(0,q.jsxs)(J,{children:[(0,q.jsx)(O,{}),(0,q.jsx)(A,{children:(0,q.jsxs)(R,{children:[(0,q.jsx)(j,{children:(0,q.jsx)(U,{children:`Rotate token`})}),(0,q.jsx)(k,{children:(0,q.jsxs)(u,{children:[`Issue a replacement for `,(0,q.jsx)(x,{children:b?.id}),b?.label?` (${b.label})`:``,`? Its limits are kept and the current value is revoked immediately, so anything still using it will start failing.`]})}),(0,q.jsxs)(F,{children:[(0,q.jsx)(l,{variant:`outline`,onClick:()=>S(null),children:`Cancel`}),(0,q.jsx)(l,{onClick:G,children:`Rotate`})]})]})})]})}),(0,q.jsx)(T,{open:!!v,onOpenChange:()=>y(null),children:(0,q.jsxs)(J,{children:[(0,q.jsx)(O,{}),(0,q.jsx)(A,{children:(0,q.jsxs)(R,{children:[(0,q.jsx)(j,{children:(0,q.jsx)(U,{children:`Revoke token`})}),(0,q.jsx)(k,{children:(0,q.jsxs)(u,{children:[`Revoke `,(0,q.jsx)(x,{children:v?.id}),v?.label?` (${v.label})`:``,`? Requests presenting it will be rejected immediately. This cannot be undone.`]})}),(0,q.jsxs)(F,{children:[(0,q.jsx)(l,{variant:`outline`,onClick:()=>y(null),children:`Cancel`}),(0,q.jsx)(l,{colorPalette:`red`,onClick:D,children:`Revoke`})]})]})})]})})]})}function be(){let[e,t]=(0,K.useState)(null),[n,r]=(0,K.useState)(ce()),[i,d]=(0,K.useState)(``),[f,g]=(0,K.useState)(``),[_,v]=(0,K.useState)(!1);(0,K.useEffect)(()=>{Q.status().then(t).catch(e=>d(e.message))},[]),(0,K.useEffect)(()=>{n&&Q.summary(n).catch(e=>{e.status===401&&(le(),r(``))})},[n]);function b(){le(),r(``)}async function S(){v(!0);try{let e=await Q.rotate(n);X(e.token),r(e.token),g(e.token)}catch(e){d(e.message)}finally{v(!1)}}return i&&!e?(0,q.jsx)(s,{maxW:`4xl`,py:`10`,children:(0,q.jsxs)(h,{status:`error`,children:[(0,q.jsx)(M,{}),(0,q.jsx)(N,{children:(0,q.jsx)(a,{children:i})})]})}):e?n?(0,q.jsxs)(s,{maxW:`6xl`,py:`8`,children:[(0,q.jsxs)(W,{gap:`6`,children:[(0,q.jsxs)(D,{justify:`space-between`,align:`center`,wrap:`wrap`,gap:`3`,children:[(0,q.jsxs)(w,{children:[(0,q.jsx)(o,{size:`lg`,children:`Link.Assistant.Router`}),(0,q.jsx)(u,{color:`fg.muted`,children:`Admin`})]}),(0,q.jsxs)(D,{gap:`3`,children:[(0,q.jsx)(l,{variant:`outline`,onClick:S,loading:_,disabled:e.provisioned_by_environment,title:e.provisioned_by_environment?`The credential is provisioned by environment; rotate it at the deployment.`:void 0,children:`Rotate admin credential`}),(0,q.jsx)(l,{variant:`subtle`,onClick:b,children:`Sign out`})]})]}),(0,q.jsxs)(y,{defaultValue:`tokens`,lazyMount:!0,unmountOnExit:!0,children:[(0,q.jsxs)(m,{children:[(0,q.jsx)(re,{value:`tokens`,children:`Tokens`}),(0,q.jsx)(re,{value:`status`,children:`Status`})]}),(0,q.jsx)(p,{value:`tokens`,children:(0,q.jsx)(ye,{token:n})}),(0,q.jsx)(p,{value:`status`,children:(0,q.jsx)(fe,{token:n})})]})]}),(0,q.jsx)(T,{open:!!f,onOpenChange:()=>g(``),children:(0,q.jsxs)(J,{children:[(0,q.jsx)(O,{}),(0,q.jsx)(A,{children:(0,q.jsxs)(R,{children:[(0,q.jsx)(j,{children:(0,q.jsx)(U,{children:`New admin credential`})}),(0,q.jsxs)(k,{children:[(0,q.jsx)(u,{mb:`3`,children:`The previous credential is retired. This value is shown once — it is already stored in this browser, but save it somewhere you can recover from.`}),(0,q.jsx)(x,{p:`2`,whiteSpace:`pre-wrap`,wordBreak:`break-all`,children:f})]}),(0,q.jsx)(F,{children:(0,q.jsx)(l,{onClick:()=>g(``),children:`Done`})})]})})]})})]}):e.bootstrap_open?(0,q.jsx)(ue,{onClaimed:e=>{r(e),Q.status().then(t).catch(()=>{})}}):(0,q.jsx)(de,{onSignedIn:r,provisionedByEnvironment:e.provisioned_by_environment}):(0,q.jsx)(D,{minH:`60vh`,align:`center`,justify:`center`,children:(0,q.jsx)(c,{size:`lg`})})}(0,se.createRoot)(document.getElementById(`root`)).render((0,q.jsx)(K.StrictMode,{children:(0,q.jsx)(d,{value:v,children:(0,q.jsx)(be,{})})}));