shapewall 0.2.2 → 0.2.4

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 (49) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/agent/package-lock.json +2 -2
  3. package/dist/client/assets/BoardChat-C0a3DDjv.js +28 -0
  4. package/dist/client/assets/{BuzzDialog-HWXBy52W.js → BuzzDialog-CZdwIQLF.js} +1 -1
  5. package/dist/client/assets/ChecksPanel-BHWgwJWO.js +1 -0
  6. package/dist/client/assets/{History-CEv6b-av.js → History-C01qLFpP.js} +1 -1
  7. package/dist/client/assets/LocalSettings-B5gtfKEl.js +1 -0
  8. package/dist/client/assets/{Management-DCfhcEUY.js → Management-BxEUZAmI.js} +1 -1
  9. package/dist/client/assets/QuickConnect-BzTM3UNO.js +1 -0
  10. package/dist/client/assets/{ShareDialog-C_plIto0.js → ShareDialog-CdVAreaw.js} +1 -1
  11. package/dist/client/assets/{app-update-dialog-2hPz_N9G.js → app-update-dialog-BONq9YFp.js} +1 -1
  12. package/dist/client/assets/{circle-x-BZMPi8Zf.js → circle-x-BmT6vHKl.js} +1 -1
  13. package/dist/client/assets/index-C1IsGdGs.js +29 -0
  14. package/dist/client/assets/index-DnsWelgZ.css +2 -0
  15. package/dist/client/assets/{refresh-cw-CRow0Nbq.js → refresh-cw-ugt3cWKH.js} +1 -1
  16. package/dist/client/assets/{square-A8EnIYLR.js → square-_KG6tM5A.js} +1 -1
  17. package/dist/client/assets/{ui-CLbws0rx.js → ui-BAGBTB_P.js} +1 -1
  18. package/dist/client/build-info.json +1 -1
  19. package/dist/client/index.html +3 -3
  20. package/dist/client/sw.js +2 -2
  21. package/dist/console/assets/LocalAccountsApp-DtfTDbQg.js +1 -0
  22. package/dist/console/assets/LocalConsole-BPpsxDq_.js +1 -0
  23. package/dist/console/assets/app-update-dialog-o4QY_jL9.js +1 -0
  24. package/dist/console/assets/console-DeOji9Zv.css +2 -0
  25. package/dist/console/assets/console-MvFrlUCC.js +51 -0
  26. package/dist/console/build-info.json +1 -1
  27. package/dist/console/console.html +2 -2
  28. package/docs/agents.md +61 -35
  29. package/docs/design-system.md +23 -12
  30. package/docs/journeys.md +13 -1
  31. package/package.json +1 -1
  32. package/src/agent/backends/acp.js +229 -41
  33. package/src/agent/manage.js +1 -1
  34. package/src/agent/options-cache.js +52 -0
  35. package/src/agent/routes.js +171 -6
  36. package/src/agent/run.js +20 -1
  37. package/src/agent/settings-events.js +103 -0
  38. package/src/agent/settings-routes.js +24 -2
  39. package/dist/client/assets/BoardChat-D5SFd8HE.js +0 -28
  40. package/dist/client/assets/ChecksPanel-DTdImWoD.js +0 -1
  41. package/dist/client/assets/LocalSettings-C4vriEVQ.js +0 -1
  42. package/dist/client/assets/QuickConnect-DQGgUsl1.js +0 -1
  43. package/dist/client/assets/index-ByQRKVit.css +0 -2
  44. package/dist/client/assets/index-DweQ8Qtu.js +0 -29
  45. package/dist/console/assets/LocalAccountsApp-BQCcmj3x.js +0 -1
  46. package/dist/console/assets/LocalConsole-Bb2FUDs7.js +0 -1
  47. package/dist/console/assets/app-update-dialog-DIeYepLZ.js +0 -1
  48. package/dist/console/assets/console-C7uJLLOn.js +0 -51
  49. package/dist/console/assets/console-R8IBY3Am.css +0 -2
