@qvac/core 0.3.5 → 0.4.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 (173) hide show
  1. package/CHANGELOG.md +177 -9
  2. package/README.md +19 -17
  3. package/dist-lib/lib/api/agents.d.ts +3 -3
  4. package/dist-lib/lib/api/agents.js +31 -20
  5. package/dist-lib/lib/api/approval-rules.d.ts +2 -2
  6. package/dist-lib/lib/api/approval-rules.js +2 -2
  7. package/dist-lib/lib/api/attachments.d.ts +2 -2
  8. package/dist-lib/lib/api/attachments.js +14 -25
  9. package/dist-lib/lib/api/chat-groups.d.ts +2 -2
  10. package/dist-lib/lib/api/chat-groups.js +9 -9
  11. package/dist-lib/lib/api/chat.d.ts +4 -2
  12. package/dist-lib/lib/api/chat.js +18 -18
  13. package/dist-lib/lib/api/chunks.d.ts +2 -2
  14. package/dist-lib/lib/api/chunks.js +27 -36
  15. package/dist-lib/lib/api/current-mesh.d.ts +7 -15
  16. package/dist-lib/lib/api/current-mesh.js +7 -22
  17. package/dist-lib/lib/api/devices.d.ts +4 -3
  18. package/dist-lib/lib/api/devices.js +18 -18
  19. package/dist-lib/lib/api/execution.d.ts +2 -2
  20. package/dist-lib/lib/api/execution.js +6 -6
  21. package/dist-lib/lib/api/files.d.ts +2 -2
  22. package/dist-lib/lib/api/files.js +4 -4
  23. package/dist-lib/lib/api/index.d.ts +12 -11
  24. package/dist-lib/lib/api/index.js +15 -13
  25. package/dist-lib/lib/api/inference-calls.d.ts +1 -1
  26. package/dist-lib/lib/api/inference-calls.js +2 -2
  27. package/dist-lib/lib/api/knowledge.d.ts +2 -2
  28. package/dist-lib/lib/api/knowledge.js +22 -11
  29. package/dist-lib/lib/api/local-files.d.ts +3 -0
  30. package/dist-lib/lib/api/local-files.js +23 -0
  31. package/dist-lib/lib/api/members.d.ts +6 -2
  32. package/dist-lib/lib/api/members.js +24 -17
  33. package/dist-lib/lib/api/mesh.d.ts +4 -5
  34. package/dist-lib/lib/api/mesh.js +7 -9
  35. package/dist-lib/lib/api/notifications.d.ts +2 -13
  36. package/dist-lib/lib/api/notifications.js +20 -52
  37. package/dist-lib/lib/api/rag.d.ts +2 -2
  38. package/dist-lib/lib/api/rag.js +4 -4
  39. package/dist-lib/lib/api/range.d.ts +11 -0
  40. package/dist-lib/lib/api/range.js +10 -0
  41. package/dist-lib/lib/api/sync.d.ts +2 -2
  42. package/dist-lib/lib/api/sync.js +3 -3
  43. package/dist-lib/lib/api/tool-activity.d.ts +2 -2
  44. package/dist-lib/lib/api/tool-activity.js +11 -10
  45. package/dist-lib/lib/api/tool-configs.d.ts +2 -2
  46. package/dist-lib/lib/api/tool-configs.js +6 -7
  47. package/dist-lib/lib/api/upload-frames.d.ts +9 -0
  48. package/dist-lib/lib/api/upload-frames.js +17 -0
  49. package/dist-lib/lib/api/watchable.d.ts +1 -6
  50. package/dist-lib/lib/api/watchable.js +4 -13
  51. package/dist-lib/lib/assistant/history.d.ts +3 -3
  52. package/dist-lib/lib/assistant-client.js +3 -2
  53. package/dist-lib/lib/assistant-tree.js +1 -1
  54. package/dist-lib/lib/assistant.d.ts +16 -14
  55. package/dist-lib/lib/assistant.js +166 -137
  56. package/dist-lib/lib/collabora/convert.js +1 -1
  57. package/dist-lib/lib/core/agent.d.ts +5 -7
  58. package/dist-lib/lib/core/agent.js +26 -6
  59. package/dist-lib/lib/core/archived-mesh.js +1 -0
  60. package/dist-lib/lib/core/chat-order.d.ts +20 -0
  61. package/dist-lib/lib/core/chat-order.js +96 -0
  62. package/dist-lib/lib/core/chat.d.ts +0 -5
  63. package/dist-lib/lib/core/chat.js +1 -3
  64. package/dist-lib/lib/core/chunk.d.ts +7 -14
  65. package/dist-lib/lib/core/chunk.js +17 -35
  66. package/dist-lib/lib/core/contract/agents.js +8 -0
  67. package/dist-lib/lib/core/contract/compute.d.ts +1 -1
  68. package/dist-lib/lib/core/contract/compute.js +1 -0
  69. package/dist-lib/lib/core/contract/joined-meshes.js +4 -3
  70. package/dist-lib/lib/core/contract/members.js +4 -3
  71. package/dist-lib/lib/core/contract/writers.js +5 -4
  72. package/dist-lib/lib/core/departures.js +5 -4
  73. package/dist-lib/lib/core/device-invites.js +2 -1
  74. package/dist-lib/lib/core/files/attachments.d.ts +8 -1
  75. package/dist-lib/lib/core/files/index.d.ts +4 -4
  76. package/dist-lib/lib/core/files/index.js +18 -8
  77. package/dist-lib/lib/core/files/local-index.d.ts +16 -0
  78. package/dist-lib/lib/core/files/local-index.js +38 -0
  79. package/dist-lib/lib/core/files/processing/document.js +2 -1
  80. package/dist-lib/lib/core/files/processing/ownership.js +6 -3
  81. package/dist-lib/lib/core/files/records/chunks.js +1 -0
  82. package/dist-lib/lib/core/files/records/reclaim.js +1 -0
  83. package/dist-lib/lib/core/files/records/routing.js +2 -1
  84. package/dist-lib/lib/core/files/store/blob.d.ts +1 -1
  85. package/dist-lib/lib/core/files/store/blob.js +6 -3
  86. package/dist-lib/lib/core/files/store/index.d.ts +1 -1
  87. package/dist-lib/lib/core/files/store/reference.js +4 -3
  88. package/dist-lib/lib/core/files/store/server.d.ts +8 -4
  89. package/dist-lib/lib/core/files/store/server.js +16 -12
  90. package/dist-lib/lib/core/files/store/sweep.js +2 -1
  91. package/dist-lib/lib/core/files/upload.d.ts +1 -1
  92. package/dist-lib/lib/core/hosted-agents.js +1 -1
  93. package/dist-lib/lib/core/image/cache-sweep.d.ts +1 -0
  94. package/dist-lib/lib/core/image/cache-sweep.js +7 -3
  95. package/dist-lib/lib/core/local/files.d.ts +24 -0
  96. package/dist-lib/lib/core/local/files.js +154 -0
  97. package/dist-lib/lib/core/local/index.d.ts +21 -5
  98. package/dist-lib/lib/core/local/index.js +75 -45
  99. package/dist-lib/lib/core/membership.d.ts +4 -1
  100. package/dist-lib/lib/core/membership.js +17 -2
  101. package/dist-lib/lib/core/mesh.d.ts +5 -0
  102. package/dist-lib/lib/core/mesh.js +10 -5
  103. package/dist-lib/lib/core/migrations/agent-indexes.d.ts +2 -0
  104. package/dist-lib/lib/core/migrations/agent-indexes.js +30 -0
  105. package/dist-lib/lib/core/migrations/file-index.d.ts +2 -0
  106. package/dist-lib/lib/core/migrations/file-index.js +27 -0
  107. package/dist-lib/lib/core/migrations/index.js +3 -1
  108. package/dist-lib/lib/core/notification.js +5 -5
  109. package/dist-lib/lib/core/range.d.ts +18 -0
  110. package/dist-lib/lib/core/range.js +17 -0
  111. package/dist-lib/lib/core/sync/index.js +39 -32
  112. package/dist-lib/lib/core/sync-status.js +3 -2
  113. package/dist-lib/lib/core/tool-activity.d.ts +2 -5
  114. package/dist-lib/lib/core/tool-activity.js +4 -7
  115. package/dist-lib/lib/core.d.ts +48 -29
  116. package/dist-lib/lib/core.js +465 -359
  117. package/dist-lib/lib/knowledge-search.d.ts +2 -2
  118. package/dist-lib/lib/kv-cache.js +1 -1
  119. package/dist-lib/lib/log.js +2 -3
  120. package/dist-lib/lib/mesh-scoped-engine.d.ts +8 -1
  121. package/dist-lib/lib/mesh-scoped-engine.js +62 -15
  122. package/dist-lib/lib/model-download.d.ts +14 -5
  123. package/dist-lib/lib/model-download.js +25 -17
  124. package/dist-lib/lib/oauth/browser-connect.d.ts +0 -14
  125. package/dist-lib/lib/oauth/browser-connect.js +1 -26
  126. package/dist-lib/lib/oauth/token-exchange.d.ts +1 -2
  127. package/dist-lib/lib/oauth/token-exchange.js +1 -4
  128. package/dist-lib/lib/run-transcript.d.ts +2 -2
  129. package/dist-lib/lib/run-transcript.js +3 -2
  130. package/dist-lib/lib/task.d.ts +1 -0
  131. package/dist-lib/lib/task.js +3 -2
  132. package/dist-lib/schema/build.js +4 -10
  133. package/dist-lib/schema/engine.js +261 -91
  134. package/dist-lib/schema/field-order.js +1 -4
  135. package/dist-lib/schema/helpers.d.ts +4 -0
  136. package/dist-lib/schema/helpers.js +20 -0
  137. package/dist-lib/schema/local.d.ts +1 -1
  138. package/dist-lib/schema/local.js +70 -2
  139. package/dist-lib/schema/qvac.js +30 -0
  140. package/dist-lib/spec/bind.js +20 -3
  141. package/dist-lib/spec/calls.js +19 -15
  142. package/dist-lib/spec/capabilities.d.ts +42 -34
  143. package/dist-lib/spec/hrpc/hrpc.json +82 -30
  144. package/dist-lib/spec/hrpc/index.js +106 -57
  145. package/dist-lib/spec/hrpc/messages.js +5420 -5019
  146. package/dist-lib/spec/hyperschema/index.js +5424 -5023
  147. package/dist-lib/spec/hyperschema/schema.json +3202 -2666
  148. package/dist-lib/spec/hyperschema/types.d.ts +455 -319
  149. package/dist-lib/spec/local/hyperdb/db.json +119 -1
  150. package/dist-lib/spec/local/hyperdb/index.js +414 -2
  151. package/dist-lib/spec/local/hyperdb/messages.js +505 -124
  152. package/dist-lib/spec/local/hyperschema/index.js +203 -5
  153. package/dist-lib/spec/local/hyperschema/schema.json +136 -1
  154. package/dist-lib/spec/local/hyperschema/types.d.ts +32 -1
  155. package/dist-lib/spec/mesh/hyperdb/db.json +55 -3
  156. package/dist-lib/spec/mesh/hyperdb/index.js +119 -3
  157. package/dist-lib/spec/mesh/hyperdb/messages.js +244 -172
  158. package/dist-lib/spec/mesh/hyperdispatch/dispatch.json +7 -1
  159. package/dist-lib/spec/mesh/hyperdispatch/index.js +18 -1
  160. package/dist-lib/spec/mesh/hyperdispatch/messages.js +74 -2
  161. package/dist-lib/spec/mesh/hyperschema/index.js +74 -2
  162. package/dist-lib/spec/mesh/hyperschema/schema.json +27 -1
  163. package/dist-lib/spec/mesh/hyperschema/types.d.ts +9 -1
  164. package/package.json +15 -9
  165. package/tui/app.mjs +376 -151
  166. package/tui/boot.mjs +2 -1
  167. package/tui/lib/busy-words.mjs +2 -1
  168. package/tui/lib/knowledge-command.mjs +11 -10
  169. package/tui/lib/knowledge-import.mjs +7 -5
  170. package/tui/lib/render.mjs +4 -3
  171. package/tui/lib/usage.mjs +2 -1
  172. package/tui/main.mjs +2 -1
  173. package/tui/lib/projection-env.mjs +0 -24
