@qvac/core 0.1.2 → 0.1.4

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.
package/README.md CHANGED
@@ -1,5 +1,5 @@
1
1
  <p align="center">
2
- <img src="https://raw.githubusercontent.com/tetherto/qvac-core/main/ducks.png" alt="" width="200">
2
+ <img src="ducks.png" alt="" width="200">
3
3
  </p>
4
4
 
5
5
  <h1 align="center">@qvac/core</h1>
@@ -21,7 +21,8 @@
21
21
  <a href="#one-shot-tasks">Tasks</a> &middot;
22
22
  <a href="#rendering-the-chunk-stream-any-ui">Chunk stream</a> &middot;
23
23
  <a href="#harness-event-reference">Events</a> &middot;
24
- <a href="#development">Development</a>
24
+ <a href="#development">Development</a> &middot;
25
+ <a href="#the-duck-tui">duck TUI</a>
25
26
  </p>
26
27
 
27
28
  A P2P, multi-device AI workbench core. Three pieces, one duplex stream:
@@ -41,6 +42,26 @@ A P2P, multi-device AI workbench core. Three pieces, one duplex stream:
41
42
  └────────────────────────────────────────────┘ └────────────────────────────┘
42
43
  ```
43
44
 
45
+ ## Install
46
+
47
+ `@qvac/core` is two things: a **library** you embed, and **`duck`**, a terminal
48
+ app that runs the whole stack on top of it.
49
+
50
+ ```sh
51
+ npm i @qvac/core # the library
52
+ npm i -g @qvac/core # duck, on your PATH
53
+ ```
54
+
55
+ ```sh
56
+ duck # the TUI
57
+ duck --help
58
+ ```
59
+
60
+ The library is the three pieces above — start at
61
+ [Integrating a harness](#integrating-a-harness). `duck` is the fastest way to
62
+ watch them work, and what the examples here drive; it has its own section at
63
+ [The duck TUI](#the-duck-tui).
64
+
44
65
  ## Integrating a harness
45
66
 
46
67
  A harness is one method. Implement `completion(context)` as an async iterable
@@ -613,8 +634,8 @@ skill's `allow_list` binds that key to the URL prefixes it may be sent to.
613
634
  Credentials are **per agent** (stored at `skills.<agentId>.<key>`), so two
614
635
  agents never share one connection.
615
636
 
616
- Fill a key with a slash command in the running TUI (`duck` drives the
617
- command set):
637
+ Fill a key with a slash command in the running TUI — see
638
+ [The duck TUI](#the-duck-tui):
618
639
 
619
640
  - `/connect google` · `/connect spotify` · `/connect asana` · `/connect notion` — browser OAuth;
620
641
  the example stores the token and refreshes it on use.
@@ -641,28 +662,53 @@ Then ask the assistant anything Notion — it loads the `notion` skill and calls
641
662
  `mcp_call` itself; the session handshake and auth are handled for you. A `401`
642
663
  in a tool result means the token expired — run `/connect notion` again.
643
664
 
665
+ ## Development
666
+
644
667
  ```sh
