@qvac/core 0.1.3 → 0.1.5

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/tui/index.mjs CHANGED
@@ -1,631 +1,48 @@
1
1
  #!/usr/bin/env bare
2
- // The duck TUI host: CLI, storage resolution, and the two topologies it can
3
- // bring the stack up in — a stowed sidecar child (the desktop shape, default)
4
- // or everything in this process (QVAC_INPROCESS=1, the only way to inject a
5
- // live harness object). See README.md for flags, env, and layout.
2
+ // The duck bin. Nothing here loads the engine, so --help and --version answer
3
+ // without paying for a module graph they never use.
6
4
  import fs from 'bare-fs'
7
- import os from 'bare-os'
8
- import process from 'bare-process'
9
- import tui from 'bare-tui'
10
- import { fileURLToPath } from 'bare-url'
11
- import { spawn } from 'child_process'
12
5
  import path from 'path'
13
- import { Harness, imageClampsFromEnv, imageModelFromEnv } from '@qvac/harness'
14
- import { createExecTool } from '@qvac/harness/lib/tools/exec.ts'
15
- import { createHttpRequestTool } from '@qvac/harness/lib/tools/http-request.ts'
16
- import { createMcpCallTool } from '@qvac/harness/lib/tools/mcp-call.ts'
17
- import { compileOperationTools } from '@qvac/harness/lib/tools/operations/compile.ts'
18
- import { createSkillTool } from '@qvac/harness/lib/tools/skill.ts'
19
- import { createWebFetchTool } from '@qvac/harness/lib/tools/web-fetch.ts'
20
- import { createWebSearchTool } from '@qvac/harness/lib/tools/web-search.ts'
21
- import {
22
- credentialAllowListFor,
23
- loadSkillCatalog,
24
- mcpReadMethods
25
- } from '@qvac/harness/lib/tools/skills/index.ts'
26
- import {
27
- harnessListModels,
28
- harnessSpeak,
29
- harnessTranscribe,
30
- QvacAssistant
31
- } from '../dist-lib/lib/assistant.js'
32
- import { Client } from '../dist-lib/lib/client.js'
33
- import { Core } from '../dist-lib/lib/core.js'
34
- import { Logger, toLoggerOptions } from '../dist-lib/lib/log.js'
35
- import { extractOfficeText } from '../dist-lib/lib/core/files/rag/extract/office-collabora.js'
36
- import { DEFAULT_RAG_MODEL } from '../dist-lib/lib/core/files/rag/models.js'
37
- import { configureSdkStorage } from '@qvac/harness/sdk-storage'
38
- import { MODEL_CACHE_PATH_ENV, releaseChannel, resolveStorage } from '@qvac/harness/storage'
39
- import {
40
- ASANA_MCP_CREDENTIAL_KEY,
41
- ASANA_OAUTH_STATE_KEY,
42
- oauthKeySpec,
43
- NOTION_MCP_CREDENTIAL_KEY,
44
- NOTION_OAUTH_STATE_KEY,
45
- resolveAsanaCredential,
46
- resolveGoogleCredential,
47
- resolveNotionCredential,
48
- resolveSpotifyCredential,
49
- SPOTIFY_CREDENTIAL_KEY,
50
- SPOTIFY_OAUTH_STATE_KEY
51
- } from '../dist-lib/lib/oauth.js'
52
- import sidecarRunner from 'bare-supervisor/runner/sidecar'
53
- import { duplexPair } from '@qvac/harness/transport'
54
- import { bootTimer, readBootTiming } from './lib/boot-timing.mjs'
55
- import { ChatApp, credKey } from './app.mjs'
56
- import { parseProjectionEnv } from './lib/projection-env.mjs'
57
-
58
- const skillsDir = path.dirname(
59
- path.dirname(new URL(import.meta.resolve('@qvac/skills/skills/weather/SKILL.md')).pathname)
6
+ import { command, description, flag, summary } from 'paparam'
7
+
8
+ const cmd = command(
9
+ 'duck',
10
+ summary('the qvac assistant in your terminal'),
11
+ description(
12
+ "Storage defaults to the desktop app's release root, so duck resumes the mesh and chats it persists there. Environment variables are documented in tui/README.md."
13
+ ),
14
+ flag('--storage|-s [dir]', 'a self-contained root, its own corestore and SDK home'),
15
+ flag('--temp', 'the same, in a throwaway dir'),
16
+ flag('--headless', 'no TUI: print the mesh invite and stream logs until ctrl+C'),
17
+ flag('--version|-v', 'versions of core, harness and the SDK')
60
18
  )
61
- const harnessEntry = new URL(import.meta.resolve('@qvac/harness/worker/stow-entry.mjs')).pathname
62
-
63
- function createCredentialStore() {
64
- let engine
65
- return {
66
- bind: (readyEngine) => {
67
- engine = readyEngine
68
- },
69
- resolve: async (key, ctx) => {
70
- if (!engine) return null
71
- const googleSpec = oauthKeySpec(key)
72
- if (googleSpec?.provider === 'google') {
73
- return resolveOAuthRecord(
74
- resolveGoogleCredential({
75
- engine,
76
- agentId: ctx?.agentId,
77
- credentialKey: key,
78
- stateKey: googleSpec.stateKey
79
- }),
80
- engine,
81
- googleSpec.stateKey,
82
- ctx?.agentId
83
- )
84
- }
85
- if (key === SPOTIFY_CREDENTIAL_KEY) {
86
- return resolveOAuthRecord(
87
- resolveSpotifyCredential({ engine, agentId: ctx?.agentId }),
88
- engine,
89
- SPOTIFY_OAUTH_STATE_KEY,
90
- ctx?.agentId
91
- )
92
- }
93
- if (key === NOTION_MCP_CREDENTIAL_KEY) {
94
- return resolveOAuthRecord(
95
- resolveNotionCredential({ engine, agentId: ctx?.agentId }),
96
- engine,
97
- NOTION_OAUTH_STATE_KEY,
98
- ctx?.agentId
99
- )
100
- }
101
- if (key === ASANA_MCP_CREDENTIAL_KEY) {
102
- return resolveOAuthRecord(
103
- resolveAsanaCredential({ engine, agentId: ctx?.agentId }),
104
- engine,
105
- ASANA_OAUTH_STATE_KEY,
106
- ctx?.agentId
107
- )
108
- }
109
- const { value } = await engine.configGet({ key: credKey(ctx?.agentId, key) })
110
- return typeof value === 'string' ? value : null
111
- }
112
- }
113
- }
114
19
 
115
- async function resolveOAuthRecord(tokenPromise, engine, stateKey, agentId) {
116
- const token = await tokenPromise
117
- if (!token) return null
118
- const { value } = await engine.configGet({ key: credKey(agentId, stateKey) })
119
- let expiresAt
120
- try {
121
- const state = typeof value === 'string' ? JSON.parse(value) : null
122
- expiresAt = typeof state?.expiresAt === 'number' ? state.expiresAt : undefined
123
- } catch {}
124
- return { token, ...(expiresAt === undefined ? {} : { expiresAt }) }
20
+ function versions() {
21
+ return [
22
+ ['@qvac/core', packageVersion(new URL('../package.json', import.meta.url).pathname)],
23
+ ['@qvac/harness', resolvedVersion('@qvac/harness')],
24
+ ['@qvac/sdk', resolvedVersion('@qvac/sdk')]
25
+ ]
26
+ .map(([name, version]) => `${name.padEnd(14)} ${version}`)
27
+ .join('\n')
125
28
  }
126
29
 
127
- const { Program } = tui
128
-
129
- // how long a lone esc waits to see whether it starts a sequence — the terminal
130
- // writes a real one in a single read, so this only has to beat human perception
131
- const ESCAPE_TIMEOUT_MS = 50
132
-
133
- // @qvac/sdk writes its own [sdk:client]/[sdk:server] logs straight to
134
- // console — bare-tui's Program owns the terminal via cursor-tracked ANSI
135
- // output, so any other writer to the same fd corrupts the redraw. Silence
136
- // console output for the TUI's lifetime; errors after it exits still print.
137
- // (llama.cpp's own native stdout logs are a separate path, not covered by
138
- // this — see assistant-harness/lib/sdk-loader.ts.)
139
- function withConsoleSuppressed(fn) {
140
- const original = {
141
- log: console.log,
142
- info: console.info,
143
- warn: console.warn,
144
- error: console.error,
145
- debug: console.debug
30
+ function resolvedVersion(specifier) {
31
+ const entry = new URL(import.meta.resolve(specifier)).pathname
32
+ for (let dir = path.dirname(entry); dir !== path.dirname(dir); dir = path.dirname(dir)) {
33
+ const manifest = path.join(dir, 'package.json')
34
+ if (fs.existsSync(manifest)) return packageVersion(manifest)
146
35
  }
147
- const noop = () => {}
148
- Object.assign(console, {
149
- log: noop,
150
- info: noop,
151
- warn: noop,
152
- error: noop,
153
- debug: noop
154
- })
155
- return fn().finally(() => Object.assign(console, original))
36
+ return 'unknown'
156
37
  }
157
38
 
158
- // llama.cpp writes some of its own init/inference logs straight to the real
159
- // stdout/stderr fd (see assistant-harness/lib/sdk-loader.ts) — that bypasses
160
- // both withConsoleSuppressed below AND bare-tui's Renderer, which only
161
- // repaints rows whose logical content changed and has no idea those rows got
162
- // clobbered by an external writer. Sending a synthetic resize forces the
163
- // same full repaint Program already does on a real terminal resize, wiping
164
- // any leaked lines. `getProgram` is a thunk because this is wired up before
165
- // Program exists.
166
- function requestRepaint(getProgram) {
167
- const program = getProgram()
168
- if (!program) return
169
- // || not ??: a size-less pty reports 0 columns, and a 0-width resize turns
170
- // the style width math into repeat(-2) — 0 means "unknown", not a size
171
- program.send({
172
- type: 'resize',
173
- width: program.output.columns || 80,
174
- height: program.output.rows || 24
175
- })
39
+ function packageVersion(manifest) {
40
+ return JSON.parse(fs.readFileSync(manifest, 'utf8')).version
176
41
  }
177
42
 
178
- // Where an in-process harness's model lifecycle lands: the log always, and the
179
- // running Program's message loop when there is one — bare-tui's documented
180
- // pattern for external code pushing messages in.
181
- function reportModel(state, logger, getProgram) {
182
- const pct = typeof state.percentage === 'number' ? ` ${state.percentage}%` : ''
183
- logger.info('model', `${state.model} ${state.status}${pct}`)
184
- const program = getProgram()
185
- if (!program) return
186
- program.send({ type: 'model', state })
187
- // 'loading'/'downloading' can't have leaked logs yet; force a repaint once
188
- // the load itself (and its native init logs) has actually happened.
189
- if (state.status === 'ready' || state.status === 'unloaded') requestRepaint(getProgram)
190
- }
191
-
192
- // ctrl+y clipboard write via the platform's own pipe-to-clipboard command —
193
- // spawned per copy, nothing printed to the tty (safe alongside bare-tui's
194
- // renderer). Candidates tried in order; the first that exits 0 wins (linux
195
- // terminals vary on wayland vs x11).
196
- function copyToClipboard(text) {
197
- const commands =
198
- process.platform === 'darwin'
199
- ? [['pbcopy', []]]
200
- : process.platform === 'win32'
201
- ? [['clip', []]]
202
- : [
203
- ['wl-copy', []],
204
- ['xclip', ['-selection', 'clipboard']]
205
- ]
206
- return new Promise((resolve, reject) => {
207
- const attempt = (i) => {
208
- if (i >= commands.length) {
209
- reject(new Error('no clipboard command available'))
210
- return
211
- }
212
- const [cmd, args] = commands[i]
213
- let child
214
- try {
215
- child = spawn(cmd, args, { stdio: ['pipe', 'ignore', 'ignore'] })
216
- } catch {
217
- attempt(i + 1)
218
- return
219
- }
220
- child.on('error', () => attempt(i + 1))
221
- child.on('exit', (code) => (code === 0 ? resolve() : attempt(i + 1)))
222
- child.stdin.write(Buffer.from(text))
223
- child.stdin.end()
224
- }
225
- attempt(0)
226
- })
227
- }
43
+ const cli = cmd.parse()
228
44
 
229
- function readClipboard() {
230
- const commands =
231
- process.platform === 'darwin'
232
- ? [['pbpaste', []]]
233
- : [
234
- ['wl-paste', ['--no-newline']],
235
- ['xclip', ['-o', '-selection', 'clipboard']]
236
- ]
237
- return new Promise((resolve, reject) => {
238
- const attempt = (i) => {
239
- if (i >= commands.length) {
240
- reject(new Error('no clipboard command available'))
241
- return
242
- }
243
- const [cmd, args] = commands[i]
244
- let child
245
- try {
246
- child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'ignore'] })
247
- } catch {
248
- attempt(i + 1)
249
- return
250
- }
251
- const out = []
252
- child.stdout.on('data', (data) => out.push(data))
253
- child.on('error', () => attempt(i + 1))
254
- child.on('exit', (code) =>
255
- code === 0 ? resolve(Buffer.concat(out).toString()) : attempt(i + 1)
256
- )
257
- }
258
- attempt(0)
259
- })
45
+ if (cli !== null) {
46
+ if (cli.flags.version) console.log(versions())
47
+ else (await import('./main.mjs')).default(cli.flags)
260
48
  }
261
-
262
- const MIME_TYPES = new Map([
263
- ['.png', 'image/png'],
264
- ['.jpg', 'image/jpeg'],
265
- ['.jpeg', 'image/jpeg'],
266
- ['.gif', 'image/gif'],
267
- ['.webp', 'image/webp'],
268
- ['.heic', 'image/heic'],
269
- ['.heif', 'image/heif'],
270
- ['.pdf', 'application/pdf'],
271
- ['.txt', 'text/plain'],
272
- ['.md', 'text/markdown'],
273
- ['.json', 'application/json']
274
- ])
275
- const MAX_ATTACHMENT_BYTES = 32 * 1024 * 1024
276
-
277
- // ctrl+v resolver: a clipboard holding a file path (or file:// URL — what
278
- // "copy" in a file manager and drag-to-terminal produce) becomes an
279
- // attachment; anything else is null and the shortcut just says so. Raw
280
- // image DATA on the clipboard has no portable tty-side accessor — copy the
281
- // file, not the pixels.
282
- async function resolvePastedFile() {
283
- const text = (await readClipboard()).trim()
284
- if (!text || text.includes('\n')) return null
285
- const file = expandFilePath(text)
286
- let stat
287
- try {
288
- stat = fs.statSync(file)
289
- } catch {
290
- return null
291
- }
292
- if (!stat.isFile()) return null
293
- return fileToAttachment(file, stat)
294
- }
295
-
296
- // `/attach` resolver: a named path -> attachment; throws on a bad path.
297
- function resolveFileAttachment(pathString) {
298
- return fileToAttachment(expandFilePath(pathString))
299
- }
300
-
301
- function expandFilePath(text) {
302
- const file = text.startsWith('file://') ? decodeURI(text.slice('file://'.length)) : text
303
- return file.startsWith('~/') ? path.join(os.homedir(), file.slice(2)) : file
304
- }
305
-
306
- function fileToAttachment(file, stat = fs.statSync(file)) {
307
- if (!stat.isFile()) throw new Error('not a regular file')
308
- if (stat.size > MAX_ATTACHMENT_BYTES) throw new Error('file too large (32MB cap)')
309
- return {
310
- fileName: path.basename(file),
311
- mimeType: MIME_TYPES.get(path.extname(file).toLowerCase()) ?? 'application/octet-stream',
312
- data: fs.readFileSync(file)
313
- }
314
- }
315
-
316
- // The QVAC_INPROCESS=1 topology: Core + the harness + the QvacAssistant all
317
- // live in THIS process, so the harness — a live JS object, which cannot cross
318
- // the sidecar's process boundary as a spawn arg — can be injected directly.
319
- // llama.cpp's native logs then share the TUI's tty, the reason for
320
- // withConsoleSuppressed/requestRepaint above.
321
- async function startInProcess({ storagePath, deviceName, modelName, logger, onModel }) {
322
- const timer = bootTimer(storagePath, 'in-process')
323
- timer.stamp('entry')
324
- const imageModel = imageModelFromEnv(
325
- process.env,
326
- () =>
327
- console.error(
328
- 'QVAC_IMAGE_MODEL is a catalog choice — ignoring QVAC_IMAGE_LLM/QVAC_IMAGE_VAE/QVAC_IMAGE_PREDICTION'
329
- ),
330
- () =>
331
- console.error(
332
- 'QVAC_IMAGE_PREDICTION needs QVAC_IMAGE_LLM and QVAC_IMAGE_VAE (a FLUX set) — ignoring it'
333
- )
334
- )
335
- const credentials = createCredentialStore()
336
- const skillCatalog = await loadSkillCatalog(skillsDir)
337
- timer.stamp('skills-catalog')
338
- const httpRequestTool = createHttpRequestTool({
339
- credentialStore: credentials.resolve,
340
- credentialAllowList: credentialAllowListFor(skillCatalog)
341
- })
342
- const mcpCallTool = createMcpCallTool({
343
- credentialStore: credentials.resolve,
344
- credentialAllowList: credentialAllowListFor(skillCatalog),
345
- readMethods: mcpReadMethods(skillCatalog)
346
- })
347
- const harness = new Harness({
348
- tools: [
349
- httpRequestTool,
350
- createExecTool({ skillsDir }),
351
- mcpCallTool,
352
- // typed tools compiled from each skill's operations.json, as the sidecar does —
353
- // without them a skill that grants sheets_create or notion_create_page is unsupported here
354
- ...compileOperationTools(skillCatalog, { httpRequestTool, mcpCallTool }),
355
- createSkillTool({ skillsDir }),
356
- createWebSearchTool(),
357
- createWebFetchTool()
358
- ],
359
- skillsDir,
360
- credentialStore: credentials.resolve,
361
- projectionModel: parseProjectionEnv(process.env.QVAC_MMPROJ),
362
- imageModel,
363
- imageClamps: imageClampsFromEnv(process.env)
364
- })
365
- await harness.ready()
366
- timer.stamp('harness-ready')
367
- const [serverStream, clientStream] = duplexPair()
368
- // `device` matters: the birth op registers this device's @qvac/devices row
369
- // (keyed by the device's public key), which the chunk/approval writer
370
- // guards resolve against — without it, every decision is silently dropped.
371
- const core = new Core(() => serverStream, {
372
- logger,
373
- storagePath,
374
- device: { name: deviceName, capabilityProfile: 'mid', recommendedModelName: modelName },
375
- listModels: harnessListModels(harness),
376
- transcribe: harnessTranscribe(harness),
377
- speak: harnessSpeak(harness),
378
- embedder: {
379
- model: DEFAULT_RAG_MODEL,
380
- embed: ({ texts, signal }) => harness.embed({ model: DEFAULT_RAG_MODEL, texts, signal })
381
- },
382
- extractors: { office: extractOfficeText }
383
- })
384
- await core.ready()
385
- timer.stamp('core-ready')
386
- const engine = new Client(() => clientStream)
387
- await engine.ready()
388
- credentials.bind(engine)
389
- const assistant = new QvacAssistant(engine, harness)
390
- await assistant.ready()
391
- timer.stamp('sup-ready')
392
- const offDiagnostics = core.registerDiagnostics(() => assistant.diagnosticsSlice())
393
- // The harness's model lifecycle is a plain EventEmitter event (see Harness's
394
- // own doc comment); the host decides where it lands — the TUI's message loop,
395
- // or a log line.
396
- harness.on('model', onModel)
397
- return {
398
- engine,
399
- skills: (agentId, modelName) => assistant.skills(agentId, modelName),
400
- close: async () => {
401
- offDiagnostics()
402
- await assistant.close()
403
- await engine.close()
404
- await core.close()
405
- await harness.close()
406
- }
407
- }
408
- }
409
-
410
- // The default topology: spawn worker/assistant-sidecar.mjs, the same entry the
411
- // desktop app stows, and speak to it through a Client. Its stdout/stderr are
412
- // pipes, so native model logs reach the logger rather than this tty.
413
- async function startSidecar({ config, logger }) {
414
- const entry = fileURLToPath(new URL('../worker/stow-entry.mjs', import.meta.url))
415
- if (!fs.existsSync(entry)) throw new Error(`assistant sidecar entry missing at ${entry}`)
416
- const engine = new Client(async () => {
417
- const { ipc, exit } = sidecarRunner(entry, [JSON.stringify(config)], logger)
418
- // the loser resolves rather than rejects: an armed rejection outlives the
419
- // race, and the child's own clean exit at teardown would then go unhandled
420
- const died = exit.then((code) => `sidecar exited (${code}) before ready`)
421
- const failure = await Promise.race([ipc.ready.then(() => null), died])
422
- if (failure) throw new Error(failure)
423
- return ipc
424
- })
425
- await engine.ready()
426
- return {
427
- engine,
428
- close: () => engine.close(),
429
- skills: async (agentId, modelName) => (await engine.skills({ agentId, modelName })).skills ?? []
430
- }
431
- }
432
-
433
- // CLI: `duck [--storage <dir>] [--temp] [--headless]`. Flags may appear in any
434
- // order. Precedence for the storage dir: --storage <dir> > QVAC_STORAGE env >
435
- // --temp/QVAC_TEMP=1 throwaway > the persistent global default (below).
436
- // Joining a mesh is /join inside the app, not a boot argument — the engine
437
- // takes an invite live (engine.joinMesh), so it never needed to be one.
438
- function parseArgs(argv) {
439
- let storageDir = null
440
- let temp = false
441
- let headless = false
442
- for (let i = 0; i < argv.length; i++) {
443
- const arg = argv[i]
444
- if (arg === '--temp') temp = true
445
- else if (arg === '--headless') headless = true
446
- else if (arg === '--storage') storageDir = argv[++i] ?? null
447
- else if (arg.startsWith('--storage=')) storageDir = arg.slice('--storage='.length)
448
- }
449
- return { storageDir, temp, headless }
450
- }
451
-
452
- // Boot-timing report (QVAC_BOOT_TIMING=1): per-stage stamps from the
453
- // sidecar/in-process bring-up (see lib/boot-timing.mjs), plus the host's own
454
- // connect wall time. The TUI calls this only once it has released the tty, so
455
- // it never fights bare-tui's live render.
456
- function printBootTiming(storagePath, connectMs) {
457
- if (process.env.QVAC_BOOT_TIMING !== '1') return
458
- const lines = [
459
- connectMs === null ? null : `host: "starting up…" (connect) = ${connectMs}ms`,
460
- readBootTiming(storagePath)
461
- ].filter(Boolean)
462
- if (lines.length) console.log(`\nboot timing:\n${lines.join('\n')}`)
463
- }
464
-
465
- async function main() {
466
- const args = parseArgs(process.argv.slice(2))
467
- // Only override the agent's model when QVAC_MODEL is EXPLICITLY set — otherwise
468
- // resuming a shared mesh would silently rewrite the desktop's agent to this
469
- // demo default. `recommendedModel` is just the device-row hint on first mint.
470
- const modelOverride = process.env.QVAC_MODEL || null
471
- const recommendedModel = modelOverride || 'Qwen3.5-9B-Q4_K_M'
472
- // Default storage IS the desktop app's own release root, so the TUI resumes
473
- // the same mesh + chats the desktop persists there. One at a time — quit the
474
- // desktop first, the corestore is single-writer; only safe across matching
475
- // Core/schema versions. configureSdkStorage points the SDK at this root's
476
- // private sdk-home and the shared model cache, before the SDK's first load so
477
- // spawned children inherit both.
478
- const useTemp = args.temp || process.env.QVAC_TEMP === '1'
479
- const explicitRoot =
480
- args.storageDir ||
481
- process.env.QVAC_STORAGE ||
482
- (useTemp ? fs.mkdtempSync(path.join(os.tmpdir(), 'duck-')) : null)
483
- const environment = process.env.QVAC_ENV || 'local'
484
- const storage = resolveStorage(releaseChannel(environment), {
485
- root: explicitRoot,
486
- models: process.env[MODEL_CACHE_PATH_ENV] ?? null
487
- })
488
- const storagePath = storage.assistant
489
- fs.mkdirSync(storagePath, { recursive: true })
490
- configureSdkStorage(storage.sdk)
491
- let program
492
- // reassigned to the engine's close() once connect resolves; noop until then
493
- let teardown = () => {}
494
- const deviceName = `duck-${process.pid}`
495
- // Every run logs; only the destination differs. Both modes write
496
- // <storage.root>/assistant.log — the same file the desktop app writes, and
497
- // the only way to read a TUI session's engine and sidecar output, since
498
- // anything printed outside bare-tui's renderer corrupts the frame. Headless
499
- // owns nothing on the tty, so it streams to stdout as well.
500
- const logFile = process.env.QVAC_LOG_FILE || path.join(storage.root, 'assistant.log')
501
- const logger = new Logger(
502
- toLoggerOptions({ logFile, logLevel: process.env.QVAC_LOG_LEVEL, logVerbose: args.headless })
503
- )
504
-
505
- // The whole engine bring-up runs INSIDE the TUI (ChatApp calls this from
506
- // init()), so the terminal shows the app's own "starting up…" frame instead
507
- // of a pre-render status line — console is suppressed for run()'s lifetime
508
- // below, so the SDK's boot logs can't corrupt the render. Sidecar is the
509
- // default (desktop topology); QVAC_INPROCESS=1 keeps everything in this
510
- // process. The app never mints an agent: a fresh mesh seeds its default at
511
- // birth (contract/seed-defaults.ts) and a joiner waits for it to replicate;
512
- // the provider applies the QVAC_MODEL override only when one is set (below).
513
- // Wall time of the whole "starting up…" frame (connect start → resolve), for
514
- // the boot-timing report printed after the TUI exits (QVAC_BOOT_TIMING=1).
515
- let connectMs = null
516
- const connect = async () => {
517
- const connectStart = Date.now()
518
- const { engine, close, skills } =
519
- process.env.QVAC_INPROCESS === '1'
520
- ? await startInProcess({
521
- storagePath,
522
- deviceName,
523
- modelName: recommendedModel,
524
- logger,
525
- onModel: (state) => reportModel(state, logger, () => program)
526
- })
527
- : await startSidecar({
528
- // worker/assistant-sidecar.mjs's own contract, verbatim: it resolves
529
- // its storage, logger and image set from this, and spawns the
530
- // harness child from harnessEntry. Everything it leaves out keeps
531
- // that entry's default (llm kv-cache, hostsModelSource, eager).
532
- config: {
533
- environment,
534
- // ALREADY resolved, not the overrides this host resolved from.
535
- // worker/assistant-sidecar.mjs calls resolveStorage again, and by
536
- // then configureSdkStorage (below) has exported SDK_HOME_ENV,
537
- // which resolveStorage reads as the base a relative root hangs
538
- // off: a null root would re-resolve to <root>/sdk-home/qvac/<ch>
539
- // — a second, empty mesh beside the real one, with an empty model
540
- // cache to match. Passing both values makes that call a
541
- // pass-through.
542
- storage: { root: storage.root, models: storage.sdk.models },
543
- logFlags: {
544
- logFile,
545
- logLevel: process.env.QVAC_LOG_LEVEL,
546
- logVerbose: args.headless
547
- },
548
- skillsDir,
549
- harnessEntry,
550
- // only the image keys cross: the arg is argv on a spawned process,
551
- // readable by anything that can list processes
552
- imageEnv: Object.fromEntries(
553
- Object.entries(process.env).filter(([key]) => key.startsWith('QVAC_IMAGE_'))
554
- ),
555
- device: {
556
- name: deviceName,
557
- capabilityProfile: 'mid',
558
- recommendedModelName: recommendedModel
559
- }
560
- },
561
- logger
562
- })
563
- teardown = close
564
- // The device id IS the device's public key — the raw 32-byte buffer end to
565
- // end (schema fixed32), never a hex string.
566
- const deviceId = (await engine.deviceInfo({})).id
567
- const meshInvite = (await engine.meshInvite({})).invite ?? null
568
- connectMs = Date.now() - connectStart
569
- return { engine, skills, deviceId, meshInvite, modelName: modelOverride }
570
- }
571
-
572
- // Headless: the same stack with no TUI at all. Bring the engine up, print the
573
- // invite another instance joins with, then park — the engine's own handles
574
- // hold the loop open and its logs stream to stdout until a signal arrives.
575
- if (args.headless) {
576
- // armed before connect, not after: a ctrl+C partway through a first-run
577
- // model download still unwinds cleanly (teardown is a noop until then)
578
- const shutdown = async () => {
579
- await teardown()
580
- Bare.exit(0)
581
- }
582
- process.on('SIGINT', () => void shutdown())
583
- process.on('SIGTERM', () => void shutdown())
584
- const { deviceId, meshInvite } = await connect()
585
- console.log(`storage ${storagePath}`)
586
- console.log(`log ${logFile}`)
587
- console.log(`device ${deviceName} ${deviceId.toString('hex')}`)
588
- console.log(`invite ${meshInvite ?? '(none — mesh not writable)'}`)
589
- printBootTiming(storagePath, connectMs)
590
- return
591
- }
592
-
593
- const app = new ChatApp({
594
- connect,
595
- requestRepaint: () => requestRepaint(() => program),
596
- copyToClipboard,
597
- resolvePastedFile,
598
- resolveFileAttachment
599
- })
600
- // wheel + drag reports (1002+1006) instead of the terminal turning the wheel
601
- // into ↑/↓ keys: the transcript scrolls, and it selects its own text (the
602
- // terminal can't while tracking is on) — see ChatApp._select
603
- program = new Program(app, { mouse: 'drag' })
604
- // bracketed paste: a paste arrives as one paste-start/…/paste-end block
605
- // instead of per-line key events submitting each pasted line
606
- program.output.write('\x1b[?2004h')
607
- try {
608
- await withConsoleSuppressed(() => {
609
- const running = program.run()
610
- // run() builds the key decoder synchronously, and bare-tui gives no way to
611
- // configure it: a lone esc waits out its 500ms sequence timeout, which is
612
- // the visible beat before an overlay closes.
613
- if (program._decoder) program._decoder._escapeDelay = ESCAPE_TIMEOUT_MS
614
- return running
615
- })
616
- } finally {
617
- program.output.write('\x1b[?2004l')
618
- }
619
-
620
- await teardown()
621
- printBootTiming(storagePath, connectMs)
622
- // Quitting is the goal — don't idle the terminal waiting for the child to
623
- // unwind a blocking native call (e.g. a model still loading) before its loop
624
- // drains; close() has already torn the sidecar down.
625
- Bare.exit(0)
626
- }
627
-
628
- main().catch((err) => {
629
- console.error(err)
630
- Bare.exit(1)
631
- })
@@ -102,6 +102,10 @@ export function runningAgentTurn(turns) {
102
102
 
103
103
  const TERMINAL_RUN_STATES = new Set(['completed', 'failed', 'canceled'])
104
104
 
105
+ export function turnDone(turn) {
106
+ return TERMINAL_RUN_STATES.has(turn.status)
107
+ }
108
+
105
109
  export function runInFlight(turns) {
106
110
  for (let i = turns.length - 1; i >= 0; i--) {
107
111
  if (turns[i].from !== 'agent') continue