agl 43.3.1 → 43.4.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 (85) hide show
  1. package/changelog.md +22 -0
  2. package/dist_serve/bundle.js +1377 -1375
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_ts/00_commitinfo_data.js +1 -1
  5. package/dist_ts/aglapi/interfaces.d.ts +5 -0
  6. package/dist_ts/aglapi/interfaces.js +2 -1
  7. package/dist_ts/classes.authstore.js +5 -2
  8. package/dist_ts/classes.claudeharness.js +4 -3
  9. package/dist_ts/classes.codexclientadapter.d.ts +5 -0
  10. package/dist_ts/classes.codexclientadapter.js +12 -6
  11. package/dist_ts/classes.controller.d.ts +33 -9
  12. package/dist_ts/classes.controller.js +173 -113
  13. package/dist_ts/classes.flexservice.d.ts +12 -1
  14. package/dist_ts/classes.flexservice.js +44 -13
  15. package/dist_ts/classes.flexstore.d.ts +20 -0
  16. package/dist_ts/classes.flexstore.js +30 -1
  17. package/dist_ts/classes.mcpclient.d.ts +2 -2
  18. package/dist_ts/classes.mcpclient.js +14 -9
  19. package/dist_ts/classes.mcptools.d.ts +1 -1
  20. package/dist_ts/classes.mcptools.js +2 -1
  21. package/dist_ts/classes.opencodeclient.js +20 -4
  22. package/dist_ts/driver/functions.driverinstructions.d.ts +1 -1
  23. package/dist_ts/driver/functions.driverinstructions.js +2 -1
  24. package/dist_ts/fleet/classes.deploymodels.d.ts +58 -1
  25. package/dist_ts/fleet/classes.deploymodels.js +121 -2
  26. package/dist_ts/fleet/classes.deploymonitor.d.ts +193 -47
  27. package/dist_ts/fleet/classes.deploymonitor.js +548 -180
  28. package/dist_ts/fleet/classes.gitfacts.d.ts +4 -1
  29. package/dist_ts/fleet/classes.gitfacts.js +13 -10
  30. package/dist_ts/fleet/classes.service.d.ts +2 -0
  31. package/dist_ts/fleet/classes.service.js +6 -3
  32. package/dist_ts/fleet/functions.deployprobes.js +21 -2
  33. package/dist_ts/fleet/functions.deploystatus.d.ts +26 -0
  34. package/dist_ts/fleet/functions.deploystatus.js +33 -0
  35. package/dist_ts/fleet/functions.deployvalidation.d.ts +1 -0
  36. package/dist_ts/fleet/functions.deployvalidation.js +5 -2
  37. package/dist_ts/functions.deploycli.js +3 -2
  38. package/dist_ts/functions.deviceapi.d.ts +7 -6
  39. package/dist_ts/functions.deviceapi.js +13 -5
  40. package/dist_ts/functions.mcpdeploytools.js +3 -1
  41. package/dist_ts/functions.promptreply.d.ts +13 -0
  42. package/dist_ts/functions.promptreply.js +17 -0
  43. package/dist_ts/interfaces.flexipc.d.ts +17 -9
  44. package/dist_ts/interfaces.flexipc.js +19 -20
  45. package/dist_ts_interfaces/deployments.d.ts +38 -6
  46. package/dist_ts_interfaces/deployments.js +7 -3
  47. package/dist_ts_interfaces/devices.d.ts +2 -1
  48. package/dist_ts_interfaces/devices.js +1 -1
  49. package/dist_ts_interfaces/inbox.d.ts +10 -1
  50. package/dist_ts_interfaces/inbox.js +1 -1
  51. package/dist_ts_interfaces/mcprequests.d.ts +1 -1
  52. package/package.json +5 -5
  53. package/readme.md +30 -12
  54. package/ts/00_commitinfo_data.ts +1 -1
  55. package/ts/aglapi/interfaces.ts +1 -0
  56. package/ts/classes.authstore.ts +4 -1
  57. package/ts/classes.claudeharness.ts +3 -2
  58. package/ts/classes.codexclientadapter.ts +11 -5
  59. package/ts/classes.controller.ts +188 -128
  60. package/ts/classes.flexservice.ts +57 -14
  61. package/ts/classes.flexstore.ts +40 -0
  62. package/ts/classes.mcpclient.ts +14 -5
  63. package/ts/classes.mcptools.ts +1 -0
  64. package/ts/classes.opencodeclient.ts +23 -3
  65. package/ts/driver/functions.driverinstructions.ts +1 -0
  66. package/ts/fleet/classes.deploymodels.ts +113 -1
  67. package/ts/fleet/classes.deploymonitor.ts +565 -179
  68. package/ts/fleet/classes.gitfacts.ts +10 -8
  69. package/ts/fleet/classes.service.ts +7 -1
  70. package/ts/fleet/functions.deployprobes.ts +16 -1
  71. package/ts/fleet/functions.deploystatus.ts +56 -0
  72. package/ts/fleet/functions.deployvalidation.ts +4 -1
  73. package/ts/functions.deploycli.ts +2 -1
  74. package/ts/functions.deviceapi.ts +19 -9
  75. package/ts/functions.mcpdeploytools.ts +2 -0
  76. package/ts/functions.promptreply.ts +20 -0
  77. package/ts/interfaces.flexipc.ts +43 -27
  78. package/ts_interfaces/deployments.ts +39 -6
  79. package/ts_interfaces/devices.schema.json +1 -1
  80. package/ts_interfaces/devices.ts +2 -1
  81. package/ts_interfaces/inbox.ts +8 -1
  82. package/ts_web/00_commitinfo_data.ts +1 -1
  83. package/ts_web/elements.deployments.ts +20 -4
  84. package/ts_web/elements.harnesscontrollerapp.ts +43 -13
  85. package/ts_web/elements.inbox.ts +3 -3
