@qvac/core 0.2.0 → 0.2.2

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 (265) hide show
  1. package/.claude/skills/compaction/SKILL.md +9 -4
  2. package/.claude/skills/pr-create/SKILL.md +24 -3
  3. package/.claude/skills/pr-review/SKILL.md +248 -40
  4. package/CLAUDE.md +1 -3
  5. package/README.md +3 -1
  6. package/dist-lib/client.js +1 -1
  7. package/dist-lib/index.js +8 -8
  8. package/dist-lib/lib/api/agents.d.ts +1 -1
  9. package/dist-lib/lib/api/agents.js +10 -9
  10. package/dist-lib/lib/api/app-config.js +1 -1
  11. package/dist-lib/lib/api/approval-rules.js +9 -5
  12. package/dist-lib/lib/api/attachments.js +25 -3
  13. package/dist-lib/lib/api/chat-groups.d.ts +1 -1
  14. package/dist-lib/lib/api/chat-groups.js +5 -4
  15. package/dist-lib/lib/api/chat.js +8 -8
  16. package/dist-lib/lib/api/chunks.js +11 -11
  17. package/dist-lib/lib/api/config.js +1 -1
  18. package/dist-lib/lib/api/custom-models.js +2 -2
  19. package/dist-lib/lib/api/devices.d.ts +1 -1
  20. package/dist-lib/lib/api/devices.js +9 -9
  21. package/dist-lib/lib/api/diagnostics.js +1 -1
  22. package/dist-lib/lib/api/effective-ctx-size.js +1 -1
  23. package/dist-lib/lib/api/execution.js +4 -4
  24. package/dist-lib/lib/api/files.js +2 -2
  25. package/dist-lib/lib/api/index.d.ts +1 -0
  26. package/dist-lib/lib/api/index.js +33 -33
  27. package/dist-lib/lib/api/instrument.js +1 -1
  28. package/dist-lib/lib/api/knowledge.js +4 -4
  29. package/dist-lib/lib/api/logs.js +1 -1
  30. package/dist-lib/lib/api/members.d.ts +4 -1
  31. package/dist-lib/lib/api/members.js +88 -18
  32. package/dist-lib/lib/api/mesh.d.ts +13 -3
  33. package/dist-lib/lib/api/mesh.js +25 -2
  34. package/dist-lib/lib/api/model-download.js +1 -1
  35. package/dist-lib/lib/api/network.js +1 -1
  36. package/dist-lib/lib/api/notifications.js +3 -3
  37. package/dist-lib/lib/api/rag.js +7 -7
  38. package/dist-lib/lib/api/sync.js +1 -1
  39. package/dist-lib/lib/api/tool-activity.js +4 -4
  40. package/dist-lib/lib/api/tool-configs.js +5 -5
  41. package/dist-lib/lib/api/watchable.js +1 -1
  42. package/dist-lib/lib/assistant/fetch-body.d.ts +5 -0
  43. package/dist-lib/lib/assistant/fetch-body.js +36 -0
  44. package/dist-lib/lib/assistant/harness.d.ts +225 -0
  45. package/dist-lib/lib/assistant/harness.js +154 -0
  46. package/dist-lib/lib/assistant/history.d.ts +32 -0
  47. package/dist-lib/lib/assistant/history.js +232 -0
  48. package/dist-lib/lib/assistant/message.d.ts +45 -0
  49. package/dist-lib/lib/assistant/message.js +47 -0
  50. package/dist-lib/lib/assistant/skill-encode.d.ts +21 -0
  51. package/dist-lib/lib/assistant/skill-encode.js +71 -0
  52. package/dist-lib/lib/assistant-client.js +2 -2
  53. package/dist-lib/lib/assistant-tree.js +10 -4
  54. package/dist-lib/lib/assistant.d.ts +25 -285
  55. package/dist-lib/lib/assistant.js +250 -637
  56. package/dist-lib/lib/audio-format.js +2 -2
  57. package/dist-lib/lib/client.js +2 -2
  58. package/dist-lib/lib/collabora/convert.js +1 -1
  59. package/dist-lib/lib/collabora/entry.js +1 -1
  60. package/dist-lib/lib/collabora/worker.js +1 -1
  61. package/dist-lib/lib/compaction.d.ts +1 -2
  62. package/dist-lib/lib/compaction.js +8 -6
  63. package/dist-lib/lib/constants.js +1 -1
  64. package/dist-lib/lib/core/account-recovery.d.ts +19 -0
  65. package/dist-lib/lib/core/account-recovery.js +50 -0
  66. package/dist-lib/lib/core/agent.js +8 -4
  67. package/dist-lib/lib/core/app-build.d.ts +1 -1
  68. package/dist-lib/lib/core/approval-rules.d.ts +1 -0
  69. package/dist-lib/lib/core/approval-rules.js +3 -1
  70. package/dist-lib/lib/core/archived-mesh.d.ts +25 -0
  71. package/dist-lib/lib/core/archived-mesh.js +162 -0
  72. package/dist-lib/lib/core/chat-activity.js +1 -1
  73. package/dist-lib/lib/core/chat-group.d.ts +1 -0
  74. package/dist-lib/lib/core/chat-group.js +24 -4
  75. package/dist-lib/lib/core/chat-search.js +2 -2
  76. package/dist-lib/lib/core/chat.js +5 -5
  77. package/dist-lib/lib/core/chunk.d.ts +1 -1
  78. package/dist-lib/lib/core/chunk.js +4 -4
  79. package/dist-lib/lib/core/contract/agents.js +1 -1
  80. package/dist-lib/lib/core/contract/approval-rules.js +6 -4
  81. package/dist-lib/lib/core/contract/attestations.js +1 -1
  82. package/dist-lib/lib/core/contract/chat-group.js +1 -1
  83. package/dist-lib/lib/core/contract/chat.js +1 -1
  84. package/dist-lib/lib/core/contract/chunks.js +2 -2
  85. package/dist-lib/lib/core/contract/compute.d.ts +11 -0
  86. package/dist-lib/lib/core/contract/compute.js +45 -0
  87. package/dist-lib/lib/core/contract/devices.js +16 -3
  88. package/dist-lib/lib/core/contract/index.d.ts +3 -1
  89. package/dist-lib/lib/core/contract/index.js +19 -16
  90. package/dist-lib/lib/core/contract/indexing.js +2 -2
  91. package/dist-lib/lib/core/contract/joined-meshes.js +1 -1
  92. package/dist-lib/lib/core/contract/knowledge.js +2 -2
  93. package/dist-lib/lib/core/contract/members.js +2 -2
  94. package/dist-lib/lib/core/contract/seal.d.ts +2 -0
  95. package/dist-lib/lib/core/contract/seal.js +8 -0
  96. package/dist-lib/lib/core/contract/seed-defaults.js +1 -1
  97. package/dist-lib/lib/core/contract/tool-activity.js +1 -1
  98. package/dist-lib/lib/core/contract/tool-configs.js +3 -3
  99. package/dist-lib/lib/core/contract/writers.js +66 -42
  100. package/dist-lib/lib/core/departures.js +1 -1
  101. package/dist-lib/lib/core/device-invites.js +1 -1
  102. package/dist-lib/lib/core/document-attachment.js +2 -2
  103. package/dist-lib/lib/core/files/attachments.js +3 -3
  104. package/dist-lib/lib/core/files/index.d.ts +2 -2
  105. package/dist-lib/lib/core/files/index.js +19 -19
  106. package/dist-lib/lib/core/files/knowledge.js +3 -3
  107. package/dist-lib/lib/core/files/preview/image.js +1 -1
  108. package/dist-lib/lib/core/files/preview/index.js +6 -6
  109. package/dist-lib/lib/core/files/processing/claims.js +1 -1
  110. package/dist-lib/lib/core/files/processing/document.js +5 -5
  111. package/dist-lib/lib/core/files/processing/index.js +8 -8
  112. package/dist-lib/lib/core/files/processing/ownership.js +1 -1
  113. package/dist-lib/lib/core/files/processing/protocol.js +3 -3
  114. package/dist-lib/lib/core/files/processing/source.js +1 -1
  115. package/dist-lib/lib/core/files/rag/artifact/codec.js +1 -1
  116. package/dist-lib/lib/core/files/rag/artifact/id.js +1 -1
  117. package/dist-lib/lib/core/files/rag/artifact/types.d.ts +4 -4
  118. package/dist-lib/lib/core/files/rag/build.js +2 -2
  119. package/dist-lib/lib/core/files/rag/chunk/chunking.js +2 -2
  120. package/dist-lib/lib/core/files/rag/document-types.d.ts +3 -3
  121. package/dist-lib/lib/core/files/rag/extract/document-types.d.ts +9 -9
  122. package/dist-lib/lib/core/files/rag/extract/extract.js +7 -7
  123. package/dist-lib/lib/core/files/rag/extract/html-text.js +1 -1
  124. package/dist-lib/lib/core/files/rag/extract/office-collabora.js +2 -2
  125. package/dist-lib/lib/core/files/rag/extract/pdf-platform.js +1 -1
  126. package/dist-lib/lib/core/files/rag/extract/pdf-text.js +1 -1
  127. package/dist-lib/lib/core/files/rag/extract/text-decoding.js +1 -1
  128. package/dist-lib/lib/core/files/rag/extract/types.d.ts +2 -2
  129. package/dist-lib/lib/core/files/rag/index.js +22 -22
  130. package/dist-lib/lib/core/files/rag/load.js +5 -5
  131. package/dist-lib/lib/core/files/rag/policy.js +2 -2
  132. package/dist-lib/lib/core/files/rag/produce.js +5 -5
  133. package/dist-lib/lib/core/files/rag/retrieval/coverage.js +2 -2
  134. package/dist-lib/lib/core/files/rag/retrieval/diversity.js +1 -1
  135. package/dist-lib/lib/core/files/rag/retrieval/floor.js +2 -2
  136. package/dist-lib/lib/core/files/rag/retrieval/format.js +1 -1
  137. package/dist-lib/lib/core/files/rag/retrieval/full-text.js +18 -11
  138. package/dist-lib/lib/core/files/rag/retrieval/knowledge.js +6 -5
  139. package/dist-lib/lib/core/files/rag/retrieval/scoring.js +2 -2
  140. package/dist-lib/lib/core/files/rag/retrieval/search.js +7 -4
  141. package/dist-lib/lib/core/files/rag/retrieval/selection.d.ts +1 -0
  142. package/dist-lib/lib/core/files/rag/retrieval/selection.js +32 -2
  143. package/dist-lib/lib/core/files/rag/retrieval/sources.js +2 -2
  144. package/dist-lib/lib/core/files/rag/retrieval/terms.js +1 -1
  145. package/dist-lib/lib/core/files/rag/retrieval/types.d.ts +1 -0
  146. package/dist-lib/lib/core/files/rag/retrieval/web-sources.js +1 -1
  147. package/dist-lib/lib/core/files/records/chunks.js +1 -1
  148. package/dist-lib/lib/core/files/records/index.js +8 -8
  149. package/dist-lib/lib/core/files/records/knowledge.js +2 -2
  150. package/dist-lib/lib/core/files/records/output.js +1 -1
  151. package/dist-lib/lib/core/files/records/reclaim.js +5 -5
  152. package/dist-lib/lib/core/files/records/routing.js +7 -7
  153. package/dist-lib/lib/core/files/store/blob.js +2 -2
  154. package/dist-lib/lib/core/files/store/index.js +7 -7
  155. package/dist-lib/lib/core/files/store/reference.js +2 -2
  156. package/dist-lib/lib/core/files/store/server.js +1 -1
  157. package/dist-lib/lib/core/files/store/sweep.js +1 -1
  158. package/dist-lib/lib/core/files/upload-input.js +2 -2
  159. package/dist-lib/lib/core/files/upload.d.ts +1 -1
  160. package/dist-lib/lib/core/files/upload.js +6 -6
  161. package/dist-lib/lib/core/harness-loan.d.ts +29 -0
  162. package/dist-lib/lib/core/harness-loan.js +187 -0
  163. package/dist-lib/lib/core/helpers/index.d.ts +2 -1
  164. package/dist-lib/lib/core/helpers/index.js +4 -4
  165. package/dist-lib/lib/core/hosted-agents.js +2 -2
  166. package/dist-lib/lib/core/identity.d.ts +2 -0
  167. package/dist-lib/lib/core/identity.js +4 -2
  168. package/dist-lib/lib/core/invite.d.ts +1 -0
  169. package/dist-lib/lib/core/invite.js +4 -2
  170. package/dist-lib/lib/core/local/index.d.ts +12 -3
  171. package/dist-lib/lib/core/local/index.js +75 -16
  172. package/dist-lib/lib/core/membership.d.ts +3 -0
  173. package/dist-lib/lib/core/membership.js +15 -1
  174. package/dist-lib/lib/core/mesh-seed-handoff.js +1 -1
  175. package/dist-lib/lib/core/mesh.d.ts +9 -3
  176. package/dist-lib/lib/core/mesh.js +41 -26
  177. package/dist-lib/lib/core/migrations/agent-catalog.js +1 -1
  178. package/dist-lib/lib/core/migrations/index.js +5 -3
  179. package/dist-lib/lib/core/migrations/membership.js +2 -2
  180. package/dist-lib/lib/core/migrations/seal.d.ts +3 -0
  181. package/dist-lib/lib/core/migrations/seal.js +30 -0
  182. package/dist-lib/lib/core/next-frame.js +1 -1
  183. package/dist-lib/lib/core/notification.js +1 -1
  184. package/dist-lib/lib/core/ota-config.js +1 -1
  185. package/dist-lib/lib/core/secret-handoff.js +1 -1
  186. package/dist-lib/lib/core/send.js +3 -3
  187. package/dist-lib/lib/core/skill-overlay-handoff.js +1 -1
  188. package/dist-lib/lib/core/skill-overlay-receiver.js +2 -2
  189. package/dist-lib/lib/core/skill-secrets.js +3 -3
  190. package/dist-lib/lib/core/sync/devices.js +1 -1
  191. package/dist-lib/lib/core/sync/index.js +8 -5
  192. package/dist-lib/lib/core/sync-status.js +1 -1
  193. package/dist-lib/lib/core/system-info.js +1 -1
  194. package/dist-lib/lib/core/tool-activity.js +2 -2
  195. package/dist-lib/lib/core/tool-configs.js +2 -2
  196. package/dist-lib/lib/core.d.ts +41 -3
  197. package/dist-lib/lib/core.js +525 -90
  198. package/dist-lib/lib/credential-pusher.js +4 -4
  199. package/dist-lib/lib/deadline.js +1 -1
  200. package/dist-lib/lib/fs-drive-bridge.js +4 -2
  201. package/dist-lib/lib/integrations/index.js +3 -3
  202. package/dist-lib/lib/integrations/oauth-providers.js +1 -1
  203. package/dist-lib/lib/integrations/setup-routes.d.ts +5 -5
  204. package/dist-lib/lib/integrations/setup-routes.js +3 -3
  205. package/dist-lib/lib/knowledge-search.js +1 -1
  206. package/dist-lib/lib/log.js +3 -3
  207. package/dist-lib/lib/mesh-scoped-engine.d.ts +3 -0
  208. package/dist-lib/lib/mesh-scoped-engine.js +96 -0
  209. package/dist-lib/lib/model-context.d.ts +2 -2
  210. package/dist-lib/lib/model-context.js +1 -1
  211. package/dist-lib/lib/model-download.js +6 -6
  212. package/dist-lib/lib/oauth/asana.js +3 -3
  213. package/dist-lib/lib/oauth/browser-connect.js +1 -1
  214. package/dist-lib/lib/oauth/client.js +2 -2
  215. package/dist-lib/lib/oauth/common.d.ts +1 -1
  216. package/dist-lib/lib/oauth/common.js +1 -1
  217. package/dist-lib/lib/oauth/flow-core.js +3 -3
  218. package/dist-lib/lib/oauth/flow.js +2 -2
  219. package/dist-lib/lib/oauth/google.js +4 -4
  220. package/dist-lib/lib/oauth/host.js +3 -3
  221. package/dist-lib/lib/oauth/loopback.js +1 -1
  222. package/dist-lib/lib/oauth/notion.js +3 -3
  223. package/dist-lib/lib/oauth/providers.js +1 -1
  224. package/dist-lib/lib/oauth/resolve.js +1 -1
  225. package/dist-lib/lib/oauth/spotify.js +3 -3
  226. package/dist-lib/lib/oauth/token-exchange.js +1 -1
  227. package/dist-lib/lib/oauth.client.js +2 -2
  228. package/dist-lib/lib/oauth.js +12 -12
  229. package/dist-lib/lib/run-notices.d.ts +7 -7
  230. package/dist-lib/lib/run-transcript.js +1 -1
  231. package/dist-lib/schema/build.js +12 -6
  232. package/dist-lib/schema/content.d.ts +11 -11
  233. package/dist-lib/schema/engine.js +193 -30
  234. package/dist-lib/schema/field-order.js +2 -2
  235. package/dist-lib/schema/local.js +18 -4
  236. package/dist-lib/schema/qvac.js +15 -6
  237. package/dist-lib/spec/bind.js +41 -0
  238. package/dist-lib/spec/calls.js +12 -0
  239. package/dist-lib/spec/capabilities.d.ts +36 -12
  240. package/dist-lib/spec/hrpc/hrpc.json +161 -5
  241. package/dist-lib/spec/hrpc/index.js +154 -9
  242. package/dist-lib/spec/hrpc/messages.js +549 -129
  243. package/dist-lib/spec/hyperschema/index.js +549 -129
  244. package/dist-lib/spec/hyperschema/schema.json +370 -40
  245. package/dist-lib/spec/hyperschema/types.d.ts +85 -1
  246. package/dist-lib/spec/local/hyperdb/db.json +15 -0
  247. package/dist-lib/spec/local/hyperdb/index.js +70 -1
  248. package/dist-lib/spec/local/hyperdb/messages.js +300 -117
  249. package/dist-lib/spec/local/hyperschema/index.js +97 -4
  250. package/dist-lib/spec/local/hyperschema/schema.json +58 -1
  251. package/dist-lib/spec/local/hyperschema/types.d.ts +14 -0
  252. package/dist-lib/spec/mesh/hyperdb/messages.js +393 -288
  253. package/dist-lib/spec/mesh/hyperdispatch/dispatch.json +6 -0
  254. package/dist-lib/spec/mesh/hyperdispatch/index.js +18 -1
  255. package/dist-lib/spec/mesh/hyperdispatch/messages.js +176 -85
  256. package/dist-lib/spec/mesh/hyperschema/index.js +176 -85
  257. package/dist-lib/spec/mesh/hyperschema/schema.json +71 -21
  258. package/dist-lib/spec/mesh/hyperschema/types.d.ts +14 -1
  259. package/package.json +16 -10
  260. package/tui/README.md +7 -0
  261. package/tui/app.mjs +311 -14
  262. package/tui/lib/busy-words.mjs +57 -5
  263. package/tui/lib/export.mjs +1 -0
  264. package/tui/lib/render.mjs +9 -2
  265. package/tui/main.mjs +5 -2