@@ -24,7 +24,7 @@ import { randomBytes } from 'node:crypto'
24
24
  import { spawn } from 'node:child_process'
25
25
  import { Readable, Writable } from 'node:stream'
26
26
  import { PROTOCOL_VERSION, RequestError, client, ndJsonStream } from '@agentclientprotocol/sdk'
27
- import { TERMINAL_ENV_ALLOWED, agentEnv, formatCommand, loginHint, terminalEnvRefused } from '../acp/command.js'
27
+ import { TERMINAL_ENV_ALLOWED, acpAgentKind, agentEnv, formatCommand, loginHint, terminalEnvRefused } from '../acp/command.js'
28
28
  import { createSandbox, SandboxError } from '../acp/sandbox.js'
29
29
  import { ACP_PREAMBLE, NEXT_STEPS_PROMPT, NO_IMAGES_NOTE, quoteData } from '../context.js'
30
30
  import { AgentError } from '../errors.js'
@@ -67,38 +67,115 @@ export function sessionChoices(session) {
67
67
  return `${name}: ${showable(String(selected?.name || option.currentValue)).slice(0, 120)}`
68
68
  })
69
69
  }
70
- // The pickers the composer may show: model and reasoning effort selects as
71
- // the agent lists them, display text made showable and bounded.
70
+ // The composer's option menus: the session's own select config options as
71
+ // the agent lists them (model, thinking level, mode, then any other), with
72
+ // display text made showable and bounded. Never a credential, path, command
73
+ // or permission setting, and never a mode or value that lets the agent act
74
+ // without asking (bypass, yolo, accept edits, full access, ...): the panel
75
+ // promises that the agent asks before it changes files or runs commands.
76
+ // An agent that reports its modes the older way (session/new `modes`, set
77
+ // with session/set_mode) gets the same "mode" option, id MODE_OPTION_ID.
72
78
  const OPTION_VALUES_MAX = 60
