@qvac/core 0.10.1 → 0.10.3

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 (40) hide show
  1. package/CHANGELOG.md +63 -1
  2. package/dist-lib/lib/api/agent-folders.d.ts +22 -0
  3. package/dist-lib/lib/api/agent-folders.js +115 -0
  4. package/dist-lib/lib/api/agents.d.ts +3 -1
  5. package/dist-lib/lib/api/agents.js +5 -3
  6. package/dist-lib/lib/api/execution.js +2 -0
  7. package/dist-lib/lib/api/index.d.ts +1 -0
  8. package/dist-lib/lib/api/index.js +4 -0
  9. package/dist-lib/lib/assistant-tree.js +2 -1
  10. package/dist-lib/lib/assistant.js +7 -4
  11. package/dist-lib/lib/core/agent.d.ts +5 -1
  12. package/dist-lib/lib/core/agent.js +8 -3
  13. package/dist-lib/lib/core/chat.d.ts +4 -1
  14. package/dist-lib/lib/core/chat.js +12 -4
  15. package/dist-lib/lib/core/local/index.d.ts +2 -1
  16. package/dist-lib/lib/core/local/index.js +9 -1
  17. package/dist-lib/lib/core/send.js +2 -0
  18. package/dist-lib/lib/core.d.ts +1 -0
  19. package/dist-lib/lib/core.js +41 -13
  20. package/dist-lib/lib/errors.d.ts +20 -0
  21. package/dist-lib/lib/errors.js +20 -0
  22. package/dist-lib/lib/lent-harness.d.ts +2 -0
  23. package/dist-lib/lib/lent-harness.js +51 -0
  24. package/dist-lib/lib/mesh-scoped-engine.js +3 -0
  25. package/dist-lib/schema/engine.js +58 -1
  26. package/dist-lib/spec/bind.js +9 -0
  27. package/dist-lib/spec/calls.js +3 -0
  28. package/dist-lib/spec/capabilities.d.ts +8 -2
  29. package/dist-lib/spec/hrpc/hrpc.json +40 -1
  30. package/dist-lib/spec/hrpc/index.js +40 -4
  31. package/dist-lib/spec/hrpc/messages.js +190 -0
  32. package/dist-lib/spec/hyperschema/index.js +190 -0
  33. package/dist-lib/spec/hyperschema/schema.json +141 -0
  34. package/dist-lib/spec/hyperschema/types.d.ts +40 -0
  35. package/package.json +2 -1
  36. package/tui/README.md +16 -0
  37. package/tui/app.mjs +80 -13
  38. package/tui/lib/folders-command.mjs +92 -0
  39. package/tui/lib/knowledge-import.mjs +3 -21
  40. package/tui/lib/local-path.mjs +21 -0
package/CHANGELOG.md CHANGED
@@ -13,6 +13,66 @@ release.
13
13
 
14
14
  ## [Unreleased]
15
15
 
