@qvac/core 0.1.3 → 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,19 +662,43 @@ 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
703
  (or a second terminal), start `duck` and join from inside it:
659
704
 
@@ -678,17 +723,3 @@ The joiner brings no models and no agents — it finds the mesh's seeded agent,
678
723
  asks, and the _creator's_ device runs the model while both sides watch the
679
724
  same replicated stream: load progress, thinking, tokens, tool approvals
680
725
  (either side can answer), and final stats.
681
-
682
- ## Development
683
-
684
- ```sh
685
- npm test # node + bare suites
686
- npm run build:schema # regenerate spec/ from schema/ (bare)
687
- bun run duck # run the TUI (no build step)
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';
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.3",
3
+ "version": "0.1.4",
4
4
  "type": "module",
5
5
  "description": "Peer-to-peer AI across your devices",
6
6
  "exports": {
@@ -265,6 +265,7 @@
265
265
  "hyperschema-ts": "^0.1.1",
266
266
  "hyperswarm": "^4.17.0",
267
267
  "keet-identity-key": "^3.2.0",
268
+ "paparam": "^1.13.0",
268
269
  "process-top": "^1.7.1",
269
270
  "protomux": "^3.11.0",
270
271
  "protomux-wakeup": "^2.9.0",
package/tui/README.md CHANGED
@@ -73,15 +73,14 @@ for the full command set.
73
73
 
74
74
  ## Environment
75
75
 
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. `QVAC_INPROCESS=1` only |
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. Per-stage stamps exist only under `QVAC_INPROCESS=1` — the shared assistant sidecar carries no boot timer |
84
- | `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 |
85
84
 
86
85
  ```sh
87
86
  QVAC_MODEL=~/.qvac/models/3a65a2a3c6a30a47_Qwen3.5-4B-Q4_K_M.gguf \
@@ -95,11 +94,13 @@ desktop. Nothing is printed: the TUI owns the tty.
95
94
 
96
95
  ## Layout
97
96
 
98
- | Path | Responsibility |
99
- | ----------- | ------------------------------------------------------------------------------------------ |
100
- | `index.mjs` | The `duck` bin — CLI, storage resolution, and the two topologies (sidecar, in-process) |
101
- | `app.mjs` | The TUI itself — state, keys, commands, rendering |
102
- | `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 |
103
104
 
104
105
  ## Splash
105
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
+ }