@@ -5,7 +5,11 @@ import {
5
5
  type IFlexModelChoiceDocument,
6
6
  assertFlexModelChoiceDocument,
7
7
  } from './classes.flexmodels.private.js';
8
- import { FlexStore, type IFlexProjectManagementHost } from './classes.flexstore.js';
8
+ import {
9
+ FlexStore,
10
+ type IFlexProjectManagementHost,
11
+ type IFlexScopeLoadReads,
12
+ } from './classes.flexstore.js';
9
13
  import { FlexPersistenceMigrationRunner } from '../ts_migration/classes.flexmigrationrunner.js';
10
14
  import {
11
15
  assertCanonicalDirectory,
@@ -46,8 +50,10 @@ import {
46
50
  type TFlexProjectManagementSessionContext,
47
51
  type TFlexRequestMethod,
48
52
  type TFlexPromptAdmissionGeneration,
53
+ type TFlexScopeLoadMetrics,
49
54
  type TFlexSessionGeneration,
50
55
  type TFlexSessionGenerationCohortEntry,
56
+ type TFlexSessionIdentity,
51
57
  createFlexServiceError,
52
58
  flexGenerationLeaseCleanupTimeoutMs,
53
59
  flexIntelligenceInstallationScopeId,
@@ -64,6 +70,7 @@ import {
64
70
  flexIpcMaximumPromptQueueEntries,
65
71
  flexIpcMaximumQueuedSessionChangeBytes,
66
72
  flexIpcMaximumQueuedSessionChanges,
73
+ flexIpcMaximumSessionIdentities,
67
74
  flexIpcMaximumDeltaBytes,
68
75
  flexIpcProtocolVersion,
69
76
  flexIpcReversionMaintenanceTimeoutMs,
@@ -341,6 +348,26 @@ export const isReadOnlyFlexToolCall = (callArg: { toolName: string; input: unkno
341
348
  && callArg.input !== null
342
349
  && (callArg.input as { action?: unknown }).action === 'list');
343
350
 
351
+ /**
352
+ * The controller log line of one FlexHarness load of a project's sessions (AGL-1713): what FlexHarness
353
+ * measured, with the snapshots the store read and decoded for that load.
354
+ */
355
+ export const formatFlexScopeLoadLine = (
356
+ metricsArg: TFlexScopeLoadMetrics,
357
+ readsArg: IFlexScopeLoadReads,
358
+ ): string => `Flex project load: ${JSON.stringify({
359
+ projectId: metricsArg.scopeId,
360
+ outcome: metricsArg.outcome,
361
+ sessions: metricsArg.sessions,
362
+ snapshotsRead: readsArg.snapshots,
363
+ bytesRead: readsArg.bytes,
364
+ parseMs: Math.round(readsArg.decodeMs),
365
+ storeReadMs: Math.round(metricsArg.storeReadMs),
366
+ agentSessionMs: Math.round(metricsArg.agentSessionMs),
367
+ repairMs: Math.round(metricsArg.repairMs),
368
+ totalMs: Math.round(metricsArg.totalMs),
369
+ })}`;
370
+
344
371
  export const createFlexBuiltInTools = (): plugins.flexharness.IFlexBuiltInToolsOptions => ({
345
372
  renameSession: true,
346
373
  projectManagement: {
@@ -355,7 +382,7 @@ const projectSerializedMethods: ReadonlySet<TFlexRequestMethod> = new Set([
355
382
  'project.remove',
356
383
  'intelligence.start',
357
384
  'intelligence.cancel',
358
- 'session.list',
385
+ 'session.identities',
359
386
  'session.create',
360
387
  'session.get',
361
388
  'session.cache.warm',
@@ -398,7 +425,7 @@ const projectScopedMethods: ReadonlySet<TFlexRequestMethod> = new Set([
398
425
  'intelligence.start',
399
426
  'intelligence.get',
400
427
  'intelligence.cancel',
401
- 'session.list',
428
+ 'session.identities',
402
429
  'session.create',
403
430
  'session.get',
404
431
  'session.metrics',
@@ -988,6 +1015,7 @@ export class FlexService {
988
1015
  reversionPolicy: 'workspace-required',
989
1016
  slashCommands: [this.worktreeSlashCommand()],
990
1017
  stores: store,
1018
+ scopeLoadObserver: (metrics) => this.reportScopeLoad(store, metrics),
991
1019
  builtInTools: createFlexBuiltInTools(),
992
1020
  toolOutputLimits: { maxDepth: 12, maxBytes: toolOutputBytes },
993
1021
  toolCatalog: { codeMode: true },
@@ -1036,6 +1064,15 @@ export class FlexService {
1036
1064
  }
1037
1065
  }
1038
1066
 
1067
+ /**
1068
+ * Writes one line per FlexHarness load of a project to stderr, which the supervisor writes to the
1069
+ * controller log, whatever the load's outcome; the store's reads of that load end with it.
1070
+ */
1071
+ private reportScopeLoad(storeArg: FlexStore, metricsArg: TFlexScopeLoadMetrics): void {
1072
+ const reads = storeArg.takeScopeLoadReads(metricsArg.storageKey);
1073
+ process.stderr.write(`${formatFlexScopeLoadLine(metricsArg, reads)}\n`);
1074
+ }
1075
+
1039
1076
  /**
1040
1077
  * An opaque FlexHarness projection that failed the initialization, restated with the raw failure
1041
1078
  * it replaced, and the harness step that met it, as its cause.
@@ -1246,19 +1283,25 @@ export class FlexService {
1246
1283
  const payload = payloadArg as IFlexRequestMap['configuration.adapt']['request'];
1247
1284
  return { result: await this.adaptConfiguration(payload, signalArg) };
1248
1285
  }
1249
- case 'session.list': {
1250
- const payload = payloadArg as IFlexRequestMap['session.list']['request'];
1251
- const sessions = (await harness.listSessions(payload.scopeId)).toSorted(
1252
- (left, right) => right.updatedAt.localeCompare(left.updatedAt)
1253
- || left.sessionId.localeCompare(right.sessionId),
1254
- );
1255
- const offset = payload.offset ?? 0;
1256
- const limit = payload.limit ?? 50;
1286
+ case 'session.identities': {
1287
+ const payload = payloadArg as IFlexRequestMap['session.identities']['request'];
1288
+ // FlexHarness answers from the project's metadata, before a load of its histories settles.
1289
+ const identities = await harness.listSessionIdentities(payload.scopeId);
1290
+ if (identities.length > flexIpcMaximumSessionIdentities) {
1291
+ throw new FlexServiceError('LIMIT_EXCEEDED');
1292
+ }
1257
1293
  return {
1258
1294
  result: {
1259
- sessions: sessions.slice(offset, offset + limit),
1260
- total: sessions.length,
1261
- truncated: offset + limit < sessions.length,
1295
+ sessions: identities.map((identity) => ({
1296
+ sessionId: identity.sessionId,
1297
+ sessionGenerationId: identity.sessionGenerationId,
1298
+ sessionGenerationSequence: identity.sessionGenerationSequence,
1299
+ ...(identity.parentSessionId === undefined
1300
+ ? {}
1301
+ : { parentSessionId: identity.parentSessionId }),
1302
+ })).sort((left, right) => (
1303
+ left.sessionId < right.sessionId ? -1 : left.sessionId > right.sessionId ? 1 : 0
1304
+ )),
1262
1305
  },
1263
1306
  };
1264
1307
  }
@@ -104,6 +104,16 @@ export interface IFlexTranscriptMigrationPage {
104
104
  nextCursor?: TFlexObjectId;
105
105
  }
106
106
 
107
+ /** What the store read for one FlexHarness load of a storage key (AGL-1713). */
108
+ export interface IFlexScopeLoadReads {
109
+ /** Private snapshots read from the database; a cached one costs no read and is not counted. */
110
+ snapshots: number;
111
+ /** Their JSON bytes. */
112
+ bytes: number;
113
+ /** Decoding them: base64, chunk and snapshot SHA-256, concatenation, UTF-8 and `JSON.parse`. */
114
+ decodeMs: number;
115
+ }
116
+
107
117
  export interface IFlexStoreOptions {
108
118
  database: plugins.nosqldb.SmartdataDb;
109
119
  controllerId: string;
@@ -1268,6 +1278,12 @@ export class FlexStore implements plugins.flexharness.IFlexHarnessStores {
1268
1278
  /** Transcripts by id; they are addressed by their content, so a cached one never goes stale. */
1269
1279
  private readonly transcriptCache = new Map<string, IFlexCachedTranscript>();
1270
1280
  private transcriptCacheBytes = 0;
1281
+ /**
1282
+ * What FlexHarness's load of each storage key has read so far: opened by the load's first read,
1283
+ * its scope snapshot, and ended by the load's report (`takeScopeLoadReads`), a purge or the
1284
+ * close. At most one entry per storage key, numbers only.
1285
+ */
1286
+ private readonly scopeLoadReads = new Map<string, IFlexScopeLoadReads>();
1271
1287
 
1272
1288
  constructor(optionsArg: IFlexStoreOptions) {
1273
1289
  assertIdentifier(optionsArg.controllerId, 'controllerId');
@@ -1638,6 +1654,7 @@ export class FlexStore implements plugins.flexharness.IFlexHarnessStores {
1638
1654
  await this.runStorage(storageKeyArg, async (lease) => {
1639
1655
  this.evictProviderScope(storageKeyArg);
1640
1656
  this.forgetCachedSnapshots(storageKeyArg);
1657
+ this.scopeLoadReads.delete(storageKeyArg);
1641
1658
  let lastDomainHeadId: TFlexObjectId | undefined;
1642
1659
  while (true) {
1643
1660
  const domainHeads = await this.readDomainHeadPage({
@@ -1756,6 +1773,16 @@ export class FlexStore implements plugins.flexharness.IFlexHarnessStores {
1756
1773
  }
1757
1774
  }
1758
1775
 
1776
+ /**
1777
+ * The reads of FlexHarness's load of a storage key since it began, which end here: FlexHarness
1778
+ * reports each load once it ended, whatever its outcome.
1779
+ */
1780
+ public takeScopeLoadReads(storageKeyArg: string): IFlexScopeLoadReads {
1781
+ const reads = this.scopeLoadReads.get(storageKeyArg) ?? { snapshots: 0, bytes: 0, decodeMs: 0 };
1782
+ this.scopeLoadReads.delete(storageKeyArg);
1783
+ return reads;
1784
+ }
1785
+
1759
1786
  public async close(): Promise<void> {
1760
1787
  if (this.closeComplete) return;
1761
1788
  if (this.closePromise) return this.closePromise;
@@ -1801,6 +1828,7 @@ export class FlexStore implements plugins.flexharness.IFlexHarnessStores {
1801
1828
  }
1802
1829
  this.agentEventStores.clear();
1803
1830
  this.jobStores.clear();
1831
+ this.scopeLoadReads.clear();
1804
1832
  const releaseResults = await Promise.allSettled(
1805
1833
  [...this.heldLeases.values()].map((lease) => this.releaseHeldLease(
1806
1834
  lease,
@@ -1822,6 +1850,11 @@ export class FlexStore implements plugins.flexharness.IFlexHarnessStores {
1822
1850
  }
1823
1851
 
1824
1852
  private async loadScope(storageKeyArg: string): Promise<TFlexScopeSnapshot | undefined> {
1853
+ // FlexHarness loads a scope's sessions after its scope snapshot, so its reads count from here on
1854
+ // until the load reports. A load already counting keeps what it read.
1855
+ if (!this.scopeLoadReads.has(storageKeyArg)) {
1856
+ this.scopeLoadReads.set(storageKeyArg, { snapshots: 0, bytes: 0, decodeMs: 0 });
1857
+ }
1825
1858
  return this.runStorage(storageKeyArg, async () => {
1826
1859
  const loaded = await this.loadDomainDirect<TFlexScopeSnapshot>(
1827
1860
  { storageKey: storageKeyArg, domain: 'scope' },
@@ -2877,6 +2910,7 @@ export class FlexStore implements plugins.flexharness.IFlexHarnessStores {
2877
2910
  scopeId: storageKeyArg,
2878
2911
  }),
2879
2912
  );
2913
+ const decodeStartedAt = performance.now();
2880
2914
  const chunks: Buffer[] = [];
2881
2915
  for (const chunkManifest of manifestArg.chunks) {
2882
2916
  abortSignalArg?.throwIfAborted();
@@ -2923,6 +2957,12 @@ export class FlexStore implements plugins.flexharness.IFlexHarnessStores {
2923
2957
  { cause: errorArg },
2924
2958
  );
2925
2959
  }
2960
+ const scopeLoadReads = this.scopeLoadReads.get(storageKeyArg);
2961
+ if (scopeLoadReads) {
2962
+ scopeLoadReads.snapshots += 1;
2963
+ scopeLoadReads.bytes += manifestArg.bytes;
2964
+ scopeLoadReads.decodeMs += performance.now() - decodeStartedAt;
2965
+ }
2926
2966
  abortSignalArg?.throwIfAborted();
2927
2967
  try {
2928
2968
  return await validateArg(parsed);
@@ -10,7 +10,7 @@ import { readTicketRevisionConflict, ticketErrorMessages, type TTicketClientErro
10
10
  import { assertMcpTicketRequest, assertTicketResponse } from './functions.ticketvalidation.js';
11
11
  import { assertSessionFeedWireRequest, assertSessionFeedWireResponse } from './functions.sessionfeedvalidation.js';
12
12
  import { assertFleetDeployResponse, assertFleetDeployWireRequest } from './fleet/functions.deployvalidation.js';
13
- import type { IFleetDeployOperations, TFleetDeployOperation } from '../ts_interfaces/deployments.js';
13
+ import { fleetDeployRefreshClientMarginMs, fleetDeployRefreshWaitMs, type IFleetDeployOperations, type TFleetDeployOperation } from '../ts_interfaces/deployments.js';
14
14
  import type { IReq_ControllerMcpSessionFeedAcknowledge, IReq_ControllerMcpSessionFeedList } from '../ts_interfaces/sessionfeed.js';
15
15
  import { isProxyCapacityAnswer, type IProxyCapacityAnswer, type IProxyCapacityRequest } from '../ts_interfaces/proxycapacity.js';
16
16
  import {
@@ -83,6 +83,8 @@ import {
83
83
  } from './functions.jobvalidation.js';
84
84
 
85
85
  const defaultRequestTimeoutMs = 30_000;
86
+ /** A deploy `refresh` waits for its check up to `fleetDeployRefreshWaitMs` on the controller before it answers. */
87
+ const deployRefreshRequestTimeoutMs = fleetDeployRefreshWaitMs + fleetDeployRefreshClientMarginMs;
86
88
  const maximumSafeServerErrorBytes = 1024;
87
89
  const maximumScratchpadCharacters = 32_768;
88
90
  const maximumScratchpadBytes = 128 * 1024;
@@ -778,13 +780,15 @@ export class ControllerMcpClient {
778
780
  const wireRequest = assertSessionFeedWireRequest('agl.mcp.sessionfeed.acknowledge', request);
779
781
  return this.dispatchAfterHandshake('agl.mcp.sessionfeed.acknowledge', wireRequest as IReq_ControllerMcpSessionFeedAcknowledge['request'], signal, true);
780
782
  }
781
- /** Deploy status, history, a probe now or release state as the local owner reads them (`agl deploy`, `agl release status`). */
783
+ /** Deploy status, history, a probe now, release state or a full check now, as the local owner asks (`agl deploy`, `agl release status`, MCP). */
782
784
  public async deploy<TOperation extends TFleetDeployOperation>(operation: TOperation,
783
785
  request: IFleetDeployOperations[TOperation]['request'] & { ownerToken: string }, signal?: AbortSignal,
784
786
  ): Promise<IFleetDeployOperations[TOperation]['response']> {
785
787
  const method = `agl.mcp.deploy.${operation}` as const;
786
788
  const wireRequest = assertFleetDeployWireRequest(method, request);
787
- return this.dispatchAfterHandshake(method, wireRequest as never, signal, operation === 'probe') as Promise<IFleetDeployOperations[TOperation]['response']>;
789
+ return this.dispatchAfterHandshake(method, wireRequest as never, signal, operation === 'probe' || operation === 'refresh',
790
+ operation === 'refresh' ? Math.max(this.requestTimeoutMs, deployRefreshRequestTimeoutMs) : undefined,
791
+ ) as Promise<IFleetDeployOperations[TOperation]['response']>;
788
792
  }
789
793
  public async fleetStatus(id: string, ownerToken: string, signal?: AbortSignal, ticketKey?: string): Promise<IFleetOperation> {
790
794
  return this.dispatchAfterHandshake('agl.mcp.fleet.status', { id, ownerToken, ...(ticketKey ? { ticketKey } : {}) }, signal, false);
@@ -818,10 +822,12 @@ export class ControllerMcpClient {
818
822
  requestArg: TRequestForMethod<TMethod>,
819
823
  signalArg: AbortSignal | undefined,
820
824
  mutatingArg: boolean,
825
+ /** This request's own deadline, for one the controller answers only after a bounded wait; the client's otherwise. */
826
+ timeoutMsArg?: number,
821
827
  ): Promise<TResponseForMethod<TMethod>> {
822
828
  const descriptor = await this.handshake(signalArg);
823
829
  try {
824
- return await this.dispatch(descriptor, methodArg, requestArg, signalArg, mutatingArg);
830
+ return await this.dispatch(descriptor, methodArg, requestArg, signalArg, mutatingArg, timeoutMsArg);
825
831
  } catch (errorArg) {
826
832
  if (mutatingArg && errorArg instanceof ControllerMcpClientError
827
833
  && (errorArg.code === 'PROTOCOL_MISMATCH' || errorArg.code === 'RESPONSE_LIMIT')) {
@@ -906,6 +912,7 @@ export class ControllerMcpClient {
906
912
  requestArg: TRequestForMethod<TMethod>,
907
913
  signalArg: AbortSignal | undefined,
908
914
  outcomeMayBeUnknownArg: boolean,
915
+ timeoutMsArg?: number,
909
916
  ): Promise<TResponseForMethod<TMethod>> {
910
917
  const requestInstanceId = plugins.crypto.randomBytes(16).toString('base64url');
911
918
  const correlationId = plugins.crypto.randomBytes(16).toString('base64url');
@@ -931,6 +938,7 @@ export class ControllerMcpClient {
931
938
  body,
932
939
  signalArg,
933
940
  () => { dispatchFinished = true; },
941
+ timeoutMsArg,
934
942
  );
935
943
  } catch (errorArg) {
936
944
  if (errorArg instanceof ControllerMcpClientError) throw errorArg;
@@ -1044,8 +1052,9 @@ export class ControllerMcpClient {
1044
1052
  bodyArg: Buffer,
1045
1053
  signalArg: AbortSignal | undefined,
1046
1054
  onDispatchFinishedArg: () => void,
1055
+ timeoutMsArg = this.requestTimeoutMs,
1047
1056
  ): Promise<Buffer> {
1048
- const timeoutSignal = AbortSignal.timeout(this.requestTimeoutMs);
1057
+ const timeoutSignal = AbortSignal.timeout(timeoutMsArg);
1049
1058
  const signal = signalArg === undefined
1050
1059
  ? timeoutSignal
1051
1060
  : AbortSignal.any([signalArg, timeoutSignal]);
@@ -99,6 +99,7 @@ export const aglMcpToolNames = [
99
99
  'deploy_status',
100
100
  'deploy_history',
101
101
  'deploy_probe',
102
+ 'deploy_refresh',
102
103
  'release_status',
103
104
  ] as const;
104
105
 
@@ -44,6 +44,7 @@ import type {
44
44
  TOpenCodeSdkClient,
45
45
  } from './interfaces.opencode.js';
46
46
  import { boundLiveToolExecution } from './functions.livetoolbounding.js';
47
+ import { promptNoLongerPending } from './functions.promptreply.js';
47
48
  import {
48
49
  openCodeSessionIdentitySnapshotCapability,
49
50
  openCodeSessionProviderGeneration,
@@ -140,6 +141,19 @@ const isOpenCodeNotFoundError = (valueArg: unknown): boolean => {
140
141
  && isOpenCodeNotFoundBody(valueArg.cause.body);
141
142
  };
142
143
 
144
+ /**
145
+ * OpenCode's refusal of an answer to a permission or question it no longer holds (answered or withdrawn meanwhile): a
146
+ * 404 with its `PermissionNotFoundError` or `QuestionNotFoundError`, before it applies anything.
147
+ */
148
+ const isOpenCodePromptNotFoundError = (
149
+ valueArg: unknown,
150
+ tagArg: 'PermissionNotFoundError' | 'QuestionNotFoundError',
151
+ ): boolean => isRecord(valueArg)
152
+ && isRecord(valueArg.cause)
153
+ && valueArg.cause.status === 404
154
+ && isRecord(valueArg.cause.body)
155
+ && valueArg.cause.body._tag === tagArg;
156
+
143
157
  const hasExactKeys = (
144
158
  valueArg: Record<string, unknown>,
145
159
  requiredArg: readonly string[],
@@ -3312,7 +3326,9 @@ export class OpenCodeClientAdapter implements IOpenCodeSessionIdentitySnapshotCa
3312
3326
  },
3313
3327
  { signal: requestSignal }
3314
3328
  )
3315
- );
3329
+ ).catch((errorArg: unknown) => {
3330
+ throw isOpenCodePromptNotFoundError(errorArg, 'QuestionNotFoundError') ? promptNoLongerPending('question') : errorArg;
3331
+ });
3316
3332
  if (typeof response !== 'boolean') {
3317
3333
  throw new Error('OpenCode returned an invalid question result.');
3318
3334
  }
@@ -3333,7 +3349,9 @@ export class OpenCodeClientAdapter implements IOpenCodeSessionIdentitySnapshotCa
3333
3349
  },
3334
3350
  { signal: requestSignal }
3335
3351
  )
3336
- );
3352
+ ).catch((errorArg: unknown) => {
3353
+ throw isOpenCodePromptNotFoundError(errorArg, 'QuestionNotFoundError') ? promptNoLongerPending('question') : errorArg;
3354
+ });
3337
3355
  if (typeof response !== 'boolean') {
3338
3356
  throw new Error('OpenCode returned an invalid question result.');
3339
3357
  }
@@ -3365,7 +3383,9 @@ export class OpenCodeClientAdapter implements IOpenCodeSessionIdentitySnapshotCa
3365
3383
  },
3366
3384
  { signal: requestSignal }
3367
3385
  )
3368
- );
3386
+ ).catch((errorArg: unknown) => {
3387
+ throw isOpenCodePromptNotFoundError(errorArg, 'PermissionNotFoundError') ? promptNoLongerPending('permission') : errorArg;
3388
+ });
3369
3389
  if (typeof response !== 'boolean') {
3370
3390
  throw new Error('OpenCode returned an invalid permission result.');
3371
3391
  }
@@ -40,6 +40,7 @@ You keep the owner's board true and the work moving. The owner talks to you thro
40
40
 
41
41
  ## Deployments
42
42
  - What runs where is deploy_status, never your notes or memory. release_status says what a repository's next release would ship.
43
+ - deploy_status answers the status AGL checked last (its checkedAt); AGL checks every five minutes. Call deploy_refresh to check now when the answer must be current: after a release or land of your own the board should show at once, when the owner asks about deployments, or when checkedAt looks stale. It waits up to a minute; refreshing means the check runs on.
43
44
  - Every deploy needs the owner's word, given on a deploy plan: a ticket whose deployPlan names the target and the release. AGL asks the owner on it (deploy now, in the next window, or hold) and closes the ticket once the target runs the release. The board pump plans one for a target that runs behind a release out for a day; you may plan one yourself (ticket_create or ticket_update deployPlan). Never deploy what waits for the owner's answer or is held.
44
45
  - A plan assigned to a direct report is that report's subject: it deploys, and the owner's answer reaches it; route the pump's notices about it to that report. An unassigned plan is yours to deploy.
45
46
  - When a deploy may run is the target's (deploy_status deployWhen): any time; only inside a maintenance window planned for it; or, for the AGL controller, when no session is busy. "Deploy now" is the owner's word to deploy at once, outside a window too. "In the next window" waits for the target's next window the owner gave: propose one when none is (a ticket with a maintenanceWindow: from, to, targets), which asks the owner and counts once approved. Only the owner answers a deploy plan's or a window's question. The controller is deployed with agl upgrade, which keeps its own owner gate.
@@ -1,5 +1,9 @@
1
1
  import * as plugins from '../plugins.js';
2
- import { fleetDeployTargetIdPattern, type IFleetDeployObservation } from '../../ts_interfaces/deployments.js';
2
+ import {
3
+ fleetDeployTargetIdPattern, type IFleetDeployObservation, type IFleetDeployPlan, type IFleetDeployStatusFailure, type IFleetDeployTargetStatus,
4
+ type IFleetDeployWindow, type IFleetRepositoryReleaseStatus,
5
+ } from '../../ts_interfaces/deployments.js';
6
+ import { ticketColumns } from '../../ts_interfaces/tickets.js';
3
7
 
4
8
  const timestamp = plugins.z.iso.datetime();
5
9
  const version = plugins.z.string().regex(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u);
@@ -42,3 +46,111 @@ export class DeployObservationModel extends plugins.nosqldb.SmartDataDbDoc<Deplo
42
46
  @plugins.nosqldb.svDb() public previousVersion?: string;
43
47
  @plugins.nosqldb.svDb() public artifacts!: IFleetDeployObservation['artifacts'];
44
48
  }
49
+
50
+ /** A maintenance window as stored: where it stands (scheduled, active, done) is derived from the clock when read. */
51
+ export type TDeployStoredWindow = Omit<IFleetDeployWindow, 'state'>;
52
+ /** A deploy plan as stored: the window it is queued into is derived from the clock when read. */
53
+ export type TDeployStoredPlan = Omit<IFleetDeployPlan, 'window'>;
54
+ /** A target's status as stored: whether a deploy may run now, the busy sessions and its windows are derived when read. */
55
+ export type TDeployStoredTarget = Omit<IFleetDeployTargetStatus, 'busySessions' | 'deployOpen' | 'windows' | 'deployPlans'> & {
56
+ deployPlans: TDeployStoredPlan[];
57
+ };
58
+ /**
59
+ * What one computation of the deploy monitor found (AGL-1704): every target's status, every maintenance window of a
60
+ * ticket that is not done, the release state of the repositories the targets, landed tickets and release plans name,
61
+ * and the tickets the `undeployed` AutoLabel marks. Nothing in it depends on the clock or on the sessions busy now.
62
+ */
63
+ export type TDeployStatusContent = {
64
+ status: { targets: TDeployStoredTarget[]; windows: TDeployStoredWindow[] };
65
+ release: { repositories: IFleetRepositoryReleaseStatus[] };
66
+ undeployed: string[];
67
+ };
68
+
69
+ const label = plugins.z.string().max(1024);
70
+ const repoName = plugins.z.string().min(1).max(1024);
71
+ const ticketKey = plugins.z.string().min(1).max(64);
72
+ const deployTicketFields = { key: ticketKey, title: plugins.z.string().max(256), priority: plugins.z.enum(['none', 'low', 'normal', 'high', 'urgent']),
73
+ columnId: plugins.z.enum(ticketColumns), version: label.optional() };
74
+ const deployTicket = plugins.z.object(deployTicketFields).strict();
75
+ const release = plugins.z.object({ version: label, sha: plugins.z.string().regex(/^[a-f0-9]{7,64}$/u), taggedAt: timestamp.optional() }).strict();
76
+ const maintenanceWindow = plugins.z.object({ ...deployTicketFields, from: timestamp, to: timestamp, targets: plugins.z.array(targetId),
77
+ go: plugins.z.enum(['given', 'waiting', 'declined']), questionId: label.optional() }).strict();
78
+ const plan = plugins.z.object({ ...deployTicketFields, target: targetId, version: label, questionId: label,
79
+ go: plugins.z.enum(['waiting', 'now', 'window', 'idle', 'hold']), answeredAt: timestamp.optional(), assignee: label.optional() }).strict();
80
+ const releasePlanTicket = plugins.z.object({ ...deployTicketFields, plannedVersion: label.optional() }).strict();
81
+ const target = plugins.z.object({
82
+ id: targetId, name: label.optional(), environment: label.optional(), repo: repoName, project: label, deploys: label.optional(), downtime: label.optional(),
83
+ deployWhen: plugins.z.enum(['anytime', 'window']).optional(), builtIn: plugins.z.literal(true).optional(),
84
+ probe: plugins.z.discriminatedUnion('kind', [
85
+ plugins.z.object({ kind: plugins.z.literal('controller') }).strict(),
86
+ plugins.z.object({ kind: plugins.z.literal('http'), url: plugins.z.string().max(2048), versionPointer: label.optional(), shaPointer: label.optional() }).strict(),
87
+ ]),
88
+ }).strict();
89
+ const storedTarget = plugins.z.object({
90
+ target, repository: repoName.optional(),
91
+ running: plugins.z.object({ version: label, sha: plugins.z.string().regex(/^[a-f0-9]{7,64}$/u).optional(), since: timestamp, previousVersion: label.optional(),
92
+ rolledBack: plugins.z.literal(true).optional(), untagged: plugins.z.literal(true).optional() }).strict().optional(),
93
+ probe: plugins.z.object({ state: plugins.z.enum(['up', 'down', 'unknown']), checkedAt: timestamp.optional(), downSince: timestamp.optional(),
94
+ error: plugins.z.string().max(2048).optional() }).strict(),
95
+ latest: release.optional(),
96
+ notRunning: plugins.z.object({ releases: plugins.z.array(release), tickets: plugins.z.array(deployTicket) }).strict(),
97
+ landedAfterLatest: plugins.z.array(deployTicket),
98
+ openBugs: plugins.z.array(plugins.z.object({ ...deployTicketFields, foundIn: label, fixLandedSha: plugins.z.string().regex(/^[a-f0-9]{7,64}$/u).optional(),
99
+ fixedIn: label.optional() }).strict()),
100
+ plans: plugins.z.array(releasePlanTicket),
101
+ deployWhen: plugins.z.enum(['anytime', 'window', 'idle']),
102
+ deployPlans: plugins.z.array(plan),
103
+ }).strict();
104
+ /**
105
+ * The content of the stored deploy status, parsed as it is loaded. Content this release cannot parse (another release
106
+ * wrote it, or it is damaged) is not served: the controller starts cold and its next computation overwrites it.
107
+ */
108
+ export const deployStatusContentSchema: plugins.z.ZodType<TDeployStatusContent> = plugins.z.object({
109
+ status: plugins.z.object({ targets: plugins.z.array(storedTarget), windows: plugins.z.array(maintenanceWindow) }).strict(),
110
+ release: plugins.z.object({ repositories: plugins.z.array(plugins.z.object({ repo: repoName, id: label, latest: release.optional(),
111
+ plans: plugins.z.array(releasePlanTicket), landedAfterLatest: plugins.z.array(deployTicket), targets: plugins.z.array(targetId) }).strict()) }).strict(),
112
+ undeployed: plugins.z.array(ticketKey),
113
+ }).strict();
114
+ /** The last computation that failed, as stored beside the content it left standing. */
115
+ export const deployStatusFailureSchema: plugins.z.ZodType<IFleetDeployStatusFailure> = plugins.z.object({
116
+ at: timestamp, message: plugins.z.string().min(1).max(2048), reference: plugins.z.string().min(1).max(128),
117
+ }).strict();
118
+
119
+ /** The one stored deploy status of a controller: `<controllerId>:deployments`. */
120
+ export const deployStatusId = (controllerIdArg: string): string => `${controllerIdArg}:deployments`;
121
+
122
+ /**
123
+ * The stored deploy status (AGL-1704): one document per controller, which the deploy monitor writes after each
124
+ * computation and serves every read from. Its top level is fixed for good, since the exact client refuses a stored
125
+ * top-level field its model does not declare: `revision` moves when the content changes, `computedAt` is when the
126
+ * content was last computed (at least once per pass), and `failure` is the last computation that failed while the
127
+ * content stands. `content` and `failure` are plain objects here and parsed by the monitor as it loads them, so a
128
+ * document another release wrote is still read, and overwritten, by this one.
129
+ */
130
+ export interface IDeployStatusDocument {
131
+ id: string;
132
+ controllerId: string;
133
+ revision: number;
134
+ computedAt: string;
135
+ content: Record<string, unknown>;
136
+ failure?: Record<string, unknown>;
137
+ }
138
+ const statusDocumentSchema = plugins.z.object({
139
+ id: plugins.z.string().min(1).max(512), controllerId: plugins.z.string().min(1).max(256), revision: plugins.z.number().int().nonnegative(),
140
+ computedAt: timestamp, content: plugins.z.record(plugins.z.string(), plugins.z.unknown()), failure: plugins.z.record(plugins.z.string(), plugins.z.unknown()).optional(),
141
+ }).strict();
142
+
143
+ @plugins.nosqldb.managed({ collectionName: 'agl_fleet_deploy_status' })
144
+ @plugins.nosqldb.exactPersistence({ assertDocument: (input: unknown) => {
145
+ const doc = statusDocumentSchema.parse(input);
146
+ if (doc.id !== deployStatusId(doc.controllerId)) throw new Error('Deploy status identity mismatch.');
147
+ } })
148
+ export class DeployStatusModel extends plugins.nosqldb.SmartDataDbDoc<DeployStatusModel, IDeployStatusDocument> {
149
+ declare static exact: plugins.nosqldb.TExact<DeployStatusModel>;
150
+ @plugins.nosqldb.unI() public id!: string;
151
+ @plugins.nosqldb.svDb() public controllerId!: string;
152
+ @plugins.nosqldb.svDb() public revision!: number;
153
+ @plugins.nosqldb.svDb() public computedAt!: string;
154
+ @plugins.nosqldb.svDb() public content!: Record<string, unknown>;
155
+ @plugins.nosqldb.svDb() public failure?: Record<string, unknown>;
156
+ }