@qvac/core 0.3.4 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/README.md +19 -17
  2. package/dist-lib/lib/api/agents.d.ts +3 -3
  3. package/dist-lib/lib/api/agents.js +31 -20
  4. package/dist-lib/lib/api/approval-rules.d.ts +2 -2
  5. package/dist-lib/lib/api/approval-rules.js +2 -2
  6. package/dist-lib/lib/api/attachments.d.ts +2 -2
  7. package/dist-lib/lib/api/attachments.js +14 -25
  8. package/dist-lib/lib/api/chat-groups.d.ts +2 -2
  9. package/dist-lib/lib/api/chat-groups.js +9 -9
  10. package/dist-lib/lib/api/chat.d.ts +4 -2
  11. package/dist-lib/lib/api/chat.js +18 -18
  12. package/dist-lib/lib/api/chunks.d.ts +2 -2
  13. package/dist-lib/lib/api/chunks.js +27 -36
  14. package/dist-lib/lib/api/current-mesh.d.ts +7 -15
  15. package/dist-lib/lib/api/current-mesh.js +7 -22
  16. package/dist-lib/lib/api/devices.d.ts +4 -3
  17. package/dist-lib/lib/api/devices.js +18 -18
  18. package/dist-lib/lib/api/execution.d.ts +2 -2
  19. package/dist-lib/lib/api/execution.js +6 -6
  20. package/dist-lib/lib/api/files.d.ts +2 -2
  21. package/dist-lib/lib/api/files.js +4 -4
  22. package/dist-lib/lib/api/index.d.ts +12 -11
  23. package/dist-lib/lib/api/index.js +15 -13
  24. package/dist-lib/lib/api/inference-calls.d.ts +1 -1
  25. package/dist-lib/lib/api/inference-calls.js +2 -2
  26. package/dist-lib/lib/api/knowledge.d.ts +2 -2
  27. package/dist-lib/lib/api/knowledge.js +22 -11
  28. package/dist-lib/lib/api/local-files.d.ts +3 -0
  29. package/dist-lib/lib/api/local-files.js +23 -0
  30. package/dist-lib/lib/api/members.d.ts +6 -2
  31. package/dist-lib/lib/api/members.js +24 -17
  32. package/dist-lib/lib/api/mesh.d.ts +4 -5
  33. package/dist-lib/lib/api/mesh.js +7 -9
  34. package/dist-lib/lib/api/notifications.d.ts +2 -13
  35. package/dist-lib/lib/api/notifications.js +20 -52
  36. package/dist-lib/lib/api/rag.d.ts +2 -2
  37. package/dist-lib/lib/api/rag.js +4 -4
  38. package/dist-lib/lib/api/range.d.ts +11 -0
  39. package/dist-lib/lib/api/range.js +10 -0
  40. package/dist-lib/lib/api/sync.d.ts +2 -2
  41. package/dist-lib/lib/api/sync.js +3 -3
  42. package/dist-lib/lib/api/tool-activity.d.ts +2 -2
  43. package/dist-lib/lib/api/tool-activity.js +11 -10
  44. package/dist-lib/lib/api/tool-configs.d.ts +2 -2
  45. package/dist-lib/lib/api/tool-configs.js +6 -7
  46. package/dist-lib/lib/api/upload-frames.d.ts +9 -0
  47. package/dist-lib/lib/api/upload-frames.js +17 -0
  48. package/dist-lib/lib/api/watchable.d.ts +1 -6
  49. package/dist-lib/lib/api/watchable.js +4 -13
  50. package/dist-lib/lib/assistant/history.d.ts +3 -3
  51. package/dist-lib/lib/assistant-client.js +3 -2
  52. package/dist-lib/lib/assistant-tree.js +1 -1
  53. package/dist-lib/lib/assistant.d.ts +16 -14
  54. package/dist-lib/lib/assistant.js +166 -137
  55. package/dist-lib/lib/collabora/convert.js +1 -1
  56. package/dist-lib/lib/core/agent.d.ts +5 -7
  57. package/dist-lib/lib/core/agent.js +26 -6
  58. package/dist-lib/lib/core/archived-mesh.js +1 -0
  59. package/dist-lib/lib/core/chat-order.d.ts +20 -0
  60. package/dist-lib/lib/core/chat-order.js +96 -0
  61. package/dist-lib/lib/core/chat.d.ts +0 -5
  62. package/dist-lib/lib/core/chat.js +1 -3
  63. package/dist-lib/lib/core/chunk.d.ts +7 -14
  64. package/dist-lib/lib/core/chunk.js +17 -35
  65. package/dist-lib/lib/core/contract/agents.js +8 -0
  66. package/dist-lib/lib/core/contract/compute.d.ts +1 -1
  67. package/dist-lib/lib/core/contract/compute.js +1 -0
  68. package/dist-lib/lib/core/contract/joined-meshes.js +4 -3
  69. package/dist-lib/lib/core/contract/members.js +4 -3
  70. package/dist-lib/lib/core/contract/writers.js +5 -4
  71. package/dist-lib/lib/core/departures.js +5 -4
  72. package/dist-lib/lib/core/device-invites.js +2 -1
  73. package/dist-lib/lib/core/files/attachments.d.ts +8 -1
  74. package/dist-lib/lib/core/files/index.d.ts +4 -4
  75. package/dist-lib/lib/core/files/index.js +18 -8
  76. package/dist-lib/lib/core/files/local-index.d.ts +16 -0
  77. package/dist-lib/lib/core/files/local-index.js +38 -0
  78. package/dist-lib/lib/core/files/processing/document.js +2 -1
  79. package/dist-lib/lib/core/files/processing/ownership.js +6 -3
  80. package/dist-lib/lib/core/files/records/chunks.js +1 -0
  81. package/dist-lib/lib/core/files/records/reclaim.js +1 -0
  82. package/dist-lib/lib/core/files/records/routing.js +2 -1
  83. package/dist-lib/lib/core/files/store/blob.d.ts +1 -1
  84. package/dist-lib/lib/core/files/store/blob.js +6 -3
  85. package/dist-lib/lib/core/files/store/index.d.ts +1 -1
  86. package/dist-lib/lib/core/files/store/reference.js +4 -3
  87. package/dist-lib/lib/core/files/store/server.d.ts +8 -4
  88. package/dist-lib/lib/core/files/store/server.js +16 -12
  89. package/dist-lib/lib/core/files/store/sweep.js +2 -1
  90. package/dist-lib/lib/core/files/upload.d.ts +1 -1
  91. package/dist-lib/lib/core/hosted-agents.js +1 -1
  92. package/dist-lib/lib/core/image/cache-sweep.d.ts +1 -0
  93. package/dist-lib/lib/core/image/cache-sweep.js +7 -3
  94. package/dist-lib/lib/core/local/files.d.ts +24 -0
  95. package/dist-lib/lib/core/local/files.js +154 -0
  96. package/dist-lib/lib/core/local/index.d.ts +21 -5
  97. package/dist-lib/lib/core/local/index.js +75 -45
  98. package/dist-lib/lib/core/membership.d.ts +4 -1
  99. package/dist-lib/lib/core/membership.js +17 -2
  100. package/dist-lib/lib/core/mesh.d.ts +5 -0
  101. package/dist-lib/lib/core/mesh.js +11 -5
  102. package/dist-lib/lib/core/migrations/agent-indexes.d.ts +2 -0
  103. package/dist-lib/lib/core/migrations/agent-indexes.js +30 -0
  104. package/dist-lib/lib/core/migrations/file-index.d.ts +2 -0
  105. package/dist-lib/lib/core/migrations/file-index.js +27 -0
  106. package/dist-lib/lib/core/migrations/index.js +3 -1
  107. package/dist-lib/lib/core/notification.js +5 -5
  108. package/dist-lib/lib/core/range.d.ts +18 -0
  109. package/dist-lib/lib/core/range.js +17 -0
  110. package/dist-lib/lib/core/sync/index.js +39 -32
  111. package/dist-lib/lib/core/sync-status.js +3 -2
  112. package/dist-lib/lib/core/tool-activity.d.ts +2 -5
  113. package/dist-lib/lib/core/tool-activity.js +4 -7
  114. package/dist-lib/lib/core.d.ts +48 -29
  115. package/dist-lib/lib/core.js +465 -359
  116. package/dist-lib/lib/knowledge-search.d.ts +2 -2
  117. package/dist-lib/lib/kv-cache.js +1 -1
  118. package/dist-lib/lib/log.js +2 -3
  119. package/dist-lib/lib/mesh-scoped-engine.d.ts +8 -1
  120. package/dist-lib/lib/mesh-scoped-engine.js +62 -15
  121. package/dist-lib/lib/model-download.d.ts +14 -5
  122. package/dist-lib/lib/model-download.js +25 -17
  123. package/dist-lib/lib/run-transcript.d.ts +2 -2
  124. package/dist-lib/lib/run-transcript.js +3 -2
  125. package/dist-lib/lib/task.d.ts +1 -0
  126. package/dist-lib/lib/task.js +3 -2
  127. package/dist-lib/schema/build.js +4 -10
  128. package/dist-lib/schema/engine.js +261 -91
  129. package/dist-lib/schema/helpers.d.ts +4 -0
  130. package/dist-lib/schema/helpers.js +20 -0
  131. package/dist-lib/schema/local.d.ts +1 -1
  132. package/dist-lib/schema/local.js +70 -2
  133. package/dist-lib/schema/qvac.js +30 -0
  134. package/dist-lib/spec/bind.js +20 -3
  135. package/dist-lib/spec/calls.js +19 -15
  136. package/dist-lib/spec/capabilities.d.ts +42 -34
  137. package/dist-lib/spec/hrpc/hrpc.json +82 -30
  138. package/dist-lib/spec/hrpc/index.js +106 -57
  139. package/dist-lib/spec/hrpc/messages.js +5420 -5019
  140. package/dist-lib/spec/hyperschema/index.js +5424 -5023
  141. package/dist-lib/spec/hyperschema/schema.json +3202 -2666
  142. package/dist-lib/spec/hyperschema/types.d.ts +455 -319
  143. package/dist-lib/spec/local/hyperdb/db.json +119 -1
  144. package/dist-lib/spec/local/hyperdb/index.js +414 -2
  145. package/dist-lib/spec/local/hyperdb/messages.js +505 -124
  146. package/dist-lib/spec/local/hyperschema/index.js +203 -5
  147. package/dist-lib/spec/local/hyperschema/schema.json +136 -1
  148. package/dist-lib/spec/local/hyperschema/types.d.ts +32 -1
  149. package/dist-lib/spec/mesh/hyperdb/db.json +55 -3
  150. package/dist-lib/spec/mesh/hyperdb/index.js +119 -3
  151. package/dist-lib/spec/mesh/hyperdb/messages.js +244 -172
  152. package/dist-lib/spec/mesh/hyperdispatch/dispatch.json +7 -1
  153. package/dist-lib/spec/mesh/hyperdispatch/index.js +18 -1
  154. package/dist-lib/spec/mesh/hyperdispatch/messages.js +74 -2
  155. package/dist-lib/spec/mesh/hyperschema/index.js +74 -2
  156. package/dist-lib/spec/mesh/hyperschema/schema.json +27 -1
  157. package/dist-lib/spec/mesh/hyperschema/types.d.ts +9 -1
  158. package/package.json +6 -6
  159. package/tui/app.mjs +376 -151
  160. package/tui/boot.mjs +2 -1
  161. package/tui/lib/busy-words.mjs +2 -1
  162. package/tui/lib/knowledge-command.mjs +11 -10
  163. package/tui/lib/knowledge-import.mjs +7 -5
  164. package/tui/lib/render.mjs +4 -3
  165. package/tui/lib/usage.mjs +2 -1
  166. package/tui/main.mjs +2 -1
