agl 42.1.0 → 42.2.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 (134) hide show
  1. package/changelog.md +38 -0
  2. package/dist_serve/bundle.js +797 -785
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_ts/00_commitinfo_data.js +1 -1
  5. package/dist_ts/aglapi/aglapisurface.document.js +124 -10
  6. package/dist_ts/classes.accountsactions.d.ts +3 -1
  7. package/dist_ts/classes.accountsactions.js +16 -1
  8. package/dist_ts/classes.authstore.js +9 -1
  9. package/dist_ts/classes.cli.js +19 -49
  10. package/dist_ts/classes.configurationauthority.js +2 -2
  11. package/dist_ts/classes.controllerservice.d.ts +20 -2
  12. package/dist_ts/classes.controllerservice.js +42 -6
  13. package/dist_ts/classes.flexservice.js +8 -3
  14. package/dist_ts/classes.inferencegateway.d.ts +30 -2
  15. package/dist_ts/classes.inferencegateway.js +115 -20
  16. package/dist_ts/classes.inferencerouter.d.ts +16 -0
  17. package/dist_ts/classes.inferencerouter.js +5 -3
  18. package/dist_ts/classes.inferenceservice.js +7 -3
  19. package/dist_ts/classes.ticketmodels.js +4 -3
  20. package/dist_ts/classes.ticketnotifier.js +9 -2
  21. package/dist_ts/classes.ticketstore.js +9 -5
  22. package/dist_ts/classes.upgradecoordinator.d.ts +6 -1
  23. package/dist_ts/classes.upgradecoordinator.js +9 -2
  24. package/dist_ts/classes.upgradetransaction.d.ts +27 -1
  25. package/dist_ts/classes.upgradetransaction.js +92 -2
  26. package/dist_ts/configuration/functions.master.d.ts +7 -2
  27. package/dist_ts/configuration/functions.master.js +7 -4
  28. package/dist_ts/driver/classes.drivereventrelay.d.ts +1 -1
  29. package/dist_ts/driver/classes.drivereventrelay.js +3 -3
  30. package/dist_ts/fleet/classes.boardpump.d.ts +1 -1
  31. package/dist_ts/fleet/classes.boardpump.js +7 -4
  32. package/dist_ts/fleet/classes.claudeworkers.d.ts +6 -0
  33. package/dist_ts/fleet/classes.claudeworkers.js +17 -7
  34. package/dist_ts/fleet/classes.deploymodels.d.ts +19 -0
  35. package/dist_ts/fleet/classes.deploymodels.js +140 -0
  36. package/dist_ts/fleet/functions.validation.d.ts +8 -1
  37. package/dist_ts/fleet/functions.validation.js +65 -3
  38. package/dist_ts/fleet/interfaces.workers.d.ts +6 -0
  39. package/dist_ts/fleet/interfaces.workers.js +65 -2
  40. package/dist_ts/functions.fleetworkercli.d.ts +16 -3
  41. package/dist_ts/functions.fleetworkercli.js +21 -7
  42. package/dist_ts/functions.inferencecli.js +4 -2
  43. package/dist_ts/functions.mcptickettools.d.ts +1 -0
  44. package/dist_ts/functions.ticketvalidation.d.ts +36 -3
  45. package/dist_ts/functions.ticketvalidation.js +45 -14
  46. package/dist_ts/interfaces.auth.d.ts +1 -1
  47. package/dist_ts/interfaces.auth.js +2 -1
  48. package/dist_ts_authswitch/authority-contract.d.ts +23 -0
  49. package/dist_ts_authswitch/authority-contract.js +1 -1
  50. package/dist_ts_authswitch/classes.authoritybroker.d.ts +6 -0
  51. package/dist_ts_authswitch/classes.authoritybroker.js +31 -4
  52. package/dist_ts_authswitch/classes.authoritycli.d.ts +1 -0
  53. package/dist_ts_authswitch/classes.authoritycli.js +26 -1
  54. package/dist_ts_authswitch/classes.authorityclient.d.ts +3 -1
  55. package/dist_ts_authswitch/classes.authorityclient.js +10 -4
  56. package/dist_ts_authswitch/classes.authoritydaemon.js +7 -1
  57. package/dist_ts_authswitch/classes.authorityimport.js +2 -2
  58. package/dist_ts_authswitch/classes.authoritymodels.d.ts +3 -0
  59. package/dist_ts_authswitch/classes.authoritymodels.js +10 -3
  60. package/dist_ts_authswitch/testsupport.js +4 -4
  61. package/dist_ts_authswitch/ts_migration/0012_account_claude_code.d.ts +11 -0
  62. package/dist_ts_authswitch/ts_migration/0012_account_claude_code.js +18 -0
  63. package/dist_ts_authswitch/ts_migration/index.js +3 -1
  64. package/dist_ts_interfaces/deployments.d.ts +104 -0
  65. package/dist_ts_interfaces/deployments.js +8 -0
  66. package/dist_ts_interfaces/fleet.d.ts +2 -0
  67. package/dist_ts_interfaces/index.d.ts +1 -0
  68. package/dist_ts_interfaces/index.js +2 -1
  69. package/dist_ts_interfaces/interfaces.d.ts +1 -1
  70. package/dist_ts_interfaces/interfaces.js +1 -1
  71. package/dist_ts_interfaces/requests.accounts.d.ts +18 -0
  72. package/dist_ts_interfaces/requests.accounts.js +1 -1
  73. package/dist_ts_interfaces/requests.d.ts +2 -2
  74. package/dist_ts_interfaces/requests.js +1 -1
  75. package/dist_ts_interfaces/tickets.d.ts +53 -4
  76. package/dist_ts_interfaces/tickets.js +6 -2
  77. package/dist_ts_migration/index.d.ts +1 -0
  78. package/dist_ts_migration/index.js +2 -1
  79. package/dist_ts_migration/v41_ticketmigrationmarkers.d.ts +19 -0
  80. package/dist_ts_migration/v41_ticketmigrationmarkers.js +85 -0
  81. package/docs/authswitch.md +6 -0
  82. package/package.json +5 -5
  83. package/readme.md +48 -12
  84. package/ts/00_commitinfo_data.ts +1 -1
  85. package/ts/aglapi/aglapisurface.document.ts +123 -9
  86. package/ts/classes.accountsactions.ts +24 -0
  87. package/ts/classes.authstore.ts +8 -0
  88. package/ts/classes.cli.ts +17 -54
  89. package/ts/classes.configurationauthority.ts +1 -1
  90. package/ts/classes.controllerservice.ts +49 -6
  91. package/ts/classes.flexservice.ts +7 -2
  92. package/ts/classes.inferencegateway.ts +133 -19
  93. package/ts/classes.inferencerouter.ts +20 -2
  94. package/ts/classes.inferenceservice.ts +6 -3
  95. package/ts/classes.ticketmodels.ts +3 -2
  96. package/ts/classes.ticketnotifier.ts +8 -1
  97. package/ts/classes.ticketstore.ts +8 -4
  98. package/ts/classes.upgradecoordinator.ts +14 -4
  99. package/ts/classes.upgradetransaction.ts +118 -0
  100. package/ts/configuration/functions.master.ts +6 -3
  101. package/ts/driver/classes.drivereventrelay.ts +2 -2
  102. package/ts/fleet/classes.boardpump.ts +7 -4
  103. package/ts/fleet/classes.claudeworkers.ts +16 -6
  104. package/ts/fleet/classes.deploymodels.ts +44 -0
  105. package/ts/fleet/functions.validation.ts +50 -2
  106. package/ts/fleet/interfaces.workers.ts +56 -1
  107. package/ts/functions.fleetworkercli.ts +26 -8
  108. package/ts/functions.inferencecli.ts +3 -1
  109. package/ts/functions.ticketvalidation.ts +48 -13
  110. package/ts/interfaces.auth.ts +1 -0
  111. package/ts_authswitch/authority-contract.ts +18 -0
  112. package/ts_authswitch/classes.authoritybroker.ts +29 -3
  113. package/ts_authswitch/classes.authoritycli.ts +29 -0
  114. package/ts_authswitch/classes.authorityclient.ts +12 -4
  115. package/ts_authswitch/classes.authoritydaemon.ts +8 -1
  116. package/ts_authswitch/classes.authorityimport.ts +1 -1
  117. package/ts_authswitch/classes.authoritymodels.ts +5 -1
  118. package/ts_authswitch/native-contracts.md +10 -0
  119. package/ts_authswitch/testsupport.ts +3 -3
  120. package/ts_authswitch/ts_migration/0012_account_claude_code.ts +17 -0
  121. package/ts_authswitch/ts_migration/index.ts +2 -0
  122. package/ts_interfaces/deployments.ts +98 -0
  123. package/ts_interfaces/fleet.ts +2 -0
  124. package/ts_interfaces/index.ts +1 -0
  125. package/ts_interfaces/interfaces.ts +1 -1
  126. package/ts_interfaces/requests.accounts.ts +16 -0
  127. package/ts_interfaces/requests.ts +2 -0
  128. package/ts_interfaces/tickets.ts +34 -4
  129. package/ts_migration/index.ts +1 -0
  130. package/ts_migration/v41_ticketmigrationmarkers.ts +28 -0
  131. package/ts_web/00_commitinfo_data.ts +1 -1
  132. package/ts_web/classes.accountsreadmodel.ts +12 -1
  133. package/ts_web/elements.accounts.ts +44 -0
  134. package/ts_web/elements.ticketboard.ts +15 -4
