@coasys/ad4m 0.13.1-staging.2 → 0.13.1-staging.4

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 (97) hide show
  1. package/lib/index.cjs +610 -208
  2. package/lib/index.js +607 -209
  3. package/lib/src/Ad4mClient.d.ts +7 -0
  4. package/lib/src/Ad4mClient.js +9 -0
  5. package/lib/src/agent/AgentClient.d.ts +16 -1
  6. package/lib/src/agent/AgentClient.js +21 -2
  7. package/lib/src/ai/AITypes.d.ts +6 -2
  8. package/lib/src/apiClient.d.ts +13 -0
  9. package/lib/src/apiClient.js +67 -12
  10. package/lib/src/generated/api/Apps.d.ts +4 -0
  11. package/lib/src/generated/api/AuthInfo.d.ts +4 -0
  12. package/lib/src/generated/api/Events.d.ts +10 -12
  13. package/lib/src/generated/api/FlowStateChangedEvent.d.ts +3 -2
  14. package/lib/src/generated/api/Model.d.ts +4 -0
  15. package/lib/src/generated/api/ModelApi.d.ts +5 -1
  16. package/lib/src/generated/api/ModelApiInput.d.ts +7 -1
  17. package/lib/src/generated/api/Notification.d.ts +5 -1
  18. package/lib/src/generated/api/NotificationInput.d.ts +4 -0
  19. package/lib/src/generated/api/PerspectiveEvent.d.ts +8 -0
  20. package/lib/src/generated/api/{PerspectiveLinkWithOwner.d.ts → PerspectiveLinkEvent.d.ts} +4 -2
  21. package/lib/src/generated/api/{PerspectiveLinkUpdatedWithOwner.d.ts → PerspectiveLinkUpdatedEvent.d.ts} +4 -2
  22. package/lib/src/generated/api/PerspectiveRemovedEvent.d.ts +7 -0
  23. package/lib/src/generated/api/RequestCapabilityRequest.d.ts +1 -0
  24. package/lib/src/generated/api/RpcMethods.d.ts +10 -1
  25. package/lib/src/generated/api/RuntimeInfo.d.ts +5 -0
  26. package/lib/src/generated/api/RuntimeUpdateNotificationParams.d.ts +6 -1
  27. package/lib/src/generated/api/UsersRevokeAllSessionsParams.d.ts +7 -0
  28. package/{src/generated/api/PerspectiveRemovedWithOwner.ts → lib/src/generated/api/UsersRevokeAllSessionsParams.js} +1 -2
  29. package/lib/src/index.d.ts +1 -0
  30. package/lib/src/index.js +1 -0
  31. package/lib/src/model/Ad4mModel.js +45 -18
  32. package/lib/src/model/ModelQueryBuilder.d.ts +7 -3
  33. package/lib/src/model/ModelQueryBuilder.js +9 -4
  34. package/lib/src/model/query-common.js +7 -1
  35. package/lib/src/model/types.d.ts +45 -2
  36. package/lib/src/model/types.js +8 -0
  37. package/lib/src/perspectives/Container.d.ts +41 -0
  38. package/lib/src/perspectives/Container.js +62 -0
  39. package/lib/src/perspectives/PerspectiveProxy.d.ts +6 -3
  40. package/lib/src/perspectives/PerspectiveProxy.js +10 -4
  41. package/lib/src/perspectives/WakerSubscriptionManager.d.ts +94 -12
  42. package/lib/src/perspectives/WakerSubscriptionManager.js +276 -75
  43. package/lib/src/runtime/RuntimeClient.d.ts +6 -3
  44. package/lib/src/runtime/RuntimeClient.js +2 -0
  45. package/lib/src/runtime/RuntimeTypes.d.ts +7 -1
  46. package/package.json +2 -2
  47. package/src/Ad4mClient.test.ts +54 -19
  48. package/src/Ad4mClient.ts +10 -0
  49. package/src/agent/AgentClient.ts +26 -2
  50. package/src/ai/AITypes.ts +6 -2
  51. package/src/apiClient.test.ts +128 -3
  52. package/src/apiClient.ts +64 -11
  53. package/src/generated/api/Apps.ts +6 -1
  54. package/src/generated/api/AuthInfo.ts +6 -1
  55. package/src/generated/api/Events.ts +10 -12
  56. package/src/generated/api/FlowStateChangedEvent.ts +3 -2
  57. package/src/generated/api/Model.ts +4 -0
  58. package/src/generated/api/ModelApi.ts +5 -1
  59. package/src/generated/api/ModelApiInput.ts +8 -1
  60. package/src/generated/api/Notification.ts +5 -1
  61. package/src/generated/api/NotificationInput.ts +6 -1
  62. package/src/generated/api/PerspectiveEvent.ts +7 -0
  63. package/src/generated/api/{PerspectiveLinkUpdatedWithOwner.ts → PerspectiveLinkEvent.ts} +4 -1
  64. package/src/generated/api/PerspectiveLinkUpdatedEvent.ts +7 -0
  65. package/src/generated/api/PerspectiveRemovedEvent.ts +6 -0
  66. package/src/generated/api/RequestCapabilityRequest.ts +1 -1
  67. package/src/generated/api/RpcMethods.ts +4 -1
  68. package/src/generated/api/RuntimeInfo.ts +6 -1
  69. package/src/generated/api/RuntimeUpdateNotificationParams.ts +7 -1
  70. package/src/generated/api/UsersRevokeAllSessionsParams.ts +8 -0
  71. package/src/index.ts +1 -0
  72. package/src/model/Ad4mModel.ts +51 -19
  73. package/src/model/ModelQueryBuilder.ts +9 -6
  74. package/src/model/containment-scope.test.ts +104 -0
  75. package/src/model/query-common.ts +10 -1
  76. package/src/model/types.ts +56 -2
  77. package/src/perspectives/Container.test.ts +65 -0
  78. package/src/perspectives/Container.ts +46 -0
  79. package/src/perspectives/PerspectiveProxy.test.ts +11 -0
  80. package/src/perspectives/PerspectiveProxy.ts +10 -4
  81. package/src/perspectives/WakerSubscriptionManager.test.ts +400 -82
  82. package/src/perspectives/WakerSubscriptionManager.ts +321 -85
  83. package/src/perspectives/link-updated-type.test.ts +2 -2
  84. package/src/perspectives/listener-leaks.test.ts +3 -3
  85. package/src/runtime/RuntimeClient.ts +6 -3
  86. package/src/runtime/RuntimeTypes.ts +10 -1
  87. package/lib/src/generated/api/MessageReceivedEvent.d.ts +0 -7
  88. package/lib/src/generated/api/PerspectiveRemovedWithOwner.d.ts +0 -5
  89. package/lib/src/generated/api/PerspectiveWithOwner.d.ts +0 -6
  90. package/lib/src/generated/api/PerspectiveWithOwner.js +0 -1
  91. package/src/generated/api/MessageReceivedEvent.ts +0 -7
  92. package/src/generated/api/PerspectiveLinkWithOwner.ts +0 -4
  93. package/src/generated/api/PerspectiveWithOwner.ts +0 -4
  94. /package/lib/src/generated/api/{MessageReceivedEvent.js → PerspectiveEvent.js} +0 -0
  95. /package/lib/src/generated/api/{PerspectiveLinkUpdatedWithOwner.js → PerspectiveLinkEvent.js} +0 -0
  96. /package/lib/src/generated/api/{PerspectiveLinkWithOwner.js → PerspectiveLinkUpdatedEvent.js} +0 -0
  97. /package/lib/src/generated/api/{PerspectiveRemovedWithOwner.js → PerspectiveRemovedEvent.js} +0 -0
