This commit is contained in:
2026-09-11 14:35:22 -04:00
parent aba185d80a
commit cc182f2ef1
10 changed files with 86 additions and 17 deletions
+10 -6
View File
@@ -13,11 +13,13 @@ import { QvacPerception } from './perception.js';
import { ComputerAudit } from '../computer-use/audit.js';
import { PortalInputBackend } from '../computer-use/portal-input.js';
import { ComputerActuator } from '../computer-use/actuator.js';
import { RuntimeTelemetry } from './telemetry.js';
import { StateRecovery } from './recovery.js';
export class JarvisDaemon extends EventEmitter {
constructor() {
super();
this.state = 'ARMED';
this.recovery = new StateRecovery(); const restored = this.recovery.load(); this.state = restored.state; this.mode = restored.mode;
this.voice = new VoiceStateMachine();
this.scheduler = new QvacScheduler({ concurrency: 1 });
this.audit = new ComputerAudit();
@@ -33,22 +35,24 @@ export class JarvisDaemon extends EventEmitter {
this.voiceLoop = null;
this._idleTimer = setInterval(() => this.tickIdle(), 30_000);
this._idleTimer.unref?.();
this.telemetry = new RuntimeTelemetry();
this._telemetryTimer = setInterval(() => this.telemetry.sample(), 60_000); this._telemetryTimer.unref?.();
this.harness.on('agent_message_chunk', (ev) => this.emit('Token', ev?.text || ev?.delta || ''));
this.harness.on('permission', (ev) => this.emit('ConfirmationRequired', ev));
this.harness.on('hud_sidecar', (ev) => this.emit('ChipOffered', 'sidecar', ev?.title || 'Suggested action', JSON.stringify(ev || {})));
}
setState(state) { this.state = state; this.emit('StateChanged', state); this.log.record('state', { state }).catch(() => {}); }
setState(state) { this.state = state; try { this.recovery.save({ state, mode: this.mode }); } catch (error) { this.emit('Error', 'RECOVERY_WRITE', error.message); } this.emit('StateChanged', state); this.log.record('state', { state }).catch(() => {}); }
async arm() { if (this.locked) return; await resumeQvac().catch(() => {}); this.voice.wake(); this.setState('LISTENING'); }
async sleep() { this.voice.sleep(); this.setState('SLEEPING'); await suspendQvac().catch((error) => this.emit('Error', 'QVAC_SUSPEND', error.message)); }
say(text) { this.lastReply = String(text); this.emit('Reply', this.lastReply); }
async ask(text) {
this.voice.utterance(); this.setState('THINKING');
try {
const reply = await this.scheduler.run(() => this.harness.ask(text), { lane: 'voice' });
const startedAt = Date.now(); const reply = await this.scheduler.run(() => this.harness.ask(text), { lane: 'voice' }); this.telemetry.record('llm', startedAt, { success: true });
this.voice.speak(); this.setState('SPEAKING'); this.lastReply = String(reply || ''); this.emit('Reply', this.lastReply); this.voiceLoop?.speak(this.lastReply).catch((error) => this.emit('Error', 'TTS', error.message)); return reply;
} catch (error) {
this.emit('Error', 'QVAC', error.message); this.voice.cancel(); this.setState('ARMED'); throw error;
this.telemetry.record('llm', Date.now(), { success: false }); this.emit('Error', 'QVAC', error.message); this.voice.cancel(); this.setState('ARMED'); throw error;
}
}
cancel() { this.harness.cancel(); this.scheduler.cancelQueued((job) => job.lane === 'voice'); this.computer.revoke(); this.voice.cancel(); this.setState('ARMED'); cancelQvac().catch((error) => this.emit('Error', 'QVAC_CANCEL', error.message)); }
@@ -61,14 +65,14 @@ export class JarvisDaemon extends EventEmitter {
try { await this.voiceLoop.start(); } catch (error) { this.voiceLoop = null; this.emit('Error', 'VOICE_UNAVAILABLE', error.message); throw error; }
}
setPushToTalk(pressed) { this.voiceLoop?.setPushToTalk(pressed); this.emit('PushToTalk', Boolean(pressed)); }
runtimeStatus() { return JSON.stringify({ local: true, qvac: qvacStatus(), scheduler: this.scheduler.status(), computer: this.computer.status(), voice: this.voiceLoop?.metrics?.snapshot?.() || null, p2p: { enabled: process.env.JARVIS_P2P_ENABLE === '1', inference: false, memorySync: false } }); }
runtimeStatus() { return JSON.stringify({ local: true, qvac: qvacStatus(), scheduler: this.scheduler.status(), scheduler_metrics: this.scheduler.metrics(), telemetry: this.telemetry.snapshot(), computer: this.computer.status(), voice: this.voiceLoop?.metrics?.snapshot?.() || null, p2p: { enabled: process.env.JARVIS_P2P_ENABLE === '1', inference: false, memorySync: false } }); }
async assessModelFit(model) { return JSON.stringify(await callQvac('assessModelFit', { modelSrc: String(model) })); }
async downloadModel(model) { return JSON.stringify(await callQvac('downloadAsset', { modelSrc: String(model) })); }
async cancelModel(model) { return JSON.stringify(await cancelQvacRequest({ modelId: String(model) })); }
async wipeComputerTraces() { await this.audit.wipeTemp(); return true; }
handleLockScreen(locked) { this.locked = Boolean(locked); if (this.locked) { this.cancel(); this.setState('ARMED'); } this.emit('LockScreenChanged', this.locked); }
tickIdle() { if (!this.locked && this.voice.expireIdle() === 'SLEEPING' && this.state !== 'SLEEPING') this.sleep(); }
async close() { clearInterval(this._idleTimer); this.computerRevoke(); await this.voiceLoop?.stop?.(); await this.harness.close(); }
async close() { clearInterval(this._idleTimer); clearInterval(this._telemetryTimer); this.computerRevoke(); this.recovery.save({ state: 'ARMED', mode: this.mode }); await this.voiceLoop?.stop?.(); await this.harness.close(); }
}
if (import.meta.url === `file://${process.argv[1]}`) {
+4
View File
@@ -0,0 +1,4 @@
export async function runIsolatedJob(scheduler, task, { lane = 'background', onError } = {}) {
try { return await scheduler.run(task, { lane }); }
catch (error) { onError?.(error); return { ok: false, unavailable: error.message, isolated: true }; }
}
+1
View File
@@ -0,0 +1 @@
export function assertLocalEndpoint(url) { const parsed = new URL(url); if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') throw new Error('only HTTP(S) model endpoints are supported'); if (!['127.0.0.1', 'localhost', '::1'].includes(parsed.hostname) && process.env.JARVIS_P2P_ENABLE !== '1') throw new Error('network access is disabled unless optional P2P/model fetch is explicitly enabled'); return parsed; }
+5 -2
View File
@@ -3,6 +3,7 @@ export class QvacScheduler {
this.concurrency = Math.max(1, concurrency);
this.running = 0;
this.queue = [];
this.completed = 0; this.failed = 0; this.totalDurationMs = 0; this.byLane = {};
}
run(task, { lane = 'background', signal } = {}) {
@@ -19,8 +20,9 @@ export class QvacScheduler {
while (this.running < this.concurrency && this.queue.length) {
const job = this.queue.shift();
if (job.signal?.aborted) { job.reject(new Error('QVAC job cancelled before start')); continue; }
this.running += 1;
Promise.resolve().then(() => job.task(job.signal)).then(job.resolve, job.reject).finally(() => {
this.running += 1; const started = Date.now();
Promise.resolve().then(() => job.task(job.signal)).then((value) => { this.completed += 1; job.resolve(value); }, (error) => { this.failed += 1; job.reject(error); }).finally(() => {
this.totalDurationMs += Date.now() - started; this.byLane[job.lane] = (this.byLane[job.lane] || 0) + 1;
this.running -= 1;
this.pump();
});
@@ -37,4 +39,5 @@ export class QvacScheduler {
}
status() { return { running: this.running, queued: this.queue.map((j) => j.lane) }; }
metrics() { return { completed: this.completed, failed: this.failed, total_duration_ms: this.totalDurationMs, by_lane: { ...this.byLane } }; }
}
+8
View File
@@ -0,0 +1,8 @@
import fs from 'node:fs';
import path from 'node:path';
export class StateRecovery {
constructor({ file = path.join(process.env.XDG_STATE_HOME || path.join(process.env.HOME || '/tmp', '.local/state'), 'jarvis/state.json') } = {}) { this.file = file; }
load() { try { const state = JSON.parse(fs.readFileSync(this.file, 'utf8')); return { state: state.state === 'SLEEPING' ? 'SLEEPING' : 'ARMED', mode: state.mode || 'chat', recovered: true }; } catch { return { state: 'ARMED', mode: 'chat', recovered: false }; } }
save({ state, mode = 'chat' }) { fs.mkdirSync(path.dirname(this.file), { recursive: true }); const temp = `${this.file}.tmp`; fs.writeFileSync(temp, JSON.stringify({ state, mode, savedAt: new Date().toISOString() }) + '\n'); fs.renameSync(temp, this.file); }
}
+8
View File
@@ -0,0 +1,8 @@
import { withQvacMaster, qvacSdk } from './qvac-master.js';
export class RuntimeTelemetry {
constructor({ now = () => Date.now() } = {}) { this.now = now; this.samples = []; this.latencies = {}; }
record(kind, startedAt, extra = {}) { const durationMs = this.now() - startedAt; const row = { kind, durationMs, ...extra }; this.samples.push(row); if (this.samples.length > 200) this.samples.shift(); this.latencies[kind] = { last_ms: durationMs, count: (this.latencies[kind]?.count || 0) + 1 }; return row; }
async sample() { try { const sdk = await qvacSdk(); const resources = await withQvacMaster(() => sdk.getSystemResources({ sample: true })); this.samples.push({ kind: 'gpu_sample', ts: this.now(), resources }); if (this.samples.length > 200) this.samples.shift(); return resources; } catch (error) { return { unavailable: error.message }; } }
snapshot() { const latest = [...this.samples].reverse().find((sample) => sample.kind === 'gpu_sample'); return { latest_resources: latest?.resources || null, latencies: { ...this.latencies }, samples: this.samples.length }; }
}