agl 42.0.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 (168) hide show
  1. package/changelog.md +44 -0
  2. package/dist_serve/bundle.js +2520 -2158
  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.d.ts +2 -0
  9. package/dist_ts/classes.authstore.js +58 -17
  10. package/dist_ts/classes.cli.js +19 -49
  11. package/dist_ts/classes.configurationauthority.js +2 -2
  12. package/dist_ts/classes.controller.d.ts +71 -2
  13. package/dist_ts/classes.controller.js +500 -113
  14. package/dist_ts/classes.controllerdevices.d.ts +128 -0
  15. package/dist_ts/classes.controllerdevices.js +472 -0
  16. package/dist_ts/classes.controllerservice.d.ts +20 -2
  17. package/dist_ts/classes.controllerservice.js +42 -6
  18. package/dist_ts/classes.flexservice.js +8 -3
  19. package/dist_ts/classes.inferencegateway.d.ts +30 -2
  20. package/dist_ts/classes.inferencegateway.js +115 -20
  21. package/dist_ts/classes.inferencerouter.d.ts +16 -0
  22. package/dist_ts/classes.inferencerouter.js +5 -3
  23. package/dist_ts/classes.inferenceservice.js +7 -3
  24. package/dist_ts/classes.sessionfeed.d.ts +10 -1
  25. package/dist_ts/classes.sessionfeed.js +12 -2
  26. package/dist_ts/classes.ticketmodels.js +4 -3
  27. package/dist_ts/classes.ticketnotifier.js +9 -2
  28. package/dist_ts/classes.ticketstore.js +9 -5
  29. package/dist_ts/classes.upgradecoordinator.d.ts +6 -1
  30. package/dist_ts/classes.upgradecoordinator.js +9 -2
  31. package/dist_ts/classes.upgradetransaction.d.ts +27 -1
  32. package/dist_ts/classes.upgradetransaction.js +92 -2
  33. package/dist_ts/classes.validation.d.ts +2 -0
  34. package/dist_ts/classes.validation.js +2 -2
  35. package/dist_ts/configuration/functions.master.d.ts +7 -2
  36. package/dist_ts/configuration/functions.master.js +7 -4
  37. package/dist_ts/driver/classes.drivereventrelay.d.ts +1 -1
  38. package/dist_ts/driver/classes.drivereventrelay.js +3 -3
  39. package/dist_ts/fleet/classes.boardpump.d.ts +1 -1
  40. package/dist_ts/fleet/classes.boardpump.js +7 -4
  41. package/dist_ts/fleet/classes.claudeworkers.d.ts +6 -0
  42. package/dist_ts/fleet/classes.claudeworkers.js +17 -7
  43. package/dist_ts/fleet/classes.deploymodels.d.ts +19 -0
  44. package/dist_ts/fleet/classes.deploymodels.js +140 -0
  45. package/dist_ts/fleet/functions.validation.d.ts +8 -1
  46. package/dist_ts/fleet/functions.validation.js +65 -3
  47. package/dist_ts/fleet/interfaces.workers.d.ts +6 -0
  48. package/dist_ts/fleet/interfaces.workers.js +65 -2
  49. package/dist_ts/functions.deviceapi.d.ts +28 -0
  50. package/dist_ts/functions.deviceapi.js +246 -0
  51. package/dist_ts/functions.deviceproof.d.ts +33 -0
  52. package/dist_ts/functions.deviceproof.js +93 -0
  53. package/dist_ts/functions.fleetworkercli.d.ts +16 -3
  54. package/dist_ts/functions.fleetworkercli.js +21 -7
  55. package/dist_ts/functions.inferencecli.js +4 -2
  56. package/dist_ts/functions.mcptickettools.d.ts +1 -0
  57. package/dist_ts/functions.remotecli.d.ts +1 -1
  58. package/dist_ts/functions.remotecli.js +12 -7
  59. package/dist_ts/functions.ticketvalidation.d.ts +36 -3
  60. package/dist_ts/functions.ticketvalidation.js +45 -14
  61. package/dist_ts/interfaces.auth.d.ts +1 -1
  62. package/dist_ts/interfaces.auth.js +7 -1
  63. package/dist_ts_authswitch/authority-contract.d.ts +23 -0
  64. package/dist_ts_authswitch/authority-contract.js +1 -1
  65. package/dist_ts_authswitch/classes.authoritybroker.d.ts +6 -0
  66. package/dist_ts_authswitch/classes.authoritybroker.js +31 -4
  67. package/dist_ts_authswitch/classes.authoritycli.d.ts +1 -0
  68. package/dist_ts_authswitch/classes.authoritycli.js +26 -1
  69. package/dist_ts_authswitch/classes.authorityclient.d.ts +3 -1
  70. package/dist_ts_authswitch/classes.authorityclient.js +10 -4
  71. package/dist_ts_authswitch/classes.authoritydaemon.js +7 -1
  72. package/dist_ts_authswitch/classes.authorityimport.js +2 -2
  73. package/dist_ts_authswitch/classes.authoritymodels.d.ts +3 -0
  74. package/dist_ts_authswitch/classes.authoritymodels.js +10 -3
  75. package/dist_ts_authswitch/testsupport.js +4 -4
  76. package/dist_ts_authswitch/ts_migration/0012_account_claude_code.d.ts +11 -0
  77. package/dist_ts_authswitch/ts_migration/0012_account_claude_code.js +18 -0
  78. package/dist_ts_authswitch/ts_migration/index.js +3 -1
  79. package/dist_ts_interfaces/deployments.d.ts +104 -0
  80. package/dist_ts_interfaces/deployments.js +8 -0
  81. package/dist_ts_interfaces/devices.d.ts +331 -0
  82. package/dist_ts_interfaces/devices.js +34 -0
  83. package/dist_ts_interfaces/fleet.d.ts +2 -0
  84. package/dist_ts_interfaces/index.d.ts +3 -0
  85. package/dist_ts_interfaces/index.js +4 -1
  86. package/dist_ts_interfaces/interfaces.d.ts +4 -2
  87. package/dist_ts_interfaces/interfaces.js +3 -2
  88. package/dist_ts_interfaces/mcprequests.d.ts +1 -1
  89. package/dist_ts_interfaces/requests.accounts.d.ts +18 -0
  90. package/dist_ts_interfaces/requests.accounts.js +1 -1
  91. package/dist_ts_interfaces/requests.d.ts +3 -2
  92. package/dist_ts_interfaces/requests.devices.d.ts +89 -0
  93. package/dist_ts_interfaces/requests.devices.js +2 -0
  94. package/dist_ts_interfaces/requests.js +1 -1
  95. package/dist_ts_interfaces/tickets.d.ts +53 -4
  96. package/dist_ts_interfaces/tickets.js +6 -2
  97. package/dist_ts_migration/index.d.ts +1 -0
  98. package/dist_ts_migration/index.js +2 -1
  99. package/dist_ts_migration/v41_ticketmigrationmarkers.d.ts +19 -0
  100. package/dist_ts_migration/v41_ticketmigrationmarkers.js +85 -0
  101. package/docs/authswitch.md +6 -0
  102. package/package.json +5 -5
  103. package/readme.md +84 -16
  104. package/ts/00_commitinfo_data.ts +1 -1
  105. package/ts/aglapi/aglapisurface.document.ts +123 -9
  106. package/ts/classes.accountsactions.ts +24 -0
  107. package/ts/classes.authstore.ts +54 -14
  108. package/ts/classes.cli.ts +17 -54
  109. package/ts/classes.configurationauthority.ts +1 -1
  110. package/ts/classes.controller.ts +697 -167
  111. package/ts/classes.controllerdevices.ts +469 -0
  112. package/ts/classes.controllerservice.ts +49 -6
  113. package/ts/classes.flexservice.ts +7 -2
  114. package/ts/classes.inferencegateway.ts +133 -19
  115. package/ts/classes.inferencerouter.ts +20 -2
  116. package/ts/classes.inferenceservice.ts +6 -3
  117. package/ts/classes.sessionfeed.ts +13 -1
  118. package/ts/classes.ticketmodels.ts +3 -2
  119. package/ts/classes.ticketnotifier.ts +8 -1
  120. package/ts/classes.ticketstore.ts +8 -4
  121. package/ts/classes.upgradecoordinator.ts +14 -4
  122. package/ts/classes.upgradetransaction.ts +118 -0
  123. package/ts/classes.validation.ts +1 -1
  124. package/ts/configuration/functions.master.ts +6 -3
  125. package/ts/driver/classes.drivereventrelay.ts +2 -2
  126. package/ts/fleet/classes.boardpump.ts +7 -4
  127. package/ts/fleet/classes.claudeworkers.ts +16 -6
  128. package/ts/fleet/classes.deploymodels.ts +44 -0
  129. package/ts/fleet/functions.validation.ts +50 -2
  130. package/ts/fleet/interfaces.workers.ts +56 -1
  131. package/ts/functions.deviceapi.ts +295 -0
  132. package/ts/functions.deviceproof.ts +118 -0
  133. package/ts/functions.fleetworkercli.ts +26 -8
  134. package/ts/functions.inferencecli.ts +3 -1
  135. package/ts/functions.remotecli.ts +11 -5
  136. package/ts/functions.ticketvalidation.ts +48 -13
  137. package/ts/interfaces.auth.ts +6 -0
  138. package/ts_authswitch/authority-contract.ts +18 -0
  139. package/ts_authswitch/classes.authoritybroker.ts +29 -3
  140. package/ts_authswitch/classes.authoritycli.ts +29 -0
  141. package/ts_authswitch/classes.authorityclient.ts +12 -4
  142. package/ts_authswitch/classes.authoritydaemon.ts +8 -1
  143. package/ts_authswitch/classes.authorityimport.ts +1 -1
  144. package/ts_authswitch/classes.authoritymodels.ts +5 -1
  145. package/ts_authswitch/native-contracts.md +10 -0
  146. package/ts_authswitch/testsupport.ts +3 -3
  147. package/ts_authswitch/ts_migration/0012_account_claude_code.ts +17 -0
  148. package/ts_authswitch/ts_migration/index.ts +2 -0
  149. package/ts_interfaces/deployments.ts +98 -0
  150. package/ts_interfaces/devices.schema.json +890 -0
  151. package/ts_interfaces/devices.ts +392 -0
  152. package/ts_interfaces/fleet.ts +2 -0
  153. package/ts_interfaces/index.ts +3 -0
  154. package/ts_interfaces/interfaces.ts +4 -1
  155. package/ts_interfaces/mcprequests.ts +1 -1
  156. package/ts_interfaces/requests.accounts.ts +16 -0
  157. package/ts_interfaces/requests.devices.ts +95 -0
  158. package/ts_interfaces/requests.ts +12 -0
  159. package/ts_interfaces/tickets.ts +34 -4
  160. package/ts_migration/index.ts +1 -0
  161. package/ts_migration/v41_ticketmigrationmarkers.ts +28 -0
  162. package/ts_web/00_commitinfo_data.ts +1 -1
  163. package/ts_web/classes.accountsreadmodel.ts +12 -1
  164. package/ts_web/classes.controllersocketclient.ts +27 -0
  165. package/ts_web/elements.accounts.ts +44 -0
  166. package/ts_web/elements.devices.ts +752 -0
  167. package/ts_web/elements.harnesscontrollerapp.ts +18 -1
  168. package/ts_web/elements.ticketboard.ts +15 -4