@@ -46,7 +46,8 @@ const MOCK_RESPONSES: Record<string, RpcHandler> = {
46
46
  'agent.updateProfile': { did: 'did:test:123', perspective: new Perspective(), directMessageLanguage: 'lang://dm' },
47
47
  'agent.sign': 'signed-message-data',
48
48
  'agent.isLocked': false,
49
- 'agent.requestCapability': 'request-id-123',
49
+ 'agent.requestCapability': (p: Record<string, unknown>) =>
50
+ 'agent' in p ? `request-for-${p.agent}` : 'request-id-123',
50
51
  'agent.permitCapability': 'permitted-token',
51
52
  'agent.generateJwt': 'jwt-token-abc',
52
53
  'agent.getApps': [{ requestId: 'app1', auth: {}, token: 'tok', revoked: false }],
@@ -174,7 +175,7 @@ const MOCK_RESPONSES: Record<string, RpcHandler> = {
174
175
  'expression.interact': 'interaction-result',
175
176
 
176
177
  // ── Runtime ──
177
- 'runtime.info': { ad4mExecutorVersion: '0.1.0', isUnlocked: true, isInitialized: true },
178
+ 'runtime.info': { ad4mExecutorVersion: '0.1.0', ad4mExecutorCommit: null, isUnlocked: true, isInitialized: true },
178
179
  'runtime.tlsDomain': 'test.domain.com',
179
180
  'runtime.quit': true,
180
181
  'runtime.openLink': true,
@@ -193,7 +194,7 @@ const MOCK_RESPONSES: Record<string, RpcHandler> = {
193
194
  'runtime.grantNotification': true,
194
195
  'runtime.deleteNotification': true,
195
196
  'runtime.setStatus': true,
196
- 'runtime.linkLanguageTemplates': ['lang://template1'],
197
+ 'runtime.linkLanguageTemplates': [{ address: 'template1', name: 'Template 1', possibleTemplateParams: ['uid', 'name'] }],
197
198
  'runtime.addLinkLanguageTemplates': ['lang://template1', 'lang://template2'],
198
199
  'runtime.removeLinkLanguageTemplates': ['lang://template1'],
199
200
  'runtime.hcAgentInfos': ['hc-agent-info-1', 'hc-agent-info-2'],
@@ -225,6 +226,8 @@ const MOCK_RESPONSES: Record<string, RpcHandler> = {
225
226
  'user.create': { success: true, did: 'did:test:new-user' },
226
227
  'user.login': 'login-jwt-token',
227
228
  'user.verifyEmail': 'verified-token',
229
+ 'user.logout': true,
230
+ 'user.revokeAllSessions': true,
228
231
  'user.requestVerification': { success: true, message: 'Verification email sent', requiresPassword: false, isExistingUser: true },
229
232
  'user.list': [{ email: 'user@test.com', credits: 100, freeAccess: false }],
230
233
  'user.multiUserEnabled': false,
@@ -378,12 +381,11 @@ function wireHandle(uuid: string): PerspectiveHandle {
378
381
  return { uuid, name: 'test-perspective', neighbourhood: null, sharedUrl: null, state: 'SYNCED', owners: null };
379
382
  }
380
383
 
381
- const OWNER = 'did:test:123';
382
- const linkAdded = (perspectiveUuid: string, source: string) => event('link-added', { perspectiveUuid, owner: OWNER, link: wireLink(source) });
383
- const linkRemoved = (perspectiveUuid: string, source: string) => event('link-removed', { perspectiveUuid, owner: OWNER, link: wireLink(source) });
384
+ const linkAdded = (perspectiveUuid: string, source: string) => event('link-added', { perspectiveUuid, link: wireLink(source) });
385
+ const linkRemoved = (perspectiveUuid: string, source: string) => event('link-removed', { perspectiveUuid, link: wireLink(source) });
384
386
  const linkUpdated = (perspectiveUuid: string, oldSource: string, newSource: string) =>
385
- event('link-updated', { perspectiveUuid, owner: OWNER, oldLink: wireLink(oldSource), newLink: wireLink(newSource) });
386
- const perspectiveAdded = (uuid: string) => event('perspective-added', { perspectiveUuid: uuid, owner: OWNER, perspective: wireHandle(uuid) });
387
+ event('link-updated', { perspectiveUuid, oldLink: wireLink(oldSource), newLink: wireLink(newSource) });
388
+ const perspectiveAdded = (uuid: string) => event('perspective-added', { perspectiveUuid: uuid, perspective: wireHandle(uuid) });
387
389
 
388
390
  // ===================== TEST SETUP =====================
389
391
 
@@ -501,6 +503,13 @@ describe('AgentClient', () => {
501
503
  expect(id).toBe('request-id-123');
502
504
  });
503
505
 
506
+ // #1399: the request names the agent the app asks to act as; without one, no `agent`
507
+ // param goes out (the executor's main agent).
508
+ test('requestCapability() passes the requested agent', async () => {
509
+ const id = await ad4m.agent.requestCapability({ appName: 'test', appDesc: 'test', appDomain: 'test', appUrl: 'test', capabilities: [] } as any, 'alice@example.org');
510
+ expect(id).toBe('request-for-alice@example.org');
511
+ });
512
+
504
513
  test('permitCapability() returns token', async () => {
505
514
  const token = await ad4m.agent.permitCapability('auth-string');
506
515
  expect(token).toBe('permitted-token');
@@ -1135,9 +1144,9 @@ describe('RuntimeClient', () => {
1135
1144
  expect(result).toEqual(['did:trusted:1']);
1136
1145
  });
1137
1146
 
1138
- test('knownLinkLanguageTemplates() returns templates', async () => {
1147
+ test('knownLinkLanguageTemplates() returns each template with its meta', async () => {
1139
1148
  const templates = await ad4m.runtime.knownLinkLanguageTemplates();
1140
- expect(templates).toEqual(['lang://template1']);
1149
+ expect(templates.map(t => [t.address, t.possibleTemplateParams])).toEqual([['template1', ['uid', 'name']]]);
1141
1150
  });
1142
1151
 
1143
1152
  test('hcAgentInfos() returns agent infos list', async () => {
@@ -1183,6 +1192,22 @@ describe('RuntimeClient', () => {
1183
1192
  expect(notifications).toEqual([]);
1184
1193
  });
1185
1194
 
1195
+ test('updateNotification() without webhookAuth sends none, so the stored one stays', async () => {
1196
+ const result = await ad4m.runtime.updateNotification('notif-1', {
1197
+ description: 'd',
1198
+ appName: 'a',
1199
+ appUrl: 'https://app.test',
1200
+ appIconPath: '',
1201
+ trigger: 'SELECT ?s WHERE { ?s ?p ?o }',
1202
+ perspectiveIds: ['p1'],
1203
+ webhookUrl: 'https://webhook.test',
1204
+ });
1205
+ expect(result).toBe(true);
1206
+ expect(lastRpcCall!.type).toBe('runtime.updateNotification');
1207
+ expect(lastRpcCall!.params.id).toBe('notif-1');
1208
+ expect('webhookAuth' in lastRpcCall!.params).toBe(false);
1209
+ });
1210
+
1186
1211
  test('grantNotification() grants a notification', async () => {
1187
1212
  const result = await ad4m.runtime.grantNotification('notif-1');
1188
1213
  expect(result).toBe(true);
@@ -1287,6 +1312,21 @@ describe('User and Auth', () => {
1287
1312
  expect(token).toBe('verified-token');
1288
1313
  });
1289
1314
 
1315
+ test('logout() revokes the session token', async () => {
1316
+ expect(await ad4m.agent.logout()).toBe(true);
1317
+ expect(lastRpcCall).toEqual({ type: 'user.logout', params: {} });
1318
+ });
1319
+
1320
+ test('revokeAllSessions() revokes the caller\'s sessions when no email is given', async () => {
1321
+ expect(await ad4m.agent.revokeAllSessions()).toBe(true);
1322
+ expect(lastRpcCall).toEqual({ type: 'user.revokeAllSessions', params: {} });
1323
+ });
1324
+
1325
+ test('revokeAllSessions(email) names the user', async () => {
1326
+ expect(await ad4m.agent.revokeAllSessions('test@test.com')).toBe(true);
1327
+ expect(lastRpcCall).toEqual({ type: 'user.revokeAllSessions', params: { email: 'test@test.com' } });
1328
+ });
1329
+
1290
1330
  test('hostingUserInfo() returns user info', async () => {
1291
1331
  const info = await ad4m.agent.hostingUserInfo();
1292
1332
  expect(info.email).toBe('test@test.com');
@@ -1458,7 +1498,7 @@ describe('Ad4mClient', () => {
1458
1498
  agentUpdated: jest.fn(), agentStatus: jest.fn(), apps: jest.fn(),
1459
1499
  hosting: jest.fn(),
1460
1500
  added: jest.fn(), updated: jest.fn(), removed: jest.fn(),
1461
- message: jest.fn(), exception: jest.fn(), notification: jest.fn(),
1501
+ exception: jest.fn(), notification: jest.fn(),
1462
1502
  };
1463
1503
  freshClient.on('agent-updated', ({ agent }) => handlers.agentUpdated(agent));
1464
1504
  freshClient.on('agent-status-changed', ({ agent }) => handlers.agentStatus(agent));
@@ -1467,7 +1507,6 @@ describe('Ad4mClient', () => {
1467
1507
  freshClient.on('perspective-added', ({ perspective }) => handlers.added(perspective));
1468
1508
  freshClient.on('perspective-updated', ({ perspective }) => handlers.updated(perspective));
1469
1509
  freshClient.on('perspective-removed', ({ perspectiveUuid }) => handlers.removed(perspectiveUuid));
1470
- freshClient.on('message-received', ({ message }) => handlers.message(message));
1471
1510
  freshClient.on('exception-occurred', ({ exception }) => handlers.exception(exception));
1472
1511
  freshClient.on('notification-triggered', ({ notification }) => handlers.notification(notification));
1473
1512
  await freshClient.agent.me(); // wait for the socket to open
@@ -1476,7 +1515,7 @@ describe('Ad4mClient', () => {
1476
1515
  const notification = {
1477
1516
  notification: {
1478
1517
  id: 'n-1', granted: true, description: 'd', appName: 'a', appUrl: 'u', appIconPath: 'i',
1479
- trigger: 'q', perspectiveIds: ['uuid-a'], webhookUrl: '', webhookAuth: '', ownerDid: 'did:key:owner',
1518
+ trigger: 'q', perspectiveIds: ['uuid-a'], webhookUrl: '', hasWebhookAuth: false, ownerDid: 'did:key:owner',
1480
1519
  },
1481
1520
  perspectiveId: 'uuid-a', triggerMatch: '[]',
1482
1521
  };
@@ -1489,12 +1528,8 @@ describe('Ad4mClient', () => {
1489
1528
  }));
1490
1529
  ws.emit(event('hosting-user-info-changed', { email: 'a@b.c', remainingCredits: '1', hotWalletAddress: null, freeAccess: false }));
1491
1530
  ws.emit(perspectiveAdded('uuid-a'));
1492
- ws.emit(event('perspective-updated', { perspectiveUuid: 'uuid-a', owner: OWNER, perspective: wireHandle('uuid-a') }));
1493
- ws.emit(event('perspective-removed', { perspectiveUuid: 'uuid-a', uuid: 'uuid-a', owner: OWNER }));
1494
- ws.emit(event('message-received', { message: {
1495
- author: 'did:test:1', timestamp: '2024-01-01T00:00:00.000Z', data: { links: [] },
1496
- proof: { key: 'k', signature: 's', valid: true, invalid: false },
1497
- } }));
1531
+ ws.emit(event('perspective-updated', { perspectiveUuid: 'uuid-a', perspective: wireHandle('uuid-a') }));
1532
+ ws.emit(event('perspective-removed', { perspectiveUuid: 'uuid-a', uuid: 'uuid-a' }));
1498
1533
  ws.emit(event('exception-occurred', { exception }));
1499
1534
  ws.emit(event('notification-triggered', { perspectiveUuid: 'uuid-a', notification }));
1500
1535
 
package/src/Ad4mClient.ts CHANGED
@@ -99,6 +99,16 @@ export class Ad4mClient {
99
99
  return this.#apiClient.on(type, handler, filter)
100
100
  }
101
101
 
102
+ /**
103
+ * Call `callback` once when the executor refuses this client's token
104
+ * (expired, revoked, or no session). Every call then fails with a 401
105
+ * `RpcError` and the client stops reconnecting: log in again and build a
106
+ * new client. Returns a function that removes the callback.
107
+ */
108
+ onAuthFailed(callback: (reason: string) => void): () => void {
109
+ return this.#apiClient.onAuthFailed(callback)
110
+ }
111
+
102
112
  /** Close all event connections and clear in-memory caches */
103
113
  close(): void {
104
114
  this.#agentClient.clearByDidCache()
@@ -230,8 +230,18 @@ export class AgentClient {
230
230
  this.#cacheAgent(Agent.fromWire(event.agent));
231
231
  };
232
232
 
233
- async requestCapability(authInfo: AuthInfoInput): Promise<string> {
234
- return this.#apiClient.call('agent.requestCapability', { authInfo });
233
+ /**
234
+ * Asks the executor for a capability token. `agent` names the agent the token will act
235
+ * as: a managed user's email or an agent's DID; absent, the executor's main agent. That
236
+ * agent's owner approves the request (the operator for the main agent, the user for
237
+ * theirs). Returns the request id that {@link generateJwt} redeems with the approver's
238
+ * six-digit code.
239
+ */
240
+ async requestCapability(authInfo: AuthInfoInput, agent?: string): Promise<string> {
241
+ return this.#apiClient.call(
242
+ 'agent.requestCapability',
243
+ agent === undefined ? { authInfo } : { authInfo, agent },
244
+ );
235
245
  }
236
246
 
237
247
  async permitCapability(auth: string): Promise<string> {
@@ -279,6 +289,20 @@ export class AgentClient {
279
289
  return this.#apiClient.call('user.verifyEmail', { email, code, verificationType });
280
290
  }
281
291
 
292
+ /** Revokes this client's user token. The executor then closes the client's sockets. */
293
+ async logout(): Promise<boolean> {
294
+ return this.#apiClient.call('user.logout', {});
295
+ }
296
+
297
+ /**
298
+ * Revokes every token of a user issued up to now, this client's own included, and closes
299
+ * their sockets. A user leaves out `email` (or names themselves); the operator names the
300
+ * user. Needs AGENT_UPDATE, which a login holds. Tokens from a later login work.
301
+ */
302
+ async revokeAllSessions(email?: string): Promise<boolean> {
303
+ return this.#apiClient.call('user.revokeAllSessions', email === undefined ? {} : { email });
304
+ }
305
+
282
306
  // Hosting methods
283
307
  async hostingUserInfo(): Promise<HostingUserInfo> {
284
308
  const info = (await this.#apiClient.call('hosting.info', {})).userInfo ?? {
package/src/ai/AITypes.ts CHANGED
@@ -2,7 +2,8 @@ import { AIModelLoadingStatus, AITask, AITaskInput } from "./Tasks";
2
2
 
3
3
  export class ModelApi {
4
4
  baseUrl: string;
5
- apiKey: string;
5
+ /** Whether the model has a provider key. The executor never returns the key itself. */
6
+ hasApiKey: boolean;
6
7
  model: string;
7
8
  apiType: String;
8
9
  /** Optional ceiling for the provider's context window (tokens).
@@ -35,7 +36,10 @@ export class Model {
35
36
 
36
37
  export class ModelApiInput {
37
38
  baseUrl: string;
38
- apiKey: string;
39
+ /** The provider key. Empty or left out on `addModel`: no key. Left out on
40
+ * `updateModel`: the stored key stays, and the update is refused if `baseUrl`
41
+ * changes too. Empty on `updateModel`: the stored key is removed. */
42
+ apiKey?: string;
39
43
  model: string;
40
44
  apiType: string;
41
45
  /** Optional ceiling for the provider's context window (tokens). */
@@ -23,7 +23,7 @@ class TestSocket {
23
23
  onopen: (() => void) | null = null
24
24
  onmessage: ((ev: { data: string }) => void) | null = null
25
25
  onerror: ((ev: unknown) => void) | null = null
26
- onclose: (() => void) | null = null
26
+ onclose: ((ev: { code: number; reason: string }) => void) | null = null
27
27
 
28
28
  constructor(public url: string) {
29
29
  TestSocket.instances.push(this)
@@ -39,7 +39,8 @@ class TestSocket {
39
39
  }
40
40
  }
41
41
  open() { this.readyState = 1; this.onopen?.() }
42
- drop() { this.readyState = 3; this.onclose?.() }
42
+ /** Close from the server side; 1006 is an abnormal close with no close frame. */
43
+ drop(code = 1006, reason = '') { this.readyState = 3; this.onclose?.({ code, reason }) }
43
44
  reply(msg: AnyMsg) { this.onmessage?.({ data: JSON.stringify(msg) }) }
44
45
  }
45
46
 
@@ -342,6 +343,131 @@ describe('ApiClient.onReconnect', () => {
342
343
  })
343
344
  })
344
345
 
346
+ describe('ApiClient when the executor refuses the token', () => {
347
+ const REASON = 'Unauthorized access: the token expired or was revoked'
348
+ let authFailed: jest.Mock
349
+ beforeEach(() => {
350
+ TestSocket.autoOpen = false
351
+ jest.useFakeTimers()
352
+ authFailed = jest.fn()
353
+ client.onAuthFailed(authFailed)
354
+ })
355
+ afterEach(() => jest.useRealTimers())
356
+
357
+ it('rejects sent calls with 401 on close code 1008, and does not reconnect', async () => {
358
+ open()
359
+ socket(0).open()
360
+ const write = call('perspective.addLink', { uuid: 'u' })
361
+ const read = call('perspective.all')
362
+ socket(0).drop(1008, REASON)
363
+ await expect(write).rejects.toMatchObject({ name: 'RpcError', status: 401, body: REASON })
364
+ // A read is retried after an ordinary close; a refused token gets no retry.
365
+ await expect(read).rejects.toMatchObject({ name: 'RpcError', status: 401, body: REASON })
366
+ expect(authFailed).toHaveBeenCalledTimes(1)
367
+ expect(authFailed).toHaveBeenCalledWith(REASON)
368
+ jest.advanceTimersByTime(60_000)
369
+ expect(TestSocket.instances).toHaveLength(1)
370
+ })
371
+
372
+ it('rejects a call still waiting to go out with 401 when the socket closes 1008 before it opens', async () => {
373
+ const queued = call('agent.get')
374
+ socket(0).drop(1008, REASON)
375
+ await expect(queued).rejects.toMatchObject({ name: 'RpcError', status: 401, body: REASON })
376
+ expect(authFailed).toHaveBeenCalledTimes(1)
377
+ jest.advanceTimersByTime(60_000)
378
+ expect(TestSocket.instances).toHaveLength(1)
379
+ })
380
+
381
+ it('rejects a waiting watchApplied() with 401 when the socket closes 1008 before it opens', async () => {
382
+ open()
383
+ const applied = client.watchApplied()
384
+ socket(0).drop(1008, REASON)
385
+ await expect(applied).rejects.toMatchObject({ name: 'RpcError', status: 401, body: REASON })
386
+ })
387
+
388
+ it('rejects a waiting watchApplied() with the reason when the socket closes 1013 before it opens', async () => {
389
+ const LOCKED = 'Executor is locked: ask the operator to unlock it, then reconnect'
390
+ open()
391
+ const applied = client.watchApplied()
392
+ socket(0).drop(1013, LOCKED)
393
+ await expect(applied).rejects.toMatchObject({ name: 'RpcError', status: 503, body: LOCKED })
394
+ expect(authFailed).not.toHaveBeenCalled()
395
+ })
396
+
397
+ it('fails every later call with 401 without opening a socket', async () => {
398
+ open()
399
+ socket(0).drop(1008, REASON)
400
+ open()
401
+ await expect(call('agent.get')).rejects.toMatchObject({ status: 401, body: REASON })
402
+ await expect(client.watchApplied()).rejects.toMatchObject({ status: 401 })
403
+ jest.advanceTimersByTime(60_000)
404
+ expect(TestSocket.instances).toHaveLength(1)
405
+ })
406
+
407
+ it('rejects watchApplied() with 401 when the executor refuses events.watch on an open socket', async () => {
408
+ open()
409
+ jest.runAllTicks() // fake timers hold the queued watch flush
410
+ socket(0).open()
411
+ const watch = socket(0).sent.find((m) => m.type === 'events.watch')!
412
+ const applied = client.watchApplied()
413
+ socket(0).reply({ id: watch.id, error: { code: 401, message: REASON } })
414
+ await expect(applied).rejects.toMatchObject({ name: 'RpcError', status: 401, body: REASON })
415
+ expect(authFailed).toHaveBeenCalledTimes(1)
416
+ })
417
+
418
+ it('fails every pending call on a 401 reply and stops once the executor closes the socket', async () => {
419
+ open()
420
+ socket(0).open()
421
+ const first = call('agent.get')
422
+ const second = call('perspective.addLink', { uuid: 'u' })
423
+ socket(0).reply({ id: socket(0).sent.find((m) => m.type === 'agent.get')!.id, error: { code: 401, message: REASON } })
424
+ await expect(first).rejects.toMatchObject({ name: 'RpcError', status: 401, body: REASON })
425
+ await expect(second).rejects.toMatchObject({ name: 'RpcError', status: 401, body: REASON })
426
+ expect(socket(0).readyState).toBe(3)
427
+ socket(0).drop(1008, REASON)
428
+ jest.advanceTimersByTime(60_000)
429
+ expect(TestSocket.instances).toHaveLength(1)
430
+ expect(authFailed).toHaveBeenCalledTimes(1)
431
+ })
432
+
433
+ it('still reconnects after an ordinary close, with 503 for an unsent write', async () => {
434
+ open()
435
+ socket(0).open()
436
+ const write = call('perspective.addLink', { uuid: 'u' })
437
+ socket(0).drop()
438
+ await expect(write).rejects.toMatchObject({ status: 503 })
439
+ jest.advanceTimersByTime(500)
440
+ expect(TestSocket.instances).toHaveLength(2)
441
+ expect(authFailed).not.toHaveBeenCalled()
442
+ })
443
+
444
+ // A locked wallet is a state of the executor: the token may be good. 1013 is not an auth failure.
445
+ it('treats close code 1013 (executor locked) as an ordinary close that carries its reason', async () => {
446
+ const LOCKED = 'Executor is locked: ask the operator to unlock it, then reconnect'
447
+ open()
448
+ socket(0).open()
449
+ const write = call('perspective.addLink', { uuid: 'u' })
450
+ socket(0).drop(1013, LOCKED)
451
+ await expect(write).rejects.toMatchObject({ name: 'RpcError', status: 503, body: LOCKED })
452
+ expect(authFailed).not.toHaveBeenCalled()
453
+ jest.advanceTimersByTime(500)
454
+ expect(TestSocket.instances).toHaveLength(2)
455
+ expect(socket(1).url).toBe(socket(0).url)
456
+ })
457
+
458
+ it('leaves a new client, with a new token, free to connect', async () => {
459
+ open()
460
+ socket(0).drop(1008, REASON)
461
+ const fresh = new ApiClient(url, 'new-token', TestSocket as unknown as new (url: string) => WebSocket)
462
+ const reply = (fresh.call as UntypedCall)('agent.get', {})
463
+ socket(1).open()
464
+ expect(socket(1).url).toContain('token=new-token')
465
+ socket(1).reply({ id: socket(1).sent.find((m) => m.type === 'agent.get')!.id, result: { did: 'd' } })
466
+ await expect(reply).resolves.toEqual({ did: 'd' })
467
+ fresh.closeAll()
468
+ })
469
+ })
470
+
345
471
  describe('long calls', () => {
346
472
  beforeEach(() => jest.useFakeTimers())
347
473
  afterEach(() => jest.useRealTimers())
@@ -395,7 +521,6 @@ function linkAdded(perspectiveUuid: string, target = 'literal://x') {
395
521
  return {
396
522
  type: 'link-added',
397
523
  perspectiveUuid,
398
- owner: 'did:test:owner',
399
524
  link: {
400
525
  author: 'did:test:alice',
401
526
  timestamp: '2026-01-01T00:00:00Z',
package/src/apiClient.ts CHANGED
@@ -85,7 +85,14 @@ interface PendingCall {
85
85
  reject: (reason: unknown) => void
86
86
  }
87
87
 
88
- const closedError = () => new RpcError(503, 'WebSocket connection closed')
88
+ const closedError = (reason?: string) => new RpcError(503, reason || 'WebSocket connection closed')
89
+
90
+ /** Close code for "try again later": the executor's wallet is locked, so it cannot check the
91
+ * token yet. The token may be good: reconnect as for any close, and pass the reason on. */
92
+ const CLOSE_TRY_AGAIN_LATER = 1013
93
+
94
+ /** Close code the executor uses when the socket's token opens no session, expired or was revoked. */
95
+ const CLOSE_AUTH_FAILED = 1008
89
96
 
90
97
  export class ApiClient {
91
98
  private baseUrl: string
@@ -117,6 +124,10 @@ export class ApiClient {
117
124
  /** `on()` handlers by event type; a type with none has no entry. */
118
125
  private _handlers = new Map<string, Set<Registration>>()
119
126
  private _reconnectCallbacks = new Set<() => void>()
127
+ private _authFailedCallbacks = new Set<(reason: string) => void>()
128
+ /** Set once the executor refused the token: the reason. The client then
129
+ * never connects again; a new token needs a new client. */
130
+ private _authFailed: string | null = null
120
131
  private _hasConnectedOnce = false
121
132
  private _pendingCalls = new Map<string, PendingCall>()
122
133
  private _wsReconnectTimer: ReturnType<typeof setTimeout> | null = null
@@ -142,6 +153,7 @@ export class ApiClient {
142
153
 
143
154
  private _ensureWs(): void {
144
155
  if (this._ws) return
156
+ if (this._authFailed !== null) throw new RpcError(401, this._authFailed)
145
157
  const WsImpl = this._webSocketImpl ?? globalThis.WebSocket
146
158
  const ws = new WsImpl(this._getWsUrl())
147
159
  this._ws = ws
@@ -150,9 +162,16 @@ export class ApiClient {
150
162
  resolve()
151
163
  this._onOpen(ws)
152
164
  }
153
- ws.onclose = () => {
154
- reject(closedError())
155
- this._onClose(ws)
165
+ ws.onclose = (event?: CloseEvent) => {
166
+ // Classify the close for watchApplied() as for every other waiting call.
167
+ reject(event?.code === CLOSE_AUTH_FAILED
168
+ ? new RpcError(401, event.reason || 'token expired or revoked')
169
+ : closedError(event?.code === CLOSE_TRY_AGAIN_LATER ? event.reason : undefined))
170
+ if (event?.code === CLOSE_AUTH_FAILED && this._ws === ws) {
171
+ this._failAuth(event.reason || 'Unauthorized access: the token expired or was revoked')
172
+ } else {
173
+ this._onClose(ws, event?.code === CLOSE_TRY_AGAIN_LATER ? event.reason : undefined)
174
+ }
156
175
  }
157
176
  })
158
177
  // Only watchApplied() awaits this; a close before open is not an error otherwise.
@@ -169,8 +188,14 @@ export class ApiClient {
169
188
  const pending = this._pendingCalls.get(parsed.id as string)
170
189
  if (!pending) return // late reply to a timed-out or aborted call, or a cancel ack
171
190
  const error = parsed.error as { code?: number; message?: string } | undefined
172
- if (error) pending.reject(new RpcError(error.code ?? 500, error.message ?? 'Unknown error'))
173
- else pending.resolve(parsed.result)
191
+ if (!error) {
192
+ pending.resolve(parsed.result)
193
+ return
194
+ }
195
+ const rpcError = new RpcError(error.code ?? 500, error.message ?? 'Unknown error')
196
+ pending.reject(rpcError)
197
+ // The executor answers 401 only when the token stopped working, then closes the socket.
198
+ if (rpcError.status === 401) this._failAuth(rpcError.body)
174
199
  return
175
200
  }
176
201
  if (parsed.type === 'pong') return
@@ -215,7 +240,8 @@ export class ApiClient {
215
240
  this._hasConnectedOnce = true
216
241
  }
217
242
 
218
- private _onClose(ws: WebSocket): void {
243
+ /** `reason` is set when the executor asked to try again later; calls that fail carry it. */
244
+ private _onClose(ws: WebSocket, reason?: string): void {
219
245
  // A socket closed by _closeWs() can report after a new one exists.
220
246
  if (this._ws !== ws) return
221
247
  this._stopPing()
@@ -227,12 +253,23 @@ export class ApiClient {
227
253
  pending.sent = false
228
254
  pending.retry = false
229
255
  } else {
230
- pending.reject(closedError())
256
+ pending.reject(closedError(reason))
231
257
  }
232
258
  }
233
259
  if (this._handlers.size > 0 || this._pendingCalls.size > 0) this._scheduleReconnect()
234
260
  }
235
261
 
262
+ /** The executor refused the token: fail every call with 401, stop
263
+ * reconnecting and tell the `onAuthFailed` callbacks, once. */
264
+ private _failAuth(reason: string): void {
265
+ if (this._authFailed !== null) return
266
+ this._authFailed = reason
267
+ const error = new RpcError(401, reason)
268
+ for (const pending of this._pendingCalls.values()) pending.reject(error)
269
+ this._closeWs()
270
+ for (const cb of [...this._authFailedCallbacks]) callSafely(cb, 'Error in auth-failed callback:', reason)
271
+ }
272
+
236
273
  private _startPing(): void {
237
274
  this._stopPing()
238
275
  this._wsPingTimer = setInterval(() => {
@@ -250,7 +287,7 @@ export class ApiClient {
250
287
  }
251
288
 
252
289
  private _scheduleReconnect(): void {
253
- if (this._wsReconnectTimer) return
290
+ if (this._wsReconnectTimer || this._authFailed !== null) return
254
291
  const delay = this._wsReconnectDelay
255
292
  this._wsReconnectDelay = Math.min(this._wsReconnectDelay * 2, MAX_RECONNECT_DELAY_MS)
256
293
  this._wsReconnectTimer = setTimeout(() => {
@@ -352,7 +389,8 @@ export class ApiClient {
352
389
  regs.add(reg)
353
390
  this._scheduleWatch()
354
391
  }
355
- this._ensureWs()
392
+ // A client whose token was refused keeps the handler but opens no socket.
393
+ if (this._authFailed === null) this._ensureWs()
356
394
 
357
395
  return () => {
358
396
  const regs = this._handlers.get(type)
@@ -415,9 +453,11 @@ export class ApiClient {
415
453
  const key = JSON.stringify(events)
416
454
  if (key === this._watching) return
417
455
  this._watching = key
418
- this._watchSent = this._request('events.watch', events).then(() => { this._watchRetries = 0 }, (e) => {
456
+ const sent = this._request('events.watch', events).then(() => { this._watchRetries = 0 }, (e) => {
419
457
  if (this._watching !== key) return
420
458
  this._watching = null
459
+ // A refused token (401) gets no next socket: watchApplied() must not resolve.
460
+ if (e instanceof RpcError && e.status === 401) throw e
421
461
  // A closed socket (503) gets the watch again when the next one opens.
422
462
  if (e instanceof RpcError && e.status === 503) return
423
463
  console.error('events.watch failed:', e)
@@ -428,6 +468,9 @@ export class ApiClient {
428
468
  }, WATCH_RETRY_DELAY_MS)
429
469
  }
430
470
  })
471
+ // Only watchApplied() awaits this; a refused watch is not an unhandled rejection otherwise.
472
+ sent.catch(() => {})
473
+ this._watchSent = sent
431
474
  }
432
475
 
433
476
  private _closeWs(): void {
@@ -454,6 +497,15 @@ export class ApiClient {
454
497
  return () => { this._reconnectCallbacks.delete(callback) }
455
498
  }
456
499
 
500
+ /** Register a callback that fires once when the executor refuses this
501
+ * client's token: a 401 reply, or a socket closed with code 1008. Every
502
+ * call then fails with a 401 `RpcError` and the client does not reconnect;
503
+ * build a new client to use another token. Returns an unsubscribe function. */
504
+ onAuthFailed(callback: (reason: string) => void): () => void {
505
+ this._authFailedCallbacks.add(callback)
506
+ return () => { this._authFailedCallbacks.delete(callback) }
507
+ }
508
+
457
509
  /** Close the WebSocket and reject pending calls. */
458
510
  closeAll(): void {
459
511
  for (const pending of this._pendingCalls.values()) {
@@ -462,6 +514,7 @@ export class ApiClient {
462
514
  this._closeWs()
463
515
  this._handlers.clear()
464
516
  this._reconnectCallbacks.clear()
517
+ this._authFailedCallbacks.clear()
465
518
  // A reused client must not fire onReconnect on its next first open.
466
519
  this._hasConnectedOnce = false
467
520
  }
@@ -1,4 +1,9 @@
1
1
  // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
2
  import type { AuthInfo } from "./AuthInfo";
3
3
 
4
- export type Apps = { auth: AuthInfo, requestId: string, revoked: boolean | null, token: string, };
4
+ export type Apps = { auth: AuthInfo, requestId: string, revoked: boolean | null,
5
+ /**
6
+ * Always empty: the executor does not keep app tokens, and an app receives its token
7
+ * once, from `agent.generateJwt`. The field stays for clients that require it.
8
+ */
9
+ token: string, };
@@ -1,4 +1,9 @@
1
1
  // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
2
2
  import type { Capability } from "./Capability";
3
3
 
4
- export type AuthInfo = { appName: string, appDesc: string, appDomain: string | null, appUrl: string | null, appIconPath: string | null, capabilities: Array<Capability> | null, userEmail: string | null, };
4
+ export type AuthInfo = { appName: string, appDesc: string, appDomain: string | null, appUrl: string | null, appIconPath: string | null, capabilities: Array<Capability> | null,
5
+ /**
6
+ * The user a multi-user token is minted for: the login name of a managed agent's
7
+ * account. The token's `sub` carries the agent's DID; this stays as the account's name.
8
+ */
9
+ userEmail: string | null, };
@@ -10,14 +10,13 @@ import type { AutoProcessorNeighbourhoodState } from "./AutoProcessorNeighbourho
10
10
  import type { ExceptionOccurredEvent } from "./ExceptionOccurredEvent";
11
11
  import type { FlowStateChangedEvent } from "./FlowStateChangedEvent";
12
12
  import type { HostingUserInfo } from "./HostingUserInfo";
13
- import type { MessageReceivedEvent } from "./MessageReceivedEvent";
14
13
  import type { NeighbourhoodSignalFilter } from "./NeighbourhoodSignalFilter";
15
14
  import type { NotificationTriggeredEvent } from "./NotificationTriggeredEvent";
16
- import type { PerspectiveLinkUpdatedWithOwner } from "./PerspectiveLinkUpdatedWithOwner";
17
- import type { PerspectiveLinkWithOwner } from "./PerspectiveLinkWithOwner";
18
- import type { PerspectiveRemovedWithOwner } from "./PerspectiveRemovedWithOwner";
15
+ import type { PerspectiveEvent } from "./PerspectiveEvent";
16
+ import type { PerspectiveLinkEvent } from "./PerspectiveLinkEvent";
17
+ import type { PerspectiveLinkUpdatedEvent } from "./PerspectiveLinkUpdatedEvent";
18
+ import type { PerspectiveRemovedEvent } from "./PerspectiveRemovedEvent";
19
19
  import type { PerspectiveStateFilter } from "./PerspectiveStateFilter";
20
- import type { PerspectiveWithOwner } from "./PerspectiveWithOwner";
21
20
  import type { QuerySubscriptionUpdateEvent } from "./QuerySubscriptionUpdateEvent";
22
21
  import type { SfuCallRenegotiationOffer } from "./SfuCallRenegotiationOffer";
23
22
  import type { SfuDataMessage } from "./SfuDataMessage";
@@ -31,15 +30,14 @@ export interface EventMap {
31
30
  "agent-updated": AgentUpdatedEvent;
32
31
  "apps-changed": Apps;
33
32
  "hosting-user-info-changed": HostingUserInfo;
34
- "perspective-added": PerspectiveWithOwner;
35
- "perspective-removed": PerspectiveRemovedWithOwner;
36
- "perspective-updated": PerspectiveWithOwner;
33
+ "perspective-added": PerspectiveEvent;
34
+ "perspective-removed": PerspectiveRemovedEvent;
35
+ "perspective-updated": PerspectiveEvent;
37
36
  "sync-state-change": PerspectiveStateFilter;
38
- "link-added": PerspectiveLinkWithOwner;
39
- "link-removed": PerspectiveLinkWithOwner;
40
- "link-updated": PerspectiveLinkUpdatedWithOwner;
37
+ "link-added": PerspectiveLinkEvent;
38
+ "link-removed": PerspectiveLinkEvent;
39
+ "link-updated": PerspectiveLinkUpdatedEvent;
41
40
  "signal": NeighbourhoodSignalFilter;
42
- "message-received": MessageReceivedEvent;
43
41
  "notification-triggered": NotificationTriggeredEvent;
44
42
  "exception-occurred": ExceptionOccurredEvent;
45
43
  "transcription-text": TranscriptionTextFilter;
@@ -12,8 +12,9 @@
12
12
  */
13
13
  export type FlowStateChangedEvent = { perspectiveUuid: string,
14
14
  /**
15
- * The agent whose replica derived this. The delivery filter matches it
16
- * against the socket's agent; nobody else receives the event.
15
+ * The agent whose replica derived this: the event's only recipient when it
16
+ * may read the perspective. Otherwise only the operator gets the main
17
+ * agent's event, and nobody gets another agent's.
17
18
  */
18
19
  agentDid: string, instance: string,
19
20
  /**