73
- export function sessionOptions(configOptions) {
74
- return (Array.isArray(configOptions) ? configOptions : [])
79
+ const OPTIONS_MAX = 5
80
+ export const MODE_OPTION_ID = 'shapewall:mode'
81
+ const CATEGORY_ORDER = ['model', 'thought_level', 'mode']
82
+ const UNSAFE_VALUE_RE =
83
+ /bypass|yolo|danger|full[\s_-]?access|accept[\s_-]?(all|edits?)|\bauto\b|never[\s_-]?ask|no[\s_-]?ask|skip[\s_-]?(perm|approv)|don'?t[\s_-]?ask|trust/i
84
+ const SENSITIVE_OPTION_RE =
85
+ /perm|approv|sandbox|trust|auth|login|key|token|secret|credential|password|env|path|dir|folder|command|shell|mcp|url|host|endpoint|proxy|network/i
86
+
87
+ const optionValues = (list) =>
88
+ (Array.isArray(list) ? list : [])
89
+ .flatMap((item) => (Array.isArray(item?.options) ? item.options : [item]))
90
+ .filter((item) => typeof item?.value === 'string')
91
+ .slice(0, OPTION_VALUES_MAX)
92
+ .map((item) => ({
93
+ value: item.value.slice(0, 200),
94
+ name: showable(String(item.name || item.value)).slice(0, 80),
95
+ ...(item.description ? { description: showable(String(item.description)).slice(0, 160) } : {}),
96
+ }))
97
+
98
+ // Only the current value and safe ones of a mode or an uncategorised option.
99
+ const safeValues = (category, values, current) =>
100
+ ['model', 'thought_level'].includes(category)
101
+ ? values
102
+ : values.filter((item) => item.value === current || !UNSAFE_VALUE_RE.test(`${item.value} ${item.name}`))
103
+
104
+ export function sessionOptions(configOptions, modes = null) {
105
+ const out = (Array.isArray(configOptions) ? configOptions : [])
75
106
  .filter(
76
107
  (option) =>
77
- ['model', 'thought_level'].includes(option?.category) &&
78
- (option.type === undefined || option.type === 'select') &&
108
+ (option?.type === undefined || option.type === 'select') &&
79
109
  typeof option.id === 'string' &&
80
- typeof option.currentValue === 'string',
110
+ typeof option.currentValue === 'string' &&
111
+ (CATEGORY_ORDER.includes(option.category) || !SENSITIVE_OPTION_RE.test(`${option.id} ${option.name || ''}`)),
81
112
  )
82
- .slice(0, 2)
83
113
  .map((option) => {
84
- const values = (Array.isArray(option.options) ? option.options : [])
85
- .flatMap((item) => (Array.isArray(item?.options) ? item.options : [item]))
86
- .filter((item) => typeof item?.value === 'string')
87
- .slice(0, OPTION_VALUES_MAX)
88
- .map((item) => ({
89
- value: item.value.slice(0, 200),
90
- name: showable(String(item.name || item.value)).slice(0, 80),
91
- ...(item.description ? { description: showable(String(item.description)).slice(0, 160) } : {}),
92
- }))
114
+ const category = CATEGORY_ORDER.includes(option.category) ? option.category : 'other'
93
115
  return {
94
116
  id: option.id.slice(0, 100),
95
- category: option.category,
96
- name: showable(String(option.name || option.category)).slice(0, 60),
117
+ category,
118
+ name: showable(String(option.name || option.category || option.id)).slice(0, 60),
119
+ ...(option.description ? { description: showable(String(option.description)).slice(0, 160) } : {}),
97
120
  currentValue: option.currentValue,
98
- values,
121
+ values: safeValues(category, optionValues(option.options), option.currentValue),
99
122
  }
100
123
  })
124
+ const available = Array.isArray(modes?.availableModes) ? modes.availableModes : []
125
+ if (!out.some((option) => option.category === 'mode') && typeof modes?.currentModeId === 'string' && available.length) {
126
+ out.push({
127
+ id: MODE_OPTION_ID,
128
+ category: 'mode',
129
+ name: 'Mode',
130
+ currentValue: modes.currentModeId,
131
+ values: safeValues(
132
+ 'mode',
133
+ optionValues(available.map((item) => ({ value: item?.id, name: item?.name, description: item?.description }))),
134
+ modes.currentModeId,
135
+ ),
136
+ })
137
+ }
138
+ // One of each of the known kinds (the first the agent lists), in that order, then the rest.
139
+ const rank = (option) => (CATEGORY_ORDER.includes(option.category) ? CATEGORY_ORDER.indexOf(option.category) : CATEGORY_ORDER.length)
140
+ const seen = new Set()
141
+ return out
101
142
  .filter((option) => option.values.length > 1)
143
+ .filter((option) => {
144
+ if (option.category === 'other') return true
145
+ if (seen.has(option.category)) return false
146
+ seen.add(option.category)
147
+ return true
148
+ })
149
+ .sort((a, b) => rank(a) - rank(b))
150
+ .slice(0, OPTIONS_MAX)
151
+ }
152
+
153
+ // What a turn ran with, for the answer's meta line: the model and the
154
+ // thinking level, by their display names.
155
+ export function usedOptions(options) {
156
+ return (options || [])
157
+ .filter((option) => ['model', 'thought_level'].includes(option.category))
158
+ .map((option) => {
159
+ const item = option.values.find((value) => value.value === option.currentValue)
160
+ return {
161
+ category: option.category,
162
+ name: option.name,
163
+ value: item?.name || showable(option.currentValue).slice(0, 80),
164
+ // "Default" models often say which model that is now (the meta line names it).
165
+ ...(item?.description && /^default\b/i.test(item.name) ? { description: item.description } : {}),
166
+ }
167
+ })
168
+ }
169
+
170
+ // A composer's choices ({ configId: value }) as sent to the server: a few
171
+ // string pairs, bounded; anything else is dropped.
172
+ export function cleanChoices(value) {
173
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return {}
174
+ const out = {}
175
+ for (const [key, item] of Object.entries(value).slice(0, 8)) {
176
+ if (typeof key === 'string' && key.length <= 100 && typeof item === 'string' && item.length <= 200) out[key] = item
177
+ }
178
+ return out
102
179
  }
103
180
  const KILL_GRACE_MS = 2000
104
181
  const POSIX = process.platform !== 'win32'
@@ -193,9 +270,13 @@ function stopTree(child) {
193
270
  return child.treeStopping
194
271
  }
195
272
 
196
- async function reserveProcessSlot(processPool, agent, signal) {
273
+ // `evict: false` (a session started only to read its options): a full pool
274
+ // is busy, never a reason to stop another thread's session.
275
+ async function reserveProcessSlot(processPool, agent, signal, { evict = true } = {}) {
197
276
  if (!processPool) return
198
277
  const epoch = processPool.epoch
278
+ if (processPool.agents.size >= processPool.max && !evict)
279
+ throw new AgentError('agent_busy', 'Native agents are busy in other threads. Try again in a moment.', 429)
199
280
  if (processPool.agents.size >= processPool.max) {
200
281
  const idle = [...processPool.agents].filter((item) => !item.turn && item.state === 'ready').sort((a, b) => a.usedAt - b.usedAt)
201
282
  if (![...processPool.agents].some((item) => item.killedFor && item.stoppingPromise)) idle[0]?.kill('evicted')
@@ -228,6 +309,13 @@ async function reserveProcessSlot(processPool, agent, signal) {
228
309
  if (signal?.aborted) throw new AgentError('agent_stopped', 'The agent start was cancelled.', 409)
229
310
  if (processPool.epoch !== epoch) throw new AgentError('agent_start', 'The server is stopping.')
230
311
  processPool.agents.add(agent)
312
+ processPool.changed?.()
313
+ }
314
+
315
+ // The pool's agents changed (one started, became ready or went away): the
316
+ // open views refetch the agents' states (routes.js processPool.changed).
317
+ function poolChanged(processPool) {
318
+ processPool?.changed?.()
231
319
  }
232
320
 
233
321
  // A queue a turn's events go into and the backend's stream reads from.
@@ -328,11 +416,17 @@ export function modelFailureAnswer(text) {
328
416
 
329
417
  // The chat error for an agent that is not logged in, with how to fix it for
330
418
  // that agent (from the command: src/agent/acp/command.js loginHint).
419
+ // `login`: the one command that signs that agent in, for the chat's card
420
+ // (copyable), when there is one.
421
+ const LOGIN_COMMANDS = { claude: 'claude auth login', codex: 'codex login', goose: 'goose configure', gemini: 'gemini' }
331
422
  export function authError(label, argv) {
332
- return new AgentError(
423
+ const error = new AgentError(
333
424
  'agent_auth',
334
425
  `${label} is not logged in (or not set up) on this machine. To fix it, ${loginHint(argv)}; then send again.`,
335
426
  )
427
+ error.login = LOGIN_COMMANDS[acpAgentKind(argv)] || null
428
+ error.label = label
429
+ return error
336
430
  }
337
431
 
338
432
  // What the person's turn looks like to the agent: on a new session, the
@@ -490,6 +584,9 @@ class AcpProcess {
490
584
  this.sessionId = session.sessionId
491
585
  this.choices = sessionChoices(session)
492
586
  this.configOptions = Array.isArray(session.configOptions) ? session.configOptions : []
587
+ this.modes = session.modes && typeof session.modes === 'object' ? session.modes : null
588
+ // As the session started, before any chat's choices: what a new chat starts from.
589
+ this.startOptions = sessionOptions(this.configOptions, this.modes)
493
590
  this.state = 'ready'
494
591
  } catch (error) {
495
592
  throw this.startError(error)
@@ -674,24 +771,61 @@ class AcpProcess {
674
771
  turn.killTimer.unref?.()
675
772
  }
676
773
 
677
- // The composer's model and effort pickers: one of the session's own
678
- // config options (model or thought_level, select only) to one of the
679
- // values it lists. Never while a turn runs; never a mode (permission
680
- // modes stay the agent's own setting, docs/agents.md).
774
+ // The composer's option menus, as sessionOptions lists them.
775
+ options() {
776
+ return sessionOptions(this.configOptions, this.modes)
777
+ }
778
+ // The same menus with the values the session started with (the agent's
779
+ // defaults): what the options cache keeps for the next new chat.
780
+ defaults() {
781
+ const now = this.options()
782
+ const start = new Map((this.startOptions || []).map((option) => [option.id, option.currentValue]))
783
+ return now.map((option) =>
784
+ start.has(option.id) && option.values.some((item) => item.value === start.get(option.id))
785
+ ? { ...option, currentValue: start.get(option.id) }
786
+ : option,
787
+ )
788
+ }
789
+
790
+ // One of those options to one of the values it lists: a config option
791
+ // through session/set_config_option, the older modes through
792
+ // session/set_mode. Never while a turn runs; never a value sessionOptions
793
+ // leaves out (one that would let the agent act without asking).
681
794
  async setOption(configId, value) {
682
795
  if (this.state !== 'ready' || this.turn) throw new AgentError('agent_running', 'Wait for the answer to finish before switching.', 409)
683
- const option = sessionOptions(this.configOptions).find((item) => item.id === configId)
796
+ const option = this.options().find((item) => item.id === configId)
684
797
  if (!option || !option.values.some((item) => item.value === value))
685
798
  throw new AgentError('bad_option', 'The agent does not offer that choice.', 400)
799
+ if (option.currentValue === value) return this.options()
686
800
  let result
687
801
  try {
688
- result = await this.connection.agent.request('session/set_config_option', { sessionId: this.sessionId, configId, value })
802
+ result =
803
+ configId === MODE_OPTION_ID
804
+ ? await this.connection.agent.request('session/set_mode', { sessionId: this.sessionId, modeId: value })
805
+ : await this.connection.agent.request('session/set_config_option', { sessionId: this.sessionId, configId, value })
689
806
  } catch (error) {
690
807
  throw new AgentError('agent_upstream', `${this.label} did not switch (${cut(errorText(error) || 'no answer', 200)}).`, 502)
691
808
  }
692
- if (Array.isArray(result?.configOptions)) this.configOptions = result.configOptions
809
+ if (configId === MODE_OPTION_ID) this.modes = { ...this.modes, currentModeId: value }
810
+ else if (Array.isArray(result?.configOptions)) this.configOptions = result.configOptions
693
811
  else this.configOptions = this.configOptions.map((item) => (item.id === configId ? { ...item, currentValue: value } : item))
694
- return sessionOptions(this.configOptions)
812
+ return this.options()
813
+ }
814
+
815
+ // The composer's choices for this chat ({ configId: value }), before a
816
+ // turn: each one the session still offers and does not have yet. A choice
817
+ // the agent refuses keeps its own value (logged, never fatal).
818
+ async applyChoices(choices) {
819
+ for (const [configId, value] of Object.entries(choices || {})) {
820
+ if (this.state !== 'ready' || this.turn) return
821
+ const option = this.options().find((item) => item.id === configId)
822
+ if (!option || option.currentValue === value || !option.values.some((item) => item.value === value)) continue
823
+ try {
824
+ await this.setOption(configId, value)
825
+ } catch (error) {
826
+ this.log(`acp: ${this.label} kept its ${option.category} (${error.message})`)
827
+ }
828
+ }
695
829
  }
696
830
 
697
831
  // ---- What the agent sends ---------------------------------------------------
@@ -706,6 +840,11 @@ class AcpProcess {
706
840
  if (Array.isArray(params.update.configOptions)) this.configOptions = params.update.configOptions
707
841
  return
708
842
  }
843
+ if (params?.sessionId === this.sessionId && params.update?.sessionUpdate === 'current_mode_update') {
844
+ if (this.modes && typeof params.update.currentModeId === 'string')
845
+ this.modes = { ...this.modes, currentModeId: params.update.currentModeId }
846
+ return
847
+ }
709
848
  const turn = this.turn
710
849
  if (!turn || turn.cancelled || params?.sessionId !== this.sessionId) return
711
850
  const update = params.update || {}
@@ -1141,15 +1280,21 @@ export function createAcpBackend(
1141
1280
  const starting = new Set()
1142
1281
  let closed = false
1143
1282
 
1144
- const evictFor = () => {
1283
+ // Sessions started for their options only, while they start: a turn (or
1284
+ // another look) for the same thread waits for that one instead of starting
1285
+ // a second process.
1286
+ const preparing = new Map()
1287
+
1288
+ const evictFor = (evict) => {
1145
1289
  if (processes.size + starting.size < limit.processesMax) return
1146
1290
  const idle = [...processes.values()].filter((item) => !item.turn && item.state === 'ready').sort((a, b) => a.usedAt - b.usedAt)
1147
- if (!idle.length) throw new AgentError('agent_busy', `${settings.label} is busy in other threads. Try again in a moment.`, 429)
1291
+ if (!idle.length || !evict)
1292
+ throw new AgentError('agent_busy', `${settings.label} is busy in other threads. Try again in a moment.`, 429)
1148
1293
  idle[0].kill('evicted')
1149
1294
  }
1150
1295
 
1151
- const start = async (thread, signal) => {
1152
- evictFor()
1296
+ const start = async (thread, signal, { evict = true } = {}) => {
1297
+ evictFor(evict)
1153
1298
  const agent = new AcpProcess({
1154
1299
  argv: settings.acp.argv,
1155
1300
  label: settings.label,
@@ -1162,10 +1307,11 @@ export function createAcpBackend(
1162
1307
  onGone: (item) => {
1163
1308
  if (item.stopped || !item.pid) processPool?.agents.delete(item)
1164
1309
  if (processes.get(item.thread) === item) processes.delete(item.thread)
1310
+ poolChanged(processPool)
1165
1311
  },
1166
1312
  })
1167
1313
  if (closed) throw new AgentError('agent_start', 'The server is stopping.')
1168
- if (processPool) await reserveProcessSlot(processPool, agent, signal)
1314
+ if (processPool) await reserveProcessSlot(processPool, agent, signal, { evict })
1169
1315
  if (closed) {
1170
1316
  agent.kill('shutdown')
1171
1317
  await agent.stoppingPromise
@@ -1182,6 +1328,8 @@ export function createAcpBackend(
1182
1328
  } finally {
1183
1329
  starting.delete(agent)
1184
1330
  if (agent.stopped || !agent.pid) processPool?.agents.delete(agent)
1331
+ // Ready now, or gone.
1332
+ poolChanged(processPool)
1185
1333
  }
1186
1334
  if (closed) {
1187
1335
  agent.kill('shutdown')
@@ -1201,27 +1349,38 @@ export function createAcpBackend(
1201
1349
  vision: settings.vision !== false,
1202
1350
  label: settings.label,
1203
1351
  runMsMax: limit.runMs,
1204
- async *stream({ messages, signal, thread = 'default' }) {
1352
+ // `choices`: the composer's options for this chat ({ configId: value },
1353
+ // owner turns only), applied before the prompt. The turn then reports
1354
+ // the model and thinking level it runs with (the answer's meta line).
1355
+ async *stream({ messages, signal, thread = 'default', choices = null }) {
1205
1356
  if (signal?.aborted) return
1357
+ await preparing.get(thread)?.catch(() => {})
1206
1358
  let agent = processes.get(thread)
1207
1359
  if (agent?.turn) await agent.settled()
1208
1360
  agent = processes.get(thread)
1209
1361
  if (!agent || agent.state !== 'ready') {
1210
1362
  yield { type: 'status', text: `Starting ${settings.label}` }
1211
1363
  agent = await start(thread, signal)
1212
- for (const text of agent.choices) yield { type: 'notice', text }
1213
1364
  }
1214
1365
  if (signal?.aborted) {
1215
1366
  agent.kill('aborted')
1216
1367
  await agent.settled()
1217
1368
  return
1218
1369
  }
1370
+ await agent.applyChoices(choices)
1371
+ const used = usedOptions(agent.options())
1372
+ if (used.length) yield { type: 'options', used }
1219
1373
  yield { type: 'status', text: `${settings.label} is working` }
1220
1374
  const image = agent.image && settings.vision !== false
1221
1375
  if (!image && messages.at(-1)?.content?.some((part) => part.type === 'image')) yield { type: 'notice', text: NO_IMAGES_NOTE }
1222
1376
  const turn = agent.prompt(promptBlocks({ messages, fresh: agent.fresh, image, thread }), signal)
1223
1377
  try {
1224
1378
  for await (const event of turn.events) yield event
1379
+ } catch (error) {
1380
+ // Not signed in: this session stops, so Check again (or the next
1381
+ // message) starts the agent afresh with the new login.
1382
+ if (error?.code === 'agent_auth') agent.kill('signed_out')
1383
+ throw error
1225
1384
  } finally {
1226
1385
  turn.finish()
1227
1386
  await agent.settled()
@@ -1238,11 +1397,38 @@ export function createAcpBackend(
1238
1397
  answerPermission(thread, id, optionId, answeredBy = null) {
1239
1398
  return processes.get(thread)?.answer(id, optionId, answeredBy) ?? null
1240
1399
  },
1241
- // The composer's model and effort pickers, for a thread whose session is
1242
- // running (they come from session/new). Null without a session.
1400
+ // The composer's option menus, for a thread whose session is running
1401
+ // (they come from session/new). Null without a session.
1243
1402
  sessionOptions(thread) {
1244
1403
  const agent = processes.get(thread)
1245
- return agent && agent.state === 'ready' ? sessionOptions(agent.configOptions) : null
1404
+ return agent && agent.state === 'ready' ? agent.options() : null
1405
+ },
1406
+ // The same, with the values the session started with.
1407
+ sessionDefaults(thread) {
1408
+ const agent = processes.get(thread)
1409
+ return agent && agent.state === 'ready' ? agent.defaults() : null
1410
+ },
1411
+ // The options before the first message: the thread's session, started
1412
+ // the way its first turn would start it (and then reused by that turn),
1413
+ // or the one already running. Never evicts another thread's session; an
1414
+ // unused one stops after `idleMs` like any idle session. `choices` are
1415
+ // applied to it as they would be before a turn.
1416
+ async prepare(thread, { choices = null, signal = null } = {}) {
1417
+ if (closed) throw new AgentError('agent_start', 'The server is stopping.')
1418
+ await preparing.get(thread)?.catch(() => {})
1419
+ let agent = processes.get(thread)
1420
+ if (!agent || agent.state !== 'ready') {
1421
+ const pending = start(thread, signal, { evict: false })
1422
+ preparing.set(thread, pending)
1423
+ try {
1424
+ agent = await pending
1425
+ } finally {
1426
+ if (preparing.get(thread) === pending) preparing.delete(thread)
1427
+ }
1428
+ if (!agent.turn) agent.idle()
1429
+ }
1430
+ if (!agent.turn) await agent.applyChoices(choices)
1431
+ return agent.options()
1246
1432
  },
1247
1433
  async setSessionOption(thread, configId, value) {
1248
1434
  const agent = processes.get(thread)
@@ -1279,6 +1465,7 @@ export async function acpHandshake(settings, { env = process.env, root, timeoutM
1279
1465
  thread: 'doctor',
1280
1466
  onGone: (item) => {
1281
1467
  if (item.stopped || !item.pid) processPool?.agents.delete(item)
1468
+ poolChanged(processPool)
1282
1469
  },
1283
1470
  })
1284
1471
  try {
@@ -1293,5 +1480,6 @@ export async function acpHandshake(settings, { env = process.env, root, timeoutM
1293
1480
  // spawn can fail without an exit event; a dead child with no pid has
1294
1481
  // no process left to release its reservation through onGone.
1295
1482
  if (agent.stopped || !agent.pid) processPool?.agents.delete(agent)
1483
+ poolChanged(processPool)
1296
1484
  }
1297
1485
  }
@@ -38,7 +38,7 @@ export function createAgentManagement({ config, env = process.env, token = newSe
38
38
  if (!expires || expires < Date.now()) return fail(res, 404)
39
39
  res.redirect(303, `/#settings-token=${token}`)
40
40
  })
41
- app.use('/api', (req, res, next) => (/^\/agent\/settings(?:\/|$)/.test(req.path) ? next() : fail(res, 404)))
41
+ app.use('/api', (req, res, next) => (/^\/agent\/(?:settings(?:\/|$)|events$)/.test(req.path) ? next() : fail(res, 404)))
42
42
  app.use('/api/agent', agents)
43
43
  app.use('/api', (req, res) => fail(res, 404))
44
44
  app.use('/assets', express.static(path.join(clientDir, 'assets'), { index: false, dotfiles: 'deny' }))
@@ -0,0 +1,52 @@
1
+ // What an agent profile's session offers (the composer's option menus),
2
+ // learned once a session of it started (src/agent/routes.js prepare, or a
3
+ // turn), so the next new chat shows them without starting another process.
4
+ //
5
+ // One entry per profile id, tied to that profile's settings: a change of
6
+ // them (another command, model or environment) misses, and clear() drops
7
+ // everything (Settings > Agent saved or connected again). Known options are
8
+ // kept for `ttlMs`; a profile that could not start (not signed in, say) is
9
+ // not tried again for `failedTtlMs`, unless the person asks (Check again).
10
+
11
+ export const OPTIONS_TTL_MS = 10 * 60 * 1000
12
+ export const OPTIONS_FAILED_TTL_MS = 60 * 1000
13
+
14
+ export function createOptionsCache({ ttlMs = OPTIONS_TTL_MS, failedTtlMs = OPTIONS_FAILED_TTL_MS, now = () => Date.now() } = {}) {
15
+ const entries = new Map()
16
+ const keyOf = (current) => current?.profileId || 'default'
17
+ const fingerprintOf = (current) => JSON.stringify(current)
18
+ return {
19
+ // { options, error, at } for these settings, or null.
20
+ get(current) {
21
+ const entry = entries.get(keyOf(current))
22
+ if (!entry || entry.fingerprint !== fingerprintOf(current)) return null
23
+ if (now() - entry.at > (entry.error ? failedTtlMs : ttlMs)) {
24
+ entries.delete(keyOf(current))
25
+ return null
26
+ }
27
+ return entry
28
+ },
29
+ // Options a session listed, or (options null) why it did not start.
30
+ remember(current, options, error = null) {
31
+ if (!options?.length && !error) return
32
+ entries.set(keyOf(current), { fingerprint: fingerprintOf(current), options: options?.length ? options : null, error, at: now() })
33
+ },
34
+ drop(current) {
35
+ entries.delete(keyOf(current))
36
+ },
37
+ clear() {
38
+ entries.clear()
39
+ },
40
+ get size() {
41
+ return entries.size
42
+ },
43
+ }
44
+ }
45
+
46
+ // A chat's choices ({ configId: value }) over a profile's options, for a
47
+ // chat with no session yet: each one the option lists, the rest as they are.
48
+ export function withChoices(options, choices) {
49
+ return (options || []).map((option) =>
50
+ option.values.some((item) => item.value === choices?.[option.id]) ? { ...option, currentValue: choices[option.id] } : option,
51
+ )
52
+ }