@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
package/README.md CHANGED
@@ -182,7 +182,7 @@ Because every part of a run is a replicated chunk, the assistant inherits the
182
182
  whole multi-device story without any harness code:
183
183
 
184
184
  - **Delegation** — agents live on the mesh with a `providerDeviceId`. Any
185
- device asks (`engine.runAgent({ chatId, agentId })` appends a `run-request`
185
+ device asks (`engine.runAgent({ meshId, chatId, agentId })` appends a `run-request`
186
186
  chunk); the device that _provides_ the agent executes; every chunk streams
187
187
  back to everyone. A request made while the provider is offline runs when it
188
188
  returns. Asking requires no harness at all.
@@ -212,7 +212,7 @@ bookkeeping — and resolves once the run settles:
212
212
  ```js
213
213
  import { runTask } from 'qvac-core/task'
214
214
 
215
- const result = await runTask(engine, { agentId: agent.id, prompt: 'Say hi' })
215
+ const result = await runTask(engine, { meshId, agentId: agent.id, prompt: 'Say hi' })
216
216
 
217
217
  result.state // 'completed' | 'failed' | 'canceled'
218
218
  result.text // the answer: content after the last tool result, trimmed
@@ -244,10 +244,12 @@ One skill per task: the mention is the first token of the message.
244
244
  The engine exposes a snapshot chat catalog:
245
245
 
246
246
  ```js
247
- const { chats } = await engine.listChats()
247
+ const { chats } = await engine.listChats({ meshId })
248
248
  ```
249
249
 
250
- It returns complete, active mesh chat rows in sidebar order, bottom first
250
+ Every mesh-backed route names the mesh it acts on: a device holds several at once
251
+ and Core keeps no current one. It returns that mesh's chat rows in sidebar order,
252
+ bottom first
251
253
  (clients reverse to render): a chat sits where the user last dragged it
252
254
  (`moveChat`) until a chunk lands in it, then most-recently-active wins; `id`
253
255
  breaks ties. Groups ride the same frame, top first (`moveChatGroup` orders
@@ -266,7 +268,7 @@ Derived per-chat run state rides its own lean stream so it never churns the
266
268
  metadata list:
267
269
 
268
270
  ```js
269
- const { activities } = await engine.listChatActivity() // or engine.chatActivityWatch()
271
+ const { activities } = await engine.listChatActivity({ meshId }) // or engine.chatActivityWatch({ meshId })
270
272
  ```
271
273
 
272
274
  Each row is just `{ id, activityState }` — a small state machine over the chat's
@@ -337,7 +339,7 @@ A chat IS its chunk stream — one watch drives the whole view, and every
337
339
  device renders the same thing because they all see the same chunks:
338
340
 
339
341
  ```js
340
- for await (const { chunks } of engine.chunksWatch({ chatId })) render(chunks)
342
+ for await (const { chunks } of engine.chunksWatch({ meshId, chatId })) render(chunks)
341
343
  ```
342
344
 
343
345
  Each frame is the full chat in seq order. To render it, group chunks into
@@ -359,22 +361,22 @@ must sort before the reply that follows it).
359
361
  | `thinking` | collapsed/dimmed reasoning segment (`chunk.thinking.text`) |
360
362
  | `tool-call` | `→ name(arguments)` line from `chunk.toolCall` |
361
363
  | `tool-result` | `← name: result` line from `chunk.toolResult` (collapse long results) |
362
- | `attachment` | file card from `chunk.attachment` (`fileName`, `mimeType`, `byteLength`); fetch bytes with `engine.downloadAttachment({ blobId })` |
364
+ | `attachment` | file card from `chunk.attachment` (`fileName`, `mimeType`, `byteLength`); fetch bytes with `engine.downloadAttachment({ meshId, blobId })` |
363
365
  | `approval-request` | **the chunk IS the approval state**, in the typed `chunk.approvalRequest` struct. `status === 'pending'` → show the ask (prefer `resource` — e.g. `host wttr.in` — over raw arguments) with allow / always-allow / deny; any other status → a resolved badge |
364
366
  | `run-status` | turn lifecycle, in the typed `chunk.runStatus` struct: `executing` with a `progress` sub-struct (`phase` `loading`/`downloading`, `model`, `percentage` — edited in place on the one executing chunk, labelled by the chunk's `originDeviceId`); `failed` → error with `reason`; `completed` → done, `metrics` (tokens, tok/s, ttft) |
365
367
 
366
- **Approval answers** go through `engine.resolveApproval({ id, approved,
367
- scope, expiresAt })` from ANY device — first decision wins, the flipped
368
+ **Approval answers** go through `engine.resolveApproval({ chunkId, approved,
369
+ scope, expiresAt, meshId })` from ANY device — first decision wins, the flipped
368
370
  chunk replicates to everyone. `scope: 'always'` also mints a standing
369
371
  approval-rule from the request's tool + resource, so matching future calls
370
372
  don't prompt anywhere until the rule expires — one hour by default; pass
371
373
  `expiresAt` (ms since epoch) to grant longer or shorter
372
- (`engine.listApprovalRules({})` shows what's remembered).
374
+ (`engine.listApprovalRules({ meshId })` shows what's remembered).
373
375
 
374
376
  **Busy state** derives from the stream, not local flags: if the last
375
377
  assistant turn has no terminal `run-status` (`completed`/`failed`/
376
378
  `canceled`), a run is in flight somewhere — show the spinner on every device
377
- and offer `engine.stopRun({ chatId, runId })`.
379
+ and offer `engine.stopRun({ meshId, chatId, runId })`.
378
380
 
379
381
  **Stopping** is a right of any device, not a request to the executor:
380
382
  `stopRun` appends the terminal `canceled` run-status itself, so it settles a
@@ -386,7 +388,7 @@ first terminal status in seq order is always the run's one outcome.
386
388
  **Orphaned agents.** Every agent from `listAgents`/`getAgent`/`agentsWatch`
387
389
  carries a derived `orphaned` flag: its provider device row is gone or
388
390
  revoked, so nobody can execute its runs until it's re-homed
389
- (`updateAgent({ id, providerDeviceId })`). Render it as "waiting for
391
+ (`updateAgent({ meshId, agentId, config: { providerDeviceId } })`). Render it as "waiting for
390
392
  provider" — on the agent itself, and on a busy turn whose agent is orphaned
391
393
  (that spinner will never resolve by itself). Device removal deliberately
392
394
  does NOT delete the device's agents: their chats survive, and re-homing
@@ -432,7 +434,7 @@ Documents whose full text already fits the prompt need no index wait.
432
434
  See the [cache and processing decision](docs/decisions/2026-07-15-vector-index-session-cache.md).
433
435
 
434
436
  ```ts
435
- const statuses = engine.fileStatusWatch({ chatId })
437
+ const statuses = engine.fileStatusWatch({ meshId, chatId })
436
438
  statuses.on('data', ({ files }) => renderFileStates(files))
437
439
 
438
440
  const upload = engine.uploadKnowledge()
@@ -563,7 +565,7 @@ evented; `T` is the hyperschema frame type), so both idioms typecheck:
563
565
  **Loop** — `break`/`return` unsubscribes:
564
566
 
565
567
  ```js
566
- for await (const { agents } of engine.agentsWatch({})) {
568
+ for await (const { agents } of engine.agentsWatch({ meshId })) {
567
569
  render(agents)
568
570
  if (done) break // break IS the unsubscribe
569
571
  }
@@ -573,7 +575,7 @@ for await (const { agents } of engine.agentsWatch({})) {
573
575
  `destroy()`; this is plain streamx, nothing layered on top:
574
576
 
575
577
  ```js
576
- const stream = engine.chunksWatch({ chatId }) // opening the chat
578
+ const stream = engine.chunksWatch({ meshId, chatId }) // opening the chat
577
579
  stream.on('data', ({ chunks }) => render(chunks))
578
580
  // ...closing the chat:
579
581
  stream.destroy() // the unsubscribe
@@ -586,7 +588,7 @@ race, because frame one is the snapshot:
586
588
  async function once(stream) {
587
589
  for await (const frame of stream) return frame // break-on-return unsubscribes
588
590
  }
589
- const { devices } = await once(engine.devicesWatch({}))
591
+ const { devices } = await once(engine.devicesWatch({ meshId }))
590
592
  ```
591
593
 
592
594
  **Errors end the stream, they never hang it.** A server-side query failure
@@ -597,7 +599,7 @@ is a re-arm loop, not error plumbing:
597
599
  ```js
