@qvac/core 0.2.2 → 0.3.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 (50) hide show
  1. package/.claude/skills/compaction/SKILL.md +15 -11
  2. package/.claude/skills/js-house-style/SKILL.md +1 -0
  3. package/.claude/skills/pr-create/SKILL.md +42 -0
  4. package/.claude/skills/pr-review/SKILL.md +4 -0
  5. package/.claude/skills/release/SKILL.md +122 -0
  6. package/CLAUDE.md +7 -2
  7. package/dist-lib/lib/api/agents.js +2 -3
  8. package/dist-lib/lib/api/chat.js +3 -3
  9. package/dist-lib/lib/api/chunks.d.ts +1 -1
  10. package/dist-lib/lib/api/chunks.js +5 -15
  11. package/dist-lib/lib/api/current-mesh.d.ts +16 -1
  12. package/dist-lib/lib/api/current-mesh.js +18 -0
  13. package/dist-lib/lib/api/devices.js +6 -3
  14. package/dist-lib/lib/api/index.js +1 -1
  15. package/dist-lib/lib/api/knowledge.js +11 -7
  16. package/dist-lib/lib/api/members.js +2 -3
  17. package/dist-lib/lib/api/sync.d.ts +1 -1
  18. package/dist-lib/lib/api/sync.js +2 -1
  19. package/dist-lib/lib/api/tool-activity.js +2 -2
  20. package/dist-lib/lib/api/tool-configs.js +2 -2
  21. package/dist-lib/lib/api/watchable.d.ts +6 -1
  22. package/dist-lib/lib/api/watchable.js +13 -2
  23. package/dist-lib/lib/assistant/history.d.ts +1 -2
  24. package/dist-lib/lib/assistant/history.js +0 -6
  25. package/dist-lib/lib/assistant.d.ts +3 -7
  26. package/dist-lib/lib/assistant.js +65 -110
  27. package/dist-lib/lib/core/chunk.d.ts +1 -0
  28. package/dist-lib/lib/core/chunk.js +27 -0
  29. package/dist-lib/lib/core/contract/devices.js +3 -2
  30. package/dist-lib/lib/core/harness-loan.js +1 -1
  31. package/dist-lib/lib/core/local/index.js +6 -0
  32. package/dist-lib/lib/core.d.ts +1 -0
  33. package/dist-lib/lib/core.js +20 -12
  34. package/dist-lib/lib/fs-drive-bridge.js +1 -1
  35. package/dist-lib/lib/mesh-scoped-engine.js +5 -0
  36. package/dist-lib/lib/model-download.d.ts +2 -0
  37. package/dist-lib/lib/model-download.js +20 -5
  38. package/dist-lib/lib/oauth/keys.js +1 -0
  39. package/dist-lib/lib/oauth/spotify.js +1 -0
  40. package/dist-lib/lib/oauth/verify.d.ts +8 -0
  41. package/dist-lib/lib/oauth/verify.js +58 -0
  42. package/dist-lib/lib/oauth.d.ts +1 -0
  43. package/dist-lib/lib/oauth.js +1 -0
  44. package/dist-lib/schema/qvac.d.ts +3 -0
  45. package/dist-lib/schema/qvac.js +7 -0
  46. package/package.json +4 -4
  47. package/tui/app.mjs +327 -46
  48. package/tui/lib/render.mjs +17 -1
  49. package/tui/lib/selection.mjs +16 -0
  50. package/tui/lib/usage.mjs +54 -0
@@ -74,17 +74,21 @@ What makes the fold legal under the rule above:
74
74
  cannot answer the question instead of summarizing it, and cannot pollute the
75
75
  chat's own cache file.
76
76
 
77
- Triggers: proactively before a run on the previous round's numbers, at the end of
78
- a run that filled the window itself, and reactively once the harness overflow
79
- ladder is exhausted. The proactive share is tiered by window — 75% under 12k, 82%
80
- under 16k, 85% under 32k, 90% under 64k, 95% from there — because the band has
81
- to hold a whole thinking turn and `cacheTokens` reports a turn with its thinking
82
- stripped. The end-of-run fold's `compacting` status is not an attempt start in
83
- `historyFromChunks`; reading it as one drops the kept turn's answer. All three
84
- announce a `compacting` phase, which clients must exempt from any restart rule
85
- that discards a streamed answer on a non-terminal status. Clearing the phase
86
- stays conditional — only the before-run fold does it, because its run carries
87
- on.
77
+ Triggers: proactively before a run on the previous round's numbers, and
78
+ reactively once the harness overflow ladder is exhausted. Never at the end of a
79
+ run on its own numbers — that path existed and was removed (see the decision
80
+ record): the turn that fills the window ends cleanly, publishes its full reading,
81
+ and the next message folds first, keeping itself verbatim. The proactive share is
82
+ tiered by window — 75% under 12k, 82% under 16k, 85% under 32k, 90% under 64k,
83
+ 95% from there — because the band has to hold a whole thinking turn and
84
+ `cacheTokens` reports a turn with its thinking stripped. Both folds announce a
85
+ `compacting` phase. The before-run fold announces before anything streamed and
86
+ clears the phase, because its run carries on; the overflow fold can land behind
87
+ a partial answer, since a mid-stream overflow is not retried, and its failed
88
+ status closes the phase. That announcement is not an attempt start in
89
+ `historyFromChunks` — reading it as one drops the streamed answer from every
90
+ later prompt — and clients exempt it from their restart rule for the same
91
+ reason.
88
92
 
