@qvac/core 0.1.5 → 0.2.0

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 (100) hide show
  1. package/.claude/skills/compaction/SKILL.md +1 -1
  2. package/.claude/skills/gh-stack/SKILL.md +24 -24
  3. package/.claude/skills/gh-stack/references/commands.md +2 -2
  4. package/.claude/skills/js-house-style/SKILL.md +1 -1
  5. package/.claude/skills/pr-create/SKILL.md +46 -3
  6. package/.claude/skills/pr-review/SKILL.md +76 -7
  7. package/CLAUDE.md +3 -0
  8. package/README.md +10 -5
  9. package/dist-lib/lib/api/agents.js +3 -3
  10. package/dist-lib/lib/api/chat-groups.d.ts +1 -1
  11. package/dist-lib/lib/api/chat-groups.js +5 -3
  12. package/dist-lib/lib/api/chat.js +2 -2
  13. package/dist-lib/lib/api/current-mesh.d.ts +3 -2
  14. package/dist-lib/lib/api/current-mesh.js +4 -3
  15. package/dist-lib/lib/api/devices.js +1 -0
  16. package/dist-lib/lib/api/index.js +2 -0
  17. package/dist-lib/lib/api/members.d.ts +3 -0
  18. package/dist-lib/lib/api/members.js +23 -0
  19. package/dist-lib/lib/api/mesh.d.ts +14 -3
  20. package/dist-lib/lib/api/mesh.js +20 -3
  21. package/dist-lib/lib/api/watchable.d.ts +1 -1
  22. package/dist-lib/lib/api/watchable.js +1 -1
  23. package/dist-lib/lib/core/agent.d.ts +1 -0
  24. package/dist-lib/lib/core/agent.js +29 -1
  25. package/dist-lib/lib/core/chat-group.d.ts +4 -0
  26. package/dist-lib/lib/core/chat-group.js +43 -1
  27. package/dist-lib/lib/core/chat.d.ts +10 -0
  28. package/dist-lib/lib/core/chat.js +75 -9
  29. package/dist-lib/lib/core/contract/index.js +2 -0
  30. package/dist-lib/lib/core/contract/joined-meshes.d.ts +2 -0
  31. package/dist-lib/lib/core/contract/joined-meshes.js +41 -0
  32. package/dist-lib/lib/core/contract/members.js +68 -2
  33. package/dist-lib/lib/core/contract/writers.js +19 -3
  34. package/dist-lib/lib/core/departures.d.ts +3 -1
  35. package/dist-lib/lib/core/departures.js +6 -4
  36. package/dist-lib/lib/core/device-attestation.d.ts +8 -0
  37. package/dist-lib/lib/core/device-attestation.js +25 -0
  38. package/dist-lib/lib/core/device-invites.d.ts +9 -0
  39. package/dist-lib/lib/core/device-invites.js +40 -0
  40. package/dist-lib/lib/core/files/index.d.ts +2 -1
  41. package/dist-lib/lib/core/files/index.js +1 -1
  42. package/dist-lib/lib/core/files/store/index.d.ts +1 -0
  43. package/dist-lib/lib/core/files/store/server.d.ts +5 -4
  44. package/dist-lib/lib/core/files/store/server.js +10 -6
  45. package/dist-lib/lib/core/helpers/index.d.ts +1 -1
  46. package/dist-lib/lib/core/hosted-agents.d.ts +3 -1
  47. package/dist-lib/lib/core/hosted-agents.js +9 -3
  48. package/dist-lib/lib/core/identity.d.ts +10 -0
  49. package/dist-lib/lib/core/identity.js +45 -0
  50. package/dist-lib/lib/core/invite.d.ts +3 -0
  51. package/dist-lib/lib/core/invite.js +8 -2
  52. package/dist-lib/lib/core/local/index.d.ts +22 -7
  53. package/dist-lib/lib/core/local/index.js +202 -66
  54. package/dist-lib/lib/core/membership.d.ts +8 -2
  55. package/dist-lib/lib/core/membership.js +33 -9
  56. package/dist-lib/lib/core/mesh-seed-handoff.d.ts +17 -0
  57. package/dist-lib/lib/core/mesh-seed-handoff.js +34 -0
  58. package/dist-lib/lib/core/mesh.d.ts +12 -1
  59. package/dist-lib/lib/core/mesh.js +36 -7
  60. package/dist-lib/lib/core/migrations/index.d.ts +3 -1
  61. package/dist-lib/lib/core/migrations/index.js +2 -2
  62. package/dist-lib/lib/core/migrations/membership.js +27 -15
  63. package/dist-lib/lib/core/rank.d.ts +14 -0
  64. package/dist-lib/lib/core/rank.js +23 -0
  65. package/dist-lib/lib/core/sync/index.js +6 -0
  66. package/dist-lib/lib/core.d.ts +91 -13
  67. package/dist-lib/lib/core.js +1051 -207
  68. package/dist-lib/schema/build.js +3 -2
  69. package/dist-lib/schema/engine.js +153 -9
  70. package/dist-lib/schema/field-order.js +4 -1
  71. package/dist-lib/schema/local.js +32 -0
  72. package/dist-lib/schema/qvac.js +45 -6
  73. package/dist-lib/spec/bind.js +35 -0
  74. package/dist-lib/spec/calls.js +37 -27
  75. package/dist-lib/spec/capabilities.d.ts +30 -10
  76. package/dist-lib/spec/hrpc/hrpc.json +135 -5
  77. package/dist-lib/spec/hrpc/index.js +130 -9
  78. package/dist-lib/spec/hrpc/messages.js +408 -14
  79. package/dist-lib/spec/hyperschema/index.js +408 -14
  80. package/dist-lib/spec/hyperschema/schema.json +309 -1
  81. package/dist-lib/spec/hyperschema/types.d.ts +90 -1
  82. package/dist-lib/spec/local/hyperdb/db.json +46 -1
  83. package/dist-lib/spec/local/hyperdb/index.js +209 -2
  84. package/dist-lib/spec/local/hyperdb/messages.js +557 -90
  85. package/dist-lib/spec/local/hyperschema/index.js +240 -2
  86. package/dist-lib/spec/local/hyperschema/schema.json +120 -1
  87. package/dist-lib/spec/local/hyperschema/types.d.ts +33 -1
  88. package/dist-lib/spec/mesh/hyperdb/db.json +16 -1
  89. package/dist-lib/spec/mesh/hyperdb/index.js +71 -2
  90. package/dist-lib/spec/mesh/hyperdb/messages.js +571 -192
  91. package/dist-lib/spec/mesh/hyperdispatch/dispatch.json +13 -1
  92. package/dist-lib/spec/mesh/hyperdispatch/index.js +35 -1
  93. package/dist-lib/spec/mesh/hyperdispatch/messages.js +283 -20
  94. package/dist-lib/spec/mesh/hyperschema/index.js +283 -20
  95. package/dist-lib/spec/mesh/hyperschema/schema.json +179 -1
  96. package/dist-lib/spec/mesh/hyperschema/types.d.ts +45 -1
  97. package/package.json +5 -5
  98. package/tui/app.mjs +416 -50
  99. package/tui/boot.mjs +1 -1
  100. package/tui/lib/sidebar.mjs +3 -2