@@ -16,14 +16,14 @@ import { acceptedRepairCount, historyBranches, isPromptChunk } from './core/prom
16
16
  import ReadyGuard from 'ready-guard';
17
17
  import ReadyResource from 'ready-resource';
18
18
  import { local } from '../spec/index.js';
19
- import { isMeshTransition } from './api/current-mesh.js';
19
+ import { isMissingMesh } from './api/current-mesh.js';
20
20
  import { meshScoped } from './mesh-scoped-engine.js';
21
21
  import { buildTitlePrompt, deriveChatTitle, isDefaultChatTitle, parseTitleResponse } from './chat-title.js';
22
22
  import { matchApprovalRule } from './core/approval-rules.js';
23
23
  import { isAudioAttachment } from './core/audio-attachment.js';
24
24
  import { attachTurnDocumentIds, formatRagContext, chooseRagNotice, RAG_KNOWLEDGE_OFF_NOTICE, RAG_TRUNCATED_NOTICE, RAG_UNAVAILABLE_NOTICE, createRagSourceTagFilter, citedByPhraseOverlap, formatFullDocumentContext, isFullTextHit, isTruncatedFullTextHit, sourcesFromHits, WEB_TOOLS, webSourcesFromToolResult, withoutDataChannel } from './core/files/index.js';
