agl 43.4.0 → 43.6.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 (45) hide show
  1. package/changelog.md +27 -0
  2. package/dist_serve/bundle.js +2250 -2240
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_serve/bundle.js.third-party-notices.json +29 -29
  5. package/dist_serve/bundle.js.third-party-notices.txt +29 -29
  6. package/dist_ts/00_commitinfo_data.js +1 -1
  7. package/dist_ts/classes.controller.d.ts +10 -1
  8. package/dist_ts/classes.controller.js +17 -2
  9. package/dist_ts/classes.inferencegateway.js +14 -2
  10. package/dist_ts/classes.inferencerouter.d.ts +9 -1
  11. package/dist_ts/classes.inferencerouter.js +68 -14
  12. package/dist_ts/fleet/classes.claudeworkers.d.ts +8 -5
  13. package/dist_ts/fleet/classes.claudeworkers.js +13 -8
  14. package/dist_ts/functions.claudecoderelease.d.ts +1 -1
  15. package/dist_ts/functions.claudecoderelease.js +1 -1
  16. package/dist_ts/functions.inferencecli.js +10 -2
  17. package/dist_ts/functions.inferencelaunch.d.ts +19 -8
  18. package/dist_ts/functions.inferencelaunch.js +23 -12
  19. package/dist_ts/functions.proxyharnessconfig.d.ts +18 -0
  20. package/dist_ts/functions.proxyharnessconfig.js +30 -1
  21. package/dist_ts_authswitch/authority-renewal.d.ts +12 -3
  22. package/dist_ts_authswitch/authority-renewal.js +14 -5
  23. package/dist_ts_authswitch/classes.claudenative.d.ts +8 -8
  24. package/dist_ts_authswitch/classes.claudenative.js +13 -13
  25. package/dist_ts_interfaces/requests.accounts.d.ts +5 -0
  26. package/dist_ts_interfaces/requests.accounts.js +3 -1
  27. package/docs/authswitch.md +5 -4
  28. package/package.json +2 -2
  29. package/readme.md +20 -10
  30. package/ts/00_commitinfo_data.ts +1 -1
  31. package/ts/classes.controller.ts +16 -1
  32. package/ts/classes.inferencegateway.ts +15 -1
  33. package/ts/classes.inferencerouter.ts +72 -13
  34. package/ts/fleet/classes.claudeworkers.ts +12 -7
  35. package/ts/functions.claudecoderelease.ts +1 -1
  36. package/ts/functions.inferencecli.ts +7 -1
  37. package/ts/functions.inferencelaunch.ts +35 -14
  38. package/ts/functions.proxyharnessconfig.ts +32 -0
  39. package/ts_authswitch/authority-renewal.ts +14 -4
  40. package/ts_authswitch/classes.claudenative.ts +12 -12
  41. package/ts_authswitch/native-contracts.md +250 -28
  42. package/ts_interfaces/requests.accounts.ts +2 -0
  43. package/ts_web/00_commitinfo_data.ts +1 -1
  44. package/ts_web/classes.accountsreadmodel.ts +49 -17
  45. package/ts_web/elements.accounts.ts +31 -18
@@ -166,6 +166,18 @@ const writeStreamCut = (cutArg: IInferenceGatewayStreamCut): void => {
166
166
  + `${cutArg.cause} (${cutArg.error})\n`);
167
167
  };
168
168
 
169
+ /**
170
+ * The proxy's journal line for a provider 429 (AGL-1797): the account by its id's first twelve characters, the model,
171
+ * and what the provider stated -- its `Retry-After` and its rate-limit headers, which name the limit that was met. The
172
+ * Codex turn-state token is left out (`isCodexResponseHeader`): it routes one turn on the account that issued it.
173
+ */
174
+ const writeProvider429 = (routeArg: { provider: string; accountId: string; model: { modelId: string } }, headersArg: Headers): void => {
175
+ const stated = [...headersArg].filter(([name]) => name === 'retry-after' || name.startsWith('anthropic-ratelimit-')
176
+ || name.startsWith('x-ratelimit-') || isCodexResponseHeader(name)).map(([name, value]) => `${name}=${value.slice(0, 80)}`);
177
+ process.stderr.write(`AGL proxy met a provider 429 (${routeArg.provider}) on account ${routeArg.accountId.slice(0, 12)} for `
178
+ + `${routeArg.model.modelId}: ${stated.length ? stated.join(', ') : 'no Retry-After or rate-limit header'}\n`);
179
+ };
180
+
169
181
  const refusalRepeatWindowMs = 60_000;
170
182
 
171
183
  /**
@@ -1106,7 +1118,9 @@ export class InferenceGateway {
1106
1118
  }
1107
1119
  if (response.status === 429) {
1108
1120
  const seconds = this.options.router.retryAfterSeconds(response.headers);
1109
- this.options.router.reportQuota(route.accountId, seconds);
1121
+ this.options.router.reportQuota(route.accountId, seconds,
1122
+ route.provider === 'anthropic' && route.credential === 'subscription' ? route.model.modelId : undefined);
1123
+ writeProvider429(route, response.headers);
1110
1124
  exhaustedPlans.add(route.plan);
1111
1125
  quotaError = new InferenceRoutingError(429, 'accounts_exhausted', 'The eligible accounts reached their provider limits.',
1112
1126
  seconds, [...exhaustedPlans]);
@@ -315,17 +315,50 @@ interface ICooldown {
315
315
  }
316
316
 
317
317
  /**
318
- * When an account's cool-down ends, judged against its held usage: a cool-down the provider's `Retry-After` named runs
319
- * its course; a default one ends once the account service holds a usage read made after the 429, which then decides --
320
- * an exhausted window until its reset, as the shared rule says. While that read is pending the cool-down holds, so
321
- * sessions still move.
318
+ * The longest `Retry-After` that names a rate limit, which no usage reading shows: five minutes. A longer one names a
319
+ * usage window, which the account service reads and the owner can reset (AGL-1797).
320
+ */
321
+ const rateLimitRestMs = 300_000;
322
+
323
+ /** Whether the provider's `Retry-After` named a rate limit's short rest, which runs its course whatever a reading says. */
324
+ const rateLimitRest = (cooldownArg: ICooldown): boolean =>
325
+ cooldownArg.explicit && cooldownArg.until - cooldownArg.at <= rateLimitRestMs;
326
+
327
+ /** Whether the account service holds a usage read made after the 429 the cool-down is from. */
328
+ const readSince = (cooldownArg: ICooldown,
329
+ usageArg: plugins.authswitchAuthority.IAuthSwitchUsageSnapshot | undefined): boolean => {
330
+ const readAt = usageArg?.readAt ? Date.parse(usageArg.readAt) : Number.NaN;
331
+ return Number.isFinite(readAt) && readAt > cooldownArg.at;
332
+ };
333
+
334
+ /**
335
+ * When an account's cool-down ends, judged against its held usage: a short one the provider's `Retry-After` named (a
336
+ * rate limit, at most five minutes) runs its course; a default one, and one whose `Retry-After` named a usage window's
337
+ * wait, ends once the account service holds a usage read made after the 429, which then decides -- an exhausted window
338
+ * until its reset, as the shared rule says, and an account whose limit was reset or raised meanwhile routes at once
339
+ * (AGL-1797). While that read is pending the cool-down holds, so sessions still move. Without a reading to judge
340
+ * (an API key) every cool-down runs its course.
322
341
  */