@@ -70,7 +70,7 @@ const gapLine = (linesArg: number): string => `[… ${linesArg} line${linesArg =
70
70
  * `textArg` within `bytesArg` UTF-8 bytes: whole when it fits. Otherwise every line the fleet reads as a report marker
71
71
  * (`fleetReportMarker`: `result:`, `needs input:`, `owner question:` and the others), newest first while they fit,
72
72
  * each at most 1 KiB, and then the text's end. A worker closes its report on its outcome, so the end is what the driver
73
- * acts on; the fleet keeps a long report's end for the same reason. Kept lines stay in their order, and each run of
73
+ * acts on; the fleet keeps a long report's end too (`boundedFleetReport`). Kept lines stay in their order, and each run of
74
74
  * left-out lines reads `[… N lines …]`; a line cut at its start begins with `…`.
75
75
  */
76
76
  export const driverRelayDigest = (textArg: string, bytesArg: number): string => {
@@ -148,7 +148,7 @@ export const formatDriverRelayEvent = (eventArg: IFleetEvent): string => {
148
148
  const text = driverRelayDigest(eventArg.text, maximumEventTextBytes);
149
149
  lines.push(...text.split('\n').map((lineArg) => ` > ${lineArg}`));
150
150
  if (text !== eventArg.text) lines.push(` (digest: its marker lines and its end; ${fullTextSource(eventArg)})`);
151
- if (eventArg.truncated) lines.push(' (the report passed 32 KiB; the fleet kept only its end)');
151
+ if (eventArg.truncated) lines.push(' (the report passed 32 KiB; the fleet kept its head, its result line and its end)');
152
152
  }
153
153
  return lines.join('\n');
154
154
  };
@@ -1,5 +1,6 @@
1
1
  import * as plugins from '../plugins.js';
2
- import type { ITicket, ITicketActivity, ITicketActor, ITicketComment, ITicketPerson, ITicketQuestion, TTicketColumn } from '../../ts_interfaces/tickets.js';
2
+ import { ticketDoneColumns, type ITicket, type ITicketActivity, type ITicketActor, type ITicketComment, type ITicketPerson, type ITicketQuestion,
3
+ type TTicketColumn } from '../../ts_interfaces/tickets.js';
3
4
  import type { ITicketHistory } from '../classes.ticketstore.js';
4
5
  import type { IFleetBoardPumpConfiguration, IFleetUnboundDriver } from '../../ts_interfaces/fleet.js';
5
6
  import type { IFleetEvent } from '../../ts_interfaces/fleetworkers.js';
@@ -164,7 +165,7 @@ export class BoardPump {
164
165
  const intervalMs = configuration.intervalMinutes * 60_000;
165
166
  if (!scope || !configuration.enabled) { this.sightings.clear(); return intervalMs; }
166
167
  const now = this.now();
167
- const tickets = (await this.host.tickets()).filter((ticketArg) => ticketArg.columnId !== 'released');
168
+ const tickets = (await this.host.tickets()).filter((ticketArg) => !ticketDoneColumns.includes(ticketArg.columnId));
168
169
  const workers = tickets.length ? await this.host.workers(scope.owner) : [];
169
170
  const listed = new Set(tickets.map((ticketArg) => ticketArg.key));
170
171
  for (const key of this.facts.keys()) if (!listed.has(key)) this.facts.delete(key);
@@ -199,8 +200,10 @@ export class BoardPump {
199
200
  const bound = workersArg.filter((viewArg) => viewArg.worker.ticketKey === ticketArg.key || assigned !== undefined && sessionOf(viewArg) === assigned)
200
201
  .sort((leftArg, rightArg) => leftArg.worker.updatedAt.localeCompare(rightArg.worker.updatedAt));
201
202
  const live = bound.filter(isLive);
202
- const watched = watchedColumns.has(column) && !(column === 'in_progress' && (ticketArg.labels.includes(boardPumpWaitingLabel) || live.length > 0));
203
- const comments = column !== 'released' && !live.length;
203
+ // A deploy plan or a maintenance window a later release planned waits for the owner's go or for its time, not for a worker.
204
+ const watched = watchedColumns.has(column) && !ticketArg.deployPlan && !ticketArg.maintenanceWindow
205
+ && !(column === 'in_progress' && (ticketArg.labels.includes(boardPumpWaitingLabel) || live.length > 0));
206
+ const comments = !ticketDoneColumns.includes(column) && !live.length;
204
207
  if (!watched && !comments) return [];
205
208
  const facts = await this.factsOf(ticketArg);
206
209
  if (facts.ticket.columnId !== column) return [];
@@ -52,14 +52,24 @@ export const fleetClaudeVersion = (result: IFleetWorkerCommand): string => {
52
52
  };
53
53
  /** Claude colours its output when FORCE_COLOR is set, through a pipe too; its control sequences are no text. */
54
54
  const plain = (text: string): string => text.replace(/\u001b\[[0-?]*[ -/]*[@-~]/gu, '');
55
- const backgrounded = (result: IFleetWorkerCommand): string | undefined => /backgrounded\s*·\s*([a-zA-Z0-9]+)\s*·/u.exec(plain(`${result.stdout}\n${result.stderr}`))?.[1];
55
+ /**
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
58
+ * the commands that reach the job, one per line.
59
+ */
60
+ export const fleetClaudeBackgrounded = (result: IFleetWorkerCommand): string | undefined => /backgrounded\s*·\s*([a-zA-Z0-9]+)(?=\s|$)/u.exec(plain(`${result.stdout}\n${result.stderr}`))?.[1];
56
61
  const reaped = (agent: TClaudeAgent): boolean => !live(agent) && (agent.state === 'done' || agent.state === 'blocked');
57
62
  /** A settled session `claude --bg --resume` continues in place: reaped, or stopped by `claude stop`. */
58
63
  const resumable = (agent: TClaudeAgent): boolean => reaped(agent) || !live(agent) && agent.state === 'stopped';
59
64
  const status = (agent?: TClaudeAgent): IFleetWorkerReport['status'] => !agent ? 'gone' : reaped(agent) ? 'reaped'
60
65
  : agent.state === 'stopped' ? 'stopped' : agent.state === 'failed' || agent.state === 'blocked' || agent.status === 'waiting' ? 'blocked'
61
66
  : agent.status === 'busy' ? 'busy' : live(agent) ? 'idle' : 'blocked';
62
- const modes = new Set(['acceptEdits', 'auto', 'bypassPermissions', 'manual', 'dontAsk']);
67
+ /**
68
+ * The permission modes a Claude Code transcript records and `--permission-mode` takes: Claude Code 2.1.282 and 2.1.306
69
+ * know `acceptEdits`, `auto`, `bypassPermissions`, `default`, `dontAsk` and `plan`, and read `manual` as `default`
70
+ * (AGL-797).
71
+ */
72
+ const modes = new Set(['acceptEdits', 'auto', 'bypassPermissions', 'default', 'dontAsk', 'manual', 'plan']);
63
73
  /** SendMessage resolves a recipient by its session name, never by the short agent id; a name another live session shares is ambiguous. */
64
74
  const address = (inventory: TClaudeAgent[], agent: TClaudeAgent): string => {
65
75
  if (!agent.name) throw new Error('Claude worker has no session name; SendMessage cannot address it.');
@@ -486,7 +496,7 @@ export class FleetClaudeWorkers implements IFleetWorkerBackend {
486
496
  }
487
497
  catch (error) { throw new FleetDispatchError(error instanceof Error ? error.message : 'Claude start preflight failed.', false, { cause: error }); }
488
498
  const result = await this.launch(worker, profile, [], overlay, prompt, before);
489
- await this.identify(worker, profile, backgrounded(result), before, bind, { attempts: 20, observation: async () => ({ offset: 0, state: 'busy', turnState: 'working' }) });
499
+ await this.identify(worker, profile, fleetClaudeBackgrounded(result), before, bind, { attempts: 20, observation: async () => ({ offset: 0, state: 'busy', turnState: 'working' }) });
490
500
  }
491
501
  /**
492
502
  * Runs `claude --bg` for `worker` with its profile's options, its overlay and `prompt`, after the launch options
@@ -502,7 +512,7 @@ export class FleetClaudeWorkers implements IFleetWorkerBackend {
502
512
  if (result.code !== 0) {
503
513
  await this.callers?.revoke(worker, 'failure');
504
514
  // Claude refused the start (an untrusted workspace, say) when it printed no backgrounded line and its inventory gained no session.
505
- const started = backgrounded(result) !== undefined || await this.agents(worker, profile).then((after) => after.some((agent) => agent.name === worker.name
515
+ const started = fleetClaudeBackgrounded(result) !== undefined || await this.agents(worker, profile).then((after) => after.some((agent) => agent.name === worker.name
506
516
  && plugins.path.resolve(agent.cwd) === plugins.path.resolve(worker.cwd) && !before.some((entry) => entry.sessionId === agent.sessionId)), () => true);
507
517
  throw new FleetDispatchError(commandFailure('--bg', result, true), started);
508
518
  }
@@ -568,7 +578,7 @@ export class FleetClaudeWorkers implements IFleetWorkerBackend {
568
578
  }
569
579
  catch (error) { throw new FleetDispatchError(error instanceof Error ? error.message : 'Claude relaunch preflight failed.', false, { cause: error }); }
570
580
  const result = await this.launch(worker, profile, ['--resume', nativeId], overlay, prompt, before);
571
- const output = plain(`${result.stdout}\n${result.stderr}`), shortId = backgrounded(result);
581
+ const output = plain(`${result.stdout}\n${result.stderr}`), shortId = fleetClaudeBackgrounded(result);
572
582
  const notes = output.split('\n').map((line) => line.trim()).filter((line) => /\bnote:/iu.test(line));
573
583
  // Claude names the copy it started for a background job; a session it continues in place takes no note.
574
584
  const copy = original.kind === 'background' && notes.length === 1
@@ -677,7 +687,7 @@ export class FleetClaudeWorkers implements IFleetWorkerBackend {
677
687
  private async wake(profile: Pick<IFleetWorkerProfile, 'home'>, cwd: string, nativeId: string, original: TClaudeAgent, text: string): Promise<void> {
678
688
  const executable = await this.supportedExecutable(profile, cwd);
679
689
  const result = await this.runner(executable, ['--bg', '--resume', nativeId, text], cwd, this.env(profile), this.signal);
680
- const output = plain(`${result.stdout}\n${result.stderr}`), shortId = backgrounded(result);
690
+ const output = plain(`${result.stdout}\n${result.stderr}`), shortId = fleetClaudeBackgrounded(result);
681
691
  // Claude confirms a wake in place with a note naming the original job; any other note reports a copy.
682
692
  const notes = output.split('\n').filter((line) => /\bnote:/iu.test(line) && !line.trim().startsWith(`note: woke session ${original.id} with its saved options`));
683
693
  if (result.code !== 0 || notes.length || shortId !== original.id) {
@@ -0,0 +1,44 @@
1
+ import * as plugins from '../plugins.js';
2
+ import { fleetDeployTargetIdPattern, type IFleetDeployObservation } from '../../ts_interfaces/deployments.js';
3
+
4
+ const timestamp = plugins.z.iso.datetime();
5
+ const version = plugins.z.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u);
6
+ const targetId = plugins.z.string().regex(fleetDeployTargetIdPattern);
7
+ const sha256Digest = plugins.z.string().regex(/^sha256:[a-f0-9]{64}$/u);
8
+ const subject = plugins.z.discriminatedUnion('kind', [
9
+ plugins.z.object({ kind: plugins.z.literal('lockfile'), repo: plugins.z.string().min(1).max(1024),
10
+ sha: plugins.z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u), path: plugins.z.string().min(1).max(1024),
11
+ blob: plugins.z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u) }).strict(),
12
+ plugins.z.object({ kind: plugins.z.literal('image'), digest: sha256Digest }).strict(),
13
+ plugins.z.object({ kind: plugins.z.literal('installed'), targetId, treeDigest: sha256Digest }).strict(),
14
+ plugins.z.object({ kind: plugins.z.literal('binary'), sha256: sha256Digest }).strict(),
15
+ ]);
16
+ const observationSchema = plugins.z.object({
17
+ id: plugins.z.string().min(1).max(256), targetId, seq: plugins.z.number().int().positive(), repo: plugins.z.string().min(1).max(1024), version,
18
+ sha: plugins.z.string().regex(/^[a-f0-9]{7,64}$/u).optional(), observedAt: timestamp, previousVersion: version.optional(),
19
+ artifacts: plugins.z.array(plugins.z.object({ subject, replicas: plugins.z.number().int().positive().optional() }).strict()).max(256),
20
+ }).strict();
21
+
22
+ /**
23
+ * What a deploy target ran (AGL-911): one row whenever its probe answers another version, commit or artifact set than the
24
+ * target's newest row holds. History and rollbacks are computed from these rows; nothing else about a deployment is stored. A row's id is
25
+ * its target and number, and `(targetId, seq)` is unique.
26
+ */
27
+ @plugins.nosqldb.compoundIndex({ name: 'deploy_target_seq', key: { targetId: 1, seq: -1 }, options: { unique: true } })
28
+ @plugins.nosqldb.managed({ collectionName: 'agl_fleet_deploy_observations' })
29
+ @plugins.nosqldb.exactPersistence({ assertDocument: (input: unknown) => {
30
+ const doc = observationSchema.parse(input);
31
+ if (doc.id !== `${doc.targetId}:${doc.seq}`) throw new Error('Deploy observation identity mismatch.');
32
+ } })
33
+ export class DeployObservationModel extends plugins.nosqldb.SmartDataDbDoc<DeployObservationModel, IFleetDeployObservation> {
34
+ declare static exact: plugins.nosqldb.TExact<DeployObservationModel>;
35
+ @plugins.nosqldb.unI() public id!: string;
36
+ @plugins.nosqldb.svDb() public targetId!: string;
37
+ @plugins.nosqldb.svDb() public seq!: number;
38
+ @plugins.nosqldb.svDb() public repo!: string;
39
+ @plugins.nosqldb.svDb() public version!: string;
40
+ @plugins.nosqldb.svDb() public sha?: string;
41
+ @plugins.nosqldb.svDb() public observedAt!: string;
42
+ @plugins.nosqldb.svDb() public previousVersion?: string;
43
+ @plugins.nosqldb.svDb() public artifacts!: IFleetDeployObservation['artifacts'];
44
+ }
@@ -1,4 +1,5 @@
1
1
  import type { IFleetConfiguration, IFleetRepositorySection, IFleetScope, TFleetOperation, TFleetRequest, IFleetOperation } from '../../ts_interfaces/fleet.js';
2
+ import { fleetDeployTargetIdPattern } from '../../ts_interfaces/deployments.js';
2
3
  import * as plugins from '../plugins.js';
3
4
  import { validateFleetWorkerProfiles } from './functions.workervalidation.js';
4
5
  import { fleetTicketKeySchema, fleetTicketSyncSchema } from './functions.ticketcontext.js';
@@ -99,12 +100,59 @@ const validateFleetBoardPump = (input: unknown): void => {
99
100
  if (pump.landedAfterHours !== undefined && (typeof pump.landedAfterHours !== 'number' || !Number.isFinite(pump.landedAfterHours)
100
101
  || pump.landedAfterHours <= 0 || pump.landedAfterHours > 720)) throw new Error('The fleet board pump landedAfterHours must be more than 0 and at most 720.');
101
102
  };
102
- export const validateFleetConfiguration = (input: unknown): IFleetConfiguration => {
103
- const config = object(input); keys(config, [], ['environment', 'workerProfiles', 'driver', 'boardPump']);
103
+ /** RFC 6901: the empty pointer or `/`-separated tokens, `~` only as `~0` or `~1`. */
104
+ const jsonPointerPattern = /^(?:\/(?:[^~/]|~[01])*)*$/u;
105
+ const label = (value: unknown, name: string): void => {
106
+ if (typeof value !== 'string' || !value.trim() || value.length > 200 || /[\0\r\n]/u.test(value)) throw new Error(`The deploy target ${name} must be one line of at most 200 characters.`);
107
+ };
108
+ const validateFleetDeployTargets = (input: unknown): void => {
109
+ if (!Array.isArray(input) || input.length > 64) throw new Error('The fleet deploy targets must be a list of at most 64.');
110
+ const ids = new Set<string>();
111
+ let controllers = 0;
112
+ for (const entry of input) {
113
+ const target = object(entry); keys(target, ['id', 'repo', 'probe', 'project'], ['name', 'environment', 'deploys', 'downtime', 'deployWhen']);
114
+ if (typeof target.id !== 'string' || !fleetDeployTargetIdPattern.test(target.id)) throw new Error('A deploy target id is lowercase letters, digits, ., _ and -, at most 64.');
115
+ if (ids.has(target.id)) throw new Error(`The deploy target ${target.id} is named twice.`);
116
+ ids.add(target.id);
117
+ if (typeof target.repo !== 'string' || !fleetRepositoryIdPattern.test(target.repo)) throw new Error(`The deploy target ${target.id} needs its repository as org/name.`);
118
+ for (const field of ['name', 'environment', 'deploys', 'downtime'] as const) if (target[field] !== undefined) label(target[field], field);
119
+ label(target.project, 'project');
120
+ if (target.deployWhen !== undefined && target.deployWhen !== 'anytime' && target.deployWhen !== 'window') {
121
+ throw new Error(`The deploy target ${target.id} deploys anytime or only inside a maintenance window (window).`);
122
+ }
123
+ const probe = object(target.probe);
124
+ if (probe.kind === 'controller') {
125
+ keys(probe, ['kind']); controllers += 1;
126
+ if (target.deployWhen !== undefined) throw new Error(`The deploy target ${target.id} probes the controller, which needs no window: it is upgraded when no session is busy.`);
127
+ continue;
128
+ }
129
+ if (probe.kind !== 'http') throw new Error(`The deploy target ${target.id} probes kind controller or http.`);
130
+ keys(probe, ['kind', 'url'], ['versionPointer', 'shaPointer']);
131
+ const url = typeof probe.url === 'string' && probe.url.length <= 2048 && URL.canParse(probe.url) ? new URL(probe.url) : undefined;
132
+ if (!url || !['http:', 'https:'].includes(url.protocol) || url.username || url.password) throw new Error(`The deploy target ${target.id} probes an http(s) URL without credentials.`);
133
+ for (const field of ['versionPointer', 'shaPointer'] as const) {
134
+ if (probe[field] !== undefined && (typeof probe[field] !== 'string' || probe[field].length > 256 || !jsonPointerPattern.test(probe[field]))) {
135
+ throw new Error(`The deploy target ${target.id} ${field} must be a JSON pointer such as /version.`);
136
+ }
137
+ }
138
+ }
139
+ if (controllers > 1) throw new Error('Only one deploy target can probe the controller.');
140
+ };
141
+ /**
142
+ * Validates the Configuration master's `fleet` section. `save` checks a document being saved, which may be stricter
143
+ * than one being read: a field this release reads but the next one writes is refused on save, so a rollback to this
144
+ * release never meets a master it cannot run.
145
+ */
146
+ export const validateFleetConfiguration = (input: unknown, optionsArg: { save?: boolean } = {}): IFleetConfiguration => {
147
+ const config = object(input); keys(config, [], ['environment', 'workerProfiles', 'driver', 'boardPump', 'deployTargets']);
148
+ if (optionsArg.save && config.deployTargets !== undefined) {
149
+ throw new Error('fleet.deployTargets is read by this AGL release and saved by the next one; upgrade AGL to configure deploy targets.');
150
+ }
104
151
  if (config.environment !== undefined) validateEnvironment(config.environment);
105
152
  if (config.workerProfiles !== undefined) validateFleetWorkerProfiles(config.workerProfiles);
106
153
  if (config.driver !== undefined) validateFleetDriver(config.driver);
107
154
  if (config.boardPump !== undefined) validateFleetBoardPump(config.boardPump);
155
+ if (config.deployTargets !== undefined) validateFleetDeployTargets(config.deployTargets);
108
156
  return structuredClone(config) as unknown as IFleetConfiguration;
109
157
  };
110
158
  /** Validates one operation's configuration with its discovered repositories. */
@@ -88,7 +88,62 @@ export interface IFleetWorkerBackend {
88
88
  * mid-turn and counts as a report too.
89
89
  */
90
90
  export const fleetReportMarker = /(?:^|\n)[ \t]*(?:result:|needs input:|owner question:|cross-subject:|spec question:|ready (?:for|to) (?:land|release)|#{1,3} Handoff|@?driver:|@driver\b|question for the driver\b)/iu;
91
- export const boundedFleetReport = (text: string): { text: string; truncated: boolean } => ({ text: text.slice(-32 * 1024), truncated: text.length > 32 * 1024 });
91
+ /** A report is kept whole up to 32 KiB of UTF-8; a longer one keeps its head, its result line and its end (AGL-158). */
92
+ const fleetReportBytes = 32 * 1024, fleetReportEndBytes = 4 * 1024, fleetReportLineBytes = 1024;
93
+ /** What one gap line takes at most, its line breaks included. */
94
+ const fleetReportGapBytes = 128;
95
+ /** The first (`head`) or last (`tail`) `bytesArg` UTF-8 bytes of `textArg` at most; a cut never splits a character. */
96
+ const clipFleetReport = (textArg: string, bytesArg: number, keepArg: 'head' | 'tail'): string => {
97
+ const bytes = Buffer.from(textArg);
98
+ if (bytes.length <= bytesArg) return textArg;
99
+ if (keepArg === 'head') {
100
+ let end = bytesArg;
101
+ while (end > 0 && (bytes[end]! & 0xc0) === 0x80) end -= 1;
102
+ return bytes.subarray(0, end).toString('utf8');
103
+ }
104
+ let start = bytes.length - bytesArg;
105
+ while (start < bytes.length && (bytes[start]! & 0xc0) === 0x80) start += 1;
106
+ return bytes.subarray(start).toString('utf8');
107
+ };
108
+ const fleetReportGap = (bytesArg: number): string => `[… ${bytesArg} bytes cut; the worker's transcript holds the whole report …]`;
109
+ /**
110
+ * A worker report within 32 KiB of UTF-8, `truncated` when it was longer. A longer report keeps, in order, its head
111
+ * (its summary and first rows), its last marker line (`fleetReportMarker`, its `result:` line; at most 1 KiB) when
112
+ * that line lies between the head and the end, and its last 4 KiB from a line start. A line
113
+ * `[… N bytes cut; the worker's transcript holds the whole report …]` stands where a part was left out.
114
+ */
115
+ export const boundedFleetReport = (text: string): { text: string; truncated: boolean } => {
116
+ if (Buffer.byteLength(text) <= fleetReportBytes) return { text, truncated: false };
117
+ let end = clipFleetReport(text, fleetReportEndBytes, 'tail');
118
+ const lineStart = end.indexOf('\n');
119
+ if (lineStart >= 0 && lineStart + 1 < end.length) end = end.slice(lineStart + 1);
120
+ const endAt = text.length - end.length;
121
+ let headBytes = fleetReportBytes - Buffer.byteLength(end) - fleetReportGapBytes;
122
+ // The last marker line, when the head does not reach it and the end does not hold it.
123
+ const lines = text.split('\n');
124
+ let markerAt = text.length;
125
+ for (let index = lines.length - 1, at = text.length; index >= 0; index -= 1) {
126
+ at -= lines[index]!.length;
127
+ if (fleetReportMarker.test(lines[index]!)) { markerAt = at; break; }
128
+ at -= 1;
129
+ }
130
+ const segments: Array<[number, number]> = [];
131
+ if (markerAt < endAt && Buffer.byteLength(text.slice(0, markerAt)) >= headBytes) {
132
+ const lineEnd = text.indexOf('\n', markerAt);
133
+ const line = clipFleetReport(text.slice(markerAt, lineEnd < 0 ? text.length : lineEnd), fleetReportLineBytes, 'head');
134
+ headBytes -= Buffer.byteLength(line) + fleetReportGapBytes;
135
+ segments.push([markerAt, Math.min(markerAt + line.length, endAt)]);
136
+ }
137
+ segments.unshift([0, clipFleetReport(text, headBytes, 'head').length]);
138
+ segments.push([endAt, text.length]);
139
+ let bounded = '';
140
+ for (const [index, [from, to]] of segments.entries()) {
141
+ const cut = index ? text.slice(segments[index - 1]![1], from) : '';
142
+ bounded += cut === '' || cut === '\n' ? cut : `\n${fleetReportGap(Buffer.byteLength(cut))}\n`;
143
+ bounded += text.slice(from, to);
144
+ }
145
+ return { text: bounded, truncated: true };
146
+ };
92
147
  /**
93
148
  * The SHA-256 (hex) a steer fence keeps of its message and a reconfirm compares a transcript's message with. Line
94
149
  * endings and surrounding whitespace do not count, so a harness that normalises either still matches.
@@ -4,7 +4,7 @@ import { withLocalConfigurationOwner } from './functions.configurationowner.js';
4
4
  import { withCliDiagnostics } from './functions.clidiagnostics.js';
5
5
  import { defaultControllerPort } from './classes.config.js';
6
6
  import { fleetObservationWindowMs, withFleetObservationOwner } from './functions.fleetcli.js';
7
- import { assertFleetWorkerRequest } from './fleet/functions.workervalidation.js';
7
+ import { assertFleetWorkerRequest, fleetWorkerRequestSchemas } from './fleet/functions.workervalidation.js';
8
8
  import { fleetWatchLines, parseFleetWatchCi, parseFleetWatchSite, watchFleetProbes, type IFleetWatchChange, type IFleetWatchProbeOptions } from './fleet/functions.watchprobes.js';
9
9
  import type { IFleetWorker, TFleetWorkerAction, TFleetWorkerRequest, IFleetEventCursor, IFleetWatchResult } from '../ts_interfaces/fleetworkers.js';
10
10
 
@@ -15,7 +15,7 @@ export const fleetWorkerCliHelp = `Usage: agl fleet worker start NAME --profile
15
15
  agl fleet worker reconfirm NAME --reason TEXT
16
16
  agl fleet worker steer NAME --message-file FILE
17
17
  agl fleet worker steer --messages-file FILE (JSON array of {name,text})
18
- agl fleet worker message NAME|NATIVE_ID --message-file FILE
18
+ agl fleet worker message NAME|NATIVE_ID --message-file FILE [--ticket KEY]
19
19
  agl fleet worker native-message NATIVE_ID --message-file FILE --sender LABEL
20
20
  agl fleet worker report|stop|archive NAME
21
21
  agl fleet worker refresh NAME --next-name NAME [--profile ID] --handoff-file FILE [--note-file FILE]
@@ -24,7 +24,7 @@ export const fleetWorkerCliHelp = `Usage: agl fleet worker start NAME --profile
24
24
  agl fleet worker status JOB_ID
25
25
  agl fleet watch [--cursor JSON] [--once] [--lines] [--site NAME=URL …] [--ci OWNER/REPO[@REF] …]
26
26
  [--gitea URL] [--gitea-token-file FILE] [--probe-interval SECONDS]
27
- All accept --ticket KEY, --json and --port PORT. Actions and report require --ticket; list/status/watch accept it as a filter.
27
+ All accept --ticket KEY, --json and --port PORT. Actions and report require --ticket, except message; list/status/watch accept it as a filter.
28
28
  Profiles live in fleet.workerProfiles in the Configuration master.
29
29
  Mutation and report commands wait for the returned job; MCP tools return its handle immediately.
30
30
  refresh --profile ID starts the successor on that configured profile, which must run the worker's own harness (only move
@@ -38,6 +38,7 @@ every --probe-interval seconds (default 60); each writes its state first and the
38
38
  --gitea defaults to https://code.foss.global; a token from --gitea-token-file reaches private repositories over https.
39
39
  Steer and message reach a live worker through a relay and resume a reaped or stopped one with its saved options.
40
40
  Message addresses one worker by its name or by its native session id (a unique prefix of at least 8 characters).
41
+ Without --ticket it steers the worker on its own ticket; a --ticket the worker is not on, and a worker on no ticket, are refused.
41
42
  native-message wakes a settled (done, blocked or stopped) Claude Code background job that no fleet worker binds, named by
42
43
  its session id or a unique prefix of at least 8 characters, through Claude Code itself, as the browser's native session
43
44
  send does. The text arrives behind the session_message attribution header with the --sender label and the local owner
@@ -63,9 +64,14 @@ reconfirm requires --ticket and a reason. It clears a steer fence whose native s
63
64
  same session, settled before and after its transcript is read, and records from the transcript whether the message
64
65
  arrived (delivered, not-found or unproven) with the resolver and a ticket comment. It sends nothing; steer again to resend.
65
66
  `;
67
+ /** A `message` steer before its recipient is resolved: without --ticket it names no ticket yet. */
68
+ export type TFleetWorkerCliMessageRequest = Omit<TFleetWorkerRequest<'steer'>, 'ticketKey'> & { ticketKey?: string };
66
69
  export interface IFleetWorkerCliArguments {
67
- action: TFleetWorkerAction; request: TFleetWorkerRequest<TFleetWorkerAction>; port: number; json: boolean; once: boolean;
68
- /** `message`: the steer recipient is a worker name or native session id the controller's worker list resolves. */
70
+ action: TFleetWorkerAction; request: TFleetWorkerRequest<TFleetWorkerAction> | TFleetWorkerCliMessageRequest; port: number; json: boolean; once: boolean;
71
+ /**
72
+ * `message`: the steer recipient is a worker name or native session id the controller's worker list resolves;
73
+ * `fleetWorkerMessageRequest` then addresses it and names its ticket.
74
+ */
69
75
  target?: string;
70
76
  /** `message`: the file the message came from, which a refusal's native-message command names. */
71
77
  messageFile?: string;
@@ -94,6 +100,18 @@ export const resolveFleetWorkerTarget = (workers: IFleetWorker[], target: string
94
100
  + 'or adopt it first.'
95
101
  : 'Adopt the session first.'));
96
102
  };
