@qvac/core 0.2.2 → 0.3.1

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 (176) hide show
  1. package/dist-lib/lib/api/agents.js +2 -3
  2. package/dist-lib/lib/api/chat.d.ts +3 -1
  3. package/dist-lib/lib/api/chat.js +9 -5
  4. package/dist-lib/lib/api/chunks.d.ts +1 -1
  5. package/dist-lib/lib/api/chunks.js +5 -15
  6. package/dist-lib/lib/api/current-mesh.d.ts +16 -1
  7. package/dist-lib/lib/api/current-mesh.js +18 -0
  8. package/dist-lib/lib/api/devices.js +6 -3
  9. package/dist-lib/lib/api/index.d.ts +2 -0
  10. package/dist-lib/lib/api/index.js +4 -2
  11. package/dist-lib/lib/api/inference-calls.d.ts +18 -0
  12. package/dist-lib/lib/api/inference-calls.js +15 -0
  13. package/dist-lib/lib/api/knowledge.js +11 -7
  14. package/dist-lib/lib/api/members.js +2 -3
  15. package/dist-lib/lib/api/rag.js +10 -2
  16. package/dist-lib/lib/api/sync.d.ts +1 -1
  17. package/dist-lib/lib/api/sync.js +2 -1
  18. package/dist-lib/lib/api/tool-activity.js +2 -2
  19. package/dist-lib/lib/api/tool-configs.js +2 -2
  20. package/dist-lib/lib/api/watchable.d.ts +6 -1
  21. package/dist-lib/lib/api/watchable.js +13 -2
  22. package/dist-lib/lib/assistant/harness.d.ts +1 -0
  23. package/dist-lib/lib/assistant/history.d.ts +1 -2
  24. package/dist-lib/lib/assistant/history.js +0 -6
  25. package/dist-lib/lib/assistant-tree.d.ts +2 -0
  26. package/dist-lib/lib/assistant-tree.js +11 -2
  27. package/dist-lib/lib/assistant.d.ts +17 -8
  28. package/dist-lib/lib/assistant.js +172 -125
  29. package/dist-lib/lib/core/chunk.d.ts +1 -0
  30. package/dist-lib/lib/core/chunk.js +32 -0
  31. package/dist-lib/lib/core/contract/devices.js +3 -2
  32. package/dist-lib/lib/core/files/rag/build.d.ts +1 -2
  33. package/dist-lib/lib/core/files/rag/build.js +1 -2
  34. package/dist-lib/lib/core/files/rag/extract/office-collabora.d.ts +1 -1
  35. package/dist-lib/lib/core/files/rag/index.d.ts +4 -24
  36. package/dist-lib/lib/core/files/rag/index.js +3 -17
  37. package/dist-lib/lib/core/files/rag/load.d.ts +1 -2
  38. package/dist-lib/lib/core/files/rag/load.js +1 -2
  39. package/dist-lib/lib/core/files/rag/produce.d.ts +1 -1
  40. package/dist-lib/lib/core/files/rag/produce.js +1 -3
  41. package/dist-lib/lib/core/files/rag/retrieval/full-text.d.ts +1 -1
  42. package/dist-lib/lib/core/files/rag/retrieval/full-text.js +1 -4
  43. package/dist-lib/lib/core/files/rag/similarity.d.ts +5 -0
  44. package/dist-lib/lib/core/files/rag/similarity.js +6 -0
  45. package/dist-lib/lib/core/files/upload.d.ts +1 -1
  46. package/dist-lib/lib/core/harness-loan.js +1 -1
  47. package/dist-lib/lib/core/inference-calls-handoff.d.ts +20 -0
  48. package/dist-lib/lib/core/inference-calls-handoff.js +37 -0
  49. package/dist-lib/lib/core/inference-calls-receiver.d.ts +14 -0
  50. package/dist-lib/lib/core/inference-calls-receiver.js +39 -0
  51. package/dist-lib/lib/core/local/index.js +6 -0
  52. package/dist-lib/lib/core/notification.js +5 -4
  53. package/dist-lib/lib/core.d.ts +9 -1
  54. package/dist-lib/lib/core.js +98 -16
  55. package/dist-lib/lib/fs-drive-bridge.js +1 -1
  56. package/dist-lib/lib/inference-calls.d.ts +40 -0
  57. package/dist-lib/lib/inference-calls.js +266 -0
  58. package/dist-lib/lib/mesh-scoped-engine.js +5 -0
  59. package/dist-lib/lib/model-download.d.ts +2 -0
  60. package/dist-lib/lib/model-download.js +20 -5
  61. package/dist-lib/lib/oauth/keys.js +1 -0
  62. package/dist-lib/lib/oauth/spotify.js +1 -0
  63. package/dist-lib/lib/oauth/verify.d.ts +8 -0
  64. package/dist-lib/lib/oauth/verify.js +58 -0
  65. package/dist-lib/lib/oauth.d.ts +1 -0
  66. package/dist-lib/lib/oauth.js +1 -0
  67. package/dist-lib/schema/content.js +5 -1
  68. package/dist-lib/schema/engine.js +42 -1
  69. package/dist-lib/schema/qvac.d.ts +3 -0
  70. package/dist-lib/schema/qvac.js +11 -2
  71. package/dist-lib/spec/bind.js +3 -0
  72. package/dist-lib/spec/calls.js +1 -0
  73. package/dist-lib/spec/capabilities.d.ts +2 -0
  74. package/dist-lib/spec/hrpc/hrpc.json +13 -0
  75. package/dist-lib/spec/hrpc/index.js +15 -3
  76. package/dist-lib/spec/hrpc/messages.js +172 -49
  77. package/dist-lib/spec/hyperschema/index.js +172 -49
  78. package/dist-lib/spec/hyperschema/schema.json +127 -1
  79. package/dist-lib/spec/hyperschema/types.d.ts +34 -1
  80. package/dist-lib/spec/local/hyperdb/messages.js +64 -128
  81. package/dist-lib/spec/local/hyperschema/index.js +32 -64
  82. package/dist-lib/spec/local/hyperschema/schema.json +16 -0
  83. package/dist-lib/spec/mesh/hyperdb/messages.js +176 -311
  84. package/dist-lib/spec/mesh/hyperdispatch/messages.js +132 -236
  85. package/dist-lib/spec/mesh/hyperschema/index.js +132 -236
  86. package/dist-lib/spec/mesh/hyperschema/schema.json +70 -1
  87. package/dist-lib/spec/mesh/hyperschema/types.d.ts +3 -1
  88. package/package.json +14 -17
  89. package/tui/app.mjs +327 -46
  90. package/tui/lib/knowledge-import.mjs +1 -1
  91. package/tui/lib/render.mjs +17 -1
  92. package/tui/lib/selection.mjs +16 -0
  93. package/tui/lib/usage.mjs +54 -0
  94. package/.claude/skills/asana/SKILL.md +0 -86
  95. package/.claude/skills/compaction/SKILL.md +0 -132
  96. package/.claude/skills/device-mesh-debug/SKILL.md +0 -328
  97. package/.claude/skills/gh-stack/SKILL.md +0 -181
  98. package/.claude/skills/gh-stack/references/commands.md +0 -177
  99. package/.claude/skills/gh-stack/references/stack-design.md +0 -97
  100. package/.claude/skills/gh-stack/references/troubleshooting.md +0 -159
  101. package/.claude/skills/js-house-style/SKILL.md +0 -670
  102. package/.claude/skills/pr-create/SKILL.md +0 -201
  103. package/.claude/skills/pr-review/SKILL.md +0 -424
  104. package/CLAUDE.md +0 -43
  105. package/dist-lib/lib/core/files/rag/artifact/codec.d.ts +0 -3
  106. package/dist-lib/lib/core/files/rag/artifact/codec.js +0 -172
  107. package/dist-lib/lib/core/files/rag/artifact/id.d.ts +0 -10
  108. package/dist-lib/lib/core/files/rag/artifact/id.js +0 -39
  109. package/dist-lib/lib/core/files/rag/artifact/types.d.ts +0 -24
  110. package/dist-lib/lib/core/files/rag/artifact/types.js +0 -41
  111. package/dist-lib/lib/core/files/rag/chunk/chunking.d.ts +0 -12
  112. package/dist-lib/lib/core/files/rag/chunk/chunking.js +0 -117
  113. package/dist-lib/lib/core/files/rag/chunk/metadata.d.ts +0 -30
  114. package/dist-lib/lib/core/files/rag/chunk/metadata.js +0 -89
  115. package/dist-lib/lib/core/files/rag/chunk/tokenizer.d.ts +0 -7
  116. package/dist-lib/lib/core/files/rag/chunk/tokenizer.js +0 -18
  117. package/dist-lib/lib/core/files/rag/extract/csv-text.d.ts +0 -1
  118. package/dist-lib/lib/core/files/rag/extract/csv-text.js +0 -117
  119. package/dist-lib/lib/core/files/rag/extract/document-types.d.ts +0 -22
  120. package/dist-lib/lib/core/files/rag/extract/document-types.js +0 -152
  121. package/dist-lib/lib/core/files/rag/extract/extract.d.ts +0 -17
  122. package/dist-lib/lib/core/files/rag/extract/extract.js +0 -81
  123. package/dist-lib/lib/core/files/rag/extract/html-table-text.d.ts +0 -1
  124. package/dist-lib/lib/core/files/rag/extract/html-table-text.js +0 -125
  125. package/dist-lib/lib/core/files/rag/extract/html-text.d.ts +0 -1
  126. package/dist-lib/lib/core/files/rag/extract/html-text.js +0 -132
  127. package/dist-lib/lib/core/files/rag/extract/pdf-platform.d.ts +0 -17
  128. package/dist-lib/lib/core/files/rag/extract/pdf-platform.js +0 -141
  129. package/dist-lib/lib/core/files/rag/extract/pdf-text.d.ts +0 -12
  130. package/dist-lib/lib/core/files/rag/extract/pdf-text.js +0 -43
  131. package/dist-lib/lib/core/files/rag/extract/rtf-text.d.ts +0 -1
  132. package/dist-lib/lib/core/files/rag/extract/rtf-text.js +0 -15
  133. package/dist-lib/lib/core/files/rag/extract/text-decoding.d.ts +0 -1
  134. package/dist-lib/lib/core/files/rag/extract/text-decoding.js +0 -91
  135. package/dist-lib/lib/core/files/rag/extract/types.d.ts +0 -36
  136. package/dist-lib/lib/core/files/rag/extract/types.js +0 -12
  137. package/dist-lib/lib/core/files/rag/extract/utf.d.ts +0 -2
  138. package/dist-lib/lib/core/files/rag/extract/utf.js +0 -18
  139. package/dist-lib/lib/core/files/rag/retrieval/citation-match.d.ts +0 -2
  140. package/dist-lib/lib/core/files/rag/retrieval/citation-match.js +0 -16
  141. package/dist-lib/lib/core/files/rag/retrieval/coverage.d.ts +0 -4
  142. package/dist-lib/lib/core/files/rag/retrieval/coverage.js +0 -48
  143. package/dist-lib/lib/core/files/rag/retrieval/diversity.d.ts +0 -10
  144. package/dist-lib/lib/core/files/rag/retrieval/diversity.js +0 -37
  145. package/dist-lib/lib/core/files/rag/retrieval/floor.d.ts +0 -5
  146. package/dist-lib/lib/core/files/rag/retrieval/floor.js +0 -21
  147. package/dist-lib/lib/core/files/rag/retrieval/format.d.ts +0 -6
  148. package/dist-lib/lib/core/files/rag/retrieval/format.js +0 -21
  149. package/dist-lib/lib/core/files/rag/retrieval/knowledge.d.ts +0 -2
  150. package/dist-lib/lib/core/files/rag/retrieval/knowledge.js +0 -54
  151. package/dist-lib/lib/core/files/rag/retrieval/notices.d.ts +0 -16
  152. package/dist-lib/lib/core/files/rag/retrieval/notices.js +0 -27
  153. package/dist-lib/lib/core/files/rag/retrieval/scoring.d.ts +0 -8
  154. package/dist-lib/lib/core/files/rag/retrieval/scoring.js +0 -82
  155. package/dist-lib/lib/core/files/rag/retrieval/search.d.ts +0 -3
  156. package/dist-lib/lib/core/files/rag/retrieval/search.js +0 -49
  157. package/dist-lib/lib/core/files/rag/retrieval/selection.d.ts +0 -11
  158. package/dist-lib/lib/core/files/rag/retrieval/selection.js +0 -93
  159. package/dist-lib/lib/core/files/rag/retrieval/source-tag-filter.d.ts +0 -6
  160. package/dist-lib/lib/core/files/rag/retrieval/source-tag-filter.js +0 -79
  161. package/dist-lib/lib/core/files/rag/retrieval/sources.d.ts +0 -13
  162. package/dist-lib/lib/core/files/rag/retrieval/sources.js +0 -20
  163. package/dist-lib/lib/core/files/rag/retrieval/target.d.ts +0 -13
  164. package/dist-lib/lib/core/files/rag/retrieval/target.js +0 -89
  165. package/dist-lib/lib/core/files/rag/retrieval/terms.d.ts +0 -8
  166. package/dist-lib/lib/core/files/rag/retrieval/terms.js +0 -70
  167. package/dist-lib/lib/core/files/rag/retrieval/types.d.ts +0 -29
  168. package/dist-lib/lib/core/files/rag/retrieval/types.js +0 -1
  169. package/dist-lib/lib/core/files/rag/retrieval/web-sources.d.ts +0 -8
  170. package/dist-lib/lib/core/files/rag/retrieval/web-sources.js +0 -41
  171. package/dist-lib/lib/core/files/rag/retrieval/whole-document-query.d.ts +0 -1
  172. package/dist-lib/lib/core/files/rag/retrieval/whole-document-query.js +0 -96
  173. package/dist-lib/lib/core/files/rag/vector/memory.d.ts +0 -15
  174. package/dist-lib/lib/core/files/rag/vector/memory.js +0 -135
  175. package/dist-lib/lib/core/files/rag/vector/types.d.ts +0 -28
  176. package/dist-lib/lib/core/files/rag/vector/types.js +0 -1