323
342
  const cooldownUntil = (cooldownArg: ICooldown | undefined,
324
343
  usageArg: plugins.authswitchAuthority.IAuthSwitchUsageSnapshot | undefined): number => {
325
344
  if (!cooldownArg) return 0;
326
- if (cooldownArg.explicit) return cooldownArg.until;
327
- const readAt = usageArg?.readAt ? Date.parse(usageArg.readAt) : Number.NaN;
328
- return Number.isFinite(readAt) && readAt > cooldownArg.at ? 0 : cooldownArg.until;
345
+ if (rateLimitRest(cooldownArg)) return cooldownArg.until;
346
+ return readSince(cooldownArg, usageArg) ? 0 : cooldownArg.until;
347
+ };
348
+
349
+ /**
350
+ * When one model's rest on a Claude sign-in ends (AGL-1797). A 429 whose `Retry-After` names a usage window's wait may be
351
+ * a feature window's (one model family's weekly use), which the account's limit leaves out as the reading does not say
352
+ * which models it covers: so it rests only the model that met it, and the account's other models keep routing. It ends
353
+ * once a usage read made after the 429 shows no feature window used up -- a reset limit routes at once -- and else at
354
+ * its stated time. An account window used up is the reading's to say, for every model.
355
+ */
356
+ const modelCooldownUntil = (cooldownArg: ICooldown | undefined,
357
+ usageArg: plugins.authswitchAuthority.IAuthSwitchUsageSnapshot | undefined): number => {
358
+ if (!cooldownArg) return 0;
359
+ if (!readSince(cooldownArg, usageArg)) return cooldownArg.until;
360
+ const windows = usageArg?.reading?.kind === 'anthropic' ? usageArg.reading.status.windows ?? [] : [];
361
+ return windows.some((windowArg) => windowArg.scope === 'feature' && (windowArg.usedPercent ?? 0) >= 100) ? cooldownArg.until : 0;
329
362
  };
330
363
 
331
364
  /**
@@ -959,6 +992,8 @@ export class InferenceRouter {
959
992
  private readonly noted = new Map<string, { unavailable: IInferenceAccountUnavailable; lastCatalog: boolean }>();
960
993
  private readonly active = new Map<string, number>();
961
994
  private readonly cooldowns = new Map<string, ICooldown>();
995
+ /** Each Claude sign-in's models resting after a 429 that named a usage window's wait (`modelCooldownUntil`). */
996
+ private readonly modelCooldowns = new Map<string, Map<string, ICooldown>>();
962
997
  /**
963
998
  * The accounts a payment problem took out of rotation (`reportPaymentProblem`): a Claude account until the account
964
999
  * service holds the problem -- one it could not be told of stays here for the proxy's lifetime -- and an API key until
@@ -1020,6 +1055,7 @@ export class InferenceRouter {
1020
1055
  for (const cacheKey of cache.keys()) if (!known.has(cacheKey.slice(0, 64))) cache.delete(cacheKey);
1021
1056
  }
1022
1057
  for (const id of this.cooldowns.keys()) if (!known.has(id)) this.cooldowns.delete(id);
1058
+ for (const id of this.modelCooldowns.keys()) if (!known.has(id)) this.modelCooldowns.delete(id);
1023
1059
  for (const id of this.noted.keys()) if (!known.has(id)) this.noted.delete(id);
1024
1060
  return { accounts, eligible: new Set(allAccounts.map((account) => account.id)), lapsed, tiers };
1025
1061
  }
@@ -1678,7 +1714,8 @@ export class InferenceRouter {
1678
1714
  this.noteAccount(accountArg.id, null);
1679
1715
  }
1680
1716
  if (optionsArg.plans && !optionsArg.plans.includes(limitsArg.plan)) return undefined;
1681
- const cooldown = cooldownUntil(this.cooldowns.get(accountArg.id), apiKey ? undefined : usageArg);
1717
+ const cooldown = Math.max(cooldownUntil(this.cooldowns.get(accountArg.id), apiKey ? undefined : usageArg),
1718
+ modelCooldownUntil(this.modelCooldowns.get(accountArg.id)?.get(optionsArg.modelId), usageArg));
1682
1719
  if (!optionsArg.ignoreLimits && (limitsArg.state !== 'available' || cooldown > this.now())) {
1683
1720
  const held = this.heldList(optionsArg.lists, accountArg);
1684
1721
  if (held && !held.some((entry) => entry.modelId === optionsArg.modelId)) return refused({ reason: 'model_missing' });
@@ -1998,8 +2035,8 @@ export class InferenceRouter {
1998
2035
  : state === 'cooling' ? 'cooling down after a provider 429'
1999
2036
  : state === 'unavailable' && refusal ? `unavailable (${unavailableText(refusal)})`
2000
2037
  : apiKey ? keyStateText(limits, held, now)
2001
- : limits.limit ? plugins.authswitchUsageLimit.authSwitchUsageLimitText(limits.limit)
2002
- : 'available (no usage reported)',
2038
+ : `${limits.limit ? plugins.authswitchUsageLimit.authSwitchUsageLimitText(limits.limit)
2039
+ : 'available (no usage reported)'}${this.modelRestText(account.id, held, now)}`,
2003
2040
  plan: limits.plan || null, headroom: limits.limit?.headroom ?? null, crossing: limits.limit?.crossing ?? [],
2004
2041
  resetAt: state === 'cooling' ? new Date(cooldown).toISOString() : limits.limit?.resetAt ?? null };
2005
2042
  });
@@ -2027,7 +2064,18 @@ export class InferenceRouter {
2027
2064
  usageArg: plugins.authswitchAuthority.IAuthSwitchUsageSnapshot | undefined): { lastAt: number | null; restUntil: number } {
2028
2065
  const cooldown = this.cooldowns.get(accountArg.id);
2029
2066
  const until = cooldownUntil(cooldown, accountArg.credential === 'api_key' ? undefined : usageArg);
2030
- return { lastAt: cooldown?.at ?? null, restUntil: until > this.now() ? until : 0 };
2067
+ // One model's rest leaves the account's room for other work, so it counts as a 429 the pool met, never as a rest.
2068
+ const lastAt = Math.max(cooldown?.at ?? 0, ...[...this.modelCooldowns.get(accountArg.id)?.values() ?? []].map((rest) => rest.at));
2069
+ return { lastAt: lastAt || null, restUntil: until > this.now() ? until : 0 };
2070
+ }
2071
+
2072
+ /** The models of an account that rest now after a provider 429, as `agl proxy status` adds them to its state. */
2073
+ private modelRestText(accountIdArg: string, usageArg: plugins.authswitchAuthority.IAuthSwitchUsageSnapshot | undefined,
2074
+ nowArg: number): string {
2075
+ const resting = [...this.modelCooldowns.get(accountIdArg) ?? []]
2076
+ .map(([modelId, rest]) => ({ modelId, until: modelCooldownUntil(rest, usageArg) }))
2077
+ .filter((rest) => rest.until > nowArg);
2078
+ return resting.map((rest) => `; ${rest.modelId} rests after a provider 429 until ${new Date(rest.until).toISOString()}`).join('');
2031
2079
  }
