agl 43.3.0 → 43.3.1

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 (71) hide show
  1. package/changelog.md +9 -0
  2. package/dist_serve/bundle.js +2 -2
  3. package/dist_serve/bundle.js.map +2 -2
  4. package/dist_ts/00_commitinfo_data.js +1 -1
  5. package/dist_ts/classes.authstore.d.ts +7 -0
  6. package/dist_ts/classes.authstore.js +9 -1
  7. package/dist_ts/classes.claudeharness.d.ts +13 -2
  8. package/dist_ts/classes.claudeharness.js +12 -5
  9. package/dist_ts/classes.controller.d.ts +27 -6
  10. package/dist_ts/classes.controller.js +136 -39
  11. package/dist_ts/classes.mcpcontrollerhost.js +4 -1
  12. package/dist_ts/classes.mcptools.js +6 -1
  13. package/dist_ts/classes.nativesessions.d.ts +12 -0
  14. package/dist_ts/classes.nativesessions.js +1 -1
  15. package/dist_ts/classes.workercallers.js +4 -2
  16. package/dist_ts/driver/classes.directreports.js +19 -19
  17. package/dist_ts/driver/classes.directreportstore.d.ts +8 -1
  18. package/dist_ts/driver/classes.directreportstore.js +20 -10
  19. package/dist_ts/fleet/classes.workers.d.ts +16 -0
  20. package/dist_ts/fleet/classes.workers.js +73 -39
  21. package/dist_ts/fleet/classes.workerstore.js +14 -8
  22. package/dist_ts/fleet/functions.workervalidation.js +10 -3
  23. package/dist_ts/fleet/interfaces.workers.d.ts +6 -2
  24. package/dist_ts/fleet/interfaces.workers.js +8 -4
  25. package/dist_ts/functions.deviceapi.d.ts +50 -3
  26. package/dist_ts/functions.deviceapi.js +174 -7
  27. package/dist_ts/functions.exactpersistence.d.ts +3 -0
  28. package/dist_ts/functions.exactpersistence.js +4 -0
  29. package/dist_ts/functions.mcpfleetworkertools.js +2 -2
  30. package/dist_ts/functions.ticketactor.d.ts +17 -1
  31. package/dist_ts/functions.ticketactor.js +55 -15
  32. package/dist_ts_interfaces/devices.d.ts +17 -4
  33. package/dist_ts_interfaces/devices.js +1 -1
  34. package/dist_ts_interfaces/fleetworkers.d.ts +32 -7
  35. package/dist_ts_interfaces/fleetworkers.js +19 -8
  36. package/dist_ts_interfaces/workercallers.d.ts +2 -0
  37. package/dist_ts_migration/classes.documentmigrationrunner.d.ts +14 -0
  38. package/dist_ts_migration/classes.documentmigrationrunner.js +20 -1
  39. package/dist_ts_migration/index.d.ts +1 -0
  40. package/dist_ts_migration/index.js +2 -1
  41. package/dist_ts_migration/v43_ticketactornames.d.ts +32 -0
  42. package/dist_ts_migration/v43_ticketactornames.js +236 -0
  43. package/package.json +1 -1
  44. package/readme.md +34 -3
  45. package/ts/00_commitinfo_data.ts +1 -1
  46. package/ts/classes.authstore.ts +10 -0
  47. package/ts/classes.claudeharness.ts +18 -4
  48. package/ts/classes.controller.ts +142 -40
  49. package/ts/classes.mcpcontrollerhost.ts +3 -0
  50. package/ts/classes.mcptools.ts +5 -0
  51. package/ts/classes.nativesessions.ts +13 -0
  52. package/ts/classes.workercallers.ts +3 -1
  53. package/ts/driver/classes.directreports.ts +18 -18
  54. package/ts/driver/classes.directreportstore.ts +20 -9
  55. package/ts/fleet/classes.workers.ts +66 -39
  56. package/ts/fleet/classes.workerstore.ts +11 -7
  57. package/ts/fleet/functions.workervalidation.ts +7 -2
  58. package/ts/fleet/interfaces.workers.ts +6 -2
  59. package/ts/functions.deviceapi.ts +227 -6
  60. package/ts/functions.exactpersistence.ts +5 -0
  61. package/ts/functions.mcpfleetworkertools.ts +1 -1
  62. package/ts/functions.ticketactor.ts +58 -14
  63. package/ts_interfaces/devices.schema.json +5 -2
  64. package/ts_interfaces/devices.ts +20 -4
  65. package/ts_interfaces/fleetworkers.ts +33 -7
  66. package/ts_interfaces/workercallers.ts +2 -0
  67. package/ts_migration/classes.documentmigrationrunner.ts +21 -0
  68. package/ts_migration/index.ts +1 -0
  69. package/ts_migration/v43_ticketactornames.ts +225 -0
  70. package/ts_web/00_commitinfo_data.ts +1 -1
  71. package/ts_web/elements.fleetworker.ts +4 -2