package/tui/app.mjs CHANGED
@@ -37,6 +37,9 @@ import { center, splash } from './lib/splash.mjs'
37
37
  import { wrapBlock, wrapLine } from './lib/wrap.mjs'
38
38
  import { knowledgeCommand } from './lib/knowledge-command.mjs'
39
39
  import { saveUniqueFile } from './lib/save-file.mjs'
40
+ import { usageReport } from './lib/usage.mjs'
41
+ import { compactionTriggerRatio } from '../dist-lib/lib/compaction.js'
42
+ import { rememberSelection } from './lib/selection.mjs'
40
43
  import {
41
44
  configureActions,
42
45
  isReady,
@@ -77,7 +80,9 @@ function fileStatusText(file) {
77
80
  // Every entry is dispatched by _command and documented in /help; `palette: true`
78
81
  // is the subset the `/` autocomplete advertises. The rest still run when typed in
79
82
  // full — they're reachable through the menu (ctrl+p), so they no longer clutter
80
- // the dropdown. See command-palette.ts, which pins these three lists together.
83
+ // the dropdown. `sub` lists the verbs a command dispatches on its second token,
84
+ // offered once the command is typed. See command-palette.ts, which pins these
85
+ // lists to the dispatcher.
81
86
  const COMMANDS = [
82
87
  { name: 'help', desc: 'list every /command with a one-liner', palette: true },
83
88
  {
@@ -87,24 +92,79 @@ const COMMANDS = [
87
92
  },
88
93
  { name: 'new-chat', desc: 'create and switch to a new chat', palette: true },
89
94
  { name: 'agents', desc: 'switch between your agents (interactive picker)', palette: true },
90
- { name: 'agent', desc: 'show, list, create, rename, or switch the active agent' },
91
- { name: 'ctx', desc: "show or set the agent's context size; ↑/↓ move, enter sets" },
95
+ {
96
+ name: 'agent',
97
+ desc: 'show, list, create, rename, or switch the active agent',
98
+ sub: [
99
+ { name: 'list', desc: 'list your agents (* marks the active one)' },
100
+ { name: 'new', desc: '<name> — create an agent hosted on this device and select it' },
101
+ { name: 'rename', desc: '<name> — rename the active agent' },
102
+ {
103
+ name: 'use',
104
+ desc: '<name|id> — switch the active agent (same chat; re-targets the next run)'
105
+ },
106
+ { name: 'borrow', desc: '[none] — borrow the model from the compute mesh, or stop borrowing' }
107
+ ]
108
+ },
109
+ {
110
+ name: 'ctx',
111
+ desc: "show or set the agent's context size; ↑/↓ move, enter sets",
112
+ sub: [{ name: 'auto', desc: 'clear the agent’s own size so the device default applies' }]
113
+ },
92
114
  {
93
115
  name: 'activity',
94
116
  desc: "list the active agent's tool-call activity (allowed/denied/auto/skip-all/blocked)"
95
117
  },
96
118
  { name: 'chats', desc: 'switch between your chats (interactive picker)', palette: true },
97
- { name: 'chat', desc: 'show, create, switch, rename, delete a chat, or toggle web search / rag' },
119
+ {
120
+ name: 'chat',
121
+ desc: 'show, create, switch, rename, delete a chat, or toggle web search / rag',
122
+ sub: [
123
+ { name: 'new', desc: '[title] — create and switch to a new chat' },
124
+ { name: 'use', desc: '<title|id> — switch to another chat' },
125
+ { name: 'rename', desc: '<title> — rename this chat' },
126
+ { name: 'del', desc: '<title|id> — delete a chat' },
127
+ { name: 'websearch', desc: 'on|off — let this chat search the web' },
128
+ { name: 'rag', desc: 'on|off — retrieve from this chat’s knowledge' }
129
+ ]
130
+ },
98
131
  {
99
132
  name: 'group',
100
133
  desc: 'list, create, rename, delete chat groups; move a chat in or out of one',
101
- palette: true
134
+ palette: true,
135
+ sub: [
136
+ { name: 'new', desc: '<name> — create a chat group' },
137
+ {
138
+ name: 'move',
139
+ desc: '<group>|- [chat] [after <chat>|first] — move a chat into a group, or out'
140
+ },
141
+ { name: 'order', desc: '<group> after <group>|first — reorder the groups themselves' },
142
+ { name: 'rename', desc: '<group> <name> — rename a group' },
143
+ { name: 'del', desc: '<group> — delete a group; its chats return to the ungrouped list' }
144
+ ]
145
+ },
146
+ {
147
+ name: 'knowledge',
148
+ desc: 'list, download, or remove knowledge in the active chat',
149
+ sub: [
150
+ { name: 'list', desc: 'knowledge and its indexing status for this chat' },
151
+ { name: 'add', desc: '<file> — index one local document into this chat' },
152
+ {
153
+ name: 'add-dir',
154
+ desc: '<directory> — index the supported files directly inside a directory'
155
+ },
156
+ { name: 'download', desc: '<n|id> — download a knowledge file' },
157
+ { name: 'remove', desc: '<n|id> — remove a knowledge file' }
158
+ ]
102
159
  },
103
- { name: 'knowledge', desc: 'list, download, or remove knowledge in the active chat' },
104
160
  {
105
161
  name: 'compact',
106
162
  desc: 'fold the older turns of this chat into a summary now, as a full window would'
107
163
  },
164
+ {
165
+ name: 'usage',
166
+ desc: 'this chat’s context usage: the window, how full it is, and what the prompt spends it on'
167
+ },
108
168
  { name: 'files', desc: 'show file readiness, progress, and failures in this chat' },
109
169
  {
110
170
  name: 'skills',
@@ -112,9 +172,30 @@ const COMMANDS = [
112
172
  palette: true
113
173
  },
114
174
  { name: 'tools', desc: 'browse installed tools; ↑/↓ move, space toggles each on/off' },
115
- { name: 'skill', desc: 'toggle a single skill on/off' },
116
- { name: 'tool', desc: 'toggle a single tool on/off' },
117
- { name: 'scope', desc: 'switch skills/tools scope between all and selected' },
175
+ {
176
+ name: 'skill',
177
+ desc: 'toggle a single skill on/off',
178
+ sub: [
179
+ { name: 'on', desc: '<name> — enable a skill for this agent (sets scope=selected)' },
180
+ { name: 'off', desc: '<name> — disable a skill for this agent (sets scope=selected)' }
181
+ ]
182
+ },
183
+ {
184
+ name: 'tool',
185
+ desc: 'toggle a single tool on/off',
186
+ sub: [
187
+ { name: 'on', desc: '<name> — enable a tool for this agent (sets scope=selected)' },
188
+ { name: 'off', desc: '<name> — disable a tool for this agent (sets scope=selected)' }
189
+ ]
190
+ },
191
+ {
192
+ name: 'scope',
193
+ desc: 'switch skills/tools scope between all and selected',
194
+ sub: [
195
+ { name: 'skills', desc: 'all|selected — every installed skill, or only the enabled list' },
196
+ { name: 'tools', desc: 'all|selected — every installed tool, or only the enabled list' }
197
+ ]
198
+ },
118
199
  {
119
200
  name: 'permissions',
120
201
  desc: "the agent's approval mode and its toolset switches; space toggles"
@@ -130,7 +211,11 @@ const COMMANDS = [
130
211
  desc: 'write the last run (or last n) to a markdown file — thinking, answer, tools',
131
212
  palette: true
132
213
  },
133
- { name: 'join', desc: "join another device's mesh with its invite (replaces this one)" },
214
+ {
215
+ name: 'join',
216
+ desc: "join another device's mesh with its invite (replaces this one)",
217
+ sub: [{ name: 'cancel', desc: 'abort a join still waiting to be admitted' }]
218
+ },
134
219
  {
135
220
  name: 'leave',
136
221
  desc: 'leave the active mesh; a fresh account is minted when nothing else is writable'
@@ -138,24 +223,57 @@ const COMMANDS = [
138
223
  {
139
224
  name: 'invite',
140
225
  desc: 'show this mesh device invite - /invite member opens your shared room and invites someone into it (your account is never shared)',
141
- palette: true
226
+ palette: true,
227
+ sub: [
228
+ {
229
+ name: 'member',
230
+ desc: '[n|id] — invite a person into your shared room (or a named room), never your account'
231
+ }
232
+ ]
142
233
  },
143
234
  { name: 'members', desc: 'list mesh members with their devices grouped', palette: true },
144
235
  // before `meshes`, so a bare /mesh offers the verb first and the list second
145
236
  {
146
237
  name: 'mesh',
147
238
  desc: 'switch which mesh is the active one, open another, or name one',
148
- palette: true
239
+ palette: true,
240
+ sub: [
241
+ { name: 'use', desc: '<n|id> — make one of your meshes the active one' },
242
+ { name: 'new', desc: '[compute] — open another shared room, or lend this device’s model' },
243
+ { name: 'label', desc: '<n|id> <name> — name a room, privately to you' }
244
+ ]
149
245
  },
150
246
  { name: 'meshes', desc: 'list the meshes this device belongs to', palette: true },
151
247
  { name: 'cred', desc: 'set a credential value for this agent' },
152
- { name: 'connect', desc: 'OAuth-connect a skill for this agent' },
248
+ {
249
+ name: 'connect',
250
+ desc: 'OAuth-connect a skill for this agent',
251
+ sub: [
252
+ { name: 'gmail', desc: 'Google OAuth (needs GOOGLE_OAUTH_CLIENT_ID + _SECRET)' },
253
+ { name: 'google-calendar', desc: 'Google OAuth (needs GOOGLE_OAUTH_CLIENT_ID + _SECRET)' },
254
+ { name: 'google-docs', desc: 'Google OAuth (needs GOOGLE_OAUTH_CLIENT_ID + _SECRET)' },
255
+ { name: 'google-drive', desc: 'Google OAuth (needs GOOGLE_OAUTH_CLIENT_ID + _SECRET)' },
256
+ { name: 'google-sheets', desc: 'Google OAuth (needs GOOGLE_OAUTH_CLIENT_ID + _SECRET)' },
257
+ { name: 'spotify', desc: 'Spotify OAuth, PKCE only (needs SPOTIFY_OAUTH_CLIENT_ID)' },
258
+ { name: 'notion', desc: 'Notion MCP OAuth, PKCE + dynamic registration (no env)' },
259
+ { name: 'asana', desc: 'Asana MCP OAuth, PKCE (needs ASANA_OAUTH_CLIENT_ID + _SECRET)' }
260
+ ]
261
+ },
153
262
  {
154
263
  name: 'my-device',
155
264
  desc: 'CPU/GPU inventory for this device (manufacturer, cores, drivers, …)'
156
265
  },
157
266
  { name: 'models', desc: 'browse every model in the SDK registry (optional type filter)' },
158
- { name: 'image', desc: 'show or set the agent’s image defaults (model, steps, size)' },
267
+ {
268
+ name: 'image',
269
+ desc: 'show or set the agent’s image defaults (model, steps, size)',
270
+ sub: [
271
+ { name: 'model', desc: '<sd2|sdxl|flux2-klein> — the diffusion model image tools use' },
272
+ { name: 'steps', desc: '<1..100> — diffusion steps per image' },
273
+ { name: 'size', desc: '<WxH> — image size in pixels' },
274
+ { name: 'reset', desc: 'back to the device defaults' }
275
+ ]
276
+ },
159
277
  { name: 'speak', desc: 'synthesize speech from text to a WAV file (TTS)' },
160
278
  { name: 'speak-stream', desc: 'synthesize speech per sentence over a duplex stream (TTS)' },
161
279
  { name: 'transcribe', desc: 'transcribe a 16kHz mono s16 WAV file to text (STT)' },
@@ -705,16 +823,22 @@ function enabledDrivers(drivers) {
705
823
  export function matchCommands(inputValue) {
706
824
  const raw = inputValue ?? ''
707
825
  if (!raw.startsWith('/')) return []
708
- const query = raw.slice(1).split(/\s+/, 1)[0].toLowerCase()
709
- // arguments after the token mean the command is chosen — exact match only,
710
- // so `/skill on x` stops surfacing /skills
711
- const committed = /\s/.test(raw.trim())
712
- const hits = COMMANDS.filter((c) =>
713
- committed ? c.name.toLowerCase() === query : c.name.toLowerCase().startsWith(query)
714
- )
715
- // the curated few first, then every other command — a bare `/` still opens on
716
- // what most people want, and typing reaches everything the TUI dispatches
717
- return [...hits.filter((c) => c.palette), ...hits.filter((c) => !c.palette)]
826
+ const [query, second, ...more] = raw.slice(1).toLowerCase().split(/\s+/)
827
+ // a space after the token means the command is chosen — exact match only, so `/skill on x`
828
+ // stops surfacing /skills — and the palette moves on to that command's own verbs
829
+ if (second === undefined) {
830
+ const hits = COMMANDS.filter((c) => c.name.startsWith(query))
831
+ // the curated few first, then every other command — a bare `/` still opens on
832
+ // what most people want, and typing reaches everything the TUI dispatches
833
+ return [...hits.filter((c) => c.palette), ...hits.filter((c) => !c.palette)]
834
+ }
835
+ const command = COMMANDS.find((c) => c.name === query)
836
+ if (!command) return []
837
+ const subs = (command.sub ?? [])
838
+ .filter((s) => (more.length ? s.name === second : s.name.startsWith(second)))
839
+ .map((s) => ({ name: `${command.name} ${s.name}`, desc: s.desc }))
840
+ // a verb under way narrows to its completions; a bare `/chat ` offers the command itself first
841
+ return second && subs.length ? subs : [command, ...subs]
718
842
  }
719
843
 
720
844
  // The dropdown never grows past PALETTE_ROWS — with every command matchable, a
@@ -828,6 +952,75 @@ function formatGpuLines(gpu) {
828
952
  return lines
829
953
  }
830
954
 
955
+ // /usage overlay: the window and how much of it the last run left in use, then what the prompt
956
+ // spends it on — every number as the run reported it, none counted here (lib/usage.mjs).
957
+ export function formatUsage(report, { title, deviceLabel }) {
958
+ const header = fg.dim.render(`Usage · ${title} — esc to return`)
959
+ if (!report) {
960
+ return [
961
+ header,
962
+ '',
963
+ fg.dim.render('no completed run in this chat yet — usage is read off the last one')
964
+ ]
965
+ }
966
+ return [
967
+ header,
968
+ '',
969
+ ...usageWindow(report, deviceLabel),
970
+ ...usageRows(report),
971
+ '',
972
+ ...usageRuns(report)
973
+ ]
974
+ }
975
+
976
+ const pct = (share) => `${Math.round(share * 100)}%`
977
+
978
+ function usageWindow({ window, occupied }, deviceLabel) {
979
+ const where = deviceLabel ? ` · as loaded on ${deviceLabel}` : ''
980
+ const lines = [` window ${window ? formatTokenCount(window) : 'not reported'}${where}`]
981
+ if (!occupied) {
982
+ lines.push(fg.dim.render(' in use not reported by the last run'))
983
+ return lines
984
+ }
985
+ const tokens = `${occupied.toLocaleString()} tokens`
986
+ if (!window) return [...lines, ` in use ${tokens}`]
987
+ const share = occupied / window
988
+ const fold = compactionTriggerRatio(window)
989
+ const filled = Math.round(share * 24)
990
+ const bar = '█'.repeat(filled) + '░'.repeat(24 - filled)
991
+ const paint = share >= fold ? fg.amber : fg.cyan
992
+ lines.push(` in use ${tokens} · ${pct(share)} ${paint.render(bar)} · folds at ${pct(fold)}`)
993
+ return lines
994
+ }
995
+
996
+ function usageRows({ rows, occupied }) {
997
+ if (!rows) return ['', fg.dim.render(' no prompt breakdown reported by the last run')]
998
+ const width = Math.max(...rows.map((row) => row.label.length))
999
+ return [
1000
+ '',
1001
+ ...rows.map(
1002
+ ({ label, tokens }) =>
1003
+ ` ${label.padEnd(width)} ${tokens.toLocaleString().padStart(7)} · ${pct(tokens / occupied).padStart(4)}`
1004
+ )
1005
+ ]
1006
+ }
1007
+
1008
+ function usageRuns({ runs, generated, folds, last }) {
1009
+ const chat = [
1010
+ `${runs} ${runs === 1 ? 'run' : 'runs'}`,
1011
+ `${generated.toLocaleString()} tokens generated`
1012
+ ]
1013
+ if (folds) chat.push(`compacted ${folds}×`)
1014
+ const parts = []
1015
+ if (last.totalTokens) parts.push(`${last.totalTokens.toLocaleString()} tok`)
1016
+ if (last.tokensPerSecond) parts.push(`${last.tokensPerSecond.toFixed(1)} tok/s`)
1017
+ if (last.timeToFirstToken) parts.push(`ttft ${Math.round(last.timeToFirstToken)}ms`)
1018
+ if (last.stopReason === 'length') parts.push('answer cut by the context window')
1019
+ const lines = [fg.dim.render(` ${chat.join(' · ')}`)]
1020
+ if (parts.length) lines.push(fg.dim.render(` last run: ${parts.join(' · ')}`))
1021
+ return lines
1022
+ }
1023
+
831
1024
  export function formatDiagnostics(stats) {
832
1025
  if (!stats) {
833
1026
  return [fg.dim.render('(no diagnostics snapshot yet — try again in a moment)')]
@@ -933,7 +1126,7 @@ const ownDefault = (agents, deviceId) => agents.find((agent) => isOwnDefault(age
933
1126
  // (agentsWatch fires on every change), no polling. This device mints one as a fallback if none
934
1127
  // shows within the timeout: an unbounded wait here blocks the composer for good, and a mesh can
935
1128
  // legitimately hold no agent - one nobody has reached yet, or one whose every agent was deleted.
936
- async function firstAgent(engine, deviceId, modelName) {
1129
+ async function firstAgent(engine, deviceId, modelName, remembered) {
937
1130
  const watch = engine.agentsWatch({})[Symbol.asyncIterator]()
938
1131
  let timer
939
1132
  const timeout = new Promise((resolve) => {
@@ -944,7 +1137,9 @@ async function firstAgent(engine, deviceId, modelName) {
944
1137
  const { value, done } = await Promise.race([watch.next(), timeout])
945
1138
  if (done) break
946
1139
  const agents = value.agents ?? []
947
- const live = ownDefault(agents, deviceId) ?? agents[0]
1140
+ // the agent the last session left active outranks the seed, as it does on the desktop
1141
+ const live =
1142
+ agents.find((agent) => agent.id === remembered) ?? ownDefault(agents, deviceId) ?? agents[0]
948
1143
  if (live) return live
949
1144
  }
950
1145
  } finally {
@@ -968,7 +1163,7 @@ async function firstAgent(engine, deviceId, modelName) {
968
1163
  // The birth op seeds a default chat too; a joiner waits for it to replicate -
969
1164
  // watch-driven like firstAgent (chatsWatch), no polling. The provider mints one
970
1165
  // as a fallback if none shows within the timeout.
971
- async function firstChat(engine, agent, isProvider) {
1166
+ async function firstChat(engine, agent, isProvider, remembered) {
972
1167
  const watch = engine.chatsWatch({})[Symbol.asyncIterator]()
973
1168
  let timer
974
1169
  const timeout = new Promise((resolve) => {
@@ -978,7 +1173,8 @@ async function firstChat(engine, agent, isProvider) {
978
1173
  while (true) {
979
1174
  const { value, done } = await Promise.race([watch.next(), timeout])
980
1175
  if (done) break
981
- const live = (value.chats ?? []).find((chat) => !chat.deletedAt)
1176
+ const chats = (value.chats ?? []).filter((chat) => !chat.deletedAt)
1177
+ const live = chats.find((chat) => chat.id === remembered) ?? chats[0]
982
1178
  if (live) return live
983
1179
  }
984
1180
  } finally {
@@ -1179,14 +1375,29 @@ export class ChatApp {
1179
1375
  return async () => {
1180
1376
  try {
1181
1377
  await firstWritable(this.engine)
1182
- let agent = await firstAgent(this.engine, this.originDeviceId, this._modelName)
1378
+ // the pick the last session persisted; null on a fake engine that has no config
1379
+ const config = this.engine.getConfig ? await this.engine.getConfig({}) : null
1380
+ let agent = await firstAgent(
1381
+ this.engine,
1382
+ this.originDeviceId,
1383
+ this._modelName,
1384
+ config?.activeAgentId
1385
+ )
1183
1386
  const isProvider = agent.providerDeviceId?.equals(this.originDeviceId) ?? false
1184
1387
  if (isProvider && this._modelName) {
1185
1388
  // Only set the model — scopes stay as the shared seed left them
1186
1389
  agent = await this.engine.updateAgent({ id: agent.id, modelName: this._modelName })
1187
1390
  }
1188
- const chat = await firstChat(this.engine, agent, isProvider)
1189
- return { type: 'booted', agent, chat }
1391
+ const chat = await firstChat(this.engine, agent, isProvider, config?.activeChatId)
1392
+ const agentRemembered = agent.id === config?.activeAgentId
1393
+ const chatRemembered = chat.id === config?.activeChatId
1394
+ // a remembered agent drives whichever chat it was left on (/agent use keeps the chat);
1395
+ // without one, the resumed chat runs under its own agent, as any switch does (_agentFor)
1396
+ if (chatRemembered && !agentRemembered && chat.agentId !== agent.id) {
1397
+ // getAgent throws for a deleted agent; the seed drives the chat then, as _agentFor does
1398
+ agent = await this.engine.getAgent({ id: chat.agentId }).catch(() => agent)
1399
+ }
1400
+ return { type: 'booted', agent, chat, remembered: agentRemembered || chatRemembered }
1190
1401
  } catch (error) {
1191
1402
  return { type: 'boot-error', error }
1192
1403
  }
@@ -1511,6 +1722,7 @@ export class ChatApp {
1511
1722
  ' /knowledge [list] · /knowledge add <file> · /knowledge add-dir <directory> · /knowledge download <n|id> · /knowledge remove <n|id>',
1512
1723
  ' /files — show upload progress, local readiness, and failures for this chat',
1513
1724
  ' /compact — fold the older turns of this chat into a summary now (what a full context window triggers on its own); the notice shows the summary or why the fold was refused',
1725
+ ' /usage — this chat’s context usage as the last run reported it: the window, how much of it is in use, and what the prompt spends it on (conversation, system prompt, agent instructions, skills, tools)',
1514
1726
  ' /attach <path> [<path> …] — attach local files to this chat (quote paths that contain spaces)',
1515
1727
  ' /save [n] — download the latest (or n-th) attachment to ~/Downloads',
1516
1728
  ' /export [n] — write the last run (or last n) to a markdown file: prompt, thinking, answer, tools',
@@ -1592,6 +1804,11 @@ export class ChatApp {
1592
1804
 
1593
1805
  if (cmd === 'my-device') return this._showDiagnostics()
1594
1806
 
1807
+ if (cmd === 'usage') {
1808
+ if (rawArgs.trim()) return notice('usage: /usage')
1809
+ return this._showUsage()
1810
+ }
1811
+
1595
1812
  if (cmd === 'ctx') {
1596
1813
  const raw = rest[0]?.toLowerCase()
1597
1814
  if (!raw) return this._showContextSizes()
@@ -1703,6 +1920,7 @@ export class ChatApp {
1703
1920
  modelName: agent.modelName
1704
1921
  })
1705
1922
  this.agent = created
1923
+ await this._persistSelection()
1706
1924
  return `created + selected ${created.name} (${created.id.slice(0, 8)}) · no skills/tools enabled`
1707
1925
  })
1708
1926
  }
@@ -1735,6 +1953,7 @@ export class ChatApp {
1735
1953
  const found = agents.find((a) => a.id === arg || a.id.startsWith(arg) || a.name === arg)
1736
1954
  if (!found) return `no agent matching: ${arg}`
1737
1955
  this.agent = found
1956
+ await this._persistSelection()
1738
1957
  return `selected ${found.name} (${found.id.slice(0, 8)})`
1739
1958
  })
1740
1959
  }
@@ -2143,7 +2362,7 @@ export class ChatApp {
2143
2362
  if (cmd === 'join') {
2144
2363
  const arg = rawArgs.trim()
2145
2364
  if (!arg) return notice('usage: /join <qvac://mesh/…> · /join cancel')
2146
- if (arg === 'cancel') {
2365
+ if (rest[0] === 'cancel') {
2147
2366
  return run(async () => {
2148
2367
  await engine.cancelMeshJoin({})
2149
2368
  return 'join canceled'
@@ -2159,7 +2378,7 @@ export class ChatApp {
2159
2378
  async () => {
2160
2379
  try {
2161
2380
  await engine.joinMesh({ invite })
2162
- const next = await engine.meshInvite({}).catch(() => null)
2381
+ const next = await engine.meshInvite({}).catch(noop)
2163
2382
  return { type: 'mesh.joined', invite: next?.invite ?? null }
2164
2383
  } catch (error) {
2165
2384
  return { type: 'mesh.joined', error }
@@ -2180,7 +2399,7 @@ export class ChatApp {
2180
2399
  async () => {
2181
2400
  try {
2182
2401
  await engine.leaveMesh({})
2183
- const next = await engine.meshInvite({}).catch(() => null)
2402
+ const next = await engine.meshInvite({}).catch(noop)
2184
2403
  return { type: 'mesh.left', invite: next?.invite ?? null }
2185
2404
  } catch (error) {
2186
2405
  return { type: 'mesh.left', error }
@@ -2527,7 +2746,8 @@ export class ChatApp {
2527
2746
  // not whichever one happens to be active (else _submit() runs the wrong provider).
2528
2747
  async _agentFor(chat) {
2529
2748
  if (chat.agentId === this.agent.id) return this.agent
2530
- return (await this.engine.getAgent({ id: chat.agentId })) ?? this.agent
2749
+ // getAgent throws for a deleted agent; the active one drives the chat then
2750
+ return this.engine.getAgent({ id: chat.agentId }).catch(() => this.agent)
2531
2751
  }
2532
2752
 
2533
2753
  _newChat(title) {
@@ -2634,7 +2854,7 @@ export class ChatApp {
2634
2854
  return { type: 'mesh.selected', text: `already on mesh ${mesh.meshId.slice(0, 8)}` }
2635
2855
  }
2636
2856
  await this.engine.selectMesh({ meshId: mesh.meshId })
2637
- const next = await this.engine.meshInvite({}).catch(() => null)
2857
+ const next = await this.engine.meshInvite({}).catch(noop)
2638
2858
  return { type: 'mesh.selected', meshId: mesh.meshId, invite: next?.invite ?? null }
2639
2859
  } catch (error) {
2640
2860
  return { type: 'mesh.selected', error }
@@ -2663,6 +2883,25 @@ export class ChatApp {
2663
2883
  return batch(...[this._watchNextDevices(), this._bootstrap()].filter(Boolean))
2664
2884
  }
2665
2885
 
2886
+ // The pick outlives the session in Core's device-local config — the same record the desktop
2887
+ // app resumes from. A fake engine without config, or a pick not yet resolved, has nothing to keep.
2888
+ async _persistSelection() {
2889
+ if (!this.engine.getConfig || !this.agent || !this.chatId) return
2890
+ await rememberSelection(this.engine, { agentId: this.agent.id, chatId: this.chatId })
2891
+ }
2892
+
2893
+ _rememberSelection() {
2894
+ if (!this.engine.getConfig) return null
2895
+ return async () => {
2896
+ try {
2897
+ await this._persistSelection()
2898
+ return { type: 'selection.remembered' }
2899
+ } catch (error) {
2900
+ return { type: 'run.error', error }
2901
+ }
2902
+ }
2903
+ }
2904
+
2666
2905
  // Swap the active chat: drop the old chat's watches, adopt the chat's owning
2667
2906
  // agent, clear the transcript + run state, and re-arm on the new chatId.
2668
2907
  _switchTo(chat, agent) {
@@ -2790,6 +3029,27 @@ export class ChatApp {
2790
3029
  ]
2791
3030
  }
2792
3031
 
3032
+ // /usage: the chat's run statuses carry the last run's own numbers; the folds say why they dropped
3033
+ _showUsage() {
3034
+ const { engine, chatId } = this
3035
+ return [
3036
+ this,
3037
+ async () => {
3038
+ try {
3039
+ const [statuses, folds, chat] = await Promise.all([
3040
+ engine.listChunks({ chatId, type: 'run-status' }),
3041
+ engine.listChunks({ chatId, type: 'compaction' }),
3042
+ engine.getChat({ id: chatId })
3043
+ ])
3044
+ const report = usageReport(statuses.chunks ?? [], folds.chunks ?? [])
3045
+ return { type: 'usage.result', report, title: chat.title }
3046
+ } catch (error) {
3047
+ return { type: 'usage.result', error }
3048
+ }
3049
+ }
3050
+ ]
3051
+ }
3052
+
2793
3053
  // /models [type]: fetch the full SDK registry via the Engine RPC (both
2794
3054
  // topologies wire harness.list into Core.listModels) and overlay it. Always
2795
3055
  // fullRegistry — the curated subset was a second command (/all-sdk-models);
@@ -2847,7 +3107,7 @@ export class ChatApp {
2847
3107
  // (pre-upgrade provider) — the selector then renders as it always did.
2848
3108
  async _skillDetail() {
2849
3109
  if (!this._skills) return null
2850
- const skills = await this._skills(this.agent?.id, this.agent?.modelName).catch(() => null)
3110
+ const skills = await this._skills(this.agent?.id, this.agent?.modelName).catch(noop)
2851
3111
  return skills ? new Map(skills.map((skill) => [skill.name, skill])) : null
2852
3112
  }
2853
3113
 
@@ -3053,6 +3313,7 @@ export class ChatApp {
3053
3313
  { label: 'Move to group…', hint: '/group move <group>|-', prefill: '/group move ' },
3054
3314
  { label: 'New group…', hint: '/group new <name>', prefill: '/group new ' },
3055
3315
  { label: 'Knowledge', hint: 'list chat knowledge', command: '/knowledge' },
3316
+ { label: 'Usage', hint: 'the context window: how full, and on what', command: '/usage' },
3056
3317
  { label: 'Compact', hint: 'fold older turns into a summary now', command: '/compact' },
3057
3318
  { label: 'Files', hint: 'readiness, progress, and failures', command: '/files' },
3058
3319
  { label: 'Attach file…', hint: '/attach <path>', prefill: '/attach ' },
@@ -3958,7 +4219,7 @@ export class ChatApp {
3958
4219
 
3959
4220
  if (msg.type === 'chat.switch') {
3960
4221
  this._switchTo(msg.chat, msg.agent)
3961
- return [this, batch(this._watchNext(), this._watchNextFiles())]
4222
+ return [this, batch(this._watchNext(), this._watchNextFiles(), this._rememberSelection())]
3962
4223
  }
3963
4224
 
3964
4225
  // /join settled. The joined mesh brings its own agents and chats, so this
@@ -4023,7 +4284,12 @@ export class ChatApp {
4023
4284
  this.chatId = msg.chat.id
4024
4285
  this._booting = false
4025
4286
  this._render()
4026
- return [this, batch(this._watchNext(), this._watchNextFiles(), this._watchOwnDefault())]
4287
+ // a remembered pick is the user's, so the seeded default must not move them off it
4288
+ const seed = msg.remembered ? null : this._watchOwnDefault()
4289
+ return [
4290
+ this,
4291
+ batch(this._watchNext(), this._watchNextFiles(), seed, this._rememberSelection())
4292
+ ]
4027
4293
  }
4028
4294
  if (msg.type === 'boot-error') {
4029
4295
  this.status = fg.err.render(`startup failed: ${msg.error.message}`)
@@ -4040,7 +4306,7 @@ export class ChatApp {
4040
4306
  this.agent = msg.agent
4041
4307
  this.notice = `selected ${msg.agent.name} (${msg.agent.id.slice(0, 8)}) · this device's default`
4042
4308
  this._render()
4043
- return [this, null]
4309
+ return [this, this._rememberSelection()]
4044
4310
  }
4045
4311
 
4046
4312
  if (msg.type === 'mesh-status') {
@@ -4099,6 +4365,19 @@ export class ChatApp {
4099
4365
  return [this, null]
4100
4366
  }
4101
4367
 
4368
+ if (msg.type === 'usage.result') {
4369
+ this._models = null
4370
+ this._selector = null
4371
+ this.overlay = msg.error
4372
+ ? [fg.err.render(`/usage failed: ${msg.error.message}`)]
4373
+ : formatUsage(msg.report, {
4374
+ title: msg.title,
4375
+ deviceLabel: this._deviceName(msg.report?.last.deviceId)
4376
+ })
4377
+ this._render()
4378
+ return [this, null]
4379
+ }
4380
+
4102
4381
  // /models resolved: an interactive overlay (↑/↓ + enter to adopt a model)
4103
4382
  // until esc; a rejection is a static err line instead of a silent dismiss.
4104
4383
  if (msg.type === 'models.result') {
@@ -4347,13 +4626,13 @@ export class ChatApp {
4347
4626
  return [this, null]
4348
4627
  }
4349
4628
 
4350
- // Enter runs the highlighted palette row when the user is still choosing a
4351
- // command (no argument typed yet); once an argument follows — or the line
4352
- // came from history — the typed line is authoritative and submits verbatim.
4629
+ // Enter runs the highlighted palette row while the user is still choosing — the typed
4630
+ // line is a prefix of that row, `/chat n` for `/chat new`; once an argument follows — or
4631
+ // the line came from history — the typed line is authoritative and submits verbatim.
4353
4632
  if (key.matches(msg, 'enter')) {
4354
- if (inPalette && !/\s/.test(this.input.value.trim())) {
4355
- this._setInput(`/${matches[Math.min(this._paletteAt, matches.length - 1)].name}`)
4356
- }
4633
+ const pick = matches[Math.min(this._paletteAt, matches.length - 1)]
4634
+ const typed = this.input.value.trim().slice(1).toLowerCase()
4635
+ if (inPalette && pick.name.startsWith(typed)) this._setInput(`/${pick.name}`)
4357
4636
  return this._submit()
4358
4637
  }
4359
4638
 
@@ -4849,3 +5128,5 @@ export class ChatApp {
4849
5128
  return [header, body, this._skillsLine(), inputBox, footer].join('\n')
4850
5129
  }
4851
5130
  }
5131
+
5132
+ function noop() {}
@@ -2,7 +2,7 @@ import fs from 'fs'
2
2
  import os from 'os'
3
3
  import path from 'path'
4
4
  import { fileURLToPath } from 'url'
5
- import { RAG_ACCEPT_EXTENSIONS } from '../../dist-lib/lib/core/files/rag/extract/document-types.js'
5
+ import { RAG_ACCEPT_EXTENSIONS } from 'rag-extract'
6
6
  import { UPLOAD_FRAME_BYTES, writeFrame } from './upload-frames.mjs'
7
7
  const ACCEPTED = new Set(RAG_ACCEPT_EXTENSIONS)
8
8
  const MIME_TYPES = new Map([
@@ -8,6 +8,22 @@ const PAYLOAD_FIELDS = {
8
8
  attachment: 'attachment'
9
9
  }
10
10
 
11
+ // A fold before a run is written after the message that triggered it and before any of
12
+ // its answer, so the marker goes above that message: that is where the folded history ends.
13
+ // An upload is appended before the message it belongs to, so the marker goes above it too.
14
+ function foldMarkerIndex(turns) {
15
+ let at = turns.length
16
+ while (at > 0 && turns[at - 1].from === 'agent' && turns[at - 1].segments.length === 0) at--
17
+ if (at === turns.length || at === 0 || turns[at - 1].from !== 'user') return turns.length
18
+ at--
19
+ while (at > 0 && turns[at - 1].from === 'user' && isUpload(turns[at - 1])) at--
20
+ return at
21
+ }
22
+
23
+ function isUpload(turn) {
24
+ return turn.segments.every((segment) => segment.type === 'attachment')
25
+ }
26
+
11
27
  export function turnsFromChunks(chunks) {
12
28
  const turns = []
13
29
  const byRun = new Map()
@@ -36,7 +52,7 @@ export function turnsFromChunks(chunks) {
36
52
  // A fold has no run: grouped by its absent runId it would become an agent turn that
37
53
  // never reaches a terminal state, and the busy gate would stay up on it.
38
54
  if (chunk.type === 'compaction') {
39
- turns.push({ from: 'compaction', segments: [] })
55
+ turns.splice(foldMarkerIndex(turns), 0, { from: 'compaction', segments: [] })
40
56
  continue
41
57
  }
42
58
  let turn = byRun.get(chunk.runId)