25
25
  import { annotateDocumentAttachments, documentUnreadNotice, documentUnreadReason } from './core/document-attachment.js';
26
- import { imageCacheName, sweepImageCache } from './core/image/cache-sweep.js';
26
+ import { imageCacheKey, imageCacheName, sweepImageCache } from './core/image/cache-sweep.js';
27
27
  import { IMAGE_MIMES, normalizeImageForModel } from './core/image/normalize.js';
28
28
  import { summarizeRuns } from './diagnostics.js';
29
29
  import { resolveFsGrants } from './fs-drive-bridge.js';
@@ -50,6 +50,7 @@ export {} from './assistant/skill-encode.js';
50
50
  export { annotateUnreadableImages, unheardAudioNotice, unreadableImagesNotice, DOCUMENT_ONLY_USER_PROMPT, IMAGE_AND_DOCUMENT_USER_PROMPT, IMAGE_ONLY_USER_PROMPT, nameSenders } from './assistant/message.js';
51
51
  export { couldNameSenders, historyFromChunks, listHistoryChunks, senderAttribution, senderNamesFrom, staleToolRunIds } from './assistant/history.js';
52
52
  const NO_SENDERS = new Map();
53
+ const DEFAULT_PROFILE = 'mid';
53
54
  const QvacState = local.getEnum('@local/qvac-state');
54
55
  const FINAL_FLUSH_MS = 10_000;
55
56
  const UPLOAD_FRAME_BYTES = 64 * 1024;