598
600
  while (!closing) {
599
601
  try {
600
- for await (const { chunks } of engine.chunksWatch({ chatId })) render(chunks)
602
+ for await (const { chunks } of engine.chunksWatch({ meshId, chatId })) render(chunks)
601
603
  break // server ended the stream deliberately
602
604
  } catch {
603
605
  await delay(1000) // transport blip — resubscribe (frame one re-syncs you)
@@ -1,5 +1,5 @@
1
- import { type CurrentMesh } from './current-mesh.ts';
1
+ import { type MeshPool } from './current-mesh.ts';
2
2
  import type { CapabilityHandlers } from '../../spec/capabilities.d.ts';
3
- type AgentCapabilities = Pick<CapabilityHandlers, 'createAgent' | 'listAgents' | 'getAgent' | 'updateAgent' | 'deleteAgent' | 'agentsWatch'>;
4
- export declare function createAgentsApi(current: CurrentMesh, deviceId: Buffer | null, computeLender?: (() => Promise<Buffer | null>) | null): AgentCapabilities;
3
+ type AgentCapabilities = Pick<CapabilityHandlers, 'createAgent' | 'listAgents' | 'getAgent' | 'getDefaultAgent' | 'updateAgent' | 'deleteAgent' | 'agentsWatch'>;
4
+ export declare function createAgentsApi(pool: MeshPool, deviceId: Buffer | null, computeLender?: (() => Promise<Buffer | null>) | null): AgentCapabilities;
5
5
  export {};
@@ -1,38 +1,49 @@
1
- import { createAgent, deleteAgent, isOrphaned, listAgents, liveProviderIds, mustGetActiveAgent, updateAgent } from '../core/agent.js';
1
+ import { createAgent, deleteAgent, getDefaultAgent, isOrphaned, listAgents, liveProviderIds, mustGetActiveAgent, updateAgent } from '../core/agent.js';
2
2
  import { meshWatchable, requireMesh } from './current-mesh.js';
3
- export function createAgentsApi(current, deviceId, computeLender = null) {
3
+ import b4a from 'b4a';
4
+ export function createAgentsApi(pool, deviceId, computeLender = null) {
4
5
  const withOrphaned = async (mesh, agent) => ({
5
6
  ...agent,
6
7
  orphaned: await isOrphaned(mesh, agent)
7
8
  });
8
- const list = async (mesh) => {
9
- const [agents, live] = await Promise.all([listAgents(mesh), liveProviderIds(mesh)]);
9
+ const list = async (mesh, providerDeviceId) => {
10
+ const [agents, live] = await Promise.all([
11
+ listAgents(mesh, providerDeviceId),
12
+ liveProviderIds(mesh)
13
+ ]);
10
14
  return {
11
15
  agents: agents.map((agent) => ({
12
16
  ...agent,
13
- orphaned: !live.has(agent.providerDeviceId.toString('hex'))
17
+ orphaned: !live.has(b4a.toHex(agent.providerDeviceId))
14
18
  }))
15
19
  };
16
20
  };
17
21
  return {
18
- createAgent: async (input) => {
19
- const mesh = await requireMesh(current, input.meshId);
20
- const lenderDeviceId = input.lenderDeviceId ?? (await computeLender?.()) ?? undefined;
21
- return withOrphaned(mesh, await createAgent(mesh, { ...input, lenderDeviceId }));
22
+ createAgent: async ({ meshId, config }) => {
23
+ const mesh = await requireMesh(pool, meshId);
24
+ const lenderDeviceId = config.lenderDeviceId ?? (await computeLender?.()) ?? undefined;
25
+ return withOrphaned(mesh, await createAgent(mesh, { ...config, lenderDeviceId }));
22
26
  },
23
- listAgents: async (request) => list(await requireMesh(current, request?.meshId)),
24
- getAgent: async ({ id, meshId }) => {
25
- const mesh = await requireMesh(current, meshId);
26
- return withOrphaned(mesh, await mustGetActiveAgent(mesh, id));
27
+ listAgents: async ({ meshId, providerDeviceId }) => list(await requireMesh(pool, meshId), providerDeviceId ?? undefined),
28
+ getAgent: async ({ agentId, meshId }) => {
29
+ const mesh = await requireMesh(pool, meshId);
30
+ return withOrphaned(mesh, await mustGetActiveAgent(mesh, agentId));
27
31
  },
28
- updateAgent: async (input) => {
29
- const mesh = await requireMesh(current);
30
- return withOrphaned(mesh, await updateAgent(mesh, input));
32
+ getDefaultAgent: async ({ meshId, providerDeviceId }) => {
33
+ const mesh = await requireMesh(pool, meshId);
34
+ const agent = await getDefaultAgent(mesh, providerDeviceId ?? undefined);
35
+ if (!agent)
36
+ return {};
37
+ return { agent: await withOrphaned(mesh, agent) };
31
38
  },
32
- deleteAgent: async ({ id, meshId }) => {
33
- const mesh = await requireMesh(current, meshId);
34
- return withOrphaned(mesh, await deleteAgent(mesh, deviceId, id));
39
+ updateAgent: async ({ agentId, meshId, config }) => {
40
+ const mesh = await requireMesh(pool, meshId);
41
+ return withOrphaned(mesh, await updateAgent(mesh, agentId, config));
35
42
  },
36
- agentsWatch: meshWatchable('agentsWatch', current, (_request, mesh) => list(mesh))
43
+ deleteAgent: async ({ agentId, meshId }) => {
44
+ const mesh = await requireMesh(pool, meshId);
45
+ return withOrphaned(mesh, await deleteAgent(mesh, deviceId, agentId));
46
+ },
47
+ agentsWatch: meshWatchable('agentsWatch', pool, (request, mesh) => list(mesh, request.providerDeviceId ?? undefined))
37
48
  };
38
49
  }
@@ -1,3 +1,3 @@
1
- import { type CurrentMesh } from './current-mesh.ts';
1
+ import { type MeshPool } from './current-mesh.ts';
2
2
  import type { CapabilityHandlers } from '../../spec/capabilities.d.ts';
3
- export declare function createApprovalRulesApi(current: CurrentMesh): Pick<CapabilityHandlers, 'listApprovalRules'>;
3
+ export declare function createApprovalRulesApi(pool: MeshPool): Pick<CapabilityHandlers, 'listApprovalRules'>;
@@ -1,9 +1,9 @@
1
1
  import { listApprovalRules } from '../core/approval-rules.js';
2
2
  import { requireMesh } from './current-mesh.js';
3
- export function createApprovalRulesApi(current) {
3
+ export function createApprovalRulesApi(pool) {
4
4
  return {
5
5
  listApprovalRules: async (request) => {
6
- const mesh = await requireMesh(current, request?.meshId);
6
+ const mesh = await requireMesh(pool, request.meshId);
7
7
  return {
8
8
  rules: await listApprovalRules(mesh),
9
9
  ourMemberId: mesh.ourMemberId ?? undefined
@@ -1,7 +1,7 @@
1
1
  import type { CapabilityHandlers } from '../../spec/capabilities.d.ts';
2
- import { type CurrentMesh } from './current-mesh.ts';
2
+ import { type MeshPool } from './current-mesh.ts';
3
3
  export { MAX_ATTACHMENT_BYTES } from '../core/files/attachments.ts';
4
- export declare function createAttachmentsApi(current: CurrentMesh, options?: {
4
+ export declare function createAttachmentsApi(pool: MeshPool, options?: {
5
5
  maxBytes?: number;
6
6
  deviceId?: Buffer | null;
7
7
  inactivityMs?: number;
@@ -1,37 +1,26 @@
1
- import { toAsyncIterable } from '../core/async-iterable.js';
1
+ import { openUpload, UPLOAD_NAMES_NO_MESH } from './upload-frames.js';
2
2
  import { requireMesh } from './current-mesh.js';
3
- function rejoin(frames, first, rest) {
4
- const replayed = (async function* () {
5
- yield first;
6
- while (true) {
7
- const next = await rest.next();
8
- if (next.done)
9
- return;
10
- yield next.value;
11
- }
12
- })();
13
- return 'writeStream' in frames
14
- ? Object.assign(replayed, { writeStream: frames.writeStream })
15
- : replayed;
16
- }
17
3
  export { MAX_ATTACHMENT_BYTES } from '../core/files/attachments.js';
18
- export function createAttachmentsApi(current, options = {}) {
4
+ export function createAttachmentsApi(pool, options = {}) {
19
5
  return {
20
6
  async *uploadAttachment(frames) {
21
- const rest = toAsyncIterable(frames)[Symbol.asyncIterator]();
22
- const first = await rest.next();
23
- if (first.done)
7
+ const upload = await openUpload(frames);
8
+ if (!upload)
24
9
  return;
25
- const mesh = await requireMesh(current, first.value.meshId);
26
- yield* mesh.files
27
- .attachments(options)
28
- .uploadAttachment(rejoin(frames, first.value, rest));
10
+ if (!upload.first.meshId)
11
+ throw new Error(UPLOAD_NAMES_NO_MESH);
12
+ const mesh = await requireMesh(pool, upload.first.meshId);
13
+ yield* mesh.files.attachments(options).uploadAttachment(upload.rest);
29
14
  },
30
15
  async *downloadAttachment(request) {
31
- yield* (await requireMesh(current)).files.attachments(options).downloadAttachment(request);
16
+ yield* (await requireMesh(pool, request.meshId)).files
17
+ .attachments(options)
18
+ .downloadAttachment(request);
32
19
  },
33
20
  async deleteAttachment(request) {
34
- return (await requireMesh(current)).files.attachments(options).deleteAttachment(request);
21
+ return (await requireMesh(pool, request.meshId)).files
22
+ .attachments(options)
23
+ .deleteAttachment(request);
35
24
  }
36
25
  };
37
26
  }
@@ -1,5 +1,5 @@
1
1
  import type { CapabilityHandlers } from '../../spec/capabilities.d.ts';
2
- import { type CurrentMesh } from './current-mesh.ts';
2
+ import { type MeshPool } from './current-mesh.ts';
3
3
  type ChatGroupCapabilities = Pick<CapabilityHandlers, 'createChatGroup' | 'listChatGroups' | 'renameChatGroup' | 'deleteChatGroup' | 'setChatGroup' | 'moveChat' | 'moveChatGroup' | 'sortChatGroupsByName'>;
4
- export declare function createChatGroupsApi(current: CurrentMesh): ChatGroupCapabilities;
4
+ export declare function createChatGroupsApi(pool: MeshPool): ChatGroupCapabilities;
5
5
  export {};
@@ -1,15 +1,15 @@
1
1
  import { createChatGroup, deleteChatGroup, listChatGroups, moveChatGroup, renameChatGroup, sortChatGroupsByName } from '../core/chat-group.js';
2
2
  import { moveChat, setChatGroup } from '../core/chat.js';
3
3
  import { requireMesh } from './current-mesh.js';
4
- export function createChatGroupsApi(current) {
4
+ export function createChatGroupsApi(pool) {
5
5
  return {
6
- createChatGroup: async ({ name }) => createChatGroup(await requireMesh(current), { name }),
7
- listChatGroups: async () => listChatGroups(await requireMesh(current)).then((groups) => ({ groups })),
8
- renameChatGroup: async ({ id, name }) => renameChatGroup(await requireMesh(current), id, name),
9
- deleteChatGroup: async ({ id }) => deleteChatGroup(await requireMesh(current), id),
10
- setChatGroup: async ({ id, groupId }) => setChatGroup(await requireMesh(current), id, groupId),
11
- moveChat: async ({ id, groupId, afterId }) => moveChat(await requireMesh(current), id, { groupId, afterId }),
12
- moveChatGroup: async ({ id, afterId }) => moveChatGroup(await requireMesh(current), id, { afterId }),
13
- sortChatGroupsByName: async () => sortChatGroupsByName(await requireMesh(current)).then((groups) => ({ groups }))
6
+ createChatGroup: async ({ meshId, config }) => createChatGroup(await requireMesh(pool, meshId), { name: config.name }),
7
+ listChatGroups: async ({ meshId }) => listChatGroups(await requireMesh(pool, meshId)).then((groups) => ({ groups })),
8
+ renameChatGroup: async ({ groupId, meshId, config }) => renameChatGroup(await requireMesh(pool, meshId), groupId, config.name),
9
+ deleteChatGroup: async ({ groupId, meshId }) => deleteChatGroup(await requireMesh(pool, meshId), groupId),
10
+ setChatGroup: async ({ chatId, groupId, meshId }) => setChatGroup(await requireMesh(pool, meshId), chatId, groupId),
11
+ moveChat: async ({ chatId, groupId, afterId, meshId }) => moveChat(await requireMesh(pool, meshId), chatId, { groupId, afterId }),
12
+ moveChatGroup: async ({ groupId, afterId, meshId }) => moveChatGroup(await requireMesh(pool, meshId), groupId, { afterId }),
13
+ sortChatGroupsByName: async ({ meshId }) => sortChatGroupsByName(await requireMesh(pool, meshId)).then((groups) => ({ groups }))
14
14
  };
15
15
  }
@@ -1,7 +1,9 @@
1
1
  import type { CapabilityHandlers } from '../../spec/capabilities.d.ts';
2
- import { type CurrentMesh } from './current-mesh.ts';
2
+ import type { openLocalStore } from '../core/local/index.ts';
3
+ import { type MeshPool } from './current-mesh.ts';
4
+ type LocalStore = ReturnType<typeof openLocalStore>;
3
5
  type ChatCapabilities = Pick<CapabilityHandlers, 'createChat' | 'listChats' | 'getChat' | 'renameChat' | 'setChatRagEnabled' | 'setChatWebSearchEnabled' | 'deleteChat' | 'chatsWatch' | 'listChatActivity' | 'chatActivityWatch' | 'searchChats'>;
4
- export declare function createChatApi(current: CurrentMesh, deviceId: Buffer | null, inferenceCalls?: {
6
+ export declare function createChatApi(pool: MeshPool, deviceId: Buffer | null, local: LocalStore, inferenceCalls?: {
5
7
  forget(chatId: string): Promise<void>;
6
8
  } | null): ChatCapabilities;
7
9
  export {};
@@ -1,36 +1,36 @@
1
1
  import { AbortController } from 'bare-abort-controller';
2
- import { createChat, deleteChat, listSidebar, mustGetActiveChatListing, renameChat, setChatRagEnabled, setChatWebSearchEnabled } from '../core/chat.js';
2
+ import { createChat, deleteChat, mustGetActiveChatListing, renameChat, setChatRagEnabled, setChatWebSearchEnabled } from '../core/chat.js';
3
3
  import { listChatActivity } from '../core/chat-activity.js';
4
+ import { listChatPage } from '../core/chat-order.js';
4
5
  import { searchChats } from '../core/chat-search.js';
5
- import { meshWatchable, requireMesh, selectionPin } from './current-mesh.js';
6
- import { watchable } from './watchable.js';
6
+ import { meshWatchable, requireMesh } from './current-mesh.js';
7
7
  const SEARCH_SUPERSEDED_ABORT = 'superseded by a newer chat search';
8
- export function createChatApi(current, deviceId, inferenceCalls = null) {
8
+ export function createChatApi(pool, deviceId, local, inferenceCalls = null) {
9
9
  let searchAbort = null;
10
- const chatList = (mesh) => listSidebar(mesh);
10
+ const chatList = (mesh, { limit, cursor }) => listChatPage(mesh, local, { limit: limit || undefined, cursor: cursor ?? undefined });
11
11
  const chatActivity = (mesh, chatIds) => listChatActivity(mesh, chatIds ?? undefined).then((activities) => ({ activities }));
12
12
  return {
13
- createChat: async (input) => createChat(await requireMesh(current), input),
14
- listChats: async (request) => chatList(await requireMesh(current, request?.meshId)),
15
- getChat: async ({ id, meshId }) => mustGetActiveChatListing(await requireMesh(current, meshId), id),
16
- renameChat: async ({ id, title, meshId }) => renameChat(await requireMesh(current, meshId), id, title),
17
- setChatRagEnabled: async ({ id, enabled }) => setChatRagEnabled(await requireMesh(current), id, enabled ?? false),
18
- setChatWebSearchEnabled: async ({ id, enabled }) => setChatWebSearchEnabled(await requireMesh(current), id, enabled ?? false),
19
- deleteChat: async ({ id, meshId }) => {
20
- const deleted = await deleteChat(await requireMesh(current, meshId), deviceId, id);
21
- await inferenceCalls?.forget(id);
13
+ createChat: async ({ meshId, agentId, config }) => createChat(await requireMesh(pool, meshId), { agentId, title: config.title }),
14
+ listChats: async (request) => chatList(await requireMesh(pool, request.meshId), request),
15
+ getChat: async ({ chatId, meshId }) => mustGetActiveChatListing(await requireMesh(pool, meshId), chatId),
16
+ renameChat: async ({ chatId, meshId, config }) => renameChat(await requireMesh(pool, meshId), chatId, config.title),
17
+ setChatRagEnabled: async ({ chatId, enabled, meshId }) => setChatRagEnabled(await requireMesh(pool, meshId), chatId, enabled ?? false),
18
+ setChatWebSearchEnabled: async ({ chatId, enabled, meshId }) => setChatWebSearchEnabled(await requireMesh(pool, meshId), chatId, enabled ?? false),
19
+ deleteChat: async ({ chatId, meshId }) => {
20
+ const deleted = await deleteChat(await requireMesh(pool, meshId), deviceId, chatId);
21
+ await inferenceCalls?.forget(chatId);
22
22
  return deleted;
23
23
  },
24
- chatsWatch: meshWatchable('chatsWatch', current, (_request, store) => chatList(store)),
25
- listChatActivity: async (input) => chatActivity(await requireMesh(current), input?.chatIds),
26
- chatActivityWatch: watchable('chatActivityWatch', () => requireMesh(current), (request, store) => chatActivity(store, request?.chatIds), () => selectionPin(current)),
24
+ chatsWatch: meshWatchable('chatsWatch', pool, (request, store) => chatList(store, request), local),
25
+ listChatActivity: async (input) => chatActivity(await requireMesh(pool, input.meshId), input.chatIds),
26
+ chatActivityWatch: meshWatchable('chatActivityWatch', pool, (request, store) => chatActivity(store, request.chatIds)),
27
27
  searchChats: async (input) => {
28
28
  searchAbort?.abort(SEARCH_SUPERSEDED_ABORT);
29
29
  const controller = new AbortController();
30
30
  searchAbort = controller;
31
31
  return {
32
32
  hits: [
33
- ...(await searchChats(await requireMesh(current), {
33
+ ...(await searchChats(await requireMesh(pool, input.meshId), {
34
34
  query: input.query,
35
35
  limit: input.limit,
36
36
  signal: controller.signal
@@ -1,5 +1,5 @@
1
- import { type CurrentMesh } from './current-mesh.ts';
1
+ import { type MeshPool } from './current-mesh.ts';
2
2
  import type { CapabilityHandlers } from '../../spec/capabilities.d.ts';
3
3
  type ChunkCapabilities = Pick<CapabilityHandlers, 'appendChunk' | 'updateChunk' | 'resolveApproval' | 'listChunks' | 'listAttachmentsByKind' | 'chunksWatch' | 'runRequestsWatch'>;
4
- export declare function createChunksApi(current: CurrentMesh, deviceId: Buffer | null): ChunkCapabilities;
4
+ export declare function createChunksApi(pool: MeshPool, deviceId: Buffer | null): ChunkCapabilities;
5
5
  export {};
@@ -1,15 +1,16 @@
1
- import { appendChunk, listAttachmentsByKind, listChunks, listRunRequests, resolveApproval, updateChunk } from '../core/chunk.js';
1
+ import { appendChunk, listAttachmentsByKind, listChunks, listRunRequests, recordLinks, resolveApproval, updateChunk } from '../core/chunk.js';
2
2
  import { meshWatchable, requireMesh } from './current-mesh.js';
3
- export function createChunksApi(current, deviceId) {
3
+ import { bounds } from './range.js';
4
+ export function createChunksApi(pool, deviceId) {
4
5
  return {
5
- appendChunk: async ({ meshId, ...input }) => appendChunk(await requireMesh(current, meshId), input),
6
- updateChunk: async ({ meshId, ...input }) => {
7
- await updateChunk(await requireMesh(current, meshId), input);
6
+ appendChunk: async ({ meshId, ...input }) => appendChunk(await requireMesh(pool, meshId), input),
7
+ updateChunk: async ({ meshId, chunkId, runStatus }) => {
8
+ await updateChunk(await requireMesh(pool, meshId), { id: chunkId, runStatus });
8
9
  return { ok: true };
9
10
  },
10
11
  resolveApproval: async (input) => {
11
- await resolveApproval(await requireMesh(current, input.meshId), {
12
- id: input.id,
12
+ await resolveApproval(await requireMesh(pool, input.meshId), {
13
+ id: input.chunkId,
13
14
  approved: input.approved === true,
14
15
  scope: input.scope ?? undefined,
15
16
  expiresAt: input.expiresAt || undefined,
@@ -17,35 +18,25 @@ export function createChunksApi(current, deviceId) {
17
18
  });
18
19
  return { ok: true };
19
20
  },
20
- listChunks: async ({ chatId, type, types, fromSeq, reverse, limit, meshId }) => ({
21
- chunks: await listChunks(await requireMesh(current, meshId), {
22
- chatId,
23
- type: type ?? undefined,
24
- types: types ?? undefined,
25
- fromSeq: fromSeq || undefined,
26
- reverse: reverse === true,
27
- limit: limit || undefined
28
- })
29
- }),
30
- listAttachmentsByKind: async ({ kind, origin, fromCreatedAt, reverse, limit }) => ({
31
- chunks: await listAttachmentsByKind(await requireMesh(current), {
32
- kind,
33
- origin: origin ?? undefined,
34
- fromCreatedAt: fromCreatedAt || undefined,
35
- reverse: reverse === true,
36
- limit: limit || undefined
37
- })
38
- }),
39
- chunksWatch: meshWatchable('chunksWatch', current, async ({ chatId, type, types, fromSeq, reverse, limit }, mesh) => ({
40
- chunks: await listChunks(mesh, {
41
- chatId,
42
- type: type ?? undefined,
43
- types: types ?? undefined,
44
- fromSeq: fromSeq || undefined,
45
- reverse: reverse === true,
46
- limit: limit || undefined
47
- })
21
+ listChunks: async ({ meshId, ...input }) => {
22
+ const mesh = await requireMesh(pool, meshId);
23
+ return { chunks: await recordLinks(mesh, await listChunks(mesh, chunkSelection(input))) };
24
+ },
25
+ listAttachmentsByKind: async ({ meshId, ...input }) => {
26
+ const mesh = await requireMesh(pool, meshId);
27
+ const chunks = await listAttachmentsByKind(mesh, {
28
+ ...bounds(input),
29
+ kind: input.kind,
30
+ origin: input.origin ?? undefined
31
+ });
32
+ return { chunks: await recordLinks(mesh, chunks) };
33
+ },
34
+ chunksWatch: meshWatchable('chunksWatch', pool, async ({ meshId, ...input }, mesh) => ({
35
+ chunks: await recordLinks(mesh, await listChunks(mesh, chunkSelection(input)))
48
36
  })),
49
- runRequestsWatch: meshWatchable('runRequestsWatch', current, async (_request, mesh) => ({ chunks: await listRunRequests(mesh, deviceId) }))
37
+ runRequestsWatch: meshWatchable('runRequestsWatch', pool, async (_request, mesh) => ({ chunks: await listRunRequests(mesh, deviceId) }))
50
38
  };
51
39
  }
40
+ function chunkSelection({ chatId, type, types, ...rest }) {
41
+ return { ...bounds(rest), chatId, type: type ?? undefined, types: types ?? undefined };
42
+ }
@@ -1,21 +1,13 @@
1
1
  import type { Mesh } from '../core/mesh.ts';
2
- import { type WatchPin } from './watchable.ts';
3
- export interface CurrentMesh {
4
- (meshId?: string | null): Mesh | null | Promise<Mesh | null>;
5
- readonly selection?: MeshSelection;
6
- }
7
- export interface MeshSelection {
8
- key(): string | null;
2
+ export type MeshPool = (meshId: string) => Mesh | null | Promise<Mesh | null>;
3
+ export declare const NO_SUCH_MESH = "no such mesh";
4
+ export declare function requireMesh(pool: MeshPool, meshId: string): Promise<Mesh>;
5
+ export declare function isMissingMesh(err: unknown): boolean;
6
+ export declare function meshWatchable<TRequest extends MeshScoped, TResult>(name: string, pool: MeshPool, query: (request: TRequest, mesh: Mesh) => Promise<TResult>, changes?: {
9
7
  watch(listener: () => void): void;
10
8
  unwatch(listener: () => void): void;
11
- }
12
- export declare const NO_ACTIVE_MESH = "no active mesh";
13
- export declare const NO_SUCH_MESH = "no such mesh";
14
- export declare function requireMesh(current: CurrentMesh, meshId?: string | null): Promise<Mesh>;
15
- export declare function isMeshTransition(err: unknown): boolean;
16
- export declare function meshWatchable<TRequest extends MeshScoped | undefined, TResult>(name: string, current: CurrentMesh, query: (request: TRequest, mesh: Mesh) => Promise<TResult>): (request: TRequest) => import("streamx").Readable<import("streamx").ReadableEvents> & AsyncIterable<TResult>;
17
- export declare function selectionPin(current: CurrentMesh, meshId?: string | null): WatchPin | null;
9
+ }): (request: TRequest) => import("streamx").Readable<import("streamx").ReadableEvents> & AsyncIterable<TResult>;
18
10
  interface MeshScoped {
19
- readonly meshId?: string | null;
11
+ readonly meshId: string;
20
12
  }
21
13
  export {};
@@ -1,31 +1,16 @@
1
1
  import { watchable } from './watchable.js';
2
- export const NO_ACTIVE_MESH = 'no active mesh';
3
2
  export const NO_SUCH_MESH = 'no such mesh';
4
- export async function requireMesh(current, meshId) {
5
- const mesh = await current(meshId);
3
+ export async function requireMesh(pool, meshId) {
4
+ const mesh = await pool(meshId);
6
5
  if (!mesh)
7
- throw new Error(meshId ? `${NO_SUCH_MESH}: ${meshId}` : NO_ACTIVE_MESH);
6
+ throw new Error(`${NO_SUCH_MESH}: ${meshId}`);
8
7
  if (!mesh.opened)
9
8
  await mesh.ready();
10
9
  return mesh;
11
10
  }
12
- export function isMeshTransition(err) {
13
- return err instanceof Error && err.message === NO_ACTIVE_MESH;
11
+ export function isMissingMesh(err) {
12
+ return err instanceof Error && err.message.startsWith(`${NO_SUCH_MESH}: `);
14
13
  }
15
- export function meshWatchable(name, current, query) {
16
- return watchable(name, (request) => requireMesh(current, request?.meshId), query, (request) => selectionPin(current, request?.meshId));
17
- }
18
- export function selectionPin(current, meshId) {
19
- const selection = current.selection;
20
- if (meshId || !selection)
21
- return null;
22
- const opened = selection.key();
23
- return {
24
- stale: () => {
25
- const now = selection.key();
26
- return now !== null && now !== opened;
27
- },
28
- watch: (listener) => selection.watch(listener),
29
- unwatch: (listener) => selection.unwatch(listener)
30
- };
14
+ export function meshWatchable(name, pool, query, changes) {
15
+ return watchable(name, (request) => requireMesh(pool, request.meshId), query, changes);
31
16
  }
@@ -1,8 +1,9 @@
1
1
  import type { AssistantCapabilityProfile } from '../../spec/hyperschema/types.d.ts';
2
- import { type CurrentMesh } from './current-mesh.ts';
2
+ import type { Mesh } from '../core/mesh.ts';
3
+ import { type MeshPool } from './current-mesh.ts';
3
4
  import type { CapabilityHandlers } from '../../spec/capabilities.d.ts';
4
- export declare function createDevicesApi(current: CurrentMesh, deviceId: Buffer, removeWriter: (writerKey: Buffer, deviceId: Buffer) => Promise<void>, renameLocal: (name: string) => Promise<void>, saveProfileLocal: (capabilityProfile: AssistantCapabilityProfile, recommendedModelName: string, platform?: string) => Promise<void>, readLocalProfile: () => {
5
+ export declare function createDevicesApi(pool: MeshPool, deviceId: Buffer, removeWriter: (writerKey: Buffer, deviceId: Buffer, mesh: Mesh) => Promise<void>, renameLocal: (name: string) => Promise<void>, saveProfileLocal: (capabilityProfile: AssistantCapabilityProfile, recommendedModelName: string, platform?: string) => Promise<void>, readLocalProfile: () => {
5
6
  capabilityProfile: AssistantCapabilityProfile;
6
7
  recommendedModelName: string;
7
8
  platform?: string;
8
- } | null, computeLender?: (() => Promise<Buffer | null>) | null): Pick<CapabilityHandlers, 'listDevices' | 'devicesWatch' | 'deviceInfo' | 'saveDeviceCapabilities' | 'saveDeviceProfile' | 'removeDevice' | 'renameDevice'>;
9
+ } | null, computeLender?: (() => Promise<Buffer | null>) | null): Pick<CapabilityHandlers, 'listDevices' | 'getDevice' | 'devicesWatch' | 'deviceInfo' | 'saveDeviceCapabilities' | 'saveDeviceProfile' | 'removeDevice' | 'renameDevice'>;