@qvac/core 1.0.0-rc.5 → 1.0.0-rc.6

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 (108) hide show
  1. package/CHANGELOG.md +43 -2
  2. package/README.md +55 -4
  3. package/dist-lib/lib/api/agents.d.ts +2 -1
  4. package/dist-lib/lib/api/agents.js +5 -1
  5. package/dist-lib/lib/api/app-config.d.ts +3 -0
  6. package/dist-lib/lib/api/app-config.js +20 -0
  7. package/dist-lib/lib/api/device-routes.d.ts +1 -1
  8. package/dist-lib/lib/api/device-routes.js +3 -1
  9. package/dist-lib/lib/api/index.js +2 -1
  10. package/dist-lib/lib/api/projects.js +3 -4
  11. package/dist-lib/lib/api/served.d.ts +2 -2
  12. package/dist-lib/lib/api/served.js +24 -1
  13. package/dist-lib/lib/assistant/harness.d.ts +3 -0
  14. package/dist-lib/lib/assistant/history.js +14 -2
  15. package/dist-lib/lib/assistant/message.d.ts +1 -0
  16. package/dist-lib/lib/assistant/model-round.d.ts +3 -0
  17. package/dist-lib/lib/assistant/model-round.js +16 -2
  18. package/dist-lib/lib/assistant/round-host.d.ts +2 -0
  19. package/dist-lib/lib/assistant/round-host.js +8 -0
  20. package/dist-lib/lib/assistant-tree.d.ts +2 -0
  21. package/dist-lib/lib/assistant-tree.js +4 -2
  22. package/dist-lib/lib/assistant.d.ts +11 -1
  23. package/dist-lib/lib/assistant.js +115 -8
  24. package/dist-lib/lib/client.js +4 -1
  25. package/dist-lib/lib/core/agent-copies.js +2 -1
  26. package/dist-lib/lib/core/agent-hosting.js +9 -4
  27. package/dist-lib/lib/core/agent.js +2 -1
  28. package/dist-lib/lib/core/chat-copy.d.ts +1 -0
  29. package/dist-lib/lib/core/chat-copy.js +13 -2
  30. package/dist-lib/lib/core/chat.d.ts +0 -1
  31. package/dist-lib/lib/core/chat.js +0 -3
  32. package/dist-lib/lib/core/collections.d.ts +7 -7
  33. package/dist-lib/lib/core/collections.js +7 -7
  34. package/dist-lib/lib/core/contract/project-device-keys.d.ts +4 -2
  35. package/dist-lib/lib/core/contract/project-device-keys.js +12 -12
  36. package/dist-lib/lib/core/contract/project-host-keys.d.ts +5 -3
  37. package/dist-lib/lib/core/contract/project-host-keys.js +22 -11
  38. package/dist-lib/lib/core/contract/projects.d.ts +4 -2
  39. package/dist-lib/lib/core/contract/projects.js +29 -17
  40. package/dist-lib/lib/core/deleted-agent-runs.d.ts +1 -0
  41. package/dist-lib/lib/core/deleted-agent-runs.js +22 -11
  42. package/dist-lib/lib/core/helpers/index.d.ts +1 -1
  43. package/dist-lib/lib/core/helpers/index.js +2 -2
  44. package/dist-lib/lib/core/mesh.d.ts +1 -0
  45. package/dist-lib/lib/core/mesh.js +4 -4
  46. package/dist-lib/lib/core/project-keys.d.ts +5 -2
  47. package/dist-lib/lib/core/project-keys.js +15 -6
  48. package/dist-lib/lib/core/sync/index.js +5 -5
  49. package/dist-lib/lib/core.d.ts +2 -0
  50. package/dist-lib/lib/core.js +102 -25
  51. package/dist-lib/lib/kv-cache-ledger.d.ts +22 -0
  52. package/dist-lib/lib/kv-cache-ledger.js +72 -0
  53. package/dist-lib/lib/kv-cache-retention.d.ts +1 -0
  54. package/dist-lib/lib/kv-cache-retention.js +5 -2
  55. package/dist-lib/lib/model-memory-cap.d.ts +3 -0
  56. package/dist-lib/lib/model-memory-cap.js +15 -6
  57. package/dist-lib/lib/run-replay.d.ts +3 -2
  58. package/dist-lib/lib/run-replay.js +16 -5
  59. package/dist-lib/lib/run-transcript.js +1 -1
  60. package/dist-lib/schema/engine.js +54 -1
  61. package/dist-lib/schema/qvac.js +62 -1
  62. package/dist-lib/spec/bind.js +3 -0
  63. package/dist-lib/spec/calls.js +1 -0
  64. package/dist-lib/spec/capabilities.d.ts +2 -0
  65. package/dist-lib/spec/hrpc/hrpc.json +13 -0
  66. package/dist-lib/spec/hrpc/index.js +15 -3
  67. package/dist-lib/spec/hrpc/messages.js +253 -3
  68. package/dist-lib/spec/hyperschema/index.js +253 -3
  69. package/dist-lib/spec/hyperschema/schema.json +187 -0
  70. package/dist-lib/spec/hyperschema/types.d.ts +33 -0
  71. package/dist-lib/spec/mesh/hyperdb/db.json +110 -0
  72. package/dist-lib/spec/mesh/hyperdb/index.js +498 -2
  73. package/dist-lib/spec/mesh/hyperdb/messages.js +865 -410
  74. package/dist-lib/spec/mesh/hyperdispatch/messages.js +244 -3
  75. package/dist-lib/spec/mesh/hyperschema/index.js +244 -3
  76. package/dist-lib/spec/mesh/hyperschema/schema.json +155 -0
  77. package/dist-lib/spec/mesh/hyperschema/types.d.ts +37 -0
  78. package/package.json +27 -11
  79. package/tui/README.md +190 -0
  80. package/tui/app.mjs +8247 -0
  81. package/tui/boot.mjs +159 -0
  82. package/tui/index.mjs +89 -0
  83. package/tui/lib/boot-timing.mjs +41 -0
  84. package/tui/lib/busy-words.mjs +116 -0
  85. package/tui/lib/connect-sheet.mjs +350 -0
  86. package/tui/lib/device-target.mjs +64 -0
  87. package/tui/lib/export.mjs +194 -0
  88. package/tui/lib/folders-command.mjs +84 -0
  89. package/tui/lib/fork-command.mjs +43 -0
  90. package/tui/lib/knowledge-command.mjs +190 -0
  91. package/tui/lib/knowledge-import.mjs +153 -0
  92. package/tui/lib/local-path.mjs +21 -0
  93. package/tui/lib/move-command.mjs +17 -0
  94. package/tui/lib/render.mjs +225 -0
  95. package/tui/lib/save-file.mjs +88 -0
  96. package/tui/lib/select.mjs +81 -0
  97. package/tui/lib/selection.mjs +18 -0
  98. package/tui/lib/setup.mjs +135 -0
  99. package/tui/lib/sidebar.mjs +63 -0
  100. package/tui/lib/skill-connect.mjs +145 -0
  101. package/tui/lib/splash-art.mjs +107 -0
  102. package/tui/lib/splash.mjs +18 -0
  103. package/tui/lib/upload-frames.mjs +9 -0
  104. package/tui/lib/usage.mjs +59 -0
  105. package/tui/lib/wrap.mjs +143 -0
  106. package/tui/main.mjs +279 -0
  107. package/tui/plugins.mjs +158 -0
  108. package/worker/assistant-sidecar.mjs +1 -0