2032
2080
 
2033
2081
  /** Counts one request on an account until its release, which may be called more than once. */
@@ -2139,12 +2187,23 @@ export class InferenceRouter {
2139
2187
  * seconds or until the account service holds a usage read made after the 429 (see `cooldownUntil`), which the 429
2140
2188
  * asks it to make at once. An API key, whose spend reading says nothing of the provider's rate limits, cools down
2141
2189
  * the 60 seconds.
2190
+ *
2191
+ * `claudeModelIdArg` names the model a Claude sign-in's request asked for. A `Retry-After` beyond five minutes then
2192
+ * rests that model alone (`modelCooldownUntil`): it may be the wait of one model family's weekly window, and the
2193
+ * account's other models keep routing (AGL-1797). A usage read after the 429 ends either rest when it shows room.
2142
2194
  */
2143
- public reportQuota(accountIdArg: string, retryAfterSecondsArg?: number): void {
2195
+ public reportQuota(accountIdArg: string, retryAfterSecondsArg?: number, claudeModelIdArg?: string): void {
2144
2196
  const explicit = Number.isFinite(retryAfterSecondsArg) && retryAfterSecondsArg! > 0;
2145
2197
  const delay = explicit ? Math.min(retryAfterSecondsArg!, 86_400) : 60;
2146
2198
  const now = this.now();
2147
- this.cooldowns.set(accountIdArg, { until: now + delay * 1000, at: now, explicit });
2199
+ const cooldown: ICooldown = { until: now + delay * 1000, at: now, explicit };
2200
+ if (claudeModelIdArg !== undefined && explicit && !rateLimitRest(cooldown) && !this.apiKeyAccounts.has(accountIdArg)) {
2201
+ const models = this.modelCooldowns.get(accountIdArg) ?? new Map<string, ICooldown>();
2202
+ models.set(claudeModelIdArg, cooldown);
2203
+ this.modelCooldowns.set(accountIdArg, models);
2204
+ } else {
2205
+ this.cooldowns.set(accountIdArg, cooldown);
2206
+ }
2148
2207
  if (!this.apiKeyAccounts.has(accountIdArg)) this.options.rateLimited?.(accountIdArg);
2149
2208
  }
2150
2209
  }
@@ -1,6 +1,7 @@
1
1
  import * as plugins from '../plugins.js';
2
2
  import { resolveControllerTerminalAgentTranscript } from '../functions.terminalagents.js';
3
3
  import { fleetWorkerPath, resolveClaudeWorkerExecutable } from '../functions.workerprocessproof.js';
4
+ import { dropClaudeHookSwitches } from '../functions.proxyharnessconfig.js';
4
5
  import type { IFleetWorker, IFleetWorkerProfile, IFleetWorkerReport, IFleetWorkerTurnOutcome, IFleetRelaunchBlocker, IFleetWorkerAbsenceProof, IFleetWorkerSessionProof, IFleetWorkerRebindProof } from '../../ts_interfaces/fleetworkers.js';
5
6
  import { controllerSessionFeedExcerpt, type IControllerMessageBundle, type IControllerNativeWait } from '../../ts_interfaces/index.js';
6
7
  import { claudePage, claudeTranscript } from '../classes.claudeprojection.js';
@@ -53,8 +54,8 @@ export const fleetClaudeVersion = (result: IFleetWorkerCommand): string => {
53
54
  /** Claude colours its output when FORCE_COLOR is set, through a pipe too; its control sequences are no text. */
54
55
  const plain = (text: string): string => text.replace(/\u001b\[[0-?]*[ -/]*[@-~]/gu, '');
55
56
  /**
56
- * The short id of the background job a `claude --bg` start or wake printed (AGL-796). Claude Code 2.1.282 and 2.1.306
57
- * print `backgrounded · <id>`, then ` · <name>` only for a named job and ` (idle — …)` for one without a prompt, then
57
+ * The short id of the background job a `claude --bg` start or wake printed (AGL-796). Claude Code 2.1.282, 2.1.306 and
58
+ * 2.1.322 print `backgrounded · <id>`, then ` · <name>` only for a named job and ` (idle — …)` for one without a prompt, then
58
59
  * the commands that reach the job, one per line.
59
60
  */
60
61
  export const fleetClaudeBackgrounded = (result: IFleetWorkerCommand): string | undefined => /backgrounded\s*·\s*([a-zA-Z0-9]+)(?=\s|$)/u.exec(plain(`${result.stdout}\n${result.stderr}`))?.[1];
@@ -100,8 +101,8 @@ const claudeObservedTurn = (nativeId: string, agent: TClaudeAgent | undefined, r
100
101
  return { ...turn, ...(outcome ? { outcome } : {}) };
101
102
  };
102
103
  /**
103
- * The permission modes a Claude Code transcript records and `--permission-mode` takes: Claude Code 2.1.282 and 2.1.306
104
- * know `acceptEdits`, `auto`, `bypassPermissions`, `default`, `dontAsk` and `plan`, and read `manual` as `default`
104
+ * The permission modes a Claude Code transcript records and `--permission-mode` takes: Claude Code 2.1.282, 2.1.306 and
105
+ * 2.1.322 know `acceptEdits`, `auto`, `bypassPermissions`, `default`, `dontAsk` and `plan`, and read `manual` as `default`
105
106
  * (AGL-797).
106
107
  */
107
108
  const modes = new Set(['acceptEdits', 'auto', 'bypassPermissions', 'default', 'dontAsk', 'manual', 'plan']);
@@ -115,8 +116,8 @@ const address = (inventory: TClaudeAgent[], agent: TClaudeAgent): string => {
115
116
  };
116
117
 
117
118
  /**
118
- * Version-coupled transcript interpretation stays here. It was verified on Claude Code 2.1.306 and on 2.1.282, the
119
- * fleet's floor, whose output the tests still pin; a newer release is used optimistically and these parsers are its
119
+ * Version-coupled transcript interpretation stays here. It was verified on Claude Code 2.1.322, 2.1.306 and on 2.1.282,
120
+ * the fleet's floor, whose output the tests still pin; a newer release is used optimistically and these parsers are its
120
121
  * checks at the point of use, failing visibly where its output changed. An older or unreadable version is refused
121
122
  * (`fleetClaudeVersion`).
122
123
  */
@@ -297,9 +298,13 @@ export class FleetClaudeWorkers implements IFleetWorkerBackend {
297
298
  /** Told each release newer than the verified one that a verified executable runs, once per executable identity. */
298
299
  private readonly observeRelease?: (releaseArg: string) => void,
299
300
  ) {}
300
- /** Workers inherit this environment; their tooling finds the controller's own node even when a service manager started it. */
301
+ /**
302
+ * Workers inherit this environment; their tooling finds the controller's own node even when a service manager started it.
303
+ * It holds no hook switch (`dropClaudeHookSwitches`), so the hooks of the profile's user settings run in every worker.
304
+ */
301
305
  private env(profile: Pick<IFleetWorkerProfile, 'home'>): NodeJS.ProcessEnv {
302
306
  const env: NodeJS.ProcessEnv = { ...process.env, PATH: fleetWorkerPath() }; delete env.AGL_HOME; if (profile.home) env.CLAUDE_CONFIG_DIR = profile.home;
307
+ dropClaudeHookSwitches(env);
303
308
  return env;
304
309
  }
305
310
  private async supportedExecutable(profile: Pick<IFleetWorkerProfile, 'home'>, cwd: string): Promise<string> {
@@ -8,7 +8,7 @@
8
8
  */
9
9
 
10
10
  /** The newest Claude Code release AGL verified: the line above which a release is new and mentioned once. */
11
- export const claudeCodeVerifiedRelease = '2.1.306';
11
+ export const claudeCodeVerifiedRelease = '2.1.322';
12
12
 
13
13
  /**
14
14
  * The oldest Claude Code release the fleet runs: the oldest whose fleet output the tests still pin. It rises only when
@@ -13,6 +13,7 @@ import { aglProxyConfinedMountPoint, aglProxyRelayMountPoint, aglProxyUnitName,
13
13
  type TAglProxyConfinedRun } from './functions.proxycontract.js';
14
14
  import { writeConfinedRelay } from './functions.confinedrelay.js';
15
15
  import { inferenceCliHelp, parseInferenceCliArguments, type IInferenceCliArguments } from './functions.inferencecliarguments.js';
16
+ import { claudeHookSwitchNotice } from './functions.proxyharnessconfig.js';
16
17
  import { runProxyCredentialCommand } from './functions.proxycredentialcli.js';
17
18
  import { runProxyCapacity } from './functions.proxycapacitycli.js';
18
19
  import { isProxyCapacityAnswer } from '../ts_interfaces/proxycapacity.js';
@@ -178,7 +179,8 @@ const serve = (portArg: number): Promise<void> => withSignals(async (signalArg)
178
179
 
179
180
  /**
180
181
  * Runs a harness on a proxy lease. A proxy that restarts meanwhile hands the lease back, so the harness keeps its
181
- * credential; a lease it does not hand back stops the harness, and the run ends with the reason.
182
+ * credential; a lease it does not hand back stops the harness, and the run ends with the reason. Claude Code's run
183
+ * says on stderr which inherited hook switches it does not get (`claudeHookSwitchNotice`).
182
184
  */
183
185
  const run = (optionsArg: IInferenceCliArguments): Promise<void> => withSignals(async (signalArg) => {
184
186
  await preflightAGLHomeMigration();
@@ -193,6 +195,8 @@ const run = (optionsArg: IInferenceCliArguments): Promise<void> => withSignals(a
193
195
  const launch = inferenceHarnessLaunch({ harness: optionsArg.harness!, baseUrl: lease.baseUrl, token: lease.token,
194
196
  catalog: lease.catalog, modelId: optionsArg.modelId, args: optionsArg.args, environment,
195
197
  claudeConfigDirectory: paths.claudeOnChatGpt });
198
+ const hookSwitches = claudeHookSwitchNotice('AGL proxy run', launch.droppedHookSwitches);
199
+ if (hookSwitches) process.stderr.write(`${hookSwitches}\n`);
196
200
  signalArg.throwIfAborted();
197
201
  const child = plugins.childProcess.spawn(optionsArg.harness!, launch.args, { env: launch.environment, stdio: 'inherit', shell: false });
198
202
  let killTimer: ReturnType<typeof setTimeout> | undefined;
@@ -259,6 +263,8 @@ const confinedContainer = async (optionsArg: IInferenceCliArguments, signalArg:
259
263
  ? `, Codex on the ChatGPT pool (ChatGPT accounts only), AGL's relay at ${aglProxyRelayMountPoint}`
260
264
  : run.provider === 'openai' ? ', served from the ChatGPT pool' : ''}; `
261
265
  + `end it at once with \`agl proxy confined end ${run.id}\`.\n`);
266
+ const hookSwitches = claudeHookSwitchNotice('AGL proxy confined run', launch.droppedHookSwitches);
267
+ if (hookSwitches) process.stderr.write(`${hookSwitches}\n`);
262
268
  signalArg.throwIfAborted();
263
269
  const child = plugins.childProcess.spawn(launch.command, launch.args, { env: launch.environment, stdio: 'inherit', shell: false });
264
270
  let killTimer: ReturnType<typeof setTimeout> | undefined;
@@ -3,7 +3,7 @@ import type { TInferenceModel } from './classes.inferencerouter.js';
3
3
  import type { TAglProxyLeaseCatalog } from './classes.proxycontrol.js';
4
4
  import { aglProxyConfinedMountPoint, aglProxyRelayMountPoint } from './functions.proxycontract.js';
5
5
  import { aglProxyProviderId, claudeProxyEnvironment, claudeProxyReservedVariables, claudeRoutingVariables, codexProxyProvider,
6
- codexRoutingVariables, openCodeProxyProvider, proxyHarnessModels } from './functions.proxyharnessconfig.js';
6
+ codexRoutingVariables, dropClaudeHookSwitches, openCodeProxyProvider, proxyHarnessModels } from './functions.proxyharnessconfig.js';
7
7
 
8
8
  export type TInferenceHarness = 'codex' | 'claude' | 'opencode';
9
9
  export interface IInferenceLaunchOptions {
@@ -17,15 +17,27 @@ export interface IInferenceLaunchOptions {
17
17
  claudeConfigDirectory: string;
18
18
  }
19
19
 
20
+ /**
21
+ * A harness's launch overlay: its arguments and environment, and the hook switches (`dropClaudeHookSwitches`) the
22
+ * environment held and Claude Code does not get; none for Codex and OpenCode.
23
+ */
24
+ export interface IInferenceLaunch {
25
+ args: string[];
26
+ environment: NodeJS.ProcessEnv;
27
+ droppedHookSwitches: string[];
28
+ }
29
+
20
30
  /**
21
31
  * Claude Code on a Claude pool: its own configuration and home, with only its endpoint and credential pointed at
22
32
  * the proxy, which sends its requests on to the account unchanged. The proxy's credential replaces any claude.ai
23
33
  * login for the run (`ANTHROPIC_AUTH_TOKEN` takes precedence over a stored login), and the login itself is left
24
- * as it is. Claude Code reads the pool's models from the proxy and sends nothing beyond its model requests.
34
+ * as it is. Claude Code reads the pool's models from the proxy and sends nothing beyond its model requests. An inherited
35
+ * hook switch is dropped, so the hooks of the user's settings run.
25
36
  */
26
- const claudeNativeLaunch = (optionsArg: IInferenceLaunchOptions & { catalog: { provider: 'anthropic' } }): { args: string[]; environment: NodeJS.ProcessEnv } => {
37
+ const claudeNativeLaunch = (optionsArg: IInferenceLaunchOptions & { catalog: { provider: 'anthropic' } }): IInferenceLaunch => {
27
38
  const environment = { ...optionsArg.environment };
28
39
  for (const name of claudeRoutingVariables) delete environment[name];
40
+ const droppedHookSwitches = dropClaudeHookSwitches(environment);
29
41
  if (optionsArg.modelId !== undefined && !optionsArg.catalog.models.some((entry) => entry.modelId === optionsArg.modelId)) {
30
42
  throw new Error('The requested model is not offered by every Claude account of this pool.');
31
43
  }
@@ -33,7 +45,7 @@ const claudeNativeLaunch = (optionsArg: IInferenceLaunchOptions & { catalog: { p
33
45
  ...claudeProxyEnvironment(optionsArg.baseUrl),
34
46
  ANTHROPIC_AUTH_TOKEN: optionsArg.token,
35
47
  ...(optionsArg.modelId === undefined ? {} : { ANTHROPIC_MODEL: optionsArg.modelId }),
36
- } };
48
+ }, droppedHookSwitches };
37
49
  };
38
50
 
39
51
  /**
@@ -107,8 +119,11 @@ const dottedFields = (prefixArg: string, valueArg: Record<string, unknown>): Rec
107
119
  ? Object.entries(dottedFields(`${prefixArg}.${key}`, value as Record<string, unknown>))
108
120
  : [[`${prefixArg}.${key}`, value]]));
109
121
 
110
- /** Ephemeral launch overlays; native credentials and generated configuration are never changed. */
111
- export const inferenceHarnessLaunch = (optionsArg: IInferenceLaunchOptions): { args: string[]; environment: NodeJS.ProcessEnv } => {
122
+ /**
123
+ * Ephemeral launch overlays; native credentials and generated configuration are never changed. Claude Code, on either
124
+ * pool, gets no inherited hook switch (`dropClaudeHookSwitches`).
125
+ */
126
+ export const inferenceHarnessLaunch = (optionsArg: IInferenceLaunchOptions): IInferenceLaunch => {
112
127
  const catalog = optionsArg.catalog;
113
128
  if (catalog.provider === 'anthropic') {
114
129
  if (optionsArg.harness !== 'claude') throw new Error('Codex and OpenCode run on a ChatGPT pool; a Claude pool serves Claude Code.');
@@ -135,15 +150,17 @@ export const inferenceHarnessLaunch = (optionsArg: IInferenceLaunchOptions): { a
135
150
  ...dottedFields(`model_providers.${aglProxyProviderId}`, codexProxyProvider({ baseUrl: optionsArg.baseUrl,
136
151
  auth: { command: 'printenv', args: ['MODELPROFILE_PROXY_TOKEN'] } })),
137
152
  };
138
- return { environment, args: [...Object.entries(configuration).flatMap(([key, value]) => ['-c', `${key}=${JSON.stringify(value)}`]), ...args] };
153
+ return { environment, args: [...Object.entries(configuration).flatMap(([key, value]) => ['-c', `${key}=${JSON.stringify(value)}`]), ...args],
154
+ droppedHookSwitches: [] };
139
155
  }
140
156
  if (optionsArg.harness === 'claude') {
141
157
  rejects(['--settings', '--model', '--fallback-model', '--betas']);
142
158
  for (const name of claudeRoutingVariables) delete environment[name];
159
+ const droppedHookSwitches = dropClaudeHookSwitches(environment);
143
160
  const launch = claudeChatGptLaunch({ baseUrl: `${optionsArg.baseUrl}/anthropic`, token: optionsArg.token,
144
161
  configDirectory: optionsArg.claudeConfigDirectory,
145
162
  models: [model, ...models.filter((entry) => entry !== model)].map((entry) => ({ ...entry, isDefault: entry === model })) });
146
- return { environment: { ...environment, ...launch.environment }, args: [...launch.args, ...args] };
163
+ return { environment: { ...environment, ...launch.environment }, args: [...launch.args, ...args], droppedHookSwitches };
147
164
  }
148
165
  rejects(['-m', '--model', '--attach']);
149
166
  if (environment.OPENCODE_CONFIG_CONTENT) throw new Error('Unset OPENCODE_CONFIG_CONTENT before starting an AGL proxy harness.');
@@ -156,8 +173,9 @@ export const inferenceHarnessLaunch = (optionsArg: IInferenceLaunchOptions): { a
156
173
  // Only `run` and the TUI (OpenCode's default command) take `--model`; every other command refuses it and runs on the
157
174
  // configuration's `model` above.
158
175
  const selection = ['--model', `${aglProxyProviderId}/${model.modelId}`];
159
- if (args[0] === 'run') return { environment, args: ['run', ...selection, ...args.slice(1)] };
160
- return { environment, args: args[0] !== undefined && openCodeCommands.has(args[0]) ? args : [...selection, ...args] };
176
+ if (args[0] === 'run') return { environment, args: ['run', ...selection, ...args.slice(1)], droppedHookSwitches: [] };
177
+ return { environment, args: args[0] !== undefined && openCodeCommands.has(args[0]) ? args : [...selection, ...args],
178
+ droppedHookSwitches: [] };
161
179
  };
162
180
 
163
181
  /**
@@ -291,9 +309,10 @@ const assertMountable = (directoryArg: string, whatArg: string): void => {
291
309
  * gets each variable by name from the docker command's environment, so the credential never appears on a command line;
292
310
  * that environment drops every variable that would give the harness another login or route -- Claude Code's always, and
293
311
  * for a Codex run Codex's and OpenAI's (`codexRoutingVariables`) -- and on the ChatGPT pool every model variable a Claude
294
- * Code run sets, so `-e NAME` of one of them passes nothing. The mount is the socket's own directory, which holds nothing
295
- * else and survives a proxy restart, unlike a mount of the socket file. Only `docker run` and `docker container run` are
296
- * taken.
312
+ * Code run sets, so `-e NAME` of one of them passes nothing. A Claude Code run's environment also drops every hook switch
313
+ * (`dropClaudeHookSwitches`), so `-e NAME` of one passes nothing either, while one typed with its value (`-e NAME=1`) is the
314
+ * command's own and stays. The mount is the socket's own directory, which holds nothing else and survives a proxy restart,
315
+ * unlike a mount of the socket file. Only `docker run` and `docker container run` are taken.
297
316
  */
298
317
  export const confinedDockerLaunch = (optionsArg: {
299
318
  args: readonly string[];
@@ -304,7 +323,7 @@ export const confinedDockerLaunch = (optionsArg: {
304
323
  token: string;
305
324
  environment: NodeJS.ProcessEnv;
306
325
  pool: TConfinedLaunchPool;
307
- }): { command: string; args: string[]; environment: NodeJS.ProcessEnv } => {
326
+ }): { command: string; args: string[]; environment: NodeJS.ProcessEnv; droppedHookSwitches: string[] } => {
308
327
  const [command, ...args] = optionsArg.args;
309
328
  const runAt = args[0] === 'run' ? 1 : args[0] === 'container' && args[1] === 'run' ? 2 : 0;
310
329
  if (command === undefined || path.basename(command) !== 'docker' || runAt === 0) {
@@ -334,6 +353,7 @@ export const confinedDockerLaunch = (optionsArg: {
334
353
  for (const name of claudeProxyReservedVariables) delete environment[name];
335
354
  if ('harness' in pool) for (const name of codexRoutingVariables) delete environment[name];
336
355
  else if (pool.provider === 'openai') for (const name of claudeChatGptVariables) delete environment[name];
356
+ const droppedHookSwitches = 'harness' in pool ? [] : dropClaudeHookSwitches(environment);
337
357
  return {
338
358
  command,
339
359
  args: [...args.slice(0, runAt),
@@ -343,5 +363,6 @@ export const confinedDockerLaunch = (optionsArg: {
343
363
  ...Object.keys(variables).flatMap((nameArg) => ['--env', nameArg]),
344
364
  ...args.slice(runAt)],
345
365
  environment: { ...environment, ...variables },
366
+ droppedHookSwitches,
346
367
  };
347
368
  };
@@ -53,6 +53,38 @@ export const claudeRoutingVariables: readonly string[] = ['ANTHROPIC_API_KEY', '
53
53
  'CLAUDE_CODE_USE_VERTEX', 'CLAUDE_CODE_USE_FOUNDRY', 'CLAUDE_CODE_USE_ANTHROPIC_AWS', 'CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD',
54
54
  'CLAUDE_CODE_USE_MANTLE', 'CLAUDE_CODE_USE_GATEWAY', 'ANTHROPIC_UNIX_SOCKET'];
55
55
 
56
+ /**
57
+ * The variables that, inherited, keep the hooks of the user's Claude Code settings from running, and with them AGL's
58
+ * policy hook (AGL-1783): bare mode, safe mode, restricted mode, no recorded workspace trust, and review mode, which
59
+ * needs four variables at once and is cut at `CLAUDE_CODE_REMOTE_SESSION_ORIGIN`, the most specific of them.
60
+ * Membership: one name per path on which the environment alone stops a hook of the user's settings; for a path that
61
+ * needs several variables together, its most specific one. A name that only adds a notice (`CLAUDE_CODE_PERSONAL_HOOKS_OFF`)
62
+ * is none. `dropClaudeHookSwitches` deletes them; ts_authswitch/native-contracts.md ("Claude Code compatibility check")
63
+ * says how a new release is read for them.
64
+ */
65
+ export const claudeHookSwitchVariables: readonly string[] = ['CLAUDE_CODE_SIMPLE', 'CLAUDE_CODE_SAFE_MODE', 'CLAUDE_CODE_RESTRICTED',
66
+ 'CLAUDE_CODE_IGNORE_PERSISTED_TRUST', 'CLAUDE_CODE_REMOTE_SESSION_ORIGIN'];
67
+
68
+ /**
69
+ * Deletes every `claudeHookSwitchVariables` name from the environment a Claude Code session is started with, whatever
70
+ * its value, and answers those that held one, in the list's order. Only inherited variables go: a flag typed for the
71
+ * run (`--bare`, `--safe-mode`) is an argument and stays.
72
+ */
73
+ export const dropClaudeHookSwitches = (environmentArg: NodeJS.ProcessEnv): string[] => {
74
+ const dropped: string[] = [];
75
+ for (const name of claudeHookSwitchVariables) {
76
+ if (environmentArg[name] !== undefined) dropped.push(name);
77
+ delete environmentArg[name];
78
+ }
79
+ return dropped;
80
+ };
81
+
82
+ /** The one line that says which hook switches `starterArg` dropped (`dropClaudeHookSwitches`); none when it dropped none. */
83
+ export const claudeHookSwitchNotice = (starterArg: string, droppedArg: readonly string[]): string | undefined =>
84
+ droppedArg.length === 0 ? undefined : `${starterArg} drops ${droppedArg.join(', ')} from the environment it starts Claude Code `
85
+ + `with: inherited, ${droppedArg.length === 1 ? 'it can keep' : 'each can keep'} the hooks of the user's Claude Code settings, `
86
+ + 'AGL\'s policy hook among them, from running.';
87
+
56
88
  /**
57
89
  * The variables that make Codex authenticate or route another way than through the proxy's provider, or read a home of
58
90
  * its own choosing: an OpenAI or Codex key, token or login, an OpenAI endpoint, organization or project, workload
@@ -9,16 +9,26 @@
9
9
  * The module imports nothing, so it bundles for a browser as it is.
10
10
  */
11
11
 
12
+ /**
13
+ * The instants a renewal anchor may name, in epoch milliseconds, both included: the first of the year 2000 and the
14
+ * last of the year 9999, in UTC. A view that bounds a date picker with it takes what `isAuthSwitchRenewsAt` takes.
15
+ */
16
+ export const authSwitchRenewsAtRange: Readonly<{ min: number; max: number }> = Object.freeze({
17
+ min: Date.UTC(2000, 0, 1),
18
+ max: Date.UTC(10000, 0, 1) - 1,
19
+ });
20
+
12
21
  /**
13
22
  * The renewal anchor rule, the one the authority applies to `authswitch.authority.renewal`: a date-time `Date.parse`
14
- * reads, in any year from 2000 to 9999, as the lapse date rule (`isAuthSwitchLapsesAt`). A past anchor is valid: the
15
- * next renewal is a whole number of months after it. A consumer validates with this rather than restating it; the
16
- * authority stores the anchor as its ISO 8601 UTC form and answers any other value with the `invalid_input` refusal.
23
+ * reads, in any year from 2000 to 9999 (`authSwitchRenewsAtRange`), as the lapse date rule (`isAuthSwitchLapsesAt`). A
24
+ * past anchor is valid: the next renewal is a whole number of months after it. A consumer validates with this rather
25
+ * than restating it; the authority stores the anchor as its ISO 8601 UTC form and answers any other value with the
26
+ * `invalid_input` refusal.
17
27
  */
18
28
  export const isAuthSwitchRenewsAt = (value: unknown): value is string => {
19
29
  if (typeof value !== 'string' || value.length > 64) return false;
20
30
  const at = Date.parse(value);
21
- return Number.isFinite(at) && at >= Date.UTC(2000, 0, 1) && at < Date.UTC(10000, 0, 1);
31
+ return Number.isFinite(at) && at >= authSwitchRenewsAtRange.min && at <= authSwitchRenewsAtRange.max;
22
32
  };
23
33
 
24
34
  /** The renewal `monthsArg` months after the anchor: the anchor's UTC day clamped to that month, at the anchor's UTC time. */
@@ -16,12 +16,12 @@ export const CLAUDE_NATIVE_MINIMUM_VERSION = '2.1.273';
16
16
  * (native-contracts.md). The usage of an adopted home's login is read from the home only while every Claude Code
17
17
  * session running there runs one of these or a release from `CLAUDE_NATIVE_READ_AS_VERIFIED_FROM` on
18
18
  * (`claudeNativeReleaseReadsAsVerified`, owner ruling 2026-10-22, AGL-685); an installed release below that line that
19
- * is not listed is read from only while no session runs in that home. The controller's verified release (2.1.306,
20
- * AGL-686) and its fleet floor (2.1.282) are listed. 2.1.288, the release AGL's own Claude chats run through the Agent
21
- * SDK, had these items read from the SDK's binary (AGL-688) and is listed for the usage read only: the fleet never ran
22
- * it, so it is never the fleet's floor or the verified release.
19
+ * is not listed is read from only while no session runs in that home. The controller's verified release (2.1.322,
20
+ * AGL-1780; 2.1.306 before it, AGL-686) and its fleet floor (2.1.282) are listed. 2.1.288, the release AGL's own Claude
21
+ * chats run through the Agent SDK, had these items read from the SDK's binary (AGL-688) and is listed for the usage
22
+ * read only: the fleet never ran it, so it is never the fleet's floor or the verified release.
23
23
  */
24
- export const CLAUDE_NATIVE_VERIFIED_RELEASES: readonly string[] = ['2.1.273', '2.1.282', '2.1.288', '2.1.306'];
24
+ export const CLAUDE_NATIVE_VERIFIED_RELEASES: readonly string[] = ['2.1.273', '2.1.282', '2.1.288', '2.1.306', '2.1.322'];
25
25
  /**
26
26
  * The line from which the usage read takes any release, listed or not, as verified (owner ruling 2026-10-22, AGL-685):
27
27
  * the controller's fleet floor (`claudeCodeFleetFloor`), which a test holds equal to it. It does not move when a newer
@@ -38,7 +38,7 @@ export const CLAUDE_NATIVE_READ_AS_VERIFIED_FROM = '2.1.282';
38
38
  * never which login a process selects (`CLAUDE_NATIVE_VERIFIED_RELEASES`). 2.1.288 is the release bundled with the
39
39
  * Agent SDK that AGL's own Claude chats run (`CLAUDE_NATIVE_AGENT_SDK_RELEASES`), read from the SDK's binary.
40
40
  */
41
- export const CLAUDE_NATIVE_CUSTODY_RELEASES: readonly string[] = ['2.1.280', '2.1.281', '2.1.282', '2.1.288', '2.1.306'];
41
+ export const CLAUDE_NATIVE_CUSTODY_RELEASES: readonly string[] = ['2.1.280', '2.1.281', '2.1.282', '2.1.288', '2.1.306', '2.1.322'];
42
42
  /** An Agent SDK version and the Claude Code release it bundles. */
43
43
  export interface IClaudeNativeAgentSdkRelease {
44
44
  /** The SDK version, as its platform package's manifest beside the binary names it. */
@@ -69,11 +69,11 @@ const PROFILE_TIMEOUT_MS = 10_000;
69
69
  /**
70
70
  * The account-bound keys of `.claude.json` a login change invalidates, beside `oauthAccount` itself: the caches
71
71
  * Claude Code's own logout clears (`performLogout`), in every listed release (2.1.288 adds the two `metricsStatus`
72
- * caches to 2.1.282's, 2.1.306 `unusedLimitResetStatusCache`).
72
+ * caches to 2.1.282's, 2.1.306 `unusedLimitResetStatusCache`, 2.1.322 `managedSettingsNoticeSeenOrg`).
73
73
  */
74
74
  export const CLAUDE_NATIVE_ACCOUNT_CACHES: readonly string[] = [
75
- 'additionalModelOptionsCache', 'additionalModelOptionsAnsweredAt', 'additionalModelCostsCache',
76
- 'modelAccessCache', 'orgModelDefaultCache', 'cachedArtifactRoster', 'artifactRosterDenied',
75
+ 'managedSettingsNoticeSeenOrg', 'additionalModelOptionsCache', 'additionalModelOptionsAnsweredAt',
76
+ 'additionalModelCostsCache', 'modelAccessCache', 'orgModelDefaultCache', 'cachedArtifactRoster', 'artifactRosterDenied',
77
77
  'lastSeenOrgDefaultUpdatedAt', 'clientDataCache', 'clientDataCacheSlots', 'autoCompactWindowsCache',
78
78
  'cachedUsageUtilization', 'metricsStatusCache', 'metricsStatusCacheByPrincipal', 'githubWebConnectionStatusCache',
79
79
  'unusedLimitResetStatusCache', 'startupPrefetchedAt',
@@ -458,9 +458,9 @@ const selectedNativeHome = (env: NodeJS.ProcessEnv): string | null => env.CLAUDE
458
458
 
459
459
  /**
460
460
  * The directory a Claude Code process keeps its credential store in and takes its OAuth refresh lock in, as its
461
- * environment selects it (2.1.282 `pw`, 2.1.288 `OS`, 2.1.306 `TL`): `CLAUDE_SECURESTORAGE_CONFIG_DIR` when it is set,
462
- * NFC-normalised, its empty value meaning `.claude` in the home directory (`os.homedir()`, read here from `HOME`), and
463
- * its native home otherwise. Null when the environment does not determine it.
461
+ * environment selects it (2.1.282 `pw`, 2.1.288 `OS`, 2.1.306 `TL`, 2.1.322 `SB`): `CLAUDE_SECURESTORAGE_CONFIG_DIR`
462
+ * when it is set, NFC-normalised, its empty value meaning `.claude` in the home directory (`os.homedir()`, read here
463
+ * from `HOME`), and its native home otherwise. Null when the environment does not determine it.
464
464
  */
465
465
  export const claudeNativeCredentialStoreDirectory = (env: NodeJS.ProcessEnv): string | null => {
466
466
  const store = env.CLAUDE_SECURESTORAGE_CONFIG_DIR;