package/tui/app.mjs CHANGED
@@ -119,6 +119,19 @@ const COMMANDS = [
119
119
  palette: true
120
120
  },
121
121
  { name: 'join', desc: "join another device's mesh with its invite (replaces this one)" },
122
+ {
123
+ name: 'invite',
124
+ desc: 'show this mesh device invite - /invite member opens your shared room and invites someone into it (your account is never shared)',
125
+ palette: true
126
+ },
127
+ { name: 'members', desc: 'list mesh members with their devices grouped', palette: true },
128
+ // before `meshes`, so a bare /mesh offers the verb first and the list second
129
+ {
130
+ name: 'mesh',
131
+ desc: 'switch which mesh is the active one, open another, or name one',
132
+ palette: true
133
+ },
134
+ { name: 'meshes', desc: 'list the meshes this device belongs to', palette: true },
122
135
  { name: 'cred', desc: 'set a credential value for this agent' },
123
136
  { name: 'connect', desc: 'OAuth-connect a skill for this agent' },
124
137
  {
@@ -778,24 +791,95 @@ export function renderSkill(s) {
778
791
  return lines.join('\n')
779
792
  }
780
793
 
781
- // The mesh seeds its default agent at birth and a joiner waits for it to
782
- // replicate — resolves on the first agent the mesh yields (agentsWatch fires on
783
- // every change, no polling).
784
- async function firstAgent(engine) {
785
- for await (const frame of engine.agentsWatch({})) {
786
- if (frame.agents?.length) return frame.agents[0]
794
+ // What a member invite actually gives away. None of it is fixable by a kick or a filter, so it
795
+ // is said out loud every time an invite is issued rather than documented somewhere.
796
+ const MEMBER_INVITE_DISCLOSURES = [
797
+ 'everyone ever admitted to this room holds its key material for good - a kick revokes a writer, never the key',
798
+ 'a later invitee replays the whole history of the room, including what earlier invitees wrote',
799
+ 'co-members see each of your devices: name, platform, app version, installed tools, skills, models and tool catalog',
800
+ 'and today a co-member approval rule governs your tool calls in this room (tracked separately)'
801
+ ]
802
+
803
+ // A mesh has no name, only its 64-char key, so the list is read by its number:
804
+ // `/mesh use <n>` takes the same index.
805
+ // `shared` is occupancy, not the registry marker: what the user wants to know is which of these
806
+ // meshes has somebody else in it.
807
+ function formatMeshes(meshes) {
808
+ if (!meshes.length) return 'no meshes yet - this device is still opening its own'
809
+ const rows = meshes.map((mesh, index) => {
810
+ const tags = [
811
+ mesh.home ? 'account' : null,
812
+ !mesh.home && mesh.members > 1 ? 'shared' : null,
813
+ mesh.open ? 'open' : 'closed'
814
+ ]
815
+ if (mesh.open) tags.push(mesh.writable ? 'writable' : 'read-only')
816
+ const marker = mesh.active ? '* ' : ' '
817
+ const name = mesh.label ? `${mesh.meshId.slice(0, 8)} "${mesh.label}"` : mesh.meshId.slice(0, 8)
818
+ return `${marker}${index + 1}. ${name} · ${tags.filter(Boolean).join(' · ')}`
819
+ })
820
+ return [...rows, '* = active · /mesh use <n|id> switches'].join('\n')
821
+ }
822
+
823
+ // Same selector shape as /knowledge: a list number, a full id, or a unique prefix.
824
+ function resolveMesh(meshes, selector) {
825
+ const exact = meshes.find((mesh) => mesh.meshId === selector)
826
+ if (exact) return { mesh: exact }
827
+ if (/^\d+$/.test(selector)) {
828
+ const index = Number(selector) - 1
829
+ return meshes[index] ? { mesh: meshes[index] } : { error: `no mesh #${selector}` }
830
+ }
831
+ const matches = meshes.filter((mesh) => mesh.meshId.startsWith(selector))
832
+ if (matches.length === 1) return { mesh: matches[0] }
833
+ if (matches.length > 1) return { error: `ambiguous mesh id: ${selector}` }
834
+ return { error: `no mesh matching: ${selector}` }
835
+ }
836
+
837
+ // How long a bootstrap waits for the mesh's own seed to replicate before minting its own.
838
+ const SEED_REPLICATION_MS = 10_000
839
+
840
+ // The mesh seeds its default agent at birth and a joiner waits for it to replicate - watch-driven
841
+ // (agentsWatch fires on every change), no polling. This device mints one as a fallback if none
842
+ // shows within the timeout: an unbounded wait here blocks the composer for good, and a mesh can
843
+ // legitimately hold no agent - one nobody has reached yet, or one whose every agent was deleted.
844
+ async function firstAgent(engine, deviceId, modelName) {
845
+ const watch = engine.agentsWatch({})[Symbol.asyncIterator]()
846
+ let timer
847
+ const timeout = new Promise((resolve) => {
848
+ timer = setTimeout(resolve, SEED_REPLICATION_MS, { done: true })
849
+ })
850
+ try {
851
+ while (true) {
852
+ const { value, done } = await Promise.race([watch.next(), timeout])
853
+ if (done) break
854
+ const live = value.agents?.[0]
855
+ if (live) return live
856
+ }
857
+ } finally {
858
+ clearTimeout(timer)
859
+ await watch.return?.()
787
860
  }
788
- throw new Error('agent stream ended before an agent replicated')
861
+ if (!deviceId) throw new Error('no agent replicated before timeout')
862
+ // The same name, bio, model and isDefault the genesis seed uses, so a minted agent and a
863
+ // replicated one are indistinguishable to the user - and isDefault above all, because Core
864
+ // seeds a per-member default of its own and counts only defaults. Without it these two
865
+ // seeders race the same gap with different bounds and the user ends up with two QV.ACs.
866
+ return engine.createAgent({
867
+ name: 'QV.AC',
868
+ bio: 'You are a helpful local assistant. Be clear, practical, and concise.',
869
+ providerDeviceId: deviceId,
870
+ modelName: modelName || (await engine.deviceInfo({})).recommendedModelName,
871
+ isDefault: true
872
+ })
789
873
  }
790
874
 
791
- // The birth op seeds a default chat too; a joiner waits for it to replicate —
875
+ // The birth op seeds a default chat too; a joiner waits for it to replicate -
792
876
  // watch-driven like firstAgent (chatsWatch), no polling. The provider mints one
793
877
  // as a fallback if none shows within the timeout.
794
878
  async function firstChat(engine, agent, isProvider) {
795
879
  const watch = engine.chatsWatch({})[Symbol.asyncIterator]()
796
880
  let timer
797
881
  const timeout = new Promise((resolve) => {
798
- timer = setTimeout(resolve, 10_000, { done: true })
882
+ timer = setTimeout(resolve, SEED_REPLICATION_MS, { done: true })
799
883
  })
800
884
  try {
801
885
  while (true) {
@@ -907,6 +991,8 @@ export class ChatApp {
907
991
  this.meshStatus = null // last meshStatusWatch frame — rendered in the header
908
992
  this._devicesIterator = null
909
993
  this.deviceLabels = new Map() // hex device id → name, from devicesWatch
994
+ this.deviceMembers = new Map() // hex device id → hex member id, from the same frames
995
+ this.memberNames = new Map() // hex member id → name, refreshed when a new member appears
910
996
  this.diagnostics = null
911
997
  this._diagnosticsIterator = null
912
998
  this.overlay = null
@@ -998,7 +1084,7 @@ export class ChatApp {
998
1084
  return async () => {
999
1085
  try {
1000
1086
  await firstWritable(this.engine)
1001
- let agent = await firstAgent(this.engine)
1087
+ let agent = await firstAgent(this.engine, this.originDeviceId, this._modelName)
1002
1088
  const isProvider = agent.providerDeviceId?.equals(this.originDeviceId) ?? false
1003
1089
  if (isProvider && this._modelName) {
1004
1090
  // Only set the model — scopes stay as the shared seed left them
@@ -1085,6 +1171,28 @@ export class ChatApp {
1085
1171
  // Device names for the per-device user labels — same re-arm/stale-guard
1086
1172
  // shape as the other watch loops. Null when the engine lacks the
1087
1173
  // capability (e.g. a headless test fake).
1174
+ _refreshMembersCmd() {
1175
+ const gen = this.gen
1176
+ return async () => {
1177
+ try {
1178
+ const res = await this.engine.listMembers({})
1179
+ return { type: 'members.frame', gen, members: res.members ?? [] }
1180
+ } catch {
1181
+ return { type: 'members.frame', gen, members: [] }
1182
+ }
1183
+ }
1184
+ }
1185
+
1186
+ _turnLabels() {
1187
+ if (this.memberNames.size < 2) return this.deviceLabels
1188
+ const labels = new Map()
1189
+ for (const [id, name] of this.deviceLabels) {
1190
+ const member = this.memberNames.get(this.deviceMembers.get(id) ?? '')
1191
+ labels.set(id, member ? `${member} · ${name}` : `${name} · unlinked`)
1192
+ }
1193
+ return labels
1194
+ }
1195
+
1088
1196
  _watchNextDevices() {
1089
1197
  if (!this.engine.devicesWatch) return null
1090
1198
  const gen = this.gen
@@ -1221,9 +1329,10 @@ export class ChatApp {
1221
1329
  // the old offset to the new max and read as "not at bottom" for every
1222
1330
  // single append — defeating auto-scroll entirely.
1223
1331
  const wasAtBottom = this.vp.atBottom
1332
+ const labels = this._turnLabels()
1224
1333
  const lines = this._turns
1225
1334
  .map((t) =>
1226
- renderTurn(t, this.agent.name, this.deviceLabels, {
1335
+ renderTurn(t, this.agent.name, labels, {
1227
1336
  expandTools: this._expandTools,
1228
1337
  width: this._bodyWidth()
1229
1338
  })
@@ -1273,15 +1382,16 @@ export class ChatApp {
1273
1382
  const HELP = [
1274
1383
  'Chat',
1275
1384
  ' /menu — open the navigable menu (Agent, Chat, Models, Voice, …); also ctrl+p, arrows + enter to browse',
1276
- ' ctrl+b — the chats sidebar: ↑/↓ walks it, enter opens a chat, m moves one to a group, esc closes',
1385
+ ' ctrl+b — the chats sidebar: ↑/↓ walks it, enter opens a chat, m moves one to a group, shift+↑/↓ reorders it, esc closes',
1277
1386
  ' esc — stop the run in flight, or clear the last command’s output',
1278
1387
  ' ctrl+o — expand the tool call/result previews (a click on a preview’s marker does the same)',
1279
1388
  ' /new-chat — create and switch to a new chat (shortcut for /chat new)',
1280
1389
  ' /chats — pick from your chats to switch (interactive) · /chat — show current',
1281
1390
  ' /chat new [title] · /chat use <title|id> · /chat rename <title> · /chat del <title|id> · /chat websearch on|off · /chat rag on|off',
1282
- ' /group — the sidebar as core orders it (groups, then ungrouped, each most-recently-active first)',
1391
+ ' /group — the sidebar as core orders it (groups, then ungrouped; a chat sits where it was dragged until it gets a message, then on top)',
1283
1392
  ' /group new <name> · /group rename <group> <name> · /group del <group> — quote any name containing spaces',
1284
- ' /group move <group> [chat] — move a chat into a group; the chat defaults to the active one, and - as the group ungroups it',
1393
+ ' /group move <group> [chat] [after <chat>|first] — move a chat into a group, optionally to a place in it; the chat defaults to the active one, and - as the group ungroups it',
1394
+ ' /group order <group> after <group>|first — reorder the groups themselves',
1285
1395
  ' /knowledge [list] · /knowledge add <file> · /knowledge add-dir <directory> · /knowledge download <n|id> · /knowledge remove <n|id>',
1286
1396
  ' /files — show upload progress, local readiness, and failures for this chat',
1287
1397
  ' /attach <path> [<path> …] — attach local files to this chat (quote paths that contain spaces)',
@@ -1314,6 +1424,11 @@ export class ChatApp {
1314
1424
  ' /cred <key> <value> — set a credential by hand for this agent (e.g. /cred github_access_token ghp_…); /skills, enter on the skill, fills this in for you',
1315
1425
  ' /scope skills|tools all|selected — switch scope',
1316
1426
  ' /join <qvac://mesh/…> — retire this device’s mesh and join that one (ctrl+y copies this mesh’s invite) · /join cancel — abort a join in progress',
1427
+ ' /invite - show this mesh device invite · /invite member - open your shared room and invite someone into it (your account is never shared)',
1428
+ ' /mesh new - open another shared room · /mesh label <n|id> <name> - name a room, privately to you',
1429
+ ' /members — list mesh members with their devices grouped',
1430
+ ' /meshes - list the meshes this device belongs to, numbered, marking account / shared / active / open / writable',
1431
+ ' /mesh use <n|id> - make one of them active; its agent, chat and roster replace the ones on screen',
1317
1432
  ' /my-device — dump this device\u2019s CPU/GPU inventory (manufacturer, cores, drivers, …)'
1318
1433
  ].join('\n')
1319
1434
 
@@ -1891,6 +2006,94 @@ export class ChatApp {
1891
2006
  ]
1892
2007
  }
1893
2008
 
2009
+ if (cmd === 'invite') {
2010
+ const member = rest[0] === 'member'
2011
+ const target = member ? rest[1] : null
2012
+ if (rawArgs.trim() && !member) {
2013
+ return notice('usage: /invite · /invite member · /invite member <n|id>')
2014
+ }
2015
+ return run(async () => {
2016
+ const named = target ? await this._resolveRoom(target) : { meshId: undefined }
2017
+ if (named.error) return named.error
2018
+ // a refusal goes to the transcript: the footer is one truncated line a status tick overwrites
2019
+ const res = await engine
2020
+ .meshInvite(member ? { member: true, meshId: named.meshId } : {})
2021
+ .catch((error) => ({ refusal: error.message }))
2022
+ if (res.refusal) return res.refusal
2023
+ if (!res?.invite) return 'no invite yet - the mesh is still opening'
2024
+ // ctrl+y copies the ACTIVE mesh invite, so a room invite is copied here and never
2025
+ // assigned to this.invite: the shortcut must not start handing out a room instead
2026
+ const copied = await this._copyQuietly(res.invite)
2027
+ if (!member) {
2028
+ return `device invite - the joiner is adopted into your member${copied ? ' (copied)' : ''}:\n${res.invite}`
2029
+ }
2030
+ const lines = [await this._roomHeading(res.meshId)]
2031
+ if (res.notice) lines.push(res.notice)
2032
+ lines.push(...MEMBER_INVITE_DISCLOSURES)
2033
+ lines.push(`${copied ? 'invite (copied)' : 'invite'}:\n${res.invite}`)
2034
+ return lines.join('\n')
2035
+ })
2036
+ }
2037
+
2038
+ if (cmd === 'members') {
2039
+ return run(async () => {
2040
+ const [membersRes, devicesRes] = await Promise.all([
2041
+ engine.listMembers({}),
2042
+ engine.listDevices({})
2043
+ ])
2044
+ const members = membersRes.members ?? []
2045
+ const devices = devicesRes.devices ?? []
2046
+ if (!members.length) return 'no members yet — the mesh is still settling'
2047
+ const lines = []
2048
+ for (const m of members) {
2049
+ const hex = m.id.toString('hex')
2050
+ lines.push(`${m.name} (${hex.slice(0, 8)})`)
2051
+ for (const d of devices) {
2052
+ if (d.memberId?.toString('hex') !== hex) continue
2053
+ lines.push(` · ${d.name}${d.revoked ? ' (revoked)' : ''}`)
2054
+ }
2055
+ }
2056
+ const unlinked = devices.filter((d) => !d.memberId && !d.revoked)
2057
+ if (unlinked.length) {
2058
+ lines.push('not linked to a member:')
2059
+ for (const d of unlinked) lines.push(` · ${d.name}`)
2060
+ }
2061
+ return lines.join('\n')
2062
+ })
2063
+ }
2064
+
2065
+ if (cmd === 'meshes') {
2066
+ return run(async () => {
2067
+ const { meshes } = await engine.listMeshes({})
2068
+ return formatMeshes(meshes ?? [])
2069
+ })
2070
+ }
2071
+
2072
+ // One command word for meshes. A room is still a room in prose, in the invite text and in
2073
+ // the `shared` tag, but a user who opens one and then lists them should not have to switch
2074
+ // vocabulary to do it.
2075
+ if (cmd === 'mesh') {
2076
+ const [action, target, ...labelParts] = rest
2077
+ if (action === 'use' && target) return this._selectMesh(target)
2078
+ if (action === 'new') {
2079
+ return run(async () => {
2080
+ const { meshId } = await engine.createRoom({})
2081
+ return `${await this._roomHeading(meshId)}\n/invite member <n|id> invites someone into it`
2082
+ })
2083
+ }
2084
+ if (action === 'label' && target) {
2085
+ const label = labelParts.join(' ')
2086
+ if (!label) return notice('usage: /mesh label <n|id> <name>')
2087
+ return run(async () => {
2088
+ const named = await this._resolveRoom(target)
2089
+ if (named.error) return named.error
2090
+ await engine.setMeshLabel({ meshId: named.meshId, label })
2091
+ return `${named.meshId.slice(0, 8)} is "${label}" to you - the room co-members never see it`
2092
+ })
2093
+ }
2094
+ return notice('usage: /mesh use <n|id> · /mesh new · /mesh label <n|id> <name>')
2095
+ }
2096
+
1894
2097
  // /chats + /agents open the same interactive pickers as the menu's Switch
1895
2098
  // rows — a standalone menu.page (see the message handler) you arrow through
1896
2099
  // and enter to switch, rather than a static list you'd then /…use by id.
@@ -1960,12 +2163,18 @@ export class ChatApp {
1960
2163
  })
1961
2164
  }
1962
2165
  if (action === 'move') {
1963
- // group first, chat optional, so the one-argument form is a strict prefix of the two;
1964
- // tokenized rather than joined, which is why a name with a space has to be quoted
1965
- const [groupNeedle, chatNeedle, ...extra] = splitPaths(argParts.join(' '))
1966
- if (!groupNeedle || extra.length > 0) {
2166
+ // group first, chat optional, quoted names intact. A trailing `after <chat>|first` also
2167
+ // places the chat (moveChat); without it recency places it (setChatGroup)
2168
+ const tokens = splitPaths(argParts.join(' '))
2169
+ const afterAt = tokens.indexOf('after', 1)
2170
+ const [groupNeedle, chatNeedle, ...extra] =
2171
+ afterAt === -1 ? tokens : tokens.slice(0, afterAt)
2172
+ const anchorNeedle = afterAt === -1 ? null : tokens[afterAt + 1]
2173
+ const malformed =
2174
+ !groupNeedle || extra.length > 0 || (afterAt !== -1 && tokens.length !== afterAt + 2)
2175
+ if (malformed) {
1967
2176
  return notice(
1968
- 'usage: /group move <group>|- [chat] (defaults to this chat; quote a name with spaces)'
2177
+ 'usage: /group move <group>|- [chat] [after <chat>|first] (defaults to this chat; quote a name with spaces)'
1969
2178
  )
1970
2179
  }
1971
2180
  // a miss comes back as text, not a throw, so it renders as a notice like every other miss
@@ -1976,19 +2185,48 @@ export class ChatApp {
1976
2185
  if (!chat) return { miss: `no chat matching "${chatNeedle}"` }
1977
2186
  return { id: chat.id, what: `"${chat.title}"` }
1978
2187
  }
1979
- if (groupNeedle === '-') {
1980
- return run(async () => {
1981
- const { id, what, miss } = await target()
1982
- if (miss) return miss
1983
- await engine.setChatGroup({ id })
1984
- return `${what} is ungrouped`
1985
- })
2188
+ const anchor = async () => {
2189
+ if (anchorNeedle === null) return { placed: '' }
2190
+ if (anchorNeedle === 'first') return { afterId: undefined, placed: ', first' }
2191
+ const { chat, ambiguous } = await this._resolveChat(anchorNeedle)
2192
+ if (ambiguous) {
2193
+ return { miss: `"${anchorNeedle}" matches ${ambiguous} chats — be specific` }
2194
+ }
2195
+ if (!chat) return { miss: `no chat matching "${anchorNeedle}"` }
2196
+ return { afterId: chat.id, placed: `, after "${chat.title}"` }
1986
2197
  }
1987
- return withGroup(groupNeedle, async (group) => {
2198
+ const place = async (groupId, into) => {
1988
2199
  const { id, what, miss } = await target()
1989
2200
  if (miss) return miss
1990
- await engine.setChatGroup({ id, groupId: group.id })
1991
- return `moved ${what} to "${group.name}"`
2201
+ const at = await anchor()
2202
+ if (at.miss) return at.miss
2203
+ if (anchorNeedle === null) {
2204
+ await engine.setChatGroup({ id, groupId })
2205
+ return groupId ? `moved ${what} to ${into}` : `${what} is ungrouped`
2206
+ }
2207
+ await engine.moveChat({ id, groupId, afterId: at.afterId })
2208
+ return `moved ${what} to ${into}${at.placed}`
2209
+ }
2210
+ if (groupNeedle === '-') return run(() => place(undefined, 'the ungrouped list'))
2211
+ return withGroup(groupNeedle, (group) => place(group.id, `"${group.name}"`))
2212
+ }
2213
+ if (action === 'order') {
2214
+ const [needle, keyword, anchorNeedle, ...extra] = splitPaths(argParts.join(' '))
2215
+ if (!needle || keyword !== 'after' || !anchorNeedle || extra.length > 0) {
2216
+ return notice(
2217
+ 'usage: /group order <group> after <group>|first (quote a name with spaces)'
2218
+ )
2219
+ }
2220
+ return withGroup(needle, async (group) => {
2221
+ if (anchorNeedle === 'first') {
2222
+ await engine.moveChatGroup({ id: group.id })
2223
+ return `moved "${group.name}" first`
2224
+ }
2225
+ const { group: anchor, ambiguous } = await this._resolveGroup(anchorNeedle)
2226
+ if (ambiguous) return `"${anchorNeedle}" matches ${ambiguous} groups — be specific`
2227
+ if (!anchor) return `no group matching "${anchorNeedle}"`
2228
+ await engine.moveChatGroup({ id: group.id, afterId: anchor.id })
2229
+ return `moved "${group.name}" after "${anchor.name}"`
1992
2230
  })
1993
2231
  }
1994
2232
  if (action === 'rename') {
@@ -2013,7 +2251,9 @@ export class ChatApp {
2013
2251
  return `deleted "${group.name}" — its chats are now ungrouped`
2014
2252
  })
2015
2253
  }
2016
- return notice('usage: /group [new <name>|rename <group> <name>|del <group>|move <group>|-]')
2254
+ return notice(
2255
+ 'usage: /group [new <name>|rename <group> <name>|del <group>|move <group>|- [chat] [after <chat>|first]|order <group> after <group>|first]'
2256
+ )
2017
2257
  }
2018
2258
 
2019
2259
  return notice(`unknown command: /${cmd}\n${HELP}`)
@@ -2052,8 +2292,7 @@ export class ChatApp {
2052
2292
  return { group: matches[0] ?? null }
2053
2293
  }
2054
2294
 
2055
- // core hands chats back oldest-activity first (app-runtime reverses to render); this does the
2056
- // same so the listing reads newest-first, and groups already arrive in presentation order
2295
+ // core hands chats back bottom-of-sidebar first; reversed so the listing reads top-down
2057
2296
  _groupOverview() {
2058
2297
  const { engine } = this
2059
2298
  return [
@@ -2080,7 +2319,7 @@ export class ChatApp {
2080
2319
  return {
2081
2320
  type: 'notice',
2082
2321
  text: lines.length
2083
- ? `chats by group — most recently active first\n${lines.join('\n')}`
2322
+ ? `chats by group — in sidebar order\n${lines.join('\n')}`
2084
2323
  : 'no chats yet'
2085
2324
  }
2086
2325
  } catch (error) {
@@ -2181,6 +2420,60 @@ export class ChatApp {
2181
2420
  this._chunkGen += 1
2182
2421
  }
2183
2422
 
2423
+ _resetMeshWatches() {
2424
+ this._devicesIterator?.return?.().catch(() => {})
2425
+ this._devicesIterator = null
2426
+ this.deviceLabels = new Map()
2427
+ this.deviceMembers = new Map()
2428
+ this.memberNames = new Map()
2429
+ }
2430
+
2431
+ // The send block goes up here and comes down only in the 'mesh.selected'
2432
+ // handler, so every outcome below has to route through it.
2433
+ _selectMesh(target) {
2434
+ this._booting = true
2435
+ this.status = 'switching mesh…'
2436
+ this.notice = null
2437
+ return [
2438
+ this,
2439
+ async () => {
2440
+ try {
2441
+ const { meshes } = await this.engine.listMeshes({})
2442
+ const { mesh, error } = resolveMesh(meshes ?? [], target)
2443
+ if (error) return { type: 'mesh.selected', text: error }
2444
+ if (mesh.active) {
2445
+ return { type: 'mesh.selected', text: `already on mesh ${mesh.meshId.slice(0, 8)}` }
2446
+ }
2447
+ await this.engine.selectMesh({ meshId: mesh.meshId })
2448
+ const next = await this.engine.meshInvite({}).catch(() => null)
2449
+ return { type: 'mesh.selected', meshId: mesh.meshId, invite: next?.invite ?? null }
2450
+ } catch (error) {
2451
+ return { type: 'mesh.selected', error }
2452
+ }
2453
+ }
2454
+ ]
2455
+ }
2456
+
2457
+ // What a mesh transition invalidates: the chunk watch is bound to a chat that
2458
+ // only exists in the mesh being left, and the roster stream to its devices.
2459
+ _adoptMesh(invite, notice) {
2460
+ this._resetChatWatches()
2461
+ this._resetMeshWatches()
2462
+ this.chatId = null
2463
+ this.agent = null
2464
+ this._turns = []
2465
+ this.busy = false
2466
+ this._awaitingRun = false
2467
+ this._runningRunId = null
2468
+ this.pendingApproval = null
2469
+ // a room refuses a device invite, so an empty refresh must clear it, not keep the account's
2470
+ this.invite = invite
2471
+ this.status = ''
2472
+ this.notice = notice
2473
+ this._render()
2474
+ return batch(...[this._watchNextDevices(), this._bootstrap()].filter(Boolean))
2475
+ }
2476
+
2184
2477
  // Swap the active chat: drop the old chat's watches, adopt the chat's owning
2185
2478
  // agent, clear the transcript + run state, and re-arm on the new chatId.
2186
2479
  _switchTo(chat, agent) {
@@ -2534,6 +2827,8 @@ export class ChatApp {
2534
2827
  title: 'Mesh',
2535
2828
  cursor: 0,
2536
2829
  entries: [
2830
+ { label: 'Meshes', hint: 'the meshes this device belongs to', command: '/meshes' },
2831
+ { label: 'Switch mesh…', hint: '/mesh use <n|id>', prefill: '/mesh use ' },
2537
2832
  { label: 'Join mesh…', hint: '/join <qvac://mesh/…>', prefill: '/join ' },
2538
2833
  { label: 'Cancel join', hint: 'abort a join in progress', command: '/join cancel' }
2539
2834
  ]
@@ -2932,6 +3227,38 @@ export class ChatApp {
2932
3227
  return [this, null]
2933
3228
  }
2934
3229
 
3230
+ // shift+↑/↓ on a chat row: drop it one place up or down inside its container
3231
+ _nudgeChat(delta) {
3232
+ const rows = this._sidebarRows()
3233
+ const row = rows[this._sidebarCursor(rows)]
3234
+ if (row?.kind !== 'chat') return [this, null]
3235
+ const chat = this._chats.find((c) => c.id === row.chatId)
3236
+ if (!chat) return [this, null]
3237
+ const groupId = chat.groupId || undefined
3238
+ const siblings = [...this._chats]
3239
+ .reverse()
3240
+ .filter((c) => !c.deletedAt && (c.groupId || undefined) === groupId)
3241
+ .map((c) => c.id)
3242
+ const at = siblings.indexOf(chat.id)
3243
+ const to = at + delta
3244
+ if (to < 0 || to >= siblings.length) return [this, null]
3245
+ // up: under the chat two above (none = top); down: under the chat just below
3246
+ const afterId = delta < 0 ? siblings[to - 1] : siblings[to]
3247
+ const { engine } = this
3248
+ const token = ++this._statusToken
3249
+ return [
3250
+ this,
3251
+ async () => {
3252
+ try {
3253
+ await engine.moveChat({ id: chat.id, groupId, afterId })
3254
+ return { type: 'transient-status', token, text: `moved ${delta < 0 ? 'up' : 'down'}` }
3255
+ } catch (error) {
3256
+ return { type: 'run.error', error }
3257
+ }
3258
+ }
3259
+ ]
3260
+ }
3261
+
2935
3262
  _sidebarActivate() {
2936
3263
  const s = this._sidebar
2937
3264
  const rows = this._sidebarRows()
@@ -2967,6 +3294,9 @@ export class ChatApp {
2967
3294
  // just hands focus back.
2968
3295
  _sidebarKey(msg) {
2969
3296
  const s = this._sidebar
3297
+ // shift first: the plain arrow also matches a shifted one
3298
+ if (!s.moving && key.matches(msg, 'shift+up')) return this._nudgeChat(-1)
3299
+ if (!s.moving && key.matches(msg, 'shift+down')) return this._nudgeChat(1)
2970
3300
  if (key.matches(msg, 'up')) return this._moveSidebar(-1)
2971
3301
  if (key.matches(msg, 'down')) return this._moveSidebar(1)
2972
3302
  if (key.matches(msg, 'enter')) return this._sidebarActivate()
@@ -3398,19 +3728,21 @@ export class ChatApp {
3398
3728
  this._render()
3399
3729
  return [this, null]
3400
3730
  }
3401
- this._resetChatWatches()
3402
- this.chatId = null
3403
- this.agent = null
3404
- this._turns = []
3405
- this.busy = false
3406
- this._awaitingRun = false
3407
- this._runningRunId = null
3408
- this.pendingApproval = null
3409
- this.invite = msg.invite ?? this.invite
3410
- this.status = ''
3411
- this.notice = 'joined — resolving the mesh’s agent and chat…'
3412
- this._render()
3413
- return [this, this._bootstrap()]
3731
+ return [this, this._adoptMesh(msg.invite, 'joined — resolving the mesh’s agent and chat…')]
3732
+ }
3733
+
3734
+ // /mesh use settled. Same landing as a join, minus the admission: the target
3735
+ // mesh was already ours, so only the agent, chat and roster have to catch up.
3736
+ if (msg.type === 'mesh.selected') {
3737
+ if (msg.error || msg.text) {
3738
+ this._booting = false
3739
+ this.status = msg.error ? fg.err.render(`mesh switch failed: ${msg.error.message}`) : ''
3740
+ this.notice = msg.text ?? null
3741
+ this._render()
3742
+ return [this, null]
3743
+ }
3744
+ const settling = `switched to mesh ${msg.meshId.slice(0, 8)} - resolving its agent and chat…`
3745
+ return [this, this._adoptMesh(msg.invite, settling)]
3414
3746
  }
3415
3747
 
3416
3748
  // _connect resolved: bind the engine + its identity, then arm the watch
@@ -3455,14 +3787,31 @@ export class ChatApp {
3455
3787
 
3456
3788
  if (msg.type === 'devices') {
3457
3789
  if (msg.gen !== this.gen) return [this, null]
3458
- this.deviceLabels = new Map(
3459
- (msg.frame.devices ?? []).map((d) => [d.id.toString('hex'), d.name])
3790
+ const devices = msg.frame.devices ?? []
3791
+ this.deviceLabels = new Map(devices.map((d) => [d.id.toString('hex'), d.name]))
3792
+ this.deviceMembers = new Map(
3793
+ devices
3794
+ .filter((d) => d.memberId)
3795
+ .map((d) => [d.id.toString('hex'), d.memberId.toString('hex')])
3460
3796
  )
3461
3797
  this._render()
3462
- return [this, this._watchNextDevices()]
3798
+ const unnamed = [...this.deviceMembers.values()].some((id) => !this.memberNames.has(id))
3799
+ return [
3800
+ this,
3801
+ unnamed
3802
+ ? batch(this._watchNextDevices(), this._refreshMembersCmd())
3803
+ : this._watchNextDevices()
3804
+ ]
3463
3805
  }
3464
3806
  if (msg.type === 'devices.done') return [this, null]
3465
3807
 
3808
+ if (msg.type === 'members.frame') {
3809
+ if (msg.gen !== this.gen) return [this, null]
3810
+ for (const m of msg.members) this.memberNames.set(m.id.toString('hex'), m.name)
3811
+ this._render()
3812
+ return [this, null]
3813
+ }
3814
+
3466
3815
  if (msg.type === 'diagnostics') {
3467
3816
  if (msg.gen !== this.gen) return [this, null]
3468
3817
  this.diagnostics = msg.stats
@@ -3884,6 +4233,23 @@ export class ChatApp {
3884
4233
  ]
3885
4234
  }
3886
4235
 
4236
+ // The same selector /mesh use takes, so a room is named by its list number as well as its id
4237
+ async _resolveRoom(selector) {
4238
+ const { meshes } = await this.engine.listMeshes({})
4239
+ const { mesh, error } = resolveMesh(meshes ?? [], selector)
4240
+ return error ? { error } : { meshId: mesh.meshId }
4241
+ }
4242
+
4243
+ // Which room, and how to get to it: a room is opened beside the active mesh and never
4244
+ // selected, so the user has to be told it exists and told how to go there.
4245
+ async _roomHeading(meshId) {
4246
+ if (!meshId) return 'shared room'
4247
+ const { meshes } = await this.engine.listMeshes({}).catch(() => ({ meshes: [] }))
4248
+ const index = (meshes ?? []).findIndex((mesh) => mesh.meshId === meshId)
4249
+ const where = index < 0 ? '/meshes lists it' : `/mesh use ${index + 1} to open it`
4250
+ return `shared room ${meshId.slice(0, 8)} - not selected, ${where}`
4251
+ }
4252
+
3887
4253
  // A clipboard that isn't there (or fails) must not fail the thing that wanted it.
3888
4254
  async _copyQuietly(text) {
3889
4255
  if (!this._copyToClipboard) return false
@@ -3986,7 +4352,7 @@ export class ChatApp {
3986
4352
  if (this._sidebar?.focus) {
3987
4353
  return this._sidebar.moving
3988
4354
  ? '↑/↓: group · enter: move here · esc: cancel · ctrl+c: quit'
3989
- : '↑/↓: chat · enter: open · m: move to group · esc: close · ctrl+c: quit'
4355
+ : '↑/↓: chat · shift+↑/↓: reorder · enter: open · m: move to group · esc: close · ctrl+c: quit'
3990
4356
  }
3991
4357
  if (this._models) return '↑/↓: move · enter: use · esc: back · ctrl+c: quit'
3992
4358
  if (this._selector) {
package/tui/boot.mjs CHANGED
@@ -74,7 +74,7 @@ export default async function boot(args) {
74
74
  const storagePath = storage.assistant
75
75
  fs.mkdirSync(storagePath, { recursive: true })
76
76
  configureSdkStorage(storage.sdk)
77
- const deviceName = `duck-${process.pid}`
77
+ const deviceName = process.env.QVAC_DEVICE_NAME || `duck-${process.pid}`
78
78
  // Every run logs; only the destination differs. Both modes write
79
79
  // <storage.root>/assistant.log — the same file the desktop app writes, and
80
80
  // the only way to read a TUI session's engine and sidecar output, since
@@ -1,6 +1,7 @@
1
1
  // The chat sidebar's row model: chats under their groups, in the order core
2
- // presents them (groups first, each chat newest-activity first). Rows are what
3
- // the pane draws and what its cursor walks; only `chat` rows are selectable.
2
+ // presents them (groups first, each chat where it was dragged or else
3
+ // newest-activity first). Rows are what the pane draws and what its cursor
4
+ // walks; only `chat` rows are selectable.
4
5
 
5
6
  export const SIDEBAR_COLS = 26
6
7