@@ -0,0 +1,225 @@
1
+ import * as plugins from './plugins.js';
2
+ import { TicketActivityModel, TicketBoardModel, TicketCommentModel, TicketModel, TicketQuestionModel } from '../ts/classes.ticketmodels.js';
3
+ import { AuthError } from '../ts/interfaces.auth.js';
4
+ import type { ITicketComment } from '../ts_interfaces/tickets.js';
5
+ import { TicketMigrationMarkerModel } from './v41_ticketmigrationmarkers.js';
6
+
7
+ export const ticketActorNamesMigrationId = 'v43_ticketactornames';
8
+
9
+ /**
10
+ * The names this migration writes, as AGL-1686 chose them: a session's harness label, keyed by the harness prefix of
11
+ * its session id, and the OpenCode runtime's name. This is the migration's own copy, never the runtime's table: what it
12
+ * wrote stays what it wrote when the runtime's labels change.
13
+ */
14
+ const sessionLabels = new Map<string, string>([
15
+ ['claude', 'Claude Code session'], ['codex', 'Codex session'], ['opencode', 'OpenCode session'], ['flex', 'Flex session'],
16
+ ]);
17
+ const openCodeRuntimeName = 'OpenCode';
18
+ /** The keys of a stored person (`ITicketPerson`) or actor (`ITicketActor`, which adds `role`). */
19
+ const personKeys = new Set(['id', 'name', 'kind', 'sessionId', 'role']);
20
+
21
+ /** History records one query reads. */
22
+ const pageRecords = 64;
23
+ /**
24
+ * A transaction's bound. It stops taking a ticket's history records once it has read 256 of them or rewritten 4 MiB
25
+ * of their JSON, and the next transaction goes on after the last one it took. Every transaction that rewrites any of
26
+ * a ticket's records moves that ticket's revision, and the one that takes its last record renames its document. The schema bounds one record (an activity entry holds a ticket's
27
+ * 64 Ki-character texts at most twice, before and after, about 1 MiB in the worst case; a comment 64 KiB of JSON), so a
28
+ * transaction rewrites at most about 6 MiB (the bound, one more record and the comment it holds a copy of, and the
29
+ * ticket's document) and reads at most 256 history records, whatever a ticket's history holds, far inside the engine's
30
+ * 60 s transaction lifetime.
31
+ */
32
+ const sliceRecords = 256;
33
+ const sliceBytes = 4 * 1024 * 1024;
34
+
35
+ /** What a stored person or actor is named now, or undefined when it keeps its name. */
36
+ const renamedTo = (valueArg: Record<string, unknown>): string | undefined => {
37
+ if (typeof valueArg.id !== 'string' || typeof valueArg.name !== 'string'
38
+ || !Object.keys(valueArg).every((keyArg) => personKeys.has(keyArg))) return undefined;
39
+ if (valueArg.sessionId !== undefined) {
40
+ if (typeof valueArg.sessionId !== 'string' || valueArg.name !== valueArg.sessionId) return undefined;
41
+ const separator = valueArg.sessionId.indexOf(':');
42
+ return separator > 0 ? sessionLabels.get(valueArg.sessionId.slice(0, separator)) : undefined;
43
+ }
44
+ // The OpenCode runtime's caller was named by its subject kind; no other actor was ever named so.
45
+ return valueArg.name === 'runtime' && valueArg.kind === 'worker' && valueArg.role === 'worker' ? openCodeRuntimeName : undefined;
46
+ };
47
+
48
+ /** `valueArg` with every person and actor in it renamed, at any depth; `valueArg` itself when none is. */
49
+ const renamed = <T>(valueArg: T): T => {
50
+ if (Array.isArray(valueArg)) {
51
+ const items = valueArg.map((itemArg: unknown) => renamed(itemArg));
52
+ return items.some((itemArg, indexArg) => itemArg !== valueArg[indexArg]) ? items as T : valueArg;
53
+ }
54
+ if (typeof valueArg !== 'object' || valueArg === null) return valueArg;
55
+ const record = valueArg as Record<string, unknown>;
56
+ const name = renamedTo(record);
57
+ if (name !== undefined) return { ...record, name } as T;
58
+ const entries = Object.entries(record).map(([keyArg, itemArg]) => [keyArg, renamed(itemArg)] as const);
59
+ return entries.some(([keyArg, itemArg]) => itemArg !== record[keyArg]) ? Object.fromEntries(entries) as T : valueArg;
60
+ };
61
+
62
+ const jsonBytes = (valueArg: unknown): number => Buffer.byteLength(JSON.stringify(valueArg));
63
+
64
+ /** A ticket's history is taken in this order; `ticket` is its document, taken last. */
65
+ const phases = ['activity', 'questions', 'comments', 'ticket'] as const;
66
+ interface ICursor { phase: (typeof phases)[number]; after?: string }
67
+ interface ISliceResult { cursor: ICursor; moved: boolean }
68
+
69
+ /**
70
+ * AGL-1686: tickets named the sessions acting on them by their session id (`claude:<uuid>`), and the OpenCode
71
+ * runtime's caller by its subject kind (`runtime`). Once, every person and actor stored in a ticket (its source,
72
+ * creator, last editor and assignee), its comments (author), its questions (asker and answerer) and its activity (actor,
73
+ * and every person in the snapshots its changes hold, the copy of a comment included) whose name is its session id
74
+ * takes its harness's label, and an actor named `runtime` with no session, kind and role `worker` is "OpenCode". Only
75
+ * those names change: ids, session ids and every other value stay, so a 41.1.0 controller reads the result.
76
+ *
77
+ * It works ticket by ticket. A ticket's history, the copy of a comment in its `commented` entry with the comment, and
78
+ * last its document move in one transaction, or, for a history larger than the bound above, in several. Every one of
79
+ * them that rewrites anything of the ticket moves its revision too: the board pump re-reads a ticket only when its
80
+ * revision moved, and no transaction depends on what an earlier one renamed, so a run cut short between them leaves
81
+ * nothing renamed under an unmoved revision. Each transaction that writes fences the board's revision first; none adds history, tells anyone or moves a ticket's
82
+ * column. The marker goes in the transaction that completes the last ticket (alone on an empty board), so a later start
83
+ * does nothing; a run cut short starts again and finds what it renamed already renamed.
84
+ */
85
+ export class TicketActorNamesV43Migration {
86
+ constructor(private readonly database: plugins.nosqldb.SmartdataDb | undefined) {}
87
+
88
+ /** Runs once; answers the keys of the tickets whose revision it moved. */
89
+ public async run(): Promise<string[]> {
90
+ if (!this.database) throw new AuthError('not_initialized', 'The authentication store database is unavailable.');
91
+ if (await TicketMigrationMarkerModel.exact.findStoredOne({ id: ticketActorNamesMigrationId })) return [];
92
+ const changed: string[] = [];
93
+ const session = this.database.createSession();
94
+ try {
95
+ let after: string | undefined;
96
+ while (true) {
97
+ // Ids only matter here: each ticket is read again inside the transaction that rewrites it.
98
+ const page = await TicketModel.exact.findStored({ filter: after === undefined ? {} : { id: { $gt: after } }, sort: { id: 1 },
99
+ limit: pageRecords + 1 });
100
+ const more = page.length > pageRecords;
101
+ const tickets = page.slice(0, pageRecords).map((recordArg) => recordArg.id);
102
+ if (!tickets.length) {
103
+ // An empty board: the marker alone.
104
+ await this.transaction(session, (transactionArg) => this.slice(transactionArg, undefined, { phase: 'ticket' }, changed));
105
+ return changed;
106
+ }
107
+ for (const [index, ticketId] of tickets.entries()) {
108
+ const last = !more && index === tickets.length - 1;
109
+ let cursor: ICursor = { phase: phases[0] };
110
+ while (true) {
111
+ const result = await this.transaction(session, (transactionArg) => this.slice(transactionArg, ticketId, cursor,
112
+ last ? changed : undefined));
113
+ // A ticket whose history takes several transactions may move its revision in each: it is named once.
114
+ if (result.moved && changed.at(-1) !== ticketId) changed.push(ticketId);
115
+ if (result.cursor.phase === 'ticket') break;
116
+ cursor = result.cursor;
117
+ }
118
+ }
119
+ if (!more) return changed;
120
+ after = tickets.at(-1);
121
+ }
122
+ } finally {
123
+ await session.close();
124
+ }
125
+ }
126
+
127
+ private async transaction(sessionArg: plugins.nosqldb.SmartdataSession,
128
+ sliceArg: (transactionArg: plugins.nosqldb.SmartdataSession) => Promise<ISliceResult>): Promise<ISliceResult> {
129
+ const result = await sessionArg.withTransaction(sliceArg, { timeoutMS: 60_000 });
130
+ if (!result) throw new AuthError('concurrent_change', 'A transaction of the actor-name migration did not complete.');
131
+ return result;
132
+ }
133
+
134
+ /**
135
+ * One transaction: the ticket's history records after `cursorArg` up to the bound, and, once its history is taken,
136
+ * its document. The ticket's revision moves when this transaction rewrote any of its records or renames its document,
137
+ * never because of an earlier one. With `markerArg` (the keys moved so far) the slice that completes the ticket writes the marker; with
138
+ * no ticket it writes the marker alone. Nothing outside the transaction changes here: the driver may run it again.
139
+ */
140
+ private async slice(sessionArg: plugins.nosqldb.SmartdataSession, ticketIdArg: string | undefined, cursorArg: ICursor,
141
+ markerArg: string[] | undefined): Promise<ISliceResult> {
142
+ const options = { session: sessionArg };
143
+ const board = await TicketBoardModel.exact.findStoredOne({ id: 'global' }, options);
144
+ if (!board) throw new AuthError('not_initialized', 'The ticket board is unavailable.');
145
+ let fenced = false;
146
+ const fence = async (): Promise<void> => {
147
+ if (fenced) return;
148
+ const transitioned = await TicketBoardModel.exact.transition({ current: board, change: (modelArg) => { modelArg.revision += 1; } }, options);
149
+ if (transitioned.status !== 'transitioned') throw new AuthError('concurrent_change', 'The ticket board changed during the actor-name migration.');
150
+ fenced = true;
151
+ };
152
+ let cursor = cursorArg;
153
+ let wrote = false;
154
+ let read = 0;
155
+ let bytes = 0;
156
+ const full = (): boolean => read >= sliceRecords || bytes >= sliceBytes;
157
+ /** Writes one renamed record after fencing the board, and counts it against the bound. */
158
+ const rewrite = async (writeArg: () => Promise<{ status: string }>, nextArg: unknown): Promise<void> => {
159
+ await fence();
160
+ if ((await writeArg()).status !== 'transitioned') throw new AuthError('concurrent_change', 'A ticket changed during the actor-name migration.');
161
+ bytes += jsonBytes(nextArg);
162
+ wrote = true;
163
+ };
164
+ /** Takes a page's records in order until the bound; answers whether the page completed the phase. */
165
+ const take = async <TRecord extends { id: string }>(pageArg: TRecord[], renameArg: (recordArg: TRecord) => Promise<void>): Promise<boolean> => {
166
+ let taken = 0;
167
+ for (const record of pageArg) {
168
+ await renameArg(record);
169
+ read += 1; taken += 1;
170
+ cursor = { phase: cursor.phase, after: record.id };
171
+ if (full()) break;
172
+ }
173
+ return taken === pageArg.length && pageArg.length < pageRecords;
174
+ };
175
+ while (ticketIdArg !== undefined && cursor.phase !== 'ticket' && !full()) {
176
+ const phase = cursor.phase;
177
+ const query = { filter: { ticketId: ticketIdArg, ...(cursor.after === undefined ? {} : { id: { $gt: cursor.after } }) },
178
+ sort: { id: 1 as const }, limit: pageRecords, ...options };
179
+ const complete = phase === 'activity' ? await take(await TicketActivityModel.exact.findStored(query), async (current) => {
180
+ const next = renamed(current.activity);
181
+ if (next === current.activity) return;
182
+ await rewrite(() => TicketActivityModel.exact.transition({ current, change: (modelArg) => { modelArg.activity = next; } }, options), next);
183
+ // A comment and the copy its `commented` entry holds are one: both move in this transaction.
184
+ const copy = next.action === 'commented' ? next.changes.comment?.after as ITicketComment | undefined : undefined;
185
+ if (!copy || copy === current.activity.changes.comment?.after) return;
186
+ const stored = await TicketCommentModel.exact.findStoredOne({ id: copy.id, ticketId: ticketIdArg }, options);
187
+ if (!stored) return;
188
+ const comment = renamed(stored.comment);
189
+ if (comment === stored.comment) return;
190
+ await rewrite(() => TicketCommentModel.exact.transition({ current: stored, change: (modelArg) => { modelArg.comment = comment; } }, options), comment);
191
+ }) : phase === 'questions' ? await take(await TicketQuestionModel.exact.findStored(query), async (current) => {
192
+ const next = renamed(current.question);
193
+ if (next !== current.question) {
194
+ await rewrite(() => TicketQuestionModel.exact.transition({ current, change: (modelArg) => { modelArg.question = next; } }, options), next);
195
+ }
196
+ }) : await take(await TicketCommentModel.exact.findStored(query), async (current) => {
197
+ // A comment whose copy needed no renaming, or that has none: the activity renamed every other one with its copy.
198
+ const next = renamed(current.comment);
199
+ if (next !== current.comment) {
200
+ await rewrite(() => TicketCommentModel.exact.transition({ current, change: (modelArg) => { modelArg.comment = next; } }, options), next);
201
+ }
202
+ });
203
+ if (complete) cursor = { phase: phases[phases.indexOf(phase) + 1]! };
204
+ }
205
+ let moved = false;
206
+ if (ticketIdArg !== undefined && (wrote || cursor.phase === 'ticket')) {
207
+ const current = await TicketModel.exact.findStoredOne({ id: ticketIdArg }, options);
208
+ if (!current) throw new AuthError('concurrent_change', 'A ticket changed during the actor-name migration.');
209
+ // The document is renamed once its history is; a transaction that rewrote any of its records moves its revision.
210
+ const next = cursor.phase === 'ticket' ? renamed(current.ticket) : current.ticket;
211
+ if (next !== current.ticket || wrote) {
212
+ await rewrite(() => TicketModel.exact.transition({ current, change: (modelArg) => {
213
+ modelArg.ticket = { ...next, revision: (modelArg.ticket.revision ?? 0) + 1 };
214
+ } }, options), next);
215
+ moved = true;
216
+ }
217
+ }
218
+ if (markerArg && cursor.phase === 'ticket') {
219
+ const inserted = await TicketMigrationMarkerModel.exact.insert({ id: ticketActorNamesMigrationId, completedAt: new Date().toISOString(),
220
+ tickets: [...markerArg, ...(moved && markerArg.at(-1) !== ticketIdArg ? [ticketIdArg!] : [])] }, options);
221
+ if (inserted.status !== 'inserted') throw new AuthError('concurrent_change', 'The actor-name migration ran twice.');
222
+ }
223
+ return { cursor, moved };
224
+ }
225
+ }
@@ -3,6 +3,6 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: 'agl',
6
- version: '43.3.0',
6
+ version: '43.3.1',
7
7
  description: 'Agent Gateway Layer for OpenCode, FlexHarness, and Codex sessions'
8
8
  }
@@ -371,12 +371,14 @@ export class AglFleetWorker extends plugins.deesElement.DeesElement {
371
371
  { timeoutMs: steerTimeoutMs },
372
372
  );
373
373
  if (generation !== this.generation) return;
374
- // A report that is a fleet worker answers with the steer job.
374
+ // A report that is a fleet worker answers with the steer job. One that failed after its dispatch may have delivered
375
+ // the message (`errorOutcome`): its outcome is unknown, as when the answer was lost.
375
376
  const job = 'job' in response ? response.job : undefined;
376
377
  if (!job || job.state === 'succeeded') {
377
378
  this.draft = '';
378
379
  this.attachments = noAttachments;
379
- } else this.steerError = job.error ?? 'The fleet did not deliver the message.';
380
+ } else if (job.errorOutcome === 'refused') this.steerError = job.error ?? 'The fleet did not deliver the message.';
381
+ else this.steerError = `The steer's outcome is unknown (${job.error ?? 'the fleet job failed'}). Check the transcript before sending it again.`;
380
382
  } catch (errorArg) {
381
383
  if (generation !== this.generation) return;
382
384
  this.steerError = errorArg instanceof plugins.typedrequest.TypedResponseError