@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.
@@ -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
package/tui/main.mjs ADDED
@@ -0,0 +1,284 @@
1
+ // The TUI itself. index.mjs parses the CLI and imports this only when there is
2
+ // something to run; this draws the first frame and then imports boot.mjs, the
3
+ // engine side, behind it.
4
+ import fs from 'bare-fs'
5
+ import os from 'bare-os'
6
+ import process from 'bare-process'
7
+ import tui from 'bare-tui'
8
+ import { spawn } from 'child_process'
9
+ import path from 'path'
10
+ import { readBootTiming } from './lib/boot-timing.mjs'
11
+ import { ChatApp } from './app.mjs'
12
+
13
+ const { Program } = tui
14
+
15
+ // how long a lone esc waits to see whether it starts a sequence — the terminal
16
+ // writes a real one in a single read, so this only has to beat human perception
17
+ const ESCAPE_TIMEOUT_MS = 50
18
+
19
+ // @qvac/sdk writes its own [sdk:client]/[sdk:server] logs straight to
20
+ // console — bare-tui's Program owns the terminal via cursor-tracked ANSI
21
+ // output, so any other writer to the same fd corrupts the redraw. Silence
22
+ // console output for the TUI's lifetime; errors after it exits still print.
23
+ // (llama.cpp's own native stdout logs are a separate path, not covered by
24
+ // this — see assistant-harness/lib/sdk-loader.ts.)
25
+ function withConsoleSuppressed(fn) {
26
+ const original = {
27
+ log: console.log,
28
+ info: console.info,
29
+ warn: console.warn,
30
+ error: console.error,
31
+ debug: console.debug
32
+ }
33
+ const noop = () => {}
34
+ Object.assign(console, {
35
+ log: noop,
36
+ info: noop,
37
+ warn: noop,
38
+ error: noop,
39
+ debug: noop
40
+ })
41
+ return fn().finally(() => Object.assign(console, original))
42
+ }
43
+
44
+ // llama.cpp writes some of its own init/inference logs straight to the real
45
+ // stdout/stderr fd (see assistant-harness/lib/sdk-loader.ts) — that bypasses
46
+ // both withConsoleSuppressed below AND bare-tui's Renderer, which only
47
+ // repaints rows whose logical content changed and has no idea those rows got
48
+ // clobbered by an external writer. Sending a synthetic resize forces the
49
+ // same full repaint Program already does on a real terminal resize, wiping
50
+ // any leaked lines. `getProgram` is a thunk because this is wired up before
51
+ // Program exists.
52
+ function requestRepaint(getProgram) {
53
+ const program = getProgram()
54
+ if (!program) return
55
+ // || not ??: a size-less pty reports 0 columns, and a 0-width resize turns
56
+ // the style width math into repeat(-2) — 0 means "unknown", not a size
57
+ program.send({
58
+ type: 'resize',
59
+ width: program.output.columns || 80,
60
+ height: program.output.rows || 24
61
+ })
62
+ }
63
+
64
+ // ctrl+y clipboard write via the platform's own pipe-to-clipboard command —
65
+ // spawned per copy, nothing printed to the tty (safe alongside bare-tui's
66
+ // renderer). Candidates tried in order; the first that exits 0 wins (linux
67
+ // terminals vary on wayland vs x11).
68
+ function copyToClipboard(text) {
69
+ const commands =
70
+ process.platform === 'darwin'
71
+ ? [['pbcopy', []]]
72
+ : process.platform === 'win32'
73
+ ? [['clip', []]]
74
+ : [
75
+ ['wl-copy', []],
76
+ ['xclip', ['-selection', 'clipboard']]
77
+ ]
78
+ return new Promise((resolve, reject) => {
79
+ const attempt = (i) => {
80
+ if (i >= commands.length) {
81
+ reject(new Error('no clipboard command available'))
82
+ return
83
+ }
84
+ const [cmd, args] = commands[i]
85
+ let child
86
+ try {
87
+ child = spawn(cmd, args, { stdio: ['pipe', 'ignore', 'ignore'] })
88
+ } catch {
89
+ attempt(i + 1)
90
+ return
91
+ }
92
+ child.on('error', () => attempt(i + 1))
93
+ child.on('exit', (code) => (code === 0 ? resolve() : attempt(i + 1)))
94
+ child.stdin.write(Buffer.from(text))
95
+ child.stdin.end()
96
+ }
97
+ attempt(0)
98
+ })
99
+ }
100
+
101
+ function readClipboard() {
102
+ const commands =
103
+ process.platform === 'darwin'
104
+ ? [['pbpaste', []]]
105
+ : [
106
+ ['wl-paste', ['--no-newline']],
107
+ ['xclip', ['-o', '-selection', 'clipboard']]
108
+ ]
109
+ return new Promise((resolve, reject) => {
110
+ const attempt = (i) => {
111
+ if (i >= commands.length) {
112
+ reject(new Error('no clipboard command available'))
113
+ return
114
+ }
115
+ const [cmd, args] = commands[i]
116
+ let child
117
+ try {
118
+ child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'ignore'] })
119
+ } catch {
120
+ attempt(i + 1)
121
+ return
122
+ }
123
+ const out = []
124
+ child.stdout.on('data', (data) => out.push(data))
125
+ child.on('error', () => attempt(i + 1))
126
+ child.on('exit', (code) =>
127
+ code === 0 ? resolve(Buffer.concat(out).toString()) : attempt(i + 1)
128
+ )
129
+ }
130
+ attempt(0)
131
+ })
132
+ }
133
+
134
+ const MIME_TYPES = new Map([
135
+ ['.png', 'image/png'],
136
+ ['.jpg', 'image/jpeg'],
137
+ ['.jpeg', 'image/jpeg'],
138
+ ['.gif', 'image/gif'],
139
+ ['.webp', 'image/webp'],
140
+ ['.heic', 'image/heic'],
141
+ ['.heif', 'image/heif'],
142
+ ['.pdf', 'application/pdf'],
143
+ ['.txt', 'text/plain'],
144
+ ['.md', 'text/markdown'],
145
+ ['.json', 'application/json']
146
+ ])
147
+ const MAX_ATTACHMENT_BYTES = 32 * 1024 * 1024
148
+
149
+ // ctrl+v resolver: a clipboard holding a file path (or file:// URL — what
150
+ // "copy" in a file manager and drag-to-terminal produce) becomes an
151
+ // attachment; anything else is null and the shortcut just says so. Raw
152
+ // image DATA on the clipboard has no portable tty-side accessor — copy the
153
+ // file, not the pixels.
154
+ async function resolvePastedFile() {
155
+ const text = (await readClipboard()).trim()
156
+ if (!text || text.includes('\n')) return null
157
+ const file = expandFilePath(text)
158
+ let stat
159
+ try {
160
+ stat = fs.statSync(file)
161
+ } catch {
162
+ return null
163
+ }
164
+ if (!stat.isFile()) return null
165
+ return fileToAttachment(file, stat)
166
+ }
167
+
168
+ // `/attach` resolver: a named path -> attachment; throws on a bad path.
169
+ function resolveFileAttachment(pathString) {
170
+ return fileToAttachment(expandFilePath(pathString))
171
+ }
172
+
173
+ function expandFilePath(text) {
174
+ const file = text.startsWith('file://') ? decodeURI(text.slice('file://'.length)) : text
175
+ return file.startsWith('~/') ? path.join(os.homedir(), file.slice(2)) : file
176
+ }
177
+
178
+ function fileToAttachment(file, stat = fs.statSync(file)) {
179
+ if (!stat.isFile()) throw new Error('not a regular file')
180
+ if (stat.size > MAX_ATTACHMENT_BYTES) throw new Error('file too large (32MB cap)')
181
+ return {
182
+ fileName: path.basename(file),
183
+ mimeType: MIME_TYPES.get(path.extname(file).toLowerCase()) ?? 'application/octet-stream',
184
+ data: fs.readFileSync(file)
185
+ }
186
+ }
187
+
188
+ // Storage precedence: --storage <dir> > QVAC_STORAGE > --temp/QVAC_TEMP=1
189
+ // throwaway > the persistent global default. Joining a mesh is /join inside the
190
+ // app — the engine takes an invite live, so it never needed to be a flag.
191
+ // Boot-timing report (QVAC_BOOT_TIMING=1): per-stage stamps from the sidecar
192
+ // bring-up (see lib/boot-timing.mjs), plus the host's own connect wall time.
193
+ // The TUI calls this only once it has released the tty, so it never fights
194
+ // bare-tui's live render.
195
+ function printBootTiming(booted) {
196
+ if (process.env.QVAC_BOOT_TIMING !== '1' || !booted) return
197
+ const lines = [
198
+ `host: "starting up…" (connect) = ${booted.connectMs}ms`,
199
+ readBootTiming(booted.storagePath)
200
+ ].filter(Boolean)
201
+ console.log(`\nboot timing:\n${lines.join('\n')}`)
202
+ }
203
+
204
+ export default function main(args) {
205
+ run(args).catch((err) => {
206
+ console.error(err)
207
+ Bare.exit(1)
208
+ })
209
+ }
210
+
211
+ async function run(args) {
212
+ let program
213
+ // the engine side, once it is up: its teardown, and what the boot report prints
214
+ let booted = null
215
+ // The whole engine bring-up runs INSIDE the TUI (ChatApp calls this from
216
+ // init()), so the terminal shows the app's own "starting up…" frame instead
217
+ // of a pre-render status line — console is suppressed for run()'s lifetime
218
+ // below, so the SDK's boot logs can't corrupt the render. boot.mjs and the
219
+ // ~1200 modules behind it are imported here, after that frame, not before.
220
+ // The app never mints an agent: a fresh mesh seeds its default at birth
221
+ // (contract/seed-defaults.ts) and a joiner waits for it to replicate; the
222
+ // provider applies the QVAC_MODEL override only when one is set.
223
+ const connect = async () => {
224
+ const { default: boot } = await import('./boot.mjs')
225
+ booted = await boot(args)
226
+ const { engine, skills, deviceId, meshInvite, modelName } = booted
227
+ return { engine, skills, deviceId, meshInvite, modelName }
228
+ }
229
+
230
+ // Headless: the same stack with no TUI at all. Bring the engine up, print the
231
+ // invite another instance joins with, then park — the engine's own handles
232
+ // hold the loop open and its logs stream to stdout until a signal arrives.
233
+ if (args.headless) {
234
+ // armed before connect, not after: a ctrl+C partway through a first-run
235
+ // model download still unwinds cleanly (nothing to tear down until then)
236
+ const shutdown = async () => {
237
+ await booted?.close()
238
+ Bare.exit(0)
239
+ }
240
+ process.on('SIGINT', () => void shutdown())
241
+ process.on('SIGTERM', () => void shutdown())
242
+ const { deviceId, meshInvite } = await connect()
243
+ console.log(`storage ${booted.storagePath}`)
244
+ console.log(`log ${booted.logFile}`)
245
+ console.log(`device ${booted.deviceName} ${deviceId.toString('hex')}`)
246
+ console.log(`invite ${meshInvite ?? '(none — mesh not writable)'}`)
247
+ printBootTiming(booted)
248
+ return
249
+ }
250
+
251
+ const app = new ChatApp({
252
+ connect,
253
+ requestRepaint: () => requestRepaint(() => program),
254
+ copyToClipboard,
255
+ resolvePastedFile,
256
+ resolveFileAttachment
257
+ })
258
+ // wheel + drag reports (1002+1006) instead of the terminal turning the wheel
259
+ // into ↑/↓ keys: the transcript scrolls, and it selects its own text (the
260
+ // terminal can't while tracking is on) — see ChatApp._select
261
+ program = new Program(app, { mouse: 'drag' })
262
+ // bracketed paste: a paste arrives as one paste-start/…/paste-end block
263
+ // instead of per-line key events submitting each pasted line
264
+ program.output.write('\x1b[?2004h')
265
+ try {
266
+ await withConsoleSuppressed(() => {
267
+ const running = program.run()
268
+ // run() builds the key decoder synchronously, and bare-tui gives no way to
269
+ // configure it: a lone esc waits out its 500ms sequence timeout, which is
270
+ // the visible beat before an overlay closes.
271
+ if (program._decoder) program._decoder._escapeDelay = ESCAPE_TIMEOUT_MS
272
+ return running
273
+ })
274
+ } finally {
275
+ program.output.write('\x1b[?2004l')
276
+ }
277
+
278
+ await booted?.close()
279
+ printBootTiming(booted)
280
+ // Quitting is the goal — don't idle the terminal waiting for the child to
281
+ // unwind a blocking native call (e.g. a model still loading) before its loop
282
+ // drains; close() has already torn the sidecar down.
283
+ Bare.exit(0)
284
+ }
@@ -0,0 +1,138 @@
1
+ /* global Bare */
2
+ import Supervisor from 'bare-supervisor'
3
+ import stowEntry from 'bare-supervisor/entry'
4
+ import sidecarRunner from 'bare-supervisor/runner/sidecar'
5
+ import { Core, assistantChild, clientSessions } from '../dist-lib/index.js'
6
+ import { DEFAULT_RAG_MODEL } from '../dist-lib/lib/core/files/rag/models.js'
7
+ import { Logger, toLoggerOptions } from '../dist-lib/lib/log.js'
8
+ import { releaseChannel, resolveStorage } from '@qvac/harness/storage'
9
+ import {
10
+ DEFAULT_IMAGE_MODEL_CHOICE,
11
+ DEFAULT_MUSIC_MODEL_CHOICE,
12
+ harnessChild,
13
+ imageClampsFromEnv,
14
+ imageModelFor,
15
+ imageModelFromEnv
16
+ } from '@qvac/harness'
17
+ import { startCredentialPusher } from '../dist-lib/lib/credential-pusher.js'
18
+
19
+ const DEFAULT_KV_CACHE = { kvCacheK: 'q8_0', kvCacheV: 'q8_0' }
20
+
21
+ export default stowEntry((ipc) => {
22
+ const {
23
+ logFlags = {},
24
+ environment = 'local',
25
+ storage: storageOverrides = {},
26
+ skillsDir = undefined,
27
+ wheelsDir = undefined,
28
+ imageEnv = {},
29
+ harnessEntry,
30
+ bootstrapNodes: bootstrapJson = undefined,
31
+ device,
32
+ app = undefined,
33
+ llm = DEFAULT_KV_CACHE,
34
+ hostsModelSource = true,
35
+ eager = true
36
+ } = JSON.parse(Bare.argv[2] || '{}')
37
+
38
+ const bootstrapNodes = bootstrapJson ? JSON.parse(bootstrapJson) : undefined
39
+
40
+ const channel = releaseChannel(environment)
41
+ const storage = resolveStorage(channel, storageOverrides)
42
+ const storagePath = storage.assistant
43
+
44
+ const logFile = logFlags.logFile || `${storage.root}/assistant.log`
45
+ const logger = new Logger(toLoggerOptions({ ...logFlags, logFile }))
46
+
47
+ // Hosts install the image tools by default: without an imageModel the harness
48
+ // registers no generate_image/edit_image, and the image-generation skill then
49
+ // resolves to `unsupported` ("Not available on this device"). Env only picks a
50
+ // different set; per-agent imageModelChoice still overrides at generation time.
51
+ const imageModel =
52
+ imageModelFromEnv(
53
+ imageEnv,
54
+ () =>
55
+ logger.warn(
56
+ 'assistant',
57
+ 'QVAC_IMAGE_MODEL is a catalog choice — ignoring QVAC_IMAGE_LLM/QVAC_IMAGE_VAE/QVAC_IMAGE_PREDICTION'
58
+ ),
59
+ () =>
60
+ logger.warn(
61
+ 'assistant',
62
+ 'QVAC_IMAGE_PREDICTION needs QVAC_IMAGE_LLM and QVAC_IMAGE_VAE (a FLUX set) — ignoring it'
63
+ )
64
+ ) ?? imageModelFor(DEFAULT_IMAGE_MODEL_CHOICE)
65
+ const imageClamps = imageClampsFromEnv(imageEnv)
66
+
67
+ // Same for music: without a musicModel the harness registers no generate_music
68
+ // and the music-generation skill resolves to "Not available on this device".
69
+ // A per-agent choice from the generate_music tool-config still overrides at
70
+ // generation time; the harness resolves the choice string to its ACE-Step stages.
71
+ const musicModel = DEFAULT_MUSIC_MODEL_CHOICE
72
+
73
+ const sup = new Supervisor()
74
+ const sessions = clientSessions(ipc)
75
+ const core = new Core(() => sessions.current, {
76
+ logger,
77
+ storagePath,
78
+ device,
79
+ bootstrapNodes,
80
+ app: app ? { ...app, channel } : undefined,
81
+ hostsModelSource,
82
+ apiLifecycle: {
83
+ suspend: () => sup.suspend(),
84
+ resume: () => sup.resume()
85
+ }
86
+ })
87
+
88
+ // the host resets the session when its renderer reloads: same process, same Core, a fresh
89
+ // client over the one pipe
90
+ ipc.on('session-reset', () => {
91
+ core
92
+ .connect(sessions.reset())
93
+ .catch((err) => logger.warn('assistant-sidecar', 'session reset failed', err?.message))
94
+ })
95
+
96
+ sup.add('core', {
97
+ start: () => core,
98
+ presuspend: (handle) => handle.presuspend(),
99
+ suspend: (handle) => handle.suspend(),
100
+ wakeup: (handle) => handle.wakeup(),
101
+ resume: (handle) => handle.resume()
102
+ })
103
+
104
+ sup.add(
105
+ 'assistant',
106
+ assistantChild({
107
+ // knowledge indexing volunteers this device; rebuilt against each harness incarnation
108
+ embedder: (harness) => ({
109
+ model: DEFAULT_RAG_MODEL,
110
+ embed: ({ texts, signal }) => harness.embed({ model: DEFAULT_RAG_MODEL, texts, signal })
111
+ }),
112
+ harness: harnessChild(harnessEntry, {
113
+ runner: sidecarRunner,
114
+ skillsDir,
115
+ wheelsDir,
116
+ sdkStorage: storage.sdk,
117
+ imageModel,
118
+ imageClamps,
119
+ musicModel,
120
+ llm: { ...llm },
121
+ logger,
122
+ eager
123
+ }),
124
+ onHarness: (harness, { engine }) => startCredentialPusher(harness, engine, logger),
125
+ logger
126
+ })
127
+ )
128
+
129
+ for (const event of ['child-died', 'child-restarting', 'stall']) {
130
+ sup.on(event, (payload) => logger.warn('assistant-sidecar', event, payload))
131
+ }
132
+ sup.on('gave-up', ({ name, error }) =>
133
+ logger.error('assistant-sidecar', `${name} gave up`, error?.message)
134
+ )
135
+ sup.on('power', (payload) => logger.info('assistant-sidecar', 'power', payload))
136
+
137
+ return sup
138
+ })
@@ -0,0 +1,51 @@
1
+ /* global Bare */
2
+ // bare-stow's generated bundle shim (lib/shim.js) as a plain file, so the
3
+ // sidecar can be spawned without stowing one.
4
+ import protocol from 'bare-stow/protocol'
5
+
6
+ const ipc = protocol.attach(Bare.IPC)
7
+
8
+ let stop = null
9
+ let readied = false
10
+ let exited = false
11
+
12
+ function ready() {
13
+ if (readied) return
14
+ readied = true
15
+
16
+ ipc.send('ready')
17
+ }
18
+
19
+ async function shutdown(code, err = null) {
20
+ if (exited) return
21
+ exited = true
22
+
23
+ try {
24
+ if (stop) await stop()
25
+ } catch (e) {
26
+ err = err || e
27
+ }
28
+
29
+ if (err) ipc.send('error', { message: err.message, stack: err.stack })
30
+
31
+ await ipc.send('exit', { code })
32
+
33
+ Bare.exit(code)
34
+ }
35
+
36
+ ipc.on('terminate', () => shutdown(0))
37
+
38
+ Bare.on('beforeExit', (exitCode) => shutdown(exitCode))
39
+ .on('uncaughtException', (err) => shutdown(1, err))
40
+ .on('unhandledRejection', (err) => shutdown(1, err))
41
+
42
+ try {
43
+ const entry = await import('./assistant-sidecar.mjs')
44
+ const start = entry.default
45
+
46
+ stop = (await start(ipc, ready)) || null
47
+
48
+ ready()
49
+ } catch (err) {
50
+ shutdown(1, err)
51
+ }