645
- duck
668
+ npm test # node + bare suites
669
+ npm run build:schema # regenerate spec/ from schema/ (bare)
670
+ bun run duck # run the TUI (no build step)
646
671
  ```
647
672
 
648
- Office documents (`docx`, `doc`, `odt`) decode through an engine the host supplies rather
649
- than a declared dependency: the package pulls all thirteen platform prebuilds at ~350MB
650
- each, so declaring it would cost every install 4.3GB. Fetch the one for this machine before
651
- exercising `/knowledge add report.docx`:
673
+ The TUI lives in [`tui/`](tui/README.md) and installs as the `duck` command.
674
+ Schema changes go in `schema/*.ts` (builders) — `spec/` is generated. The
675
+ mesh schema (`spec/mesh/*`) is the replicated protocol: every device in a
676
+ mesh must run the same generated spec. See `MIGRATION.md` for the audited
677
+ feature checklist vs core v1.
678
+
679
+ ### Office documents
680
+
681
+ Word-processor documents (`.docx`, `.doc`, `.docm`, `.dot`, `.dotx`, `.odt`,
682
+ `.fodt`, `.ott`) decode through an engine the host supplies rather than a
683
+ declared dependency: the package pulls all thirteen platform prebuilds at
684
+ ~350MB each, so declaring it would cost every install 4.3GB. In this repo,
685
+ fetch the one for this machine before exercising `/knowledge add report.docx`:
652
686
 
653
687
  ```sh
654
688
  bun run engine:collabora
655
689
  ```
656
690
 
691
+ **There is no equivalent for an installed `duck`.** Nothing fetches the engine
692
+ for you, so those formats fail to index outside this repo, even though
693
+ `/knowledge add` accepts them. Everything else it accepts — `.pdf`, `.txt`,
694
+ `.md`, `.rtf`, `.html`, `.csv`, `.json` and the rest — works from any install.
695
+
696
+ ## The duck TUI
697
+
698
+ `duck` brings the whole stack up — Core, the assistant, your harness — behind a
699
+ terminal UI. It is on your PATH after `npm i -g @qvac/core`, or `bun run duck`
700
+ in this repo. `duck --help` lists the flags.
701
+
657
702
  The TUI copies its mesh invite to the clipboard on ctrl+y. On a second machine
658
- (or a second terminal):
703
+ (or a second terminal), start `duck` and join from inside it:
659
704
 
660
- ```sh
661
- duck qvac://mesh/…
705
+ ```
706
+ /join qvac://mesh/…
662
707
  ```
663
708
 
664
- A running TUI moves mesh with `/join qvac://mesh/…` — it retires the mesh it is
665
- on, joins that one, and re-resolves the agent and chat from it.
709
+ That retires the mesh it is on, joins the invited one, and re-resolves the agent
710
+ and chat from it. The engine takes an invite live, so joining never needed to be
711
+ a boot argument.
666
712
 
667
713
  `--headless` brings the same stack up with no TUI: it prints the invite and then
668
714
  streams logs (including the sidecar child's own output, which the TUI drops) to
@@ -677,18 +723,3 @@ The joiner brings no models and no agents — it finds the mesh's seeded agent,
677
723
  asks, and the _creator's_ device runs the model while both sides watch the
678
724
  same replicated stream: load progress, thinking, tokens, tool approvals
679
725
  (either side can answer), and final stats.
680
-
681
- ## Development
682
-
683
- ```sh
684
- npm test # node + bare suites
685
- npm run build:schema # regenerate spec/ from schema/ (bare)
686
- bun run duck # build the assistant bundle, then run the TUI on it
687
- bun run duck:warm # run the TUI against the last-built bundle
688
- ```
689
-
690
- The TUI lives in [`tui/`](tui/README.md) and installs as the `duck` command.
691
- Schema changes go in `schema/*.ts` (builders) — `spec/` is generated. The
692
- mesh schema (`spec/mesh/*`) is the replicated protocol: every device in a
693
- mesh must run the same generated spec. See `MIGRATION.md` for the audited
694
- feature checklist vs core v1.
@@ -1,4 +1,5 @@
1
1
  import { Buffer } from 'buffer';
2
+ export { scopedKey } from './keys.ts';
2
3
  export declare const CALLBACK_PATH = "/callback";
3
4
  export declare const DEFAULT_TIMEOUT_MS = 120000;
4
5
  export declare const REFRESH_SKEW_MS = 60000;
@@ -33,6 +34,5 @@ export declare function createPkce(randomBytes?: RandomBytes): {
33
34
  challenge: string;
34
35
  method: "S256";
35
36
  };
36
- export declare function scopedKey(agentId: string | undefined, key: string): string;
37
37
  export declare function oauthRedirectUri(port: number): string;
38
38
  export declare function tokenRequest(fetchImpl: Fetch, tokenUrl: string, body: URLSearchParams, label: string): Promise<OAuthTokens>;
@@ -1,5 +1,6 @@
1
1
  import { Buffer } from 'buffer';
2
2
  import { createHash, randomBytes as defaultRandomBytes } from 'crypto';
3
+ export { scopedKey } from "./keys.js";
3
4
  export const CALLBACK_PATH = '/callback';
4
5
  export const DEFAULT_TIMEOUT_MS = 120_000;
5
6
  export const REFRESH_SKEW_MS = 60_000;
@@ -11,9 +12,6 @@ export function createPkce(randomBytes = defaultRandomBytes) {
11
12
  const challenge = base64url(createHash('sha256').update(verifier).digest());
12
13
  return { verifier, challenge, method: 'S256' };
13
14
  }
14
- export function scopedKey(agentId, key) {
15
- return agentId ? `skills.${agentId}.${key}` : `skills.${key}`;
16
- }
17
15
  export function oauthRedirectUri(port) {
18
16
  return `http://127.0.0.1:${port}${CALLBACK_PATH}`;
19
17
  }
@@ -1,4 +1,5 @@
1
1
  import type { OAuthProvider } from './types.ts';
2
+ export declare function scopedKey(agentId: string | undefined, key: string): string;
2
3
  export declare const GMAIL_CREDENTIAL_KEY = "gmail_access_token";
3
4
  export declare const GOOGLE_CALENDAR_CREDENTIAL_KEY = "google_calendar_access_token";
4
5
  export declare const GOOGLE_DOCS_CREDENTIAL_KEY = "google_docs_access_token";
@@ -1,3 +1,6 @@
1
+ export function scopedKey(agentId, key) {
2
+ return agentId ? `skills.${agentId}.${key}` : `skills.${key}`;
3
+ }
1
4
  export const GMAIL_CREDENTIAL_KEY = 'gmail_access_token';
2
5
  export const GOOGLE_CALENDAR_CREDENTIAL_KEY = 'google_calendar_access_token';
3
6
  export const GOOGLE_DOCS_CREDENTIAL_KEY = 'google_docs_access_token';
@@ -21,6 +21,7 @@ export interface UploadStream<In, Out> extends WatchStream<Out> {
21
21
 
22
22
  // what hrpc hands a duplex handler (its own async iterator hangs - see api/attachments.ts)
23
23
  export interface HandlerFrames<Frame> {
24
+ readonly writeStream?: { readonly destroyed: boolean; readonly destroying: boolean; on(event: 'close', listener: () => void): void; off(event: 'close', listener: () => void): void }
24
25
  on(event: 'data', listener: (frame: Frame) => void): void
25
26
  on(event: 'end', listener: () => void): void
26
27
  on(event: 'error', listener: (err: Error) => void): void
package/ducks.png ADDED
Binary file
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@qvac/core",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "type": "module",
5
5
  "description": "Peer-to-peer AI across your devices",
6
6
  "exports": {
@@ -134,8 +134,7 @@
134
134
  "./suspend-lifecycle": {
135
135
  "types": "./dist-lib/lib/suspend-lifecycle.d.ts",
136
136
  "default": "./dist-lib/lib/suspend-lifecycle.js"
137
- },
138
- "./dist/assistant.cjs": "./dist/assistant.cjs"
137
+ }
139
138
  },
140
139
  "bin": {
141
140
  "duck": "./tui/index.mjs"
@@ -143,8 +142,7 @@
143
142
  "scripts": {
144
143
  "build:splash": "node tui/build-splash.mjs",
145
144
  "build:schema": "bare schema/build.ts",
146
- "duck": "node scripts/build-bundle.mjs && bare tui/index.mjs",
147
- "duck:warm": "bare tui/index.mjs",
145
+ "duck": "bare tui/index.mjs",
148
146
  "mesh-peer": "bare examples/mesh-peer.mjs",
149
147
  "mesh-lab": "bare examples/mesh-lab.mjs",
150
148
  "test": "npm run test:node && npm run test:bare && npm run test:addons",
@@ -154,7 +152,7 @@
154
152
  "format": "prettier . --write",
155
153
  "lint": "prettier . --check && lunte && tsc --noEmit",
156
154
  "build:bundle": "node scripts/build-bundle.mjs",
157
- "prepack": "node scripts/build-lib.mjs && node scripts/build-bundle.mjs --minify",
155
+ "prepack": "node scripts/build-lib.mjs",
158
156
  "build:lib": "node scripts/build-lib.mjs",
159
157
  "test:addons": "node --test scripts/addon-externals.test.cjs"
160
158
  },
@@ -218,7 +216,7 @@
218
216
  }
219
217
  },
220
218
  "dependencies": {
221
- "@qvac/harness": "^0.2.1",
219
+ "@qvac/harness": "^0.2.4",
222
220
  "@qvac/skills": "^0.1.3",
223
221
  "asenion": "^0.1.0",
224
222
  "autobee": "2.6.0",
@@ -242,6 +240,7 @@
242
240
  "bare-rpc": "^1.3.7",
243
241
  "bare-semver": "^1.1.0",
244
242
  "bare-storage": "^1.1.0",
243
+ "bare-stow": "^0.1.4",
245
244
  "bare-stream": "^2.13.3",
246
245
  "bare-subprocess": "^6.1.0",
247
246
  "bare-supervisor": "^0.1.1",
@@ -266,11 +265,15 @@
266
265
  "hyperschema-ts": "^0.1.1",
267
266
  "hyperswarm": "^4.17.0",
268
267
  "keet-identity-key": "^3.2.0",
268
+ "paparam": "^1.13.0",
269
269
  "process-top": "^1.7.1",
270
270
  "protomux": "^3.11.0",
271
271
  "protomux-wakeup": "^2.9.0",
272
272
  "rache": "^1.0.0",
273
273
  "ready-guard": "^1.0.0",
274
+ "ready-resource": "^1.2.0",
275
+ "rocksdb-native": "^3.17.4",
276
+ "safety-catch": "^1.0.3",
274
277
  "scope-lock": "^1.2.4",
275
278
  "streamx": "^2.28.0",
276
279
  "suspendify": "^1.7.2",
@@ -287,7 +290,6 @@
287
290
  "bare-pack": "^2.2.1",
288
291
  "bare-runtime": "^1.30.0",
289
292
  "bare-sidecar": "^0.5.2",
290
- "bare-stow": "^0.1.4",
291
293
  "brittle": "^4.0.2",
292
294
  "holepunch-types": "^0.2.1",
293
295
  "hyperdht": "^6.32.0",
package/tui/README.md CHANGED
@@ -14,25 +14,26 @@ npm i -g @qvac/core # duck
14
14
  In the repo:
15
15
 
16
16
  ```sh
17
- bun run duck # build the assistant bundle, then run
18
- bun run duck:warm # reuse the last-built bundle
17
+ bun run duck # no build step
19
18
  ```
20
19
 
21
- `duck` runs the SAME `dist/assistant.bundle` the desktop app ships — the stow of
22
- `worker/assistant-sidecar.mjs` that `scripts/build-bundle.mjs` builds. `bun run
23
- duck` rebuilds it first, because a stale bundle decodes with the old wire format
24
- and dies on the first call whose encoding changed; a freshly written bundle also
25
- pays a one-time cold start on its first spawn (OS page-cache miss + the
26
- platform's security assessment of the new binary and its native addons). The TUI
27
- host (`index.mjs`, `app.mjs`) is not in that bundle, so while iterating on the
28
- TUI use `duck:warm`. Rebuild after changing any `worker/`, wire, or `lib/`
29
- source.
30
-
31
- The bundle carries its JS but not its native addons: `build-bundle.mjs` offloads
32
- those beside the bundle and leaves the forest out of the tarball, shipping
33
- `dist/prebuilds-manifest.json` instead. `lib/prebuilds.mjs` links this host's
34
- addons back into place from the installed `node_modules` on first run — which is
35
- why an installed `duck` needs no postinstall step.
20
+ `duck` spawns `worker/assistant-sidecar.mjs` — the same entry the desktop app
21
+ stows — and the harness the same way, as files rather than bundles. There is
22
+ nothing to rebuild: every source it runs is read from disk, so an edit to
23
+ `worker/`, `lib/` or the TUI itself takes effect on the next run.
24
+
25
+ A stow bundle is two halves — the JS inlined into it, and the native addons
26
+ offloaded beside it, since dlopen cannot read a path inside a bundle — and it
27
+ earns that split only when the code is relocated away from `node_modules`. The
28
+ desktop and mobile apps do exactly that, and stow their own entries at their own
29
+ build time, from one tree, so their halves cannot disagree. `duck` runs from
30
+ inside `node_modules`, where every addon already sits beside the JS that calls
31
+ it, so a bundle here would only separate a pair that is already together. This
32
+ package published one anyway until 0.1.2, and a `bare-pipe` one patch release
33
+ ahead of the JS calling it hung the sidecar on boot with no error at all.
34
+
35
+ `scripts/build-bundle.mjs` still builds one for anyone who does relocate; it is
36
+ not published.
36
37
 
37
38
  `index.mjs` is the `duck` bin — a `#!/usr/bin/env bare` script, so `bare` has to
38
39
  be on PATH (`bare-runtime` puts it in `node_modules/.bin`). `bare-tui` needs
@@ -72,15 +73,14 @@ for the full command set.
72
73
 
73
74
  ## Environment
74
75
 
75
- | Variable | Effect |
76
- | ----------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
77
- | `QVAC_MODEL` | Overrides the demo agent's model — a registry name, or a local path/URL |
78
- | `QVAC_MMPROJ` | Pairs models with their mmproj projections so ctrl+V'd images reach the model natively. One value applies to every model; `model=mmproj,model2=mmproj2` pairs are per-model. `QVAC_INPROCESS=1` only |
79
- | `QVAC_IMAGE_MODEL` | Enables the `generate_image`/`edit_image` tools — a catalog choice (`sd2` \| `sdxl` \| `flux2-klein`), or a local diffusion model |
80
- | `QVAC_IMAGE_LLM`, `QVAC_IMAGE_VAE`, `QVAC_IMAGE_PREDICTION` | FLUX.2 is a companion set: the Qwen3 text encoder, the VAE, and `flux2_flow` (required for img2img) |
81
- | `QVAC_LOG_FILE`, `QVAC_LOG_LEVEL` | Move the log file / pick the level (`debug` \| `info` \| `warn` \| `error`, default `info`) |
82
- | `QVAC_BOOT_TIMING=1` | Prints the total connect time after the TUI exits. Per-stage stamps exist only under `QVAC_INPROCESS=1` — the shared assistant sidecar carries no boot timer |
83
- | `QVAC_INPROCESS=1` | Runs Core and Client in this process, no sidecar — the only topology that can inject a live harness object |
76
+ | Variable | Effect |
77
+ | ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
78
+ | `QVAC_MODEL` | Overrides the demo agent's model — a registry name, or a local path/URL |
79
+ | `QVAC_MMPROJ` | Pairs models with their mmproj projections so ctrl+V'd images reach the model natively. One value applies to every model; `model=mmproj,model2=mmproj2` pairs are per-model |
80
+ | `QVAC_IMAGE_MODEL` | Enables the `generate_image`/`edit_image` tools — a catalog choice (`sd2` \| `sdxl` \| `flux2-klein`), or a local diffusion model |
81
+ | `QVAC_IMAGE_LLM`, `QVAC_IMAGE_VAE`, `QVAC_IMAGE_PREDICTION` | FLUX.2 is a companion set: the Qwen3 text encoder, the VAE, and `flux2_flow` (required for img2img) |
82
+ | `QVAC_LOG_FILE`, `QVAC_LOG_LEVEL` | Move the log file / pick the level (`debug` \| `info` \| `warn` \| `error`, default `info`) |
83
+ | `QVAC_BOOT_TIMING=1` | Prints the total connect time after the TUI exits |
84
84
 
85
85
  ```sh
86
86
  QVAC_MODEL=~/.qvac/models/3a65a2a3c6a30a47_Qwen3.5-4B-Q4_K_M.gguf \
@@ -94,11 +94,13 @@ desktop. Nothing is printed: the TUI owns the tty.
94
94
 
95
95
  ## Layout
96
96
 
97
- | Path | Responsibility |
98
- | ----------- | ------------------------------------------------------------------------------------------ |
99
- | `index.mjs` | The `duck` bin — CLI, storage resolution, and the two topologies (sidecar, in-process) |
100
- | `app.mjs` | The TUI itself — state, keys, commands, rendering |
101
- | `lib/` | Leaf helpers: wrapping, selection, rendering, export, knowledge import, uploads, prebuilds |
97
+ | Path | Responsibility |
98
+ | ----------- | ------------------------------------------------------------------------------- |
99
+ | `index.mjs` | The `duck` bin — CLI parsing; loads nothing else for `--help` and `--version` |
100
+ | `main.mjs` | The app and its first frame; imports `boot.mjs` behind it |
101
+ | `boot.mjs` | Storage resolution, the sidecar the stack comes up in, and the Client to it |
102
+ | `app.mjs` | The TUI itself — state, keys, commands, rendering |
103
+ | `lib/` | Leaf helpers: wrapping, selection, rendering, export, knowledge import, uploads |
102
104
 
103
105
  ## Splash
104
106
 
package/tui/app.mjs CHANGED
@@ -5,29 +5,23 @@
5
5
  import tui from 'bare-tui'
6
6
  import { spawn } from 'child_process'
7
7
  import fs from 'fs'
8
- import { settingsDimension, TOOLSETS } from '@qvac/harness'
8
+ import { TOOLSETS } from '@qvac/harness/lib/tools/toolsets.ts'
9
9
  import os from 'os'
10
10
  import path from 'path'
11
11
  import process from 'process'
12
12
  import {
13
13
  ASANA_MCP_CREDENTIAL_KEY,
14
- ASANA_OAUTH_STATE_KEY,
15
- connectAsana,
16
- connectGoogle,
17
- connectNotion,
18
- connectSpotify,
19
- oauthKeySpec,
20
14
  NOTION_MCP_CREDENTIAL_KEY,
21
- NOTION_OAUTH_STATE_KEY,
15
+ oauthKeySpec,
22
16
  scopedKey,
23
- SPOTIFY_CREDENTIAL_KEY,
24
- SPOTIFY_OAUTH_STATE_KEY
25
- } from '../dist-lib/lib/oauth.js'
17
+ SPOTIFY_CREDENTIAL_KEY
18
+ } from '../dist-lib/lib/oauth/keys.js'
26
19
  import {
27
20
  busyStatus,
28
21
  findPendingApproval,
29
22
  runInFlight,
30
23
  runningAgentTurn,
24
+ turnDone,
31
25
  turnsFromChunks
32
26
  } from './lib/render.mjs'
33
27
  import { exportMarkdown } from './lib/export.mjs'
@@ -524,8 +518,11 @@ export function renderTurn(turn, agentName, deviceLabels, opts = {}) {
524
518
  const label = turn.from === 'user' ? fg.cyan.render(userLabel) : fg.magenta.render(agentName)
525
519
  const lines = [`${label}:`]
526
520
  for (const segment of turn.segments) {
527
- if (segment.type === 'thinking') lines.push(fg.dim.render(` (thinking: ${segment.text})`))
528
- else if (segment.type === 'tool-call') {
521
+ if (segment.type === 'thinking') {
522
+ // a model that skips its reasoning still streams the think tags' newlines
523
+ const thought = segment.text.trim()
524
+ if (thought) lines.push(fg.dim.render(` (thinking: ${thought})`))
525
+ } else if (segment.type === 'tool-call') {
529
526
  const call = ` → ${segment.detail.name}(${JSON.stringify(segment.detail.arguments)})`
530
527
  lines.push(fg.amber.render(clampTool(call, opts)))
531
528
  } else if (segment.type === 'tool-result') {
@@ -560,7 +557,14 @@ export function renderTurn(turn, agentName, deviceLabels, opts = {}) {
560
557
  : `${name}(${JSON.stringify(args)})`
561
558
  if (status === 'pending') lines.push(fg.amber.render(` allow ${call}? [y/a/n]`))
562
559
  else lines.push(fg.dim.render(` [${status}] ${call}`))
563
- } else lines.push(fg.white.render(` ${segment.text || '…'}`))
560
+ } else {
561
+ // a model streams newlines between its tool calls; the … is the answer still to come
562
+ const text = segment.text.trim()
563
+ if (text) lines.push(fg.white.render(` ${text}`))
564
+ else if (!turnDone(turn) && segment === turn.segments.at(-1)) {
565
+ lines.push(fg.white.render(' …'))
566
+ }
567
+ }
564
568
  }
565
569
  if (turn.status === 'failed') {
566
570
  lines.push(fg.err.render(` [failed${turn.statusReason ? `: ${turn.statusReason}` : ''}]`))
@@ -1397,11 +1401,12 @@ export class ChatApp {
1397
1401
  if (field === 'size') {
1398
1402
  const match = /^(\d+)x(\d+)$/.exec(value ?? '')
1399
1403
  if (!match) return notice(USAGE)
1400
- // persist through the runtime's own clamp/snap so the stored size is the effective one
1401
- const width = settingsDimension(Number(match[1]))
1402
- const height = settingsDimension(Number(match[2]))
1403
- if (!width || !height) return notice(USAGE)
1404
1404
  return run(async () => {
1405
+ // persist through the runtime's own clamp/snap so the stored size is the effective one
1406
+ const { settingsDimension } = await import('@qvac/harness/lib/tools/generate-image.ts')
1407
+ const width = settingsDimension(Number(match[1]))
1408
+ const height = settingsDimension(Number(match[2]))
1409
+ if (!width || !height) return USAGE
1405
1410
  await engine.updateAgent({ id: agent.id, imageWidth: width, imageHeight: height })
1406
1411
  return `image size set to ${width}x${height}`
1407
1412
  })
@@ -1722,6 +1727,7 @@ export class ChatApp {
1722
1727
  return notice('set GOOGLE_OAUTH_CLIENT_ID and GOOGLE_OAUTH_CLIENT_SECRET, then retry')
1723
1728
  }
1724
1729
  return run(async () => {
1730
+ const { connectGoogle } = await import('../dist-lib/lib/oauth.js')
1725
1731
  const tokens = await connectGoogle({
1726
1732
  clientId,
1727
1733
  clientSecret,
@@ -1754,6 +1760,7 @@ export class ChatApp {
1754
1760
  return notice('set SPOTIFY_OAUTH_CLIENT_ID, then retry')
1755
1761
  }
1756
1762
  return run(async () => {
1763
+ const { connectSpotify, SPOTIFY_OAUTH_STATE_KEY } = await import('../dist-lib/lib/oauth.js')
1757
1764
  const tokens = await connectSpotify({
1758
1765
  clientId,
1759
1766
  openUrl: (url) => {
@@ -1779,6 +1786,7 @@ export class ChatApp {
1779
1786
  }
1780
1787
  if (provider === 'notion') {
1781
1788
  return run(async () => {
1789
+ const { connectNotion, NOTION_OAUTH_STATE_KEY } = await import('../dist-lib/lib/oauth.js')
1782
1790
  const tokens = await connectNotion({
1783
1791
  openUrl: (url) => {
1784
1792
  this.status = fg.dim.render(`authorize in your browser: ${url}`)
@@ -1808,6 +1816,7 @@ export class ChatApp {
1808
1816
  return notice('set ASANA_OAUTH_CLIENT_ID and ASANA_OAUTH_CLIENT_SECRET, then retry')
1809
1817
  }
1810
1818
  return run(async () => {
1819
+ const { connectAsana, ASANA_OAUTH_STATE_KEY } = await import('../dist-lib/lib/oauth.js')
1811
1820
  const tokens = await connectAsana({
1812
1821
  clientId,
1813
1822
  clientSecret,
package/tui/boot.mjs ADDED
@@ -0,0 +1,141 @@
1
+ // The engine side of the TUI: storage resolution, the log, the sidecar the
2
+ // stack comes up in, and the Client that speaks to it. main.mjs draws its
3
+ // first frame before importing this, so the ~1200 modules behind it load
4
+ // behind "starting up…" rather than in front of it.
5
+ import fs from 'bare-fs'
6
+ import os from 'bare-os'
7
+ import process from 'bare-process'
8
+ import { fileURLToPath } from 'bare-url'
9
+ import path from 'path'
10
+ import { Client } from '../dist-lib/lib/client.js'
11
+ import { Logger, toLoggerOptions } from '../dist-lib/lib/log.js'
12
+ import { configureSdkStorage } from '@qvac/harness/sdk-storage'
13
+ import { MODEL_CACHE_PATH_ENV, releaseChannel, resolveStorage } from '@qvac/harness/storage'
14
+ import sidecarRunner from 'bare-supervisor/runner/sidecar'
15
+
16
+ const skillsDir = path.dirname(
17
+ path.dirname(new URL(import.meta.resolve('@qvac/skills/skills/weather/SKILL.md')).pathname)
18
+ )
19
+ const harnessEntry = new URL(import.meta.resolve('@qvac/harness/worker/stow-entry.mjs')).pathname
20
+ const sidecarEntry = fileURLToPath(new URL('../worker/stow-entry.mjs', import.meta.url))
21
+ if (!fs.existsSync(sidecarEntry)) {
22
+ throw new Error(`assistant sidecar entry missing at ${sidecarEntry}`)
23
+ }
24
+
25
+ // Spawn worker/assistant-sidecar.mjs, the same entry the desktop app stows,
26
+ // and speak to it through a Client. Its stdout/stderr are pipes, so native
27
+ // model logs reach the logger rather than this tty.
28
+ async function startSidecar({ entry, config, logger }) {
29
+ const engine = new Client(async () => {
30
+ const { ipc, exit } = sidecarRunner(entry, [JSON.stringify(config)], logger)
31
+ // the loser resolves rather than rejects: an armed rejection outlives the
32
+ // race, and the child's own clean exit at teardown would then go unhandled
33
+ const died = exit.then((code) => `sidecar exited (${code}) before ready`)
34
+ const failure = await Promise.race([ipc.ready.then(() => null), died])
35
+ if (failure) throw new Error(failure)
36
+ return ipc
37
+ })
38
+ await engine.ready()
39
+ return {
40
+ engine,
41
+ close: () => engine.close(),
42
+ skills: async (agentId, modelName) => (await engine.skills({ agentId, modelName })).skills ?? []
43
+ }
44
+ }
45
+
46
+ // Storage precedence: --storage <dir> > QVAC_STORAGE > --temp/QVAC_TEMP=1
47
+ // throwaway > the persistent global default. Joining a mesh is /join inside the
48
+ // app — the engine takes an invite live, so it never needed to be a flag.
49
+ // Resolves once the engine answers: the connection, its teardown, and the
50
+ // timings the boot report prints (QVAC_BOOT_TIMING=1).
51
+ export default async function boot(args) {
52
+ const connectStart = Date.now()
53
+ // Only override the agent's model when QVAC_MODEL is EXPLICITLY set — otherwise
54
+ // resuming a shared mesh would silently rewrite the desktop's agent to this
55
+ // demo default. `recommendedModel` is just the device-row hint on first mint.
56
+ const modelOverride = process.env.QVAC_MODEL || null
57
+ const recommendedModel = modelOverride || 'Qwen3.5-9B-Q4_K_M'
58
+ // Default storage IS the desktop app's own release root, so the TUI resumes
59
+ // the same mesh + chats the desktop persists there. One at a time — quit the
60
+ // desktop first, the corestore is single-writer; only safe across matching
61
+ // Core/schema versions. configureSdkStorage points the SDK at this root's
62
+ // private sdk-home and the shared model cache, before the SDK's first load so
63
+ // spawned children inherit both.
64
+ const useTemp = args.temp || process.env.QVAC_TEMP === '1'
65
+ const explicitRoot =
66
+ args.storage ||
67
+ process.env.QVAC_STORAGE ||
68
+ (useTemp ? fs.mkdtempSync(path.join(os.tmpdir(), 'duck-')) : null)
69
+ const environment = process.env.QVAC_ENV || 'local'
70
+ const storage = resolveStorage(releaseChannel(environment), {
71
+ root: explicitRoot,
72
+ models: process.env[MODEL_CACHE_PATH_ENV] ?? null
73
+ })
74
+ const storagePath = storage.assistant
75
+ fs.mkdirSync(storagePath, { recursive: true })
76
+ configureSdkStorage(storage.sdk)
77
+ const deviceName = `duck-${process.pid}`
78
+ // Every run logs; only the destination differs. Both modes write
79
+ // <storage.root>/assistant.log — the same file the desktop app writes, and
80
+ // the only way to read a TUI session's engine and sidecar output, since
81
+ // anything printed outside bare-tui's renderer corrupts the frame. Headless
82
+ // owns nothing on the tty, so it streams to stdout as well.
83
+ const logFile = process.env.QVAC_LOG_FILE || path.join(storage.root, 'assistant.log')
84
+ const logger = new Logger(
85
+ toLoggerOptions({ logFile, logLevel: process.env.QVAC_LOG_LEVEL, logVerbose: args.headless })
86
+ )
87
+
88
+ const { engine, close, skills } = await startSidecar({
89
+ entry: sidecarEntry,
90
+ // worker/assistant-sidecar.mjs's own contract, verbatim: it resolves
91
+ // its storage, logger and image set from this, and spawns the
92
+ // harness child from harnessEntry. Everything it leaves out keeps
93
+ // that entry's default (llm kv-cache, hostsModelSource, eager).
94
+ config: {
95
+ environment,
96
+ // ALREADY resolved, not the overrides this host resolved from.
97
+ // worker/assistant-sidecar.mjs calls resolveStorage again, and by
98
+ // then configureSdkStorage (below) has exported SDK_HOME_ENV,
99
+ // which resolveStorage reads as the base a relative root hangs
100
+ // off: a null root would re-resolve to <root>/sdk-home/qvac/<ch>
101
+ // — a second, empty mesh beside the real one, with an empty model
102
+ // cache to match. Passing both values makes that call a
103
+ // pass-through.
104
+ storage: { root: storage.root, models: storage.sdk.models },
105
+ logFlags: {
106
+ logFile,
107
+ logLevel: process.env.QVAC_LOG_LEVEL,
108
+ logVerbose: args.headless
109
+ },
110
+ skillsDir,
111
+ harnessEntry,
112
+ // only the image keys cross: the arg is argv on a spawned process,
113
+ // readable by anything that can list processes
114
+ imageEnv: Object.fromEntries(
115
+ Object.entries(process.env).filter(([key]) => key.startsWith('QVAC_IMAGE_'))
116
+ ),
117
+ device: {
118
+ name: deviceName,
119
+ capabilityProfile: 'mid',
120
+ recommendedModelName: recommendedModel
121
+ }
122
+ },
123
+ logger
124
+ })
125
+ // The device id IS the device's public key — the raw 32-byte buffer end to
126
+ // end (schema fixed32), never a hex string.
127
+ const deviceId = (await engine.deviceInfo({})).id
128
+ const meshInvite = (await engine.meshInvite({})).invite ?? null
129
+ return {
130
+ engine,
131
+ skills,
132
+ close,
133
+ deviceId,
134
+ meshInvite,
135
+ modelName: modelOverride,
136
+ storagePath,
137
+ logFile,
138
+ deviceName,
139
+ connectMs: Date.now() - connectStart
140
+ }
141
+ }