@qvac/core 0.7.0 → 0.7.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 (74) hide show
  1. package/CHANGELOG.md +80 -1
  2. package/dist-lib/lib/api/chat.d.ts +1 -1
  3. package/dist-lib/lib/api/chat.js +9 -0
  4. package/dist-lib/lib/api/index.d.ts +2 -1
  5. package/dist-lib/lib/api/index.js +2 -1
  6. package/dist-lib/lib/api/network.d.ts +8 -1
  7. package/dist-lib/lib/api/network.js +6 -0
  8. package/dist-lib/lib/assistant/harness.d.ts +2 -0
  9. package/dist-lib/lib/assistant.js +9 -4
  10. package/dist-lib/lib/core/agent.d.ts +2 -0
  11. package/dist-lib/lib/core/agent.js +16 -5
  12. package/dist-lib/lib/core/blind-peers.d.ts +4 -0
  13. package/dist-lib/lib/core/blind-peers.js +1 -0
  14. package/dist-lib/lib/core/chat-copy.d.ts +4 -0
  15. package/dist-lib/lib/core/chat-copy.js +1 -1
  16. package/dist-lib/lib/core/chat-fork.d.ts +21 -0
  17. package/dist-lib/lib/core/chat-fork.js +245 -0
  18. package/dist-lib/lib/core/chat-move.js +1 -4
  19. package/dist-lib/lib/core/chat.d.ts +1 -0
  20. package/dist-lib/lib/core/chat.js +1 -1
  21. package/dist-lib/lib/core/departures.d.ts +5 -1
  22. package/dist-lib/lib/core/departures.js +15 -1
  23. package/dist-lib/lib/core/fs-drives.d.ts +8 -1
  24. package/dist-lib/lib/core/fs-drives.js +47 -15
  25. package/dist-lib/lib/core/harness-loan.d.ts +4 -20
  26. package/dist-lib/lib/core/harness-loan.js +7 -184
  27. package/dist-lib/lib/core/id.d.ts +1 -0
  28. package/dist-lib/lib/core/id.js +3 -0
  29. package/dist-lib/lib/core/mesh.d.ts +3 -2
  30. package/dist-lib/lib/core/mesh.js +11 -1
  31. package/dist-lib/lib/core/migrations/agent-tools-scope.d.ts +2 -0
  32. package/dist-lib/lib/core/migrations/agent-tools-scope.js +24 -0
  33. package/dist-lib/lib/core/migrations/index.js +3 -1
  34. package/dist-lib/lib/core/peer-duplex.d.ts +32 -0
  35. package/dist-lib/lib/core/peer-duplex.js +207 -0
  36. package/dist-lib/lib/core.d.ts +17 -1
  37. package/dist-lib/lib/core.js +183 -10
  38. package/dist-lib/lib/doctor/checks.js +4 -1
  39. package/dist-lib/lib/inference-calls.d.ts +1 -2
  40. package/dist-lib/lib/inference-calls.js +1 -5
  41. package/dist-lib/lib/mesh-scoped-engine.js +3 -0
  42. package/dist-lib/lib/model-download.d.ts +0 -9
  43. package/dist-lib/lib/model-download.js +1 -13
  44. package/dist-lib/lib/persistent-dir.d.ts +1 -0
  45. package/dist-lib/lib/persistent-dir.js +9 -0
  46. package/dist-lib/lib/run-replay.d.ts +1 -2
  47. package/dist-lib/lib/run-replay.js +1 -5
  48. package/dist-lib/lib/test-env.d.ts +1 -0
  49. package/dist-lib/lib/test-env.js +4 -0
  50. package/dist-lib/schema/engine.js +45 -1
  51. package/dist-lib/schema/field-order.js +1 -1
  52. package/dist-lib/schema/qvac.js +10 -1
  53. package/dist-lib/spec/bind.js +14 -0
  54. package/dist-lib/spec/calls.js +3 -0
  55. package/dist-lib/spec/capabilities.d.ts +6 -0
  56. package/dist-lib/spec/hrpc/hrpc.json +39 -0
  57. package/dist-lib/spec/hrpc/index.js +41 -4
  58. package/dist-lib/spec/hrpc/messages.js +1420 -1289
  59. package/dist-lib/spec/hyperschema/index.js +1420 -1289
  60. package/dist-lib/spec/hyperschema/schema.json +102 -0
  61. package/dist-lib/spec/hyperschema/types.d.ts +29 -0
  62. package/dist-lib/spec/mesh/hyperdb/messages.js +295 -248
  63. package/dist-lib/spec/mesh/hyperdispatch/messages.js +45 -5
  64. package/dist-lib/spec/mesh/hyperschema/index.js +45 -5
  65. package/dist-lib/spec/mesh/hyperschema/schema.json +31 -1
  66. package/dist-lib/spec/mesh/hyperschema/types.d.ts +9 -1
  67. package/package.json +10 -7
  68. package/tui/README.md +8 -5
  69. package/tui/app.mjs +151 -67
  70. package/tui/boot.mjs +5 -1
  71. package/tui/index.mjs +2 -1
  72. package/tui/lib/fork-command.mjs +43 -0
  73. package/dist-lib/lib/image-cache-dir.d.ts +0 -1
  74. package/dist-lib/lib/image-cache-dir.js +0 -5
package/CHANGELOG.md CHANGED
@@ -13,6 +13,83 @@ release.
13
13
 
14
14
  ## [Unreleased]
15
15
 
