@qvac/core 0.1.1 → 0.1.3

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.
@@ -0,0 +1,114 @@
1
+ import tui from 'bare-tui'
2
+
3
+ const { style } = tui
4
+
5
+ const SGR = /\x1b\[[0-9;]*m/y
6
+ const SGR_ALL = /\x1b\[[0-9;]*m/g
7
+ const RESET = '\x1b[0m'
8
+
9
+ function charWidth(ch) {
10
+ return ch >= ' ' && ch <= '~' ? 1 : style.width(ch)
11
+ }
12
+
13
+ export function cells(line) {
14
+ const out = []
15
+ for (let i = 0; i < line.length;) {
16
+ if (line[i] === '\x1b') {
17
+ SGR.lastIndex = i
18
+ const match = SGR.exec(line)
19
+ if (match) {
20
+ out.push({ esc: match[0] })
21
+ i = SGR.lastIndex
22
+ continue
23
+ }
24
+ }
25
+ const ch = String.fromCodePoint(line.codePointAt(i))
26
+ out.push({ ch, w: charWidth(ch) })
27
+ i += ch.length
28
+ }
29
+ return out
30
+ }
31
+
32
+ function tokens(line) {
33
+ const out = []
34
+ let token = null
35
+ for (const cell of cells(line)) {
36
+ if (cell.esc) {
37
+ if (!token) out.push((token = { raw: '', w: 0, space: false, cells: [] }))
38
+ token.raw += cell.esc
39
+ token.cells.push(cell)
40
+ continue
41
+ }
42
+ const space = cell.ch === ' '
43
+ if (!token || (token.w > 0 && token.space !== space)) {
44
+ out.push((token = { raw: '', w: 0, space, cells: [] }))
45
+ }
46
+ token.space = space
47
+ token.raw += cell.ch
48
+ token.w += cell.w
49
+ token.cells.push(cell)
50
+ }
51
+ return out
52
+ }
53
+
54
+ function activeSgr(raw) {
55
+ let open = ''
56
+ for (const match of raw.matchAll(SGR_ALL)) {
57
+ open = match[0] === RESET || match[0] === '\x1b[m' ? '' : open + match[0]
58
+ }
59
+ return open
60
+ }
61
+
62
+ function leadingSpaces(line) {
63
+ const plain = style.stripAnsi(line)
64
+ return plain.length - plain.replace(/^ +/, '').length
65
+ }
66
+
67
+ export function wrapLine(line, max) {
68
+ if (max <= 0 || style.width(line) <= max) return [line]
69
+ const indent = ' '.repeat(Math.min(leadingSpaces(line), Math.max(0, max - 1)))
70
+ const rows = []
71
+ let row = ''
72
+ let col = 0
73
+ const breakRow = () => {
74
+ const open = activeSgr(row)
75
+ const done = row.replace(/ +$/, '')
76
+ rows.push(open ? done + RESET : done)
77
+ row = open + indent
78
+ col = indent.length
79
+ }
80
+ for (const token of tokens(line)) {
81
+ if (token.w === 0) {
82
+ row += token.raw
83
+ continue
84
+ }
85
+ if (col + token.w <= max) {
86
+ row += token.raw
87
+ col += token.w
88
+ continue
89
+ }
90
+ if (token.space) {
91
+ if (col > indent.length) breakRow()
92
+ continue
93
+ }
94
+ if (col > indent.length && indent.length + token.w <= max) breakRow()
95
+ for (const cell of token.cells) {
96
+ if (cell.esc) {
97
+ row += cell.esc
98
+ continue
99
+ }
100
+ if (col + cell.w > max) breakRow()
101
+ row += cell.ch
102
+ col += cell.w
103
+ }
104
+ }
105
+ if (rows.length === 0 || style.width(row) > indent.length) rows.push(row)
106
+ return rows
107
+ }
108
+
109
+ export function wrapBlock(text, max) {
110
+ return String(text)
111
+ .split('\n')
112
+ .flatMap((line) => wrapLine(line, max))
113
+ .join('\n')
114
+ }
@@ -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
+ }