@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,105 @@
1
+ {
2
+ "$defs": {},
3
+ "$id": "link-assistant-router/with/v1",
4
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
5
+ "additionalProperties": false,
6
+ "allOf": [
7
+ {
8
+ "else": {
9
+ "properties": {
10
+ "exit_code": {
11
+ "minimum": 1,
12
+ "type": "integer"
13
+ }
14
+ }
15
+ },
16
+ "if": {
17
+ "properties": {
18
+ "success": {
19
+ "const": true
20
+ }
21
+ }
22
+ },
23
+ "then": {
24
+ "properties": {
25
+ "exit_code": {
26
+ "const": 0
27
+ }
28
+ }
29
+ }
30
+ }
31
+ ],
32
+ "properties": {
33
+ "data": {
34
+ "anyOf": [
35
+ {
36
+ "additionalProperties": false,
37
+ "properties": {
38
+ "client_exit_code": {
39
+ "type": [
40
+ "integer",
41
+ "null"
42
+ ]
43
+ },
44
+ "stderr": {
45
+ "type": "string"
46
+ },
47
+ "stdout": {
48
+ "type": "string"
49
+ }
50
+ },
51
+ "required": [
52
+ "client_exit_code",
53
+ "stdout",
54
+ "stderr"
55
+ ],
56
+ "type": "object"
57
+ },
58
+ {
59
+ "additionalProperties": false,
60
+ "properties": {
61
+ "output": {
62
+ "items": {
63
+ "type": "string"
64
+ },
65
+ "type": "array"
66
+ }
67
+ },
68
+ "required": [
69
+ "output"
70
+ ],
71
+ "type": "object"
72
+ }
73
+ ]
74
+ },
75
+ "diagnostics": {
76
+ "items": {
77
+ "type": "string"
78
+ },
79
+ "type": "array"
80
+ },
81
+ "exit_code": {
82
+ "maximum": 255,
83
+ "minimum": 0,
84
+ "type": "integer"
85
+ },
86
+ "operation": {
87
+ "const": "with"
88
+ },
89
+ "schema": {
90
+ "const": "link-assistant-router/with/v1"
91
+ },
92
+ "success": {
93
+ "type": "boolean"
94
+ }
95
+ },
96
+ "required": [
97
+ "schema",
98
+ "operation",
99
+ "success",
100
+ "exit_code",
101
+ "data",
102
+ "diagnostics"
103
+ ],
104
+ "type": "object"
105
+ }
@@ -0,0 +1,233 @@
1
+ import { cooldownActive } from '../portable/policy.mjs';
2
+ import { atomicWrite, readOptional, serialized } from './storage.mjs';
3
+ import { RouterError } from './tokens.mjs';
4
+
5
+ const strategyAliases = new Map([
6
+ ['rr','round-robin'],['roundrobin','round-robin'],['weighted_round_robin','weighted-round-robin'],
7
+ ['prio','priority'],['fill-first','priority'],['leastused','least-used'],['quota-first','least-used'],['lru','least-used'],
8
+ ]);
9
+ export const retryableStatus = status => [401,429,529,500,502,503,504].includes(status);
10
+ export function requestErrorAction(policy,status,body) {
11
+ const prefix=Buffer.from(body ?? '').subarray(0,16384);
12
+ return policy.request_scoped_errors.find(rule=>rule.status===status && prefix.indexOf(Buffer.from(rule.match))>=0)?.action;
13
+ }
14
+ const subscriptionKinds=new Set(['anthropic','claude','codex','gemini','qwen','vertex','vertex-ai','bedrock']);
15
+ const storedKinds=new Set(['openai-compatible','openai','litellm','lefine','z.ai-coding-plan']);
16
+ export function principalAccountName(account,provider) {return account.implicit && subscriptionKinds.has(provider?.kind)?'primary':account.name;}
17
+ /** Explicit internal pins select physical accounts; token principals select subscription accounts. */
18
+ export function principalAccountScope(records,providers,context={}) {
19
+ const pin=context.pinnedAccount ?? context.pinned_account,principal=context.principalAccount,byProvider=new Map(providers.map(provider=>[provider.name,provider]));
20
+ return new Map([...records].filter(([,account])=>{const provider=byProvider.get(account.provider);return provider && (pin?account.name===pin:!principal || storedKinds.has(provider.kind) || principalAccountName(account,provider)===principal);}));
21
+ }
22
+ export function wildcardMatch(pattern, value) {
23
+ const regex = pattern.split('').map(c => c === '*' ? '.*' : c === '?' ? '.' : c.replace(/[\\^$.[\]{}()+|]/g,'\\$&')).join('');
24
+ return new RegExp(`^${regex}$`).test(value);
25
+ }
26
+ export function validateAccountPolicy(policy = {}) {
27
+ const p = { weight:1, prefix:null, disable_cooling:false, request_retry:null, request_scoped_errors:[], headers:{}, model_aliases:[], excluded_models:[], ...policy };
28
+ if (!Number.isInteger(p.weight) || p.weight > 1000000 || p.request_retry != null && (!Number.isSafeInteger(p.request_retry) || p.request_retry < 0 || p.request_retry > 100)) throw new RouterError('invalid_policy','Invalid policy weight or retry');
29
+ if (p.prefix != null && (typeof p.prefix !== 'string' || !p.prefix || p.prefix.includes('/') || /\s/.test(p.prefix))) throw new RouterError('invalid_policy','Account prefix must be one nonempty path component');
30
+ if (!Array.isArray(p.excluded_models) || p.excluded_models.some(m => typeof m !== 'string')) throw new RouterError('invalid_policy','Invalid excluded_models');
31
+ if (!Array.isArray(p.model_aliases) || p.model_aliases.some(a => typeof a.model !== 'string' || !a.model.trim() || typeof a.alias !== 'string' || !a.alias.trim() || a.alias === a.model)) throw new RouterError('invalid_policy','Invalid model aliases');
32
+ if (new Set(p.model_aliases.map(a => a.alias)).size !== p.model_aliases.length) throw new RouterError('invalid_policy','Aliases must be unique');
33
+ if (!Array.isArray(p.request_scoped_errors) || p.request_scoped_errors.some(e => !Number.isInteger(e.status) || e.status < 100 || e.status > 599 || typeof e.match !== 'string' || Buffer.byteLength(e.match) > 16384 || !['relay','retry-next','cooldown'].includes(e.action))) throw new RouterError('invalid_policy','Invalid request scoped error rule');
34
+ // Authentication and transport headers cannot be overwritten by operator tags.
35
+ const protectedHeader = /^(authorization|proxy-authorization|cookie|set-cookie|x-api-key|x-goog-api-key|anthropic-auth-token|chatgpt-account-id|host|connection|content-length|content-encoding|transfer-encoding|upgrade|te|trailer|proxy-authenticate|keep-alive|x-router-.*|x-link-assistant-.*)$/i;
36
+ const copyHeaders = new Set(['x-request-id','x-correlation-id','traceparent','tracestate','x-claude-code-session-id','x-codex-session-id','x-session-id','session-id']);
37
+ if (!p.headers || typeof p.headers !== 'object') throw new RouterError('invalid_policy','Invalid policy headers');
38
+ for (const [name,value] of Object.entries(p.headers)) {
39
+ if (protectedHeader.test(name) || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name) || typeof value !== 'string' || /[\r\n\0]/.test(value)) throw new RouterError('invalid_policy','Policy headers cannot replace authentication or transport headers');
40
+ if (value.startsWith('$') && !copyHeaders.has(value.slice(1).toLowerCase())) throw new RouterError('invalid_policy','Policy header copy source is not allowed');
41
+ }
42
+ return p;
43
+ }
44
+ export function accountVisibleModels(account, upstream) {
45
+ const p = account.policy;
46
+ const excluded = model => p.excluded_models.some(pattern => wildcardMatch(pattern,model));
47
+ if (excluded(upstream)) return [];
48
+ const aliases = p.model_aliases.filter(alias => alias.model === upstream);
49
+ const models = aliases.map(alias => alias.alias);
50
+ if (!aliases.length || aliases.some(alias => alias.fork)) models.push(upstream);
51
+ const visible = [];
52
+ for (const model of models) {
53
+ if (!excluded(model)) visible.push({ selector:model, model:upstream });
54
+ if (p.prefix && !excluded(`${p.prefix}/${model}`)) visible.push({ selector:`${p.prefix}/${model}`,model:upstream });
55
+ }
56
+ return visible;
57
+ }
58
+ export class AccountRouter {
59
+ constructor({ config, clock = () => Math.floor(Date.now()/1000) }) {
60
+ this.config = config; this.clock = clock; this.cursor = 0; this.failoverCursor = 0; this.affinities = new Map(); this.weights = new Map();
61
+ this.strategy = strategyAliases.get(config.account_strategy) ?? config.account_strategy;
62
+ if (!['round-robin','weighted-round-robin','priority','least-used'].includes(this.strategy)) throw new RouterError('invalid_config','Unknown account selection strategy');
63
+ this.records = new Map(); this.limits = new Map(); this.used = new Map();
64
+ for (const account of config.accounts) {
65
+ if (!account.name || this.records.has(account.name)) throw new RouterError('invalid_config','Account names must be nonempty and unique');
66
+ if (account.request_limit != null && (!Number.isSafeInteger(account.request_limit) || account.request_limit < 0)) throw new RouterError('invalid_config','Account request_limit must be nonnegative');
67
+ this.records.set(account.name,{ ...account,policy:validateAccountPolicy(account.policy) });
68
+ }
69
+ // Physical provider keys stay distinct; implicit subscription accounts expose logical primary.
70
+ for (const provider of config.providers) if (![...this.records.values()].some(a => a.provider === provider.name && (!subscriptionKinds.has(provider.kind) || a.name==='primary'))) {
71
+ if(this.records.has(provider.name))throw new RouterError('invalid_config','An implicit provider account collides with a named account');
72
+ this.records.set(provider.name,{name:provider.name,provider:provider.name,policy:validateAccountPolicy(),implicit:true});
73
+ }
74
+ }
75
+ async load() {
76
+ for (const account of this.records.values()) if (account.home) {
77
+ const policy = await readOptional(`${account.home}/routing-policy.json`);
78
+ if (policy) account.policy = validateAccountPolicy(JSON.parse(policy));
79
+ }
80
+ if (this.config.storage_policy === 'memory') return this;
81
+ const saved = JSON.parse(await readOptional(`${this.config.data_dir}/account-limits.json`,'null'));
82
+ if (saved) for (const [name,state] of Object.entries(saved.accounts ?? {})) if (this.records.get(name)?.provider === saved.provider) this.limits.set(name,state);
83
+ return this;
84
+ }
85
+ async persist() {
86
+ if (this.config.storage_policy === 'memory') return;
87
+ const providers = [...new Set([...this.records.values()].map(a => a.provider))];
88
+ // Rust account-limits.json is a single-provider projection. Do not write a
89
+ // novel multiplexed format or clobber another provider's persisted state.
90
+ if (providers.length !== 1) return;
91
+ const accounts = Object.fromEntries(this.limits);
92
+ await atomicWrite(`${this.config.data_dir}/account-limits.json`,JSON.stringify({provider:providers[0],accounts}));
93
+ }
94
+ serves(name, model, excluded = []) {
95
+ const a = this.records.get(name), state = this.limits.get(name) ?? {}, now = this.clock();
96
+ if (!a || a.enabled === false || excluded.includes(name) || (a.request_limit != null && (this.used.get(name) ?? 0) >= a.request_limit)) return false;
97
+ if (state.pause && (state.pause.until_unix == null || cooldownActive(state.pause.until_unix,now))) return false;
98
+ if (a.policy.disable_cooling) return true;
99
+ if (cooldownActive(state.cooldown_until_unix ?? 0,now)) return false;
100
+ const lower = (model ?? '').toLowerCase();
101
+ return !Object.entries(state.model_cooldowns ?? {}).some(([key,until]) => cooldownActive(until,now) && (key === lower || ['haiku','sonnet','opus'].includes(key) && lower.includes(key)));
102
+ }
103
+ bound(context) {
104
+ const session = context.sessionKey ?? context.session_key;
105
+ const parent = context.parentSessionKey ?? context.parent_session_key;
106
+ for (const key of [session,parent]) {
107
+ const binding = this.affinities.get(key);
108
+ if (binding?.until > this.clock()) return binding.name;
109
+ this.affinities.delete(key);
110
+ }
111
+ return null;
112
+ }
113
+ order(candidates, context = {}) {
114
+ const pin = context.pinnedAccount ?? context.pinned_account;
115
+ const exclude = context.exclude ?? [];
116
+ const eligible = candidates.filter(c => this.serves(c.account,c.model,exclude));
117
+ if (pin) {
118
+ if (!this.records.has(pin)) throw new RouterError('unknown_pinned_account',`Unknown account '${pin}'`,404);
119
+ const selected = eligible.filter(c => c.account === pin);
120
+ if (!selected.length) throw new RouterError('pinned_account_unavailable',`Pinned account '${pin}' is unavailable`,503);
121
+ return selected;
122
+ }
123
+ const bound = this.bound(context);
124
+ if (bound) {
125
+ const preferred = eligible.filter(c => c.account === bound);
126
+ if (preferred.length) return [...preferred,...eligible.filter(c => c.account !== bound)];
127
+ const account = this.records.get(bound);
128
+ const hasPolicy = account && JSON.stringify(account.policy) !== JSON.stringify(validateAccountPolicy());
129
+ if (!this.config.account_failover && !hasPolicy) throw new RouterError('session_account_unavailable',`Session account '${bound}' is unavailable`,503);
130
+ }
131
+ if (!eligible.length) throw new RouterError('no_healthy_accounts','No healthy accounts',503);
132
+ if (bound || exclude.length) {
133
+ const start = this.failoverCursor++ % eligible.length;
134
+ return [...eligible.slice(start),...eligible.slice(0,start)];
135
+ }
136
+ if (this.strategy === 'round-robin') {
137
+ const start = this.cursor++ % eligible.length; return [...eligible.slice(start),...eligible.slice(0,start)];
138
+ }
139
+ if (this.strategy === 'least-used') return eligible.slice().sort((a,b) => {
140
+ const left = this.records.get(a.account), right = this.records.get(b.account), l = this.used.get(a.account) ?? 0, r = this.used.get(b.account) ?? 0;
141
+ if (left.request_limit != null && right.request_limit != null) return l*right.request_limit-r*left.request_limit || l-r;
142
+ if (left.request_limit != null) return -1;
143
+ if (right.request_limit != null) return 1;
144
+ return l-r;
145
+ });
146
+ if (this.strategy === 'weighted-round-robin') {
147
+ const active = eligible.filter(c => this.records.get(c.account).policy.weight > 0);
148
+ if (!active.length) throw new RouterError('no_healthy_accounts','No positive-weight accounts',503);
149
+ let total = 0, selected = active[0], largest = -Infinity;
150
+ const seen = new Set();
151
+ for (const candidate of active) {
152
+ if (seen.has(candidate.account)) continue; seen.add(candidate.account);
153
+ const weight = this.records.get(candidate.account).policy.weight;
154
+ total += weight; const current = (this.weights.get(candidate.account) ?? 0)+weight;
155
+ this.weights.set(candidate.account,current);
156
+ if (current > largest) { largest = current; selected = candidate; }
157
+ }
158
+ for (const name of this.weights.keys()) if (!seen.has(name)) this.weights.set(name,0);
159
+ this.weights.set(selected.account,largest-total);
160
+ return [selected,...active.filter(c => c !== selected)];
161
+ }
162
+ return eligible;
163
+ }
164
+ recordUse(candidate, context = {}) {
165
+ if (!this.serves(candidate.account,candidate.model,context.exclude)) throw new RouterError('account_unavailable','Account became unavailable',503);
166
+ this.used.set(candidate.account,(this.used.get(candidate.account) ?? 0)+1);
167
+ const session = context.sessionKey ?? context.session_key;
168
+ const old = this.bound(context);
169
+ if (session && this.config.session_affinity_ttl_seconds > 0) this.affinities.set(session,{name:old ?? candidate.account,until:this.clock()+this.config.session_affinity_ttl_seconds});
170
+ }
171
+ async reportFailure(candidate, { status, retryAfter, scope = 'account', message = '', body } = {}) {
172
+ const account = this.records.get(candidate.account); if (!account) return;
173
+ const action=requestErrorAction(account.policy,status,body ?? message);
174
+ if (action === 'relay' || action === 'retry-next') return action;
175
+ if (status != null && !retryableStatus(status) && action !== 'cooldown') return 'relay';
176
+ if (account.policy.disable_cooling) return action === 'cooldown'?'cooldown':'retry-next';
177
+ let seconds = typeof retryAfter==='number' || typeof retryAfter==='string' && /^\d+$/.test(retryAfter.trim()) ? Number(retryAfter):NaN;
178
+ if (!Number.isFinite(seconds) && typeof retryAfter === 'string') seconds = Math.ceil((Date.parse(retryAfter)-this.clock()*1000)/1000);
179
+ if (!Number.isFinite(seconds) || seconds < 0) seconds = this.config.account_cooldown_seconds;
180
+ const until = this.clock()+Math.min(seconds,this.config.account_max_cooldown_seconds);
181
+ return serialized(this,async () => {
182
+ const state = this.limits.get(candidate.account) ?? {model_cooldowns:{}};
183
+ if (scope === 'model') { const key = candidate.model.toLowerCase(); state.model_cooldowns ??= {}; state.model_cooldowns[key] = Math.max(state.model_cooldowns[key] ?? 0,until); }
184
+ else { state.cooldown_until_unix = Math.max(state.cooldown_until_unix ?? 0,until); state.cooldown_reason = message || `HTTP ${status ?? 'network failure'}`; }
185
+ this.limits.set(candidate.account,state); await this.persist(); return action === 'cooldown'?'cooldown':'retry-next';
186
+ });
187
+ }
188
+ async reportSuccess(candidate) { const state = this.limits.get(candidate.account); if (state) { state.last_error = null; } }
189
+ setStrategy(value) {
190
+ const strategy = strategyAliases.get(value.trim().toLowerCase()) ?? value.trim().toLowerCase();
191
+ if (!['round-robin','weighted-round-robin','priority','least-used'].includes(strategy)) throw new RouterError('invalid_argument','Unknown routing strategy');
192
+ this.strategy = strategy;
193
+ return {strategy:strategy === 'priority' ? 'fill-first' : strategy};
194
+ }
195
+ async resetCooldowns(account, model) {
196
+ if (model != null && account == null || account != null && !account.trim() || model != null && !model.trim()) throw new RouterError('invalid_argument','A model reset requires a nonempty account and model');
197
+ if (account != null && !this.records.has(account)) throw new RouterError('not_found','Account not found',404);
198
+ return serialized(this,async () => {
199
+ let cleared = 0;
200
+ for (const [name,state] of this.limits) {
201
+ if (account != null && account !== name) continue;
202
+ const active = Object.entries(state.model_cooldowns ?? {}).filter(([,until]) => until > this.clock());
203
+ state.model_cooldowns = Object.fromEntries(active);
204
+ if (state.cooldown_until_unix != null && state.cooldown_until_unix <= this.clock()) { delete state.cooldown_until_unix; delete state.cooldown_reason; }
205
+ if (model != null) {
206
+ const key = model.toLowerCase();
207
+ if (Object.hasOwn(state.model_cooldowns,key)) { cleared++; delete state.model_cooldowns[key]; }
208
+ } else {
209
+ cleared += (state.cooldown_until_unix != null ? 1 : 0)+active.length;
210
+ delete state.cooldown_until_unix; delete state.cooldown_reason; state.model_cooldowns = {};
211
+ }
212
+ }
213
+ await this.persist(); return {cleared};
214
+ });
215
+ }
216
+ async list() { return [...this.records.values()].map(a => ({ name:a.name,provider:a.provider,request_limit:a.request_limit ?? null,used_requests:this.used.get(a.name) ?? 0,healthy:this.serves(a.name),policy:structuredClone(a.policy),limits:structuredClone(this.limits.get(a.name) ?? {}) })); }
217
+ async pause(name, { reason = 'Operator pause', until_unix = null } = {}) {
218
+ if (!this.records.has(name)) throw new RouterError('not_found','Account not found',404);
219
+ if (until_unix != null && (!Number.isSafeInteger(until_unix) || until_unix <= this.clock())) throw new RouterError('invalid_argument','Pause expiry must be a future timestamp');
220
+ return serialized(this,async () => { const state = this.limits.get(name) ?? {}; state.pause = {kind:'manual',reason,until_unix}; this.limits.set(name,state); await this.persist(); return {name,...state}; });
221
+ }
222
+ async resume(name) {
223
+ if (!this.records.has(name)) throw new RouterError('not_found','Account not found',404);
224
+ return serialized(this,async () => { const state = this.limits.get(name) ?? {}; delete state.pause; this.limits.set(name,state); await this.persist(); return {name,...state}; });
225
+ }
226
+ async policy(name, policy) {
227
+ const account = this.records.get(name); if (!account) throw new RouterError('not_found','Account not found',404);
228
+ account.policy = validateAccountPolicy(policy);
229
+ // Rust keeps each policy next to its account home.
230
+ if (account.home) await atomicWrite(`${account.home}/routing-policy.json`,JSON.stringify(account.policy));
231
+ return {name,policy:structuredClone(account.policy)};
232
+ }
233
+ }
@@ -0,0 +1,23 @@
1
+ const ROOT='/api/services/activitypub';
2
+ const context=['https://www.w3.org/ns/activitystreams','https://forgefed.org/ns',{'fep':'https://w3id.org/fep/ef61#',aliases:'fep:aliases'}];
3
+ export const defaultActivityPublicKey='-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEA0000000000000000000000000000000000000000000=\n-----END PUBLIC KEY-----';
4
+ export function activityDocument(path,config={}) {
5
+ const base=(config.activitypub_actor_base_url ?? `http://${config.host ?? '127.0.0.1'}:${config.port ?? 3000}`).replace(/\/+$/,'');
6
+ const actor=`${base}${ROOT}/actor/code`;
7
+ if(path === `${ROOT}/actor/code`)return {'@context':context,id:actor,type:'Service',preferredUsername:'code',name:'Link Assistant Code Router',summary:'ActivityPub and ForgeFed service actor for coding problem federation',inbox:`${base}${ROOT}/inbox/code`,outbox:`${base}${ROOT}/outbox/code`,followers:`${base}${ROOT}/actors/code/followers`,aliases:['urn:link-assistant:router:code',actor],publicKey:{id:`${actor}#main-key`,owner:actor,publicKeyPem:config.activitypub_public_key_pem ?? defaultActivityPublicKey}};
8
+ if([`${ROOT}/outbox/code`,`${ROOT}/actors/code/followers`].includes(path))return {'@context':context,id:base+path,type:'OrderedCollection',totalItems:0,orderedItems:[]};
9
+ if(path === `${ROOT}/activities/follow-problemsets-code-001`)return {'@context':context,id:base+path,type:'Follow',actor,object:'https://problemsets.lefine.pro/actor/code',to:['https://problemsets.lefine.pro/actor/code']};
10
+ }
11
+ export async function activityResponse(request,config,readJSON) {
12
+ const path=new URL(request.url).pathname;
13
+ const reply=(value,status=200)=>new Response(JSON.stringify(value),{status,headers:{'content-type':'application/activity+json',accept:'application/activity+json'}});
14
+ if(request.method === 'GET') {const document=activityDocument(path,config);if(document)return reply(document);}
15
+ if(request.method === 'POST' && path === `${ROOT}/inbox/code`) {
16
+ const body=await readJSON(request);
17
+ let message;
18
+ for(const field of ['id','type'])if(typeof body?.[field] !== 'string' || !body[field].trim()){message=`activity ${field} is required`;break;}
19
+ if(!message && typeof body?.actor !== 'string' && typeof body?.attributedTo !== 'string')message='activity must include actor or attributedTo';
20
+ if(message)return new Response(JSON.stringify({error:'invalid_activity',message}),{status:400,headers:{'content-type':'application/json'}});
21
+ return reply({'@context':context,type:'Accept',object:body},202);
22
+ }
23
+ }
@@ -0,0 +1,16 @@
1
+ import {readFile,lstat} from 'node:fs/promises';
2
+ import {extname,resolve} from 'node:path';
3
+ import {fileURLToPath} from 'node:url';
4
+ const mime={'.html':'text/html; charset=utf-8','.js':'text/javascript; charset=utf-8','.mjs':'text/javascript; charset=utf-8','.css':'text/css; charset=utf-8','.json':'application/json','.svg':'image/svg+xml','.png':'image/png','.ico':'image/x-icon','.woff2':'font/woff2'};
5
+ const security={'content-security-policy':"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",'x-frame-options':'DENY','x-content-type-options':'nosniff','referrer-policy':'no-referrer'};
6
+ export function hardenAdmin(response) {for(const [name,value] of Object.entries(security))response.headers.set(name,value);return response;}
7
+ export async function serveAdminAsset(request,{directory=fileURLToPath(new URL('./assets/admin/',import.meta.url))}={}) {
8
+ const path=new URL(request.url).pathname;
9
+ if(path.startsWith('/api/'))return new Response('not found',{status:404});
10
+ const root=resolve(directory),relative=path.replace(/^\/+|\/+$/g,'') || 'index.html';
11
+ let target=resolve(root,relative);if(target!==root && !target.startsWith(root+'/'))return new Response('not found',{status:404});
12
+ const load=async file=>{const stat=await lstat(file);if(!stat.isFile() || stat.isSymbolicLink() || stat.size>4*1024*1024)throw new Error('invalid asset');return readFile(file);};
13
+ let bytes;
14
+ try{bytes=await load(target);}catch{target=resolve(root,'index.html');try{bytes=await load(target);}catch{return new Response('admin UI bundle is missing from this build',{status:500});}}
15
+ return new Response(bytes,{headers:{'content-type':mime[extname(target)] ?? 'application/octet-stream','cache-control':'no-cache, must-revalidate'}});
16
+ }
package/src/admin.mjs ADDED
@@ -0,0 +1,108 @@
1
+ import { randomUUID,createHash,timingSafeEqual } from 'node:crypto';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { atomicWrite,decodeLino,encodeLino,readOptional,serialized } from './storage.mjs';
5
+ import { rustLockPath,withAdvisoryFileLock } from './file-lock.mjs';
6
+ import { RouterError } from './tokens.mjs';
7
+
8
+ const digest = value => createHash('sha256').update(value).digest('hex');
9
+ function equal(left,right) { const a = Buffer.from(left ?? ''), b = Buffer.from(right ?? ''); return a.length === b.length && timingSafeEqual(a,b); }
10
+ const ttl = hours => Number.isSafeInteger(hours) && hours > 0 ? Math.min(hours,8760) : 8760;
11
+ const claimed = file => Boolean(file.token_id || file.token_sha256);
12
+ const refuse = (code,message,status) => { throw new RouterError(code,message,status); };
13
+
14
+ /** Rust's two-phase claim: mint revoked, confirm possession, then activate. */
15
+ export class AdminClaim {
16
+ constructor(core,{candidateTtl = 120,env = core.env} = {}) {
17
+ this.core = core; this.path = join(core.config.data_dir,'admin-claim.json');
18
+ this.persistent = core.config.storage_policy !== 'memory'; this.candidateTtl = candidateTtl;
19
+ this.envKey = core.config.token_admin_key ?? core.config.admin_key ?? env.TOKEN_ADMIN_KEY ?? null;
20
+ this.file = {}; this.candidate = null; this.queue = {};
21
+ }
22
+ async load() {
23
+ if (this.persistent) {
24
+ const source = await readOptional(this.path,null);
25
+ if (source != null) {
26
+ try {
27
+ const parsed = source.trimStart().startsWith('{') ? JSON.parse(source) : decodeLino(source);
28
+ if (parsed && claimed(parsed)) this.file = parsed;
29
+ } catch { /* Rust loads invalid legacy claim documents as unclaimed. */ }
30
+ }
31
+ }
32
+ if (this.candidate && this.candidate.expires_at <= this.core.clock()) this.candidate = null;
33
+ return this.file;
34
+ }
35
+ async transaction(operation) {
36
+ return serialized(this.queue,() => this.persistent ? withAdvisoryFileLock(rustLockPath(this.path),async () => { await this.load(); return operation(); }) : operation());
37
+ }
38
+ async persist(file) { if (this.persistent) await atomicWrite(this.path,encodeLino(file)); this.file = file; }
39
+ status() {
40
+ return this.transaction(async () => {
41
+ await this.load(); const provisioned = Boolean(this.envKey), active = provisioned || claimed(this.file);
42
+ return {claimed:active,bootstrap_open:!active,provisioned_by_environment:provisioned,candidate_pending:Boolean(this.candidate),
43
+ claimed_at:this.file.claimed_at ?? null,credential_kind:provisioned ? 'environment' : this.file.token_id ? 'jwt' : this.file.token_sha256 ? 'legacy_opaque' : 'none',
44
+ ...(this.file.token_id ? {token_id:this.file.token_id} : {})};
45
+ });
46
+ }
47
+ async verify(bearer) {
48
+ if (typeof bearer !== 'string' || !bearer) return false;
49
+ if (this.envKey && equal(this.envKey,bearer)) return true;
50
+ await this.load();
51
+ if (this.file.token_id) {
52
+ try { return (await this.core.tokens.validate(bearer,{admin:true})).sub === this.file.token_id; } catch { return false; }
53
+ }
54
+ return Boolean(this.file.token_sha256 && equal(this.file.token_sha256,digest(bearer)));
55
+ }
56
+ async beginWithTtl(hours) {
57
+ return this.transaction(async () => {
58
+ await this.load();
59
+ if (this.envKey) refuse('already_claimed','An admin credential is provisioned by environment',409);
60
+ if (claimed(this.file)) refuse('already_claimed','Admin is already claimed',409);
61
+ const ttlHours = ttl(hours), issued = await this.core.tokens.issue({scope:'admin',label:'first-visitor-admin',ttl_hours:ttlHours});
62
+ await this.core.tokens.revoke(issued.id);
63
+ const claimId = randomUUID();
64
+ this.candidate = {claim_id:claimId,token_sha256:digest(issued.token),token_id:issued.id,ttl_hours:ttlHours,expires_at:this.core.clock()+this.candidateTtl};
65
+ return {claim_id:claimId,token:issued.token,expires_in_secs:this.candidateTtl,ttl_hours:ttlHours,confirm_url:'/api/management/admin/bootstrap/confirm'};
66
+ });
67
+ }
68
+ async confirm(claimId,bearer) {
69
+ return this.transaction(async () => {
70
+ await this.load();
71
+ if (this.envKey || claimed(this.file)) refuse('already_claimed','Admin bootstrap is closed',409);
72
+ const candidate = this.candidate;
73
+ if (!candidate) refuse('invalid_request_error','No outstanding bootstrap candidate',400);
74
+ if (!equal(candidate.claim_id,claimId)) refuse('invalid_request_error','claim_id does not match the outstanding candidate',400);
75
+ if (typeof bearer !== 'string' || !equal(candidate.token_sha256,digest(bearer))) refuse('authentication_error','Presented token does not match the outstanding candidate',401);
76
+ const file = {token_sha256:'',token_id:candidate.token_id,ttl_hours:candidate.ttl_hours,claimed_at:this.core.clock()};
77
+ await this.persist(file);
78
+ await this.core.tokens.store.transaction(records => {
79
+ const active = records.get(candidate.token_id);
80
+ if (!active) refuse('api_error','Candidate token record is unavailable',500);
81
+ active.revoked = false;
82
+ for (const record of records.values()) if (record.scope === 'admin' && record.id !== active.id) record.revoked = true;
83
+ });
84
+ this.candidate = null;
85
+ return {claimed:true};
86
+ });
87
+ }
88
+ async rotate(bearer,hours) {
89
+ return this.transaction(async () => {
90
+ await this.load();
91
+ if (this.envKey) refuse('already_claimed','Rotate the environment credential at deployment',409);
92
+ if (!claimed(this.file)) refuse('invalid_request_error','No claimed admin credential',400);
93
+ if (!await this.verify(bearer)) refuse('authentication_error','Active admin credential is required',401);
94
+ const ttlHours = hours == null && this.file.ttl_hours > 0 ? this.file.ttl_hours : ttl(hours);
95
+ const issued = this.file.token_id ? await this.core.tokens.rotate(this.file.token_id,{ttl_hours:ttlHours,label:'first-visitor-admin'}) : await this.core.tokens.issue({scope:'admin',label:'first-visitor-admin',ttl_hours:ttlHours});
96
+ await this.persist({token_sha256:'',token_id:issued.id,ttl_hours:ttlHours,claimed_at:this.core.clock()}); this.candidate = null;
97
+ return {token:issued.token,token_id:issued.id,credential_kind:'jwt'};
98
+ });
99
+ }
100
+ async summary() {
101
+ const credentials = this.core.credentialStatus ? await this.core.credentialStatus() : null;
102
+ const version = JSON.parse(await readFile(new URL('../package.json',import.meta.url),'utf8')).version;
103
+ return {version,upstream_provider:this.core.config.upstream_provider ?? 'claude',
104
+ upstream_base_url:this.core.config.upstream_base_url ?? 'https://api.anthropic.com',accounts:this.core.accounts.records.size,
105
+ claude_credential:credentials?.credentials?.claude?.path ?? null,subscription:null,login_api_enabled:Boolean(this.core.login),
106
+ admin:await this.status(),management_bans:this.core.managementAccess?.activeBans() ?? [],emergency_auth:this.core.emergency?.status() ?? null};
107
+ }
108
+ }