@@ -119,6 +120,7 @@ export class QvacAssistant extends ReadyResource {
119
120
  _readinessDirty = false;
120
121
  _reconciling;
121
122
  _onlineBoot = new ReadyGuard();
123
+ _accountSeen = Promise.withResolvers();
122
124
  _capability;
123
125
  _downloads;
124
126
  _state;
@@ -126,13 +128,12 @@ export class QvacAssistant extends ReadyResource {
126
128
  _harnessDeath;
127
129
  _refreshingDiagnostics;
128
130
  _meshList;
131
+ _accountFrames;
132
+ _accountMeshId;
129
133
  _advertisedOn;
130
- _chatList;
131
- _agentList;
132
- _chatListWatch;
133
- _agentWatch;
134
134
  _meshListWatch;
135
- _runConsumers;
135
+ _accountWatch;
136
+ _meshConsumers;
136
137
  _runs;
137
138
  _seen;
138
139
  _inferenceCalls;
@@ -172,13 +173,12 @@ export class QvacAssistant extends ReadyResource {
172
173
  this._harnessDeath = null;
173
174
  this._refreshingDiagnostics = false;
174
175
  this._meshList = null;
176
+ this._accountFrames = null;
177
+ this._accountMeshId = null;
175
178
  this._advertisedOn = null;
176
- this._chatList = null;
177
- this._agentList = null;
178
- this._chatListWatch = this._supervisedWatch('chat-list', () => this._watchChatList());
179
- this._agentWatch = this._supervisedWatch('agent', () => this._watchAgents());
180
179
  this._meshListWatch = this._supervisedWatch('mesh-list', () => this._watchMeshList());
181
- this._runConsumers = new Map();
180
+ this._accountWatch = this._supervisedWatch('account', () => this._watchAccount());
181
+ this._meshConsumers = new Map();
182
182
  this._runs = new Map();
183
183
  this._seen = new Map();
184
184
  this._inferenceCalls = new InferenceCallStore(inferenceCallsDir);
@@ -224,6 +224,7 @@ export class QvacAssistant extends ReadyResource {
224
224
  engine: this._engine,
225
225
  harness: this._harness,
226
226
  deviceId: this._deviceId,
227
+ meshId: () => this._accountMeshId,
227
228
  onCacheChanged: () => {
228
229
  this._modelCatalog.notify();
229
230
  void this._reportCapabilities();
@@ -234,9 +235,8 @@ export class QvacAssistant extends ReadyResource {
234
235
  mobileClass: this._mobileClass
235
236
  });
236
237
  this._downloads.start();
237
- this._chatListWatch.start();
238
- this._agentWatch.start();
239
238
  this._meshListWatch.start();
239
+ this._accountWatch.start();
240
240
  void this._bootOnline();
241
241
  this._triggerModelWarm();
242
242
  void this.onlineReady().then(() => this._triggerModelWarm(), noop);
@@ -274,21 +274,30 @@ export class QvacAssistant extends ReadyResource {
274
274
  this._log?.info('models', 'model warm done', { model, ms: Date.now() - started });
275
275
  }
276
276
  async _currentAgent(activeAgentId, deviceId) {
277
+ const meshId = this._accountMeshId;
278
+ if (!meshId)
279
+ return null;
277
280
  if (activeAgentId) {
278
- const agent = await this._engine.getAgent({ id: activeAgentId }).catch(noop);
279
- if (agent && !agent.deletedAt)
280
- return agent;
281
+ const active = await this._engine.getAgent({ agentId: activeAgentId, meshId }).catch(noop);
282
+ if (active)
283
+ return active;
284
+ }
285
+ try {
286
+ const own = await this._engine.getDefaultAgent({ meshId, providerDeviceId: deviceId });
287
+ if (own.agent)
288
+ return own.agent;
289
+ const any = await this._engine.getDefaultAgent({ meshId });
290
+ return any.agent ?? null;
291
+ }
292
+ catch (err) {
293
+ this._log?.warn('models', 'reading the default agent for the warm failed', err);
294
+ return null;
281
295
  }
282
- const { agents } = await this._engine.listAgents({}).catch(() => ({ agents: [] }));
283
- const all = agents ?? [];
284
- return (all.find((agent) => agent.isDefault && agent.providerDeviceId?.equals(deviceId)) ??
285
- all.find((agent) => agent.isDefault) ??
286
- all[0] ??
287
- null);
288
296
  }
289
297
  async _bootOnline() {
290
298
  void this._onlineBoot.ready().catch(noop);
291
299
  try {
300
+ await this._accountSeen.promise;
292
301
  await Promise.allSettled([
293
302
  this._sweepImageCache(),
294
303
  this._sweepInferenceCalls(),
@@ -331,12 +340,19 @@ export class QvacAssistant extends ReadyResource {
331
340
  }
332
341
  }
333
342
  async _persistedProfile() {
343
+ await this._accountSeen.promise;
334
344
  const deviceId = this._deviceId;
335
- if (!deviceId)
336
- return 'mid';
337
- const { devices } = await this._engine.listDevices({}).catch(() => ({ devices: [] }));
338
- const self = (devices ?? []).find((device) => device.id.equals(deviceId));
339
- return self?.capabilityProfile ?? 'mid';
345
+ const meshId = this._accountMeshId;
346
+ if (!deviceId || !meshId)
347
+ return DEFAULT_PROFILE;
348
+ try {
349
+ const self = await this._engine.getDevice({ meshId, deviceId });
350
+ return self.capabilityProfile ?? DEFAULT_PROFILE;
351
+ }
352
+ catch (err) {
353
+ this._log?.warn('assistant', 'reading this device profile failed', err);
354
+ return DEFAULT_PROFILE;
355
+ }
340
356
  }
341
357
  async _sweepImageCache() {
342
358
  try {
@@ -370,21 +386,13 @@ export class QvacAssistant extends ReadyResource {
370
386
  }
371
387
  async _referencedImageNames() {
372
388
  try {
373
- const { chats } = await this._engine.listChats({});
374
- if (!chats?.length)
389
+ const { files } = await this._engine.listLocalFiles({});
390
+ if (!files?.length)
375
391
  return null;
376
- const keep = new Set();
377
- for (const chat of chats) {
378
- const { chunks } = await this._engine.listChunks({ chatId: chat.id, type: 'attachment' });
379
- for (const chunk of chunks ?? []) {
380
- const attachment = chunk.attachment;
381
- if (attachment && !attachment.deletedAt)
382
- keep.add(imageCacheName(attachment));
383
- }
384
- }
385
- return keep;
392
+ return new Set(files.map((file) => imageCacheKey(file.blobId)));
386
393
  }
387
- catch {
394
+ catch (err) {
395
+ this._log?.warn('assistant', 'reading the local file index failed', err);
388
396
  return null;
389
397
  }
390
398
  }
@@ -471,8 +479,12 @@ export class QvacAssistant extends ReadyResource {
471
479
  ]);
472
480
  if (key === this._lastCapabilities)
473
481
  return;
482
+ const meshId = this._accountMeshId;
483
+ if (!meshId)
484
+ return;
474
485
  try {
475
486
  await this._engine.saveDeviceCapabilities({
487
+ meshId,
476
488
  installedToolNames: this._info.toolNames,
477
489
  installedSkillNames: this._info.skills,
478
490
  installedModelNames,
@@ -483,7 +495,7 @@ export class QvacAssistant extends ReadyResource {
483
495
  this._lastCapabilities = key;
484
496
  }
485
497
  catch (err) {
486
- if (isMeshTransition(err))
498
+ if (isMissingMesh(err))
487
499
  return;
488
500
  this._log?.error('assistant', 'saveDeviceCapabilities failed', err);
489
501
  }
@@ -506,15 +518,15 @@ export class QvacAssistant extends ReadyResource {
506
518
  }
507
519
  async _reconcileDeviceProfile() {
508
520
  const deviceId = this._deviceId;
509
- if (!deviceId || this._reconciling)
521
+ const meshId = this._accountMeshId;
522
+ if (!deviceId || !meshId || this._reconciling)
510
523
  return;
511
524
  this._reconciling = true;
512
525
  try {
513
526
  const capability = await this._ensureCapability();
514
527
  if (!capability)
515
528
  return;
516
- const { devices } = await this._engine.listDevices({}).catch(() => ({ devices: [] }));
517
- const self = (devices ?? []).find((device) => device.id.equals(deviceId));
529
+ const self = await this._engine.getDevice({ meshId, deviceId }).catch(noop);
518
530
  if (!self)
519
531
  return;
520
532
  const profileUpdated = !(self.capabilityProfile === capability.capabilityProfile &&
@@ -532,6 +544,7 @@ export class QvacAssistant extends ReadyResource {
532
544
  if (profileUpdated) {
533
545
  try {
534
546
  await this._engine.saveDeviceProfile({
547
+ meshId,
535
548
  capabilityProfile: capability.capabilityProfile,
536
549
  recommendedModelName: capability.recommendedModelName,
537
550
  platform: this._platform
@@ -549,8 +562,6 @@ export class QvacAssistant extends ReadyResource {
549
562
  }
550
563
  }
551
564
  async _close() {
552
- this._chatListWatch.stop();
553
- this._agentWatch.stop();
554
565
  this._stopMeshIntake();
555
566
  this._harness.off?.('status', this._onHarnessStatus);
556
567
  this._harness.off?.('model', this._onModelCatalogEvent);
@@ -560,9 +571,8 @@ export class QvacAssistant extends ReadyResource {
560
571
  run.controller.abort(RUNNER_CLOSED);
561
572
  await this._downloads?.close();
562
573
  this._modelCatalog.close();
563
- await this._meshList?.return?.();
564
- await this._chatList?.return?.();
565
- await this._agentList?.return?.();
574
+ this._meshList?.destroy();
575
+ this._accountFrames?.destroy();
566
576
  this._lifecycle.abort(RUNNER_CLOSED);
567
577
  await Promise.allSettled([...this._runs.values()].map((run) => run.done));
568
578
  }
@@ -583,13 +593,10 @@ export class QvacAssistant extends ReadyResource {
583
593
  return;
584
594
  this._state = QvacState.SUSPEND;
585
595
  this._log?.info('assistant', 'suspending', { runs: this._runs.size });
586
- this._chatListWatch.stop();
587
- this._agentWatch.stop();
588
596
  this._stopMeshIntake();
589
597
  await this._downloads?.suspend();
590
- await this._meshList?.return?.();
591
- await this._chatList?.return?.();
592
- await this._agentList?.return?.();
598
+ this._meshList?.destroy();
599
+ this._accountFrames?.destroy();
593
600
  for (const run of this._runs.values())
594
601
  run.controller.abort(SUSPENDED);
595
602
  this._warmedModel = false;
@@ -618,11 +625,10 @@ export class QvacAssistant extends ReadyResource {
618
625
  this._log?.info('assistant', 'resuming');
619
626
  await Promise.allSettled([...this._runs.values()].map((run) => run.done));
620
627
  this._downloads?.resume();
621
- if (this.opened) {
622
- this._chatListWatch.start();
623
- this._agentWatch.start();
624
- this._meshListWatch.start();
625
- }
628
+ if (!this.opened)
629
+ return;
630
+ this._meshListWatch.start();
631
+ this._accountWatch.start();
626
632
  }
627
633
  async listModels(options) {
628
634
  return (await this._harness.list?.(options)) ?? [];
@@ -642,7 +648,8 @@ export class QvacAssistant extends ReadyResource {
642
648
  if (!this.opened)
643
649
  await this.ready();
644
650
  if (agentId) {
645
- const agent = await this._engine.getAgent({ id: agentId }).catch(noop);
651
+ const meshId = options?.meshId ?? this._accountMeshId;
652
+ const agent = meshId ? await this._engine.getAgent({ agentId, meshId }).catch(noop) : null;
646
653
  const deviceId = this._deviceId;
647
654
  if (agent && deviceId && !agent.providerDeviceId?.equals(deviceId)) {
648
655
  agentId = null;
@@ -666,10 +673,10 @@ export class QvacAssistant extends ReadyResource {
666
673
  .filter((skill) => isSetUpHere(skill.status))
667
674
  .map((skill) => skill.name);
668
675
  const deviceId = this._deviceId;
669
- if (deviceId) {
670
- const { agents } = await this._engine.listAgents({});
671
- const local = (agents ?? []).filter((agent) => !agent.deletedAt && agent.providerDeviceId?.equals(deviceId));
672
- for (const agent of local) {
676
+ const meshId = this._accountMeshId;
677
+ if (deviceId && meshId) {
678
+ const { agents } = await this._engine.listAgents({ meshId, providerDeviceId: deviceId });
679
+ for (const agent of agents ?? []) {
673
680
  const resolved = (await this._harness.skills?.(agent.id, agent.modelName, {
674
681
  skipCredentialProbe: true
675
682
  })) ?? [];
@@ -695,7 +702,7 @@ export class QvacAssistant extends ReadyResource {
695
702
  let again = false;
696
703
  const settle = (err) => {
697
704
  running = false;
698
- if (err !== null && !isMeshTransition(err)) {
705
+ if (err !== null && !isMissingMesh(err)) {
699
706
  this._log?.error('assistant', `${label} watch failed`, err);
700
707
  }
701
708
  if (again)
@@ -714,15 +721,12 @@ export class QvacAssistant extends ReadyResource {
714
721
  };
715
722
  return { start, stop: () => void (again = false) };
716
723
  }
717
- async _watchChatList() {
718
- const stream = this._engine.chatsWatch({});
719
- this._chatList = stream[Symbol.asyncIterator]();
724
+ async _reclaimDeletedChats(frames) {
720
725
  let known = null;
721
- while (true) {
722
- const { value, done } = await this._chatList.next();
723
- if (done || this.closing || this.suspended)
726
+ for await (const frame of frames) {
727
+ if (this.closing || this.suspended)
724
728
  return;
725
- const ids = (value.chats ?? []).map((chat) => chat.id);
729
+ const ids = (frame.chats ?? []).map((chat) => chat.id);
726
730
  if (known !== null) {
727
731
  for (const chatId of disappearedChatIds(known, ids)) {
728
732
  this._reconciledCompactions.delete(chatId);
@@ -738,30 +742,27 @@ export class QvacAssistant extends ReadyResource {
738
742
  await this._sweepInferenceCalls();
739
743
  }
740
744
  }
741
- async _watchAgents() {
742
- const stream = this._engine.agentsWatch({});
743
- this._agentList = stream[Symbol.asyncIterator]();
745
+ async _reclaimRekeyedAgents(meshId, frames) {
744
746
  let known = null;
745
- while (true) {
746
- const { value, done } = await this._agentList.next();
747
- if (done || this.closing || this.suspended)
747
+ for await (const frame of frames) {
748
+ if (this.closing || this.suspended)
748
749
  return;
749
- const agents = value.agents ?? [];
750
+ const agents = frame.agents ?? [];
750
751
  const next = new Map(agents.map((agent) => [agent.id, agentRekeyFingerprint(agent)]));
751
752
  if (known !== null) {
752
753
  for (const agent of agents) {
753
754
  const previous = known.get(agent.id);
754
755
  if (previous !== undefined && previous !== next.get(agent.id)) {
755
- void this._reclaimAgentChatCaches(agent.id);
756
+ void this._reclaimAgentChatCaches(meshId, agent.id);
756
757
  }
757
758
  }
758
759
  }
759
760
  known = next;
760
761
  }
761
762
  }
762
- async _reclaimAgentChatCaches(agentId) {
763
+ async _reclaimAgentChatCaches(meshId, agentId) {
763
764
  try {
764
- const { chats } = await this._engine.listChats({});
765
+ const { chats } = await this._engine.listChats({ meshId });
765
766
  for (const chat of chats ?? []) {
766
767
  if (chat.agentId === agentId)
767
768
  await this._deleteChatKvCache(chat.id, 'agent re-key');
@@ -836,35 +837,45 @@ export class QvacAssistant extends ReadyResource {
836
837
  }
837
838
  }
838
839
  async _watchMeshList() {
839
- const stream = this._engine.meshesWatch({});
840
- this._meshList = stream[Symbol.asyncIterator]();
841
- while (true) {
842
- const { value, done } = await this._meshList.next();
843
- if (done || this.closing || this.suspended)
840
+ this._meshList = this._engine.meshesWatch({});
841
+ for await (const { meshes } of this._meshList) {
842
+ if (this.closing || this.suspended)
844
843
  return;
845
- const meshes = value.meshes ?? [];
846
- this._syncRunConsumers(meshes);
847
- this._followSelectedMesh(meshes);
844
+ this._syncMeshConsumers(meshes ?? []);
848
845
  }
849
846
  }
850
- _syncRunConsumers(meshes) {
847
+ async _watchAccount() {
848
+ this._accountFrames = this._engine.accountWatch({});
849
+ try {
850
+ for await (const account of this._accountFrames) {
851
+ if (this.closing || this.suspended)
852
+ return;
853
+ this._followAccount(account);
854
+ this._accountSeen.resolve();
855
+ }
856
+ }
857
+ finally {
858
+ this._accountSeen.resolve();
859
+ }
860
+ }
861
+ _syncMeshConsumers(meshes) {
851
862
  const open = new Set(meshes.filter((mesh) => mesh.open).map((mesh) => mesh.meshId));
852
- for (const [meshId, consumer] of this._runConsumers) {
863
+ for (const [meshId, consumer] of this._meshConsumers) {
853
864
  if (open.has(meshId))
854
865
  continue;
855
866
  consumer.stop();
856
- this._runConsumers.delete(meshId);
867
+ this._meshConsumers.delete(meshId);
857
868
  this._pruneSeen(meshId, new Set());
858
869
  }
859
870
  for (const meshId of open) {
860
- const consumer = this._runConsumers.get(meshId) ?? this._meshRunConsumer(meshId);
861
- this._runConsumers.set(meshId, consumer);
871
+ const consumer = this._meshConsumers.get(meshId) ?? this._meshConsumer(meshId);
872
+ this._meshConsumers.set(meshId, consumer);
862
873
  consumer.start();
863
874
  }
864
875
  }
865
- _followSelectedMesh(meshes) {
866
- const selected = meshes.find((mesh) => mesh.active);
867
- const on = selected ? `${selected.meshId}:${selected.writable}` : null;
876
+ _followAccount(account) {
877
+ this._accountMeshId = account.meshId ?? null;
878
+ const on = account.meshId ? `${account.meshId}:${account.writable}` : null;
868
879
  if (on === null) {
869
880
  this._advertisedOn = null;
870
881
  return;
@@ -872,41 +883,53 @@ export class QvacAssistant extends ReadyResource {
872
883
  if (on === this._advertisedOn)
873
884
  return;
874
885
  this._advertisedOn = on;
875
- this._chatListWatch.start();
876
- this._agentWatch.start();
877
- this._downloads?.meshSelected();
886
+ this._downloads?.meshAdopted();
878
887
  this._lastCapabilities = null;
879
- this._reportCapabilities().catch(noop);
880
- this._reconcileDeviceProfile().catch(noop);
881
- }
882
- _meshRunConsumer(meshId) {
883
- let requests = null;
884
- const watch = this._supervisedWatch(`run-requests:${meshId}`, async () => {
885
- const stream = this._engine.runRequestsWatch({ meshId });
886
- requests = stream[Symbol.asyncIterator]();
887
- while (true) {
888
- const { value, done } = await requests.next();
889
- if (done || this.closing || this.suspended)
890
- return;
891
- const chunks = value.chunks ?? [];
892
- for (const chunk of chunks)
893
- this._dispatch(chunk, meshId);
894
- this._pruneSeen(meshId, new Set(chunks.map((chunk) => chunk.runId)));
895
- }
888
+ void this._reportCapabilities();
889
+ void this._reconcileDeviceProfile();
890
+ this._triggerModelWarm();
891
+ }
892
+ _meshConsumer(meshId) {
893
+ const watches = [
894
+ this._streamWatch(`run-requests:${meshId}`, () => this._engine.runRequestsWatch({ meshId }), (frames) => this._dispatchRunRequests(meshId, frames)),
895
+ this._streamWatch(`chat-list:${meshId}`, () => this._engine.chatsWatch({ meshId }), (frames) => this._reclaimDeletedChats(frames)),
896
+ this._streamWatch(`agent:${meshId}`, () => this._engine.agentsWatch({ meshId }), (frames) => this._reclaimRekeyedAgents(meshId, frames))
897
+ ];
898
+ return {
899
+ start: () => watches.forEach((watch) => watch.start()),
900
+ stop: () => watches.forEach((watch) => watch.stop())
901
+ };
902
+ }
903
+ _streamWatch(label, open, consume) {
904
+ let frames = null;
905
+ const watch = this._supervisedWatch(label, async () => {
906
+ frames = open();
907
+ return consume(frames);
896
908
  });
897
909
  return {
898
910
  start: () => watch.start(),
899
911
  stop: () => {
900
912
  watch.stop();
901
- void requests?.return?.();
913
+ frames?.destroy();
902
914
  }
903
915
  };
904
916
  }
917
+ async _dispatchRunRequests(meshId, frames) {
918
+ for await (const frame of frames) {
919
+ if (this.closing || this.suspended)
920
+ return;
921
+ const chunks = frame.chunks ?? [];
922
+ for (const chunk of chunks)
923
+ this._dispatch(chunk, meshId);
924
+ this._pruneSeen(meshId, new Set(chunks.map((chunk) => chunk.runId)));
925
+ }
926
+ }
905
927
  _stopMeshIntake() {
906
928
  this._meshListWatch.stop();
907
- for (const consumer of this._runConsumers.values())
929
+ this._accountWatch.stop();
930
+ for (const consumer of this._meshConsumers.values())
908
931
  consumer.stop();
909
- this._runConsumers.clear();
932
+ this._meshConsumers.clear();
910
933
  this._advertisedOn = null;
911
934
  }
912
935
  _pruneSeen(meshId, live) {
@@ -920,8 +943,9 @@ export class QvacAssistant extends ReadyResource {
920
943
  const lender = agent.lenderDeviceId;
921
944
  if (!lender || !this._borrowHarness)
922
945
  return null;
923
- const id = lender.toString('hex');
924
- return id === this._deviceId?.toString('hex') ? null : id;
946
+ const id = b4a.toHex(lender);
947
+ const own = this._deviceId;
948
+ return own && id === b4a.toHex(own) ? null : id;
925
949
  }
926
950
  _harnessFor(agent) {
927
951
  const id = this._lenderFor(agent);
@@ -948,7 +972,7 @@ export class QvacAssistant extends ReadyResource {
948
972
  const engine = meshScoped(this._engine, meshId);
949
973
  const settle = (async () => {
950
974
  const agentId = request.runRequest?.agentId;
951
- const agent = await engine.getAgent({ id: agentId }).catch(noop);
975
+ const agent = await engine.getAgent({ agentId }).catch(noop);
952
976
  if (!agent) {
953
977
  this._seen.delete(runId);
954
978
  return;
@@ -979,7 +1003,7 @@ export class QvacAssistant extends ReadyResource {
979
1003
  this._yieldDownloads();
980
1004
  if (this._chats.get(request.chatId) === link)
981
1005
  this._chats.delete(request.chatId);
982
- this._reportCapabilities().catch(noop);
1006
+ void this._reportCapabilities();
983
1007
  }
984
1008
  })();
985
1009
  settle.catch((err) => this._log?.error('assistant', `run ${runId} failed`, err));
@@ -1043,7 +1067,7 @@ export class QvacAssistant extends ReadyResource {
1043
1067
  }
1044
1068
  if (await this._isHandled(engine, request))
1045
1069
  return;
1046
- const fresh = await engine.getAgent({ id: agent.id }).catch(noop);
1070
+ const fresh = await engine.getAgent({ agentId: agent.id }).catch(noop);
1047
1071
  if (!fresh || fresh.deletedAt || !fresh.providerDeviceId?.equals(deviceId))
1048
1072
  return;
1049
1073
  agent = fresh;
@@ -1449,7 +1473,7 @@ export class QvacAssistant extends ReadyResource {
1449
1473
  runFailure = runFailureNotice(event.message);
1450
1474
  await transcript.status({ state: 'failed', reason: runFailure, metrics });
1451
1475
  if (folded) {
1452
- await this._engine
1476
+ await engine
1453
1477
  .runAgent({ chatId, agentId: agent.id, parentRunId: runId })
1454
1478
  .catch((err) => this._log?.warn('runs', 'compaction retry not queued', { runId, err }));
1455
1479
  }
@@ -1769,7 +1793,7 @@ export class QvacAssistant extends ReadyResource {
1769
1793
  if (!raw)
1770
1794
  throw new Error(`empty download for ${image.fileName}`);
1771
1795
  const bytes = await normalizeImageForModel(raw);
1772
- const staging = `${file}.partial-${crypto.randomBytes(4).toString('hex')}`;
1796
+ const staging = `${file}.partial-${b4a.toHex(crypto.randomBytes(4))}`;
1773
1797
  await fs.promises.writeFile(staging, bytes, { mode: 0o600 });
1774
1798
  await fs.promises.rename(staging, file);
1775
1799
  }
@@ -1813,8 +1837,8 @@ export class QvacAssistant extends ReadyResource {
1813
1837
  });
1814
1838
  statusId = status.id;
1815
1839
  },
1816
- ...(signal ? { signal } : {}),
1817
- ...(meshId ? { meshId } : {})
1840
+ meshId,
1841
+ signal
1818
1842
  });
1819
1843
  this._log?.info('runs', 'compaction', {
1820
1844
  chatId,
@@ -1857,15 +1881,15 @@ export class QvacAssistant extends ReadyResource {
1857
1881
  }
1858
1882
  return {};
1859
1883
  }
1860
- async compactChat(chatId, options = {}) {
1884
+ async compactChat(chatId, options) {
1861
1885
  if (!this.opened)
1862
1886
  await this.ready();
1863
1887
  const engine = meshScoped(this._engine, options.meshId);
1864
1888
  const deviceId = this._deviceId;
1865
- const chat = await engine.getChat({ id: chatId }).catch(noop);
1889
+ const chat = await engine.getChat({ chatId }).catch(noop);
1866
1890
  if (!chat)
1867
1891
  return { compacted: false, reason: 'unknown chat' };
1868
- const agent = await engine.getAgent({ id: chat.agentId }).catch(noop);
1892
+ const agent = await engine.getAgent({ agentId: chat.agentId }).catch(noop);
1869
1893
  if (!agent || !agent.providerDeviceId?.equals(deviceId)) {
1870
1894
  return { compacted: false, reason: 'not the provider device' };
1871
1895
  }
@@ -1978,7 +2002,7 @@ export class QvacAssistant extends ReadyResource {
1978
2002
  const first = messages.find((turn) => turn.role === 'user' && turn.content.trim());
1979
2003
  if (!first)
1980
2004
  return;
1981
- const chat = await engine.getChat({ id: chatId });
2005
+ const chat = await engine.getChat({ chatId });
1982
2006
  if (!isDefaultChatTitle(chat?.title))
1983
2007
  return;
1984
2008
  await this._generateChatTitle({ engine, chatId, input: first.content, model, agent, probe });
@@ -2010,7 +2034,7 @@ export class QvacAssistant extends ReadyResource {
2010
2034
  const title = generated ?? deriveChatTitle(prompt);
2011
2035
  if (!title)
2012
2036
  return null;
2013
- await engine.renameChat({ id: chatId, title });
2037
+ await engine.renameChat({ chatId, config: { title } });
2014
2038
  this._log?.info('runs', 'chat titled', {
2015
2039
  chatId,
2016
2040
  title,
@@ -2222,7 +2246,7 @@ export class QvacAssistant extends ReadyResource {
2222
2246
  chunkId: ask.id,
2223
2247
  tool: ask.approvalRequest?.name
2224
2248
  });
2225
- await engine.resolveApproval({ id: ask.id, approved: false });
2249
+ await engine.resolveApproval({ chunkId: ask.id, approved: false });
2226
2250
  }
2227
2251
  for (const waiter of waiters.values())
2228
2252
  waiter.resolve(false);
@@ -2328,6 +2352,7 @@ export class QvacAssistant extends ReadyResource {
2328
2352
  let showing = queued;
2329
2353
  let transcribing = false;
2330
2354
  let documents = false;
2355
+ let sampling = false;
2331
2356
  const apply = (progress) => {
2332
2357
  const runStatus = progress
2333
2358
  ? { state: 'executing', progress }
@@ -2342,6 +2367,8 @@ export class QvacAssistant extends ReadyResource {
2342
2367
  update(runStatus).catch(noop);
2343
2368
  };
2344
2369
  const onModel = (state) => {
2370
+ if (sampling)
2371
+ return;
2345
2372
  if (state.status === 'loading')
2346
2373
  apply({ phase: 'loading', model: state.model });
2347
2374
  else if (state.status === 'downloading') {
@@ -2363,12 +2390,14 @@ export class QvacAssistant extends ReadyResource {
2363
2390
  apply(active ? { phase: 'transcribing' } : null);
2364
2391
  },
2365
2392
  image: (progress) => {
2393
+ sampling = progress !== null;
2366
2394
  if (!progress)
2367
2395
  return apply(null);
2368
2396
  apply({ phase: 'generating', percentage: Math.floor(progress.percentage / 10) * 10 });
2369
2397
  },
2370
2398
  stop: () => this._harness.off?.('model', onModel),
2371
2399
  clear: () => {
2400
+ sampling = false;
2372
2401
  if (!showing)
2373
2402
  return;
2374
2403
  showing = false;
@@ -10,7 +10,7 @@ const EOCD_SIZE = 22;
10
10
  const EOCD_SCAN = 65_535 + EOCD_SIZE;
11
11
  export async function convert(input) {
12
12
  assertIntactZip(input.bytes);
13
- const base = path.join(os.tmpdir(), `qvac-collabora-${randomBytes(8).toString('hex')}`);
13
+ const base = path.join(os.tmpdir(), `qvac-collabora-${b4a.toHex(randomBytes(8))}`);
14
14
  const src = `${base}${sourceExtension(input.fileName)}`;
15
15
  const out = `${base}.${input.to}`;
16
16
  try {