16
+ ## [0.7.2] - 2026-10-13
17
+
18
+ ### Added
19
+
20
+ - `duck --join <invite>` (`-j`) joins a mesh invite at boot, so a `--headless` peer, which has no prompt to `/join` from, can get onto an existing mesh. A device invite pairs it into your account; a member invite adds a shared mesh to its own. (#371)
21
+
22
+ ```sh
23
+ duck --headless --storage ~/duck-data --join qvac://mesh/…
24
+ ```
25
+
26
+ - `/rename device <name>` names this device and `/rename member <name>` names you in every mesh at once, so a roster of `duck-<pid>` devices can be told apart. (#372)
27
+
28
+ ## [0.7.1] - 2026-10-12
29
+
30
+ ### Added
31
+
32
+ - `forkChat` copies a chat into a new one, through a turn or just before it, in
33
+ the same mesh or another (QVAC-26722). The source stays as it was, the fork
34
+ lands on top of its list with ids of its own, and `AssistantChat` names where
35
+ it came from in `forkedFrom`. Its files are its own copies, so removing one
36
+ in either chat leaves the other's, and into another mesh it needs one of that
37
+ mesh's agents. (#346)
38
+
39
+ ```js
40
+ const fork = await engine.forkChat({ meshId, chatId, runId: reply.runId })
41
+ ```
42
+
43
+ - `setBlindPeering` and `blindPeeringWatch` turn every blind peering on this
44
+ device off or back on, kept across restarts, for reproducing sync with no
45
+ mirror in the middle. `diagnostics` reports it as `stats.mesh.blindPeering`,
46
+ and a `recoveryPublish` made while it is off does not mark the account
47
+ recoverable. (#334)
48
+
49
+ ```js
50
+ await engine.setBlindPeering({ enabled: false })
51
+ ```
52
+
53
+ ### Changed
54
+
55
+ - `@qvac/harness` is `^0.8.7` and `@qvac/skills` 0.1.14, which bring the
56
+ `browser` skill. Every run now hands the harness its chat as `session`, with
57
+ or without a cache key, so a skill whose manifest declares
58
+ `${session}` in its `env` keeps one resource per chat, such as the browser
59
+ the `browser` skill drives. (#369)
60
+ - `createAgent` and `updateAgent` ignore `toolsScope` and `enabledTools` and
61
+ always store `toolsScope: 'all'`, leaving `disabledToolsets` as the only
62
+ per-agent gate on tools. Each mesh rewrites its stored `selected` agents to
63
+ `all` once on open, so an agent saved with an empty list runs with its tools
64
+ again. (#363)
65
+
66
+ ### Fixed
67
+
68
+ - The harness is handed the turn as typed, so a skill mention or a search ask
69
+ is read from what the user wrote, not from attached documents, knowledge or
70
+ sender lines wrapped around it (QVAC-24963). Before,
71
+ `@pdf Summarize these docs` with a PDF attached could load
72
+ `image-generation`, and a document saying "search the web" went out as the
73
+ search query. (#347)
74
+ - The model downloader picks the text-to-speech model for the profile the
75
+ hardware probe found, the same one speaking asks for (QVAC-25679). Before, a
76
+ new device could plan its downloads while its row still held the host's seed
77
+ profile and keep that for the session, so a "mid" or higher device fetched
78
+ `Supertonic3-Q4_0` while read aloud waited for `Supertonic3-FP16` and stayed
79
+ disabled until a restart. If the probe fails, it plans for "low", the voice
80
+ the harness then speaks with. (#367)
81
+ - A device dials the other devices of its account by key as well as finding
82
+ them on the mesh topic, and dials them again on resume. Before, a topic
83
+ refresh that missed after a suspend or a network change left a phone without
84
+ its Mac for ten minutes or more, so a chat with an agent the Mac hosted sat
85
+ on "waiting to reconnect" though both were online. (#327)
86
+ - `removeDevice` on a device of our own member moves the agents it hosted to
87
+ the device that removed it, in that mesh and, for a removal from the account,
88
+ in every shared mesh of ours it is revoked in, so a run waiting on the removed
89
+ device runs there; a removal made on an earlier build is caught up on the
90
+ next boot. Before, the agents stayed orphaned and the chat waited forever.
91
+ (#327)
92
+
16
93
  ## [0.7.0] - 2026-10-09
17
94
 
18
95
  ### Added
@@ -1416,7 +1493,9 @@ Published under the `release-0.1` dist-tag.
1416
1493
  await assistant.ready()
1417
1494
  ```
1418
1495
 
1419
- [Unreleased]: https://github.com/tetherto/qvac-core/compare/v0.7.0...HEAD
1496
+ [Unreleased]: https://github.com/tetherto/qvac-core/compare/v0.7.2...HEAD
1497
+ [0.7.2]: https://github.com/tetherto/qvac-core/compare/v0.7.1...v0.7.2
1498
+ [0.7.1]: https://github.com/tetherto/qvac-core/compare/v0.7.0...v0.7.1
1420
1499
  [0.7.0]: https://github.com/tetherto/qvac-core/compare/v0.6.7...v0.7.0
1421
1500
  [0.6.7]: https://github.com/tetherto/qvac-core/compare/v0.6.6...v0.6.7
1422
1501
  [0.6.6]: https://github.com/tetherto/qvac-core/compare/v0.6.5...v0.6.6
@@ -2,7 +2,7 @@ import type { CapabilityHandlers } from '../../spec/capabilities.d.ts';
2
2
  import type { openLocalStore } from '../core/local/index.ts';
3
3
  import { type MeshPool } from './current-mesh.ts';
4
4
  type LocalStore = ReturnType<typeof openLocalStore>;
5
- type ChatCapabilities = Pick<CapabilityHandlers, 'createChat' | 'listChats' | 'getChat' | 'renameChat' | 'markChatRead' | 'setChatAgent' | 'setChatRagEnabled' | 'setChatWebSearchEnabled' | 'deleteChat' | 'chatsWatch' | 'listChatActivity' | 'chatActivityWatch' | 'searchChats'>;
5
+ type ChatCapabilities = Pick<CapabilityHandlers, 'createChat' | 'listChats' | 'getChat' | 'renameChat' | 'markChatRead' | 'setChatAgent' | 'forkChat' | 'setChatRagEnabled' | 'setChatWebSearchEnabled' | 'deleteChat' | 'chatsWatch' | 'listChatActivity' | 'chatActivityWatch' | 'searchChats'>;
6
6
  export interface CreateChatApiOptions {
7
7
  readonly deviceId: Buffer | null;
8
8
  readonly inferenceCalls?: {
@@ -1,10 +1,12 @@
1
1
  import { AbortController } from 'bare-abort-controller';
2
2
  import { createChat, deleteChat, markChatRead, mustGetActiveChatListing, renameChat, setChatAgent, setChatRagEnabled, setChatWebSearchEnabled } from '../core/chat.js';
3
3
  import { listChatActivity } from '../core/chat-activity.js';
4
+ import { forkChat } from '../core/chat-fork.js';
4
5
  import { listChatPage } from '../core/chat-order.js';
5
6
  import { searchChats } from '../core/chat-search.js';
6
7
  import { meshWatchable, requireMesh } from './current-mesh.js';
7
8
  const SEARCH_SUPERSEDED_ABORT = 'superseded by a newer chat search';
9
+ const NO_DEVICE = 'this device has no identity yet, so it cannot write a fork';
8
10
  export function createChatApi(pool, local, { deviceId, inferenceCalls = null }) {
9
11
  let searchAbort = null;
10
12
  const chatList = (mesh, { limit, cursor }) => listChatPage(mesh, local, { limit: limit || undefined, cursor: cursor ?? undefined });
@@ -16,6 +18,13 @@ export function createChatApi(pool, local, { deviceId, inferenceCalls = null })
16
18
  renameChat: async ({ chatId, meshId, config }) => renameChat(await requireMesh(pool, meshId), chatId, config.title),
17
19
  markChatRead: async ({ chatId, meshId }) => markChatRead(await requireMesh(pool, meshId), chatId),
18
20
  setChatAgent: async ({ chatId, agentId, meshId }) => setChatAgent(await requireMesh(pool, meshId), chatId, agentId),
21
+ forkChat: async ({ meshId, targetMeshId, config, ...cut }) => {
22
+ if (!deviceId)
23
+ throw new Error(NO_DEVICE);
24
+ const from = await requireMesh(pool, meshId);
25
+ const into = targetMeshId ? await requireMesh(pool, targetMeshId) : from;
26
+ return forkChat({ from, into }, { ...cut, title: config?.title, originDeviceId: deviceId });
27
+ },
19
28
  setChatRagEnabled: async ({ chatId, enabled, meshId }) => setChatRagEnabled(await requireMesh(pool, meshId), chatId, { ragEnabled: enabled ?? false }),
20
29
  setChatWebSearchEnabled: async ({ chatId, enabled, meshId }) => setChatWebSearchEnabled(await requireMesh(pool, meshId), chatId, enabled ?? false),
21
30
  deleteChat: async ({ chatId, meshId }) => {
@@ -8,7 +8,7 @@ import { type DiagnosticsSource } from './diagnostics.ts';
8
8
  import { type InferenceCallReader } from './inference-calls.ts';
9
9
  import { type LogSource } from './logs.ts';
10
10
  import { type MeshStatusSource } from './mesh.ts';
11
- import { type NetworkSource } from './network.ts';
11
+ import { type BlindPeeringSource, type NetworkSource } from './network.ts';
12
12
  import { type CustomModelPreviewSource } from './custom-models.ts';
13
13
  import type { IndexingEmbedder, VectorIndex } from '../core/files/index.ts';
14
14
  interface ApiDeps {
@@ -16,6 +16,7 @@ interface ApiDeps {
16
16
  mesh?: MeshPool | null;
17
17
  meshStatus?: MeshStatusSource | null;
18
18
  network?: NetworkSource | null;
19
+ blindPeering?: BlindPeeringSource | null;
19
20
  diagnostics?: DiagnosticsSource | null;
20
21
  inferenceCalls?: InferenceCallReader | null;
21
22
  chatMoves?: ChatMoves | null;
@@ -22,7 +22,7 @@ import { instrument } from './instrument.js';
22
22
  import { watchable } from './watchable.js';
23
23
  import { createMembersApi } from './members.js';
24
24
  import { createMeshApi } from './mesh.js';
25
- import { createNetworkApi } from './network.js';
25
+ import { createBlindPeeringApi, createNetworkApi } from './network.js';
26
26
  import { createNotificationsApi } from './notifications.js';
27
27
  import { createModelDownloadApi } from './model-download.js';
28
28
  import { createCustomModelApi } from './custom-models.js';
@@ -87,6 +87,7 @@ export function createApi(deps = {}) {
87
87
  ...members,
88
88
  ...(deps.meshStatus && members ? createMeshApi(deps.meshStatus, members.updateMember) : null),
89
89
  ...(deps.network ? createNetworkApi(deps.network) : null),
90
+ ...(deps.blindPeering ? createBlindPeeringApi(deps.blindPeering) : null),
90
91
  ...(deps.diagnostics ? createDiagnosticsApi(deps.diagnostics) : null),
91
92
  ...(deps.inferenceCalls ? createInferenceCallsApi(deps.inferenceCalls) : null),
92
93
  ...(deps.logs ? createLogsApi(deps.logs) : null),
@@ -1,4 +1,4 @@
1
- import type { AssistantNetworkStatus } from '../../spec/hyperschema/types.d.ts';
1
+ import type { AssistantBlindPeering, AssistantNetworkStatus } from '../../spec/hyperschema/types.d.ts';
2
2
  import type { CapabilityHandlers } from '../../spec/capabilities.d.ts';
3
3
  export interface NetworkSource {
4
4
  watch(listener: () => void): void;
@@ -6,4 +6,11 @@ export interface NetworkSource {
6
6
  snapshot(): AssistantNetworkStatus;
7
7
  readonly sampled: true;
8
8
  }
9
+ export interface BlindPeeringSource {
10
+ watch(listener: () => void): void;
11
+ unwatch(listener: () => void): void;
12
+ snapshot(): AssistantBlindPeering;
13
+ set(enabled: boolean): Promise<AssistantBlindPeering>;
14
+ }
9
15
  export declare function createNetworkApi(source: NetworkSource): Pick<CapabilityHandlers, 'networkWatch'>;
16
+ export declare function createBlindPeeringApi(source: BlindPeeringSource): Pick<CapabilityHandlers, 'setBlindPeering' | 'blindPeeringWatch'>;
@@ -4,3 +4,9 @@ export function createNetworkApi(source) {
4
4
  networkWatch: watchable(() => source, async () => source.snapshot(), { name: 'networkWatch' })
5
5
  };
6
6
  }
7
+ export function createBlindPeeringApi(source) {
8
+ return {
9
+ setBlindPeering: ({ enabled }) => source.set(enabled === true),
10
+ blindPeeringWatch: watchable(() => source, async () => source.snapshot(), { name: 'blindPeeringWatch' })
11
+ };
12
+ }
@@ -86,7 +86,9 @@ export interface Harness {
86
86
  model: string;
87
87
  agent: AssistantAgent;
88
88
  messages: ChatMessage[];
89
+ typedText?: string;
89
90
  cacheKey?: string;
91
+ session?: string;
90
92
  thinkingDefault?: string;
91
93
  toolConfigs?: Record<string, Record<string, unknown>>;
92
94
  captureInferenceCalls?: boolean;
@@ -33,7 +33,7 @@ import { InferenceCallStore } from './inference-calls.js';
33
33
  import { LOCAL_HOLDER, RunReplayStore, trackSentRun } from './run-replay.js';
34
34
  import { fsGrantKey, fsWriteGrantKey } from './fs-grant-keys.js';
35
35
  import { fsGrantsFrom, grantedDirsFrom } from './fs-grants.js';
36
- import { defaultImageCacheDir } from './image-cache-dir.js';
36
+ import { persistentDir } from './persistent-dir.js';
37
37
  import { ModelCatalogRevisionHub } from './model-catalog-revision.js';
38
38
  import { agentRekeyFingerprint, agentSwitched, chatKvCacheKey, chatRepairKvCacheKey, disappearedChatIds } from './kv-cache-reclaim.js';
39
39
  import { buildCompactionPrompt, canCompact, foldReducesPrompt, COMPACTION_KEEP_TURNS, COMPACTION_TURN_PREFIX, isContextOverflowFailure, nearContextLimit, compactionBoundary, lastCompactedThroughId, parseCompactionSummary } from './compaction.js';
@@ -201,7 +201,7 @@ export class QvacAssistant extends ReadyResource {
201
201
  this._borrowHarness = borrowHarness ?? null;
202
202
  this._drives = drives;
203
203
  this._log = logger;
204
- this._imageCacheDir = imageCacheDir ?? defaultImageCacheDir();
204
+ this._imageCacheDir = imageCacheDir ?? persistentDir('image-cache');
205
205
  this._imageCacheMaxBytes = imageCacheMaxBytes;
206
206
  this._imageCacheMaxAgeMs = imageCacheMaxAgeMs;
207
207
  this._downloadRetryMs = downloadRetryMs;
@@ -229,8 +229,8 @@ export class QvacAssistant extends ReadyResource {
229
229
  this._meshConsumers = new Map();
230
230
  this._runs = new Map();
231
231
  this._seen = new Map();
232
- this._inferenceCalls = new InferenceCallStore(inferenceCallsDir);
233
- this._runReplay = new RunReplayStore(runReplayDir);
232
+ this._inferenceCalls = new InferenceCallStore(inferenceCallsDir ?? persistentDir('inspector'));
233
+ this._runReplay = new RunReplayStore(runReplayDir ?? persistentDir('run-replay'));
234
234
  this._lifecycle = new AbortController();
235
235
  this._audioTranscripts = new Map();
236
236
  this._pdfPages = new Map();
@@ -1598,6 +1598,9 @@ export class QvacAssistant extends ReadyResource {
1598
1598
  const stale = staleToolRunIds(history, priorAsks ?? [], runId);
1599
1599
  const sentRuns = await this._sentRuns(chatId, holder);
1600
1600
  const messages = historyFromChunks(history, stale, { senderNames: senders, sentRuns });
1601
+ const typedText = currentRepair
1602
+ ? undefined
1603
+ : history.findLast((chunk) => chunk.userMessage)?.userMessage?.text;
1601
1604
  if (currentRepair) {
1602
1605
  messages.push({ role: 'user', content: currentRepair.promptText });
1603
1606
  }
@@ -1864,7 +1867,9 @@ export class QvacAssistant extends ReadyResource {
1864
1867
  model,
1865
1868
  agent: runAgent,
1866
1869
  messages: input,
1870
+ typedText,
1867
1871
  cacheKey,
1872
+ session: chatKvCacheKey(chatId),
1868
1873
  thinkingDefault: thinkingDefault(config),
1869
1874
  toolConfigs,
1870
1875
  grantedDirs,
@@ -1,6 +1,7 @@
1
1
  import type { AssistantAgentConfig, AssistantAgentUpdateConfig } from '../../spec/hyperschema/types.d.ts';
2
2
  import type { QvacAgent } from '../../spec/mesh/hyperschema/types.d.ts';
3
3
  import type { Mesh } from './mesh.ts';
4
+ export declare function allTools(): Pick<QvacAgent, 'toolsScope' | 'enabledTools'>;
4
5
  export declare function listAgents(store: Mesh, providerDeviceId?: Buffer): Promise<QvacAgent[]>;
5
6
  export declare function getDefaultAgent(store: Mesh, providerDeviceId?: Buffer): Promise<QvacAgent | null>;
6
7
  export declare function getAgent(store: Mesh, id: string): Promise<QvacAgent | null>;
@@ -10,4 +11,5 @@ export declare function mustGetAgent(store: Mesh, id: string): Promise<QvacAgent
10
11
  export declare function mustGetActiveAgent(store: Mesh, id: string): Promise<QvacAgent>;
11
12
  export declare function createAgent(store: Mesh, input: AssistantAgentConfig): Promise<QvacAgent>;
12
13
  export declare function updateAgent(store: Mesh, agentId: string, input: AssistantAgentUpdateConfig): Promise<QvacAgent>;
14
+ export declare function rehomeAgents(store: Mesh, from: Buffer, to: Buffer): Promise<void>;
13
15
  export declare function deleteAgent(store: Mesh, deviceId: Buffer | null, id: string): Promise<QvacAgent>;
@@ -4,6 +4,9 @@ import { softDeleteToolConfigsForAgent } from './tool-configs.js';
4
4
  import b4a from 'b4a';
5
5
  import { ACTIVE_AGENTS, AGENTS, AGENTS_BY_PROVIDER, DEFAULT_AGENTS, DEVICES } from './collections.js';
6
6
  const DEFAULT_ICON_NAME = 'artificial-intelligence';
7
+ export function allTools() {
8
+ return { toolsScope: 'all', enabledTools: [] };
9
+ }
7
10
  function mergeSkills(base, enabled) {
8
11
  return Array.from(new Set([...(base ?? []), ...(enabled ?? [])]));
9
12
  }
@@ -89,7 +92,6 @@ export async function mustGetActiveAgent(store, id) {
89
92
  export async function createAgent(store, input) {
90
93
  const now = Date.now();
91
94
  const enabledSkills = input.enabledSkills ?? [];
92
- const enabledTools = input.enabledTools ?? [];
93
95
  const installedBase = input.installedSkills ?? enabledSkills;
94
96
  const agent = {
95
97
  id: randomId(),
@@ -99,7 +101,7 @@ export async function createAgent(store, input) {
99
101
  modelName: input.modelName,
100
102
  reasoning: input.reasoning ?? 'inherit',
101
103
  enabledSkills,
102
- enabledTools,
104
+ ...allTools(),
103
105
  installedSkills: mergeSkills(installedBase, enabledSkills),
104
106
  isDefault: input.isDefault ?? false,
105
107
  createdAt: now,
@@ -110,7 +112,6 @@ export async function createAgent(store, input) {
110
112
  kvCacheV: input.kvCacheV ?? undefined,
111
113
  iconName: input.iconName ?? DEFAULT_ICON_NAME,
112
114
  ctxSize: input.ctxSize || undefined,
113
- toolsScope: input.toolsScope ?? 'selected',
114
115
  skillsScope: input.skillsScope ?? 'selected',
115
116
  imageSteps: input.imageSteps || undefined,
116
117
  imageWidth: input.imageWidth || undefined,
@@ -166,7 +167,6 @@ export async function updateAgent(store, agentId, input) {
166
167
  modelName: patch(input.modelName, current.modelName),
167
168
  reasoning: patch(input.reasoning, current.reasoning),
168
169
  enabledSkills,
169
- enabledTools: patch(input.enabledTools, current.enabledTools),
170
170
  installedSkills: mergeSkills(installedBase, enabledSkills),
171
171
  isDefault: input.clearIsDefault ? false : input.isDefault || current.isDefault,
172
172
  imageModelChoice: patch(input.imageModelChoice, imageBase.imageModelChoice),
@@ -174,7 +174,7 @@ export async function updateAgent(store, agentId, input) {
174
174
  kvCacheV: patch(input.kvCacheV, current.kvCacheV),
175
175
  iconName: patch(input.iconName, current.iconName),
176
176
  ctxSize: input.clearCtxSize ? undefined : input.ctxSize || current.ctxSize || undefined,
177
- toolsScope: patch(input.toolsScope, current.toolsScope),
177
+ ...allTools(),
178
178
  skillsScope: patch(input.skillsScope, current.skillsScope),
179
179
  imageSteps: input.imageSteps || imageBase.imageSteps || undefined,
180
180
  imageWidth: input.imageWidth || imageBase.imageWidth || undefined,
@@ -189,6 +189,17 @@ export async function updateAgent(store, agentId, input) {
189
189
  await store.dispatch('put-agent', { agent: updated });
190
190
  return updated;
191
191
  }
192
+ export async function rehomeAgents(store, from, to) {
193
+ const hasDefault = (await getDefaultAgent(store, to)) !== null;
194
+ for (const agent of await listAgents(store, from)) {
195
+ if (!agent.deletedAt) {
196
+ await updateAgent(store, agent.id, {
197
+ providerDeviceId: to,
198
+ clearIsDefault: hasDefault && agent.isDefault
199
+ });
200
+ }
201
+ }
202
+ }
192
203
  export async function deleteAgent(store, deviceId, id) {
193
204
  const current = await mustGetAgent(store, id);
194
205
  if (current.isDefault) {
@@ -1,3 +1,7 @@
1
+ export declare const BLIND_PEERING_OFF_KEY = "debug.blindPeeringOff";
2
+ export interface StartBlindPeeringOpts {
3
+ readonly suspended?: boolean;
4
+ }
1
5
  export interface BlindPeeringOpts {
2
6
  readonly batchIdleWait?: number;
3
7
  readonly batchMaxWait?: number;
@@ -1,4 +1,5 @@
1
1
  import { decode } from 'z32';
2
+ export const BLIND_PEERING_OFF_KEY = 'debug.blindPeeringOff';
2
3
  export const BLIND_RELAY_KEYS = [
3
4
  'tgbo7m8fh3hwqqxj95zrezorjgodtjr19b9dqruyauwnbafsmx8y',
4
5
  'tfo1aqsc4hc4ok6a4akpxifkp65efoo9n13g1386zoa7umjipqpo',
@@ -14,6 +14,10 @@ export declare function copyChunks(snap: HyperDB, chatId: string, { from, into }
14
14
  export declare function copyMovedChunks(snap: HyperDB, chatId: string, copy: ChatMoveCopy): Promise<number>;
15
15
  export declare function copyMovedKnowledge(snap: HyperDB, chatId: string, copy: ChatMoveCopy): Promise<void>;
16
16
  export declare function movedBlob({ from, into, references }: ChatMoveCopy, { blobId }: BlobHolder): Promise<string>;
17
+ export declare function removedReference({ mimeType }: TypedFile): string;
18
+ interface TypedFile {
19
+ readonly mimeType: string;
20
+ }
17
21
  interface BlobHolder {
18
22
  readonly blobId: string;
19
23
  }
@@ -83,7 +83,7 @@ export async function movedBlob({ from, into, references }, { blobId }) {
83
83
  }
84
84
  return moved;
85
85
  }
86
- function removedReference({ mimeType }) {
86
+ export function removedReference({ mimeType }) {
87
87
  return inlineReference(b4a.alloc(0), mimeType);
88
88
  }
89
89
  async function heldInTarget(into, { collection, id, chatId }) {
@@ -0,0 +1,21 @@
1
+ import { type ChatListing } from './chat.ts';
2
+ import type { Mesh } from './mesh.ts';
3
+ export declare const NO_SUCH_TURN = "no turn of this chat has that run id";
4
+ export declare const TURN_RUNNING = "a turn up to the fork point is still running; fork once it has finished";
5
+ export declare const NOTHING_BEFORE = "nothing comes before the first turn, so there is nothing to fork";
6
+ export declare const AGENT_REQUIRED = "a chat forked into another mesh needs an agent of that mesh";
7
+ export declare const FILE_ARRIVING = "a file in this chat is still arriving; fork once it has landed";
8
+ export declare const FILE_NOT_HERE = "a file in this chat is not on this device yet; open it here first";
9
+ export interface ForkMeshes {
10
+ readonly from: Mesh;
11
+ readonly into: Mesh;
12
+ }
13
+ export interface ForkChatInput {
14
+ readonly chatId: string;
15
+ readonly runId?: string | null;
16
+ readonly exclusive?: boolean;
17
+ readonly agentId?: string | null;
18
+ readonly title?: string | null;
19
+ readonly originDeviceId: Buffer;
20
+ }
21
+ export declare function forkChat(meshes: ForkMeshes, input: ForkChatInput): Promise<ChatListing>;
@@ -0,0 +1,245 @@
1
+ import b4a from 'b4a';
2
+ import { mustGetActiveAgent } from './agent.js';
3
+ import { TERMINAL_RUN_STATES, enrichChat, listSidebar } from './chat.js';
4
+ import { copyBlob, removedReference, stripped } from './chat-copy.js';
5
+ import { COMPUTE_MESH, NOT_A_WRITER } from './chat-move.js';
6
+ import { chatSortKey } from './chat-order.js';
7
+ import { isPendingBlobReference } from './files/index.js';
8
+ import { groupAttachmentsByMessage } from './files/records/linkage.js';
9
+ import { derivedId, randomId } from './id.js';
10
+ import { rankOnTop } from './rank.js';
11
+ import { CHATS, CHUNKS_BY_CHAT, KNOWLEDGE_BY_CHAT } from './collections.js';
12
+ export const NO_SUCH_TURN = 'no turn of this chat has that run id';
13
+ export const TURN_RUNNING = 'a turn up to the fork point is still running; fork once it has finished';
14
+ export const NOTHING_BEFORE = 'nothing comes before the first turn, so there is nothing to fork';
15
+ export const AGENT_REQUIRED = 'a chat forked into another mesh needs an agent of that mesh';
16
+ export const FILE_ARRIVING = 'a file in this chat is still arriving; fork once it has landed';
17
+ export const FILE_NOT_HERE = 'a file in this chat is not on this device yet; open it here first';
18
+ export async function forkChat(meshes, input) {
19
+ const { into } = meshes;
20
+ if (meshes.from.compute || into.compute) {
21
+ throw new Error(COMPUTE_MESH);
22
+ }
23
+ if (!into.writable) {
24
+ throw new Error(NOT_A_WRITER);
25
+ }
26
+ const plan = await forkPlan(meshes, input);
27
+ const batch = into.batch();
28
+ batch.dispatch('put-chat', { chat: plan.chat });
29
+ for (const chunk of plan.chunks) {
30
+ batch.dispatch('append-chunk', chunk);
31
+ }
32
+ for (const knowledge of plan.knowledge) {
33
+ batch.dispatch('add-knowledge', { knowledge });
34
+ }
35
+ await batch.flush();
36
+ await into.fileIndex?.record(plan.chunks.filter((chunk) => chunk.attachment));
37
+ return enrichChat(into, plan.chat);
38
+ }
39
+ async function forkPlan(meshes, input) {
40
+ const snap = meshes.from.view.snapshot();
41
+ try {
42
+ const source = await snap.get(CHATS, { id: input.chatId });
43
+ if (!source || source.deletedAt) {
44
+ throw new Error(`chat not found: ${input.chatId}`);
45
+ }
46
+ const all = await chunksOf(snap, source.id);
47
+ const cut = forkCut(all, input);
48
+ const documents = await documentsOf(snap, { source, all, cut });
49
+ const ctx = contextOf(meshes, { cut, documents, originDeviceId: input.originDeviceId });
50
+ const agentId = await forkAgentId(ctx, { source, agentId: input.agentId });
51
+ const chunks = await forkedChunks(ctx, cut.chunks);
52
+ const knowledge = await forkedDocuments(ctx, documents);
53
+ const chat = await forkedChat(ctx, { source, cut, agentId, title: input.title, chunks });
54
+ return { chat, chunks, knowledge };
55
+ }
56
+ finally {
57
+ await snap.close();
58
+ }
59
+ }
60
+ function forkCut(chunks, input) {
61
+ const requests = chunks.filter((chunk) => chunk.type === 'run-request' && chunk.runId);
62
+ const finished = finishedRuns(chunks);
63
+ const end = input.runId ? endAt(requests, input) : settledEnd(requests, finished);
64
+ const included = requests.slice(0, end);
65
+ if (included.some((request) => !finished.has(request.runId ?? ''))) {
66
+ throw new Error(TURN_RUNNING);
67
+ }
68
+ const turns = new Set(requests.map((request) => request.runId));
69
+ const runs = new Set(included.map((request) => request.runId));
70
+ const next = requests[end];
71
+ const from = next ? turnStart(chunks, { next, included }) : Infinity;
72
+ const kept = [];
73
+ let before = Infinity;
74
+ for (const chunk of chunks) {
75
+ if (turns.has(chunk.runId) ? runs.has(chunk.runId) : chunk.seq < from) {
76
+ kept.push(chunk);
77
+ }
78
+ else {
79
+ before = Math.min(before, chunk.createdAt);
80
+ }
81
+ }
82
+ return { chunks: kept, before, runId: included.at(-1)?.runId ?? undefined };
83
+ }
84
+ function endAt(requests, { runId, exclusive }) {
85
+ const at = requests.findIndex((request) => request.runId === runId);
86
+ if (at === -1) {
87
+ throw new Error(NO_SUCH_TURN);
88
+ }
89
+ const end = exclusive ? at : at + 1;
90
+ if (end === 0) {
91
+ throw new Error(NOTHING_BEFORE);
92
+ }
93
+ return end;
94
+ }
95
+ function settledEnd(requests, finished) {
96
+ const running = requests.findIndex((request) => !finished.has(request.runId ?? ''));
97
+ if (running === 0) {
98
+ throw new Error(TURN_RUNNING);
99
+ }
100
+ return running === -1 ? requests.length : running;
101
+ }
102
+ function finishedRuns(chunks) {
103
+ const runs = new Set();
104
+ for (const chunk of chunks) {
105
+ if (chunk.runId && TERMINAL_RUN_STATES.has(chunk.runStatus?.state ?? '')) {
106
+ runs.add(chunk.runId);
107
+ }
108
+ }
109
+ return runs;
110
+ }
111
+ function turnStart(chunks, { next, included }) {
112
+ const messages = chunks.filter((chunk) => chunk.type === 'user-message' && !chunk.runId);
113
+ const message = messages.findLast((chunk) => chunk.seq < next.seq);
114
+ const answered = (included.at(-1)?.seq ?? -1) > (message?.seq ?? -1);
115
+ if (!message || answered) {
116
+ return next.seq;
117
+ }
118
+ const attachments = chunks.filter((chunk) => chunk.type === 'attachment');
119
+ const bound = groupAttachmentsByMessage(attachments, messages).get(message.id) ?? [];
120
+ return Math.min(message.seq, ...bound.map((chunk) => chunk.seq));
121
+ }
122
+ async function documentsOf(snap, { source, all, cut }) {
123
+ const inChat = { gte: { chatId: source.id }, lte: { chatId: source.id } };
124
+ const rows = await snap.find(KNOWLEDGE_BY_CHAT, inChat).toArray();
125
+ const attached = new Set(all.map(fileIdOf));
126
+ const carried = new Set(cut.chunks.map(fileIdOf));
127
+ return rows.filter((row) => attached.has(row.id) ? carried.has(row.id) : row.createdAt < cut.before);
128
+ }
129
+ function fileIdOf(chunk) {
130
+ return chunk.attachment?.id;
131
+ }
132
+ function contextOf(meshes, { cut, documents, originDeviceId }) {
133
+ const files = cut.chunks.map(fileIdOf).filter((id) => id !== undefined);
134
+ return {
135
+ ...meshes,
136
+ same: b4a.equals(meshes.from.key, meshes.into.key),
137
+ chatId: randomId(),
138
+ kept: new Set(cut.chunks.map((chunk) => chunk.id)),
139
+ files: new Set([...files, ...documents.map((row) => row.id)]),
140
+ originDeviceId,
141
+ references: new Map()
142
+ };
143
+ }
144
+ async function forkAgentId(ctx, { source, agentId }) {
145
+ if (agentId) {
146
+ return (await mustGetActiveAgent(ctx.into, agentId)).id;
147
+ }
148
+ if (!ctx.same) {
149
+ throw new Error(AGENT_REQUIRED);
150
+ }
151
+ return source.agentId;
152
+ }
153
+ function forkedId(ctx, id) {
154
+ return derivedId(id, ctx.chatId);
155
+ }
156
+ async function forkedChunks(ctx, chunks) {
157
+ const forked = [];
158
+ for (const chunk of chunks) {
159
+ const through = chunk.compaction?.throughId;
160
+ if (through && !ctx.kept.has(through)) {
161
+ continue;
162
+ }
163
+ forked.push(await forkedChunk(ctx, chunk));
164
+ }
165
+ return forked;
166
+ }
167
+ async function forkedChunk(ctx, chunk) {
168
+ const { seq: _seq, updatedAt: _updatedAt, ...op } = stripped(chunk);
169
+ const forked = {
170
+ ...op,
171
+ id: forkedId(ctx, chunk.id),
172
+ chatId: ctx.chatId,
173
+ runId: chunk.runId && forkedId(ctx, chunk.runId),
174
+ parentId: chunk.parentId && ctx.kept.has(chunk.parentId) ? forkedId(ctx, chunk.parentId) : null,
175
+ compaction: chunk.compaction && {
176
+ ...chunk.compaction,
177
+ throughId: forkedId(ctx, chunk.compaction.throughId)
178
+ },
179
+ sources: chunk.sources && {
180
+ ...chunk.sources,
181
+ sources: chunk.sources.sources.map((source) => forkedSource(ctx, source))
182
+ }
183
+ };
184
+ if (!chunk.attachment) {
185
+ return forked;
186
+ }
187
+ const blobId = await forkedReference(ctx, chunk.attachment);
188
+ const attachment = { ...chunk.attachment, id: forkedId(ctx, chunk.attachment.id), blobId };
189
+ return { ...forked, attachment, originDeviceId: ctx.originDeviceId };
190
+ }
191
+ function forkedSource(ctx, source) {
192
+ const file = (id) => (id && ctx.files.has(id) ? forkedId(ctx, id) : id);
193
+ return { ...source, documentId: file(source.documentId), attachmentId: file(source.attachmentId) };
194
+ }
195
+ async function forkedDocuments(ctx, rows) {
196
+ const forked = [];
197
+ for (const row of rows) {
198
+ const blobId = await forkedReference(ctx, row);
199
+ forked.push({ ...stripped(row), id: forkedId(ctx, row.id), chatId: ctx.chatId, blobId });
200
+ }
201
+ return forked;
202
+ }
203
+ async function forkedReference(ctx, file) {
204
+ if (file.deletedAt) {
205
+ return removedReference(file);
206
+ }
207
+ if (isPendingBlobReference(file.blobId)) {
208
+ throw new Error(FILE_ARRIVING);
209
+ }
210
+ const known = ctx.references.get(file.blobId);
211
+ if (known) {
212
+ return known;
213
+ }
214
+ const copied = await copyBlob(ctx.from, ctx.into, file.blobId);
215
+ if (!copied) {
216
+ throw new Error(FILE_NOT_HERE);
217
+ }
218
+ ctx.references.set(file.blobId, copied);
219
+ return copied;
220
+ }
221
+ async function forkedChat(ctx, input) {
222
+ const { source, cut } = input;
223
+ const now = Date.now();
224
+ const groupId = ctx.same ? source.groupId : undefined;
225
+ const { chats } = await listSidebar(ctx.into);
226
+ const siblings = chats.filter((chat) => (chat.groupId || undefined) === (groupId || undefined));
227
+ const top = siblings.length > 0 ? Math.max(...siblings.map(chatSortKey)) : undefined;
228
+ return {
229
+ ...stripped(source),
230
+ id: ctx.chatId,
231
+ agentId: input.agentId,
232
+ title: input.title || source.title,
233
+ createdAt: now,
234
+ updatedAt: now,
235
+ deletedAt: undefined,
236
+ groupId,
237
+ rank: rankOnTop(top, now),
238
+ rankedAt: now,
239
+ readThrough: input.chunks.length || undefined,
240
+ forkedFrom: { meshId: b4a.toHex(ctx.from.key), chatId: source.id, runId: cut.runId }
241
+ };
242
+ }
243
+ function chunksOf(snap, chatId) {
244
+ return snap.find(CHUNKS_BY_CHAT, { gte: { chatId }, lte: { chatId } }).toArray();
245
+ }