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
@@ -1,10 +1,13 @@
1
1
  // /api/agent/*: the chat panel's API. JSON in, server-sent events out.
2
2
  //
3
3
  // GET /api/agent/status what chat is connected to (no secrets)
4
+ // GET /api/agent/events SSE: "agents" when the agent settings change (settings-events.js)
4
5
  // GET /api/agent/boards/:id/threads the viewer's chat history (?q= searches it)
5
6
  // GET /api/agent/boards/:id/threads/:thread one thread
6
7
  // POST /api/agent/boards/:id/threads/:thread/messages send a message (editOf: rerun from an edit; regenerate: a new answer); SSE back
7
8
  // POST /api/agent/boards/:id/threads/:thread/stop stop the answer being written
9
+ // POST /api/agent/boards/:id/threads/:thread/prepare the composer's options before the first message (owner only)
10
+ // POST /api/agent/boards/:id/threads/:thread/options choose one of them { configId, value, choices? }
8
11
  // PATCH /api/agent/boards/:id/threads/:thread rename or archive { title?, archived? }
9
12
  // POST /api/agent/boards/:id/threads/:thread/versions/:v bring back an earlier version (before an edit)
10
13
  // DELETE /api/agent/boards/:id/threads/:thread clear the thread (a chat: delete it)
@@ -35,13 +38,16 @@ import { createHash, randomBytes } from 'node:crypto'
35
38
  import express from 'express'
36
39
  import { addReply, getComment, listComments, setAgentStatus } from '../store.js'
37
40
  import { createBackend } from './backends/index.js'
41
+ import { AGENTS_EVENT, createSettingsEvents } from './settings-events.js'
42
+ import { cleanChoices } from './backends/acp.js'
43
+ import { createOptionsCache, withChoices } from './options-cache.js'
38
44
  import { authFiles } from '../config.js'
39
45
  import { agentSettings, publicAgentInfo } from './config.js'
40
46
  import { AgentError } from './errors.js'
41
47
  import { createAgentHealth } from './agent-health.js'
42
48
  import { beginAgentOperation } from './control.js'
43
49
  import { validateFiles, validateMentions } from './composer.js'
44
- import { profileForDefault, userAgentEntry } from './user-settings.js'
50
+ import { profileForDefault, userAgentEntry, userSettingsFile } from './user-settings.js'
45
51
  import { finishFix, projectChanged, projectSnapshot } from './feedback-loop.js'
46
52
  import { ownerMcpServers } from './owner-mcp.js'
47
53
  import { RUN_MS_MAX, commentIdOf, runTurn } from './run.js'