@@ -1,4 +1,5 @@
1
1
  import { meshWatchable, requireMesh } from './current-mesh.js';
2
+ import b4a from 'b4a';
2
3
  const MEMBERS = '@qvac/members';
3
4
  const DEVICES = '@qvac/devices';
4
5
  const RESOLVE_MEMBER_MS = 10_000;
@@ -25,15 +26,15 @@ async function liveMemberIds(snap) {
25
26
  for await (const device of snap.find(DEVICES)) {
26
27
  const owner = device.revoked ? null : (device.memberId ?? device.claimedMemberId);
27
28
  if (owner)
28
- live.add(owner.toString('hex'));
29
+ live.add(b4a.toHex(owner));
29
30
  }
30
31
  return live;
31
32
  }
32
- export function createMembersApi(current, state = null) {
33
+ export function createMembersApi(pool, self, state = null) {
33
34
  const mustGetMember = async (reader, id) => {
34
35
  const member = await reader.get(MEMBERS, { id });
35
36
  if (!member)
36
- throw new Error(`member not found: ${id.toString('hex')}`);
37
+ throw new Error(`member not found: ${b4a.toHex(id)}`);
37
38
  return member;
38
39
  };
39
40
  const list = async (mesh) => {
@@ -42,7 +43,7 @@ export function createMembersApi(current, state = null) {
42
43
  const live = await liveMemberIds(snap);
43
44
  const members = await snap.find(MEMBERS).toArray();
44
45
  return {
45
- members: members.map((member) => toEngineMember(member, !live.has(member.id.toString('hex'))))
46
+ members: members.map((member) => toEngineMember(member, !live.has(b4a.toHex(member.id))))
46
47
  };
47
48
  }
48
49
  finally {
@@ -53,32 +54,38 @@ export function createMembersApi(current, state = null) {
53
54
  const snap = mesh.view.snapshot();
54
55
  try {
55
56
  const member = await mustGetMember(snap, id);
56
- return toEngineMember(member, !(await liveMemberIds(snap)).has(id.toString('hex')));
57
+ return toEngineMember(member, !(await liveMemberIds(snap)).has(b4a.toHex(id)));
57
58
  }
58
59
  finally {
59
60
  await snap.close();
60
61
  }
61
62
  };
62
63
  return {
63
- listMembers: async (request) => list(await requireMesh(current, request?.meshId)),
64
- membersWatch: meshWatchable('membersWatch', current, (_request, mesh) => list(mesh)),
65
- updateMember: async ({ id, name, meshId }) => {
66
- const mesh = await requireMesh(current, meshId);
67
- const trimmed = name.trim();
64
+ listMembers: async (request) => list(await requireMesh(pool, request.meshId)),
65
+ membersWatch: meshWatchable('membersWatch', pool, (_request, mesh) => list(mesh)),
66
+ updateMember: async ({ config }) => {
67
+ const trimmed = config.name.trim();
68
68
  if (!trimmed)
69
69
  throw new Error('member name must not be empty');
70
- const member = await mustGetMember(mesh.view, id);
70
+ const { meshId } = await self.account();
71
+ if (!meshId)
72
+ throw new Error('no account to rename the member in');
73
+ const mesh = await requireMesh(pool, meshId);
71
74
  if (!mesh.ourMemberId)
72
- await mesh.refreshOurMember();
73
- if (mesh.ourMemberId?.equals(id))
74
- await state?.saveDisplayName(trimmed);
75
+ await resolveOurMember(mesh);
76
+ const id = mesh.ourMemberId;
77
+ if (!id)
78
+ throw new Error('this device is in no member of its account');
79
+ const member = await mustGetMember(mesh.view, id);
80
+ const namedAt = Math.max(Date.now(), member.updatedAt + 1);
81
+ await state?.saveDisplayName(trimmed, namedAt);
75
82
  await mesh.dispatch('update-member', {
76
- member: { ...member, name: trimmed, updatedAt: Date.now() }
83
+ member: { ...member, name: trimmed, updatedAt: namedAt }
77
84
  });
78
85
  return readMember(mesh, id);
79
86
  },
80
- removeMember: async ({ id, meshId }) => {
81
- const mesh = await requireMesh(current, meshId);
87
+ removeMember: async ({ memberId: id, meshId }) => {
88
+ const mesh = await requireMesh(pool, meshId);
82
89
  if (!mesh.ourMemberId)
83
90
  await resolveOurMember(mesh);
84
91
  if (!mesh.ourMemberId)
@@ -1,4 +1,4 @@
1
- import type { AssistantArchivedMeshContents, AssistantArchivedMeshList, AssistantArchivedMeshMigration, AssistantMeshList, AssistantMeshStatus } from '../../spec/hyperschema/types.d.ts';
1
+ import type { AssistantAccount, AssistantArchivedMeshContents, AssistantArchivedMeshList, AssistantArchivedMeshMigration, AssistantMeshList, AssistantMeshStatus } from '../../spec/hyperschema/types.d.ts';
2
2
  import type { CapabilityHandlers } from '../../spec/capabilities.d.ts';
3
3
  export interface MeshInviteResult {
4
4
  readonly invite?: string;
@@ -9,14 +9,14 @@ export interface MeshStatusSource {
9
9
  watch(listener: () => void): void;
10
10
  unwatch(listener: () => void): void;
11
11
  snapshot(): AssistantMeshStatus;
12
- leave(): Promise<void>;
12
+ leave(meshId: string): Promise<void>;
13
13
  acknowledgeKicked(): void;
14
14
  join(invite: string): Promise<void>;
15
15
  cancelJoin(): void;
16
16
  invite(member?: boolean, meshId?: string): Promise<MeshInviteResult>;
17
17
  list(): Promise<AssistantMeshList>;
18
+ account(): Promise<AssistantAccount>;
18
19
  open(meshId: string): Promise<void>;
19
- select(meshId: string): Promise<void>;
20
20
  close(meshId: string): Promise<void>;
21
21
  label(meshId: string, label: string): Promise<void>;
22
22
  createRoom(opts?: {
@@ -29,6 +29,5 @@ export interface MeshStatusSource {
29
29
  publishRecovery(phrase: string): Promise<void>;
30
30
  recover(phrase: string, timeout?: number): Promise<void>;
31
31
  displayName(): Promise<string | null>;
32
- setDisplayName(name: string): Promise<void>;
33
32
  }
34
- export declare function createMeshApi(status: MeshStatusSource): Pick<CapabilityHandlers, 'meshStatusWatch' | 'listMeshes' | 'meshesWatch' | 'openMesh' | 'selectMesh' | 'closeMesh' | 'leaveMesh' | 'acknowledgeKicked' | 'joinMesh' | 'cancelMeshJoin' | 'meshInvite' | 'setMeshLabel' | 'createRoom' | 'listArchivedMeshes' | 'archivedMeshContents' | 'migrateArchivedMesh' | 'accountRecoverable' | 'recoveryPublish' | 'recoverAccount' | 'displayName' | 'setDisplayName'>;
33
+ export declare function createMeshApi(status: MeshStatusSource, updateMember: CapabilityHandlers['updateMember']): Pick<CapabilityHandlers, 'meshStatusWatch' | 'listMeshes' | 'meshesWatch' | 'account' | 'accountWatch' | 'openMesh' | 'closeMesh' | 'leaveMesh' | 'acknowledgeKicked' | 'joinMesh' | 'cancelMeshJoin' | 'meshInvite' | 'setMeshLabel' | 'createRoom' | 'listArchivedMeshes' | 'archivedMeshContents' | 'migrateArchivedMesh' | 'accountRecoverable' | 'recoveryPublish' | 'recoverAccount' | 'displayName' | 'setDisplayName'>;
@@ -1,23 +1,21 @@
1
1
  import { watchable } from './watchable.js';
2
- export function createMeshApi(status) {
2
+ export function createMeshApi(status, updateMember) {
3
3
  return {
4
4
  meshStatusWatch: watchable('meshStatusWatch', () => status, async () => status.snapshot()),
5
5
  listMeshes: () => status.list(),
6
6
  meshesWatch: watchable('meshesWatch', () => status, () => status.list()),
7
+ account: () => status.account(),
8
+ accountWatch: watchable('accountWatch', () => status, () => status.account()),
7
9
  openMesh: async ({ meshId }) => {
8
10
  await status.open(meshId);
9
11
  return { ok: true };
10
12
  },
11
- selectMesh: async ({ meshId }) => {
12
- await status.select(meshId);
13
- return { ok: true };
14
- },
15
13
  closeMesh: async ({ meshId }) => {
16
14
  await status.close(meshId);
17
15
  return { ok: true };
18
16
  },
19
- leaveMesh: async () => {
20
- await status.leave();
17
+ leaveMesh: async ({ meshId }) => {
18
+ await status.leave(meshId);
21
19
  return { ok: true };
22
20
  },
23
21
  acknowledgeKicked: async () => {
@@ -38,7 +36,7 @@ export function createMeshApi(status) {
38
36
  return { ok: true };
39
37
  },
40
38
  createRoom: async (request) => ({
41
- meshId: await status.createRoom({ compute: request?.compute })
39
+ meshId: await status.createRoom({ compute: request?.config?.compute })
42
40
  }),
43
41
  listArchivedMeshes: () => status.listArchived(),
44
42
  archivedMeshContents: ({ meshId }) => status.archivedContents(meshId),
@@ -58,7 +56,7 @@ export function createMeshApi(status) {
58
56
  name: await status.displayName()
59
57
  }),
60
58
  setDisplayName: async ({ name }) => {
61
- await status.setDisplayName(name ?? '');
59
+ await updateMember({ config: { name: name ?? '' } });
62
60
  return { ok: true };
63
61
  }
64
62
  };
@@ -1,21 +1,10 @@
1
1
  import type { CapabilityHandlers } from '../../spec/capabilities.d.ts';
2
2
  import type { openLocalStore } from '../core/local/index.ts';
3
- import { type CurrentMesh } from './current-mesh.ts';
3
+ import { type MeshPool } from './current-mesh.ts';
4
4
  type LocalStore = Awaited<ReturnType<typeof openLocalStore>>;
5
5
  type NotificationCapabilities = Pick<CapabilityHandlers, 'notificationsWatch' | 'ackNotification'>;
6
- export interface NotificationLifetime {
7
- once(event: 'close', listener: () => void): unknown;
8
- off(event: 'close', listener: () => void): unknown;
9
- readonly closing: unknown;
10
- readonly closed: boolean;
11
- }
12
6
  interface NotificationOptions {
13
7
  readonly deviceId?: Buffer | null;
14
- readonly lifetime?: NotificationLifetime;
15
- readonly changes?: {
16
- watch(listener: () => void): void;
17
- unwatch(listener: () => void): void;
18
- };
19
8
  }
20
- export declare function createNotificationsApi(current: CurrentMesh, local: LocalStore, options?: NotificationOptions): NotificationCapabilities;
9
+ export declare function createNotificationsApi(pool: MeshPool, local: LocalStore, options?: NotificationOptions): NotificationCapabilities;
21
10
  export {};
@@ -1,10 +1,10 @@
1
1
  import { deriveNotifications } from '../core/notification.js';
2
2
  import { requireMesh } from './current-mesh.js';
3
3
  import { watchable } from './watchable.js';
4
- export function createNotificationsApi(current, local, options = {}) {
4
+ export function createNotificationsApi(pool, local, options = {}) {
5
5
  return {
6
- notificationsWatch: watchable('notificationsWatch', () => notificationSource(current, local, options), (request) => notificationSnapshot(current, local, request?.limit, options.deviceId)),
7
- ackNotification: async ({ chatId, seq, notificationId }) => {
6
+ notificationsWatch: watchable('notificationsWatch', async (request) => notificationSource(await requireMesh(pool, request.meshId), local), (request, source) => notificationSnapshot(source.mesh, local, request.limit, options.deviceId)),
7
+ ackNotification: async ({ chatId, seq, notificationId, meshId }) => {
8
8
  if (notificationId) {
9
9
  if ((chatId !== undefined && chatId !== null) || (seq ?? 0) !== 0) {
10
10
  throw new Error('notification acknowledgement must select one source');
@@ -15,79 +15,47 @@ export function createNotificationsApi(current, local, options = {}) {
15
15
  if (!chatId || seq === undefined || seq === null) {
16
16
  throw new Error('chat acknowledgement requires chatId and seq');
17
17
  }
18
- await requireMesh(current);
18
+ await requireMesh(pool, meshId);
19
19
  await local.ackChatNotify(chatId, seq);
20
20
  }
21
21
  return { ok: true };
22
22
  }
23
23
  };
24
24
  }
25
- function notificationSource(current, local, options) {
26
- let mesh = null;
27
- let generation = 0;
28
- let watching = false;
29
- let listener = null;
30
- const notify = () => listener?.();
31
- const detach = () => {
32
- mesh?.unwatch(notify);
33
- mesh?.off('close', changed);
34
- mesh = null;
35
- };
36
- const changed = () => {
37
- const version = ++generation;
38
- detach();
39
- notify();
40
- void Promise.resolve(current())
41
- .then((next) => {
42
- if (!watching || version !== generation || next?.closing || next?.closed)
43
- return;
44
- mesh = next;
45
- mesh?.watch(notify);
46
- mesh?.once('close', changed);
47
- notify();
48
- })
49
- .catch(notify);
50
- };
25
+ function notificationSource(mesh, local) {
51
26
  return {
52
- watch(onChange) {
53
- listener = onChange;
54
- watching = true;
55
- local.watch(notify);
56
- options.changes?.watch(changed);
57
- changed();
27
+ mesh,
28
+ watch(listener) {
29
+ mesh.watch(listener);
30
+ local.watch(listener);
58
31
  },
59
- unwatch() {
60
- watching = false;
61
- generation++;
62
- detach();
63
- local.unwatch(notify);
64
- options.changes?.unwatch(changed);
65
- listener = null;
32
+ unwatch(listener) {
33
+ mesh.unwatch(listener);
34
+ local.unwatch(listener);
66
35
  },
67
- once: (event, onClose) => options.lifetime?.once(event, onClose),
68
- off: (event, onClose) => options.lifetime?.off(event, onClose),
36
+ once: (event, listener) => mesh.once(event, listener),
37
+ off: (event, listener) => mesh.off(event, listener),
69
38
  get closing() {
70
- return options.lifetime?.closing;
39
+ return mesh.closing;
71
40
  },
72
41
  get closed() {
73
- return options.lifetime?.closed ?? false;
42
+ return mesh.closed;
74
43
  }
75
44
  };
76
45
  }
77
- async function notificationSnapshot(current, local, requestedLimit, deviceId) {
78
- const mesh = await current();
46
+ async function notificationSnapshot(mesh, local, requestedLimit, deviceId) {
79
47
  let chats = { notifications: [] };
80
- if (mesh && !mesh.closing && !mesh.closed) {
48
+ if (!mesh.closing && !mesh.closed) {
81
49
  try {
82
50
  chats = await deriveNotifications(mesh, local, Number.MAX_SAFE_INTEGER, deviceId);
83
51
  }
84
52
  catch (error) {
85
- if (mesh === (await current()) && !mesh.closing && !mesh.closed)
53
+ if (!mesh.closing && !mesh.closed)
86
54
  throw error;
87
55
  }
88
56
  }
89
57
  const models = await local.getModelNotifications();
90
- if (mesh !== (await current()) || mesh?.closing || mesh?.closed)
58
+ if (mesh.closing || mesh.closed)
91
59
  chats = { notifications: [] };
92
60
  const notifications = [
93
61
  ...(chats.notifications ?? []),
@@ -2,6 +2,6 @@ import '../logger.ts';
2
2
  import type { CapabilityHandlers } from '../../spec/capabilities.d.ts';
3
3
  import type { QvacAgent } from '../../spec/mesh/hyperschema/types.d.ts';
4
4
  import { type IndexingEmbedder, type VectorIndex } from '../core/files/index.ts';
5
- import { type CurrentMesh } from './current-mesh.ts';
5
+ import { type MeshPool } from './current-mesh.ts';
6
6
  export declare const MAX_RAG_SEARCH_LIMIT = 20;
7
- export declare function createRagApi(current: CurrentMesh, index: () => VectorIndex | null, embedder: () => IndexingEmbedder | null, effectiveCtxSize?: ((agent: QvacAgent | null) => Promise<number>) | null): Pick<CapabilityHandlers, 'ragSearch'>;
7
+ export declare function createRagApi(pool: MeshPool, index: (meshId: string) => VectorIndex | null, embedder: (meshId: string) => IndexingEmbedder | null, effectiveCtxSize?: ((agent: QvacAgent | null) => Promise<number>) | null): Pick<CapabilityHandlers, 'ragSearch'>;
@@ -11,12 +11,12 @@ function clampLimit(limit) {
11
11
  return DEFAULT_RAG_SEARCH_LIMIT;
12
12
  return Math.min(Math.max(1, Math.floor(limit)), MAX_RAG_SEARCH_LIMIT);
13
13
  }
14
- export function createRagApi(current, index, embedder, effectiveCtxSize = null) {
14
+ export function createRagApi(pool, index, embedder, effectiveCtxSize = null) {
15
15
  return {
16
16
  ragSearch: async ({ chatId, query, mode, limit, attachmentIds, meshId }) => {
17
17
  let pendingFiles = [];
18
18
  const respond = (overrides) => response({ pendingFiles, ...overrides });
19
- const mesh = await requireMesh(current, meshId);
19
+ const mesh = await requireMesh(pool, meshId);
20
20
  const chat = await getChat(mesh, chatId);
21
21
  const toolMode = mode === 'tool';
22
22
  if (!chat)
@@ -61,8 +61,8 @@ export function createRagApi(current, index, embedder, effectiveCtxSize = null)
61
61
  scopeRows = rows.filter((row) => scopeIds.has(row.id));
62
62
  }
63
63
  const hasKnowledge = rows.length > 0;
64
- const vectorIndex = index();
65
- const embed = embedder();
64
+ const vectorIndex = index(meshId);
65
+ const embed = embedder(meshId);
66
66
  if (!vectorIndex || !embed) {
67
67
  return respond({ hasKnowledge, errorMessage: 'knowledge index unavailable on this device' });
68
68
  }
@@ -0,0 +1,11 @@
1
+ import type { Bounds } from '../core/range.ts';
2
+ type WireBounds = {
3
+ gt?: number | null;
4
+ gte?: number | null;
5
+ lt?: number | null;
6
+ lte?: number | null;
7
+ reverse?: boolean | null;
8
+ limit?: number | null;
9
+ };
10
+ export declare function bounds({ gt, gte, lt, lte, reverse, limit }: WireBounds): Bounds;
11
+ export {};
@@ -0,0 +1,10 @@
1
+ export function bounds({ gt, gte, lt, lte, reverse, limit }) {
2
+ return {
3
+ gt: gt || undefined,
4
+ gte: gte || undefined,
5
+ lt: lt || undefined,
6
+ lte: lte || undefined,
7
+ reverse: reverse === true,
8
+ limit: limit || undefined
9
+ };
10
+ }
@@ -1,3 +1,3 @@
1
1
  import type { CapabilityHandlers } from '../../spec/capabilities.d.ts';
2
- import { type CurrentMesh } from './current-mesh.ts';
3
- export declare function createSyncApi(current: CurrentMesh): Pick<CapabilityHandlers, 'syncStatusWatch'>;
2
+ import { type MeshPool } from './current-mesh.ts';
3
+ export declare function createSyncApi(pool: MeshPool): Pick<CapabilityHandlers, 'syncStatusWatch'>;
@@ -1,7 +1,7 @@
1
- import { selectionPin } from './current-mesh.js';
1
+ import { requireMesh } from './current-mesh.js';
2
2
  import { watchable } from './watchable.js';
3
- export function createSyncApi(current) {
3
+ export function createSyncApi(pool) {
4
4
  return {
5
- syncStatusWatch: watchable('syncStatusWatch', async () => (await current())?.syncActivity ?? null, (_request, activity) => activity.snapshot(), () => selectionPin(current))
5
+ syncStatusWatch: watchable('syncStatusWatch', async (request) => (await requireMesh(pool, request.meshId)).syncActivity ?? null, (_request, activity) => activity.snapshot())
6
6
  };
7
7
  }
@@ -1,5 +1,5 @@
1
1
  import type { CapabilityHandlers } from '../../spec/capabilities.d.ts';
2
- import { type CurrentMesh } from './current-mesh.ts';
2
+ import { type MeshPool } from './current-mesh.ts';
3
3
  type ToolActivityCapabilities = Pick<CapabilityHandlers, 'listToolActivity' | 'toolActivityWatch' | 'recordToolActivity'>;
4
- export declare function createToolActivityApi(current: CurrentMesh, deviceId: Buffer | null): ToolActivityCapabilities;
4
+ export declare function createToolActivityApi(pool: MeshPool, deviceId: Buffer | null): ToolActivityCapabilities;
5
5
  export {};
@@ -1,6 +1,7 @@
1
1
  import { listToolActivity, recordToolActivity } from '../core/tool-activity.js';
2
- import { requireMesh, selectionPin } from './current-mesh.js';
3
- import { watchable } from './watchable.js';
2
+ import { meshWatchable, requireMesh } from './current-mesh.js';
3
+ import { bounds } from './range.js';
4
+ import b4a from 'b4a';
4
5
  const DEFAULT_LIMIT = 200;
5
6
  const MAX_LIMIT = 1000;
6
7
  const DECISIONS = new Set(['auto', 'allowed', 'denied', 'skip-all', 'blocked']);
@@ -11,7 +12,7 @@ function toEntry(row) {
11
12
  return {
12
13
  id: row.id,
13
14
  agentId: row.agentId,
14
- deviceId: row.originDeviceId.toString('hex'),
15
+ deviceId: b4a.toHex(row.originDeviceId),
15
16
  chatId: row.chatId ?? undefined,
16
17
  runId: row.runId ?? undefined,
17
18
  toolName: row.toolName,
@@ -23,20 +24,20 @@ function toEntry(row) {
23
24
  seq: row.seq ?? 0
24
25
  };
25
26
  }
26
- export function createToolActivityApi(current, deviceId) {
27
- const query = async ({ agentId, limit, beforeSeq }, mesh) => ({
27
+ export function createToolActivityApi(pool, deviceId) {
28
+ const query = async ({ agentId, ...input }, mesh) => ({
28
29
  activities: (await listToolActivity(mesh, agentId, {
29
- limit: Math.min(limit || DEFAULT_LIMIT, MAX_LIMIT),
30
- beforeSeq: beforeSeq || undefined
30
+ ...bounds(input),
31
+ limit: Math.min(input.limit || DEFAULT_LIMIT, MAX_LIMIT)
31
32
  })).map(toEntry)
32
33
  });
33
34
  return {
34
- listToolActivity: async (request) => query(request, await requireMesh(current)),
35
- toolActivityWatch: watchable('toolActivityWatch', () => requireMesh(current), query, () => selectionPin(current)),
35
+ listToolActivity: async (request) => query(request, await requireMesh(pool, request.meshId)),
36
+ toolActivityWatch: meshWatchable('toolActivityWatch', pool, query),
36
37
  recordToolActivity: async (request) => {
37
38
  if (!deviceId)
38
39
  throw new Error('cannot record tool activity without a device id');
39
- return recordToolActivity(await requireMesh(current, request.meshId), {
40
+ return recordToolActivity(await requireMesh(pool, request.meshId), {
40
41
  agentId: request.agentId,
41
42
  originDeviceId: deviceId,
42
43
  toolName: request.toolName,
@@ -1,6 +1,6 @@
1
1
  import type { CapabilityHandlers } from '../../spec/capabilities.d.ts';
2
2
  import { getToolConfigs } from '../core/tool-configs.ts';
3
- import { type CurrentMesh } from './current-mesh.ts';
3
+ import { type MeshPool } from './current-mesh.ts';
4
4
  type ToolConfigsCapabilities = Pick<CapabilityHandlers, 'setToolConfigs' | 'deleteToolConfigs' | 'listToolConfigs' | 'toolConfigsWatch'>;
5
- export declare function createToolConfigsApi(current: CurrentMesh): ToolConfigsCapabilities;
5
+ export declare function createToolConfigsApi(pool: MeshPool): ToolConfigsCapabilities;
6
6
  export { getToolConfigs };
@@ -1,6 +1,5 @@
1
1
  import { deleteToolConfigs, getToolConfigs, listToolConfigs, setToolConfigs } from '../core/tool-configs.js';
2
- import { requireMesh, selectionPin } from './current-mesh.js';
3
- import { watchable } from './watchable.js';
2
+ import { meshWatchable, requireMesh } from './current-mesh.js';
4
3
  function isRecord(value) {
5
4
  return typeof value === 'object' && value !== null && !Array.isArray(value);
6
5
  }
@@ -9,19 +8,19 @@ function ensureSettingsPayload(value) {
9
8
  throw new Error('tool configs must be a plain object');
10
9
  return value;
11
10
  }
12
- export function createToolConfigsApi(current) {
11
+ export function createToolConfigsApi(pool) {
13
12
  const query = async ({ agentId }, mesh) => ({
14
13
  configs: await listToolConfigs(mesh, agentId)
15
14
  });
16
15
  return {
17
- setToolConfigs: async ({ agentId, toolName, settings }) => setToolConfigs(await requireMesh(current), {
16
+ setToolConfigs: async ({ agentId, toolName, settings, meshId }) => setToolConfigs(await requireMesh(pool, meshId), {
18
17
  agentId,
19
18
  toolName,
20
19
  settings: ensureSettingsPayload(settings)
21
20
  }),
22
- deleteToolConfigs: async ({ agentId, toolName }) => deleteToolConfigs(await requireMesh(current), agentId, toolName),
23
- listToolConfigs: async (request) => query(request, await requireMesh(current, request.meshId)),
24
- toolConfigsWatch: watchable('toolConfigsWatch', (request) => requireMesh(current, request?.meshId), query, (request) => selectionPin(current, request?.meshId))
21
+ deleteToolConfigs: async ({ agentId, toolName, meshId }) => deleteToolConfigs(await requireMesh(pool, meshId), agentId, toolName),
22
+ listToolConfigs: async (request) => query(request, await requireMesh(pool, request.meshId)),
23
+ toolConfigsWatch: meshWatchable('toolConfigsWatch', pool, query)
25
24
  };
26
25
  }
27
26
  export { getToolConfigs };
@@ -0,0 +1,9 @@
1
+ export declare const UPLOAD_NAMES_NO_MESH = "an upload must name its mesh on its first frame";
2
+ export type UploadFrames<Frame> = AsyncIterable<Frame> | {
3
+ writeStream?: unknown;
4
+ on: (...args: never[]) => void;
5
+ };
6
+ export declare function openUpload<Frame>(frames: UploadFrames<Frame>): Promise<{
7
+ first: Frame;
8
+ rest: AsyncIterable<Frame>;
9
+ } | null>;
@@ -0,0 +1,17 @@
1
+ import { toAsyncIterable } from '../core/async-iterable.js';
2
+ export const UPLOAD_NAMES_NO_MESH = 'an upload must name its mesh on its first frame';
3
+ export async function openUpload(frames) {
4
+ const iterator = toAsyncIterable(frames)[Symbol.asyncIterator]();
5
+ const first = await iterator.next();
6
+ if (first.done)
7
+ return null;
8
+ const rest = replay(first.value, iterator);
9
+ if ('writeStream' in frames) {
10
+ Object.assign(rest, { writeStream: frames.writeStream });
11
+ }
12
+ return { first: first.value, rest };
13
+ }
14
+ async function* replay(first, rest) {
15
+ yield first;
16
+ yield* { [Symbol.asyncIterator]: () => rest };
17
+ }
@@ -1,10 +1,5 @@
1
1
  import { Readable } from 'streamx';
2
2
  import '../logger.ts';
3
- export interface WatchPin {
4
- stale(): boolean;
5
- watch(listener: () => void): void;
6
- unwatch(listener: () => void): void;
7
- }
8
3
  interface WatchableStore {
9
4
  watch(listener: () => void): void;
10
5
  unwatch(listener: () => void): void;
@@ -13,5 +8,5 @@ interface WatchableStore {
13
8
  closing?: unknown;
14
9
  closed?: boolean;
15
10
  }
16
- export declare function watchable<TRequest, TResult, TStore extends WatchableStore = WatchableStore>(name: string, storeOf: (request: TRequest) => TStore | null | Promise<TStore | null>, query: (request: TRequest, store: TStore) => Promise<TResult>, pinOf?: (request: TRequest) => WatchPin | null): (request: TRequest) => Readable & AsyncIterable<TResult>;
11
+ export declare function watchable<TRequest, TResult, TStore extends WatchableStore = WatchableStore>(name: string, storeOf: (request: TRequest) => TStore | null | Promise<TStore | null>, query: (request: TRequest, store: TStore) => Promise<TResult>, changes?: WatchableStore): (request: TRequest) => Readable & AsyncIterable<TResult>;
17
12
  export {};
@@ -24,9 +24,8 @@ function snapshotEquals(a, b) {
24
24
  function isRecord(value) {
25
25
  return typeof value === 'object' && value !== null;
26
26
  }
27
- export function watchable(name, storeOf, query, pinOf) {
27
+ export function watchable(name, storeOf, query, changes) {
28
28
  return (request) => {
29
- const pin = pinOf?.(request) ?? null;
30
29
  const resolved = storeOf(request);
31
30
  const pending = resolved instanceof Promise ? resolved.catch(noop) : null;
32
31
  let store = resolved instanceof Promise ? null : resolved;
@@ -57,22 +56,14 @@ export function watchable(name, storeOf, query, pinOf) {
57
56
  wake?.resolve();
58
57
  wake = null;
59
58
  };
60
- const onPinMove = () => {
61
- if (pin?.stale())
62
- onStoreClose();
63
- };
64
- const storeGone = () => store === null ||
65
- ended ||
66
- Boolean(store.closed) ||
67
- Boolean(store.closing) ||
68
- Boolean(pin?.stale());
59
+ const storeGone = () => store === null || ended || Boolean(store.closed) || Boolean(store.closing);
69
60
  const stream = new Readable({
70
61
  async open(cb) {
71
62
  if (pending)
72
63
  store = (await pending) ?? null;
73
64
  store?.watch(onChange);
65
+ changes?.watch(onChange);
74
66
  store?.once?.('close', onStoreClose);
75
- pin?.watch(onPinMove);
76
67
  cb(null);
77
68
  },
78
69
  async read(cb) {
@@ -121,8 +112,8 @@ export function watchable(name, storeOf, query, pinOf) {
121
112
  destroy(cb) {
122
113
  reportChurn(true);
123
114
  store?.unwatch(onChange);
115
+ changes?.unwatch(onChange);
124
116
  store?.off?.('close', onStoreClose);
125
- pin?.unwatch(onPinMove);
126
117
  cb(null);
127
118
  }
128
119
  });
@@ -1,6 +1,6 @@
1
1
  import type { AbortSignal } from 'bare-abort-controller';
2
2
  import type { AssistantChunk } from '../../spec/hyperschema/types.d.ts';
3
- import type { Capabilities } from '../api/index.ts';
3
+ import type { ScopedCapabilities } from '../mesh-scoped-engine.ts';
4
4
  import type { ChatMessage } from './message.ts';
5
5
  export declare const TERMINAL_STATES: Set<string>;
6
6
  export declare const HISTORY_TYPES: AssistantChunk['type'][];
@@ -9,13 +9,13 @@ export interface StaleToolRuns {
9
9
  runIds: Set<string>;
10
10
  questionChunkIds: Set<string>;
11
11
  }
12
- export declare function listHistoryChunks(engine: Pick<Capabilities, 'listChunks'>, chatId: string): Promise<AssistantChunk[]>;
12
+ export declare function listHistoryChunks(engine: Pick<ScopedCapabilities, 'listChunks'>, chatId: string): Promise<AssistantChunk[]>;
13
13
  export declare function latestAttemptStarts(chunks: ReadonlyArray<AssistantChunk>): Map<string, number>;
14
14
  export declare function beforeLatestAttempt(chunk: AssistantChunk, starts: Map<string, number>): boolean;
15
15
  export interface CompactOptions {
16
16
  readonly signal?: AbortSignal;
17
17
  readonly onFold?: () => Promise<void> | void;
18
- readonly meshId?: string;
18
+ readonly meshId: string;
19
19
  }
20
20
  export type CompactionTrigger = 'before-run' | 'overflow';
21
21
  export interface CompactResult {
@@ -1,5 +1,6 @@
1
1
  import { Client } from './client.js';
2
2
  import { duplexPair } from '@qvac/harness/transport';
3
+ import b4a from 'b4a';
3
4
  export class AssistantClient extends Client {
4
5
  _inline;
5
6
  constructor({ sidecar: spawnSidecar = true, storagePath, device, meshSeed, meshKey, bootstrapNodes, entry, ...engineOptions }) {
@@ -11,8 +12,8 @@ export class AssistantClient extends Client {
11
12
  device?.name ?? '',
12
13
  device?.capabilityProfile ?? '',
13
14
  device?.recommendedModelName ?? '',
14
- meshSeed?.toString('hex') ?? '',
15
- meshKey?.toString('hex') ?? '',
15
+ meshSeed ? b4a.toHex(meshSeed) : '',
16
+ meshKey ? b4a.toHex(meshKey) : '',
16
17
  (bootstrapNodes ?? []).map((node) => `${node.host}:${node.port}`).join(',')
17
18
  ];
18
19
  const transport = spawnSidecar
@@ -77,7 +77,7 @@ export function assistantTree(opts) {
77
77
  offDeleteModel = core.registerDeleteModel(harnessDeleteModel(harness));
78
78
  offClearKvCache = core.registerClearKvCache(harnessClearKvCache(harness));
79
79
  offDeleteChatKvCache = core.registerDeleteChatKvCache((chatId) => assistant.deleteChatKvCache(chatId));
80
- offCompactChat = core.registerCompactChat((chatId) => assistant.compactChat(chatId));
80
+ offCompactChat = core.registerCompactChat((chatId, meshId) => assistant.compactChat(chatId, { meshId }));
81
81
  offModelCatalogWatch = core.registerModelCatalogWatch(() => assistant.modelCatalogWatch());
82
82
  offCustomModels = startCustomModelPusher(harness, core.local, logger);
83
83
  offLoanableHarness = core.registerLoanableHarness((stream) => serveHarness(stream, harness));