@@ -5,293 +5,51 @@ import fs from 'fs';
5
5
  import crypto from 'hypercore-crypto';
6
6
  import os from 'os';
7
7
  import path from 'path';
8
- import { attachmentTurn, skillLoadedTurn } from '@qvac/harness/lib/capabilities/tool-turns.ts';
9
- import { diffusionDownloadName, mediaModelNameFor } from '@qvac/harness/lib/models/model-catalog.ts';
10
- import { readSetup as normalizeSkillSetup } from '@qvac/harness/lib/tools/skills/manifest-parse.ts';
8
+ import { mediaModelNameFor } from '@qvac/harness/lib/models/model-catalog.ts';
9
+ import { connectHarness } from '@qvac/harness';
10
+ import { loanFailureNotice } from './core/harness-loan.js';
11
11
  import { SKILL_STATE } from '@qvac/harness/lib/tools/skills/skill-state.ts';
12
12
  import { toolsetEnabled } from '@qvac/harness/lib/tools/toolsets.ts';
13
13
  import { RAG_CITATION_LINE } from '@qvac/harness/lib/prompt.ts';
14
- import { acceptedRepairCount, historyBranches, isPromptChunk } from "./core/prompt-history.js";
14
+ import { acceptedRepairCount, historyBranches, isPromptChunk } from './core/prompt-history.js';
15
15
  import ReadyGuard from 'ready-guard';
16
16
  import ReadyResource from 'ready-resource';
17
17
  import { local } from '../spec/index.js';