@@ -18,6 +18,7 @@ import {
18
18
  unmanagedControllerError,
19
19
  queryControllerStatus,
20
20
  requestControllerUpgradeFinalize,
21
+ requestControllerUpgradeLaunch,
21
22
  requestControllerUpgradePrepareBegin,
22
23
  stopRunningController,
23
24
  type IControllerServiceUnitControl,
@@ -1762,6 +1763,123 @@ export async function launchDetachedUpgradeWorker(
1762
1763
  return await launchDetachedUpgradeWorkerProcess(optionsArg, dependenciesArg);
1763
1764
  }
1764
1765
 
1766
+ export interface ILaunchUpgradeWorkerUnderLockOptions {
1767
+ coordinator: UpgradeCoordinator;
1768
+ installation: IPnpmGlobalInstallation;
1769
+ /** The invocation's upgrade lock, held over the `starting` transaction of `payload.token`. */
1770
+ lock: UpgradeInstallationLock;
1771
+ payload: IUpgradeWorkerPayload;
1772
+ /** The running controller, which launches the worker against a one-time grant; absent, it is launched detached. */
1773
+ status?: IControllerStatus;
1774
+ }
1775
+
1776
+ export interface ILaunchUpgradeWorkerDependencies {
1777
+ requestControllerLaunch?: typeof requestControllerUpgradeLaunch;
1778
+ launchDetachedWorker?: (optionsArg: ILaunchDetachedUpgradeWorkerOptions) => Promise<IDetachedUpgradeWorker>;
1779
+ }
1780
+
1781
+ /**
1782
+ * Launches the worker of a fresh `agl upgrade` whose transaction is still `starting`: through the running controller
1783
+ * against a one-time launch grant, else detached. The candidate it returns goes on, with the lock, to
1784
+ * `handoffLaunchedUpgradeWorkerUnderLock`.
1785
+ *
1786
+ * A failure that may have left a worker running throws `UpgradeWorkerCandidateDrainageError` and leaves the lock and
1787
+ * the transaction as they are. A failure that proves no worker runs ends the transaction failed and releases the
1788
+ * lock, so the next `agl upgrade` proceeds (AGL-327). A controller launch proves it when its grant is revoked
1789
+ * unconsumed: the controller consumes the grant (an atomic rename) before it launches a worker, so this covers a
1790
+ * controller that refuses the request before it consumes the grant, as one still starting does, and a request that
1791
+ * never reached it.
1792
+ */
1793
+ export const launchUpgradeWorkerUnderLock = async (
1794
+ optionsArg: ILaunchUpgradeWorkerUnderLockOptions,
1795
+ dependenciesArg: ILaunchUpgradeWorkerDependencies = {},
1796
+ ): Promise<IUpgradeWorkerLaunchCandidate> => {
1797
+ const { coordinator, installation, payload, status } = optionsArg;
1798
+ let candidate: IUpgradeWorkerLaunchCandidate | undefined;
1799
+ let launchError: unknown;
1800
+ // Only a sent launch request lets the controller consume the grant.
1801
+ let requested = false;
1802
+ try {
1803
+ if (status) {
1804
+ if (!payload.expectedController) {
1805
+ throw new Error('The upgrade worker payload does not name the running controller.');
1806
+ }
1807
+ await coordinator.createLaunchGrant({
1808
+ token: payload.token,
1809
+ port: payload.port,
1810
+ packageName: controllerPackageName,
1811
+ packageVersion: commitinfo.version,
1812
+ cliPath: installation.cliPath,
1813
+ controller: payload.expectedController,
1814
+ });
1815
+ requested = true;
1816
+ const launched = await (dependenciesArg.requestControllerLaunch ?? requestControllerUpgradeLaunch)(
1817
+ payload.port,
1818
+ status,
1819
+ payload.token,
1820
+ );
1821
+ candidate = { pid: launched.workerPid, cliPath: installation.cliPath, logFilePath: launched.logFilePath };
1822
+ } else {
1823
+ const launchDetached = dependenciesArg.launchDetachedWorker ?? launchDetachedUpgradeWorker;
1824
+ candidate = await launchDetached({ installation, payload });
1825
+ }
1826
+ } catch (errorArg) {
1827
+ launchError = errorArg;
1828
+ }
1829
+ if (status) {
1830
+ let revoked = false;
1831
+ try {
1832
+ revoked = await coordinator.removeLaunchGrant(payload.token);
1833
+ } catch (removalErrorArg) {
1834
+ launchError = launchError === undefined
1835
+ ? removalErrorArg
1836
+ : new AggregateError(
1837
+ [launchError, removalErrorArg],
1838
+ 'The controller upgrade launch failed and its launch grant could not be revoked.',
1839
+ );
1840
+ }
1841
+ // A consumed grant may have launched a worker the CLI cannot see, so the transaction stays as it is.
1842
+ if (launchError !== undefined && requested && !revoked) {
1843
+ throw new UpgradeWorkerCandidateDrainageError(
1844
+ 'The controller upgrade launch failed and candidate drainage cannot be proven by the CLI.',
1845
+ launchError,
1846
+ );
1847
+ }
1848
+ }
1849
+ if (launchError === undefined) return candidate!;
1850
+ if (launchError instanceof UpgradeWorkerCandidateDrainageError) throw launchError;
1851
+ const errors: unknown[] = [launchError];
1852
+ try {
1853
+ const transaction = await coordinator.readTransaction(payload.token);
1854
+ if (transaction.worker?.logFilePath) {
1855
+ return {
1856
+ pid: transaction.worker.pid,
1857
+ processGroupId: transaction.worker.processGroupId,
1858
+ fingerprint: transaction.worker.fingerprint,
1859
+ cliPath: transaction.worker.cliPath,
1860
+ logFilePath: transaction.worker.logFilePath,
1861
+ };
1862
+ }
1863
+ await coordinator.finishTransaction(
1864
+ payload.token,
1865
+ false,
1866
+ 'The upgrade worker could not be launched.',
1867
+ launchError instanceof Error ? launchError.message : String(launchError),
1868
+ );
1869
+ } catch (errorArg) {
1870
+ errors.push(errorArg);
1871
+ }
1872
+ try {
1873
+ await optionsArg.lock.release();
1874
+ } catch (errorArg) {
1875
+ errors.push(errorArg);
1876
+ }
1877
+ if (errors.length > 1) {
1878
+ throw new AggregateError(errors, 'The upgrade worker could not be launched and its cleanup was incomplete.');
1879
+ }
1880
+ throw launchError;
1881
+ };
1882
+
1765
1883
  const launchDetachedRecoveryWorker = async (optionsArg: {
1766
1884
  installation: IPnpmGlobalInstallation;
1767
1885
  payload: IUpgradeWorkerPayload;
@@ -2653,7 +2653,7 @@ export const assertTerminalResizeRequest = (
2653
2653
  };
2654
2654
 
2655
2655
  /** One answer list per question, in question order; null rejects the request. */
2656
- const assertQuestionAnswers = (valueArg: unknown): string[][] | null => {
2656
+ export const assertQuestionAnswers = (valueArg: unknown): string[][] | null => {
2657
2657
  if (valueArg === null) return null;
2658
2658
  if (!Array.isArray(valueArg) || valueArg.length === 0 || valueArg.length > 16) {
2659
2659
  throw new Error('answers must be null or contain 1-16 per-question answer lists.');
@@ -280,11 +280,14 @@ const visitStrings = (valueArg: unknown, pathArg: string, visitorArg: (textArg:
280
280
  else if (isPlainObject(valueArg)) for (const [key, item] of Object.entries(valueArg)) visitStrings(item, `${pathArg}.${key}`, visitorArg);
281
281
  };
282
282
 
283
- /** Admits a master document or throws naming the first offending field. */
284
- export const validateMaster = (valueArg: unknown): IConfigurationMaster => {
283
+ /**
284
+ * Admits a master document or throws naming the first offending field. `save` checks a document being saved rather than
285
+ * read: it refuses what this release reads but only a later one writes.
286
+ */
287
+ export const validateMaster = (valueArg: unknown, optionsArg: { save?: boolean } = {}): IConfigurationMaster => {
285
288
  if (!isPlainObject(valueArg)) invalid('master', 'must be an object.');
286
289
  exactKeys(valueArg, 'master', ['instructions', 'harnessInstructions', 'drivers', 'skills', 'agents', 'commands', 'mcpServers', 'policy'], ['nativeSettings', 'inference', 'fleet']);
287
- if (valueArg.fleet !== undefined) validateFleetConfiguration(valueArg.fleet);
290
+ if (valueArg.fleet !== undefined) validateFleetConfiguration(valueArg.fleet, optionsArg);
288
291
  if (Buffer.byteLength(JSON.stringify(valueArg), 'utf8') > maxMasterBytes) invalid('master', 'exceeds 4 MiB.');
289
292
  text(valueArg.instructions, 'instructions');
290
293
  if (!isPlainObject(valueArg.harnessInstructions)) invalid('harnessInstructions', 'must map harnesses to text.');
@@ -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.