@qvac/core 1.0.0-rc.7 → 1.0.0-rc.8

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/CHANGELOG.md CHANGED
@@ -88,11 +88,14 @@ release.
88
88
  unchanged.
89
89
  ([decision](docs/decisions/2026-11-05-a-streaming-reply-lands-once-a-second.md))
90
90
 
91
+ - A private chat linked to a project no longer reads the project's knowledge base: `ragSearch` and
92
+ the runs it feeds rank the knowledge base only for a chat in the project. ([rag.md](docs/api/rag.md))
93
+
91
94
  - The KV cache retention sweep runs every 12 hours instead of every hour, besides when a mesh opens
92
95
  and when `kvCache.retentionDays` changes, so a cache can outlive its retention by up to 12 hours
93
96
  on a host that stays up. ([config.md](docs/api/config.md#kv-cache-retention))
94
97
 
95
- - Core depends on `@qvac/harness` 1.0.0-rc.17 from npm instead of a git commit, so a consumer installs
98
+ - Core depends on `@qvac/harness` 1.0.0-rc.18 from npm instead of a git commit, so a consumer installs
96
99
  the published harness with its named entries.
97
100
 
98
101
  - Wipe a store written by 1.0.0-rc.0 to rc.2 before running this build. The collection, route and
@@ -128,6 +131,10 @@ release.
128
131
 
129
132
  ### Fixed
130
133
 
134
+ - A reply served by another device no longer repeats parts of itself. The run owner skips the text
135
+ the host already wrote when its harness streams it back, but matched that text chunk by chunk,
136
+ and the harness wire joins chunks that arrive together, so a delta frame carrying two of the
137
+ host's chunks was written a second time by the owner. The echo is now matched as text.
131
138
  - A run that restarts mid-reply no longer has its host write the abandoned round's answer a second
132
139
  time beside the new attempt's: the run cancels the model rounds its earlier attempt left open
133
140
  before it starts again.
@@ -6,4 +6,9 @@ export interface ForwardingOptions {
6
6
  readonly remote: (deviceId: Buffer) => Capabilities;
7
7
  }
8
8
  export declare function forwardToDevices(local: Partial<CapabilityHandlers>, opts: ForwardingOptions): DeviceRoutes;
9
- export declare function servedToSiblings(local: Partial<CapabilityHandlers>): DeviceRoutes;
9
+ interface SiblingAsks {
10
+ asked(name: string): Promise<void> | undefined;
11
+ resumed(name: string): void;
12
+ }
13
+ export declare function servedToSiblings(local: Partial<CapabilityHandlers>, sibling: SiblingAsks): DeviceRoutes;
14
+ export {};
@@ -64,10 +64,11 @@ export function forwardToDevices(local, opts) {
64
64
  };
65
65
  return modelRoutes(at);
66
66
  }
67
- export function servedToSiblings(local) {
67
+ export function servedToSiblings(local, sibling) {
68
68
  const routes = modelRoutes(() => local);
69
69
  return {
70
70
  ...routes,
71
+ ...siblingDownloads(routes, sibling),
71
72
  previewCustomModel: (input) => {
72
73
  refuseLocalSources(input);
73
74
  return routes.previewCustomModel(input);
@@ -90,6 +91,24 @@ export function servedToSiblings(local) {
90
91
  })
91
92
  };
92
93
  }
94
+ function siblingDownloads(routes, sibling) {
95
+ return {
96
+ retryModelDownload: async (input) => {
97
+ const asked = sibling.asked(input.name);
98
+ if (!asked) {
99
+ return await routes.retryModelDownload(input);
100
+ }
101
+ await asked;
102
+ return { ok: true };
103
+ },
104
+ setModelPaused: async (input) => {
105
+ if (!input.paused) {
106
+ sibling.resumed(input.name);
107
+ }
108
+ return await routes.setModelPaused(input);
109
+ }
110
+ };
111
+ }
93
112
  function here(input) {
94
113
  const local = { ...input };
95
114
  delete local.deviceId;
@@ -2,9 +2,8 @@ import { toolsetEnabled } from '@qvac/harness/lib/tools/toolsets.ts';
2
2
  import { getAgent } from '../core/agent.js';
3
3
  import { runDefinition } from '../core/shared-agents.js';
4
4
  import { getChat } from '../core/chat.js';
5
- import { chatProject } from '../core/chat-project.js';
6
5
  import { isKnowledgeRoutedAttachment, fullTextBudgetChars, fullTextHits, joinedIndex, retrievalBudgetTokens, retrieveRagKnowledge, searchRagChunks, referencesPendingFile } from '../core/files/index.js';
7
- import { heldMesh, requireMesh } from './current-mesh.js';
6
+ import { requireMesh } from './current-mesh.js';
8
7
  import { errorMessage } from '../guards.js';
9
8
  import b4a from 'b4a';
10
9
  export const MAX_RAG_SEARCH_LIMIT = 20;
@@ -50,9 +49,7 @@ export function createRagApi(pool, { index, embedder, effectiveCtxSize = null })
50
49
  pendingFiles = pendingFileNames(initialFiles);
51
50
  chatFilesIndexingHere = indexingHere(initialFiles);
52
51
  const scopeRows = chatRows.filter((row) => scopeIds.has(row.id));
53
- const project = off.has('project')
54
- ? null
55
- : await chatProject(mesh, chatId, (id) => heldMesh(pool, id));
52
+ const project = off.has('project') || mesh.role !== 'project' ? null : mesh;
56
53
  const kbEntries = project ? ((await project.files.knowledgeBase()).entries ?? []) : [];
57
54
  const kbRows = kbEntries.filter((entry) => entry.loaded).map((entry) => entry.knowledge);
58
55
  projectFilesNotReady = kbEntries.filter((entry) => !entry.loaded && entry.status !== 'failed').length;
@@ -44,6 +44,11 @@ export interface OutputHooks {
44
44
  forwarded(echo: Echo): void;
45
45
  retook(): void;
46
46
  }
47
+ export declare class Echoes {
48
+ private readonly _pending;
49
+ forwarded({ type, text }: Echo): void;
50
+ own(type: Echo['type'], text: string): string;
51
+ }
47
52
  export declare class OwnerRounds {
48
53
  readonly port: ModelRoundPort;
49
54
  inputLength: number;
@@ -59,7 +64,7 @@ export declare class OwnerRounds {
59
64
  get rounds(): number;
60
65
  ranHere(round: number | undefined): boolean;
61
66
  retook(): boolean;
62
- echoed(type: string, text: string): boolean;
67
+ unechoed(type: Echo['type'], text: string): string;
63
68
  retire(): Promise<void>;
64
69
  private _round;
65
70
  probe({ kind, prompt, modelId, responseFormat, signal }: Probe): Promise<string>;
@@ -90,6 +95,7 @@ export declare class RoundOutput {
90
95
  private _resetAt;
91
96
  constructor(id: string, io: ModelRoundIo, hooks: OutputHooks);
92
97
  apply(frame: AssistantChunkDelta): AssistantChunkContentModelRequest | undefined;
98
+ hold(): void;
93
99
  reask(id: string, emit: ModelRoundIo['emit']): void;
94
100
  round(): AssistantChunkContentModelRequest | undefined;
95
101
  switchedTo(from: number): string | undefined;
@@ -35,12 +35,30 @@ const roundOptions = z.object({
35
35
  media: z.array(z.object({ at: z.number(), refs: z.array(mediaRef) })).optional()
36
36
  });
37
37
  const roundResult = z.custom((value) => isRecord(value) && typeof value.contentText === 'string' && isRecord(value.final));
38
+ export class Echoes {
39
+ _pending = { content: '', thinking: '' };
40
+ forwarded({ type, text }) {
41
+ this._pending[type] += text;
42
+ }
43
+ own(type, text) {
44
+ const pending = this._pending[type];
45
+ if (pending.startsWith(text)) {
46
+ this._pending[type] = pending.slice(text.length);
47
+ return '';
48
+ }
49
+ if (pending && text.startsWith(pending)) {
50
+ this._pending[type] = '';
51
+ return text.slice(pending.length);
52
+ }
53
+ return text;
54
+ }
55
+ }
38
56
  export class OwnerRounds {
39
57
  port;
40
58
  inputLength = 0;
41
59
  share = null;
42
60
  _opts;
43
- _echoes = [];
61
+ _echoes = new Echoes();
44
62
  _known = null;
45
63
  _contextSent = false;
46
64
  _rounds = 0;
@@ -65,13 +83,8 @@ export class OwnerRounds {
65
83
  this._retakes--;
66
84
  return true;
67
85
  }
68
- echoed(type, text) {
69
- const at = this._echoes.findIndex((echo) => echo.type === type && echo.text === text);
70
- if (at === -1) {
71
- return false;
72
- }
73
- this._echoes.splice(at, 1);
74
- return true;
86
+ unechoed(type, text) {
87
+ return this._echoes.own(type, text);
75
88
  }
76
89
  async retire() {
77
90
  const { engine, chatId, runId } = this._opts;
@@ -305,11 +318,12 @@ export class OwnerRounds {
305
318
  io.signal.addEventListener('abort', abort);
306
319
  const at = { asked: first, moving: null, host: null };
307
320
  const output = new RoundOutput(first.id, io, {
308
- forwarded: (echo) => this._echoes.push(echo),
321
+ forwarded: (echo) => this._echoes.forwarded(echo),
309
322
  retook: () => this._retakes++
310
323
  });
311
324
  const move = async (agentId) => {
312
325
  at.moving = { agentId, after: output.newest(), emit: io.retake() };
326
+ output.hold();
313
327
  await engine.cancelModelRequest({ chunkId: at.asked.id }).catch(noop);
314
328
  };
315
329
  void this._followHost(agents, { at, output, move }).catch(noop);
@@ -416,6 +430,9 @@ export class RoundOutput {
416
430
  }
417
431
  return round;
418
432
  }
433
+ hold() {
434
+ this._emit = null;
435
+ }
419
436
  reask(id, emit) {
420
437
  this._id = id;
421
438
  this._emit = emit;
@@ -463,16 +480,21 @@ export class RoundOutput {
463
480
  this._takenAt = now ? at : this._takenAt;
464
481
  }
465
482
  _forward(chunk) {
483
+ const emit = this._emit;
466
484
  const text = chunk.content?.text ?? chunk.thinking?.text;
467
485
  const type = chunk.type;
468
486
  const fresh = chunk.parentId === this._id && !this._emitted.has(chunk.id) && chunk.seq > this._resetAt;
469
487
  const taken = !this._reopened && this._taker && b4a.equals(chunk.originDeviceId, this._taker);
470
- if (!fresh || !taken || text === undefined || (type !== 'content' && type !== 'thinking')) {
488
+ if (!emit ||
489
+ !fresh ||
490
+ !taken ||
491
+ text === undefined ||
492
+ (type !== 'content' && type !== 'thinking')) {
471
493
  return;
472
494
  }
473
495
  this._emitted.add(chunk.id);
474
496
  this._hooks.forwarded({ type, text });
475
- this._emit({ type, text });
497
+ emit({ type, text });
476
498
  }
477
499
  }
478
500
  export async function listRoundChunks(engine, chatId) {
@@ -23,6 +23,7 @@ export function assistantTree(opts) {
23
23
  let offDeleteChatKvCache = null;
24
24
  let offCompactChat = null;
25
25
  let offRetryModelDownload = null;
26
+ let offSiblingDownloads = null;
26
27
  let offModelResidency = null;
27
28
  let offModelUsers = null;
28
29
  let offSkills = null;
@@ -118,6 +119,10 @@ export function assistantTree(opts) {
118
119
  logger
119
120
  });
120
121
  offRetryModelDownload = core.registerRetryModelDownload((name) => assistant.retryModelDownload(name));
122
+ offSiblingDownloads = core.registerSiblingDownloads({
123
+ asked: (name) => assistant.retryModelDownload(name, { sibling: true }),
124
+ resumed: (name) => assistant.siblingResumedDownload(name)
125
+ });
121
126
  offModelResidency = core.registerModelResidency({
122
127
  load: (name) => assistant.loadModel(name),
123
128
  unload: (name) => assistant.unloadModel(name)
@@ -204,6 +209,8 @@ export function assistantTree(opts) {
204
209
  offFakeModels = null;
205
210
  offRetryModelDownload?.();
206
211
  offRetryModelDownload = null;
212
+ offSiblingDownloads?.();
213
+ offSiblingDownloads = null;
207
214
  offModelResidency?.();
208
215
  offModelResidency = null;
209
216
  offModelUsers?.();
@@ -8,6 +8,7 @@ import type { DriveHost } from './core/fs-drives.ts';
8
8
  import { type DiagnosticsSlice } from './diagnostics.ts';
9
9
  import { type InferenceCallPage } from './inference-calls.ts';
10
10
  import type { LoggerInterface } from '@qvac/logging';
11
+ import { type RetryOptions } from './model-download.ts';
11
12
  import { type DeleteModelSummary, type Harness, type ListModelsOptions, type ModelInfo, type ToolCatalogEntry } from './assistant/harness.ts';
12
13
  import type { Skill } from './assistant/skill-encode.ts';
13
14
  import { type CompactOptions, type CompactResult } from './assistant/history.ts';
@@ -172,7 +173,8 @@ export declare class QvacAssistant extends ReadyResource {
172
173
  private _runnableHost;
173
174
  notifyModelCatalog(): void;
174
175
  cachedModelsChanged(): void;
175
- retryModelDownload(name: string): Promise<void>;
176
+ retryModelDownload(name: string, options?: RetryOptions): Promise<void>;
177
+ siblingResumedDownload(name: string): void;
176
178
  skills(agentId?: string | null, modelName?: string | null, options?: SkillListOptions): Promise<ReadonlyArray<Skill>>;
177
179
  private _recordSkillReadiness;
178
180
  private _readySkillNames;
@@ -1131,11 +1131,14 @@ export class QvacAssistant extends ReadyResource {
1131
1131
  this._modelCatalog.notify();
1132
1132
  this._reportCapabilities().catch(noop);
1133
1133
  }
1134
- async retryModelDownload(name) {
1134
+ async retryModelDownload(name, options) {
1135
1135
  if (!this._downloads) {
1136
1136
  throw new CoreError('MODEL_DOWNLOAD_UNAVAILABLE');
1137
1137
  }
1138
- await this._downloads.retry(name);
1138
+ await this._downloads.retry(name, options);
1139
+ }
1140
+ siblingResumedDownload(name) {
1141
+ this._downloads?.siblingResumed(name);
1139
1142
  }
1140
1143
  async skills(agentId, modelName, options) {
1141
1144
  if (!this.opened)
@@ -2206,11 +2209,12 @@ export class QvacAssistant extends ReadyResource {
2206
2209
  await transcript.text(type, text, round);
2207
2210
  };
2208
2211
  const writeRoundText = async (type, text) => {
2209
- if (!rounds.echoed(type, text)) {
2210
- await writeText(type, text);
2212
+ const own = rounds.unechoed(type, text);
2213
+ if (type === 'content' && own.length < text.length) {
2214
+ answer(text.slice(0, text.length - own.length));
2211
2215
  }
2212
- else if (type === 'content') {
2213
- answer(text);
2216
+ if (own) {
2217
+ await writeText(type, own);
2214
2218
  }
2215
2219
  };
2216
2220
  const failRun = async (message) => {
@@ -24,6 +24,10 @@ import { Mesh, type DeviceMetadata, type ProjectIdentity } from './core/mesh.ts'
24
24
  import { type Stream, type Transport } from '@qvac/harness/rpc';
25
25
  import { type CoreSpec } from './spec-loader.ts';
26
26
  import { type LocalQvacState } from '../spec/index.js';
27
+ export interface SiblingDownloads {
28
+ asked(name: string): Promise<void>;
29
+ resumed(name: string): void;
30
+ }
27
31
  export interface ClearOldFilesOptions {
28
32
  readonly olderThanMs: number;
29
33
  readonly includeOwn?: boolean;
@@ -185,6 +189,7 @@ export declare class Core extends ReadyResource {
185
189
  private _modelCatalogWatch;
186
190
  private _modelCatalogWatchSource;
187
191
  private _retryModelDownload;
192
+ private _siblingDownloads;
188
193
  private _transcribe;
189
194
  private _detectLanguage;
190
195
  private _previewModelSource;
@@ -708,6 +713,7 @@ export declare class Core extends ReadyResource {
708
713
  private _readModels;
709
714
  private _openModelCatalogWatchSource;
710
715
  private _resetModelCatalogWatchSource;
716
+ registerSiblingDownloads(hooks: SiblingDownloads): () => void;
711
717
  registerRetryModelDownload(hook: (name: string) => Promise<void>): () => void;
712
718
  registerSkills(hook: (agentId?: string | null, modelName?: string | null, options?: SkillOptions) => Promise<unknown>): () => void;
713
719
  registerSkillCatalog(hook: (agentId?: string | null, modelName?: string | null, options?: SkillCatalogOptions) => Promise<AssistantSkillCatalogResponse>): () => void;
@@ -150,6 +150,7 @@ export class Core extends ReadyResource {
150
150
  _modelCatalogWatch;
151
151
  _modelCatalogWatchSource = new ReadyGuard();
152
152
  _retryModelDownload;
153
+ _siblingDownloads;
153
154
  _transcribe;
154
155
  _detectLanguage;
155
156
  _previewModelSource;
@@ -315,6 +316,7 @@ export class Core extends ReadyResource {
315
316
  this._openModelCatalogWatchSource();
316
317
  void this._modelCatalogWatchSource.ready().catch(noop);
317
318
  this._retryModelDownload = retryModelDownload ?? null;
319
+ this._siblingDownloads = null;
318
320
  this._transcribe = transcribe ?? null;
319
321
  this._detectLanguage = detectLanguage ?? null;
320
322
  this._previewModelSource = previewModelSource ?? null;
@@ -659,7 +661,10 @@ export class Core extends ReadyResource {
659
661
  : null
660
662
  });
661
663
  api.skillOauth = (request) => this._skillOauth(request);
662
- this._servedToSiblings = servedToSiblings(api);
664
+ this._servedToSiblings = servedToSiblings(api, {
665
+ asked: (name) => this._siblingDownloads?.asked(name),
666
+ resumed: (name) => this._siblingDownloads?.resumed(name)
667
+ });
663
668
  this._api = {
664
669
  ...api,
665
670
  ...forwardToDevices(api, {
@@ -7076,6 +7081,14 @@ export class Core extends ReadyResource {
7076
7081
  this._modelCatalogWatchSource = new ReadyGuard();
7077
7082
  void this._modelCatalogWatchSource.ready().catch(noop);
7078
7083
  }
7084
+ registerSiblingDownloads(hooks) {
7085
+ this._siblingDownloads = hooks;
7086
+ return () => {
7087
+ if (this._siblingDownloads === hooks) {
7088
+ this._siblingDownloads = null;
7089
+ }
7090
+ };
7091
+ }
7079
7092
  registerRetryModelDownload(hook) {
7080
7093
  this._retryModelDownload = hook;
7081
7094
  return () => {
@@ -735,6 +735,10 @@ declare const DEFINITIONS: {
735
735
  readonly code: 101220;
736
736
  readonly message: () => string;
737
737
  };
738
+ readonly OAUTH_GRANT_REVOKED: {
739
+ readonly code: 101221;
740
+ readonly message: () => string;
741
+ };
738
742
  readonly SIDECAR_ENTRY_MISSING: {
739
743
  readonly code: 101301;
740
744
  readonly message: () => string;
@@ -650,6 +650,10 @@ const DEFINITIONS = {
650
650
  code: 101220,
651
651
  message: () => 'OAuth client registration timed out'
652
652
  },
653
+ OAUTH_GRANT_REVOKED: {
654
+ code: 101221,
655
+ message: () => 'OAuth grant was revoked or expired (invalid_grant); sign in again'
656
+ },
653
657
  SIDECAR_ENTRY_MISSING: {
654
658
  code: 101301,
655
659
  message: () => 'sidecar mode needs a stowed bundle entry'
@@ -25,6 +25,9 @@ export interface CacheWaitOptions {
25
25
  readonly onProgress?: (percentage: number) => void;
26
26
  readonly onStall?: () => void;
27
27
  }
28
+ export interface RetryOptions {
29
+ readonly sibling?: boolean;
30
+ }
28
31
  interface DownloadHarness {
29
32
  list?(options?: {
30
33
  cachedOnly?: boolean;
@@ -138,6 +141,7 @@ export declare class ModelDownloadReconciler {
138
141
  private readonly _observedProgress;
139
142
  private readonly _observedSpeed;
140
143
  private readonly _requestedModels;
144
+ private readonly _siblingRequests;
141
145
  private readonly _heldLoads;
142
146
  private readonly _releasing;
143
147
  private readonly _targetTotals;
@@ -174,7 +178,8 @@ export declare class ModelDownloadReconciler {
174
178
  private _transfer;
175
179
  private _completeTransfer;
176
180
  waitUntilCached(model: string, signal: AbortSignal, { onHold, onProgress, onStall }?: CacheWaitOptions): Promise<void>;
177
- retry(name: string): Promise<void>;
181
+ retry(name: string, { sibling }?: RetryOptions): Promise<void>;
182
+ siblingResumed(name: string): void;
178
183
  release<T>(name: string, removeFiles: () => Promise<T>): Promise<T>;
179
184
  close(): Promise<void>;
180
185
  private _watchConfig;
@@ -34,6 +34,7 @@ export class ModelDownloadReconciler {
34
34
  _observedProgress = new Map();
35
35
  _observedSpeed = new Map();
36
36
  _requestedModels = new Set();
37
+ _siblingRequests = new Set();
37
38
  _heldLoads = new Set();
38
39
  _releasing = new Set();
39
40
  _targetTotals = new Map();
@@ -227,10 +228,15 @@ export class ModelDownloadReconciler {
227
228
  this._kick();
228
229
  });
229
230
  }
230
- async retry(name) {
231
+ async retry(name, { sibling = false } = {}) {
231
232
  if (this._closed)
232
233
  throw new CoreError('MODEL_DOWNLOAD_CLOSED');
233
- this._requestedModels.add(name);
234
+ if (!sibling) {
235
+ this._requestedModels.add(name);
236
+ }
237
+ else if (!this._requestedModels.has(name)) {
238
+ this._siblingRequests.add(name);
239
+ }
234
240
  this._attemptGenerations.set(name, this._attemptGeneration(name) + 1);
235
241
  const demand = this._demands.get(name);
236
242
  if (demand) {
@@ -243,11 +249,17 @@ export class ModelDownloadReconciler {
243
249
  }
244
250
  this._kick();
245
251
  }
252
+ siblingResumed(name) {
253
+ if (this._config?.pausedModels?.includes(name) && this._requestedModels.delete(name)) {
254
+ this._siblingRequests.add(name);
255
+ }
256
+ }
246
257
  async release(name, removeFiles) {
247
258
  if (this._closed)
248
259
  throw new CoreError('MODEL_DOWNLOAD_CLOSED');
249
260
  this._releasing.add(name);
250
261
  this._requestedModels.delete(name);
262
+ this._siblingRequests.delete(name);
251
263
  this._handled.delete(name);
252
264
  try {
253
265
  if (this._active?.model === name) {
@@ -616,7 +628,7 @@ export class ModelDownloadReconciler {
616
628
  }
617
629
  }
618
630
  }
619
- for (const name of this._requestedModels) {
631
+ for (const name of [...this._requestedModels, ...this._siblingRequests]) {
620
632
  if (wanted.has(name))
621
633
  continue;
622
634
  const addon = availability.addons.get(name);
@@ -647,6 +659,7 @@ export class ModelDownloadReconciler {
647
659
  for (const model of wanted.values()) {
648
660
  if (availability.cached.has(model.name)) {
649
661
  this._requestedModels.delete(model.name);
662
+ this._siblingRequests.delete(model.name);
650
663
  this._resolveDemand(model.name);
651
664
  await this._status.clear(model.name);
652
665
  continue;
@@ -1,4 +1,5 @@
1
1
  import { scopedKey } from './keys.js';
2
+ import { isCoreError } from '../errors.js';
2
3
  export const REFRESH_SKEW_MS = 60_000;
3
4
  const inFlightRefresh = new WeakMap();
4
5
  export async function resolveOAuthCredential(opts) {
@@ -41,12 +42,16 @@ export async function resolveOAuthCredential(opts) {
41
42
  let pending = engineRefreshes.get(refreshKey);
42
43
  if (!pending) {
43
44
  pending = (async () => {
44
- const refreshed = await refresh({
45
- clientId,
46
- clientSecret,
47
- refreshToken,
48
- fetch: opts.fetch
49
- });
45
+ let refreshed;
46
+ try {
47
+ refreshed = await refresh({ clientId, clientSecret, refreshToken, fetch: opts.fetch });
48
+ }
49
+ catch (err) {
50
+ if (isCoreError(err, 'OAUTH_GRANT_REVOKED')) {
51
+ await forgetGrant(opts, refreshToken);
52
+ }
53
+ throw err;
54
+ }
50
55
  await engine.configSet({
51
56
  key: scopedKey(agentId, credentialKey),
52
57
  value: refreshed.accessToken
@@ -65,7 +70,23 @@ export async function resolveOAuthCredential(opts) {
65
70
  }
66
71
  return await pending;
67
72
  }
68
- catch {
69
- return token;
73
+ catch (err) {
74
+ return isCoreError(err, 'OAUTH_GRANT_REVOKED') ? null : token;
75
+ }
76
+ }
77
+ async function forgetGrant({ engine, agentId, credentialKey, stateKey }, deadRefreshToken) {
78
+ const { value: raw } = await engine.configGet({ key: scopedKey(agentId, stateKey) });
79
+ let current = {};
80
+ try {
81
+ current = (typeof raw === 'string' && JSON.parse(raw)) || {};
82
+ }
83
+ catch { }
84
+ if (current.refreshToken !== deadRefreshToken) {
85
+ return;
70
86
  }
87
+ await engine.configSet({ key: scopedKey(agentId, credentialKey), value: '' });
88
+ await engine.configSet({
89
+ key: scopedKey(agentId, stateKey),
90
+ value: JSON.stringify({ ...current, refreshToken: undefined, expiresAt: undefined })
91
+ });
71
92
  }
@@ -86,12 +86,23 @@ export async function refreshOAuthTokensWithFetch(config, refreshToken, fetchImp
86
86
  read: async (response) => {
87
87
  if (!response.ok) {
88
88
  const text = await response.text().catch(() => '');
89
+ if (isInvalidGrant(text)) {
90
+ throw new CoreError('OAUTH_GRANT_REVOKED');
91
+ }
89
92
  throw new CoreError('OAUTH_TOKEN_REFRESH_FAILED', [response.status, text]);
90
93
  }
91
94
  return toTokens(parseTokenResponse(await response.json()), refreshToken);
92
95
  }
93
96
  });
94
97
  }
98
+ function isInvalidGrant(text) {
99
+ try {
100
+ return TokenErrorSchema.safeParse(JSON.parse(text)).data?.error === 'invalid_grant';
101
+ }
102
+ catch {
103
+ return false;
104
+ }
105
+ }
95
106
  export function isTokenExpired(record, bufferMs = 60_000) {
96
107
  return typeof record.expiresAt === 'number' && Date.now() + bufferMs >= record.expiresAt;
97
108
  }
package/package.json CHANGED
@@ -1,6 +1,7 @@
1
1
  {
2
2
  "name": "@qvac/core",
3
- "version": "1.0.0-rc.7",
3
+ "version": "1.0.0-rc.8",
4
+ "upgrade": "pear://56h5xtm7xjjpkbj1ubbuffcjastpxri11n6wr6zy8ikzmyq7ctey",
4
5
  "type": "module",
5
6
  "description": "Peer-to-peer AI across your devices",
6
7
  "engines": {
@@ -189,7 +190,8 @@
189
190
  "build:bundle": "node scripts/build-bundle.mjs",
190
191
  "prepack": "node scripts/build-lib.mjs",
191
192
  "build:lib": "node scripts/build-lib.mjs",
192
- "provenance": "node scripts/provenance.mjs --out docs/provenance/$npm_package_version.json"
193
+ "provenance": "node scripts/provenance.mjs --out docs/provenance/$npm_package_version.json",
194
+ "make": "node scripts/make.mjs"
193
195
  },
194
196
  "prettier": "prettier-config-holepunch",
195
197
  "imports": {
@@ -252,9 +254,9 @@
252
254
  },
253
255
  "dependencies": {
254
256
  "@qvac/error": "^0.2.0",
255
- "@qvac/harness": "1.0.0-rc.17",
257
+ "@qvac/harness": "1.0.0-rc.18",
256
258
  "@qvac/logging": "^0.2.0",
257
- "@qvac/skills": "^0.1.21",
259
+ "@qvac/skills": "^0.3.0",
258
260
  "asenion": "^0.1.0",
259
261
  "autobee": "^2.12.1",
260
262
  "b4a": "^1.9.0",
@@ -286,12 +288,14 @@
286
288
  "bare-system-logger": "^1.0.3",
287
289
  "bare-thread": "~1.2.7",
288
290
  "bare-tui": "^0.3.0",
291
+ "bare-tui-updater": "^0.0.1",
289
292
  "bare-url": "^2.4.5",
290
293
  "bare-worker": "^4.5.0",
291
294
  "blind-peer": "^3.10.2",
292
295
  "blind-peering": "2.9.5",
293
296
  "compact-encoding": "^3.4.0",
294
297
  "corestore": "^7.16.1",
298
+ "fs-native-lock": "^1.2.0",
295
299
  "hrpc": "^4.3.0",
296
300
  "hyperblobs": "^2.12.1",
297
301
  "hyperconf": "^1.0.3",
@@ -307,6 +311,7 @@
307
311
  "hyperswarm": "^4.17.0",
308
312
  "keet-identity-key": "^3.2.0",
309
313
  "paparam": "^1.13.0",
314
+ "pear-runtime-updater": "^3.4.0",
310
315
  "process-top": "^1.7.1",
311
316
  "protomux": "^3.11.0",
312
317
  "protomux-wakeup": "^2.9.0",
@@ -342,6 +347,7 @@
342
347
  "devDependencies": {
343
348
  "@qvac/core-previous": "npm:@qvac/core@0.10.3",
344
349
  "@types/node": "^26.4.0",
350
+ "bare-build": "^1.0.4",
345
351
  "bare-bundle": "^1.10.0",
346
352
  "bare-module-lexer": "^1.6.3",
347
353
  "bare-pack": "^2.2.1",
package/tui/README.md CHANGED
@@ -40,6 +40,57 @@ not published.
40
40
  be on PATH (`bare-runtime` puts it in `node_modules/.bin`). `bare-tui` needs
41
41
  Bare's native TTY; the TUI will not run under node.
42
42
 
43
+ ## Standalone executable
44
+
45
+ `bun run make` builds `out/make/duck` (`duck.exe` on Windows) for this machine,
46
+ or for `HOST=<platform>-<arch>`: one file with no `bare` or `node_modules` to
47
+ install beside it.
48
+
49
+ `scripts/make.mjs` bundles the TUI launcher, stows the sidecar and harness as
50
+ separate bundles, and embeds their native addons, the skills tree and release
51
+ metadata as assets. On launch, the runtime extracts the spawned children and
52
+ assets to real paths so their addons can load without a separate `bare` or
53
+ `node_modules` install.
54
+
55
+ ### Updates
56
+
57
+ The executable updates itself peer to peer with
58
+ [`pear-runtime-updater`](https://github.com/holepunchto/pear-runtime-updater),
59
+ the way [bmus](https://github.com/rafapaezbas/bmus) does. It follows the
60
+ `pear://` link in package.json `upgrade` (`UPGRADE_KEY` overrides it at build
61
+ time), and when that drive carries a newer version for this host it downloads it
62
+ into `.duck-update/` beside the executable, so the swap stays on one volume:
63
+
64
+ - in the TUI a banner reports the download, and `ctrl+u` swaps the new build in
65
+ over the running one, to take effect on the next launch;
66
+ - `--headless` has no one to ask, so it swaps as soon as the build is downloaded,
67
+ prints an `update` line and exits with 75 for its supervisor to restart it on
68
+ the new build.
69
+
70
+ A headless duck is meant to run under a supervisor, such as a systemd user unit
71
+ with `ExecStart=%h/.local/bin/duck --headless` and `Restart=on-failure` (75 is a
72
+ failure, so an update restarts it too). The executable's directory must be one
73
+ duck can write to. Run by hand, it stops after an update.
74
+
75
+ A build is about 1.3GB, and the whole of it downloads for each update. A duck
76
+ already on the newest version also fetches that build into its corestore in the
77
+ background, and the corestore keeps every version it has fetched.
78
+
79
+ With no `upgrade` link there is nothing to follow, and the updater never starts;
80
+ an npm install never starts one either, since the executable it would swap is
81
+ `bare` itself. Its corestore and lock live in the per-user app directory
82
+ (`~/Library/Application Support/duck`, `~/.config/duck`,
83
+ `%APPDATA%\duck`), not under `--storage`: one executable serves every storage
84
+ root, and only the first duck running holds the updater.
85
+
86
+ `.github/workflows/stage-duck.yml` builds every host on its own runner and
87
+ stages them together to the `duck` namespace with
88
+ [pear-ci](https://docs.pears.com/pear/reference/ci-and-release/pear-ci-action/),
89
+ which keeps `ci/snapshot.json` on `main` in step with the drive, so it runs only
90
+ once the workflow and that file are on `main`. A dry run prints the drive's key
91
+ after `starting stage for key`: that `pear://` link is the `upgrade` to commit,
92
+ and `pear seed` on it must be running before a real stage.
93
+
43
94
  ## Usage
44
95
 
45
96
  ```
package/tui/app.mjs CHANGED
@@ -1,5 +1,6 @@
1
1
  // the bare-tui chat model, split from the host so it can be driven headlessly with a fake engine
2
2
  import tui from 'bare-tui'
3
+ import updateBanner from 'bare-tui-updater'
3
4
  import { spawn } from 'child_process'
4
5
  import fs from 'fs'
5
6
  import { TOOLSETS } from '@qvac/harness/lib/tools/toolsets.ts'
@@ -1892,6 +1893,7 @@ export class ChatApp {
1892
1893
  copyToClipboard,
1893
1894
  resolvePastedFile,
1894
1895
  resolveFileAttachment,
1896
+ applyUpdate,
1895
1897
  saveDir,
1896
1898
  skills,
1897
1899
  openUrl
@@ -1920,6 +1922,9 @@ export class ChatApp {
1920
1922
  this._resolvePastedFile = resolvePastedFile || null
1921
1923
  // `/attach <path>` resolver: named path -> attachment, or throws.
1922
1924
  this._resolveFileAttachment = resolveFileAttachment || null
1925
+ this.updateBanner = applyUpdate
1926
+ ? updateBanner.create({ onAccept: applyUpdate, acceptKey: 'ctrl+u' })
1927
+ : null
1923
1928
  this._selection = null // { anchor, focus, edge } in content cells, while a drag selects text
1924
1929
  this._dragToken = 0 // stale-guards the edge auto-scroll beats
1925
1930
  this._saveDir = saveDir || path.join(os.homedir(), 'Downloads')
@@ -7385,6 +7390,15 @@ export class ChatApp {
7385
7390
  return [this, null]
7386
7391
  }
7387
7392
 
7393
+ if (
7394
+ this.updateBanner &&
7395
+ (msg.type.startsWith('update.') ||
7396
+ (msg.type === 'spinner.tick' && msg.id === this.updateBanner.spinner.id))
7397
+ ) {
7398
+ const [, cmd] = this.updateBanner.update(msg)
7399
+ return [this, cmd]
7400
+ }
7401
+
7388
7402
  if (msg.type === 'spinner.tick') {
7389
7403
  const [s, cmd] = this.spin.update(msg)
7390
7404
  this.spin = s
@@ -7514,6 +7528,12 @@ export class ChatApp {
7514
7528
  return this._toggleToolOutput()
7515
7529
  }
7516
7530
 
7531
+ // only the accept chord reaches the banner: its own u/enter/esc are typing here
7532
+ if (this.updateBanner && key.matches(msg, 'ctrl+u')) {
7533
+ const [, cmd] = this.updateBanner.update(msg)
7534
+ return [this, cmd]
7535
+ }
7536
+
7517
7537
  // typing dismisses an overlay into the input; other keys are swallowed so they can't leak through
7518
7538
  if (this._models || this._selector || this.overlay || this._menu) {
7519
7539
  const handled = this._overlayKey(msg)
@@ -7559,6 +7579,11 @@ export class ChatApp {
7559
7579
 
7560
7580
  return [this, null]
7561
7581
  }
7582
+
7583
+ if (['ready', 'applied', 'error'].includes(this.updateBanner?.state)) {
7584
+ this.updateBanner.update({ type: 'update.dismiss' })
7585
+ return [this, null]
7586
+ }
7562
7587
  }
7563
7588
 
7564
7589
  if (this.pendingApproval) {
@@ -8097,9 +8122,8 @@ export class ChatApp {
8097
8122
  return rows.slice(start, start + max)
8098
8123
  }
8099
8124
 
8100
- // every extra input row costs the transcript one: the frame stays exactly as tall as the terminal
8101
- _fitViewport(inputRows) {
8102
- const height = Math.max(1, this.height - CHROME_ROWS - (inputRows - 1))
8125
+ _fitViewport(inputRows, bannerRows = 0) {
8126
+ const height = Math.max(1, this.height - CHROME_ROWS - (inputRows - 1) - bannerRows)
8103
8127
  if (this.vp.height === height) {
8104
8128
  return
8105
8129
  }
@@ -8235,7 +8259,17 @@ export class ChatApp {
8235
8259
  .render(title.slice(0, Math.max(0, this.width - 4)))
8236
8260
 
8237
8261
  const inputRows = this._inputRows()
8238
- this._fitViewport(inputRows.length)
8262
+ if (this.updateBanner) {
8263
+ this.updateBanner.width = this.width - 4
8264
+ }
8265
+
8266
+ let banner = this.updateBanner?.view() ?? ''
8267
+ const bannerRows = banner ? banner.split('\n').length : 0
8268
+ if (this.height - CHROME_ROWS - (inputRows.length - 1) - bannerRows < 1) {
8269
+ banner = ''
8270
+ }
8271
+
8272
+ this._fitViewport(inputRows.length, banner ? bannerRows : 0)
8239
8273
  const lines = this._viewLines()
8240
8274
  const vpLines =
8241
8275
  this._selection?.region === 'transcript'
@@ -8275,7 +8309,9 @@ export class ChatApp {
8275
8309
  // a wrapped footer row shifts the whole frame and scrolls the header off — never let it wrap
8276
8310
  const footer = fg.dim.render(hints.slice(0, Math.max(0, this.width - 1)))
8277
8311
 
8278
- return [header, body, this._skillsLine(), inputBox, footer].join('\n')
8312
+ return [header, body, this._skillsLine(), inputBox, ...(banner ? [banner] : []), footer].join(
8313
+ '\n'
8314
+ )
8279
8315
  }
8280
8316
  }
8281
8317
 
package/tui/boot.mjs CHANGED
@@ -10,12 +10,28 @@ import { Logger, toLoggerOptions } from '../dist-lib/lib/log.js'
10
10
  import { configureSdkStorage } from '@qvac/harness/sdk-storage'
11
11
  import { MODEL_CACHE_PATH_ENV, releaseChannel, resolveStorage } from '@qvac/harness/storage'
12
12
  import sidecarRunner from 'bare-supervisor/runner/sidecar'
13
- import { skillsDir } from '@qvac/skills'
14
13
 
15
- const harnessEntry = new URL(import.meta.resolve('@qvac/harness/worker/stow-entry.mjs')).pathname
16
- const sidecarEntry = fileURLToPath(new URL('../worker/stow-entry.mjs', import.meta.url))
17
- if (!fs.existsSync(sidecarEntry)) {
18
- throw new Error(`assistant sidecar entry missing at ${sidecarEntry}`)
14
+ async function resolvePaths(entries) {
15
+ if (entries) {
16
+ return {
17
+ // make stages the skills tree beside release.json
18
+ skillsDir: path.join(path.dirname(fileURLToPath(entries.release)), 'skills'),
19
+ harnessEntry: fileURLToPath(entries.harness),
20
+ sidecarEntry: fileURLToPath(entries.sidecar)
21
+ }
22
+ }
23
+
24
+ const sidecarEntry = fileURLToPath(new URL('../worker/stow-entry.mjs', import.meta.url))
25
+ if (!fs.existsSync(sidecarEntry)) {
26
+ throw new Error(`assistant sidecar entry missing at ${sidecarEntry}`)
27
+ }
28
+
29
+ return {
30
+ // imported here, as at load it reads a path from import.meta.url, which a bundle does not have
31
+ skillsDir: (await import('@qvac/skills')).skillsDir,
32
+ harnessEntry: fileURLToPath(import.meta.resolve('@qvac/harness/worker/stow-entry.mjs')),
33
+ sidecarEntry
34
+ }
19
35
  }
20
36
 
21
37
  // its stdout/stderr are pipes so native model logs reach the logger rather than this tty
@@ -82,8 +98,9 @@ async function joined(engine) {
82
98
  }
83
99
 
84
100
  // --join and --device-join are the headless way in, /join the interactive one
85
- export async function boot(args) {
101
+ export async function boot(args, entries = null) {
86
102
  const joining = bootInvite(args)
103
+ const { skillsDir, harnessEntry, sidecarEntry } = await resolvePaths(entries)
87
104
  const connectStart = Date.now()
88
105
  // only an explicit QVAC_MODEL overrides, or resuming a shared mesh rewrites the desktop's agent
89
106
  const modelOverride = process.env.QVAC_MODEL || null
package/tui/cli.mjs ADDED
@@ -0,0 +1,93 @@
1
+ import fs from 'bare-fs'
2
+ import path from 'path'
3
+ import { fileURLToPath } from 'bare-url'
4
+ import { arg, command, description, flag, summary } from 'paparam'
5
+
6
+ const pluginsCommand = (name, info, ...modifiers) =>
7
+ command(name, summary(info), ...modifiers, async ({ args }) => {
8
+ const api = await import('./plugins.mjs')
9
+ try {
10
+ await api[name](...Object.values(args))
11
+ } catch (err) {
12
+ console.error(err.message)
13
+ Bare.exitCode = 1
14
+ }
15
+ })
16
+
17
+ const plugins = command(
18
+ 'plugins',
19
+ summary('list, enable, disable and install userland plugins in ~/.config/qv-ac'),
20
+ pluginsCommand('list', 'installed plugins and whether config.json loads them'),
21
+ pluginsCommand('enable', 'list a plugin in config.json', arg('<name>', 'plugin folder name')),
22
+ pluginsCommand(
23
+ 'disable',
24
+ 'drop a plugin from config.json, keeping its options',
25
+ arg('<name>', 'plugin folder name')
26
+ ),
27
+ pluginsCommand(
28
+ 'install',
29
+ 'fetch a plugin folder from a git URL or a hyper:// drive key',
30
+ arg('<source>', 'git URL or hyper://<key>'),
31
+ arg('[name]', 'folder name; defaults to the repo name, required for hyper://')
32
+ )
33
+ )
34
+
35
+ const cmd = command(
36
+ 'duck',
37
+ summary('the qvac assistant in your terminal'),
38
+ description(
39
+ "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."
40
+ ),
41
+ flag('--storage|-s [dir]', 'a self-contained root, its own corestore and SDK home'),
42
+ flag('--temp', 'the same, in a throwaway dir'),
43
+ flag('--headless', 'no TUI: print the device invite and stream logs until ctrl+C'),
44
+ flag('--join|-j <invite>', 'join a mesh as a new member at boot (a member invite)'),
45
+ flag(
46
+ '--device-join <invite>',
47
+ 'pair this device into the inviter’s account at boot (a device invite)'
48
+ ),
49
+ flag('--fake-models', 'adds the quack model: a deterministic fake LLM for testing without AI'),
50
+ flag('--version|-v', 'versions of core, harness and the SDK'),
51
+ plugins
52
+ )
53
+
54
+ function versions(entries) {
55
+ const resolved = entries
56
+ ? Object.entries(JSON.parse(fs.readFileSync(fileURLToPath(entries.release), 'utf8')).versions)
57
+ : [
58
+ ['@qvac/core', packageVersion(fileURLToPath(new URL('../package.json', import.meta.url)))],
59
+ ['@qvac/harness', resolvedVersion('@qvac/harness')],
60
+ ['@qvac/sdk', resolvedVersion('@qvac/sdk')]
61
+ ]
62
+
63
+ return resolved.map(([name, version]) => `${name.padEnd(14)} ${version}`).join('\n')
64
+ }
65
+
66
+ function resolvedVersion(specifier) {
67
+ const entry = fileURLToPath(import.meta.resolve(specifier))
68
+ for (let dir = path.dirname(entry); dir !== path.dirname(dir); dir = path.dirname(dir)) {
69
+ const manifest = path.join(dir, 'package.json')
70
+ if (fs.existsSync(manifest)) {
71
+ return packageVersion(manifest)
72
+ }
73
+ }
74
+
75
+ return 'unknown'
76
+ }
77
+
78
+ function packageVersion(manifest) {
79
+ return JSON.parse(fs.readFileSync(manifest, 'utf8')).version
80
+ }
81
+
82
+ export async function cli({ argv, standalone = false, entries = null } = {}) {
83
+ const parsed = cmd.parse(argv)
84
+ if (parsed !== cmd) {
85
+ return
86
+ }
87
+
88
+ if (parsed.flags.version) {
89
+ console.log(versions(entries))
90
+ } else {
91
+ ;(await import('./main.mjs')).main(parsed.flags, { standalone, entries })
92
+ }
93
+ }
package/tui/index.mjs CHANGED
@@ -1,89 +1,4 @@
1
1
  #!/usr/bin/env bare
2
- // the duck bin loads no engine, so --help and --version skip the module graph
3
- import fs from 'bare-fs'
4
- import path from 'path'
5
- import { arg, command, description, flag, summary } from 'paparam'
2
+ import { cli } from './cli.mjs'
6
3
 
7
- const pluginsCommand = (name, info, ...modifiers) =>
8
- command(name, summary(info), ...modifiers, async ({ args }) => {
9
- const api = await import('./plugins.mjs')
10
- try {
11
- await api[name](...Object.values(args))
12
- } catch (err) {
13
- console.error(err.message)
14
- Bare.exitCode = 1
15
- }
16
- })
17
-
18
- const plugins = command(
19
- 'plugins',
20
- summary('list, enable, disable and install userland plugins in ~/.config/qv-ac'),
21
- pluginsCommand('list', 'installed plugins and whether config.json loads them'),
22
- pluginsCommand('enable', 'list a plugin in config.json', arg('<name>', 'plugin folder name')),
23
- pluginsCommand(
24
- 'disable',
25
- 'drop a plugin from config.json, keeping its options',
26
- arg('<name>', 'plugin folder name')
27
- ),
28
- pluginsCommand(
29
- 'install',
30
- 'fetch a plugin folder from a git URL or a hyper:// drive key',
31
- arg('<source>', 'git URL or hyper://<key>'),
32
- arg('[name]', 'folder name; defaults to the repo name, required for hyper://')
33
- )
34
- )
35
-
36
- const cmd = command(
37
- 'duck',
38
- summary('the qvac assistant in your terminal'),
39
- description(
40
- "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."
41
- ),
42
- flag('--storage|-s [dir]', 'a self-contained root, its own corestore and SDK home'),
43
- flag('--temp', 'the same, in a throwaway dir'),
44
- flag('--headless', 'no TUI: print the device invite and stream logs until ctrl+C'),
45
- flag('--join|-j <invite>', 'join a mesh as a new member at boot (a member invite)'),
46
- flag(
47
- '--device-join <invite>',
48
- 'pair this device into the inviter’s account at boot (a device invite)'
49
- ),
50
- flag('--fake-models', 'adds the quack model: a deterministic fake LLM for testing without AI'),
51
- flag('--version|-v', 'versions of core, harness and the SDK'),
52
- plugins
53
- )
54
-
55
- function versions() {
56
- return [
57
- ['@qvac/core', packageVersion(new URL('../package.json', import.meta.url).pathname)],
58
- ['@qvac/harness', resolvedVersion('@qvac/harness')],
59
- ['@qvac/sdk', resolvedVersion('@qvac/sdk')]
60
- ]
61
- .map(([name, version]) => `${name.padEnd(14)} ${version}`)
62
- .join('\n')
63
- }
64
-
65
- function resolvedVersion(specifier) {
66
- const entry = new URL(import.meta.resolve(specifier)).pathname
67
- for (let dir = path.dirname(entry); dir !== path.dirname(dir); dir = path.dirname(dir)) {
68
- const manifest = path.join(dir, 'package.json')
69
- if (fs.existsSync(manifest)) {
70
- return packageVersion(manifest)
71
- }
72
- }
73
-
74
- return 'unknown'
75
- }
76
-
77
- function packageVersion(manifest) {
78
- return JSON.parse(fs.readFileSync(manifest, 'utf8')).version
79
- }
80
-
81
- const cli = cmd.parse()
82
-
83
- if (cli === cmd) {
84
- if (cli.flags.version) {
85
- console.log(versions())
86
- } else {
87
- ;(await import('./main.mjs')).main(cli.flags)
88
- }
89
- }
4
+ await cli()
@@ -0,0 +1,86 @@
1
+ import fs from 'bare-fs'
2
+ import os from 'bare-os'
3
+ import path from 'path'
4
+ import Corestore from 'corestore'
5
+ import Hyperswarm from 'hyperswarm'
6
+ import PearRuntimeUpdater from 'pear-runtime-updater'
7
+
8
+ export async function startUpdater(entries) {
9
+ const { version, upgrade } = JSON.parse(fs.readFileSync(new URL(entries.release), 'utf8'))
10
+ if (!upgrade) {
11
+ return null
12
+ }
13
+
14
+ const dir = appDir()
15
+ fs.mkdirSync(dir, { recursive: true })
16
+
17
+ const { default: LockFile } = await import('fs-native-lock')
18
+ const lock = new LockFile(path.join(dir, 'duck.lock'))
19
+ try {
20
+ await lock.lock()
21
+ } catch {
22
+ return null
23
+ }
24
+
25
+ const store = new Corestore(path.join(dir, 'pear-runtime', 'corestore'))
26
+ const swarm = new Hyperswarm()
27
+ swarm.on('connection', (connection) => store.replicate(connection))
28
+
29
+ const app = os.execPath()
30
+ const updater = new PearRuntimeUpdater({
31
+ // the next build is swapped in by rename, so it downloads onto the executable's own volume
32
+ dir: path.join(path.dirname(app), '.duck-update'),
33
+ store,
34
+ version,
35
+ upgrade,
36
+ app,
37
+ name: os.platform() === 'win32' ? 'duck.exe' : 'duck'
38
+ })
39
+ updater.on('error', () => {})
40
+
41
+ // updater.close() waits out a download that can no longer finish once the swarm is gone
42
+ const close = async () => {
43
+ await swarm.destroy()
44
+ await store.close()
45
+ await lock.unlock()
46
+ }
47
+
48
+ try {
49
+ await updater.ready()
50
+ } catch (err) {
51
+ await close()
52
+ throw err
53
+ }
54
+
55
+ swarm.join(updater.drive.core.discoveryKey)
56
+
57
+ return { updater, close }
58
+ }
59
+
60
+ export function applyUnattended(updater, log, onInstalled) {
61
+ // closing the store on shutdown cancels a download in flight, which is not a failed update
62
+ const fail = (err) => err.code === 'REQUEST_CANCELLED' || log(`update failed: ${err.message}`)
63
+ const apply = () =>
64
+ updater.applyUpdate().then(() => {
65
+ log(`update v${updater.nextVersion} installed, exiting for the supervisor to restart`)
66
+ onInstalled()
67
+ }, fail)
68
+
69
+ updater.on('updated', apply)
70
+ updater.on('error', fail)
71
+ if (updater.updated) {
72
+ apply()
73
+ }
74
+ }
75
+
76
+ function appDir() {
77
+ const home = os.homedir()
78
+ switch (os.platform()) {
79
+ case 'win32':
80
+ return path.join(home, 'AppData', 'Roaming', 'duck')
81
+ case 'darwin':
82
+ return path.join(home, 'Library', 'Application Support', 'duck')
83
+ default:
84
+ return path.join(home, '.config', 'duck')
85
+ }
86
+ }
package/tui/main.mjs CHANGED
@@ -1,15 +1,18 @@
1
1
  // the TUI itself: draws the first frame, then imports boot.mjs, the engine side, behind it
2
2
  import fs from 'bare-fs'
3
- import os from 'bare-os'
4
3
  import process from 'bare-process'
5
4
  import tui from 'bare-tui'
5
+ import pear from 'bare-tui-updater/pear'
6
6
  import { spawn } from 'child_process'
7
7
  import path from 'path'
8
8
  import { readBootTiming } from './lib/boot-timing.mjs'
9
+ import { resolveLocalPath } from './lib/local-path.mjs'
10
+ import { applyUnattended, startUpdater } from './lib/updater.mjs'
9
11
  import { ChatApp } from './app.mjs'
10
12
  import b4a from 'b4a'
11
13
 
12
14
  const { Program } = tui
15
+ const { wire } = pear
13
16
 
14
17
  // the terminal writes a real sequence in one read, so this only has to beat human perception
15
18
  const ESCAPE_TIMEOUT_MS = 50
@@ -160,7 +163,7 @@ async function resolvePastedFile() {
160
163
  return null
161
164
  }
162
165
 
163
- const file = expandFilePath(text)
166
+ const file = resolveLocalPath(text)
164
167
  let stat
165
168
  try {
166
169
  stat = fs.statSync(file)
@@ -177,12 +180,7 @@ async function resolvePastedFile() {
177
180
 
178
181
  // `/attach` resolver: a named path -> attachment; throws on a bad path.
179
182
  function resolveFileAttachment(pathString) {
180
- return fileToAttachment(expandFilePath(pathString))
181
- }
182
-
183
- function expandFilePath(text) {
184
- const file = text.startsWith('file://') ? decodeURI(text.slice('file://'.length)) : text
185
- return file.startsWith('~/') ? path.join(os.homedir(), file.slice(2)) : file
183
+ return fileToAttachment(resolveLocalPath(pathString))
186
184
  }
187
185
 
188
186
  function fileToAttachment(file, stat = fs.statSync(file)) {
@@ -208,21 +206,22 @@ function printBootTiming(booted) {
208
206
  console.log(`\nboot timing:\n${lines.join('\n')}`)
209
207
  }
210
208
 
211
- export function main(args) {
212
- run(args).catch((err) => {
209
+ export function main(args, { standalone = false, entries = null } = {}) {
210
+ run(args, standalone, entries).catch((err) => {
213
211
  console.error(err)
214
212
  Bare.exit(1)
215
213
  })
216
214
  }
217
215
 
218
- async function run(args) {
216
+ async function run(args, standalone, entries) {
217
+ const updates = standalone ? await startUpdater(entries) : null
219
218
  let program
220
219
  // the engine side, once it is up: its teardown, and what the boot report prints
221
220
  let booted = null
222
221
  // bring-up runs inside the TUI so its "starting up…" frame shows while ~1200 modules load
223
222
  const connect = async () => {
224
223
  const { boot } = await import('./boot.mjs')
225
- booted = await boot(args)
224
+ booted = await boot(args, entries)
226
225
  const { engine, skills, deviceId, meshInvite, modelName } = booted
227
226
 
228
227
  return { engine, skills, deviceId, meshInvite, modelName }
@@ -231,12 +230,18 @@ async function run(args) {
231
230
  // the engine's own handles hold the loop open until a signal arrives
232
231
  if (args.headless) {
233
232
  // armed before connect so a ctrl+C during a first-run model download still unwinds cleanly
234
- const shutdown = async () => {
233
+ const shutdown = async (code = 0) => {
234
+ await updates?.close()
235
235
  await booted?.close()
236
- Bare.exit(0)
236
+ Bare.exit(code)
237
237
  }
238
238
  process.on('SIGINT', () => void shutdown())
239
239
  process.on('SIGTERM', () => void shutdown())
240
+ if (updates) {
241
+ // 75 (EX_TEMPFAIL): non-zero, so Restart=on-failure brings the new build up too
242
+ applyUnattended(updates.updater, console.log, () => void shutdown(75))
243
+ }
244
+
240
245
  const { deviceId, meshInvite } = await connect()
241
246
  console.log(`storage ${booted.storagePath}`)
242
247
  console.log(`log ${booted.logFile}`)
@@ -252,10 +257,15 @@ async function run(args) {
252
257
  requestRepaint: () => requestRepaint(() => program),
253
258
  copyToClipboard: (text) => copyToClipboard(text).catch(() => copyViaTerminal(program, text)),
254
259
  resolvePastedFile,
255
- resolveFileAttachment
260
+ resolveFileAttachment,
261
+ applyUpdate: updates ? () => updates.updater.applyUpdate() : null
256
262
  })
257
263
  // the transcript selects its own text, since the terminal can't while mouse tracking is on
258
264
  program = new Program(app, { mouse: 'drag' })
265
+ if (updates) {
266
+ wire(app.updateBanner, { updater: updates.updater, send: (msg) => program.send(msg) })
267
+ }
268
+
259
269
  // bracketed paste, or each pasted line arrives as keys and submits itself
260
270
  program.output.write('\x1b[?2004h')
261
271
  try {
@@ -272,6 +282,7 @@ async function run(args) {
272
282
  program.output.write('\x1b[?2004l')
273
283
  }
274
284
 
285
+ await updates?.close()
275
286
  await booted?.close()
276
287
  printBootTiming(booted)
277
288
  // don't wait for the child to unwind a blocking native call; close() already tore the sidecar down
@@ -1,2 +0,0 @@
1
- import type { Mesh } from './mesh.ts';
2
- export declare function chatProject(chatMesh: Mesh, chatId: string, open: (projectId: string) => Promise<Mesh | null>): Promise<Mesh | null>;
@@ -1,15 +0,0 @@
1
- import { CHATS } from './collections.js';
2
- import { accountMember } from './contract/members.js';
3
- import { inProject } from './contract/projects.js';
4
- export async function chatProject(chatMesh, chatId, open) {
5
- if (chatMesh.role === 'project') {
6
- return chatMesh;
7
- }
8
- const chat = await chatMesh.view.get(CHATS, { id: chatId });
9
- const owner = chat?.projectId ? await accountMember(chatMesh.view) : null;
10
- const project = owner && chat?.projectId ? await open(chat.projectId) : null;
11
- if (!owner || project?.role !== 'project' || !(await inProject(project.view, owner))) {
12
- return null;
13
- }
14
- return project;
15
- }