89
93
  After the fact the fold is visible from its chunk (`thread.compactionMarkers`,
90
94
  anchored before the user message the fold precedes). Only the device that ran the
@@ -446,6 +446,7 @@ We do **not** program defensively. We don't litter methods with arg-type checks,
446
446
  somePromise().catch(safetyCatch)
447
447
  ```
448
448
  - **Never swallow silently.** If you catch and ignore an _operational_ error, leave a comment on why it's safe.
449
+ - **A swallow that keeps the rejection is `.catch(noop)`**, never `.catch(() => null)` or another inline closure fabricating a value the caller does not read. Define `noop` once at the foot of the file. This is about not inventing a value — it says nothing about _whether_ to swallow, which is the `safety-catch` question above.
449
450
 
450
451
  The line to hold: **caller bug → let it crash. Runtime condition → handle it on the resource.** Don't blur the two by defending against the first.
451
452
 
@@ -81,6 +81,26 @@ Nothing else needs one — an internal module, a `tui/` command, a refactor, a
81
81
  fix. Do not pad `examples/` to clear a checklist: one script a reader can run
82
82
  beats three that restate the types.
83
83
 
84
+ ## API docs
85
+
86
+ `docs/api/` carries one file per api module: every route's signature, its input
87
+ fields with what each is for, the mesh scope its handler honours, and a
88
+ changelog.
89
+
90
+ **A PR that changes a route's behaviour updates that route's file in the same
91
+ commit**, including its `### [Unreleased]` entry under the Keep a Changelog
92
+ heading it fits — `Fixed` for a defect, `Changed` for a contract that moved,
93
+ `Added` for a new route. The entry says what a caller has to do differently, not
94
+ what the diff did.
95
+
96
+ This is not optional documentation. The scope line is the only place that records
97
+ whether a handler honours `meshId`, and the changelog is what a consumer reads
98
+ to decide whether an upgrade touches them. A route whose behaviour moved and
99
+ whose file did not is a review finding.
100
+
101
+ Nothing else triggers it. An internal refactor behind an unchanged route, a
102
+ `tui/` change, a test — no doc change, no finding.
103
+
84
104
  ## Decision records
85
105
 
86
106
  `docs/decisions/` holds the durable, non-obvious choices — why a boundary is
@@ -168,6 +188,28 @@ For a **breaking change**, say so in the body under its own `## Breaking`
168
188
  heading, with the migration a consumer has to perform. Published package —
169
189
  this is the only warning they get.
170
190
 
191
+ ### Length, and the shape it has to hold
192
+
193
+ Twenty lines. The bodies in this log run 17–28 (`#134`, `#133`, `#130`), and a
194
+ reviewer reads the diff, not the description.
195
+
196
+ - **Use the template's headings and only those.** Delete what does not apply;
197
+ do not invent `## How I decided`, `## What is unresolved`, `## Is this a
198
+ contract change`. A point that needs its own heading is usually a point that
199
+ belongs in the commit message.
200
+ - **Never hard-wrap.** GitHub renders a single newline as a line break in PR
201
+ bodies, so text wrapped at 80 columns displays as a narrow ragged column
202
+ instead of filling the width. One bullet is one line, however long.
203
+ - **No process narrative.** "Checked rather than assumed", "found by
204
+ intersecting two facts", "I have not established" — how you arrived at the
205
+ change is not what a reviewer needs. State what is true.
206
+ - **No open-question lists.** A body that ends in four things somebody should
207
+ think about is a change that was not finished. Decide them, or say plainly in
208
+ one line what is deliberately left and why.
209
+ - **Depth goes in the commit message.** It is the durable record and it is where
210
+ a rejected alternative, a subtle invariant or a caveat belongs. The body is
211
+ the summary a reviewer reads first, not the second copy.
212
+
171
213
  ## Before opening
172
214
 
173
215
  1. Check the branch is not `main` and the name is neutral.
@@ -164,6 +164,10 @@ is a promise to a consumer.
164
164
  baseline regenerated (`bun run build:schema`) rather than hand-edited?
