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
@@ -0,0 +1,295 @@
1
+ import type {
2
+ IControllerEvent,
3
+ IControllerMessageBundle,
4
+ IControllerPermission,
5
+ IControllerQuestion,
6
+ IControllerRuntimeId,
7
+ IControllerSessionFeedRow,
8
+ TControllerEventType,
9
+ TControllerSessionFeedDelta,
10
+ } from '../ts_interfaces/index.js';
11
+ import {
12
+ deviceLabelMaximumCharacters,
13
+ deviceMessageMaximumBytes,
14
+ type IDeviceMessage,
15
+ type IDevicePermission,
16
+ type IDeviceQuestion,
17
+ type IDeviceSessionFeedDelta,
18
+ type IDeviceSessionRow,
19
+ type IReq_DeviceAuthChallenge,
20
+ type IReq_DeviceAuthProve,
21
+ type IReq_DevicePair,
22
+ type IReq_DevicePermissionReply,
23
+ type IReq_DeviceQuestionReply,
24
+ type IReq_DeviceSessionRead,
25
+ type IReq_DeviceSessionSend,
26
+ type TDeviceEvent,
27
+ type TDeviceMessagePart,
28
+ } from '../ts_interfaces/devices.js';
29
+ import { isControllerSessionFeedRowId } from '../ts_interfaces/sessionfeed.js';
30
+ import { assertKeys, assertObject, assertQuestionAnswers } from './classes.validation.js';
31
+ import { sessionFeedRowId } from './classes.sessionfeed.js';
32
+
33
+ /*
34
+ * The device API's requests and projections: what a device may ask, checked before anything is read, and the reduced
35
+ * shapes of what it gets. A device sees the session feed without host paths, tickets or terminals, transcripts with
36
+ * tool calls reduced to name, title and status, and an allowlist of events.
37
+ */
38
+
39
+ /** The controller events a device receives, each projected by `deviceEvent`; every other event never reaches one. */
40
+ export const deviceRelayedEventTypes: ReadonlySet<TControllerEventType> = new Set<TControllerEventType>([
41
+ 'sessionfeed.changed',
42
+ 'sessions.changed',
43
+ 'session.changed',
44
+ 'session.history.changed',
45
+ 'permissions.changed',
46
+ 'session.text.updated',
47
+ 'session.text.delta',
48
+ ]);
49
+
50
+ /** A feed row as a device sees it; none for a terminal row, which a device does not open. */
51
+ export const deviceSessionRow = (rowArg: IControllerSessionFeedRow): IDeviceSessionRow | undefined => (
52
+ rowArg.open.kind === 'terminal' ? undefined : {
53
+ id: rowArg.id,
54
+ harness: rowArg.harness,
55
+ state: rowArg.state,
56
+ name: rowArg.name,
57
+ ...(rowArg.excerpt === undefined ? {} : { excerpt: rowArg.excerpt }),
58
+ updatedAt: rowArg.updatedAt,
59
+ }
60
+ );
61
+
62
+ export const deviceSessionRows = (rowsArg: readonly IControllerSessionFeedRow[]): IDeviceSessionRow[] => rowsArg
63
+ .flatMap((rowArg) => deviceSessionRow(rowArg) ?? []);
64
+
65
+ /** A feed change as a device applies it: the same epoch and revision, terminal rows left out. */
66
+ export const deviceFeedDelta = (deltaArg: TControllerSessionFeedDelta): IDeviceSessionFeedDelta => 'reset' in deltaArg
67
+ ? { epoch: deltaArg.epoch, revision: deltaArg.revision, reset: true, upserts: [], removed: [] }
68
+ : {
69
+ epoch: deltaArg.epoch,
70
+ revision: deltaArg.revision,
71
+ reset: false,
72
+ upserts: deviceSessionRows(deltaArg.upserts),
73
+ removed: [...deltaArg.removed],
74
+ };
75
+
76
+ /** One source message of a transcript as one device message: its reasoning, text and tool calls as parts, in order. */
77
+ const deviceMessage = (bundleArg: IControllerMessageBundle): IDeviceMessage | undefined => {
78
+ const first = bundleArg.messages[0];
79
+ if (!first) return undefined;
80
+ const parts: TDeviceMessagePart[] = [];
81
+ for (const message of bundleArg.messages) {
82
+ for (const reasoning of message.reasoning ?? []) {
83
+ if (reasoning.text !== '') parts.push({ type: 'reasoning', id: reasoning.id.nativeId, text: reasoning.text });
84
+ }
85
+ if (message.toolCall) {
86
+ parts.push({
87
+ type: 'tool',
88
+ id: message.toolCall.id.nativeId,
89
+ tool: message.toolCall.name,
90
+ ...(message.toolCall.title === undefined ? {} : { title: message.toolCall.title }),
91
+ status: message.toolCall.status,
92
+ });
93
+ } else if (message.text !== '' || message.streaming === true) {
94
+ // A streaming part is listed while still empty: its live text applies to it.
95
+ parts.push({ type: 'text', id: message.id.nativeId, text: message.text });
96
+ }
97
+ }
98
+ return {
99
+ id: bundleArg.sourceMessageId.nativeId,
100
+ role: bundleArg.messages.some((messageArg) => messageArg.role === 'user') ? 'user' : 'assistant',
101
+ createdAt: first.createdAt,
102
+ parts,
103
+ };
104
+ };
105
+
106
+ /** A transcript page's messages, oldest first. */
107
+ export const deviceMessages = (bundlesArg: readonly IControllerMessageBundle[]): IDeviceMessage[] => bundlesArg
108
+ .flatMap((bundleArg) => deviceMessage(bundleArg) ?? []);
109
+
110
+ export const devicePermissions = (permissionsArg: readonly IControllerPermission[]): IDevicePermission[] => permissionsArg
111
+ .map((permissionArg) => ({
112
+ id: permissionArg.id.nativeId,
113
+ title: permissionArg.title,
114
+ type: permissionArg.type,
115
+ patterns: [...permissionArg.patterns],
116
+ }));
117
+
118
+ export const deviceQuestions = (questionsArg: readonly IControllerQuestion[]): IDeviceQuestion[] => questionsArg
119
+ .map((questionArg) => ({
120
+ id: questionArg.id.nativeId,
121
+ questions: questionArg.questions.map((itemArg) => ({
122
+ question: itemArg.question,
123
+ header: itemArg.header,
124
+ options: itemArg.options.map(({ label, description }) => ({ label, description })),
125
+ ...(itemArg.multiple === undefined ? {} : { multiple: itemArg.multiple }),
126
+ ...(itemArg.custom === undefined ? {} : { custom: itemArg.custom }),
127
+ })),
128
+ }));
129
+
130
+ /**
131
+ * The row id a device names a conversation by, when the feed lists it as something a device opens; events about any
132
+ * other session (a driver, a child, a terminal's agent, one the feed has not listed yet) reach no device.
133
+ */
134
+ const visibleRowId = (
135
+ sessionIdArg: IControllerRuntimeId | undefined,
136
+ rowOfArg: (rowIdArg: string) => IControllerSessionFeedRow | undefined,
137
+ ): string | undefined => {
138
+ if (!sessionIdArg || sessionIdArg.harnessId === 'controller') return undefined;
139
+ const rowId = sessionFeedRowId(sessionIdArg.harnessId, sessionIdArg.nativeId);
140
+ const row = rowOfArg(rowId);
141
+ return row && row.open.kind !== 'terminal' ? rowId : undefined;
142
+ };
143
+
144
+ /** A controller event as a device receives it, or none. `rowOfArg` answers the feed's published rows. */
145
+ export const deviceEvent = (
146
+ eventArg: IControllerEvent,
147
+ rowOfArg: (rowIdArg: string) => IControllerSessionFeedRow | undefined,
148
+ ): TDeviceEvent | undefined => {
149
+ switch (eventArg.type) {
150
+ case 'sessionfeed.changed':
151
+ return eventArg.sessionFeed ? { type: 'sessionfeed.changed', delta: deviceFeedDelta(eventArg.sessionFeed) } : undefined;
152
+ case 'sessions.changed':
153
+ return { type: 'sessions.changed' };
154
+ case 'session.changed':
155
+ case 'session.history.changed':
156
+ case 'permissions.changed': {
157
+ if (!eventArg.sessionId) return eventArg.type === 'permissions.changed' ? { type: 'sessions.changed' } : undefined;
158
+ const sessionId = visibleRowId(eventArg.sessionId, rowOfArg);
159
+ return sessionId === undefined ? undefined : { type: 'session.changed', sessionId };
160
+ }
161
+ case 'session.text.updated': {
162
+ const update = eventArg.textUpdate;
163
+ const sessionId = visibleRowId(update?.sessionId, rowOfArg);
164
+ return update && sessionId !== undefined ? {
165
+ type: 'session.text.updated',
166
+ update: { sessionId, messageId: update.messageId.nativeId, partId: update.partId.nativeId, text: update.text },
167
+ } : undefined;
168
+ }
169
+ case 'session.text.delta': {
170
+ const delta = eventArg.textDelta;
171
+ const sessionId = visibleRowId(delta?.sessionId, rowOfArg);
172
+ return delta && sessionId !== undefined ? {
173
+ type: 'session.text.delta',
174
+ delta: {
175
+ sessionId,
176
+ messageId: delta.messageId.nativeId,
177
+ partId: delta.partId.nativeId,
178
+ delta: delta.delta,
179
+ baseTextUtf8Bytes: delta.baseTextUtf8Bytes,
180
+ textUtf8Bytes: delta.textUtf8Bytes,
181
+ },
182
+ } : undefined;
183
+ }
184
+ default:
185
+ return undefined;
186
+ }
187
+ };
188
+
189
+ const assertText = (valueArg: unknown, nameArg: string, maximumBytesArg: number): string => {
190
+ if (typeof valueArg !== 'string' || valueArg.length === 0 || Buffer.byteLength(valueArg, 'utf8') > maximumBytesArg) {
191
+ throw new Error(`${nameArg} must contain 1-${maximumBytesArg} UTF-8 bytes.`);
192
+ }
193
+ return valueArg;
194
+ };
195
+
196
+ const assertDeviceId = (valueArg: unknown): string => {
197
+ if (typeof valueArg !== 'string' || !/^[A-Za-z0-9_-]{24}$/u.test(valueArg)) throw new Error('deviceId is not a device id.');
198
+ return valueArg;
199
+ };
200
+
201
+ const assertRowId = (valueArg: unknown): string => {
202
+ if (!isControllerSessionFeedRowId(valueArg)) throw new Error('sessionId must name a session as the session feed does.');
203
+ return valueArg;
204
+ };
205
+
206
+ /** A device's name or model: one line of 1 to 64 characters, its surrounding blanks dropped. */
207
+ const assertDeviceLabel = (valueArg: unknown, nameArg: string): string => {
208
+ const label = typeof valueArg === 'string' ? valueArg.trim() : '';
209
+ if (label.length === 0 || [...label].length > deviceLabelMaximumCharacters || /\p{Cc}/u.test(label)) {
210
+ throw new Error(`${nameArg} must be one line of 1-${deviceLabelMaximumCharacters} characters.`);
211
+ }
212
+ return label;
213
+ };
214
+
215
+ export const assertDevicePairRequest = (valueArg: unknown): IReq_DevicePair['request'] => {
216
+ const value = assertObject(valueArg, 'device pair request');
217
+ assertKeys(value, ['code', 'name', 'model', 'publicKey', 'proof']);
218
+ return {
219
+ code: assertText(value.code, 'code', 64),
220
+ name: assertDeviceLabel(value.name, 'name'),
221
+ model: assertDeviceLabel(value.model, 'model'),
222
+ publicKey: assertText(value.publicKey, 'publicKey', 256),
223
+ proof: assertText(value.proof, 'proof', 128),
224
+ };
225
+ };
226
+
227
+ export const assertDeviceAuthChallengeRequest = (valueArg: unknown): IReq_DeviceAuthChallenge['request'] => {
228
+ const value = assertObject(valueArg, 'device challenge request');
229
+ assertKeys(value, ['deviceId']);
230
+ return { deviceId: assertDeviceId(value.deviceId) };
231
+ };
232
+
233
+ export const assertDeviceAuthProveRequest = (valueArg: unknown): IReq_DeviceAuthProve['request'] => {
234
+ const value = assertObject(valueArg, 'device proof request');
235
+ assertKeys(value, ['deviceId', 'signature']);
236
+ return { deviceId: assertDeviceId(value.deviceId), signature: assertText(value.signature, 'signature', 128) };
237
+ };
238
+
239
+ export const assertDeviceSessionReadRequest = (valueArg: unknown): IReq_DeviceSessionRead['request'] => {
240
+ const value = assertObject(valueArg, 'device session read request');
241
+ assertKeys(value, ['sessionId'], ['before', 'limit']);
242
+ if (value.limit !== undefined && (!Number.isSafeInteger(value.limit) || (value.limit as number) < 1 || (value.limit as number) > 50)) {
243
+ throw new Error('limit must be an integer from 1 to 50.');
244
+ }
245
+ return {
246
+ sessionId: assertRowId(value.sessionId),
247
+ ...(value.before === undefined ? {} : { before: assertText(value.before, 'before', 4096) }),
248
+ ...(value.limit === undefined ? {} : { limit: value.limit as number }),
249
+ };
250
+ };
251
+
252
+ export const assertDeviceSessionSendRequest = (valueArg: unknown): IReq_DeviceSessionSend['request'] => {
253
+ const value = assertObject(valueArg, 'device session send request');
254
+ assertKeys(value, ['sessionId', 'text']);
255
+ const text = assertText(value.text, 'text', deviceMessageMaximumBytes);
256
+ if (!text.trim() || text.includes('\0')) throw new Error('text must be a message that is not blank.');
257
+ return { sessionId: assertRowId(value.sessionId), text };
258
+ };
259
+
260
+ export const assertDevicePermissionReplyRequest = (valueArg: unknown): IReq_DevicePermissionReply['request'] => {
261
+ const value = assertObject(valueArg, 'device permission reply request');
262
+ assertKeys(value, ['sessionId', 'permissionId', 'reply'], ['message']);
263
+ if (value.reply !== 'once' && value.reply !== 'reject') throw new Error('reply must be once or reject.');
264
+ return {
265
+ sessionId: assertRowId(value.sessionId),
266
+ permissionId: assertText(value.permissionId, 'permissionId', 512),
267
+ reply: value.reply,
268
+ ...(value.message === undefined ? {} : { message: assertText(value.message, 'message', 2048) }),
269
+ };
270
+ };
271
+
272
+ export const assertDeviceQuestionReplyRequest = (valueArg: unknown): IReq_DeviceQuestionReply['request'] => {
273
+ const value = assertObject(valueArg, 'device question reply request');
274
+ assertKeys(value, ['sessionId', 'questionId', 'answers']);
275
+ return {
276
+ sessionId: assertRowId(value.sessionId),
277
+ questionId: assertText(value.questionId, 'questionId', 512),
278
+ answers: assertQuestionAnswers(value.answers),
279
+ };
280
+ };
281
+
282
+ export const assertDevicePairingCancelRequest = (valueArg: unknown): { pairingId: string } => {
283
+ const value = assertObject(valueArg, 'pairing cancel request');
284
+ assertKeys(value, ['pairingId']);
285
+ if (typeof value.pairingId !== 'string' || !/^[A-Za-z0-9_-]{22}$/u.test(value.pairingId)) {
286
+ throw new Error('pairingId is not a pairing id.');
287
+ }
288
+ return { pairingId: value.pairingId };
289
+ };
290
+
291
+ export const assertDeviceRevokeRequest = (valueArg: unknown): { deviceId: string } => {
292
+ const value = assertObject(valueArg, 'device revoke request');
293
+ assertKeys(value, ['deviceId']);
294
+ return { deviceId: assertDeviceId(value.deviceId) };
295
+ };
@@ -0,0 +1,118 @@
1
+ import * as plugins from './plugins.js';
2
+ import {
3
+ deviceAuthenticationMessageLabel,
4
+ devicePairingMessageLabel,
5
+ devicePairingScheme,
6
+ deviceSecretBytes,
7
+ } from '../ts_interfaces/devices.js';
8
+
9
+ /*
10
+ * The cryptography of the device protocol (`ts_interfaces/devices.ts`): the messages a device key signs, the P-256 key
11
+ * and signature checks, the fingerprint people compare, and the pairing payload of the QR code. Everything runs on
12
+ * `node:crypto`; the signed messages are byte for byte what HarnessKit's `DeviceProof` builds.
13
+ */
14
+
15
+ /** Everything of a P-256 SubjectPublicKeyInfo in DER before the uncompressed point's 64 bytes. */
16
+ const p256SpkiPrefix = Buffer.from('3059301306072a8648ce3d020106082a8648ce3d03010703420004', 'hex');
17
+ const p256SpkiBytes = p256SpkiPrefix.byteLength + 64;
18
+ const base64UrlPattern = /^[A-Za-z0-9_-]+$/u;
19
+
20
+ /**
21
+ * The bytes of a base64url text without padding, refused (undefined) unless it is exactly that text's canonical form,
22
+ * of `byteLengthArg` bytes when given and of at most `maximumBytesArg` otherwise.
23
+ */
24
+ export const decodeDeviceBase64Url = (
25
+ valueArg: unknown,
26
+ sizeArg: { bytes: number } | { maximumBytes: number },
27
+ ): Buffer | undefined => {
28
+ if (typeof valueArg !== 'string' || !base64UrlPattern.test(valueArg)) return undefined;
29
+ const maximum = 'bytes' in sizeArg ? sizeArg.bytes : sizeArg.maximumBytes;
30
+ if (valueArg.length > Math.ceil((maximum * 4) / 3)) return undefined;
31
+ const bytes = Buffer.from(valueArg, 'base64url');
32
+ if (bytes.toString('base64url') !== valueArg) return undefined;
33
+ if ('bytes' in sizeArg ? bytes.byteLength !== sizeArg.bytes : bytes.byteLength === 0) return undefined;
34
+ return bytes;
35
+ };
36
+
37
+ /** A signed message: each field as a 4-byte big-endian length followed by its bytes. */
38
+ const signedMessage = (fieldsArg: readonly Uint8Array[]): Buffer => Buffer.concat(fieldsArg.flatMap((fieldArg) => {
39
+ const length = Buffer.alloc(4);
40
+ length.writeUInt32BE(fieldArg.byteLength);
41
+ return [length, fieldArg];
42
+ }));
43
+
44
+ export interface IDeviceMessageBinding {
45
+ /** `controller:<port>`. */
46
+ controllerId: string;
47
+ /** The controller's public origin, exactly as it is configured. */
48
+ origin: string;
49
+ /** The device key, SubjectPublicKeyInfo DER. */
50
+ publicKey: Uint8Array;
51
+ }
52
+
53
+ /** The message a device signs to pair: it binds the key to this controller, origin and code. */
54
+ export const devicePairingMessage = (bindingArg: IDeviceMessageBinding, codeArg: Uint8Array): Buffer => signedMessage([
55
+ Buffer.from(devicePairingMessageLabel, 'utf8'),
56
+ Buffer.from(bindingArg.controllerId, 'utf8'),
57
+ Buffer.from(bindingArg.origin, 'utf8'),
58
+ plugins.crypto.createHash('sha256').update(codeArg).digest(),
59
+ bindingArg.publicKey,
60
+ ]);
61
+
62
+ /** The message a device signs to authenticate one connection: it binds the key to this controller, origin and nonce. */
63
+ export const deviceAuthenticationMessage = (bindingArg: IDeviceMessageBinding, nonceArg: Uint8Array): Buffer => {
64
+ if (nonceArg.byteLength !== deviceSecretBytes) throw new Error(`A device nonce is ${deviceSecretBytes} bytes.`);
65
+ return signedMessage([
66
+ Buffer.from(deviceAuthenticationMessageLabel, 'utf8'),
67
+ Buffer.from(bindingArg.controllerId, 'utf8'),
68
+ Buffer.from(bindingArg.origin, 'utf8'),
69
+ nonceArg,
70
+ bindingArg.publicKey,
71
+ ]);
72
+ };
73
+
74
+ /**
75
+ * A device's public key: a P-256 SubjectPublicKeyInfo in DER with an uncompressed point on the curve, in exactly the
76
+ * form `node:crypto` exports it again, so one key has one text and one fingerprint. Undefined for anything else.
77
+ */
78
+ export const importDevicePublicKey = (spkiArg: Uint8Array): plugins.crypto.KeyObject | undefined => {
79
+ const spki = Buffer.from(spkiArg);
80
+ if (spki.byteLength !== p256SpkiBytes || !spki.subarray(0, p256SpkiPrefix.byteLength).equals(p256SpkiPrefix)) {
81
+ return undefined;
82
+ }
83
+ let key: plugins.crypto.KeyObject;
84
+ try {
85
+ key = plugins.crypto.createPublicKey({ key: spki, format: 'der', type: 'spki' });
86
+ } catch {
87
+ return undefined;
88
+ }
89
+ if (key.asymmetricKeyType !== 'ec' || key.asymmetricKeyDetails?.namedCurve !== 'prime256v1') return undefined;
90
+ return key.export({ format: 'der', type: 'spki' }).equals(spki) ? key : undefined;
91
+ };
92
+
93
+ /** Whether `signatureArg` (ECDSA P-256 with SHA-256, DER) is the key's signature of `messageArg`. */
94
+ export const verifyDeviceSignature = (
95
+ keyArg: plugins.crypto.KeyObject,
96
+ messageArg: Uint8Array,
97
+ signatureArg: Uint8Array,
98
+ ): boolean => {
99
+ try {
100
+ return plugins.crypto.verify('sha256', messageArg, { key: keyArg, dsaEncoding: 'der' }, signatureArg);
101
+ } catch {
102
+ return false;
103
+ }
104
+ };
105
+
106
+ /** A key's fingerprint for people to compare: SHA-256 of the SPKI, the first 16 bytes as 8 groups of 4 uppercase hex. */
107
+ export const deviceKeyFingerprint = (spkiArg: Uint8Array): string => plugins.crypto.createHash('sha256').update(spkiArg)
108
+ .digest().subarray(0, 16).toString('hex').toUpperCase().match(/.{4}/gu)!.join(' ');
109
+
110
+ /** Percent-encodes everything in a query value but letters, digits and `-._~`, as HarnessKit's payload writer does. */
111
+ const queryValue = (valueArg: string): string => encodeURIComponent(valueArg)
112
+ .replace(/[!'()*]/gu, (characterArg) => `%${characterArg.charCodeAt(0).toString(16).toUpperCase()}`);
113
+
114
+ /** The QR code's payload: `agl-pair:?origin=<https origin>&controller=<controller id>&code=<base64url>`, each once. */
115
+ export const devicePairingPayload = (originArg: string, controllerIdArg: string, codeArg: Uint8Array): string => (
116
+ `${devicePairingScheme}:?origin=${queryValue(originArg)}&controller=${queryValue(controllerIdArg)}`
117
+ + `&code=${Buffer.from(codeArg).toString('base64url')}`
118
+ );
@@ -4,7 +4,7 @@ import { withLocalConfigurationOwner } from './functions.configurationowner.js';
4
4
  import { withCliDiagnostics } from './functions.clidiagnostics.js';
5
5
  import { defaultControllerPort } from './classes.config.js';
6
6
  import { fleetObservationWindowMs, withFleetObservationOwner } from './functions.fleetcli.js';
7
- import { assertFleetWorkerRequest } from './fleet/functions.workervalidation.js';
7
+ import { assertFleetWorkerRequest, fleetWorkerRequestSchemas } from './fleet/functions.workervalidation.js';
8
8
  import { fleetWatchLines, parseFleetWatchCi, parseFleetWatchSite, watchFleetProbes, type IFleetWatchChange, type IFleetWatchProbeOptions } from './fleet/functions.watchprobes.js';
9
9
  import type { IFleetWorker, TFleetWorkerAction, TFleetWorkerRequest, IFleetEventCursor, IFleetWatchResult } from '../ts_interfaces/fleetworkers.js';
10
10
 
@@ -15,7 +15,7 @@ export const fleetWorkerCliHelp = `Usage: agl fleet worker start NAME --profile
15
15
  agl fleet worker reconfirm NAME --reason TEXT
16
16
  agl fleet worker steer NAME --message-file FILE
17
17
  agl fleet worker steer --messages-file FILE (JSON array of {name,text})
18
- agl fleet worker message NAME|NATIVE_ID --message-file FILE
18
+ agl fleet worker message NAME|NATIVE_ID --message-file FILE [--ticket KEY]
19
19
  agl fleet worker native-message NATIVE_ID --message-file FILE --sender LABEL
20
20
  agl fleet worker report|stop|archive NAME
21
21
  agl fleet worker refresh NAME --next-name NAME [--profile ID] --handoff-file FILE [--note-file FILE]
@@ -24,7 +24,7 @@ export const fleetWorkerCliHelp = `Usage: agl fleet worker start NAME --profile
24
24
  agl fleet worker status JOB_ID
25
25
  agl fleet watch [--cursor JSON] [--once] [--lines] [--site NAME=URL …] [--ci OWNER/REPO[@REF] …]
26
26
  [--gitea URL] [--gitea-token-file FILE] [--probe-interval SECONDS]
27
- All accept --ticket KEY, --json and --port PORT. Actions and report require --ticket; list/status/watch accept it as a filter.
27
+ All accept --ticket KEY, --json and --port PORT. Actions and report require --ticket, except message; list/status/watch accept it as a filter.
28
28
  Profiles live in fleet.workerProfiles in the Configuration master.
29
29
  Mutation and report commands wait for the returned job; MCP tools return its handle immediately.
30
30
  refresh --profile ID starts the successor on that configured profile, which must run the worker's own harness (only move
@@ -38,6 +38,7 @@ every --probe-interval seconds (default 60); each writes its state first and the
38
38
  --gitea defaults to https://code.foss.global; a token from --gitea-token-file reaches private repositories over https.
39
39
  Steer and message reach a live worker through a relay and resume a reaped or stopped one with its saved options.
40
40
  Message addresses one worker by its name or by its native session id (a unique prefix of at least 8 characters).
41
+ Without --ticket it steers the worker on its own ticket; a --ticket the worker is not on, and a worker on no ticket, are refused.
41
42
  native-message wakes a settled (done, blocked or stopped) Claude Code background job that no fleet worker binds, named by
42
43
  its session id or a unique prefix of at least 8 characters, through Claude Code itself, as the browser's native session
43
44
  send does. The text arrives behind the session_message attribution header with the --sender label and the local owner
@@ -63,9 +64,14 @@ reconfirm requires --ticket and a reason. It clears a steer fence whose native s
63
64
  same session, settled before and after its transcript is read, and records from the transcript whether the message
64
65
  arrived (delivered, not-found or unproven) with the resolver and a ticket comment. It sends nothing; steer again to resend.
65
66
  `;
67
+ /** A `message` steer before its recipient is resolved: without --ticket it names no ticket yet. */
68
+ export type TFleetWorkerCliMessageRequest = Omit<TFleetWorkerRequest<'steer'>, 'ticketKey'> & { ticketKey?: string };
66
69
  export interface IFleetWorkerCliArguments {
67
- action: TFleetWorkerAction; request: TFleetWorkerRequest<TFleetWorkerAction>; port: number; json: boolean; once: boolean;
68
- /** `message`: the steer recipient is a worker name or native session id the controller's worker list resolves. */
70
+ action: TFleetWorkerAction; request: TFleetWorkerRequest<TFleetWorkerAction> | TFleetWorkerCliMessageRequest; port: number; json: boolean; once: boolean;
71
+ /**
72
+ * `message`: the steer recipient is a worker name or native session id the controller's worker list resolves;
73
+ * `fleetWorkerMessageRequest` then addresses it and names its ticket.
74
+ */
69
75
  target?: string;
70
76
  /** `message`: the file the message came from, which a refusal's native-message command names. */
71
77
  messageFile?: string;
@@ -94,6 +100,18 @@ export const resolveFleetWorkerTarget = (workers: IFleetWorker[], target: string
94
100
  + 'or adopt it first.'
95
101
  : 'Adopt the session first.'));
96
102
  };
103
+ /**
104
+ * The steer `message` sends once its recipient resolved to `worker` (AGL-919): addressed by the worker's name, on the
105
+ * ticket --ticket named or else on the worker's own. A --ticket the worker is not on and a worker on no ticket are
106
+ * refused before anything is sent; the fleet still checks the ticket when it takes the steer.
107
+ */
108
+ export const fleetWorkerMessageRequest = (request: TFleetWorkerCliMessageRequest, worker: IFleetWorker): TFleetWorkerRequest<'steer'> => {
109
+ if (!worker.ticketKey) throw new Error(`Fleet worker ${worker.name} is on no ticket, so it takes no message; adopt it with --ticket KEY first.`);
110
+ if (request.ticketKey !== undefined && request.ticketKey !== worker.ticketKey) {
111
+ throw new Error(`Fleet worker ${worker.name} is on ${worker.ticketKey}, not ${request.ticketKey}; without --ticket, message steers it on its own ticket.`);
112
+ }
113
+ return assertFleetWorkerRequest('steer', { ticketKey: worker.ticketKey, messages: [{ ...request.messages[0]!, name: worker.name }] });
114
+ };
97
115
  const fileText = async (path: string): Promise<string> => {
98
116
  const file = await plugins.fs.promises.open(path, 'r');
99
117
  try { if ((await file.stat()).size > 128 * 1024) throw new Error('Fleet message file exceeds 128 KiB.'); return await file.readFile('utf8'); }
@@ -159,7 +177,8 @@ export const parseFleetWorkerCliArguments = async (args: string[]): Promise<IFle
159
177
  probes.giteaToken = (await fileText(giteaTokenFile)).trim();
160
178
  if (!probes.giteaToken) throw new Error('The Gitea token file is empty.');
161
179
  }
162
- const request = assertFleetWorkerRequest(action, input);
180
+ // Without --ticket, `message` steers on its recipient's own ticket, which `fleetWorkerMessageRequest` names (AGL-919).
181
+ const request = message && input.ticketKey === undefined ? fleetWorkerRequestSchemas.steer.omit({ ticketKey: true }).parse(input) : assertFleetWorkerRequest(action, input);
163
182
  return { action, request, port, json, once, ...(lines ? { lines } : {}), ...(probing ? { probes } : {}),
164
183
  ...(message ? { target: (request as TFleetWorkerRequest<'steer'>).messages[0]!.name, ...(messageFile ? { messageFile } : {}) } : {}) };
165
184
  };
@@ -223,8 +242,7 @@ export const runFleetWorkerCli = async (args: string[]): Promise<void> => {
223
242
  await withCliDiagnostics(async () => withLocalConfigurationOwner(client!, parsed.port, async (ownerToken) => {
224
243
  if (parsed.target) {
225
244
  const { workers } = await client!.fleetWorker('list', { ownerToken }, abort.signal);
226
- const steer = parsed.request as TFleetWorkerRequest<'steer'>;
227
- steer.messages = [{ ...steer.messages[0]!, name: resolveFleetWorkerTarget(workers, parsed.target, parsed.messageFile).name }];
245
+ parsed.request = fleetWorkerMessageRequest(parsed.request as TFleetWorkerCliMessageRequest, resolveFleetWorkerTarget(workers, parsed.target, parsed.messageFile));
228
246
  }
229
247
  let result = await client!.fleetWorker(parsed.action, { ...parsed.request, ownerToken } as never, abort.signal);
230
248
  if ('job' in result && parsed.action !== 'status') {
@@ -92,7 +92,9 @@ export const formatProxyStatus = (unitArg: string, statusArg: TReportedProxyStat
92
92
  lines.push(`Account ${account.label} (${account.credential === 'api_key'
93
93
  ? `${account.provider === 'openai' ? 'OpenAI' : 'Anthropic'} API key` : account.provider === 'openai' ? 'ChatGPT' : 'Claude'}`
94
94
  + `${account.plan === null ? '' : `, ${account.plan}`}): ${account.stateText}`
95
- + `${account.resetAt === null ? '' : `, until ${account.resetAt}`}; `
95
+ + `${account.resetAt === null ? '' : `, until ${account.resetAt}`}`
96
+ // A key kept from Claude Code (AGL-1146) still serves every other client.
97
+ + `${account.credential === 'api_key' && account.claudeCode === false ? ', not for Claude Code' : ''}; `
96
98
  // A key has no maximum usage: its headroom is what is left of its monthly spend limit.
97
99
  + `${account.credential === 'api_key'
98
100
  ? `${account.headroom === null ? '' : `${Math.round(account.headroom)}% of its spend limit left, `}`
@@ -27,10 +27,11 @@ set moves the port to the HTTPS public origin ORIGIN behind a TLS reverse proxy,
27
27
  the origin's hostname). Each --gateway-source names an address the proxy reaches this host from; without one only a
28
28
  reverse proxy on this host reaches the controller, which then listens on loopback. The controller keeps its id and
29
29
  all of its data. When the origin or RP ID changes, its passkey is removed and every temporary password revoked: the
30
- next start prints a new setup code, to enroll a passkey at the new origin. Run it again to change the gateway
31
- sources; the passkey then stays.
32
- unset moves the port back to http://localhost:PORT (RP ID localhost), removes the passkey, revokes every temporary
33
- password and forgets the trusted-proxy secret.
30
+ next start prints a new setup code, to enroll a passkey at the new origin. When the origin changes, every paired
31
+ device is removed as well (a device signs the origin it paired with). Run it again to change the gateway sources;
32
+ the passkey and the devices then stay.
33
+ unset moves the port back to http://localhost:PORT (RP ID localhost), removes the passkey and every paired device,
34
+ revokes every temporary password and forgets the trusted-proxy secret.
34
35
  secret import reads a 32-byte base64url secret (43 characters) from standard input, never from a terminal, and makes
35
36
  it the controller's trusted-proxy secret, for a reverse proxy other than AGL's own gateway: that proxy injects it as
36
37
  X-Harness-Controller-Proxy-Secret. The secret is sealed with the TPM and never printed.
@@ -209,12 +210,17 @@ const moveOutcome = (
209
210
  previousArg: IControllerRuntimeConfig,
210
211
  targetArg: IControllerRuntimeConfig,
211
212
  enrollmentResetArg: boolean,
213
+ devicesRemovedArg: number,
212
214
  ): string => [
213
215
  `Moved ${controllerIdArg} from ${describeConfig(previousArg)} to ${describeConfig(targetArg)}.`,
214
216
  ...(enrollmentResetArg
215
217
  ? [`Its passkey was removed and every temporary password revoked. The next \`agl start --port ${targetArg.controllerPort}\` `
216
218
  + `prints a setup code: enroll a passkey with it at ${targetArg.publicOrigin}.`]
217
219
  : ['Its passkey stays: the origin and RP ID did not change.']),
220
+ ...(devicesRemovedArg > 0
221
+ ? [`${devicesRemovedArg === 1 ? 'Its paired device was' : `Its ${devicesRemovedArg} paired devices were`} removed: a device `
222
+ + 'signs the origin it paired with. Pair it again in Settings → Devices once the controller has a public origin.']
223
+ : []),
218
224
  ...(targetArg.gatewaySources
219
225
  ? [`Let only ${targetArg.gatewaySources.join(', ')} reach port ${targetArg.controllerPort} through the host firewall.`]
220
226
  : []),
@@ -258,7 +264,7 @@ export const runRemoteCli = async (argsArg: string[], optionsArg: IRemoteCliOpti
258
264
  target: { publicOrigin: target.publicOrigin, rpId: target.rpId },
259
265
  });
260
266
  return moved.changed
261
- ? moveOutcome(controllerArg.controllerId, moved.previous, target, moved.enrollmentReset)
267
+ ? moveOutcome(controllerArg.controllerId, moved.previous, target, moved.enrollmentReset, moved.devicesRemoved)
262
268
  : `${controllerArg.controllerId} already serves ${describeConfig(target)}; nothing changed.\n`;
263
269
  }));
264
270
  };