18
- import { isMeshTransition } from "./api/current-mesh.js";
19
- import { buildTitlePrompt, deriveChatTitle, isDefaultChatTitle, parseTitleResponse } from "./chat-title.js";
20
- import { matchApprovalRule } from "./core/approval-rules.js";
21
- import { attachTurnDocumentIds, groupAttachmentsByMessage, 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";
22
- import { isAudioAttachment } from "./core/audio-attachment.js";
23
- import { annotateDocumentAttachments, documentUnreadNotice, documentUnreadReason, isDocumentAttachment } from "./core/document-attachment.js";
24
- import { HISTORY_CHUNK_TYPES } from "./core/chunk.js";
25
- import { imageCacheName, sweepImageCache } from "./core/image/cache-sweep.js";
26
- import { IMAGE_MIMES, normalizeImageForModel } from "./core/image/normalize.js";
27
- import { summarizeRuns } from "./diagnostics.js";
28
- import { resolveFsGrants } from "./fs-drive-bridge.js";
29
- import { fsGrantKey, fsWriteGrantKey } from "./fs-grant-keys.js";
30
- import { fsGrantsFrom, grantedDirsFrom } from "./fs-grants.js";
31
- import { defaultImageCacheDir } from "./image-cache-dir.js";
32
- import { ModelCatalogRevisionHub } from "./model-catalog-revision.js";
33
- import { agentRekeyFingerprint, chatKvCacheKey, chatRepairKvCacheKey, disappearedChatIds } from "./kv-cache-reclaim.js";
34
- import { buildCompactionPrompt, canCompact, foldReducesPrompt, COMPACTION_KEEP_TURNS, COMPACTION_TURN_PREFIX, isContextOverflowFailure, nearContextLimit, compactionBoundary, compactionTurn, foldCompactedChunks, lastCompactedThroughId, parseCompactionSummary } from "./compaction.js";
35
- import { isMobilePlatform, runnableModelName } from "./model-clamp.js";
36
- import { ModelDownloadReconciler } from "./model-download.js";
18
+ import { isMeshTransition } from './api/current-mesh.js';
19
+ import { meshScoped } from './mesh-scoped-engine.js';
20
+ import { buildTitlePrompt, deriveChatTitle, isDefaultChatTitle, parseTitleResponse } from './chat-title.js';
21
+ import { matchApprovalRule } from './core/approval-rules.js';
22
+ import { isAudioAttachment } from './core/audio-attachment.js';
23
+ 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';
24
+ import { annotateDocumentAttachments, documentUnreadNotice, documentUnreadReason } from './core/document-attachment.js';
25
+ import { imageCacheName, sweepImageCache } from './core/image/cache-sweep.js';
26
+ import { IMAGE_MIMES, normalizeImageForModel } from './core/image/normalize.js';
27
+ import { summarizeRuns } from './diagnostics.js';
28
+ import { resolveFsGrants } from './fs-drive-bridge.js';
29
+ import { fsGrantKey, fsWriteGrantKey } from './fs-grant-keys.js';
30
+ import { fsGrantsFrom, grantedDirsFrom } from './fs-grants.js';
31
+ import { defaultImageCacheDir } from './image-cache-dir.js';
32
+ import { ModelCatalogRevisionHub } from './model-catalog-revision.js';
33
+ import { agentRekeyFingerprint, chatKvCacheKey, chatRepairKvCacheKey, disappearedChatIds } from './kv-cache-reclaim.js';
34
+ import { buildCompactionPrompt, canCompact, foldReducesPrompt, COMPACTION_KEEP_TURNS, COMPACTION_TURN_PREFIX, isContextOverflowFailure, nearContextLimit, compactionBoundary, lastCompactedThroughId, parseCompactionSummary } from './compaction.js';
35
+ import { isMobilePlatform, runnableModelName } from './model-clamp.js';
36
+ import { ModelDownloadReconciler } from './model-download.js';
37
37
  import { AbortedError, raceAbort } from '@qvac/harness/race-abort';
38
- import { RunTranscript } from "./run-transcript.js";
39
- import { searchKnowledge } from "./knowledge-search.js";
40
- import { isLifecycleTeardown, knownAbortOutcome, RUN_ABORT_REASONS, RUN_FAILURE_REASONS, runFailureNotice } from "./run-notices.js";
41
- import { encodeAgentSkillReadiness } from "./skill-readiness.js";
38
+ import { RunTranscript } from './run-transcript.js';
39
+ import { searchKnowledge } from './knowledge-search.js';
40
+ import { isLifecycleTeardown, knownAbortOutcome, RUN_ABORT_REASONS, RUN_FAILURE_REASONS, runFailureNotice } from './run-notices.js';
41
+ import { encodeAgentSkillReadiness } from './skill-readiness.js';
42
+ import { harnessClearKvCache, harnessDeathReason, harnessDeleteModel, harnessDied, harnessListModels, harnessSkillCatalog, harnessSkillManagement, harnessSpeak, harnessSpeakStream, harnessTools, harnessTranscribe, imageDownloadProgress, modelCatalogChanged, toolReportEntry } from './assistant/harness.js';
43
+ import { annotateUnreadableImages, audioTranscriptBlock, backfillDocumentOnlyTurn, backfillImageOnlyTurns, silentAudioNotice, unheardAudioNotice } from './assistant/message.js';
44
+ import { drainBody, raceInactivity } from './assistant/fetch-body.js';
45
+ import { GENERIC_ACKNOWLEDGEMENTS, HISTORY_TYPES, SKILL_TOOL, TERMINAL_STATES, historyFromChunks, inputAvailableToRun, listHistoryChunks, staleToolRunIds, withoutOccupancy } from './assistant/history.js';
46
+ export { harnessClearKvCache, harnessDeleteModel, harnessListModels, harnessSkillCatalog, harnessSkillManagement, harnessSpeak, harnessSpeakStream, harnessTools, harnessTranscribe } from './assistant/harness.js';
47
+ export {} from './assistant/skill-encode.js';
48
+ export { annotateUnreadableImages, unheardAudioNotice, unreadableImagesNotice, DOCUMENT_ONLY_USER_PROMPT, IMAGE_AND_DOCUMENT_USER_PROMPT, IMAGE_ONLY_USER_PROMPT } from './assistant/message.js';
49
+ export { historyFromChunks, listHistoryChunks, staleToolRunIds } from './assistant/history.js';
42
50
  const QvacState = local.getEnum('@local/qvac-state');
43
- export const IMAGE_ONLY_USER_PROMPT = 'The user sent one or more images without any accompanying text. Describe what the images show and respond to anything notable in them.';
44
- export const DOCUMENT_ONLY_USER_PROMPT = 'The user sent one or more documents without any accompanying text. Summarize the attached documents.';
45
- export const IMAGE_AND_DOCUMENT_USER_PROMPT = 'The user sent one or more images together with one or more documents, and no accompanying text. Describe what the images show and summarize the attached documents.';
46
- function backfillDocumentOnlyTurn(messages) {
47
- const last = messages.findLast((turn) => turn.role === 'user');
48
- if (!last || last.content.trim())
49
- return;
50
- last.content = last.attachments?.length
51
- ? IMAGE_AND_DOCUMENT_USER_PROMPT
52
- : DOCUMENT_ONLY_USER_PROMPT;
53
- }
54
- function backfillImageOnlyTurns(messages) {
55
- for (const turn of messages) {
56
- if (turn.role !== 'user' || turn.content.trim())
57
- continue;
58
- if (turn.attachments?.length)
59
- turn.content = IMAGE_ONLY_USER_PROMPT;
60
- }
61
- }
62
- export function unreadableImagesNotice(fileNames) {
63
- const plural = fileNames.length > 1;
64
- return (`[Attached image${plural ? 's' : ''}: ${fileNames.join(', ')} — could not be read, so ` +
65
- `${plural ? 'they are' : 'it is'} not visible to you. Tell the user the upload failed and ` +
66
- `ask for a re-upload; never describe or recreate ${plural ? 'them' : 'it'}]`);
67
- }
68
- export function annotateUnreadableImages(unreadable) {
69
- for (const [turn, names] of unreadable) {
70
- const notice = unreadableImagesNotice(names);
71
- turn.content = turn.content ? `${turn.content}\n${notice}` : notice;
72
- }
73
- }
74
- async function raceInactivity(promise, signal, timeoutMs) {
75
- let timer = null;
76
- const expired = new Promise((_, reject) => {
77
- timer = setTimeout(() => reject(new Error('blob read timed out')), timeoutMs);
78
- });
79
- try {
80
- return await raceAbort(Promise.race([promise, expired]), signal);
81
- }
82
- finally {
83
- if (timer !== null)
84
- clearTimeout(timer);
85
- }
86
- }
87
- async function drainBody(body, signal, timeoutMs) {
88
- if (!body)
89
- return null;
90
- const reader = body.getReader();
91
- const parts = [];
92
- try {
93
- for (;;) {
94
- const read = await raceInactivity(reader.read(), signal, timeoutMs);
95
- if (read.done)
96
- break;
97
- parts.push(b4a.from(read.value));
98
- }
99
- }
100
- catch {
101
- await reader.cancel();
102
- return null;
103
- }
104
- return b4a.concat(parts);
105
- }
106
- export function unheardAudioNotice(label, reason, opts = {}) {
107
- const retry = opts.retryable === false ? '' : ', and ask them to try again';
108
- return (`${label} could not be transcribed (${reason}). Tell the user the audio was not ` +
109
- `transcribed and why${retry}; never invent what it might contain.`);
110
- }
111
- function silentAudioNotice(fileName) {
112
- return (`Attached audio "${fileName}" was transcribed and contained no detectable speech. ` +
113
- 'Tell the user; never invent what it might contain.');
114
- }
115
- function audioTranscriptBlock(fileName, transcript) {
116
- return [
117
- `The audio file "${fileName}" has already been transcribed on-device. You cannot open the file itself — use the transcript below as its full content and answer from it.`,
118
- 'Transcript:',
119
- transcript
120
- ].join('\n');
121
- }
122
- export function harnessListModels(harness) {
123
- return async ({ type, cachedOnly, fullRegistry } = {}) => ({
124
- models: [
125
- ...((await harness.list?.({
126
- type: type ?? undefined,
127
- cachedOnly: cachedOnly ?? undefined,
128
- fullRegistry: fullRegistry ?? undefined
129
- })) ?? [])
130
- ]
131
- });
132
- }
133
- export function harnessDeleteModel(harness) {
134
- return async ({ name }) => (await harness.deleteModel?.(name)) ?? { name, removed: 0, freedBytes: 0 };
135
- }
136
- export function harnessClearKvCache(harness) {
137
- return async () => (await harness.clearKvCache?.()) ?? {
138
- status: 'unsupported',
139
- error: 'Harness does not support KV cache deletion'
140
- };
141
- }
142
- export function harnessTranscribe(harness) {
143
- return async ({ audio, model }) => {
144
- if (!harness.transcribe)
145
- throw new Error('harness does not support transcribe');
146
- return { text: await harness.transcribe({ audio, model: model ?? '' }) };
147
- };
148
- }
149
- export function harnessSpeak(harness) {
150
- return async ({ text, model }) => {
151
- if (!harness.speak)
152
- throw new Error('harness does not support speak');
153
- const { audio, sampleRate } = await harness.speak({ text, model: model ?? '' });
154
- return { audio, sampleRate };
155
- };
156
- }
157
- export function harnessSkillCatalog(harness, syncCredentials) {
158
- return async (agentId, modelName, options) => {
159
- if (options?.refresh)
160
- await syncCredentials?.();
161
- return {
162
- skills: ((await harness.skills?.(agentId, modelName, options)) ?? []).map(toEngineSkill)
163
- };
164
- };
165
- }
166
- export function harnessSkillManagement(harness) {
167
- return {
168
- async listManagedSkills() {
169
- return {
170
- skills: ((await harness.listManagedSkills?.()) ?? []).map((skill) => ({
171
- name: skill.name,
172
- origin: skill.origin,
173
- overridesBase: skill.overridesBase
174
- }))
175
- };
176
- },
177
- async readSkillFile(name) {
178
- const file = await harness.readSkillFile?.(name);
179
- return file ? { found: true, content: file.content, origin: file.origin } : { found: false };
180
- },
181
- async writeSkillFile(name, content) {
182
- if (!harness.writeSkillFile)
183
- return { ok: false };
184
- return harness.writeSkillFile(name, content);
185
- },
186
- async copySkillForEdit(name) {
187
- return { copied: (await harness.copyBaseForEdit?.(name))?.copied ?? false };
188
- },
189
- async deleteOverlaySkill(name) {
190
- return { removed: (await harness.deleteOverlaySkill?.(name))?.removed ?? false };
191
- }
192
- };
193
- }
194
- export function harnessTools(harness) {
195
- return async () => ({
196
- tools: ((await harness.tools?.()) ?? []).map((tool) => ({
197
- ...toolReportEntry(tool),
198
- description: tool.description
199
- }))
200
- });
201
- }
202
- function toolReportEntry(tool) {
203
- return {
204
- name: tool.name,
205
- promptChars: tool.promptChars ?? 0,
206
- toolset: tool.toolset ?? null,
207
- skillGated: tool.skillGated === true,
208
- scopeRequired: tool.scopeRequired === true,
209
- rootsRequired: tool.rootsRequired === true,
210
- writeRootsRequired: tool.writeRootsRequired === true
211
- };
212
- }
213
- export function harnessSpeakStream(harness) {
214
- return async function* (text) {
215
- if (!harness.speakStream)
216
- throw new Error('harness does not support speakStream');
217
- for await (const { audio, sampleRate } of harness.speakStream({ model: '', text })) {
218
- yield { audio, sampleRate };
219
- }
220
- };
221
- }
222
- function toEngineSkill(skill) {
223
- const setup = normalizeSkillSetup(skill.setup);
224
- return {
225
- name: skill.name,
226
- description: skill.description,
227
- tools: [...skill.tools],
228
- credentials: [...skill.credentials],
229
- allowList: [...skill.allowList],
230
- platforms: [...skill.platform],
231
- status: skill.status,
232
- ...(skill.requires ? { requirements: toEngineSkillRequirements(skill.requires) } : {}),
233
- ...(skill.install ? { install: skill.install.map(toEngineInstallStep) } : {}),
234
- ...(setup ? { setup: toEngineSkillSetup(setup) } : {}),
235
- ...(skill.stub !== undefined ? { stub: skill.stub } : {}),
236
- ...(skill.minCapabilityProfile ? { minCapabilityProfile: skill.minCapabilityProfile } : {}),
237
- ...(skill.emoji ? { emoji: skill.emoji } : {})
238
- };
239
- }
240
- function toEngineSkillRequirements(requires) {
241
- return {
242
- binaries: (requires.bins ?? []).map((bin) => ({
243
- bin,
244
- minVersion: requires.binMinVersions?.[bin]?.min,
245
- command: requires.binMinVersions?.[bin]?.command
246
- })),
247
- credentials: [...(requires.credentials ?? [])]
248
- };
249
- }
250
- function toEngineInstallStep(step) {
251
- return {
252
- id: step.id,
253
- kind: step.kind,
254
- label: step.label,
255
- ...(step.formula ? { formula: step.formula } : {}),
256
- ...(step.command ? { command: step.command } : {}),
257
- ...(step.manual !== undefined ? { manual: step.manual } : {}),
258
- ...(step.bins ? { bins: [...step.bins] } : {})
259
- };
260
- }
261
- function toEngineSkillSetup(setup) {
262
- return {
263
- ...(setup.summary ? { summary: setup.summary } : {}),
264
- ...(setup.routes
265
- ? {
266
- routes: setup.routes.map((route) => ({
267
- kind: route.kind,
268
- label: route.label,
269
- ...(route.provider ? { provider: route.provider } : {}),
270
- ...(route.credentialKey ? { credentialKey: route.credentialKey } : {}),
271
- ...(route.description ? { description: route.description } : {}),
272
- ...(route.helpUrl ? { helpUrl: route.helpUrl } : {}),
273
- ...(route.steps ? { steps: [...route.steps] } : {}),
274
- ...(route.configSteps ? { configSteps: [...route.configSteps] } : {}),
275
- ...(route.fields
276
- ? {
277
- fields: route.fields.map((field) => ({
278
- key: field.key,
279
- label: field.label,
280
- ...(field.placeholder ? { placeholder: field.placeholder } : {}),
281
- ...(field.secret !== undefined ? { secret: field.secret } : {}),
282
- ...(field.required !== undefined ? { required: field.required } : {})
283
- }))
284
- }
285
- : {}),
286
- ...(route.satisfied !== undefined ? { satisfied: route.satisfied } : {})
287
- }))
288
- }
289
- : {})
290
- };
291
- }
292
51
  const FINAL_FLUSH_MS = 10_000;
293
52
  const UPLOAD_FRAME_BYTES = 64 * 1024;
294
- const TERMINAL_STATES = new Set(['completed', 'failed', 'canceled']);
295
53
  function settledWithin(write, ms) {
296
54
  let timer;
297
55
  const expired = new Promise((resolve) => {
@@ -316,8 +74,6 @@ const OWNERSHIP_LOST = RUN_ABORT_REASONS.ownershipLost;
316
74
  const RUN_SETTLED = RUN_ABORT_REASONS.runSettled;
317
75
  const RUNNER_DIED = RUN_ABORT_REASONS.runnerDied;
318
76
  const RUNNER_CLOSED = RUN_ABORT_REASONS.runnerClosed;
319
- const HISTORY_TYPES = HISTORY_CHUNK_TYPES;
320
- const SKILL_TOOL = 'skill';
321
77
  function isSetUpHere(status) {
322
78
  return status === SKILL_STATE.ready || status === SKILL_STATE.incompatibleModel;
323
79
  }
@@ -329,229 +85,11 @@ function withConfigDefaults(agent, config) {
329
85
  return agent;
330
86
  return { ...agent, ctxSize: config.ctxSize };
331
87
  }
332
- export async function listHistoryChunks(engine, chatId) {
333
- const [history, toolResults, runStatuses] = await Promise.all([
334
- engine.listChunks({ chatId, types: HISTORY_TYPES }),
335
- engine.listChunks({ chatId, type: 'tool-result' }),
336
- engine.listChunks({ chatId, type: 'run-status' })
337
- ]);
338
- return [
339
- ...(history.chunks ?? []),
340
- ...(toolResults.chunks ?? []),
341
- ...(runStatuses.chunks ?? [])
342
- ].sort((a, b) => a.seq - b.seq);
343
- }
344
- function latestAttemptStarts(chunks) {
345
- const starts = new Map();
346
- for (const chunk of chunks) {
347
- if (chunk.type !== 'run-status' || !chunk.runId)
348
- continue;
349
- if (TERMINAL_STATES.has(chunk.runStatus?.state ?? ''))
350
- continue;
351
- starts.set(chunk.runId, chunk.seq);
352
- }
353
- return starts;
354
- }
355
- function beforeLatestAttempt(chunk, starts) {
356
- if (!chunk.runId)
357
- return false;
358
- const start = starts.get(chunk.runId);
359
- return start !== undefined && chunk.seq < start;
360
- }
361
- export function historyFromChunks(chunks, stale = {}) {
362
- const attemptStarts = latestAttemptStarts(chunks);
363
- const staleRunIds = stale.runIds ?? new Set();
364
- const staleQuestionChunkIds = stale.questionChunkIds ?? new Set();
365
- const folded = foldCompactedChunks(chunks);
366
- const source = folded.chunks;
367
- const attachments = [];
368
- const userMessages = [];
369
- for (const chunk of source) {
370
- if (chunk.type === 'attachment')
371
- attachments.push(chunk);
372
- else if (chunk.userMessage)
373
- userMessages.push(chunk);
374
- }
375
- const byMessage = groupAttachmentsByMessage(attachments, userMessages);
376
- const history = [];
377
- const replayedSkills = new Set();
378
- if (folded.summary)
379
- history.push({ role: 'user', content: compactionTurn(folded.summary) });
380
- const byRun = new Map();
381
- const anchor = (runId) => {
382
- let turn = byRun.get(runId);
383
- if (!turn) {
384
- turn = { role: 'assistant', content: '' };
385
- byRun.set(runId, turn);
386
- history.push(turn);
387
- }
388
- return turn;
389
- };
390
- for (const chunk of source) {
391
- if (chunk.userMessage) {
392
- if (staleQuestionChunkIds.has(chunk.id))
393
- continue;
394
- const turn = { role: 'user', content: chunk.userMessage.text };
395
- const refs = (byMessage.get(chunk.id) ?? [])
396
- .map((attachmentChunk) => attachmentChunk.attachment)
397
- .filter((ref) => !ref.deletedAt);
398
- const images = refs.filter((ref) => IMAGE_MIMES.has(ref.mimeType.toLowerCase()));
399
- const audio = refs.filter((ref) => isAudioAttachment(ref.fileName, ref.mimeType));
400
- const documents = refs.filter((ref) => isDocumentAttachment(ref));
401
- if (images.length)
402
- turn.images = images;
403
- if (audio.length)
404
- turn.audioAttachments = audio;
405
- if (documents.length)
406
- turn.documents = documents;
407
- history.push(turn);
408
- continue;
409
- }
410
- if (chunk.attachment)
411
- continue;
412
- if (chunk.type === 'run-request' && chunk.runId) {
413
- anchor(chunk.runId);
414
- continue;
415
- }
416
- if (chunk.toolResult?.name === SKILL_TOOL) {
417
- if (chunk.runId && staleRunIds.has(chunk.runId))
418
- continue;
419
- if (beforeLatestAttempt(chunk, attemptStarts))
420
- continue;
421
- const loaded = chunk.toolResult.result?.name;
422
- if (typeof loaded === 'string' && !replayedSkills.has(loaded)) {
423
- replayedSkills.add(loaded);
424
- const at = history.indexOf(anchor(chunk.runId)) + 1;
425
- history.splice(at, 0, { role: 'tool', content: skillLoadedTurn(loaded) });
426
- }
427
- continue;
428
- }
429
- if (chunk.toolResult) {
430
- if (chunk.runId && staleRunIds.has(chunk.runId))
431
- continue;
432
- if (beforeLatestAttempt(chunk, attemptStarts))
433
- continue;
434
- const produced = attachmentTurn(chunk.toolResult.name, chunk.toolResult.result);
435
- if (produced)
436
- history.push({ role: 'tool', content: produced });
437
- continue;
438
- }
439
- if (!chunk.content)
440
- continue;
441
- if (chunk.runId && staleRunIds.has(chunk.runId))
442
- continue;
443
- if (beforeLatestAttempt(chunk, attemptStarts))
444
- continue;
445
- anchor(chunk.runId).content += chunk.content.text;
446
- }
447
- return history.filter((turn) => turn.role === 'user' || turn.content.length > 0);
448
- }
449
- function withoutOccupancy(metrics) {
450
- if (!metrics)
451
- return metrics;
452
- const { cacheTokens, promptTokens, ...rest } = metrics;
453
- return rest;
454
- }
455
- function inputAvailableToRun(chunk, requestSeq) {
456
- const userInput = Boolean(chunk.userMessage || (chunk.attachment && !chunk.runId));
457
- return !userInput || chunk.seq < requestSeq;
458
- }
459
- function normalizeQuestion(text) {
460
- return text.trim().toLowerCase().replace(/\s+/g, ' ');
461
- }
462
- const GENERIC_ACKNOWLEDGEMENTS = new Set([
463
- 'yes',
464
- 'y',
465
- 'yeah',
466
- 'yep',
467
- 'yup',
468
- 'ok',
469
- 'okay',
470
- 'k',
471
- 'sure',
472
- 'fine',
473
- 'no',
474
- 'n',
475
- 'nope',
476
- 'nah',
477
- 'again',
478
- 'continue',
479
- 'go on',
480
- 'go ahead',
481
- 'keep going',
482
- 'proceed',
483
- 'do it',
484
- 'more',
485
- 'please',
486
- 'thanks',
487
- 'thank you',
488
- 'retry',
489
- 'redo'
490
- ]);
491
- function isGenericAcknowledgement(question) {
492
- return GENERIC_ACKNOWLEDGEMENTS.has(question.replace(/[?.!]+$/, '').trim());
493
- }
494
- export function staleToolRunIds(historyChunks, approvalChunks, currentRunId) {
495
- const empty = { runIds: new Set(), questionChunkIds: new Set() };
496
- const toolRuns = new Set();
497
- for (const chunk of approvalChunks) {
498
- if (chunk.runId)
499
- toolRuns.add(chunk.runId);
500
- }
501
- if (!toolRuns.size)
502
- return empty;
503
- const turnOrder = [];
504
- const turnText = new Map();
505
- const turnRuns = new Map();
506
- const runChunk = new Map();
507
- let lastUser = null;
508
- for (const chunk of historyChunks) {
509
- if (chunk.userMessage) {
510
- lastUser = { text: chunk.userMessage.text, chunkId: chunk.id };
511
- continue;
512
- }
513
- if (chunk.type === 'run-request' && chunk.runId && lastUser !== null) {
514
- const chunkId = lastUser.chunkId;
515
- if (!turnText.has(chunkId)) {
516
- turnOrder.push(chunkId);
517
- turnText.set(chunkId, lastUser.text);
518
- }
519
- turnRuns.set(chunkId, [...(turnRuns.get(chunkId) ?? []), chunk.runId]);
520
- runChunk.set(chunk.runId, chunkId);
521
- }
522
- }
523
- const currentChunkId = runChunk.get(currentRunId) ?? lastUser?.chunkId;
524
- if (currentChunkId === undefined)
525
- return empty;
526
- const currentText = turnText.get(currentChunkId) ?? lastUser?.text;
527
- if (currentText === undefined)
528
- return empty;
529
- const target = normalizeQuestion(currentText);
530
- if (isGenericAcknowledgement(target))
531
- return empty;
532
- const currentIndex = turnOrder.indexOf(currentChunkId);
533
- const start = currentIndex === -1 ? turnOrder.length - 1 : currentIndex - 1;
534
- const runIds = new Set();
535
- const questionChunkIds = new Set();
536
- let blockHadApproval = false;
537
- for (let i = start; i >= 0; i--) {
538
- const chunkId = turnOrder[i];
539
- if (normalizeQuestion(turnText.get(chunkId)) !== target)
540
- break;
541
- questionChunkIds.add(chunkId);
542
- for (const rid of turnRuns.get(chunkId) ?? []) {
543
- runIds.add(rid);
544
- if (toolRuns.has(rid))
545
- blockHadApproval = true;
546
- }
547
- }
548
- if (!blockHadApproval)
549
- return empty;
550
- return { runIds, questionChunkIds };
551
- }
552
88
  export class QvacAssistant extends ReadyResource {
553
89
  _engine;
554
90
  _harness;
91
+ _borrowHarness;
92
+ _borrowed = new Map();
555
93
  _log;
556
94
  _imageCacheDir;
557
95
  _imageCacheMaxBytes;
@@ -581,12 +119,15 @@ export class QvacAssistant extends ReadyResource {
581
119
  _harnessDeath;
582
120
  _refreshingDiagnostics;
583
121
  _requests;
122
+ _meshList;
584
123
  _retry;
585
124
  _retryMs = CONSUME_RETRY_MS;
586
125
  _chatList;
587
126
  _agentList;
588
127
  _chatListWatch;
589
128
  _agentWatch;
129
+ _meshListWatch;
130
+ _runConsumers;
590
131
  _runs;
591
132
  _seen;
592
133
  _lifecycle;
@@ -597,10 +138,11 @@ export class QvacAssistant extends ReadyResource {
597
138
  _modelCatalog = new ModelCatalogRevisionHub();
598
139
  _onHarnessStatus;
599
140
  _onModelCatalogEvent;
600
- constructor(engine, harness, { logger = null, imageCacheDir, imageCacheMaxBytes, imageCacheMaxAgeMs, downloadRetryMs, platform = os.platform(), preloadCurrentAgentModel = true, drives, blobReadTimeoutMs = BLOB_READ_TIMEOUT_MS } = {}) {
141
+ constructor(engine, harness, { logger = null, imageCacheDir, imageCacheMaxBytes, imageCacheMaxAgeMs, downloadRetryMs, platform = os.platform(), preloadCurrentAgentModel = true, drives, borrowHarness, blobReadTimeoutMs = BLOB_READ_TIMEOUT_MS } = {}) {
601
142
  super();
602
143
  this._engine = engine;
603
144
  this._harness = harness;
145
+ this._borrowHarness = borrowHarness ?? null;
604
146
  this._drives = drives;
605
147
  this._log = logger;
606
148
  this._imageCacheDir = imageCacheDir ?? defaultImageCacheDir();
@@ -623,13 +165,16 @@ export class QvacAssistant extends ReadyResource {
623
165
  this._harnessDeath = null;
624
166
  this._refreshingDiagnostics = false;
625
167
  this._requests = null;
168
+ this._meshList = null;
626
169
  this._retry = null;
627
170
  this._chatList = null;
628
171
  this._agentList = null;
629
172
  this._chatListWatch = this._rearmingWatch('chat-list', () => this._watchChatList());
630
173
  this._agentWatch = this._rearmingWatch('agent', () => this._watchAgents());
174
+ this._meshListWatch = this._rearmingWatch('mesh-list', () => this._watchMeshList());
175
+ this._runConsumers = new Map();
631
176
  this._runs = new Map();
632
- this._seen = new Set();
177
+ this._seen = new Map();
633
178
  this._lifecycle = new AbortController();
634
179
  this._audioTranscripts = new Map();
635
180
  this._chats = new Map();
@@ -684,6 +229,7 @@ export class QvacAssistant extends ReadyResource {
684
229
  this._startConsume();
685
230
  this._chatListWatch.start();
686
231
  this._agentWatch.start();
232
+ this._meshListWatch.start();
687
233
  void this._bootOnline();
688
234
  this._triggerModelWarm();
689
235
  void this.onlineReady().then(() => this._triggerModelWarm(), noop);
@@ -973,6 +519,7 @@ export class QvacAssistant extends ReadyResource {
973
519
  clearTimeout(this._retry);
974
520
  this._chatListWatch.stop();
975
521
  this._agentWatch.stop();
522
+ this._stopMeshIntake();
976
523
  this._harness.off?.('status', this._onHarnessStatus);
977
524
  this._harness.off?.('model', this._onModelCatalogEvent);
978
525
  this._warmAbort.abort(RUNNER_CLOSED);
@@ -982,6 +529,7 @@ export class QvacAssistant extends ReadyResource {
982
529
  await this._downloads?.close();
983
530
  this._modelCatalog.close();
984
531
  await this._requests?.return?.();
532
+ await this._meshList?.return?.();
985
533
  await this._chatList?.return?.();
986
534
  await this._agentList?.return?.();
987
535
  this._lifecycle.abort(RUNNER_CLOSED);
@@ -1008,8 +556,10 @@ export class QvacAssistant extends ReadyResource {
1008
556
  clearTimeout(this._retry);
1009
557
  this._chatListWatch.stop();
1010
558
  this._agentWatch.stop();
559
+ this._stopMeshIntake();
1011
560
  await this._downloads?.suspend();
1012
561
  await this._requests?.return?.();
562
+ await this._meshList?.return?.();
1013
563
  await this._chatList?.return?.();
1014
564
  await this._agentList?.return?.();
1015
565
  for (const run of this._runs.values())
@@ -1044,6 +594,7 @@ export class QvacAssistant extends ReadyResource {
1044
594
  this._startConsume();
1045
595
  this._chatListWatch.start();
1046
596
  this._agentWatch.start();
597
+ this._meshListWatch.start();
1047
598
  }
1048
599
  }
1049
600
  async listModels(options) {
@@ -1118,8 +669,9 @@ export class QvacAssistant extends ReadyResource {
1118
669
  _rearmingWatch(label, run) {
1119
670
  let retryMs = CONSUME_RETRY_MS;
1120
671
  let timer = null;
672
+ let stopped = false;
1121
673
  const rearm = (err) => {
1122
- if (this.closing || this.suspended)
674
+ if (stopped || this.closing || this.suspended)
1123
675
  return;
1124
676
  if (err !== null && !isMeshTransition(err)) {
1125
677
  this._log?.error('assistant', `${label} watch failed — restarting`, err);
@@ -1129,11 +681,13 @@ export class QvacAssistant extends ReadyResource {
1129
681
  timer = setTimeout(start, delay);
1130
682
  };
1131
683
  const start = () => {
684
+ stopped = false;
1132
685
  run().then(() => rearm(null), (err) => rearm(err));
1133
686
  };
1134
687
  return {
1135
688
  start,
1136
689
  stop: () => {
690
+ stopped = true;
1137
691
  if (timer)
1138
692
  clearTimeout(timer);
1139
693
  }
@@ -1191,9 +745,9 @@ export class QvacAssistant extends ReadyResource {
1191
745
  this._log?.warn('assistant', 'agent re-key cache reclaim failed', { agentId, err });
1192
746
  }
1193
747
  }
1194
- async _reconcileCompaction(chatId) {
748
+ async _reconcileCompaction(engine, chatId) {
1195
749
  const deviceId = this._deviceId;
1196
- const { chunks } = await this._engine
750
+ const { chunks } = await engine
1197
751
  .listChunks({ chatId, type: 'compaction' })
1198
752
  .catch(() => ({ chunks: [] }));
1199
753
  let newest = null;
@@ -1260,32 +814,116 @@ export class QvacAssistant extends ReadyResource {
1260
814
  const requests = value.chunks ?? [];
1261
815
  for (const chunk of requests)
1262
816
  this._dispatch(chunk);
1263
- const live = new Set(requests.map((c) => c.runId));
1264
- for (const id of this._seen)
1265
- if (!live.has(id))
1266
- this._seen.delete(id);
817
+ this._pruneSeen(null, new Set(requests.map((c) => c.runId)));
818
+ }
819
+ }
820
+ async _watchMeshList() {
821
+ const stream = this._engine.meshesWatch({});
822
+ this._meshList = stream[Symbol.asyncIterator]();
823
+ while (true) {
824
+ const { value, done } = await this._meshList.next();
825
+ if (done || this.closing || this.suspended)
826
+ return;
827
+ this._syncRunConsumers(value.meshes ?? []);
828
+ }
829
+ }
830
+ _syncRunConsumers(meshes) {
831
+ const background = new Set(meshes.filter((mesh) => mesh.open && !mesh.active).map((mesh) => mesh.meshId));
832
+ for (const [meshId, consumer] of this._runConsumers) {
833
+ if (background.has(meshId))
834
+ continue;
835
+ consumer.stop();
836
+ this._runConsumers.delete(meshId);
837
+ }
838
+ for (const meshId of background) {
839
+ if (this._runConsumers.has(meshId))
840
+ continue;
841
+ const consumer = this._meshRunConsumer(meshId);
842
+ this._runConsumers.set(meshId, consumer);
843
+ consumer.start();
1267
844
  }
1268
845
  }
1269
- _dispatch(request) {
846
+ _meshRunConsumer(meshId) {
847
+ let requests = null;
848
+ const watch = this._rearmingWatch(`run-requests:${meshId}`, async () => {
849
+ const stream = this._engine.runRequestsWatch({ meshId });
850
+ requests = stream[Symbol.asyncIterator]();
851
+ while (true) {
852
+ const { value, done } = await requests.next();
853
+ if (done || this.closing || this.suspended)
854
+ return;
855
+ const chunks = value.chunks ?? [];
856
+ for (const chunk of chunks)
857
+ this._dispatch(chunk, meshId);
858
+ this._pruneSeen(meshId, new Set(chunks.map((chunk) => chunk.runId)));
859
+ }
860
+ });
861
+ return {
862
+ start: () => watch.start(),
863
+ stop: () => {
864
+ watch.stop();
865
+ void requests?.return?.();
866
+ }
867
+ };
868
+ }
869
+ _stopMeshIntake() {
870
+ this._meshListWatch.stop();
871
+ for (const consumer of this._runConsumers.values())
872
+ consumer.stop();
873
+ this._runConsumers.clear();
874
+ }
875
+ _pruneSeen(meshId, live) {
876
+ for (const [runId, from] of this._seen) {
877
+ if (from !== meshId || live.has(runId))
878
+ continue;
879
+ this._seen.delete(runId);
880
+ }
881
+ }
882
+ _lenderFor(agent) {
883
+ const lender = agent.lenderDeviceId;
884
+ if (!lender || !this._borrowHarness)
885
+ return null;
886
+ const id = lender.toString('hex');
887
+ return id === this._deviceId?.toString('hex') ? null : id;
888
+ }
889
+ _harnessFor(agent) {
890
+ const id = this._lenderFor(agent);
891
+ const borrow = this._borrowHarness;
892
+ if (!id || !borrow)
893
+ return this._harness;
894
+ const held = this._borrowed.get(id);
895
+ if (held)
896
+ return held;
897
+ const remote = connectHarness(() => borrow(id));
898
+ remote.on('status', ((status) => {
899
+ if (status.state === 'died')
900
+ this._borrowed.delete(id);
901
+ }));
902
+ const harness = remote;
903
+ this._borrowed.set(id, harness);
904
+ return harness;
905
+ }
906
+ _dispatch(request, meshId) {
1270
907
  const runId = request.runId;
1271
908
  if (!runId || this._runs.has(runId) || this._seen.has(runId))
1272
909
  return;
1273
- this._seen.add(runId);
910
+ this._seen.set(runId, meshId ?? null);
911
+ const engine = meshScoped(this._engine, meshId);
1274
912
  const settle = (async () => {
1275
913
  const agentId = request.runRequest?.agentId;
1276
- const agent = await this._engine.getAgent({ id: agentId }).catch(() => null);
914
+ const agent = await engine.getAgent({ id: agentId }).catch(() => null);
1277
915
  if (!agent) {
1278
916
  this._seen.delete(runId);
1279
917
  return;
1280
918
  }
1281
919
  if (!agent.providerDeviceId?.equals(this._deviceId))
1282
920
  return;
1283
- if (await this._isHandled(request))
921
+ if (await this._isHandled(engine, request))
1284
922
  return;
1285
923
  this._log?.info('runs', 'run claimed', { runId, chatId: request.chatId, agentId });
1286
924
  const controller = new AbortController();
1287
925
  const prior = this._chats.get(request.chatId) ?? Promise.resolve();
1288
- const done = prior.then(() => this._execute(request, agent, controller));
926
+ const done = prior.then(() => this._execute(request, agent, controller, meshId));
1289
927
  const link = done.catch(noop);
1290
928
  this._chats.set(request.chatId, link);
1291
929
  this._runs.set(runId, {
@@ -1320,7 +958,7 @@ export class QvacAssistant extends ReadyResource {
1320
958
  this._log?.warn('assistant', 'web sources chunk skipped', { runId, err });
1321
959
  }
1322
960
  }
1323
- async _searchKnowledge(chatId, messages, attachmentIds, signal, preparing) {
961
+ async _searchKnowledge(engine, chatId, messages, attachmentIds, signal, preparing) {
1324
962
  let lastUser;
1325
963
  for (let index = messages.length - 1; index >= 0; index--) {
1326
964
  if (messages[index].role === 'user') {
@@ -1332,7 +970,7 @@ export class QvacAssistant extends ReadyResource {
1332
970
  if (!lastUser || !query)
1333
971
  return null;
1334
972
  try {
1335
- const search = await searchKnowledge(this._engine, {
973
+ const search = await searchKnowledge(engine, {
1336
974
  chatId,
1337
975
  query,
1338
976
  attachmentIds: attachmentIds.length > 0 ? [...attachmentIds] : undefined
@@ -1350,14 +988,15 @@ export class QvacAssistant extends ReadyResource {
1350
988
  return null;
1351
989
  }
1352
990
  }
1353
- async _isHandled(request) {
1354
- const { chunks } = await this._engine.listChunks({
991
+ async _isHandled(engine, request) {
992
+ const { chunks } = await engine.listChunks({
1355
993
  chatId: request.chatId,
1356
994
  type: 'run-status'
1357
995
  });
1358
996
  return (chunks ?? []).some((c) => c.runId === request.runId && TERMINAL_STATES.has(c.runStatus?.state ?? ''));
1359
997
  }
1360
- async _execute(request, agent, controller) {
998
+ async _execute(request, agent, controller, meshId) {
999
+ const engine = meshScoped(this._engine, meshId);
1361
1000
  const { chatId } = request;
1362
1001
  const runId = request.runId;
1363
1002
  const deviceId = this._deviceId;
@@ -1365,16 +1004,19 @@ export class QvacAssistant extends ReadyResource {
1365
1004
  this._seen.delete(runId);
1366
1005
  return;
1367
1006
  }
1368
- if (await this._isHandled(request))
1007
+ if (await this._isHandled(engine, request))
1369
1008
  return;
1370
- const fresh = await this._engine.getAgent({ id: agent.id }).catch(() => null);
1009
+ const fresh = await engine.getAgent({ id: agent.id }).catch(() => null);
1371
1010
  if (!fresh || fresh.deletedAt || !fresh.providerDeviceId?.equals(deviceId))
1372
1011
  return;
1373
1012
  agent = fresh;
1374
- await this._reconcileCompaction(chatId);
1013
+ await this._reconcileCompaction(engine, chatId);
1375
1014
  if (request.parentId)
1376
1015
  await this._deleteChatKvCache(chatId, 'superseding run');
1377
- const model = runnableModelName(agent.modelName, await this._ensureCapability(), this._mobileClass);
1016
+ const lender = this._lenderFor(agent);
1017
+ const model = lender
1018
+ ? agent.modelName
1019
+ : runnableModelName(agent.modelName, await this._ensureCapability(), this._mobileClass);
1378
1020
  if (model !== agent.modelName) {
1379
1021
  this._log?.warn('runs', 'model clamped to what this device can run', {
1380
1022
  runId,
@@ -1386,7 +1028,7 @@ export class QvacAssistant extends ReadyResource {
1386
1028
  if (inflight)
1387
1029
  this._runs.set(runId, { ...inflight, model });
1388
1030
  }
1389
- const config = await this._engine.getConfig({}).catch(noop);
1031
+ const config = await engine.getConfig({}).catch(noop);
1390
1032
  const configuredAgent = withConfigDefaults(agent, config);
1391
1033
  this._log?.info('runs', 'run model resolved', {
1392
1034
  runId,
@@ -1394,7 +1036,7 @@ export class QvacAssistant extends ReadyResource {
1394
1036
  agentModel: agent.modelName,
1395
1037
  warmedModel: this._warmedModelName
1396
1038
  });
1397
- const transcript = new RunTranscript(this._engine, {
1039
+ const transcript = new RunTranscript(engine, {
1398
1040
  chatId,
1399
1041
  runId,
1400
1042
  deviceId,
@@ -1405,11 +1047,12 @@ export class QvacAssistant extends ReadyResource {
1405
1047
  chatId,
1406
1048
  transcript,
1407
1049
  trigger: 'before-run',
1408
- signal: controller.signal
1050
+ signal: controller.signal,
1051
+ meshId
1409
1052
  });
1410
- const toolConfigsPromise = this._loadToolConfigs(agent.id);
1053
+ const toolConfigsPromise = this._loadToolConfigs(engine, agent.id);
1411
1054
  const fsGrantsPromise = this._loadFsGrants(agent.id);
1412
- const all = await listHistoryChunks(this._engine, chatId);
1055
+ const all = await listHistoryChunks(engine, chatId);
1413
1056
  const branches = historyBranches(all, runId);
1414
1057
  const currentRepair = branches.repairByRunId.get(runId);
1415
1058
  const repairParent = currentRepair
@@ -1421,11 +1064,11 @@ export class QvacAssistant extends ReadyResource {
1421
1064
  inputAvailableToRun(chunk, request.seq) &&
1422
1065
  (!repairParent || chunk.seq <= repairParent.seq || chunk.runId === repairParent.runId) &&
1423
1066
  isPromptChunk(chunk, branches)));
1424
- const { chunks: priorAsks } = await this._engine.listChunks({
1067
+ const { chunks: priorAsks } = await engine.listChunks({
1425
1068
  chatId,
1426
1069
  type: 'approval-request'
1427
1070
  });
1428
- const { chunks: priorResults } = await this._engine.listChunks({ chatId, type: 'tool-result' });
1071
+ const { chunks: priorResults } = await engine.listChunks({ chatId, type: 'tool-result' });
1429
1072
  let ran = (priorResults ?? []).some((chunk) => chunk.runId === runId &&
1430
1073
  chunk.toolResult?.name !== SKILL_TOOL &&
1431
1074
  !isDeniedResult(chunk.toolResult?.result));
@@ -1462,11 +1105,12 @@ export class QvacAssistant extends ReadyResource {
1462
1105
  else {
1463
1106
  unreadableImages = await this._hydrateImages(messages, controller.signal, runId);
1464
1107
  }
1465
- const settledWatch = this._watchSettled(chatId, runId, controller);
1466
- const ownershipWatch = this._watchOwnership(agent.id, controller);
1108
+ const settledWatch = this._watchSettled(engine, chatId, runId, controller);
1109
+ const ownershipWatch = this._watchOwnership(engine, agent.id, controller);
1467
1110
  let readinessError = null;
1468
1111
  try {
1469
- await this._downloads?.waitUntilCached(model, controller.signal);
1112
+ if (!lender)
1113
+ await this._downloads?.waitUntilCached(model, controller.signal);
1470
1114
  }
1471
1115
  catch (err) {
1472
1116
  readinessError = err instanceof Error ? err : new Error(String(err));
@@ -1507,7 +1151,7 @@ export class QvacAssistant extends ReadyResource {
1507
1151
  ? { state: 'executing', progress: { phase: 'queued', busyChatId } }
1508
1152
  : { state: 'executing' });
1509
1153
  const runStatusId = executing.id;
1510
- const approvals = this._createApprove(chatId, runId, deviceId, agent.id, () => ran);
1154
+ const approvals = this._createApprove(engine, chatId, runId, deviceId, agent.id, () => ran);
1511
1155
  const modelWatch = this._watchModelProgress((runStatus) => transcript.progress(runStatusId, runStatus), busyChatId !== null);
1512
1156
  let metrics;
1513
1157
  const sourceTagFilter = createRagSourceTagFilter();
@@ -1529,7 +1173,7 @@ export class QvacAssistant extends ReadyResource {
1529
1173
  backfillDocumentOnlyTurn(messages);
1530
1174
  const knowledge = !diagramRepair &&
1531
1175
  (toolsetEnabled('knowledge', runAgent.disabledToolsets) || attachTurnIds.length > 0)
1532
- ? await this._searchKnowledge(chatId, messages, attachTurnIds, controller.signal, modelWatch.documents)
1176
+ ? await this._searchKnowledge(engine, chatId, messages, attachTurnIds, controller.signal, modelWatch.documents)
1533
1177
  : null;
1534
1178
  if (controller.signal.aborted) {
1535
1179
  const outcome = this._abortOutcome(runId, controller.signal.reason);
@@ -1642,7 +1286,7 @@ export class QvacAssistant extends ReadyResource {
1642
1286
  key,
1643
1287
  error: err instanceof Error ? err.message : String(err)
1644
1288
  }));
1645
- if (await this._isHandled(request))
1289
+ if (await this._isHandled(engine, request))
1646
1290
  return;
1647
1291
  const cacheKey = diagramRepair ? undefined : chatRepairKvCacheKey(chatId, acceptedRepairs);
1648
1292
  this._log?.info('runs', 'completion requested', {
@@ -1651,7 +1295,7 @@ export class QvacAssistant extends ReadyResource {
1651
1295
  cacheKey,
1652
1296
  turns: messages.length
1653
1297
  });
1654
- const events = this._harness.completion({
1298
+ const events = this._harnessFor(runAgent).completion({
1655
1299
  model,
1656
1300
  agent: runAgent,
1657
1301
  messages,
@@ -1663,10 +1307,10 @@ export class QvacAssistant extends ReadyResource {
1663
1307
  driveOp,
1664
1308
  grantedWriteDirs: write,
1665
1309
  approve: approvals.approve,
1666
- attach: (input) => this._uploadGenerated(chatId, runId, deviceId, input),
1667
- fetchAttachment: (query) => this._fetchAttachment(chatId, query),
1310
+ attach: (input) => this._uploadGenerated(meshId, chatId, runId, deviceId, input),
1311
+ fetchAttachment: (query) => this._fetchAttachment(engine, chatId, query),
1668
1312
  ragSearch: async (input) => {
1669
- const found = await raceAbort(this._engine.ragSearch({
1313
+ const found = await raceAbort(engine.ragSearch({
1670
1314
  chatId,
1671
1315
  query: input.query,
1672
1316
  mode: 'tool',
@@ -1731,7 +1375,8 @@ export class QvacAssistant extends ReadyResource {
1731
1375
  chatId,
1732
1376
  transcript,
1733
1377
  trigger: 'overflow',
1734
- signal: controller.signal
1378
+ signal: controller.signal,
1379
+ meshId
1735
1380
  }));
1736
1381
  await transcript.status({
1737
1382
  state: 'failed',
@@ -1787,7 +1432,7 @@ export class QvacAssistant extends ReadyResource {
1787
1432
  });
1788
1433
  }
1789
1434
  else if (event.type === 'tool-activity') {
1790
- void this._engine
1435
+ void engine
1791
1436
  .recordToolActivity({
1792
1437
  agentId: runAgent.id,
1793
1438
  toolName: event.name,
@@ -1822,7 +1467,8 @@ export class QvacAssistant extends ReadyResource {
1822
1467
  transcript,
1823
1468
  trigger: 'turn-filled-window',
1824
1469
  metrics: metrics,
1825
- signal: controller.signal
1470
+ signal: controller.signal,
1471
+ meshId
1826
1472
  })
1827
1473
  : false;
1828
1474
  const settled = foldedNow ? withoutOccupancy(metrics) : metrics;
@@ -1843,7 +1489,8 @@ export class QvacAssistant extends ReadyResource {
1843
1489
  if (outcome?.kind === 'handoff')
1844
1490
  return;
1845
1491
  await flushTranscript();
1846
- await transcript.status({ state: 'failed', reason: runFailureNotice(err), metrics });
1492
+ const failure = (this._lenderFor(runAgent) ? loanFailureNotice(err) : null) ?? runFailureNotice(err);
1493
+ await transcript.status({ state: 'failed', reason: failure, metrics });
1847
1494
  titleOutcome = 'ended';
1848
1495
  }
1849
1496
  finally {
@@ -1853,12 +1500,12 @@ export class QvacAssistant extends ReadyResource {
1853
1500
  await approvals.settle({ preservePending: isLifecycleTeardown(controller.signal.reason) });
1854
1501
  settledWatch.stop();
1855
1502
  if (titleOutcome && !diagramRepair) {
1856
- void this._autoTitle(chatId, messages, model, runAgent, titleOutcome === 'completed');
1503
+ void this._autoTitle(engine, chatId, messages, model, runAgent, titleOutcome === 'completed');
1857
1504
  }
1858
1505
  }
1859
1506
  }
1860
- async _loadToolConfigs(agentId) {
1861
- const { configs } = await this._engine.listToolConfigs({ agentId }).catch((err) => {
1507
+ async _loadToolConfigs(engine, agentId) {
1508
+ const { configs } = await engine.listToolConfigs({ agentId }).catch((err) => {
1862
1509
  this._log?.warn('assistant', 'tool configs read failed', err);
1863
1510
  return { configs: [] };
1864
1511
  });
@@ -1891,17 +1538,23 @@ export class QvacAssistant extends ReadyResource {
1891
1538
  });
1892
1539
  return grantedDirsFrom(value);
1893
1540
  }
1894
- async _fetchAttachment(chatId, { attachmentId, signal, meta } = {}) {
1541
+ async _fetchAttachment(engine, chatId, { attachmentId, kind = 'image', signal, meta } = {}) {
1895
1542
  if (!attachmentId) {
1896
- const { chunks } = await raceAbort(this._engine.listChunks({ chatId, type: 'attachment' }), signal);
1543
+ const { chunks } = await raceAbort(engine.listChunks({ chatId, type: 'attachment' }), signal);
1897
1544
  attachmentId = (chunks ?? [])
1898
1545
  .map((chunk) => chunk.attachment)
1899
- .filter((file) => file && !file.deletedAt && IMAGE_MIMES.has(file.mimeType.toLowerCase()))
1546
+ .filter((file) => {
1547
+ if (!file || file.deletedAt)
1548
+ return false;
1549
+ return kind === 'audio'
1550
+ ? isAudioAttachment(file.fileName, file.mimeType)
1551
+ : IMAGE_MIMES.has(file.mimeType.toLowerCase());
1552
+ })
1900
1553
  .at(-1)?.id;
1901
1554
  }
1902
1555
  if (!attachmentId)
1903
1556
  return null;
1904
- const stream = this._engine.fileRead({ chatId, fileId: attachmentId, metadataOnly: meta });
1557
+ const stream = engine.fileRead({ chatId, fileId: attachmentId, metadataOnly: meta });
1905
1558
  const abort = () => stream.destroy();
1906
1559
  const pieces = [];
1907
1560
  let head = null;
@@ -1943,9 +1596,9 @@ export class QvacAssistant extends ReadyResource {
1943
1596
  return null;
1944
1597
  }
1945
1598
  }
1946
- async _uploadGenerated(chatId, runId, deviceId, { fileName, mimeType, bytes, raw }) {
1599
+ async _uploadGenerated(meshId, chatId, runId, deviceId, { fileName, mimeType, bytes, raw }) {
1947
1600
  const duplex = this._engine.uploadAttachment();
1948
- duplex.write({ chatId, runId, originDeviceId: deviceId, fileName, mimeType, raw });
1601
+ duplex.write({ chatId, runId, originDeviceId: deviceId, fileName, mimeType, raw, meshId });
1949
1602
  const buf = Buffer.isBuffer(bytes)
1950
1603
  ? bytes
1951
1604
  : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
@@ -2058,8 +1711,8 @@ export class QvacAssistant extends ReadyResource {
2058
1711
  return file;
2059
1712
  }
2060
1713
  async _compactIfNearFull(params) {
2061
- const { chatId, transcript, trigger, signal } = params;
2062
- const metrics = params.metrics ?? (await this._lastRunMetrics(chatId));
1714
+ const { chatId, transcript, trigger, signal, meshId } = params;
1715
+ const metrics = params.metrics ?? (await this._lastRunMetrics(chatId, meshId));
2063
1716
  if (!nearContextLimit(metrics.cacheTokens, metrics.ctxSize))
2064
1717
  return false;
2065
1718
  if (!canCompact(metrics.ctxSize)) {
@@ -2069,10 +1722,17 @@ export class QvacAssistant extends ReadyResource {
2069
1722
  });
2070
1723
  return false;
2071
1724
  }
2072
- return this._runCompaction({ chatId, transcript, trigger, signal, occupancy: metrics });
1725
+ return this._runCompaction({
1726
+ chatId,
1727
+ transcript,
1728
+ trigger,
1729
+ signal,
1730
+ occupancy: metrics,
1731
+ meshId
1732
+ });
2073
1733
  }
2074
1734
  async _runCompaction(params) {
2075
- const { chatId, transcript, trigger, signal } = params;
1735
+ const { chatId, transcript, trigger, signal, meshId } = params;
2076
1736
  let statusId = null;
2077
1737
  const started = Date.now();
2078
1738
  try {
@@ -2084,7 +1744,8 @@ export class QvacAssistant extends ReadyResource {
2084
1744
  });
2085
1745
  statusId = status.id;
2086
1746
  },
2087
- ...(signal ? { signal } : {})
1747
+ ...(signal ? { signal } : {}),
1748
+ ...(meshId ? { meshId } : {})
2088
1749
  });
2089
1750
  this._log?.info('runs', 'compaction', {
2090
1751
  chatId,
@@ -2109,9 +1770,9 @@ export class QvacAssistant extends ReadyResource {
2109
1770
  }
2110
1771
  }
2111
1772
  }
2112
- async _lastRunMetrics(chatId) {
1773
+ async _lastRunMetrics(chatId, meshId) {
2113
1774
  const deviceId = this._deviceId;
2114
- const { chunks } = await this._engine
1775
+ const { chunks } = await meshScoped(this._engine, meshId)
2115
1776
  .listChunks({ chatId, type: 'run-status' })
2116
1777
  .catch(() => ({ chunks: [] }));
2117
1778
  const statuses = chunks ?? [];
@@ -2130,24 +1791,25 @@ export class QvacAssistant extends ReadyResource {
2130
1791
  async compactChat(chatId, options = {}) {
2131
1792
  if (!this.opened)
2132
1793
  await this.ready();
1794
+ const engine = meshScoped(this._engine, options.meshId);
2133
1795
  const deviceId = this._deviceId;
2134
- const chat = await this._engine.getChat({ id: chatId }).catch(() => null);
1796
+ const chat = await engine.getChat({ id: chatId }).catch(() => null);
2135
1797
  if (!chat)
2136
1798
  return { compacted: false, reason: 'unknown chat' };
2137
- const agent = await this._engine.getAgent({ id: chat.agentId }).catch(() => null);
1799
+ const agent = await engine.getAgent({ id: chat.agentId }).catch(() => null);
2138
1800
  if (!agent || !agent.providerDeviceId?.equals(deviceId)) {
2139
1801
  return { compacted: false, reason: 'not the provider device' };
2140
1802
  }
2141
1803
  const model = runnableModelName(agent.modelName, await this._ensureCapability(), this._mobileClass);
2142
- const config = await this._engine.getConfig({}).catch(() => null);
1804
+ const config = await engine.getConfig({}).catch(() => null);
2143
1805
  const ctxSize = agent.ctxSize || config?.ctxSize || undefined;
2144
1806
  if (ctxSize !== undefined && !canCompact(ctxSize)) {
2145
1807
  return { compacted: false, reason: 'below-floor' };
2146
1808
  }
2147
- const stored = await listHistoryChunks(this._engine, chatId);
1809
+ const stored = await listHistoryChunks(engine, chatId);
2148
1810
  const branches = historyBranches(stored);
2149
1811
  const chunks = stored.filter((chunk) => isPromptChunk(chunk, branches));
2150
- const { chunks: priorAsks } = await this._engine
1812
+ const { chunks: priorAsks } = await engine
2151
1813
  .listChunks({ chatId, type: 'approval-request' })
2152
1814
  .catch(() => ({ chunks: [] }));
2153
1815
  const lastThroughId = lastCompactedThroughId(chunks);
@@ -2184,7 +1846,7 @@ export class QvacAssistant extends ReadyResource {
2184
1846
  }
2185
1847
  if (options.signal?.aborted)
2186
1848
  return { compacted: false, reason: 'canceled' };
2187
- await this._engine.appendChunk({
1849
+ await engine.appendChunk({
2188
1850
  chatId,
2189
1851
  type: 'compaction',
2190
1852
  compaction: { summary, throughId: boundary.throughId },
@@ -2201,7 +1863,7 @@ export class QvacAssistant extends ReadyResource {
2201
1863
  }
2202
1864
  async _summarize(turns, model, agent, signal) {
2203
1865
  const hasPriorSummary = turns[0]?.content.startsWith(COMPACTION_TURN_PREFIX) === true;
2204
- const events = this._harness.completion({
1866
+ const events = this._harnessFor(agent).completion({
2205
1867
  model,
2206
1868
  agent: {
2207
1869
  ...agent,
@@ -2241,22 +1903,22 @@ export class QvacAssistant extends ReadyResource {
2241
1903
  }
2242
1904
  return { summary: parseCompactionSummary(text), overflowed: false };
2243
1905
  }
2244
- async _autoTitle(chatId, messages, model, agent, probe) {
1906
+ async _autoTitle(engine, chatId, messages, model, agent, probe) {
2245
1907
  try {
2246
1908
  const first = messages.find((turn) => turn.role === 'user' && turn.content.trim());
2247
1909
  if (!first)
2248
1910
  return;
2249
- const chat = await this._engine.getChat({ id: chatId });
1911
+ const chat = await engine.getChat({ id: chatId });
2250
1912
  if (!isDefaultChatTitle(chat?.title))
2251
1913
  return;
2252
- await this._generateChatTitle({ chatId, input: first.content, model, agent, probe });
1914
+ await this._generateChatTitle({ engine, chatId, input: first.content, model, agent, probe });
2253
1915
  }
2254
1916
  catch (err) {
2255
1917
  this._log?.warn('runs', 'auto-title skipped', { chatId, err });
2256
1918
  }
2257
1919
  }
2258
1920
  async _generateChatTitle(params) {
2259
- const { chatId, input, model, agent, probe } = params;
1921
+ const { engine, chatId, input, model, agent, probe } = params;
2260
1922
  const prompt = input.trim();
2261
1923
  if (!prompt)
2262
1924
  return null;
@@ -2277,7 +1939,7 @@ export class QvacAssistant extends ReadyResource {
2277
1939
  const title = generated ?? deriveChatTitle(prompt);
2278
1940
  if (!title)
2279
1941
  return null;
2280
- await this._engine.renameChat({ id: chatId, title });
1942
+ await engine.renameChat({ id: chatId, title });
2281
1943
  this._log?.info('runs', 'chat titled', {
2282
1944
  chatId,
2283
1945
  title,
@@ -2287,7 +1949,7 @@ export class QvacAssistant extends ReadyResource {
2287
1949
  }
2288
1950
  async _titleFromCompletion(params) {
2289
1951
  const { input, model, agent, signal } = params;
2290
- const events = this._harness.completion({
1952
+ const events = this._harnessFor(agent).completion({
2291
1953
  model,
2292
1954
  agent: {
2293
1955
  ...agent,
@@ -2321,7 +1983,7 @@ export class QvacAssistant extends ReadyResource {
2321
1983
  }
2322
1984
  return parseTitleResponse(text);
2323
1985
  }
2324
- _createApprove(chatId, runId, deviceId, agentId, hasRun) {
1986
+ _createApprove(engine, chatId, runId, deviceId, agentId, hasRun) {
2325
1987
  const waiters = new Map();
2326
1988
  let latestChunks = [];
2327
1989
  let watcher = null;
@@ -2353,7 +2015,7 @@ export class QvacAssistant extends ReadyResource {
2353
2015
  const ensureWatch = () => {
2354
2016
  if (watcher)
2355
2017
  return;
2356
- const opened = this._engine
2018
+ const opened = engine
2357
2019
  .chunksWatch({ chatId, type: 'approval-request' })[Symbol.asyncIterator]();
2358
2020
  watcher = opened;
2359
2021
  pump(opened)
@@ -2377,7 +2039,7 @@ export class QvacAssistant extends ReadyResource {
2377
2039
  });
2378
2040
  };
2379
2041
  const asksForRun = async () => {
2380
- const { chunks } = await this._engine
2042
+ const { chunks } = await engine
2381
2043
  .listChunks({ chatId, type: 'approval-request' })
2382
2044
  .catch(() => ({ chunks: [] }));
2383
2045
  return (chunks ?? []).filter((chunk) => chunk.runId === runId);
@@ -2399,14 +2061,15 @@ export class QvacAssistant extends ReadyResource {
2399
2061
  return new Promise((resolve) => waiters.set(chunkId, { resolve, tool }));
2400
2062
  };
2401
2063
  const approve = async (call) => {
2402
- const { rules } = await this._engine.listApprovalRules({}).catch((err) => {
2064
+ const { rules, ourMemberId } = await engine.listApprovalRules({}).catch((err) => {
2403
2065
  this._log?.warn('approvals', 'rule lookup failed, asking instead', { runId, err });
2404
- return { rules: [] };
2066
+ return { rules: [], ourMemberId: undefined };
2405
2067
  });
2406
2068
  const rule = matchApprovalRule(rules ?? [], {
2407
2069
  toolName: call.name,
2408
2070
  resource: call.resource,
2409
- agentId
2071
+ agentId,
2072
+ memberId: ourMemberId
2410
2073
  });
2411
2074
  if (rule) {
2412
2075
  this._log?.info('approvals', `rule ${rule.decision}`, {
@@ -2453,7 +2116,7 @@ export class QvacAssistant extends ReadyResource {
2453
2116
  resource: call.resource ?? undefined,
2454
2117
  agentId
2455
2118
  };
2456
- const chunk = await this._engine.appendChunk({
2119
+ const chunk = await engine.appendChunk({
2457
2120
  chatId,
2458
2121
  runId,
2459
2122
  type: 'approval-request',
@@ -2482,7 +2145,7 @@ export class QvacAssistant extends ReadyResource {
2482
2145
  chunkId: ask.id,
2483
2146
  tool: ask.approvalRequest?.name
2484
2147
  });
2485
- await this._engine.resolveApproval({ id: ask.id, approved: false });
2148
+ await engine.resolveApproval({ id: ask.id, approved: false });
2486
2149
  }
2487
2150
  for (const waiter of waiters.values())
2488
2151
  waiter.resolve(false);
@@ -2508,8 +2171,8 @@ export class QvacAssistant extends ReadyResource {
2508
2171
  }
2509
2172
  return { kind: 'failed', reason: RUN_FAILURE_REASONS.runtimeEndedTurn };
2510
2173
  }
2511
- _watchSettled(chatId, runId, controller) {
2512
- const it = this._engine.chunksWatch({ chatId, type: 'run-status' })[Symbol.asyncIterator]();
2174
+ _watchSettled(engine, chatId, runId, controller) {
2175
+ const it = engine.chunksWatch({ chatId, type: 'run-status' })[Symbol.asyncIterator]();
2513
2176
  const watching = (async () => {
2514
2177
  while (true) {
2515
2178
  const { value, done } = await it.next();
@@ -2533,9 +2196,9 @@ export class QvacAssistant extends ReadyResource {
2533
2196
  }
2534
2197
  };
2535
2198
  }
2536
- _watchOwnership(agentId, controller) {
2199
+ _watchOwnership(engine, agentId, controller) {
2537
2200
  const deviceId = this._deviceId;
2538
- const it = this._engine.agentsWatch({})[Symbol.asyncIterator]();
2201
+ const it = engine.agentsWatch({})[Symbol.asyncIterator]();
2539
2202
  const watching = (async () => {
2540
2203
  while (true) {
2541
2204
  const { value, done } = await it.next();
@@ -2640,7 +2303,7 @@ export class QvacAssistant extends ReadyResource {
2640
2303
  }
2641
2304
  function noop() { }
2642
2305
  function runMetricsSummary(metrics) {
2643
- const { timeToFirstToken, promptTokens, promptTokensPerSecond, cacheTokens, tokensPerSecond, totalTokens, durationMs } = metrics;
2306
+ const { timeToFirstToken, promptTokens, promptTokensPerSecond, cacheTokens, tokensPerSecond, totalTokens, durationMs, stopReason } = metrics;
2644
2307
  return {
2645
2308
  timeToFirstToken,
2646
2309
  promptTokens,
@@ -2648,60 +2311,10 @@ function runMetricsSummary(metrics) {
2648
2311
  cacheTokens,
2649
2312
  tokensPerSecond,
2650
2313
  totalTokens,
2651
- durationMs
2314
+ durationMs,
2315
+ stopReason
2652
2316
  };
2653
2317
  }
2654
2318
  function isStreamDestroyed(err) {
2655
2319
  return typeof err === 'object' && err !== null && 'code' in err && err.code === 'STREAM_DESTROYED';
2656
2320
  }
2657
- function harnessDeathReason(status) {
2658
- const HARNESS_DIED = RUN_FAILURE_REASONS.harnessDied;
2659
- if (typeof status !== 'object' || status === null)
2660
- return HARNESS_DIED;
2661
- const record = status;
2662
- const detail = typeof record.error === 'string' && record.error ? record.error : null;
2663
- const code = typeof record.code === 'string' && record.code ? record.code : null;
2664
- if (!detail)
2665
- return code ? `${HARNESS_DIED} (${code})` : HARNESS_DIED;
2666
- return code ? `${HARNESS_DIED}: ${detail} (${code})` : `${HARNESS_DIED}: ${detail}`;
2667
- }
2668
- function harnessDied(status) {
2669
- if (typeof status !== 'object' || status === null || !('state' in status))
2670
- return false;
2671
- return status.state === 'died';
2672
- }
2673
- function modelCatalogChanged(state) {
2674
- return (typeof state === 'object' &&
2675
- state !== null &&
2676
- 'catalogChanged' in state &&
2677
- state.catalogChanged === true);
2678
- }
2679
- function imageDownloadProgress(state) {
2680
- if (typeof state !== 'object' ||
2681
- state === null ||
2682
- !('status' in state) ||
2683
- (state.status !== 'downloading' && state.status !== 'downloaded') ||
2684
- !('model' in state) ||
2685
- typeof state.model !== 'string' ||
2686
- !('percentage' in state) ||
2687
- typeof state.percentage !== 'number' ||
2688
- !Number.isFinite(state.percentage) ||
2689
- !('downloaded' in state) ||
2690
- typeof state.downloaded !== 'number' ||
2691
- !Number.isFinite(state.downloaded) ||
2692
- !('total' in state) ||
2693
- typeof state.total !== 'number' ||
2694
- !Number.isFinite(state.total)) {
2695
- return null;
2696
- }
2697
- const model = diffusionDownloadName(state.model);
2698
- if (!model)
2699
- return null;
2700
- return {
2701
- model,
2702
- phase: state.status === 'downloading' ? 'downloading' : 'complete',
2703
- percentage: state.percentage,
2704
- downloaded: state.downloaded,
2705
- total: state.total
2706
- };
2707
- }