165
165
  - Does the change match its own type declarations, and do callers in this repo
166
166
  still typecheck?
167
+ - A route whose behaviour moved: is `docs/api/<module>.md` updated with it — the
168
+ scope line if the mesh handling changed, and an entry under `### [Unreleased]`?
169
+ That file is where a consumer looks before upgrading, so a stale one is a `[P2]`.
170
+ A refactor behind an unchanged route needs nothing.
167
171
 
168
172
  **4. House style.** Load **js-house-style** and run the changed files against
169
173
  it — that document, not your own taste or your memory of it. Layering,
@@ -0,0 +1,122 @@
1
+ ---
2
+ name: release
3
+ description: Cut a release of @qvac/core — pick the version from what landed, bump package.json on a release/x.y.z branch, and roll the api changelogs from Unreleased to the dated version. Use when asked to release, cut a version, publish, or bump the version.
4
+ ---
5
+
6
+ # Release
7
+
8
+ A release here is small and shaped by convention, and both halves matter: the
9
+ version bump, and rolling `docs/api/` from `[Unreleased]` to a dated heading.
10
+ Nothing else rides along.
11
+
12
+ ## What publishes
13
+
14
+ `.github/workflows/publish.yml` triggers on `push: tags: v*`. **The tag is the
15
+ release.** It is created on the merge commit after the PR lands, never on the
16
+ branch — a tag pushed from the branch publishes unreviewed code.
17
+
18
+ So this skill takes you to a merged PR. Tagging is the step after, and it is the
19
+ user's to take unless they ask otherwise.
20
+
21
+ ## 1. Choose the version, then ask
22
+
23
+ Read what has landed since the last tag:
24
+
25
+ ```bash
26
+ git describe --tags --abbrev=0
27
+ git log --format='%s' "$(git describe --tags --abbrev=0)"..main
28
+ ```
29
+
30
+ Classify by conventional-commit type, and remember this package is pre-1.0:
31
+
32
+ | What landed | Bump |
33
+ | -------------------------------------------- | ------- |
34
+ | A breaking change (`!`, or a removed export) | `minor` |
35
+ | `feat` | `minor` |
36
+ | `fix`, `perf`, `refactor`, `chore`, `docs` | `patch` |
37
+
38
+ While the major is `0`, a breaking change is a **minor** bump, not a major one —
39
+ `0.1.7 → 0.2.0` in this repo's history is exactly that. Reserve `major` for
40
+ declaring the API stable, which is a decision, not a consequence of a diff.
41
+
42
+ **Always suggest a version and always ask.** State the bump, the resulting
43
+ version, and the one or two commits that drove it, then wait for a clear answer.
44
+ The log is a signal, not the decision — a `feat` that nobody can reach yet is a
45
+ patch, and a `fix` that changes a contract is not.
46
+
47
+ ## 2. Branch
48
+
49
+ ```bash
50
+ git checkout main && git pull
51
+ git checkout -b release/0.2.3
52
+ ```
53
+
54
+ The branch is named for the version it carries.
55
+
56
+ ## 3. Bump
57
+
58
+ ```bash
59
+ npm version 0.2.3 --no-git-tag-version
60
+ ```
61
+
62
+ `--no-git-tag-version` is not optional: `npm version` tags by default, and a tag
63
+ on this branch publishes before review.
64
+
65
+ Then check what moved:
66
+
67
+ ```bash
68
+ git status --porcelain
69
+ ```
70
+
71
+ **Only `package.json` may change.** `package-lock.json` has been stale since
72
+ `0.1.4` and every release since has left it alone; if npm touches it, revert it
73
+ rather than bringing unrelated churn into a release PR. Same for `bun.lock`.
74
+
75
+ ## 4. Roll the api changelogs
76
+
77
+ Every file in `docs/api/` ends with a changelog in
78
+ [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) form. For each file:
79
+
80
+ - A `### [Unreleased]` with entries under it becomes `### [0.2.3] - 2026-09-21`,
81
+ dated today. Leave the entries as they are — they were written by whoever made
82
+ the change and say what a caller has to do differently.
83
+ - A `### [Unreleased]` reading "No behaviour changes since …" is **not** rolled.
84
+ That module did not change; giving it a dated heading would claim it did.
85
+ Update its sentence to name the new version instead.
86
+ - Every file's `Latest release: **0.2.2**` line becomes the new version.
87
+
88
+ The next behaviour change adds `### [Unreleased]` back above the dated heading.
89
+ Do not leave an empty one behind.
90
+
91
+ ## 5. Commit and open
92
+
93
+ The commit message and the PR title are **the version alone**:
94
+
95
+ ```
96
+ 0.2.3
97
+ ```
98
+
99
+ No type, no scope, no body. That is how every release in this log reads
100
+ (`0.2.2 (#131)`, `0.2.1 (#78)`), and it is what makes them findable.
101
+
102
+ A release PR carries the bump and the changelog roll and nothing else. Do not
103
+ fold a fix into it, and do not fold a bump into a feature PR.
104
+
105
+ Open it against `main`, not as a draft — there is nothing to iterate on.
106
+
107
+ ## 6. After it merges
108
+
109
+ Tag the merge commit and push the tag; that is what publishes:
110
+
111
+ ```bash
112
+ git checkout main && git pull
113
+ git tag v0.2.3 && git push origin v0.2.3
114
+ ```
115
+
116
+ Confirm with the user before pushing a tag. It is the one irreversible step —
117
+ npm does not let a version be republished.
118
+
119
+ ## Sibling skills
120
+
121
+ - Writing any other PR → **pr-create**, which also covers why release PRs are
122
+ titled by version alone.
package/CLAUDE.md CHANGED
@@ -31,10 +31,15 @@ The library runs on both Bare and Node; the test suite runs under Bare only.
31
31
 