@@ -174,6 +180,13 @@ export function agentRouter({
174
180
  }) {
175
181
  const limit = { ...DEFAULT_LIMITS, ...limits }
176
182
  const router = express.Router()
183
+ // "Agents changed" for every open view: this server's settings routes and
184
+ // edits of the agents file from outside (settings-events.js).
185
+ const settingsEvents = createSettingsEvents({ file: userSettingsFile(env), watch: limit.watchSettings !== false })
186
+ router.settingsEvents = settingsEvents
187
+ // The open GET /events responses, ended on close.
188
+ const eventStreams = new Set()
189
+ let eventsClosed = false
177
190
  const settings = (profileId = null) => {
178
191
  const current = agentSettings(config, env, { acp, profileId })
179
192
  if (shared && !allowRemoteAgent && current.backend === 'acp' && current.configured) {
@@ -191,7 +204,14 @@ export function agentRouter({
191
204
  // processes) while the settings stay the same.
192
205
  let cached = null
193
206
  const backends = new Map()
194
- const processPool = { epoch: 0, agents: new Set(), max: Math.min(limit.runsMax, limit.acp?.processesMax ?? limit.runsMax) }
207
+ // `changed`: an agent process started, became ready or went away, which
208
+ // moves an agent's state ("Starting", "Ready"): the open views hear it.
209
+ const processPool = {
210
+ epoch: 0,
211
+ agents: new Set(),
212
+ max: Math.min(limit.runsMax, limit.acp?.processesMax ?? limit.runsMax),
213
+ changed: () => settingsEvents.changed('state'),
214
+ }
195
215
  // How each agent is doing (agent-health.js): from the last turn or test.
196
216
  const health = createAgentHealth()
197
217
  const agentStatus = (current) => health.status(current, processPool)
@@ -276,6 +296,11 @@ export function agentRouter({
276
296
  // Server shutdown: stop agent processes (src/server/app.js stopChildren).
277
297
  router.close = () => {
278
298
  processPool.epoch += 1
299
+ settingsEvents.close()
300
+ // An open events stream would hold the server open: end every one.
301
+ eventsClosed = true
302
+ for (const res of eventStreams) res.end()
303
+ eventStreams.clear()
279
304
  const settingsStopped = settingsApi.close()
280
305
  const owned = [...processPool.agents]
281
306
  for (const agent of owned) agent.kill('shutdown')
@@ -295,18 +320,43 @@ export function agentRouter({
295
320
  const entry = threadModels.get(key)
296
321
  return entry && entry.fingerprint === JSON.stringify(current) ? entry.model : null
297
322
  }
323
+ // What each profile's sessions offer, so a new chat shows its options
324
+ // without starting a process (options-cache.js).
325
+ const optionsCache = createOptionsCache({ ttlMs: limit.optionsTtlMs, failedTtlMs: limit.optionsFailedTtlMs })
326
+ router.optionsCache = optionsCache
327
+ const cachedOptions = (current) => optionsCache.get(current)
328
+ const rememberOptions = (current, options, error = null) => optionsCache.remember(current, options, error)
329
+ // A session's options as it started (the agent's defaults, not one chat's
330
+ // choices), for the next new chat.
331
+ const rememberSession = (current, backend, key) =>
332
+ rememberOptions(current, backend.sessionDefaults?.(key) || backend.sessionOptions?.(key))
298
333
  const pickerOptions = async (current, key) => {
299
334
  const backend = liveOwnerBackend(current)
300
- if (backend?.sessionOptions) return backend.sessionOptions(key)
335
+ if (backend?.sessionOptions) {
336
+ const live = backend.sessionOptions(key)
337
+ if (live?.length) rememberSession(current, backend, key)
338
+ return live
339
+ }
301
340
  if (!backend?.listModels) return null
302
341
  const ids = await backend.listModels()
303
342
  const model = chosenModel(current, key) || current.model
304
343
  const values = [...new Set([model, ...ids])].filter(Boolean).map((id) => ({ value: id, name: id }))
305
344
  return values.length > 1 ? [{ id: 'model', category: 'model', name: 'Model', currentValue: model, values }] : null
306
345
  }
307
- const setPickerOption = async (current, key, configId, value) => {
346
+ const setPickerOption = async (current, key, configId, value, choices = {}) => {
308
347
  const backend = liveOwnerBackend(current)
309
- if (backend?.setSessionOption) return backend.setSessionOption(key, configId, value)
348
+ if (backend?.setSessionOption && backend.sessionOptions(key)) return backend.setSessionOption(key, configId, value)
349
+ // No session yet (a new chat, or one whose session stopped): the choice
350
+ // is checked against what the profile offers and goes with the next
351
+ // message (the composer sends this chat's choices with it).
352
+ const known = cachedOptions(current)?.options
353
+ if (backend?.setSessionOption || (!backend && current.backend === 'acp')) {
354
+ const option = known?.find((item) => item.id === configId)
355
+ if (!option) throw new AgentError('no_session', 'The agent session ended. Send a message, then choose again.', 409)
356
+ if (!option.values.some((item) => item.value === value))
357
+ throw new AgentError('bad_option', 'The agent does not offer that choice.', 400)
358
+ return withChoices(known, { ...choices, [configId]: value })
359
+ }
310
360
  if (!backend?.listModels) throw new AgentError('no_session', 'The agent session ended. Send a message, then choose again.', 409)
311
361
  if (configId !== 'model' || (value !== current.model && !(await backend.listModels()).includes(value)))
312
362
  throw new AgentError('bad_option', 'The endpoint does not list that model.', 400)
@@ -616,6 +666,8 @@ export function agentRouter({
616
666
  modelOverride: ownerWrites ? chosenModel(current, `${board.id}/${threadId}`) : null,
617
667
  // The owner's own feedback notes go to the owner's turns only (ratings-core.js downNotes).
618
668
  ownerTurn: res.locals.viewer === 'owner',
669
+ // The composer's options for this chat (an ACP session's own), owner turns only.
670
+ choices: ownerWrites && backend.id === 'acp' ? cleanChoices(req.body?.options) : null,
619
671
  emit,
620
672
  signal: controller.signal,
621
673
  ownerWrites,
@@ -624,6 +676,10 @@ export function agentRouter({
624
676
  requestedPages,
625
677
  })
626
678
  health.record(current, reply)
679
+ // What the profile offers, as this turn's session saw it; a turn that
680
+ // could not sign in drops what was known (the next look starts fresh).
681
+ if (reply.error?.code === 'agent_auth') optionsCache.drop(current)
682
+ else if (backend.id === 'acp') rememberSession(current, backend, `${board.id}/${threadId}`)
627
683
  if (baseline) {
628
684
  try {
629
685
  const { summary, undo } = await finishTurnChanges(config, baseline, {
@@ -680,6 +736,34 @@ export function agentRouter({
680
736
 
681
737
  router.use(express.json({ limit: SMALL_BODY_LIMIT }))
682
738
 
739
+ // The agent settings changed (here, in another tab, or in the file): a
740
+ // nudge only, no settings in it; each view refetches what it shows.
741
+ router.get('/events', (req, res) => {
742
+ if (eventsClosed) return res.status(503).json({ error: { code: 'stopping', message: 'The server is stopping.' } })
743
+ res.writeHead(200, {
744
+ 'Content-Type': 'text/event-stream; charset=utf-8',
745
+ 'Cache-Control': 'no-store',
746
+ 'X-Accel-Buffering': 'no',
747
+ Connection: 'keep-alive',
748
+ })
749
+ res.flushHeaders?.()
750
+ res.write(': connected\n\n')
751
+ const stop = settingsEvents.subscribe((event) => {
752
+ if (!res.writableEnded) res.write(`event: ${AGENTS_EVENT}\ndata: ${JSON.stringify({ at: event.at })}\n\n`)
753
+ })
754
+ const keepalive = setInterval(() => {
755
+ if (!res.writableEnded) res.write(': ping\n\n')
756
+ }, limit.keepaliveMs)
757
+ keepalive.unref?.()
758
+ eventStreams.add(res)
759
+ const done = () => {
760
+ clearInterval(keepalive)
761
+ stop()
762
+ eventStreams.delete(res)
763
+ }
764
+ req.on('close', done)
765
+ res.on('finish', done)
766
+ })
683
767
  router.get('/status', (req, res) =>
684
768
  res.json({
685
769
  ...publicAgentInfo(settings()),
@@ -692,6 +776,7 @@ export function agentRouter({
692
776
  }),
693
777
  )
694
778
  const settingsApi = settingsRoutes({
779
+ events: settingsEvents,
695
780
  config,
696
781
  env,
697
782
  fetchImpl,
@@ -706,6 +791,8 @@ export function agentRouter({
706
791
  reload: () => {
707
792
  for (const entry of backends.values()) entry.backend?.close?.()
708
793
  backends.clear()
794
+ // Connected again or changed: what its sessions offer is learned anew.
795
+ optionsCache.clear()
709
796
  return backendFor(settings())
710
797
  },
711
798
  })
@@ -851,6 +938,83 @@ export function agentRouter({
851
938
  }
852
939
  }),
853
940
  )
941
+ // The composer's options before the first message: { choices } (this
942
+ // chat's, or the agent's last used) in, { options } out, or { options:
943
+ // null } when the agent offers none, is busy or cannot start (with
944
+ // { error } when it is not signed in). Owner only and from this board's
945
+ // page: nobody else can chat with a native agent, so nobody else starts
946
+ // one. It starts (or reuses) the thread's own session, the one its first
947
+ // turn uses, unless the profile's options are already known (then no
948
+ // process starts; the choices go with the first message). Never evicts
949
+ // another thread's session; an unused one stops when idle, like any.
950
+ router.post(
951
+ '/boards/:id/threads/:thread/prepare',
952
+ findThread,
953
+ handle(async (req, res, board, threadId) => {
954
+ if (!ownerWritesFor(req) || !sameOriginWrite(req)) return controlDenied(res)
955
+ const key = `${board.id}/${threadId}`
956
+ const current = settings(readThread(config, board.id, threadId).profileId)
957
+ if (!current.configured || chatNeedsOwner(req, current)) return res.json({ options: null })
958
+ const choices = cleanChoices(req.body?.choices)
959
+ const force = req.body?.force === true
960
+ const backend = backendFor(current, true)
961
+ if (!backend) return res.json({ options: null })
962
+ if (!backend.prepare) {
963
+ // An endpoint: its model list, and this chat's model when it lists it.
964
+ if (choices.model && choices.model !== chosenModel(current, key)) {
965
+ try {
966
+ await setPickerOption(current, key, 'model', choices.model)
967
+ } catch {
968
+ /* not listed any more: the configured model stays */
969
+ }
970
+ }
971
+ return res.json({ options: (await pickerOptions(current, key).catch(() => null)) || null })
972
+ }
973
+ const live = backend.sessionOptions(key)
974
+ const busy = runs.has(key) || selecting.has(key) || connectionTesting() || undoing
975
+ if (live && (busy || !Object.keys(choices).length)) return res.json({ options: live })
976
+ const known = cachedOptions(current)
977
+ if (busy) return res.json({ options: known?.options ? withChoices(known.options, choices) : null })
978
+ if (!live && known && !force) {
979
+ if (known.error) return res.json({ options: null, ...(known.error.quiet ? {} : { error: known.error }) })
980
+ return res.json({ options: withChoices(known.options, choices), cached: true })
981
+ }
982
+ const admission = new AbortController()
983
+ res.once('close', () => {
984
+ if (!res.writableEnded) admission.abort()
985
+ })
986
+ const release = await beginAgentOperation(config, env, 'turn', { signal: admission.signal }).catch(() => null)
987
+ if (!release) return res.json({ options: null })
988
+ try {
989
+ if (runs.has(key) || selecting.has(key)) return res.json({ options: backend.sessionOptions(key) })
990
+ const options = await backend.prepare(key, { choices, signal: admission.signal })
991
+ ownerThreads.add(key)
992
+ rememberSession(current, backend, key)
993
+ res.json({ options: options?.length ? options : null })
994
+ } catch (error) {
995
+ if (error.code === 'agent_auth') {
996
+ const failure = {
997
+ code: error.code,
998
+ message: error.message,
999
+ ...(error.label ? { label: error.label } : {}),
1000
+ ...(error.login ? { login: error.login } : {}),
1001
+ }
1002
+ health.record(current, { status: 'error', error: failure })
1003
+ rememberOptions(current, null, failure)
1004
+ return res.json({ options: null, error: failure })
1005
+ }
1006
+ // Busy or stopped: today's composer, quietly. An agent that does not
1007
+ // start is not started again for a while either (it says why on a turn).
1008
+ if (!['agent_busy', 'agent_stopped'].includes(error.code)) {
1009
+ log(`options: ${error.message}`)
1010
+ rememberOptions(current, null, { code: error.code || 'agent_start', quiet: true })
1011
+ }
1012
+ res.json({ options: null })
1013
+ } finally {
1014
+ await release()
1015
+ }
1016
+ }),
1017
+ )
854
1018
  // The composer's model or effort picker: { configId, value }, one of the
855
1019
  // choices the thread's running agent session lists. Owner only, never
856
1020
  // while an answer runs; the agent's defaults and Settings > Agent stay as
@@ -865,7 +1029,8 @@ export function agentRouter({
865
1029
  const { configId, value } = req.body || {}
866
1030
  if (typeof configId !== 'string' || typeof value !== 'string' || configId.length > 100 || value.length > 200)
867
1031
  return fail(res, 400, 'bad_option', 'configId and value are strings.')
868
- const options = await setPickerOption(settings(readThread(config, board.id, threadId).profileId), key, configId, value)
1032
+ const current = settings(readThread(config, board.id, threadId).profileId)
1033
+ const options = await setPickerOption(current, key, configId, value, cleanChoices(req.body?.choices))
869
1034
  res.json({ options })
870
1035
  }),
871
1036
  )
package/src/agent/run.js CHANGED
@@ -108,6 +108,9 @@ export async function runTurn({
108
108
  modelOverride = null,
109
109
  // The owner is asking (routes.js viewerOf): see modelMessages.
110
110
  ownerTurn = false,
111
+ // The composer's options for this chat ({ configId: value }), owner turns
112
+ // of an agent with its own session options (an ACP agent).
113
+ choices = null,
111
114
  }) {
112
115
  const thread = `${board.id}/${threadId}`
113
116
  const runMs = backend.runMsMax || RUN_MS_MAX
@@ -182,6 +185,7 @@ export async function runTurn({
182
185
  messages: conversation,
183
186
  tools: round < TOOL_ROUNDS_MAX ? tools : [],
184
187
  ...(modelOverride ? { model: modelOverride } : {}),
188
+ ...(choices ? { choices } : {}),
185
189
  signal,
186
190
  thread,
187
191
  })) {
@@ -197,6 +201,15 @@ export async function runTurn({
197
201
  emit('reasoning', { text: event.text })
198
202
  } else if (event.type === 'status') {
199
203
  emit('status', { text: String(event.text).slice(0, 200) })
204
+ } else if (event.type === 'options') {
205
+ // What the turn runs with (the answer's meta line): model and thinking level.
206
+ reply.options = (Array.isArray(event.used) ? event.used : []).slice(0, 4).map((item) => ({
207
+ category: String(item.category || '').slice(0, 40),
208
+ name: String(item.name || '').slice(0, 60),
209
+ value: String(item.value || '').slice(0, 80),
210
+ ...(item.description ? { description: String(item.description).slice(0, 160) } : {}),
211
+ }))
212
+ emit('options', { options: reply.options })
200
213
  } else if (event.type === 'notice') {
201
214
  // Something the person should know about this answer (images dropped).
202
215
  noteOnce(String(event.text || '').slice(0, 200))
@@ -274,7 +287,13 @@ export async function runTurn({
274
287
  reply.status = 'error'
275
288
  reply.error =
276
289
  error instanceof AgentError
277
- ? { code: error.code, message: error.message }
290
+ ? {
291
+ code: error.code,
292
+ message: error.message,
293
+ // Not signed in: who, and the command that signs it in (acp.js authError).
294
+ ...(error.label ? { label: String(error.label).slice(0, 60) } : {}),
295
+ ...(error.login ? { login: String(error.login).slice(0, 80) } : {}),
296
+ }
278
297
  : { code: 'server_error', message: 'Something went wrong while talking to the agent.' }
279
298
  }
280
299
  }
@@ -0,0 +1,103 @@
1
+ // "Agents changed": one event for every open view when the agent settings
2
+ // change, whoever changed them. Two sources:
3
+ // - this server's own settings routes (connect, remove, default, save):
4
+ // changed('settings') after each one;
5
+ // - the saved agents file itself (src/agent/user-settings.js), watched with
6
+ // fs.watch on its folder, for edits made outside this process
7
+ // (`shapewall settings`, another `shapewall serve`, a person or an agent
8
+ // editing the file).
9
+ // Changes inside `debounceMs` of each other become one event, so a route's
10
+ // own write and the watcher noticing it say "changed" once.
11
+ //
12
+ // Browsers hear it on GET /api/agent/events (server-sent events, routes.js),
13
+ // which carries no settings, only that they changed: each view refetches
14
+ // what it shows through its usual, authorized routes.
15
+
16
+ import fs from 'node:fs'
17
+ import path from 'node:path'
18
+
19
+ export const AGENTS_EVENT = 'agents'
20
+
21
+ export function createSettingsEvents({ file = null, debounceMs = 150, watch = true, now = () => Date.now() } = {}) {
22
+ const listeners = new Set()
23
+ let timer = null
24
+ let reasons = new Set()
25
+ let watcher = null
26
+ let closed = false
27
+
28
+ const flush = () => {
29
+ timer = null
30
+ const event = { at: new Date(now()).toISOString(), reasons: [...reasons] }
31
+ reasons = new Set()
32
+ for (const listener of [...listeners]) {
33
+ try {
34
+ listener(event)
35
+ } catch {
36
+ // One listener failing never stops the others.
37
+ }
38
+ }
39
+ }
40
+ const changed = (reason = 'settings') => {
41
+ if (closed) return
42
+ reasons.add(reason)
43
+ if (!timer) {
44
+ timer = setTimeout(flush, debounceMs)
45
+ timer.unref?.()
46
+ }
47
+ }
48
+
49
+ // The folder, not the file: saves replace the file (write, then rename),
50
+ // which a watch on the file itself would lose. A folder that does not
51
+ // exist yet (no settings saved) is watched once it appears, via its parent.
52
+ const start = () => {
53
+ if (!watch || !file || closed || watcher) return
54
+ const dir = path.dirname(file)
55
+ const name = path.basename(file)
56
+ try {
57
+ watcher = fs.watch(dir, (event, changedName) => {
58
+ if (!changedName || changedName === name || String(changedName).startsWith(`${name}.`)) changed('file')
59
+ })
60
+ watcher.on('error', () => {
61
+ watcher?.close()
62
+ watcher = null
63
+ })
64
+ watcher.unref?.()
65
+ } catch {
66
+ watcher = null
67
+ // The folder is not there yet: wait for it in the parent.
68
+ try {
69
+ const parent = fs.watch(path.dirname(dir), (event, changedName) => {
70
+ if (changedName !== path.basename(dir) || !fs.existsSync(dir)) return
71
+ parent.close()
72
+ watcher = null
73
+ start()
74
+ changed('file')
75
+ })
76
+ parent.on('error', () => parent.close())
77
+ parent.unref?.()
78
+ // Replaced by the real watcher once the folder appears.
79
+ watcher = { close: () => parent.close() }
80
+ } catch {
81
+ // No parent either: only this server's own changes are announced.
82
+ }
83
+ }
84
+ }
85
+ start()
86
+
87
+ return {
88
+ changed,
89
+ subscribe(listener) {
90
+ listeners.add(listener)
91
+ return () => listeners.delete(listener)
92
+ },
93
+ listenerCount: () => listeners.size,
94
+ close() {
95
+ closed = true
96
+ if (timer) clearTimeout(timer)
97
+ timer = null
98
+ watcher?.close()
99
+ watcher = null
100
+ listeners.clear()
101
+ },
102
+ }
103
+ }
@@ -328,8 +328,30 @@ export async function testConnection(settings, { env = process.env, fetchImpl =
328
328
  // `repo` is the config's `agent`. `busy()` is true while an answer is being
329
329
  // written, `reload()` switches the chat over to new settings.
330
330
  // `token` is the per-process settings token (null: the routes are off).
331
- export function settingsRoutes({ config, env, fetchImpl, settings, shared, token, busy, reload, processPool, health = null }) {
331
+ export function settingsRoutes({
332
+ config,
333
+ env,
334
+ fetchImpl,
335
+ settings,
336
+ shared,
337
+ token,
338
+ busy,
339
+ reload,
340
+ processPool,
341
+ health = null,
342
+ events = null,
343
+ }) {
332
344
  const router = express.Router()
345
+ // Every change that went through (and a test, which updates an agent's
346
+ // state) tells the open views (settings-events.js).
347
+ router.use((req, res, next) => {
348
+ if (events && !['GET', 'HEAD', 'OPTIONS'].includes(req.method)) {
349
+ res.on('finish', () => {
350
+ if (res.statusCode < 400) events.changed('settings')
351
+ })
352
+ }
353
+ next()
354
+ })
333
355
  const repo = () => config.agent || {}
334
356
  let testing = false
335
357
  let closing = false
@@ -479,7 +501,7 @@ export function settingsRoutes({ config, env, fetchImpl, settings, shared, token
479
501
  // The agent CLIs found on PATH (looked up, never started), for the
480
502
  // one-click Connect in an unconnected chat panel.
481
503
  detected: detectAgents(env),
482
- // Every agent Shapewall knows how to run, found or not (Settings > Agents).
504
+ // Every agent Shapewall knows how to run, found or not (the console's Agents page).
483
505
  known: KNOWN_AGENTS.map(({ id, label, adapter, cli, install }) => ({ id, label, adapter, cli, install })),
484
506
  knownKeyHosts: [...KNOWN_KEY_HOSTS],
485
507
  defaultKeyVar: DEFAULT_KEY_VAR,