@qvac/core 1.0.0-rc.6 → 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.
Files changed (67) hide show
  1. package/CHANGELOG.md +8 -1
  2. package/dist-lib/lib/api/agents.js +5 -2
  3. package/dist-lib/lib/api/approval-rules.js +8 -5
  4. package/dist-lib/lib/api/chat.d.ts +1 -2
  5. package/dist-lib/lib/api/chat.js +4 -18
  6. package/dist-lib/lib/api/device-routes.d.ts +6 -1
  7. package/dist-lib/lib/api/device-routes.js +20 -1
  8. package/dist-lib/lib/api/index.d.ts +0 -1
  9. package/dist-lib/lib/api/index.js +1 -2
  10. package/dist-lib/lib/api/mesh.d.ts +1 -1
  11. package/dist-lib/lib/api/mesh.js +1 -1
  12. package/dist-lib/lib/api/rag.js +2 -5
  13. package/dist-lib/lib/api/sync.js +12 -2
  14. package/dist-lib/lib/assistant/model-round.d.ts +7 -1
  15. package/dist-lib/lib/assistant/model-round.js +33 -11
  16. package/dist-lib/lib/assistant-tree.js +7 -0
  17. package/dist-lib/lib/assistant.d.ts +3 -2
  18. package/dist-lib/lib/assistant.js +20 -19
  19. package/dist-lib/lib/core/archived-mesh.d.ts +1 -0
  20. package/dist-lib/lib/core/archived-mesh.js +11 -14
  21. package/dist-lib/lib/core/chat-copy.d.ts +0 -1
  22. package/dist-lib/lib/core/chat-copy.js +1 -2
  23. package/dist-lib/lib/core/chat-move.d.ts +3 -1
  24. package/dist-lib/lib/core/chat-move.js +5 -2
  25. package/dist-lib/lib/core/contract/joined-meshes.js +2 -1
  26. package/dist-lib/lib/core/local/index.d.ts +2 -1
  27. package/dist-lib/lib/core/local/index.js +3 -2
  28. package/dist-lib/lib/core/public-mesh.d.ts +6 -8
  29. package/dist-lib/lib/core/public-mesh.js +19 -29
  30. package/dist-lib/lib/core/sync/index.js +1 -1
  31. package/dist-lib/lib/core.d.ts +21 -8
  32. package/dist-lib/lib/core.js +233 -204
  33. package/dist-lib/lib/errors.d.ts +8 -12
  34. package/dist-lib/lib/errors.js +8 -12
  35. package/dist-lib/lib/model-download.d.ts +6 -1
  36. package/dist-lib/lib/model-download.js +16 -3
  37. package/dist-lib/lib/oauth/resolve.js +29 -8
  38. package/dist-lib/lib/oauth/token-exchange-core.js +11 -0
  39. package/dist-lib/schema/engine.js +10 -3
  40. package/dist-lib/schema/local.js +4 -2
  41. package/dist-lib/schema/qvac.js +2 -1
  42. package/dist-lib/spec/capabilities.d.ts +2 -2
  43. package/dist-lib/spec/hrpc/hrpc.json +1 -1
  44. package/dist-lib/spec/hrpc/index.js +1 -1
  45. package/dist-lib/spec/hrpc/messages.js +273 -250
  46. package/dist-lib/spec/hyperschema/index.js +273 -250
  47. package/dist-lib/spec/hyperschema/schema.json +27 -6
  48. package/dist-lib/spec/hyperschema/types.d.ts +7 -1
  49. package/dist-lib/spec/local/hyperdb/messages.js +26 -12
  50. package/dist-lib/spec/local/hyperschema/index.js +13 -6
  51. package/dist-lib/spec/local/hyperschema/schema.json +10 -0
  52. package/dist-lib/spec/local/hyperschema/types.d.ts +2 -0
  53. package/dist-lib/spec/mesh/hyperdb/messages.js +30 -6
  54. package/dist-lib/spec/mesh/hyperdispatch/messages.js +15 -3
  55. package/dist-lib/spec/mesh/hyperschema/index.js +15 -3
  56. package/dist-lib/spec/mesh/hyperschema/schema.json +5 -0
  57. package/dist-lib/spec/mesh/hyperschema/types.d.ts +1 -0
  58. package/package.json +10 -4
  59. package/tui/README.md +51 -0
  60. package/tui/app.mjs +88 -17
  61. package/tui/boot.mjs +23 -6
  62. package/tui/cli.mjs +93 -0
  63. package/tui/index.mjs +2 -87
  64. package/tui/lib/updater.mjs +86 -0
  65. package/tui/main.mjs +26 -15
  66. package/dist-lib/lib/core/chat-project.d.ts +0 -2
  67. package/dist-lib/lib/core/chat-project.js +0 -15
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'
@@ -283,7 +284,7 @@ const COMMANDS = [
283
284
  palette: true,
284
285
  sub: [
285
286
  { name: 'use', desc: '<n|id> — make one of your meshes the active one' },
286
- { name: 'new', desc: 'open another shared mesh' },
287
+ { name: 'new', desc: 'create a workspace' },
287
288
  { name: 'label', desc: '<n|id> <name> — name a mesh, privately to you' },
288
289
  { name: 'move', desc: '<n|id> [chat] — move this chat, or a named one, into another mesh' },
289
290
  { name: 'moved', desc: '[chat] — how the last move from this window is going' },
@@ -1742,8 +1743,9 @@ const isOwnDefault = (agent, deviceId) =>
1742
1743
  b4a.equals(agent.providerDeviceId, deviceId)
1743
1744
  const ownDefault = (agents, deviceId) => agents.find((agent) => isOwnDefault(agent, deviceId))
1744
1745
 
1745
- // deviceInfo carries no model: the recommendation lives on the device's own row in the mesh
1746
- async function recommendedModel(engine, meshId, deviceId) {
1746
+ // deviceInfo carries no model: the recommendation lives on the device's own row in the account
1747
+ async function recommendedModel(engine, deviceId) {
1748
+ const meshId = await accountMeshId(engine)
1747
1749
  return (await engine.getDevice({ meshId, deviceId })).recommendedModelName
1748
1750
  }
1749
1751
 
@@ -1793,7 +1795,7 @@ async function firstAgent(engine, meshId, { deviceId, modelName, remembered, acc
1793
1795
  name: 'QV.AC',
1794
1796
  bio: 'You are a helpful local assistant. Be clear, practical, and concise.',
1795
1797
  providerDeviceId: deviceId,
1796
- modelName: modelName || (await recommendedModel(engine, meshId, deviceId)),
1798
+ modelName: modelName || (await recommendedModel(engine, deviceId)),
1797
1799
  isDefault: true
1798
1800
  }
1799
1801
  })
@@ -1835,7 +1837,28 @@ async function firstChat(engine, meshId, { agent, remembered, account }) {
1835
1837
  return engine.createChat({ meshId, agentId: agent.id, config: { title: 'New Chat' } })
1836
1838
  }
1837
1839
 
1838
- // the account, where a window starts; a kicked device has none until Core adopts or mints the next
1840
+ const NO_WORKSPACE = 'you are in no workspace - /mesh new creates one, /join <invite> joins one'
1841
+
1842
+ // the workspace a window opens on: the last chat's if still listed, else the first, else none
1843
+ async function windowWorkspace(engine) {
1844
+ // from joined on, an empty list means no workspace rather than one still being minted
1845
+ for await (const status of engine.meshStatusWatch?.({}) ?? []) {
1846
+ if (status.state === 'joined') break
1847
+ }
1848
+
1849
+ const { meshes } = await engine.listMeshes({})
1850
+ const workspaces = (meshes ?? []).filter((mesh) => mesh.workspace)
1851
+ const config = engine.getConfig ? await engine.getConfig({}) : null
1852
+ for (const { meshId } of config?.activeChatId ? workspaces : []) {
1853
+ if (await engine.getChat({ meshId, chatId: config.activeChatId }).catch(() => null)) {
1854
+ return meshId
1855
+ }
1856
+ }
1857
+
1858
+ return workspaces[0]?.meshId ?? null
1859
+ }
1860
+
1861
+ // the account, where agents and devices live; a kicked device has none until Core mints the next
1839
1862
  async function accountMeshId(engine) {
1840
1863
  for await (const account of engine.accountWatch({})) {
1841
1864
  if (account.meshId) return account.meshId
@@ -1870,6 +1893,7 @@ export class ChatApp {
1870
1893
  copyToClipboard,
1871
1894
  resolvePastedFile,
1872
1895
  resolveFileAttachment,
1896
+ applyUpdate,
1873
1897
  saveDir,
1874
1898
  skills,
1875
1899
  openUrl
@@ -1898,6 +1922,9 @@ export class ChatApp {
1898
1922
  this._resolvePastedFile = resolvePastedFile || null
1899
1923
  // `/attach <path>` resolver: named path -> attachment, or throws.
1900
1924
  this._resolveFileAttachment = resolveFileAttachment || null
1925
+ this.updateBanner = applyUpdate
1926
+ ? updateBanner.create({ onAccept: applyUpdate, acceptKey: 'ctrl+u' })
1927
+ : null
1901
1928
  this._selection = null // { anchor, focus, edge } in content cells, while a drag selects text
1902
1929
  this._dragToken = 0 // stale-guards the edge auto-scroll beats
1903
1930
  this._saveDir = saveDir || path.join(os.homedir(), 'Downloads')
@@ -2011,7 +2038,8 @@ export class ChatApp {
2011
2038
  _resolveAccount() {
2012
2039
  return async () => {
2013
2040
  try {
2014
- return { type: 'mesh.account', meshId: await accountMeshId(this.engine) }
2041
+ const meshId = await windowWorkspace(this.engine)
2042
+ return meshId ? { type: 'mesh.account', meshId } : { type: 'mesh.none' }
2015
2043
  } catch (error) {
2016
2044
  return { type: 'boot-error', error }
2017
2045
  }
@@ -2033,14 +2061,15 @@ export class ChatApp {
2033
2061
  _bootstrap() {
2034
2062
  return async () => {
2035
2063
  try {
2036
- const { account } = await firstWritable(this.engine, this.meshId)
2064
+ // a chat names a workspace now, so the first agent and chat are minted in one as in the account
2065
+ const { account, workspace } = await firstWritable(this.engine, this.meshId)
2037
2066
  // the pick the last session persisted; null on a fake engine that has no config
2038
2067
  const config = this.engine.getConfig ? await this.engine.getConfig({}) : null
2039
2068
  let agent = await firstAgent(this.engine, this.meshId, {
2040
2069
  deviceId: this.originDeviceId,
2041
2070
  modelName: this._modelName,
2042
2071
  remembered: config?.activeAgentId,
2043
- account
2072
+ account: account || workspace
2044
2073
  })
2045
2074
  if (!agent) {
2046
2075
  return { type: 'booted', agent: null, chat: null, remembered: false }
@@ -2060,7 +2089,7 @@ export class ChatApp {
2060
2089
  const chat = await firstChat(this.engine, this.meshId, {
2061
2090
  agent,
2062
2091
  remembered: config?.activeChatId,
2063
- account
2092
+ account: account || workspace
2064
2093
  })
2065
2094
  if (!chat) {
2066
2095
  return { type: 'booted', agent, chat: null, remembered: false }
@@ -3100,7 +3129,7 @@ export class ChatApp {
3100
3129
  modelName:
3101
3130
  agent?.modelName ??
3102
3131
  this._modelName ??
3103
- (await recommendedModel(engine, this.meshId, this.originDeviceId))
3132
+ (await recommendedModel(engine, this.originDeviceId))
3104
3133
  }
3105
3134
  })
3106
3135
  await this._handChatTo(created)
@@ -3705,7 +3734,7 @@ export class ChatApp {
3705
3734
 
3706
3735
  if (action === 'new') {
3707
3736
  return run(async () => {
3708
- const { meshId } = await engine.createMesh({ config: {} })
3737
+ const { meshId } = await engine.createWorkspace({ config: { name: 'Workspace' } })
3709
3738
  const invite = '/invite member <n|id> invites someone into it'
3710
3739
  return `${await this._meshHeading(meshId)}\n${invite}`
3711
3740
  })
@@ -6888,6 +6917,14 @@ export class ChatApp {
6888
6917
  return [this, this._enterMesh()]
6889
6918
  }
6890
6919
 
6920
+ if (msg.type === 'mesh.none') {
6921
+ this._booting = false
6922
+ this.status = ''
6923
+ this.notice = NO_WORKSPACE
6924
+ this._render()
6925
+ return [this, null]
6926
+ }
6927
+
6891
6928
  if (msg.type === 'meshes') {
6892
6929
  const ids = new Set(msg.meshes.map((mesh) => mesh.meshId))
6893
6930
  // a mesh transition in flight moves the window itself
@@ -6895,13 +6932,16 @@ export class ChatApp {
6895
6932
  // only the startup frame: a later closed mesh was closed on purpose
6896
6933
  const first = this._meshIds === null
6897
6934
  this._meshIds = ids
6935
+ // a window in no workspace opens the first one created or joined
6936
+ const arrived = !this.meshId && !this._booting && msg.meshes.some((mesh) => mesh.workspace)
6898
6937
 
6899
6938
  return [
6900
6939
  this,
6901
6940
  batch(
6902
6941
  this._watchNextMeshes(),
6903
6942
  lost ? this._lostMesh(this.meshId) : null,
6904
- first ? this._reopenMeshes(msg.meshes) : null
6943
+ first ? this._reopenMeshes(msg.meshes) : null,
6944
+ arrived ? this._enterMesh() : null
6905
6945
  )
6906
6946
  ]
6907
6947
  }
@@ -7350,6 +7390,15 @@ export class ChatApp {
7350
7390
  return [this, null]
7351
7391
  }
7352
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
+
7353
7402
  if (msg.type === 'spinner.tick') {
7354
7403
  const [s, cmd] = this.spin.update(msg)
7355
7404
  this.spin = s
@@ -7479,6 +7528,12 @@ export class ChatApp {
7479
7528
  return this._toggleToolOutput()
7480
7529
  }
7481
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
+
7482
7537
  // typing dismisses an overlay into the input; other keys are swallowed so they can't leak through
7483
7538
  if (this._models || this._selector || this.overlay || this._menu) {
7484
7539
  const handled = this._overlayKey(msg)
@@ -7524,6 +7579,11 @@ export class ChatApp {
7524
7579
 
7525
7580
  return [this, null]
7526
7581
  }
7582
+
7583
+ if (['ready', 'applied', 'error'].includes(this.updateBanner?.state)) {
7584
+ this.updateBanner.update({ type: 'update.dismiss' })
7585
+ return [this, null]
7586
+ }
7527
7587
  }
7528
7588
 
7529
7589
  if (this.pendingApproval) {
@@ -8062,9 +8122,8 @@ export class ChatApp {
8062
8122
  return rows.slice(start, start + max)
8063
8123
  }
8064
8124
 
8065
- // every extra input row costs the transcript one: the frame stays exactly as tall as the terminal
8066
- _fitViewport(inputRows) {
8067
- 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)
8068
8127
  if (this.vp.height === height) {
8069
8128
  return
8070
8129
  }
@@ -8200,7 +8259,17 @@ export class ChatApp {
8200
8259
  .render(title.slice(0, Math.max(0, this.width - 4)))
8201
8260
 
8202
8261
  const inputRows = this._inputRows()
8203
- 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)
8204
8273
  const lines = this._viewLines()
8205
8274
  const vpLines =
8206
8275
  this._selection?.region === 'transcript'
@@ -8240,7 +8309,9 @@ export class ChatApp {
8240
8309
  // a wrapped footer row shifts the whole frame and scrolls the header off — never let it wrap
8241
8310
  const footer = fg.dim.render(hints.slice(0, Math.max(0, this.width - 1)))
8242
8311
 
8243
- return [header, body, this._skillsLine(), inputBox, footer].join('\n')
8312
+ return [header, body, this._skillsLine(), inputBox, ...(banner ? [banner] : []), footer].join(
8313
+ '\n'
8314
+ )
8244
8315
  }
8245
8316
  }
8246
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>;