103
+ /**
104
+ * The steer `message` sends once its recipient resolved to `worker` (AGL-919): addressed by the worker's name, on the
105
+ * ticket --ticket named or else on the worker's own. A --ticket the worker is not on and a worker on no ticket are
106
+ * refused before anything is sent; the fleet still checks the ticket when it takes the steer.
107
+ */
108
+ export const fleetWorkerMessageRequest = (request: TFleetWorkerCliMessageRequest, worker: IFleetWorker): TFleetWorkerRequest<'steer'> => {
109
+ if (!worker.ticketKey) throw new Error(`Fleet worker ${worker.name} is on no ticket, so it takes no message; adopt it with --ticket KEY first.`);
110
+ if (request.ticketKey !== undefined && request.ticketKey !== worker.ticketKey) {
111
+ throw new Error(`Fleet worker ${worker.name} is on ${worker.ticketKey}, not ${request.ticketKey}; without --ticket, message steers it on its own ticket.`);
112
+ }
113
+ return assertFleetWorkerRequest('steer', { ticketKey: worker.ticketKey, messages: [{ ...request.messages[0]!, name: worker.name }] });
114
+ };
97
115
  const fileText = async (path: string): Promise<string> => {
98
116
  const file = await plugins.fs.promises.open(path, 'r');
99
117
  try { if ((await file.stat()).size > 128 * 1024) throw new Error('Fleet message file exceeds 128 KiB.'); return await file.readFile('utf8'); }
@@ -159,7 +177,8 @@ export const parseFleetWorkerCliArguments = async (args: string[]): Promise<IFle
159
177
  probes.giteaToken = (await fileText(giteaTokenFile)).trim();
160
178
  if (!probes.giteaToken) throw new Error('The Gitea token file is empty.');
161
179
  }