@@ -0,0 +1,350 @@
1
+ // the form a skill is set up through: its routes, the fields each asks for, and how it draws
2
+ import { isReady, statusLabel } from './setup.mjs'
3
+
4
+ const MASK_CAP = 24
5
+
6
+ const CONNECTED = {
7
+ oauth: 'connected — fill this in again to change it',
8
+ token: 'connected — fill this in again to change it',
9
+ picker: 'set — pick another folder to change it',
10
+ install: 'installed',
11
+ instructions: 'ready'
12
+ }
13
+
14
+ export function openSheet(skill, { routes, enable = false, field = null }) {
15
+ const sheet = {
16
+ skill,
17
+ routes,
18
+ route: firstRoute(routes, field),
19
+ cursor: Math.max(
20
+ 0,
21
+ routes.findIndex((route) => !route.satisfied && route.credentialKey)
22
+ ),
23
+ focus: 0,
24
+ values: {},
25
+ revealed: false,
26
+ enable,
27
+ phase: 'edit',
28
+ attempt: 0,
29
+ stage: null,
30
+ url: null,
31
+ error: null,
32
+ oauth: null
33
+ }
34
+ if (field) {
35
+ focusField(sheet, field)
36
+ }
37
+
38
+ return sheet
39
+ }
40
+
41
+ // a named field opens the route that holds it; several routes otherwise start on the picker
42
+ function firstRoute(routes, field) {
43
+ const holding = field ? routes.findIndex((route) => hasField(route, field)) : -1
44
+ if (holding >= 0) {
45
+ return holding
46
+ }
47
+
48
+ return routes.length === 1 ? 0 : null
49
+ }
50
+
51
+ export function hasField(route, key) {
52
+ return routeFields(route).some((field) => field.key === key)
53
+ }
54
+
55
+ export function currentRoute(sheet) {
56
+ return sheet.route === null ? null : sheet.routes[sheet.route]
57
+ }
58
+
59
+ export function pickRoute(sheet, index) {
60
+ sheet.route = index
61
+ sheet.focus = 0
62
+ sheet.values = {}
63
+ sheet.error = null
64
+ }
65
+
66
+ export function sheetFields(sheet) {
67
+ const route = currentRoute(sheet)
68
+ return route ? routeFields(route) : []
69
+ }
70
+
71
+ // a picker is one path; a token route without fields still takes its own key
72
+ export function routeFields(route) {
73
+ if (route.kind === 'picker') {
74
+ return [{ key: route.credentialKey, label: 'Folder', placeholder: '~/path/to/folder' }]
75
+ }
76
+
77
+ if (route.kind === 'token' && !route.fields?.length) {
78
+ return [{ key: route.credentialKey, label: route.credentialKey, secret: true }]
79
+ }
80
+
81
+ return route.kind === 'oauth' || route.kind === 'token' ? [...(route.fields ?? [])] : []
82
+ }
83
+
84
+ // every sheet can be left from its own buttons, not only by a key named in the header
85
+ export function sheetButtons(sheet) {
86
+ const route = currentRoute(sheet)
87
+ if (!route) {
88
+ return []
89
+ }
90
+
91
+ if (sheet.phase === 'waiting') {
92
+ return [{ id: 'cancel', label: 'Cancel sign-in' }]
93
+ }
94
+
95
+ return [...actionButtons(sheet, route), { id: 'cancel', label: 'Cancel' }]
96
+ }
97
+
98
+ function actionButtons(sheet, route) {
99
+ const connected = isConnected(sheet)
100
+ const remove = connected && route.credentialKey ? [{ id: 'disconnect', label: 'Disconnect' }] : []
101
+ if (route.kind === 'oauth') {
102
+ return [{ id: 'connect', label: connected ? 'Reconnect' : 'Connect' }, ...remove]
103
+ }
104
+
105
+ if (route.kind === 'token' || route.kind === 'picker') {
106
+ return [{ id: 'save', label: 'Save' }, ...remove]
107
+ }
108
+
109
+ return [{ id: 'check', label: route.kind === 'install' ? 'Check again' : 'Done' }]
110
+ }
111
+
112
+ // with several ways in, the skill being ready says nothing about the one on screen
113
+ export function isConnected(sheet) {
114
+ const route = currentRoute(sheet)
115
+ if (route?.satisfied === true) {
116
+ return true
117
+ }
118
+
119
+ return sheet.routes.length === 1 && isReady(sheet.skill)
120
+ }
121
+
122
+ export function focused(sheet) {
123
+ const fields = sheetFields(sheet)
124
+ if (sheet.focus < fields.length) {
125
+ return { field: fields[sheet.focus] }
126
+ }
127
+
128
+ return { button: sheetButtons(sheet)[sheet.focus - fields.length] ?? null }
129
+ }
130
+
131
+ export function moveFocus(sheet, delta) {
132
+ const count = sheetFields(sheet).length + sheetButtons(sheet).length
133
+ sheet.focus = Math.max(0, Math.min(count - 1, sheet.focus + delta))
134
+ }
135
+
136
+ export function focusField(sheet, key) {
137
+ sheet.focus = Math.max(
138
+ 0,
139
+ sheetFields(sheet).findIndex((entry) => entry.key === key)
140
+ )
141
+ }
142
+
143
+ // a pasted value arrives with the terminal's line breaks and padding, never meant as part of it
144
+ export function typeInto(sheet, text) {
145
+ const { field } = focused(sheet)
146
+ if (!field) {
147
+ return false
148
+ }
149
+
150
+ const value = (sheet.values[field.key] ?? '') + text.replace(/[\r\n]+/g, '')
151
+ sheet.values[field.key] = value.trimStart()
152
+ sheet.error = null
153
+
154
+ return true
155
+ }
156
+
157
+ export function backspace(sheet) {
158
+ const { field } = focused(sheet)
159
+ if (!field) {
160
+ return
161
+ }
162
+
163
+ sheet.values[field.key] = (sheet.values[field.key] ?? '').slice(0, -1)
164
+ }
165
+
166
+ export function enteredValues(sheet) {
167
+ return Object.fromEntries(
168
+ sheetFields(sheet).map((field) => [field.key, (sheet.values[field.key] ?? '').trim()])
169
+ )
170
+ }
171
+
172
+ // `at` is the line the focus sits on, so a long guide scrolls to the field being typed
173
+ export function formatSheet(sheet, fg) {
174
+ const { skill } = sheet
175
+ const route = currentRoute(sheet)
176
+ const title = `Set up ${skill.name}`
177
+ if (!route) {
178
+ return { lines: formatRoutePicker(sheet, fg, title), at: sheet.cursor + 2 }
179
+ }
180
+
181
+ const keys =
182
+ sheet.phase === 'waiting'
183
+ ? 'esc cancel · ctrl+y copy link'
184
+ : 'tab/↑↓ move · enter select · ctrl+r show secrets · esc back'
185
+ const lines = [fg.dim.render(`${title} — ${keys}`), '']
186
+ lines.push(fg.white.render(route.description ?? skill.setup?.summary ?? skill.description))
187
+ lines.push(stateLine(sheet, fg))
188
+ if (route.helpUrl) {
189
+ lines.push(fg.dim.render(route.helpUrl))
190
+ }
191
+
192
+ const fieldAt = pushForm(sheet, lines, fg)
193
+ lines.push('')
194
+ const footerAt = lines.length
195
+ lines.push(...footer(sheet, fg))
196
+ const onField = sheet.focus < sheetFields(sheet).length
197
+
198
+ return { lines, at: onField ? fieldAt + sheet.focus : footerAt }
199
+ }
200
+
201
+ // the guide, the fields, then the steps that follow them; returns the first field's line
202
+ function pushForm(sheet, lines, fg) {
203
+ const guide = guideSteps(sheet)
204
+ if (guide.length) {
205
+ lines.push('')
206
+ guide.forEach((step, i) =>
207
+ lines.push(`${fg.cyan.render(`${i + 1}.`)} ${stepText(sheet, step)}`)
208
+ )
209
+ }
210
+
211
+ const fields = sheetFields(sheet)
212
+ const fieldAt = lines.length + 1
213
+ if (fields.length) {
214
+ lines.push('')
215
+ const width = Math.max(...fields.map((field) => field.label.length))
216
+ fields.forEach((field, i) => lines.push(fieldLine(sheet, { field, i, width }, fg)))
217
+ }
218
+
219
+ const after = stepsAfterFields(sheet)
220
+ if (after.length) {
221
+ lines.push('', ...after.map((step) => fg.dim.render(`• ${stepText(sheet, step)}`)))
222
+ }
223
+
224
+ return fieldAt
225
+ }
226
+
227
+ function formatRoutePicker(sheet, fg, title) {
228
+ const lines = [fg.dim.render(`${title} — ↑/↓ move · enter choose · esc back`), '']
229
+ sheet.routes.forEach((route, i) => {
230
+ const point = i === sheet.cursor ? fg.magenta.render('❯ ') : ' '
231
+ const mark = route.satisfied ? fg.green.render('● ') : fg.dim.render('○ ')
232
+ lines.push(`${point}${mark}${fg.white.render(route.label)}`)
233
+ })
234
+
235
+ return lines
236
+ }
237
+
238
+ function stateLine(sheet, fg) {
239
+ if (isConnected(sheet)) {
240
+ return fg.green.render(`● ${CONNECTED[currentRoute(sheet).kind]}`)
241
+ }
242
+
243
+ if (isReady(sheet.skill)) {
244
+ return fg.dim.render(`○ not set — ${sheet.skill.name} already works another way`)
245
+ }
246
+
247
+ return fg.amber.render(`○ ${statusLabel(sheet.skill.status)}`)
248
+ }
249
+
250
+ // above the fields: what to do before filling them, so a guide's "the fields below" reads true
251
+ function guideSteps(sheet) {
252
+ const route = currentRoute(sheet)
253
+ if (route.kind === 'install') {
254
+ return installSteps(sheet.skill, route)
255
+ }
256
+
257
+ if (route.kind === 'oauth') {
258
+ return ownApp(sheet) ? [...(route.configSteps ?? []), ...redirectStep(sheet)] : []
259
+ }
260
+
261
+ return route.kind === 'token' ? [] : [...(route.steps ?? [])]
262
+ }
263
+
264
+ // below the fields, as desktop draws them: a token's guide and an OAuth consent say "above"
265
+ function stepsAfterFields(sheet) {
266
+ const route = currentRoute(sheet)
267
+ if (route.kind === 'token') {
268
+ return [...(route.steps ?? [])]
269
+ }
270
+
271
+ const guided = ownApp(sheet) && route.configSteps?.length
272
+
273
+ return route.kind === 'oauth' && !guided ? [...(route.steps ?? [])] : []
274
+ }
275
+
276
+ // the user's own app is set up in its console; a built-in client needs only the consent
277
+ function ownApp(sheet) {
278
+ const route = currentRoute(sheet)
279
+ return route.kind === 'oauth' && !!route.fields?.length && !sheet.oauth?.builtIn
280
+ }
281
+
282
+ // a pinned loopback port is the one redirect a provider console can be told in advance
283
+ function redirectStep(sheet) {
284
+ const uri = sheet.oauth?.redirectUri
285
+ return uri ? [`Register this redirect URI in your app: ${uri} (ctrl+y copies it)`] : []
286
+ }
287
+
288
+ // a brew step names a formula, not a command, so the command is spelled out to run by hand
289
+ function installSteps(skill, route) {
290
+ const steps = (skill.install ?? []).map((step) => {
291
+ const command = step.command ?? (step.formula ? `brew install ${step.formula}` : null)
292
+ return command ? `${step.label}: ${command}` : step.label
293
+ })
294
+
295
+ return steps.length ? steps : [...(route.steps ?? [])]
296
+ }
297
+
298
+ function fieldLine(sheet, { field, i, width }, fg) {
299
+ const active = sheet.focus === i && sheet.phase === 'edit'
300
+ const point = active ? fg.magenta.render('❯ ') : ' '
301
+ const value = sheet.values[field.key] ?? ''
302
+ const shown = field.secret && !sheet.revealed ? mask(value) : value
303
+ const cursor = active ? fg.magenta.render('▏') : ''
304
+ const hint = value ? '' : fg.dim.render(fieldHint(sheet, field))
305
+
306
+ return `${point}${field.label.padEnd(width)} ${shown}${cursor}${hint}`
307
+ }
308
+
309
+ // a saved app outranks the built-in one when connecting, so it outranks it here too
310
+ function fieldHint(sheet, field) {
311
+ if (field.secret && sheet.oauth?.savedSecret) {
312
+ return 'blank keeps the saved one'
313
+ }
314
+
315
+ if (sheet.oauth?.builtIn && !sheet.oauth.savedClientId && !sheet.oauth.savedSecret) {
316
+ return 'optional — blank uses the built-in client'
317
+ }
318
+
319
+ return field.placeholder ?? ''
320
+ }
321
+
322
+ function mask(value) {
323
+ return value ? `${'•'.repeat(Math.min(value.length, MASK_CAP))} ${value.length} chars` : ''
324
+ }
325
+
326
+ function footer(sheet, fg) {
327
+ const fields = sheetFields(sheet).length
328
+ const buttons = sheetButtons(sheet).map((button, i) => {
329
+ const label = `[ ${button.label} ]`
330
+ return sheet.focus === fields + i ? fg.magenta.render(label) : fg.white.render(label)
331
+ })
332
+ if (sheet.phase === 'waiting') {
333
+ const url = sheet.url ? [fg.dim.render(sheet.url)] : []
334
+ return [fg.amber.render(sheet.stage ?? 'waiting for the browser…'), ...url, '', buttons[0]]
335
+ }
336
+
337
+ const lines = [buttons.join(' ')]
338
+ if (sheet.error) {
339
+ lines.push('', fg.err.render(sheet.error))
340
+ }
341
+
342
+ return lines
343
+ }
344
+
345
+ // a link is shown with its address, and `{skill}` is the placeholder desktop fills in too
346
+ function stepText(sheet, step) {
347
+ return step
348
+ .replaceAll('{skill}', sheet.skill.name)
349
+ .replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, '$1 ($2)')
350
+ }
@@ -0,0 +1,64 @@
1
+ import b4a from 'b4a'
2
+ import { DEVICE_ROUTES } from '../../dist-lib/lib/api/device-routes.js'
3
+
4
+ // the routes /device points at another device of this account; every other route stays here
5
+ const ON_DEVICE = new Set(DEVICE_ROUTES)
6
+
7
+ export function onDevice(engine, deviceId) {
8
+ if (!deviceId) {
9
+ return engine
10
+ }
11
+
12
+ return new Proxy(engine, {
13
+ get(target, prop) {
14
+ const value = Reflect.get(target, prop)
15
+ if (typeof value !== 'function') {
16
+ return value
17
+ }
18
+
19
+ if (!ON_DEVICE.has(prop)) {
20
+ return value.bind(target)
21
+ }
22
+
23
+ return (input = {}) => value.call(target, { ...input, deviceId })
24
+ }
25
+ })
26
+ }
27
+
28
+ // by its number in /device list, its name, or a prefix of its id
29
+ export function pickDevice(devices, asked) {
30
+ const wanted = asked.trim().toLowerCase()
31
+ if (!wanted) {
32
+ return null
33
+ }
34
+
35
+ const index = Number(wanted)
36
+ if (Number.isInteger(index) && index >= 1 && index <= devices.length) {
37
+ return devices[index - 1]
38
+ }
39
+
40
+ const named = devices.filter((device) => device.name?.toLowerCase() === wanted)
41
+ if (named.length === 1) {
42
+ return named[0]
43
+ }
44
+
45
+ const prefixed = devices.filter((device) => b4a.toHex(device.id).startsWith(wanted))
46
+
47
+ return prefixed.length === 1 ? prefixed[0] : null
48
+ }
49
+
50
+ export function deviceLines(devices, { own, target, connected }) {
51
+ return devices.map((device, i) => {
52
+ const mark = target && b4a.equals(device.id, target) ? '*' : ' '
53
+ const facts = []
54
+ if (own && b4a.equals(device.id, own)) {
55
+ facts.push('this device')
56
+ } else {
57
+ facts.push(connected.has(b4a.toHex(device.id)) ? 'connected' : 'not connected')
58
+ }
59
+
60
+ facts.push(`${device.cachedModelNames?.length ?? 0} models downloaded`)
61
+
62
+ return `${mark}${i + 1}. ${device.name} (${b4a.toHex(device.id).slice(0, 8)}) — ${facts.join(' · ')}`
63
+ })
64
+ }
@@ -0,0 +1,194 @@
1
+ // the transcript as markdown, readable (and reportable) away from the TUI
2
+
3
+ const STATUS = { completed: 'completed', failed: 'failed', canceled: 'canceled' }
4
+
5
+ function quote(text) {
6
+ return text
7
+ .split('\n')
8
+ .map((line) => `> ${line}`)
9
+ .join('\n')
10
+ }
11
+
12
+ function json(value) {
13
+ return ['```json', JSON.stringify(value ?? null, null, 2), '```'].join('\n')
14
+ }
15
+
16
+ // the file identifies the run either way, so the directories never reach the report
17
+ function modelLabel(model) {
18
+ return model.split(/[?#]/)[0].split(/[\\/]/).pop() || model
19
+ }
20
+
21
+ function metricsLine(turn) {
22
+ const metrics = turn.statusDetail?.metrics
23
+ if (!metrics) {
24
+ return null
25
+ }
26
+
27
+ const parts = [`${metrics.totalTokens} tokens`]
28
+ if (metrics.tokensPerSecond) {
29
+ parts.push(`${metrics.tokensPerSecond.toFixed(1)} tok/s`)
30
+ }
31
+
32
+ if (metrics.timeToFirstToken) {
33
+ parts.push(`ttft ${Math.round(metrics.timeToFirstToken)}ms`)
34
+ }
35
+
36
+ if (metrics.cacheTokens) {
37
+ parts.push(`${metrics.cacheTokens} cached`)
38
+ }
39
+
40
+ return `_${parts.join(' · ')}_`
41
+ }
42
+
43
+ // retrieval returns chunks, so one document can appear many times over
44
+ function sourcesSection(detail) {
45
+ const rows = detail.sources ?? []
46
+ if (!rows.length) {
47
+ return ['### Sources', '', detail.notice ?? '(none)']
48
+ }
49
+
50
+ const documents = new Set(rows.map((source) => source.documentId ?? source.title)).size
51
+ const chunks = `${rows.length} ${rows.length === 1 ? 'chunk' : 'chunks'}`
52
+ const from = `${documents} ${documents === 1 ? 'document' : 'documents'}`
53
+ const lines = [`### Sources — ${chunks} from ${from}`, '']
54
+ for (const source of rows) {
55
+ const score = typeof source.score === 'number' ? ` · score ${source.score.toFixed(2)}` : ''
56
+ lines.push(`- **${source.title}** — chunk ${source.chunkIndex}${score}`)
57
+ if (source.url) {
58
+ lines.push(` ${source.url}`)
59
+ }
60
+
61
+ if (source.excerpt) {
62
+ lines.push('', quote(source.excerpt.trim()).replace(/^/gm, ' '), '')
63
+ }
64
+ }
65
+
66
+ return lines
67
+ }
68
+
69
+ function segmentSection(segment) {
70
+ const { type, detail } = segment
71
+ if (type === 'thinking') {
72
+ return ['### Thinking', '', quote(segment.text.trim())]
73
+ }
74
+
75
+ if (type === 'content') {
76
+ return ['### Answer', '', segment.text.trim()]
77
+ }
78
+
79
+ if (type === 'tool-call') {
80
+ return [`### Tool call — \`${detail.name}\``, '', json(detail.arguments)]
81
+ }
82
+
83
+ if (type === 'tool-result') {
84
+ return [`### Tool result — \`${detail.name}\``, '', json(detail.result)]
85
+ }
86
+
87
+ if (type === 'attachment') {
88
+ return [`- **attachment:** ${detail.fileName} (${detail.mimeType}, ${detail.byteLength}B)`]
89
+ }
90
+
91
+ if (type === 'sources') {
92
+ return sourcesSection(detail)
93
+ }
94
+
95
+ if (type === 'approval-request') {
96
+ const call = detail.resource
97
+ ? `${detail.name} → ${detail.resource.kind} ${detail.resource.label}`
98
+ : `${detail.name}(${JSON.stringify(detail.arguments)})`
99
+ return [`### Approval — ${detail.status}`, '', call]
100
+ }
101
+
102
+ return ['### Answer', '', (segment.text ?? '').trim()]
103
+ }
104
+
105
+ function agentSection(turn, index) {
106
+ const status = STATUS[turn.status] ?? turn.status ?? 'in flight'
107
+ const lines = [`## Run ${index} — ${status}`, '']
108
+ for (const segment of turn.segments) {
109
+ lines.push(...segmentSection(segment), '')
110
+ }
111
+
112
+ if (turn.status === 'failed') {
113
+ lines.push(`> **failed:** ${turn.statusReason ?? 'unknown'}`, '')
114
+ }
115
+
116
+ const metrics = metricsLine(turn)
117
+ if (metrics) {
118
+ lines.push(metrics, '')
119
+ }
120
+
121
+ return lines
122
+ }
123
+
124
+ function userSection(turn) {
125
+ const lines = ['## Prompt', '']
126
+ for (const segment of turn.segments) {
127
+ if (segment.type === 'attachment') {
128
+ lines.push(...segmentSection(segment), '')
129
+ } else {
130
+ lines.push((segment.text ?? '').trim(), '')
131
+ }
132
+ }
133
+
134
+ return lines
135
+ }
136
+
137
+ // the nth-from-last run, plus the user turn right before it
138
+ function startOfRuns(turns, runs) {
139
+ const runAt = []
140
+ for (const [index, turn] of turns.entries()) {
141
+ if (turn.from === 'agent' && (turn.segments.length || turn.status)) {
142
+ runAt.push(index)
143
+ }
144
+ }
145
+
146
+ if (!runAt.length) {
147
+ return -1
148
+ }
149
+
150
+ let start = runAt[Math.max(0, runAt.length - runs)]
151
+ while (start > 0 && turns[start - 1].from === 'user') {
152
+ start--
153
+ }
154
+
155
+ return start
156
+ }
157
+
158
+ export function exportMarkdown(turns, runs = 1, meta = {}) {
159
+ const start = startOfRuns(turns, runs)
160
+ if (start < 0) {
161
+ return null
162
+ }
163
+
164
+ const lines = [`# ${meta.title ?? 'Chat'}`, '']
165
+ if (meta.chatId) {
166
+ lines.push(`- **chat:** \`${meta.chatId}\``)
167
+ }
168
+
169
+ if (meta.agentName) {
170
+ lines.push(`- **agent:** ${meta.agentName}`)
171
+ }
172
+
173
+ if (meta.modelName) {
174
+ lines.push(`- **model:** ${modelLabel(meta.modelName)}`)
175
+ }
176
+
177
+ lines.push(`- **exported:** ${new Date(meta.at ?? Date.now()).toISOString()}`, '')
178
+
179
+ let index = 0
180
+ for (const turn of turns.slice(start)) {
181
+ if (turn.from === 'compaction') continue
182
+ lines.push('---', '')
183
+ if (turn.from === 'user') {
184
+ lines.push(...userSection(turn))
185
+ } else {
186
+ lines.push(...agentSection(turn, ++index))
187
+ }
188
+ }
189
+
190
+ return `${lines
191
+ .join('\n')
192
+ .replace(/\n{3,}/g, '\n\n')
193
+ .trim()}\n`
194
+ }
@@ -0,0 +1,84 @@
1
+ import { resolveLocalPath } from './local-path.mjs'
2
+
3
+ const USAGE = 'usage: /folders [list] · /folders add <path> [ro|rw] · /folders remove <path>'
4
+ const ACCESS = new Map([
5
+ ['ro', 'read'],
6
+ ['rw', 'write']
7
+ ])
8
+ const LABEL = { read: 'ro', write: 'rw' }
9
+
10
+ // host: the agent runs elsewhere
11
+ export async function foldersCommand(engine, { agent, host = null }, input) {
12
+ if (host) {
13
+ return {
14
+ type: 'notice',
15
+ text: `${agent.name} runs on ${host}, so its folders are shared there · run /folders on that device`
16
+ }
17
+ }
18
+
19
+ try {
20
+ return { type: 'notice', text: await execute(engine, agent, input) }
21
+ } catch (error) {
22
+ return { type: 'run.error', error }
23
+ }
24
+ }
25
+
26
+ async function execute(engine, agent, input) {
27
+ const agentId = agent.id
28
+ const { action, argument } = parseInput(input)
29
+ if (!action || action === 'list') {
30
+ const { folders } = await engine.listAgentFolders({ agentId })
31
+
32
+ return folders?.length ? formatFolders(agent, folders) : empty(agent)
33
+ }
34
+
35
+ if (action === 'add' && argument) {
36
+ // the access is the last word, so a path with spaces needs no quotes
37
+ const [, given, flag = 'ro'] = argument.match(/^(.*?)(?:\s+(ro|rw))?$/)
38
+ const access = ACCESS.get(flag)
39
+ const path = resolveLocalPath(unquote(given))
40
+ const { folders } = await engine.addAgentFolder({ agentId, path, access })
41
+ const can = access === 'write' ? 'read and edit' : 'read'
42
+
43
+ return [`${agent.name} can ${can} ${path} from its next message`, ...rows(folders)].join('\n')
44
+ }
45
+
46
+ if (action === 'remove' && argument) {
47
+ const path = resolveLocalPath(unquote(argument))
48
+ await engine.removeAgentFolder({ agentId, path })
49
+
50
+ return `stopped sharing ${path} with ${agent.name}`
51
+ }
52
+
53
+ return USAGE
54
+ }
55
+
56
+ function empty(agent) {
57
+ return `no folders shared with ${agent.name} on this device · /folders add <path> [ro|rw]`
58
+ }
59
+
60
+ function formatFolders(agent, folders) {
61
+ return [
62
+ `folders ${agent.name} can use on this device (relative paths start in the first):`,
63
+ ...rows(folders)
64
+ ].join('\n')
65
+ }
66
+
67
+ function rows(folders) {
68
+ return folders.map((folder) => ` ${LABEL[folder.access]} ${folder.path}`)
69
+ }
70
+
71
+ function parseInput(input) {
72
+ const value = input.trim()
73
+ const separator = value.search(/\s/)
74
+ if (separator === -1) {
75
+ return { action: value, argument: '' }
76
+ }
77
+
78
+ return { action: value.slice(0, separator), argument: value.slice(separator).trim() }
79
+ }
80
+
81
+ function unquote(value) {
82
+ const match = value.match(/^(["'])(.*)\1$/)
83
+ return match ? match[2] : value
84
+ }