16
+ ## [0.10.3] - 2026-10-21
17
+
18
+ ### Added
19
+
20
+ - `listAgentFolders`, `addAgentFolder` and `removeAgentFolder` share a folder on
21
+ this device with an agent, read only or read and write, so its file tools have
22
+ somewhere to work. They keep the `fs.<agentId>.roots` and
23
+ `fs.<agentId>.writable` config keys the assistant already reads, so a grant
24
+ written before keeps working. See
25
+ [agent folders](docs/api/agent-folders.md). (#445)
26
+
27
+ ### Changed
28
+
29
+ - The runs a `deleteAgent` with `keepChats` cancels carry
30
+ `reason: 'agent-deleted'`, so an app can tell them from a run its user took
31
+ back and keep the message they answered. (#486)
32
+ - `deleteAgent` forgets the folders shared with the agent on this device. (#445)
33
+
34
+ ### Fixed
35
+
36
+ - A borrowed run (`lenderDeviceId`) no longer acts on the lender's machine. The
37
+ lender serves it with no shared folders, with the `files` and `exec` toolsets
38
+ off, as none of its own agents, and with its KV caches kept apart; a borrowed
39
+ run gets no image or attachment. (#477)
40
+ - A device-invite `joinMesh` no longer lists a mesh it is leaving as closed, so
41
+ the app no longer reopens it and reports `MESH_NOT_FOUND` after pairing.
42
+ (#489)
43
+
44
+ ## [0.10.2] - 2026-10-20
45
+
46
+ ### Added
47
+
48
+ - `deleteAgent` takes `keepChats`, so an app can take an agent off a space
49
+ without deleting the conversations it answered there. They stay readable, and
50
+ `setChatAgent` hands each to another agent. The agent's open runs in them are
51
+ canceled. (`AssistantDeleteAgentRequest`) (#469)
52
+
53
+ ### Changed
54
+
55
+ - `sendMessage` and `runAgent` refuse an agent that is deleted with
56
+ `AGENT_NOT_FOUND` instead of writing a run no device would claim. (#469)
57
+
58
+ ### Fixed
59
+
60
+ - A device that pairs onto another account no longer lists its old workspace
61
+ beside the new one. An `openMesh` sent during the pair waits for it and is
62
+ refused with `MESH_NOT_FOUND` for a workspace the pair left. (#482)
63
+ - A device that pairs onto another account no longer renames that account's user
64
+ to the name it had before; it takes the account's name. (#475)
65
+ - An edited or reverted skill reaches chats that had already loaded it. A
66
+ skill write or delete clears the hosting device's KV caches and run replay
67
+ records, so each chat's next turn reloads the skill from disk; that turn
68
+ prefills cold (QVAC-26561). (#473)
69
+ - `duck`: `/models add` keeps a vision model's projector, so its images are no
70
+ longer dropped. (#480)
71
+ - `duck`: `/models use <name>` refuses a name that is neither an added model's
72
+ label or id nor an exact catalog or registry name, instead of setting it and
73
+ letting the harness load whatever file the registry search hit first, which
74
+ could be a vision projector. A path or URL is still set as given. (#481)
75
+
16
76
  ## [0.10.1] - 2026-10-19
17
77
 
18
78
  ### Added
@@ -1797,7 +1857,9 @@ Published under the `release-0.1` dist-tag.
1797
1857
  await assistant.ready()
1798
1858
  ```
1799
1859
 
1800
- [Unreleased]: https://github.com/tetherto/qvac-core/compare/v0.10.1...HEAD
1860
+ [Unreleased]: https://github.com/tetherto/qvac-core/compare/v0.10.3...HEAD
1861
+ [0.10.3]: https://github.com/tetherto/qvac-core/compare/v0.10.2...v0.10.3
1862
+ [0.10.2]: https://github.com/tetherto/qvac-core/compare/v0.10.1...v0.10.2
1801
1863
  [0.10.1]: https://github.com/tetherto/qvac-core/compare/v0.10.0...v0.10.1
1802
1864
  [0.10.0]: https://github.com/tetherto/qvac-core/compare/v0.9.0...v0.10.0
1803
1865
  [0.9.0]: https://github.com/tetherto/qvac-core/compare/v0.8.0...v0.9.0
@@ -0,0 +1,22 @@
1
+ import type { AssistantAddAgentFolderRequest, AssistantAgentFolders, AssistantAgentFoldersRequest, AssistantRemoveAgentFolderRequest } from '../../spec/hyperschema/types.d.ts';
2
+ import type { openLocalStore } from '../core/local/index.ts';
3
+ import type { CapabilityHandlers } from '../../spec/capabilities.d.ts';
4
+ type LocalStore = Awaited<ReturnType<typeof openLocalStore>>;
5
+ export interface AgentFoldersOptions {
6
+ readonly storageRoot: string;
7
+ }
8
+ export declare class AgentFolders {
9
+ private readonly _state;
10
+ private readonly _storageRoot;
11
+ private readonly _lock;
12
+ constructor(state: LocalStore, { storageRoot }: AgentFoldersOptions);
13
+ list({ agentId }: AssistantAgentFoldersRequest): Promise<AssistantAgentFolders>;
14
+ add({ agentId, path: given, access }: AssistantAddAgentFolderRequest): Promise<AssistantAgentFolders>;
15
+ remove({ agentId, path: given }: AssistantRemoveAgentFolderRequest): Promise<AssistantAgentFolders>;
16
+ forget(agentId: string): Promise<void>;
17
+ private _read;
18
+ private _update;
19
+ private _shareable;
20
+ }
21
+ export declare function createAgentFoldersApi(folders: AgentFolders): Pick<CapabilityHandlers, 'listAgentFolders' | 'addAgentFolder' | 'removeAgentFolder'>;
22
+ export {};
@@ -0,0 +1,115 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import ScopeLock from 'scope-lock';
4
+ import { CoreError } from '../errors.js';
5
+ import { fsGrantKey, fsWriteGrantKey } from '../fs-grant-keys.js';
6
+ import { fsGrantsFrom, grantedDirsFrom } from '../fs-grants.js';
7
+ export class AgentFolders {
8
+ _state;
9
+ _storageRoot;
10
+ _lock = new ScopeLock();
11
+ constructor(state, { storageRoot }) {
12
+ this._state = state;
13
+ this._storageRoot = storageRoot;
14
+ }
15
+ async list({ agentId }) {
16
+ return { agentId, folders: foldersOf(await this._read(agentId)) };
17
+ }
18
+ async add({ agentId, path: given, access }) {
19
+ const folder = await this._shareable(given);
20
+ return this._update(agentId, ({ roots, writable }) => ({
21
+ roots: localPathsOf(roots).includes(folder)
22
+ ? roots
23
+ : [...roots, { kind: 'local', path: folder }],
24
+ writable: access === 'write' ? withDir(writable, folder) : withoutDir(writable, folder)
25
+ }));
26
+ }
27
+ async remove({ agentId, path: given }) {
28
+ const names = await namesOf(given);
29
+ return this._update(agentId, (grants) => {
30
+ if (!foldersOf(grants).some((folder) => names.includes(folder.path))) {
31
+ throw new CoreError('AGENT_FOLDER_NOT_SHARED', [given]);
32
+ }
33
+ return {
34
+ roots: grants.roots.filter((root) => !names.includes(localPathOf(root) ?? '')),
35
+ writable: names.reduce(withoutDir, grants.writable)
36
+ };
37
+ });
38
+ }
39
+ async forget(agentId) {
40
+ await this._lock.lock();
41
+ try {
42
+ await this._state.deleteAll([fsGrantKey(agentId), fsWriteGrantKey(agentId)]);
43
+ }
44
+ finally {
45
+ this._lock.unlock();
46
+ }
47
+ }
48
+ async _read(agentId) {
49
+ const [roots, writable] = await Promise.all([
50
+ this._state.get(fsGrantKey(agentId)),
51
+ this._state.get(fsWriteGrantKey(agentId))
52
+ ]);
53
+ return { roots: Array.isArray(roots) ? roots : [], writable: grantedDirsFrom(writable) };
54
+ }
55
+ async _update(agentId, change) {
56
+ await this._lock.lock();
57
+ try {
58
+ const next = change(await this._read(agentId));
59
+ await this._state.setAll([
60
+ { key: fsGrantKey(agentId), value: next.roots },
61
+ { key: fsWriteGrantKey(agentId), value: next.writable }
62
+ ]);
63
+ return { agentId, folders: foldersOf(next) };
64
+ }
65
+ finally {
66
+ this._lock.unlock();
67
+ }
68
+ }
69
+ async _shareable(given) {
70
+ if (!path.isAbsolute(given)) {
71
+ throw new CoreError('AGENT_FOLDER_NOT_ABSOLUTE', [given]);
72
+ }
73
+ const folder = await fs.promises.realpath(given).catch(() => null);
74
+ if (!folder) {
75
+ throw new CoreError('AGENT_FOLDER_MISSING', [given]);
76
+ }
77
+ if (!(await fs.promises.stat(folder)).isDirectory()) {
78
+ throw new CoreError('AGENT_FOLDER_IS_FILE', [given]);
79
+ }
80
+ const storage = await fs.promises.realpath(this._storageRoot);
81
+ if (folder === storage || folder.startsWith(storage + path.sep)) {
82
+ throw new CoreError('AGENT_FOLDER_IN_STORAGE', [given]);
83
+ }
84
+ return folder;
85
+ }
86
+ }
87
+ export function createAgentFoldersApi(folders) {
88
+ return {
89
+ listAgentFolders: (request) => folders.list(request),
90
+ addAgentFolder: (request) => folders.add(request),
91
+ removeAgentFolder: (request) => folders.remove(request)
92
+ };
93
+ }
94
+ async function namesOf(given) {
95
+ const resolved = path.resolve(given);
96
+ const real = await fs.promises.realpath(resolved).catch(() => resolved);
97
+ return [...new Set([resolved, real])];
98
+ }
99
+ function localPathOf(root) {
100
+ const [grant] = fsGrantsFrom([root]);
101
+ return grant?.kind === 'local' ? grant.path : null;
102
+ }
103
+ function localPathsOf(roots) {
104
+ return roots.map(localPathOf).filter((dir) => dir !== null);
105
+ }
106
+ function withDir(dirs, dir) {
107
+ return dirs.includes(dir) ? dirs : [...dirs, dir];
108
+ }
109
+ function withoutDir(dirs, dir) {
110
+ return dirs.filter((other) => other !== dir);
111
+ }
112
+ function foldersOf({ roots, writable }) {
113
+ const paths = [...new Set([...localPathsOf(roots), ...writable])];
114
+ return paths.map((dir) => ({ path: dir, access: writable.includes(dir) ? 'write' : 'read' }));
115
+ }
@@ -1,11 +1,13 @@
1
1
  import type { LoggerInterface } from '@qvac/logging';
2
2
  import { type MeshPool } from './current-mesh.ts';
3
3
  import type { CapabilityHandlers } from '../../spec/capabilities.d.ts';
4
+ import type { AgentFolders } from './agent-folders.ts';
4
5
  type AgentCapabilities = Pick<CapabilityHandlers, 'createAgent' | 'listAgents' | 'getAgent' | 'getDefaultAgent' | 'updateAgent' | 'deleteAgent' | 'agentsWatch'>;
5
6
  export interface CreateAgentsApiOptions {
6
7
  readonly deviceId: Buffer | null;
7
8
  readonly computeLender: (() => Promise<Buffer | null>) | null;
9
+ readonly folders: AgentFolders | null;
8
10
  readonly log: LoggerInterface | null;
9
11
  }
10
- export declare function createAgentsApi(pool: MeshPool, { deviceId, computeLender, log }: CreateAgentsApiOptions): AgentCapabilities;
12
+ export declare function createAgentsApi(pool: MeshPool, { deviceId, computeLender, folders, log }: CreateAgentsApiOptions): AgentCapabilities;
11
13
  export {};
@@ -1,7 +1,7 @@
1
1
  import { createAgent, deleteAgent, getDefaultAgent, isOrphaned, listAgents, liveProviderIds, mustGetActiveAgent, updateAgent } from '../core/agent.js';
2
2
  import { meshWatchable, requireMesh } from './current-mesh.js';
3
3
  import b4a from 'b4a';
4
- export function createAgentsApi(pool, { deviceId, computeLender, log }) {
4
+ export function createAgentsApi(pool, { deviceId, computeLender, folders, log }) {
5
5
  const withOrphaned = async (mesh, agent) => ({
6
6
  ...agent,
7
7
  orphaned: await isOrphaned(mesh, agent)
@@ -41,9 +41,11 @@ export function createAgentsApi(pool, { deviceId, computeLender, log }) {
41
41
  const mesh = await requireMesh(pool, meshId);
42
42
  return withOrphaned(mesh, await updateAgent(mesh, agentId, config));
43
43
  },
44
- deleteAgent: async ({ agentId, meshId }) => {
44
+ deleteAgent: async ({ agentId, meshId, keepChats }) => {
45
45
  const mesh = await requireMesh(pool, meshId);
46
- return withOrphaned(mesh, await deleteAgent(mesh, deviceId, agentId));
46
+ const deleted = await deleteAgent(mesh, deviceId, { id: agentId, keepChats });
47
+ await folders?.forget(agentId);
48
+ return withOrphaned(mesh, deleted);
47
49
  },
48
50
  agentsWatch: meshWatchable(pool, (request, mesh) => list(mesh, request.providerDeviceId ?? undefined), { name: 'agentsWatch', log })
49
51
  };
@@ -1,3 +1,4 @@
1
+ import { mustGetActiveAgent } from '../core/agent.js';
1
2
  import { appendChunk, listChunks } from '../core/chunk.js';
2
3
  import { randomId } from '../core/id.js';
3
4
  import { parentRequestId, sendMessage } from '../core/send.js';
@@ -18,6 +19,7 @@ export function createExecutionApi(pool, deviceId) {
18
19
  }),
19
20
  runAgent: async ({ chatId, agentId, parentRunId, meshId, capability, capabilityArgs, enhance }) => {
20
21
  const mesh = await requireMesh(pool, meshId);
22
+ await mustGetActiveAgent(mesh, agentId);
21
23
  const parentId = parentRunId ? await parentRequestId(mesh, chatId, parentRunId) : undefined;
22
24
  await appendChunk(mesh, {
23
25
  chatId,
@@ -60,6 +60,7 @@ interface ApiDeps {
60
60
  platform?: (() => string | null) | null;
61
61
  computeLender?: (() => Promise<Buffer | null>) | null;
62
62
  pushSkillSecret?: ((request: AssistantPushSkillSecretRequest) => Promise<void>) | null;
63
+ storageRoot?: string | null;
63
64
  skills?: ((agentId?: string | null, modelName?: string | null, options?: SkillOptions) => Promise<unknown>) | null;
64
65
  skillCatalog?: ((agentId?: string | null, modelName?: string | null, options?: {
65
66
  readonly refresh?: boolean;
@@ -2,6 +2,7 @@ import { toAsyncIterable } from '../core/async-iterable.js';
2
2
  import { normalizeImageForModel } from '../core/image/normalize.js';
3
3
  import { detectImageMime } from '../core/image/sniff.js';
4
4
  import { createAgentsApi } from './agents.js';
5
+ import { AgentFolders, createAgentFoldersApi } from './agent-folders.js';
5
6
  import { createApprovalRulesApi } from './approval-rules.js';
6
7
  import { createAttachmentsApi } from './attachments.js';
7
8
  import { createChatApi } from './chat.js';
@@ -38,6 +39,7 @@ export function createApi(deps = {}) {
38
39
  const state = deps.state ?? null;
39
40
  const log = deps.log ?? null;
40
41
  const members = mesh && deps.meshStatus ? createMembersApi(mesh, deps.meshStatus, { state, log }) : null;
42
+ const folders = state && deps.storageRoot ? new AgentFolders(state, { storageRoot: deps.storageRoot }) : null;
41
43
  const handlers = {
42
44
  ...(state ? createConfigApi(state, log) : null),
43
45
  ...(state ? createAppConfigApi(state, log) : null),
@@ -49,10 +51,12 @@ export function createApi(deps = {}) {
49
51
  log
50
52
  })
51
53
  : null),
54
+ ...(folders ? createAgentFoldersApi(folders) : null),
52
55
  ...(mesh
53
56
  ? createAgentsApi(mesh, {
54
57
  deviceId: deps.deviceId ?? null,
55
58
  computeLender: deps.computeLender ?? null,
59
+ folders,
56
60
  log
57
61
  })
58
62
  : null),
@@ -8,6 +8,7 @@ import { startModelMemoryCap } from './model-memory-cap.js';
8
8
  import { startDownloadsAllowedPusher } from './downloads-allowed-pusher.js';
9
9
  import { serveHarness } from '@qvac/harness';
10
10
  import { duplexPair } from '@qvac/harness/transport';
11
+ import { lentHarness } from './lent-harness.js';
11
12
  export function assistantTree(opts) {
12
13
  const { core, harness, logger = null, imageCacheDir, inferenceCallsDir, runReplayDir, imageCacheMaxBytes, imageCacheMaxAgeMs, embedder, extractors, onHarness, platform, preloadCurrentAgentModel, fakeModels = false } = opts;
13
14
  const sup = new Supervisor();
@@ -118,7 +119,7 @@ export function assistantTree(opts) {
118
119
  },
119
120
  logger
120
121
  });
121
- offLoanableHarness = core.registerLoanableHarness((stream) => serveHarness(stream, harness));
122
+ offLoanableHarness = core.registerLoanableHarness((stream) => serveHarness(stream, lentHarness(harness)));
122
123
  offRetryModelDownload = core.registerRetryModelDownload((name) => assistant.retryModelDownload(name));
123
124
  offModelResidency = core.registerModelResidency({
124
125
  load: (name) => assistant.loadModel(name),
@@ -161,6 +161,7 @@ const RAG_SOURCE_BOUNDS = {
161
161
  excerptChars: RAG_SOURCE_EXCERPT_CHARS
162
162
  };
163
163
  const WEB_RAG_SOURCE_BOUNDS = { ...RAG_SOURCE_BOUNDS, maxUrlChars: MAX_RAG_SOURCE_URL_CHARS };
164
+ const NO_FS_GRANTS = { roots: [], write: [] };
164
165
  export class QvacAssistant extends ReadyResource {
165
166
  _engine;
166
167
  _harness;
@@ -1619,7 +1620,7 @@ export class QvacAssistant extends ReadyResource {
1619
1620
  meshId
1620
1621
  });
1621
1622
  const toolConfigsPromise = this._loadToolConfigs(engine, agent.id);
1622
- const fsGrantsPromise = this._loadFsGrants(agent.id);
1623
+ const fsGrantsPromise = lender ? Promise.resolve(NO_FS_GRANTS) : this._loadFsGrants(agent.id);
1623
1624
  const all = await listHistoryChunks(engine, chatId);
1624
1625
  if (agentSwitched(all, request, deviceId)) {
1625
1626
  await this._deleteChatKvCache(chatId, 'agent switched');
@@ -1670,9 +1671,11 @@ export class QvacAssistant extends ReadyResource {
1670
1671
  enabledSkills: []
1671
1672
  }
1672
1673
  : configuredAgent;
1673
- const seesImages = this._harness.supportsImagesFor
1674
- ? this._harness.supportsImagesFor(model)
1675
- : (this._harness.supportsImages ?? this._info.supportsImages) !== false;
1674
+ const sendsFiles = lender === null;
1675
+ const seesImages = sendsFiles &&
1676
+ (this._harness.supportsImagesFor
1677
+ ? this._harness.supportsImagesFor(model)
1678
+ : (this._harness.supportsImages ?? this._info.supportsImages) !== false);
1676
1679
  let unreadableImages = new Map();
1677
1680
  let renderedPdfIds = new Set();
1678
1681
  if (!seesImages) {
@@ -12,4 +12,8 @@ export declare function mustGetActiveAgent(store: Mesh, id: string): Promise<Qva
12
12
  export declare function createAgent(store: Mesh, input: AssistantAgentConfig): Promise<QvacAgent>;
13
13
  export declare function updateAgent(store: Mesh, agentId: string, input: AssistantAgentUpdateConfig): Promise<QvacAgent>;
14
14
  export declare function rehomeAgents(store: Mesh, from: Buffer, to: Buffer): Promise<void>;
15
- export declare function deleteAgent(store: Mesh, deviceId: Buffer | null, id: string): Promise<QvacAgent>;
15
+ export interface DeleteAgentInput {
16
+ readonly id: string;
17
+ readonly keepChats?: boolean;
18
+ }
19
+ export declare function deleteAgent(store: Mesh, deviceId: Buffer | null, { id, keepChats }: DeleteAgentInput): Promise<QvacAgent>;
@@ -1,4 +1,4 @@
1
- import { softDeleteChatsForAgent } from './chat.js';
1
+ import { cancelRunsForAgent, softDeleteChatsForAgent } from './chat.js';
2
2
  import { randomId } from './id.js';
3
3
  import { softDeleteToolConfigsForAgent } from './tool-configs.js';
4
4
  import b4a from 'b4a';
@@ -201,7 +201,7 @@ export async function rehomeAgents(store, from, to) {
201
201
  }
202
202
  }
203
203
  }
204
- export async function deleteAgent(store, deviceId, id) {
204
+ export async function deleteAgent(store, deviceId, { id, keepChats }) {
205
205
  const current = await mustGetAgent(store, id);
206
206
  if (current.isDefault) {
207
207
  throw new CoreError('AGENT_DEFAULT_UNDELETABLE');
@@ -213,7 +213,12 @@ export async function deleteAgent(store, deviceId, id) {
213
213
  updatedAt: Math.max(deletedAt, current.updatedAt + 1)
214
214
  };
215
215
  await store.dispatch('put-agent', { agent: updated });
216
- await softDeleteChatsForAgent(store, deviceId, id);
216
+ if (!keepChats) {
217
+ await softDeleteChatsForAgent(store, deviceId, id);
218
+ }
219
+ else if (deviceId) {
220
+ await cancelRunsForAgent(store, deviceId, id);
221
+ }
217
222
  await softDeleteToolConfigsForAgent(store, id);
218
223
  return updated;
219
224
  }
@@ -44,8 +44,9 @@ export declare function markChatRead(store: Mesh, id: string): Promise<ChatListi
44
44
  export interface CancelActiveRunsOptions {
45
45
  readonly deviceId: Buffer;
46
46
  readonly reason?: string;
47
+ readonly agentId?: string;
47
48
  }
48
- export declare function cancelActiveRuns(store: Mesh, chatId: string, { deviceId, reason }: CancelActiveRunsOptions): Promise<string[]>;
49
+ export declare function cancelActiveRuns(store: Mesh, chatId: string, { deviceId, reason, agentId }: CancelActiveRunsOptions): Promise<string[]>;
49
50
  export declare function removeChatKnowledge(store: Mesh, chatId: string, at: number): Promise<void>;
50
51
  export interface RemoveChatAttachmentsOptions {
51
52
  readonly deviceId: Buffer;
@@ -54,3 +55,5 @@ export interface RemoveChatAttachmentsOptions {
54
55
  export declare function removeChatAttachments(store: Mesh, chatId: string, { deviceId, at }: RemoveChatAttachmentsOptions): Promise<void>;
55
56
  export declare function deleteChat(store: Mesh, deviceId: Buffer | null, id: string): Promise<ChatListing>;
56
57
  export declare function softDeleteChatsForAgent(store: Mesh, deviceId: Buffer | null, agentId: string): Promise<void>;
58
+ export declare const AGENT_DELETED = "agent-deleted";
59
+ export declare function cancelRunsForAgent(store: Mesh, deviceId: Buffer, agentId: string): Promise<void>;
@@ -226,11 +226,12 @@ export async function markChatRead(store, id) {
226
226
  await store.dispatch('put-chat', { chat: read });
227
227
  return enrichChat(store, read);
228
228
  }
229
- export async function cancelActiveRuns(store, chatId, { deviceId, reason }) {
229
+ export async function cancelActiveRuns(store, chatId, { deviceId, reason, agentId }) {
230
230
  const statuses = await listChunks(store, { chatId, type: 'run-status' });
231
231
  const terminal = new Set(statuses.filter((c) => TERMINAL_RUN_STATES.has(c.runStatus?.state ?? '')).map((c) => c.runId));
232
232
  const requests = await listChunks(store, { chatId, type: 'run-request' });
233
- const runIds = new Set(requests.map((c) => c.runId).filter((id) => Boolean(id)));
233
+ const asked = agentId ? requests.filter((c) => c.runRequest?.agentId === agentId) : requests;
234
+ const runIds = new Set(asked.map((c) => c.runId).filter((id) => Boolean(id)));
234
235
  const canceled = [];
235
236
  const batch = store.batch();
236
237
  for (const runId of runIds) {
@@ -287,7 +288,14 @@ export async function deleteChat(store, deviceId, id) {
287
288
  await reclaimReferences(store, references).catch((err) => store.log?.warn('sync', "reclaiming a deleted chat's files failed", { id, err }));
288
289
  return listing;
289
290
  }
290
- export async function softDeleteChatsForAgent(store, deviceId, agentId) {
291
+ export function softDeleteChatsForAgent(store, deviceId, agentId) {
292
+ return eachChatOfAgent(store, agentId, (chatId) => deleteChat(store, deviceId, chatId));
293
+ }
294
+ export const AGENT_DELETED = 'agent-deleted';
295
+ export function cancelRunsForAgent(store, deviceId, agentId) {
296
+ return eachChatOfAgent(store, agentId, (chatId) => cancelActiveRuns(store, chatId, { deviceId, agentId, reason: AGENT_DELETED }));
297
+ }
298
+ async function eachChatOfAgent(store, agentId, fn) {
291
299
  const snap = store.view.snapshot();
292
300
  try {
293
301
  for await (const chat of snap.find(ACTIVE_CHATS_BY_AGENT, {
@@ -296,7 +304,7 @@ export async function softDeleteChatsForAgent(store, deviceId, agentId) {
296
304
  })) {
297
305
  if (store.closing)
298
306
  return;
299
- await deleteChat(store, deviceId, chat.id);
307
+ await fn(chat.id);
300
308
  }
301
309
  }
302
310
  finally {
@@ -61,6 +61,7 @@ export interface RecordDepartureOptions {
61
61
  }
62
62
  export interface AdoptAccountMeshOptions {
63
63
  readonly account?: Buffer | null;
64
+ readonly keepName?: boolean;
64
65
  }
65
66
  export interface MarkAwaitingAdmissionOptions {
66
67
  readonly awaitingAdmission: boolean;
@@ -129,7 +130,7 @@ declare class LocalStore {
129
130
  markAwaitingAdmission(key: Buffer, opts: MarkAwaitingAdmissionOptions): Promise<void>;
130
131
  awaitsAdmission(key: Buffer): Promise<boolean>;
131
132
  markMeshMigrated(key: Buffer, migratedAt: number): Promise<void>;
132
- adoptAccountMesh(deviceId: Buffer, key: Buffer, { account }: AdoptAccountMeshOptions): Promise<void>;
133
+ adoptAccountMesh(deviceId: Buffer, key: Buffer, { account, keepName }: AdoptAccountMeshOptions): Promise<void>;
133
134
  private _pointersAt;
134
135
  listMeshes(): Promise<LocalMeshMembership[]>;
135
136
  listArchivedMeshes(): Promise<ArchivedMeshMembership[]>;
@@ -615,7 +615,7 @@ class LocalStore {
615
615
  await tx.flush();
616
616
  });
617
617
  }
618
- adoptAccountMesh(deviceId, key, { account }) {
618
+ adoptAccountMesh(deviceId, key, { account, keepName }) {
619
619
  return this._locked(async () => {
620
620
  const departed = [];
621
621
  for await (const row of this._db.find(LOCAL_MESH_MEMBERSHIP)) {
@@ -632,6 +632,14 @@ class LocalStore {
632
632
  await dropMeshFiles(tx, row.key);
633
633
  await tx.delete(LOCAL_MESH_UPDATES, { meshKey: row.key });
634
634
  }
635
+ const identity = await tx.get(LOCAL_IDENTITY, { id: IDENTITY_ID });
636
+ if (!keepName && identity?.displayName) {
637
+ await tx.insert(LOCAL_IDENTITY, {
638
+ ...identity,
639
+ displayName: null,
640
+ displayNameAt: 0
641
+ });
642
+ }
635
643
  await tx.insert(LOCAL_ACTIVE_MESH, { deviceId, homeMeshKey: key });
636
644
  await tx.flush();
637
645
  });
@@ -1,4 +1,5 @@
1
1
  import { CoreError } from '../errors.js';
2
+ import { mustGetActiveAgent } from './agent.js';
2
3
  import { buildChat, enrichChat, mustGetActiveChat } from './chat.js';
3
4
  import { appendChunk, listChunks } from './chunk.js';
4
5
  import { randomId } from './id.js';
@@ -8,6 +9,7 @@ export async function sendMessage(mesh, input) {
8
9
  if (!agentId) {
9
10
  throw new CoreError('SEND_AGENT_REQUIRED');
10
11
  }
12
+ await mustGetActiveAgent(mesh, agentId);
11
13
  const chat = existing ?? buildChat({ agentId, title: input.title ?? '' });
12
14
  const chatId = chat.id;
13
15
  const parentId = input.parentRunId
@@ -457,6 +457,7 @@ export declare class Core extends ReadyResource {
457
457
  private _meshHoldingChat;
458
458
  private _serveSkillOverlayOp;
459
459
  private _runLocalSkillOverlayOp;
460
+ private _forgetSkillBodies;
460
461
  private _setupFields;
461
462
  private _hostSkills;
462
463
  private _onConnection;
@@ -4,6 +4,7 @@ import BlindPeering from 'blind-peering';
4
4
  import Corestore from 'corestore';
5
5
  import CorestoreStorage from 'hypercore-storage';
6
6
  import { constants as RocksConstants } from 'rocksdb-native';
7
+ import path from 'path';
7
8
  import Rache from 'rache';
8
9
  import Hyperswarm from 'hyperswarm';
9
10
  import Wakeup from 'protomux-wakeup';
@@ -409,6 +410,7 @@ export class Core extends ReadyResource {
409
410
  platform: () => this._localDevice?.platform ?? null,
410
411
  computeLender: () => this._computeLender(),
411
412
  pushSkillSecret: (request) => this.pushSkillSecret(request),
413
+ storageRoot: path.dirname(this._storagePath),
412
414
  listModels: this._hostsModelSource || this._listModels
413
415
  ? async (request) => (await this._readModelList(request)) ?? { models: [] }
414
416
  : null,
@@ -2099,12 +2101,13 @@ export class Core extends ReadyResource {
2099
2101
  source,
2100
2102
  deviceId,
2101
2103
  memberInvite: !!invite.memberInvite,
2104
+ recovery: !!invite.recovery,
2102
2105
  appended
2103
2106
  });
2104
2107
  }
2105
- async _landJoinedMesh(candidate, { source, deviceId, memberInvite, appended }) {
2108
+ async _landJoinedMesh(candidate, { source, deviceId, memberInvite, recovery, appended }) {
2106
2109
  if (!memberInvite) {
2107
- await this._departOldAccount(candidate.key, source);
2110
+ await this._departOldAccount(candidate.key, source, { keepName: recovery });
2108
2111
  }
2109
2112
  if (this._blockedByMinVersion()) {
2110
2113
  if (!memberInvite) {
@@ -2140,17 +2143,20 @@ export class Core extends ReadyResource {
2140
2143
  this.emit('mesh-changed', candidate);
2141
2144
  return candidate;
2142
2145
  }
2143
- async _departOldAccount(joined, source) {
2146
+ async _departOldAccount(joined, source, { keepName }) {
2144
2147
  const account = (await this._storedAccountKey()) ?? source?.key;
2145
2148
  if (account && b4a.equals(account, joined)) {
2146
2149
  return;
2147
2150
  }
2148
2151
  const rows = (await this.local.listMeshes()).filter((row) => !b4a.equals(row.key, joined));
2149
2152
  const meshes = rows.filter((row) => !(account && b4a.equals(account, row.key)));
2153
+ await this.local.adoptAccountMesh(this._requireDeviceKeyPair().publicKey, joined, {
2154
+ account,
2155
+ keepName
2156
+ });
2150
2157
  for (const mesh of meshes) {
2151
2158
  await this._departIfPooled(mesh.key, 'mesh');
2152
2159
  }
2153
- await this.local.adoptAccountMesh(this._requireDeviceKeyPair().publicKey, joined, { account });
2154
2160
  if (account) {
2155
2161
  await this._departIfPooled(account, 'account');
2156
2162
  }
@@ -2274,7 +2280,7 @@ export class Core extends ReadyResource {
2274
2280
  if (this.closing)
2275
2281
  return null;
2276
2282
  const key = await this._storedAccountKey();
2277
- const held = key ? this._pooled(b4a.toHex(key)) : null;
2283
+ const held = key ? (this._pooled(b4a.toHex(key)) ?? this._opening.get(b4a.toHex(key))) : null;
2278
2284
  const mesh = key ? await this._openPooledMesh(b4a.toHex(key)).catch(noop) : null;
2279
2285
  if (mesh && !mesh.ourMemberId) {
2280
2286
  await mesh.refreshOurMember();
@@ -3188,7 +3194,15 @@ export class Core extends ReadyResource {
3188
3194
  }
3189
3195
  }
3190
3196
  async openMesh(meshId) {
3191
- await this._openPooledMesh(meshId);
3197
+ if (!this.opened)
3198
+ await this.ready();
3199
+ await this._meshTransitionLock.lock();
3200
+ try {
3201
+ await this._openPooledMesh(meshId);
3202
+ }
3203
+ finally {
3204
+ this._meshTransitionLock.unlock();
3205
+ }
3192
3206
  }
3193
3207
  async closeMesh(meshId) {
3194
3208
  if (!this.opened)
@@ -4035,22 +4049,36 @@ export class Core extends ReadyResource {
4035
4049
  const res = (await mgmt?.readSkillFile(op.name ?? '')) ?? { found: false };
4036
4050
  return { found: res.found ?? false, content: res.content, origin: res.origin };
4037
4051
  }
4038
- case 'write':
4039
- return {
4040
- ok: ((await mgmt?.writeSkillFile(op.name ?? '', op.content ?? '')) ?? { ok: false }).ok
4052
+ case 'write': {
4053
+ const { ok } = (await mgmt?.writeSkillFile(op.name ?? '', op.content ?? '')) ?? {
4054
+ ok: false
4041
4055
  };
4056
+ if (ok) {
4057
+ await this._forgetSkillBodies();
4058
+ }
4059
+ return { ok };
4060
+ }
4042
4061
  case 'copy':
4043
4062
  return {
4044
4063
  copied: ((await mgmt?.copySkillForEdit(op.name ?? '')) ?? { copied: false }).copied
4045
4064
  };
4046
- case 'delete':
4047
- return {
4048
- removed: ((await mgmt?.deleteOverlaySkill(op.name ?? '')) ?? { removed: false }).removed
4049
- };
4065
+ case 'delete': {
4066
+ const { removed } = (await mgmt?.deleteOverlaySkill(op.name ?? '')) ?? { removed: false };
4067
+ if (removed) {
4068
+ await this._forgetSkillBodies();
4069
+ }
4070
+ return { removed };
4071
+ }
4050
4072
  default:
4051
4073
  throw new CoreError('SKILL_OVERLAY_OP_UNKNOWN', [op.op]);
4052
4074
  }
4053
4075
  }
4076
+ async _forgetSkillBodies() {
4077
+ const result = await this._clearKvCache?.();
4078
+ if (result?.status === 'failure') {
4079
+ this._log?.warn('skills', 'kv caches not cleared after a skill edit', { error: result.error });
4080
+ }
4081
+ }
4054
4082
  async _setupFields(skillName) {
4055
4083
  const skills = await this._hostSkills();
4056
4084
  if (skills.length === 0) {