162
- const request = assertFleetWorkerRequest(action, input);
180
+ // Without --ticket, `message` steers on its recipient's own ticket, which `fleetWorkerMessageRequest` names (AGL-919).
181
+ const request = message && input.ticketKey === undefined ? fleetWorkerRequestSchemas.steer.omit({ ticketKey: true }).parse(input) : assertFleetWorkerRequest(action, input);
163
182
  return { action, request, port, json, once, ...(lines ? { lines } : {}), ...(probing ? { probes } : {}),
164
183
  ...(message ? { target: (request as TFleetWorkerRequest<'steer'>).messages[0]!.name, ...(messageFile ? { messageFile } : {}) } : {}) };
165
184
  };
@@ -223,8 +242,7 @@ export const runFleetWorkerCli = async (args: string[]): Promise<void> => {
223
242
  await withCliDiagnostics(async () => withLocalConfigurationOwner(client!, parsed.port, async (ownerToken) => {
224
243
  if (parsed.target) {
225
244
  const { workers } = await client!.fleetWorker('list', { ownerToken }, abort.signal);
226
- const steer = parsed.request as TFleetWorkerRequest<'steer'>;
227
- steer.messages = [{ ...steer.messages[0]!, name: resolveFleetWorkerTarget(workers, parsed.target, parsed.messageFile).name }];
245
+ parsed.request = fleetWorkerMessageRequest(parsed.request as TFleetWorkerCliMessageRequest, resolveFleetWorkerTarget(workers, parsed.target, parsed.messageFile));
228
246
  }
229
247
  let result = await client!.fleetWorker(parsed.action, { ...parsed.request, ownerToken } as never, abort.signal);
230
248
  if ('job' in result && parsed.action !== 'status') {
@@ -92,7 +92,9 @@ export const formatProxyStatus = (unitArg: string, statusArg: TReportedProxyStat
92
92
  lines.push(`Account ${account.label} (${account.credential === 'api_key'
93
93
  ? `${account.provider === 'openai' ? 'OpenAI' : 'Anthropic'} API key` : account.provider === 'openai' ? 'ChatGPT' : 'Claude'}`
94
94
  + `${account.plan === null ? '' : `, ${account.plan}`}): ${account.stateText}`
95
- + `${account.resetAt === null ? '' : `, until ${account.resetAt}`}; `
95
+ + `${account.resetAt === null ? '' : `, until ${account.resetAt}`}`
96
+ // A key kept from Claude Code (AGL-1146) still serves every other client.
97
+ + `${account.credential === 'api_key' && account.claudeCode === false ? ', not for Claude Code' : ''}; `
96
98
  // A key has no maximum usage: its headroom is what is left of its monthly spend limit.
97
99
  + `${account.credential === 'api_key'
98
100
  ? `${account.headroom === null ? '' : `${Math.round(account.headroom)}% of its spend limit left, `}`
@@ -1,5 +1,8 @@
1
1
  import * as plugins from './plugins.js';
2
- import { ticketAutoLabels, ticketColumns, ticketHistoryPage, type TTicketOperation, type TTicketRequest } from '../ts_interfaces/tickets.js';
2
+ import {
3
+ ticketAutoLabels, ticketColumns, ticketHistoryPage, type TTicketFleetEvent, type TTicketLink, type TTicketOperation, type TTicketRequest,
4
+ } from '../ts_interfaces/tickets.js';
5
+ import { fleetDeployTargetIdPattern } from '../ts_interfaces/deployments.js';
3
6
 
4
7
  const text = (maximumArg: number) => plugins.z.string().max(maximumArg);
5
8
  const identifier = text(1024).min(1).refine((valueArg) => !/[\x00-\x1f\x7f]/u.test(valueArg));
@@ -11,11 +14,37 @@ const person = plugins.z.object({
11
14
  sessionId: identifier.optional(),
12
15
  }).strict();
13
16
  const actor = person.extend({ role: plugins.z.enum(['owner', 'driver', 'worker']) }).strict();
17
+ const branchLink = plugins.z.object({ kind: plugins.z.literal('branch'), repo: identifier, branch: identifier, sha }).strict();
18
+ const commitLink = plugins.z.object({ kind: plugins.z.literal('commit'), repo: identifier, sha }).strict();
14
19
  const link = plugins.z.discriminatedUnion('kind', [
15
- plugins.z.object({ kind: plugins.z.literal('branch'), repo: identifier, branch: identifier, sha }).strict(),
16
- plugins.z.object({ kind: plugins.z.literal('commit'), repo: identifier, sha }).strict(),
20
+ branchLink, commitLink,
17
21
  plugins.z.object({ kind: plugins.z.literal('release'), package: identifier, version: identifier }).strict(),
18
22
  ]);
23
+ /**
24
+ * Every link a stored ticket may hold: what callers link, plus the repository and commit a fleet release adds to its
25
+ * release link and the `affects` link (found in). Readers accept these one release before any writer sends them.
26
+ */
27
+ const storedLink = plugins.z.discriminatedUnion('kind', [
28
+ branchLink, commitLink,
29
+ plugins.z.object({ kind: plugins.z.literal('release'), version: identifier, package: identifier.optional(),
30
+ repo: identifier.optional(), sha: sha.optional() }).strict(),
31
+ plugins.z.object({ kind: plugins.z.literal('affects'), repo: identifier, version: identifier }).strict(),
32
+ ]).refine((linkArg) => linkArg.kind !== 'release' || linkArg.package !== undefined || linkArg.repo !== undefined,
33
+ 'A release link names its repository or its package.');
34
+ /** The columns a stored ticket may name. */
35
+ const storedColumn = plugins.z.enum(ticketColumns);
36
+ /** The columns a request may move a ticket to; `closed` is read one release before anything moves a ticket there. */
37
+ const requestColumn = plugins.z.enum(ticketColumns).exclude(['closed']);
38
+ const releasePlan = plugins.z.object({ repo: identifier, version: identifier.optional() }).strict();
39
+ const deployTargetId = plugins.z.string().regex(fleetDeployTargetIdPattern);
40
+ const questionId = plugins.z.string().regex(/^Q[1-9][0-9]*$/u);
41
+ /** A stored maintenance window; read one release before anything writes one. */
42
+ const maintenanceWindow = plugins.z.object({ from: plugins.z.iso.datetime(), to: plugins.z.iso.datetime(),
43
+ targets: plugins.z.array(deployTargetId).min(1).max(64).refine((valueArg) => new Set(valueArg).size === valueArg.length),
44
+ questionId: questionId.optional() }).strict()
45
+ .refine((valueArg) => Date.parse(valueArg.to) > Date.parse(valueArg.from), 'A maintenance window ends after it starts.');
46
+ /** A stored deploy plan; read one release before anything writes one. */
47
+ const deployPlan = plugins.z.object({ target: deployTargetId, version: identifier, questionId }).strict();
19
48
  const attachment = plugins.z.object({ name: text(200).min(1),
20
49
  url: plugins.z.url().max(4096).refine((valueArg) => /^https?:\/\//iu.test(valueArg), 'Attachments require HTTP or HTTPS URLs.') }).strict();
21
50
  const labels = plugins.z.array(text(100).min(1)).max(100).refine((valueArg) => new Set(valueArg).size === valueArg.length);
@@ -25,7 +54,6 @@ const referenceContent = plugins.z.array(plugins.z.discriminatedUnion('type', [
25
54
  plugins.z.object({ type: plugins.z.literal('text'), text: text(64 * 1024) }).strict(),
26
55
  plugins.z.object({ type: plugins.z.literal('reference'), id: identifier, label: text(200).min(1) }).strict(),
27
56
  ])).min(1).max(100).refine((valueArg) => JSON.stringify(valueArg).length <= 64 * 1024);
28
- const questionId = plugins.z.string().regex(/^Q[1-9][0-9]*$/u);
29
57
  const optionId = plugins.z.string().regex(/^[1-9][0-9]*$/u);
30
58
  const questionOption = plugins.z.object({ label: text(200).trim().min(1), description: text(1000).optional() }).strict();
31
59
  const filters = plugins.z.object({ mine: plugins.z.boolean().optional(), project: identifier.optional(),
@@ -44,11 +72,11 @@ export const ticketInputSchemas = {
44
72
  'commentId reads one comment and excludes before and limit.'),
45
73
  comments: plugins.z.object({ ticketId }).strict(),
46
74
  create: plugins.z.object({ project: identifier, kind: kind.optional(), title: text(200).trim().min(1),
47
- description: text(64 * 1024).optional(), columnId: plugins.z.enum(ticketColumns).optional(), parentId: ticketId.optional(),
75
+ description: text(64 * 1024).optional(), columnId: requestColumn.optional(), parentId: ticketId.optional(),
48
76
  priority: priority.optional(), assignee: person.optional(), labels: labels.optional(), sourceText: text(64 * 1024).optional(),
49
77
  attachments: plugins.z.array(attachment).max(100).optional() }).strict(),
50
78
  update: plugins.z.object({ ticketId, expectedRevision: plugins.z.number().int().nonnegative(), changes }).strict(),
51
- move: plugins.z.object({ ticketId, columnId: plugins.z.enum(ticketColumns), beforeTicketId: ticketId.optional() }).strict(),
79
+ move: plugins.z.object({ ticketId, columnId: requestColumn, beforeTicketId: ticketId.optional() }).strict(),
52
80
  comment: plugins.z.object({ ticketId, body: plugins.z.union([text(64 * 1024).min(1), referenceContent]) }).strict(),
53
81
  link: plugins.z.object({ ticketId, link }).strict(),
54
82
  ask: plugins.z.object({ ticketId, question: text(16 * 1024).trim().min(1),
@@ -69,15 +97,22 @@ const fleetEventBase = { ticketKey: ticketId,
69
97
  export const ticketFleetEventSchema = plugins.z.discriminatedUnion('kind', [
70
98
  plugins.z.object({ ...fleetEventBase, kind: plugins.z.literal('landed'), repo: identifier,
71
99
  branch: identifier, sha, body: ticketInputSchemas.comment.shape.body.optional() }).strict(),
72
- plugins.z.object({ ...fleetEventBase, kind: plugins.z.literal('released'), package: identifier,
73
- version: identifier, body: ticketInputSchemas.comment.shape.body.optional() }).strict(),
100
+ plugins.z.object({ ...fleetEventBase, kind: plugins.z.literal('released'), version: identifier, package: identifier.optional(),
101
+ repo: identifier.optional(), sha: sha.optional(), body: ticketInputSchemas.comment.shape.body.optional() }).strict(),
74
102
  plugins.z.object({ ...fleetEventBase, kind: plugins.z.literal('comment'), body: ticketInputSchemas.comment.shape.body }).strict(),
75
- ]);
103
+ ]).refine((eventArg) => eventArg.kind !== 'released' || eventArg.package !== undefined || eventArg.repo !== undefined,
104
+ 'A released event names its repository or its package.');
105
+ /** The release link a `released` event writes: its version, and the repository, commit and package it names. */
106
+ export const ticketReleaseLink = (eventArg: Extract<TTicketFleetEvent, { kind: 'released' }>): Extract<TTicketLink, { kind: 'release' }> => ({
107
+ kind: 'release', version: eventArg.version, ...(eventArg.package === undefined ? {} : { package: eventArg.package }),
108
+ ...(eventArg.repo === undefined ? {} : { repo: eventArg.repo }), ...(eventArg.sha === undefined ? {} : { sha: eventArg.sha }),
109
+ });
76
110
  export const ticketSchema = plugins.z.object({
77
111
  id: ticketId, key: ticketId, revision: plugins.z.number().int().nonnegative().optional(),
78
112
  project: identifier, kind, title: text(200).min(1), description: text(64 * 1024),
79
- parentId: ticketId.optional(), columnId: plugins.z.enum(ticketColumns), order: plugins.z.number().int().nonnegative(),
80
- priority, assignee: person.optional(), labels, links: plugins.z.array(link).max(100),
113
+ parentId: ticketId.optional(), columnId: storedColumn, order: plugins.z.number().int().nonnegative(),
114
+ priority, assignee: person.optional(), labels, links: plugins.z.array(storedLink).max(100), releasePlan: releasePlan.optional(),
115
+ maintenanceWindow: maintenanceWindow.optional(), deployPlan: deployPlan.optional(),
81
116
  source: plugins.z.object({ kind: plugins.z.enum(['owner_words', 'driver', 'worker']), text: text(64 * 1024),
82
117
  actor, attachments: plugins.z.array(attachment).max(100) }).strict(),
83
118
  createdBy: actor, updatedBy: actor, createdAt: plugins.z.iso.datetime(), updatedAt: plugins.z.iso.datetime(),
@@ -85,7 +120,7 @@ export const ticketSchema = plugins.z.object({
85
120
  export const ticketCommentSchema = plugins.z.object({ id: identifier, ticketId, author: actor,
86
121
  createdAt: plugins.z.iso.datetime(), body: referenceContent }).strict();
87
122
  export const ticketActivitySchema = plugins.z.object({ id: identifier, ticketId, actor, createdAt: plugins.z.iso.datetime(),
88
- action: plugins.z.enum(['created', 'updated', 'moved', 'reordered', 'commented', 'linked', 'asked', 'answered']),
123
+ action: plugins.z.enum(['created', 'updated', 'moved', 'reordered', 'commented', 'linked', 'unlinked', 'asked', 'answered']),
89
124
  changes: plugins.z.record(plugins.z.string(), plugins.z.object({ before: plugins.z.unknown().optional(), after: plugins.z.unknown().optional() }).strict()) }).strict();
90
125
  export const ticketQuestionSchema = plugins.z.object({ id: questionId, ticketId, kind: plugins.z.literal('question'),
91
126
  question: text(16 * 1024).min(1), options: plugins.z.array(questionOption.extend({ id: optionId }).strict()).max(20),
@@ -118,7 +153,7 @@ export const assertTicketResponse = (methodArg: string, valueArg: unknown): void
118
153
  list: plugins.z.object({ tickets: plugins.z.array(ticket) }).strict(),
119
154
  search: plugins.z.object({ tickets: plugins.z.array(ticket) }).strict(),
120
155
  board: plugins.z.object({ revision: plugins.z.number().int().nonnegative(), columns: plugins.z.array(plugins.z.object({
121
- id: plugins.z.enum(ticketColumns), title: plugins.z.string(), done: plugins.z.boolean().optional() }).strict()), tickets: plugins.z.array(ticket),
156
+ id: storedColumn, title: plugins.z.string(), done: plugins.z.boolean().optional() }).strict()), tickets: plugins.z.array(ticket),
122
157
  viewer: person }).strict(),
123
158
  get: plugins.z.object({ ticket, comments: plugins.z.array(ticketCommentSchema), activity: plugins.z.array(ticketActivitySchema),
124
159
  questions: plugins.z.array(ticketQuestionSchema), historyBefore: identifier.optional() }).strict(),
@@ -75,6 +75,7 @@ export const controllerAuditEventTypes = [
75
75
  'accounts.reserve.lift',
76
76
  'accounts.apikey.add',
77
77
  'accounts.spendlimit',
78
+ 'accounts.claudecode',
78
79
  'accounts.remove',
79
80
  'accounts.add',
80
81
  'accounts.reauth',
@@ -282,6 +282,13 @@ export interface IAuthSwitchAccount {
282
282
  * account on a sign-in, and for an Anthropic key the accounts service held before it kept hints.
283
283
  */
284
284
  keyHint: string | null;
285
+ /**
286
+ * Whether the account may serve Claude Code (AGL-1146): `false` keeps AGL's inference proxy from placing a Claude Code
287
+ * request on the key -- for a key whose credit its provider grants for API use other than Claude Code -- while every
288
+ * other client of the pool still uses it. Always `true` for an account on a sign-in, and for a key unless its owner
289
+ * set it otherwise.
290
+ */
291
+ claudeCode: boolean;
285
292
  removed: boolean;
286
293
  revision: number;
287
294
  statusObservedAt: string;
@@ -1485,6 +1492,17 @@ export interface IReq_AuthSwitchSetAccountSpendLimit extends ITypedRequest {
1485
1492
  response: { account: IAuthSwitchAccount };
1486
1493
  }
1487
1494
 
1495
+ /**
1496
+ * Sets whether an API key account may serve Claude Code (`claudeCode`). Refused (`invalid_input`) for an account on a
1497
+ * sign-in, which always may; a change of an account that changed since `expectedRevision` is refused as
1498
+ * `account_changed`. Setting the value the account already has changes nothing and keeps its revision.
1499
+ */
1500
+ export interface IReq_AuthSwitchSetAccountClaudeCode extends ITypedRequest {
1501
+ method: 'authswitch.authority.claudecode';
1502
+ request: { accountId: string; expectedRevision: number; claudeCode: boolean };
1503
+ response: { account: IAuthSwitchAccount };
1504
+ }
1505
+
1488
1506
  /**
1489
1507
  * Lift only the saved reserve for whole hours 1..24, using the authority clock and expected revision. Refused
1490
1508
  * (`invalid_input`) for an API key account, which has a spend limit instead of a reserve.
@@ -156,7 +156,7 @@ const notOnApiKey = 'An API key account has no usage windows to keep a reserve o
156
156
  const publicAccount = (account: IStoredAuthorityAccount): IAuthSwitchAccount => ({
157
157
  id: account.id, providerId: account.providerId, label: account.label, email: account.email,
158
158
  plan: account.plan, organizationId: account.workspaceId, maxUsagePercent: account.maxUsagePercent, reserveLiftUntil: account.reserveLiftUntil,
159
- lapsesAt: account.lapsesAt, spendLimitMicroUsd: account.spendLimitMicroUsd, keyHint: account.keyHint,
159
+ lapsesAt: account.lapsesAt, spendLimitMicroUsd: account.spendLimitMicroUsd, keyHint: account.keyHint, claudeCode: account.claudeCode,
160
160
  removed: account.removed, revision: account.revision, statusObservedAt: account.statusObservedAt,
161
161
  });
162
162
 
@@ -675,7 +675,7 @@ export class AuthSwitchAuthorityBroker {
675
675
  revision: existing.revision + 1, statusObservedAt: now, updateId: commitId }
676
676
  : { id: identity.id, providerId: 'openai', issuer: 'openai', subject: identity.subject,
677
677
  workspaceId: identity.workspaceId, label: identity.email ?? `OpenAI ${identity.workspaceId}`,
678
- email: identity.email, plan: identity.plan, primaryGrantId: grantId, maxUsagePercent: null, reserveLiftUntil: null, lapsesAt: null, spendLimitMicroUsd: null, keyHint: null, removed: false,
678
+ email: identity.email, plan: identity.plan, primaryGrantId: grantId, maxUsagePercent: null, reserveLiftUntil: null, lapsesAt: null, spendLimitMicroUsd: null, keyHint: null, claudeCode: true, removed: false,
679
679
  revision: 1, statusObservedAt: now, updateId: commitId };
680
680
  const grant: IStoredAuthorityGrant = oldGrant
681
681
  ? { ...oldGrant, state: 'ready', owner: 'daemon', ciphertext,
@@ -870,6 +870,32 @@ export class AuthSwitchAuthorityBroker {
870
870
  return publicAccount(updated.account);
871
871
  }
872
872
 
873
+ /**
874
+ * Sets whether an API key account may serve Claude Code (`IAuthSwitchAccount.claudeCode`), as `setAccountSpendLimit`
875
+ * changes its limit. The proxy applies it from the next request on: a Claude Code session on a key that may not serve
876
+ * it moves to another account then. The value the key already has changes nothing.
877
+ */
878
+ public async setAccountClaudeCode(accountId: string, expectedRevision: number, claudeCode: boolean): Promise<IAuthSwitchAccount> {
879
+ if (!isId(accountId) || !validRevision(expectedRevision) || typeof claudeCode !== 'boolean') {
880
+ throw new Error('Invalid account change.');
881
+ }
882
+ const current = await this.database.readAccount(accountId);
883
+ if (current && !current.removed && current.revision === expectedRevision && isApiKeyAccount(current)
884
+ && current.claudeCode === claudeCode) return publicAccount(current);
885
+ const updateId = plugins.crypto.randomUUID();
886
+ const updated = await this.database.changeAccount(updateId, accountId, account => {
887
+ if (!account || account.removed || account.revision !== expectedRevision) throw new AuthSwitchRefusal('account_changed', 'Account changed; refresh before editing.');
888
+ if (!isApiKeyAccount(account)) {
889
+ throw new AuthSwitchRefusal('invalid_input', 'A sign-in always serves Claude Code. Only an API key account can be '
890
+ + 'kept from it.');
891
+ }
892
+ return { ...account, claudeCode, revision: account.revision + 1, updateId,
893
+ statusObservedAt: new Date(this.now()).toISOString() };
894
+ });
895
+ this.publish();
896
+ return publicAccount(updated.account);
897
+ }
898
+
873
899
  /**
874
900
  * Sets or clears the date an account's subscription ends, as `setAccountMaxUsage` changes its threshold. The date is
875
901
  * stored in its ISO 8601 UTC form; a past one is kept as given and means the account lapsed already.
@@ -1379,7 +1405,7 @@ export class AuthSwitchAuthorityBroker {
1379
1405
  : { id: accountId, providerId, issuer: providerId, subject, workspaceId: apiKeyWorkspace,
1380
1406
  label: label ?? kind.label, email: null, plan: null, primaryGrantId: grantId, maxUsagePercent: null,
1381
1407
  reserveLiftUntil: null, lapsesAt: null, spendLimitMicroUsd: spendLimitMicroUsd ?? null, keyHint,
1382
- removed: false, revision: 1, statusObservedAt: now, updateId };
1408
+ claudeCode: true, removed: false, revision: 1, statusObservedAt: now, updateId };
1383
1409
  const grant: IStoredAuthorityGrant = oldGrant
1384
1410
  ? { ...oldGrant, state: 'ready', owner: 'daemon', ciphertext, grantGeneration: oldGrant.grantGeneration + 1,
1385
1411
  authorizationGeneration: oldGrant.authorizationGeneration + 1, revision: oldGrant.revision + 1,