32
32
  ## Always
33
33
 
34
- - **Comment only what the code cannot say.** Why, not what. One or two lines,
35
- never more. Most code needs none — do not narrate it.
34
+ - **Comment only what the code cannot say.** Why, not what. One line, never two.
35
+ Most code needs none — do not narrate it. If one line cannot carry it, the code
36
+ needs reshaping, not a longer comment.
36
37
  - **Commits read as if a human wrote them.** No `Co-Authored-By` trailer and no
37
38
  AI or agent attribution, in a commit message or a PR.
39
+ - **Route behaviour is in `docs/api/`**, one file per api module, each with a
40
+ changelog. Read the one for a route before changing it, and add to its
41
+ changelog when you do. A module without a file yet gets one when a change
42
+ needs it.
38
43
  - **Durable decisions are in `docs/decisions/`.** Read `INDEX.md` when touching an
39
44
  area it lists, and open a record only on a path or keyword match — they are
40
45
  reference, not rules. Add one when a change makes a non-obvious lasting choice.
@@ -1,6 +1,5 @@
1
1
  import { createAgent, deleteAgent, isOrphaned, listAgents, liveProviderIds, mustGetActiveAgent, updateAgent } from '../core/agent.js';
2
- import { requireMesh } from './current-mesh.js';
3
- import { watchable } from './watchable.js';
2
+ import { meshWatchable, requireMesh } from './current-mesh.js';
4
3
  export function createAgentsApi(current, deviceId, computeLender = null) {
5
4
  const withOrphaned = async (mesh, agent) => ({
6
5
  ...agent,
@@ -34,6 +33,6 @@ export function createAgentsApi(current, deviceId, computeLender = null) {
34
33
  const mesh = await requireMesh(current, meshId);
35
34
  return withOrphaned(mesh, await deleteAgent(mesh, deviceId, id));
36
35
  },
37
- agentsWatch: watchable('agentsWatch', (request) => requireMesh(current, request?.meshId), (_request, mesh) => list(mesh))
36
+ agentsWatch: meshWatchable('agentsWatch', current, (_request, mesh) => list(mesh))
38
37
  };
39
38
  }
@@ -2,7 +2,7 @@ import { AbortController } from 'bare-abort-controller';
2
2
  import { createChat, deleteChat, listSidebar, mustGetActiveChatListing, renameChat, setChatRagEnabled, setChatWebSearchEnabled } from '../core/chat.js';
3
3
  import { listChatActivity } from '../core/chat-activity.js';
4
4
  import { searchChats } from '../core/chat-search.js';
5
- import { requireMesh } from './current-mesh.js';
5
+ import { meshWatchable, requireMesh, selectionPin } from './current-mesh.js';
6
6
  import { watchable } from './watchable.js';
7
7
  const SEARCH_SUPERSEDED_ABORT = 'superseded by a newer chat search';
8
8
  export function createChatApi(current, deviceId) {
@@ -17,9 +17,9 @@ export function createChatApi(current, deviceId) {
17
17
  setChatRagEnabled: async ({ id, enabled }) => setChatRagEnabled(await requireMesh(current), id, enabled ?? false),
18
18
  setChatWebSearchEnabled: async ({ id, enabled }) => setChatWebSearchEnabled(await requireMesh(current), id, enabled ?? false),
19
19
  deleteChat: async ({ id, meshId }) => deleteChat(await requireMesh(current, meshId), deviceId, id),
20
- chatsWatch: watchable('chatsWatch', (request) => requireMesh(current, request?.meshId), (_request, store) => chatList(store)),
20
+ chatsWatch: meshWatchable('chatsWatch', current, (_request, store) => chatList(store)),
21
21
  listChatActivity: async (input) => chatActivity(await requireMesh(current), input?.chatIds),
22
- chatActivityWatch: watchable('chatActivityWatch', () => requireMesh(current), (request, store) => chatActivity(store, request?.chatIds)),
22
+ chatActivityWatch: watchable('chatActivityWatch', () => requireMesh(current), (request, store) => chatActivity(store, request?.chatIds), () => selectionPin(current)),
23
23
  searchChats: async (input) => {
24
24
  searchAbort?.abort(SEARCH_SUPERSEDED_ABORT);
25
25
  const controller = new AbortController();
@@ -1,5 +1,5 @@
1
1
  import { type CurrentMesh } 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): ChunkCapabilities;
4
+ export declare function createChunksApi(current: CurrentMesh, deviceId: Buffer | null): ChunkCapabilities;
5
5
  export {};
@@ -1,7 +1,6 @@
1
- import { appendChunk, listAttachmentsByKind, listChunks, resolveApproval, updateChunk } from '../core/chunk.js';
2
- import { requireMesh } from './current-mesh.js';
3
- import { watchable } from './watchable.js';
4
- export function createChunksApi(current) {
1
+ import { appendChunk, listAttachmentsByKind, listChunks, listRunRequests, resolveApproval, updateChunk } from '../core/chunk.js';
2
+ import { meshWatchable, requireMesh } from './current-mesh.js';
3
+ export function createChunksApi(current, deviceId) {
5
4
  return {
6
5
  appendChunk: async ({ meshId, ...input }) => appendChunk(await requireMesh(current, meshId), input),
7
6
  updateChunk: async ({ meshId, ...input }) => {
@@ -37,7 +36,7 @@ export function createChunksApi(current) {
37
36
  limit: limit || undefined
38
37
  })
39
38
  }),
40
- chunksWatch: watchable('chunksWatch', (request) => requireMesh(current, request?.meshId), async ({ chatId, type, types, fromSeq, reverse, limit }, mesh) => ({
39
+ chunksWatch: meshWatchable('chunksWatch', current, async ({ chatId, type, types, fromSeq, reverse, limit }, mesh) => ({
41
40
  chunks: await listChunks(mesh, {
42
41
  chatId,
43
42
  type: type ?? undefined,
@@ -47,15 +46,6 @@ export function createChunksApi(current) {
47
46
  limit: limit || undefined
48
47
  })
49
48
  })),
50
- runRequestsWatch: watchable('runRequestsWatch', (request) => requireMesh(current, request?.meshId), async (_request, mesh) => {
51
- const snap = mesh.view.snapshot();
52
- try {
53
- const chunks = await snap.find('@qvac/run-requests').toArray();
54
- return { chunks };
55
- }
56
- finally {
57
- await snap.close();
58
- }
59
- })
49
+ runRequestsWatch: meshWatchable('runRequestsWatch', current, async (_request, mesh) => ({ chunks: await listRunRequests(mesh, deviceId) }))
60
50
  };
61
51
  }
@@ -1,6 +1,21 @@
1
1
  import type { Mesh } from '../core/mesh.ts';
2
- export type CurrentMesh = (meshId?: string | null) => Mesh | null | Promise<Mesh | null>;
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;
9
+ watch(listener: () => void): void;
10
+ unwatch(listener: () => void): void;
11
+ }
3
12
  export declare const NO_ACTIVE_MESH = "no active mesh";
4
13
  export declare const NO_SUCH_MESH = "no such mesh";
5
14
  export declare function requireMesh(current: CurrentMesh, meshId?: string | null): Promise<Mesh>;
6
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;
18
+ interface MeshScoped {
19
+ readonly meshId?: string | null;
20
+ }
21
+ export {};
@@ -1,3 +1,4 @@
1
+ import { watchable } from './watchable.js';
1
2
  export const NO_ACTIVE_MESH = 'no active mesh';
2
3
  export const NO_SUCH_MESH = 'no such mesh';
3
4
  export async function requireMesh(current, meshId) {
@@ -11,3 +12,20 @@ export async function requireMesh(current, meshId) {
11
12
  export function isMeshTransition(err) {
12
13
  return err instanceof Error && err.message === NO_ACTIVE_MESH;
13
14
  }
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
+ };
31
+ }
@@ -1,6 +1,6 @@
1
+ import { MAX_DEVICE_NAME_CHARS, deviceNameWithinBounds } from '../../schema/qvac.js';
1
2
  import { saveDeviceCapabilities } from '../core/devices.js';
2
- import { requireMesh } from './current-mesh.js';
3
- import { watchable } from './watchable.js';
3
+ import { meshWatchable, requireMesh } from './current-mesh.js';
4
4
  const DEVICES = '@qvac/devices';
5
5
  function toEngineDevice(device, overrides = {}) {
6
6
  return {
@@ -49,7 +49,7 @@ export function createDevicesApi(current, deviceId, removeWriter, renameLocal, s
49
49
  };
50
50
  return {
51
51
  listDevices: async (request) => list(await requireMesh(current, request?.meshId)),
52
- devicesWatch: watchable('devicesWatch', (request) => requireMesh(current, request?.meshId), (_request, mesh) => list(mesh)),
52
+ devicesWatch: meshWatchable('devicesWatch', current, (_request, mesh) => list(mesh)),
53
53
  deviceInfo: async () => {
54
54
  logger.info(['api', 'devices'], 'deviceInfo handler reached');
55
55
  const computeLenderId = (await computeLender?.()) ?? undefined;
@@ -85,6 +85,9 @@ export function createDevicesApi(current, deviceId, removeWriter, renameLocal, s
85
85
  const trimmed = name.trim();
86
86
  if (!trimmed)
87
87
  throw new Error('device name must not be empty');
88
+ if (!deviceNameWithinBounds(trimmed)) {
89
+ throw new Error(`device name must be at most ${MAX_DEVICE_NAME_CHARS} characters`);
90
+ }
88
91
  const mesh = await requireMesh(current);
89
92
  const device = await mustGetDevice(mesh, id);
90
93
  await renameLocal(trimmed);
@@ -41,7 +41,7 @@ export function createApi(deps = {}) {
41
41
  ...(mesh ? createChatApi(mesh, deps.deviceId ?? null) : null),
42
42
  ...(mesh ? createChatGroupsApi(mesh) : null),
43
43
  ...(mesh ? createApprovalRulesApi(mesh) : null),
44
- ...(mesh ? createChunksApi(mesh) : null),
44
+ ...(mesh ? createChunksApi(mesh, deps.deviceId ?? null) : null),
45
45
  ...(mesh && deps.deviceId && deps.deviceHost
46
46
  ? createDevicesApi(mesh, deps.deviceId, deps.deviceHost.removeWriter, deps.deviceHost.renameLocal, deps.deviceHost.saveProfileLocal, deps.deviceHost.readLocalProfile, deps.computeLender ?? null)
47
47
  : null),
@@ -1,4 +1,4 @@
1
- import { requireMesh } from './current-mesh.js';
1
+ import { requireMesh, selectionPin } from './current-mesh.js';
2
2
  import { watchable } from './watchable.js';
3
3
  export { MAX_KNOWLEDGE_BYTES } from '../core/files/knowledge.js';
4
4
  export function createKnowledgeApi(current, options = {}) {
@@ -13,14 +13,18 @@ export function createKnowledgeApi(current, options = {}) {
13
13
  return (await requireMesh(current)).files.knowledge(options).removeKnowledge(request);
14
14
  },
15
15
  async listKnowledge(request) {
16
- return (await requireMesh(current)).files.knowledge(options).listKnowledge(request);
16
+ return (await requireMesh(current, request?.meshId)).files
17
+ .knowledge(options)
18
+ .listKnowledge(request);
17
19
  },
18
20
  async listIndexing(request) {
19
- return (await requireMesh(current)).files.knowledge(options).listIndexing(request);
21
+ return (await requireMesh(current, request?.meshId)).files
22
+ .knowledge(options)
23
+ .listIndexing(request);
20
24
  },
21
- knowledgeWatch: watchable('knowledgeWatch', () => requireMesh(current), async (request, mesh) => mesh.files.knowledge(options).listKnowledge(request)),
22
- indexingWatch: watchable('indexingWatch', async () => (await requireMesh(current)).files, ({ chatId }, files) => files.listIndexing(chatId)),
23
- fileStatusWatch: watchable('fileStatusWatch', async (request) => (await requireMesh(current, request?.meshId)).files, ({ chatId }, files) => files.status(chatId)),
24
- indexingProgressWatch: watchable('indexingProgressWatch', async () => (await requireMesh(current)).files, ({ chatId }, files) => Promise.resolve({ entries: files.progress(chatId) }))
25
+ knowledgeWatch: watchable('knowledgeWatch', (request) => requireMesh(current, request?.meshId), async (request, mesh) => mesh.files.knowledge(options).listKnowledge(request), (request) => selectionPin(current, request?.meshId)),
26
+ indexingWatch: watchable('indexingWatch', async (request) => (await requireMesh(current, request?.meshId)).files, ({ chatId }, files) => files.listIndexing(chatId), (request) => selectionPin(current, request?.meshId)),
27
+ fileStatusWatch: watchable('fileStatusWatch', async (request) => (await requireMesh(current, request?.meshId)).files, ({ chatId }, files) => files.status(chatId), (request) => selectionPin(current, request?.meshId)),
28
+ indexingProgressWatch: watchable('indexingProgressWatch', async (request) => (await requireMesh(current, request?.meshId)).files, ({ chatId }, files) => Promise.resolve({ entries: files.progress(chatId) }), (request) => selectionPin(current, request?.meshId))
25
29
  };
26
30
  }
@@ -1,5 +1,4 @@
1
- import { requireMesh } from './current-mesh.js';
2
- import { watchable } from './watchable.js';
1
+ import { meshWatchable, requireMesh } from './current-mesh.js';
3
2
  const MEMBERS = '@qvac/members';
4
3
  const DEVICES = '@qvac/devices';
5
4
  const RESOLVE_MEMBER_MS = 10_000;
@@ -62,7 +61,7 @@ export function createMembersApi(current, state = null) {
62
61
  };
63
62
  return {
64
63
  listMembers: async (request) => list(await requireMesh(current, request?.meshId)),
65
- membersWatch: watchable('membersWatch', (request) => requireMesh(current, request?.meshId), (_request, mesh) => list(mesh)),
64
+ membersWatch: meshWatchable('membersWatch', current, (_request, mesh) => list(mesh)),
66
65
  updateMember: async ({ id, name, meshId }) => {
67
66
  const mesh = await requireMesh(current, meshId);
68
67
  const trimmed = name.trim();
@@ -1,3 +1,3 @@
1
1
  import type { CapabilityHandlers } from '../../spec/capabilities.d.ts';
2
- import type { CurrentMesh } from './current-mesh.ts';
2
+ import { type CurrentMesh } from './current-mesh.ts';
3
3
  export declare function createSyncApi(current: CurrentMesh): Pick<CapabilityHandlers, 'syncStatusWatch'>;
@@ -1,6 +1,7 @@
1
+ import { selectionPin } from './current-mesh.js';
1
2
  import { watchable } from './watchable.js';
2
3
  export function createSyncApi(current) {
3
4
  return {
4
- syncStatusWatch: watchable('syncStatusWatch', async () => (await current())?.syncActivity ?? null, (_request, activity) => activity.snapshot())
5
+ syncStatusWatch: watchable('syncStatusWatch', async () => (await current())?.syncActivity ?? null, (_request, activity) => activity.snapshot(), () => selectionPin(current))
5
6
  };
6
7
  }
@@ -1,5 +1,5 @@
1
1
  import { listToolActivity, recordToolActivity } from '../core/tool-activity.js';
2
- import { requireMesh } from './current-mesh.js';
2
+ import { requireMesh, selectionPin } from './current-mesh.js';
3
3
  import { watchable } from './watchable.js';
4
4
  const DEFAULT_LIMIT = 200;
5
5
  const MAX_LIMIT = 1000;
@@ -32,7 +32,7 @@ export function createToolActivityApi(current, deviceId) {
32
32
  });
33
33
  return {
34
34
  listToolActivity: async (request) => query(request, await requireMesh(current)),
35
- toolActivityWatch: watchable('toolActivityWatch', () => requireMesh(current), query),
35
+ toolActivityWatch: watchable('toolActivityWatch', () => requireMesh(current), query, () => selectionPin(current)),
36
36
  recordToolActivity: async (request) => {
37
37
  if (!deviceId)
38
38
  throw new Error('cannot record tool activity without a device id');
@@ -1,5 +1,5 @@
1
1
  import { deleteToolConfigs, getToolConfigs, listToolConfigs, setToolConfigs } from '../core/tool-configs.js';
2
- import { requireMesh } from './current-mesh.js';
2
+ import { requireMesh, selectionPin } from './current-mesh.js';
3
3
  import { watchable } from './watchable.js';
4
4
  function isRecord(value) {
5
5
  return typeof value === 'object' && value !== null && !Array.isArray(value);
@@ -21,7 +21,7 @@ export function createToolConfigsApi(current) {
21
21
  }),
22
22
  deleteToolConfigs: async ({ agentId, toolName }) => deleteToolConfigs(await requireMesh(current), agentId, toolName),
23
23
  listToolConfigs: async (request) => query(request, await requireMesh(current, request.meshId)),
24
- toolConfigsWatch: watchable('toolConfigsWatch', (request) => requireMesh(current, request?.meshId), query)
24
+ toolConfigsWatch: watchable('toolConfigsWatch', (request) => requireMesh(current, request?.meshId), query, (request) => selectionPin(current, request?.meshId))
25
25
  };
26
26
  }
27
27
  export { getToolConfigs };
@@ -1,5 +1,10 @@
1
1
  import { Readable } from 'streamx';
2
2
  import '../logger.ts';
3
+ export interface WatchPin {
4
+ stale(): boolean;
5
+ watch(listener: () => void): void;
6
+ unwatch(listener: () => void): void;
7
+ }
3
8
  interface WatchableStore {
4
9
  watch(listener: () => void): void;
5
10
  unwatch(listener: () => void): void;
@@ -8,5 +13,5 @@ interface WatchableStore {
8
13
  closing?: unknown;
9
14
  closed?: boolean;
10
15
  }
11
- export declare function watchable<TRequest, TResult, TStore extends WatchableStore = WatchableStore>(name: string, storeOf: (request: TRequest) => TStore | null | Promise<TStore | null>, query: (request: TRequest, store: TStore) => Promise<TResult>): (request: TRequest) => Readable & AsyncIterable<TResult>;
16
+ export declare function watchable<TRequest, TResult, TStore extends WatchableStore = WatchableStore>(name: string, storeOf: (request: TRequest) => TStore | null | Promise<TStore | null>, query: (request: TRequest, store: TStore) => Promise<TResult>, pinOf?: (request: TRequest) => WatchPin | null): (request: TRequest) => Readable & AsyncIterable<TResult>;
12
17
  export {};
@@ -24,8 +24,9 @@ function snapshotEquals(a, b) {
24
24
  function isRecord(value) {
25
25
  return typeof value === 'object' && value !== null;
26
26
  }
27
- export function watchable(name, storeOf, query) {
27
+ export function watchable(name, storeOf, query, pinOf) {
28
28
  return (request) => {
29
+ const pin = pinOf?.(request) ?? null;
29
30
  const resolved = storeOf(request);
30
31
  const pending = resolved instanceof Promise ? resolved.catch(noop) : null;
31
32
  let store = resolved instanceof Promise ? null : resolved;
@@ -56,13 +57,22 @@ export function watchable(name, storeOf, query) {
56
57
  wake?.resolve();
57
58
  wake = null;
58
59
  };
59
- const storeGone = () => store === null || ended || Boolean(store.closed) || Boolean(store.closing);
60
+ const onPinMove = () => {
61
+ if (pin?.stale())
62
+ onStoreClose();
63
+ };
64
+ const storeGone = () => store === null ||
65
+ ended ||
66
+ Boolean(store.closed) ||
67
+ Boolean(store.closing) ||
68
+ Boolean(pin?.stale());
60
69
  const stream = new Readable({
61
70
  async open(cb) {
62
71
  if (pending)
63
72
  store = (await pending) ?? null;
64
73
  store?.watch(onChange);
65
74
  store?.once?.('close', onStoreClose);
75
+ pin?.watch(onPinMove);
66
76
  cb(null);
67
77
  },
68
78
  async read(cb) {
@@ -112,6 +122,7 @@ export function watchable(name, storeOf, query) {
112
122
  reportChurn(true);
113
123
  store?.unwatch(onChange);
114
124
  store?.off?.('close', onStoreClose);
125
+ pin?.unwatch(onPinMove);
115
126
  cb(null);
116
127
  }
117
128
  });
@@ -17,14 +17,13 @@ export interface CompactOptions {
17
17
  readonly onFold?: () => Promise<void> | void;
18
18
  readonly meshId?: string;
19
19
  }
20
- export type CompactionTrigger = 'before-run' | 'turn-filled-window' | 'overflow';
20
+ export type CompactionTrigger = 'before-run' | 'overflow';
21
21
  export interface CompactResult {
22
22
  readonly compacted: boolean;
23
23
  readonly foldedTurns?: number;
24
24
  readonly reason?: string;
25
25
  }
26
26
  export declare function historyFromChunks(chunks: ReadonlyArray<AssistantChunk>, stale?: Partial<StaleToolRuns>): ChatMessage[];
27
- export declare function withoutOccupancy(metrics: Record<string, unknown> | undefined): typeof metrics;
28
27
  export declare function inputAvailableToRun(chunk: AssistantChunk, requestSeq: number): boolean;
29
28
  export declare function normalizeQuestion(text: string): string;
30
29
  export declare const GENERIC_ACKNOWLEDGEMENTS: Set<string>;
@@ -127,12 +127,6 @@ export function historyFromChunks(chunks, stale = {}) {
127
127
  }
128
128
  return history.filter((turn) => turn.role === 'user' || turn.content.length > 0);
129
129
  }
130
- export function withoutOccupancy(metrics) {
131
- if (!metrics)
132
- return metrics;
133
- const { cacheTokens, promptTokens, ...rest } = metrics;
134
- return rest;
135
- }
136
130
  export function inputAvailableToRun(chunk, requestSeq) {
137
131
  const userInput = Boolean(chunk.userMessage || (chunk.attachment && !chunk.runId));
138
132
  return !userInput || chunk.seq < requestSeq;