shapewall 0.2.1 → 0.2.3

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 (60) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +4 -12
  3. package/dist/agent/package-lock.json +2 -2
  4. package/dist/client/assets/BoardChat-C88k4s-W.js +28 -0
  5. package/dist/client/assets/BuzzDialog-CZdwIQLF.js +1 -0
  6. package/dist/client/assets/ChecksPanel-B54chcLA.js +1 -0
  7. package/dist/client/assets/History-CVVuuxUK.js +1 -0
  8. package/dist/client/assets/LocalSettings-CvlVtNY_.js +1 -0
  9. package/dist/client/assets/Management-DOJkFY_o.js +1 -0
  10. package/dist/client/assets/QuickConnect-D40mj4Ry.js +1 -0
  11. package/dist/client/assets/ShareDialog-CdVAreaw.js +2 -0
  12. package/dist/client/assets/app-update-dialog-Dox9-LWv.js +1 -0
  13. package/dist/client/assets/circle-x-BmT6vHKl.js +1 -0
  14. package/dist/client/assets/index-CwvFfwU0.js +29 -0
  15. package/dist/client/assets/index-UIYSPHoh.css +2 -0
  16. package/dist/client/assets/refresh-cw-ugt3cWKH.js +1 -0
  17. package/dist/client/assets/square-_KG6tM5A.js +1 -0
  18. package/dist/client/assets/ui-BAGBTB_P.js +41 -0
  19. package/dist/client/build-info.json +1 -1
  20. package/dist/client/index.html +3 -2
  21. package/dist/client/sw.js +2 -2
  22. package/dist/console/assets/LocalAccountsApp-4MtW1QlZ.js +1 -0
  23. package/dist/console/assets/LocalConsole-CgKqYa8i.js +1 -0
  24. package/dist/console/assets/{app-update-dialog-C5JVG7ck.js → app-update-dialog-S2Yyc7Pw.js} +1 -1
  25. package/dist/console/assets/console-BPmBRIoz.js +51 -0
  26. package/dist/console/assets/console-DgVrGRMD.css +2 -0
  27. package/dist/console/build-info.json +1 -1
  28. package/dist/console/console.html +2 -2
  29. package/docs/agents.md +105 -43
  30. package/docs/deployment.md +1 -2
  31. package/docs/design-system.md +31 -7
  32. package/docs/hosted.md +2 -4
  33. package/package.json +1 -1
  34. package/src/agent/agent-health.js +75 -0
  35. package/src/agent/backends/acp.js +217 -41
  36. package/src/agent/config.js +9 -1
  37. package/src/agent/options-cache.js +52 -0
  38. package/src/agent/routes.js +140 -7
  39. package/src/agent/run.js +20 -1
  40. package/src/agent/settings-routes.js +75 -8
  41. package/src/agent/user-settings.js +12 -0
  42. package/src/server/app.js +1 -0
  43. package/dist/client/assets/AgentSettings-CEOkftKf.js +0 -1
  44. package/dist/client/assets/BoardChat-DyD_rQlA.js +0 -30
  45. package/dist/client/assets/BuzzDialog-DAdMz66r.js +0 -1
  46. package/dist/client/assets/ChecksPanel-Due6G_M8.js +0 -1
  47. package/dist/client/assets/History-DxCP1-IS.js +0 -1
  48. package/dist/client/assets/LocalSettings-BVVleHqg.js +0 -1
  49. package/dist/client/assets/Management-BkQimoMa.js +0 -1
  50. package/dist/client/assets/ShareDialog-D9mIRVJ4.js +0 -2
  51. package/dist/client/assets/app-update-dialog-BNJaXH1v.js +0 -1
  52. package/dist/client/assets/circle-x-B5smn8Mj.js +0 -1
  53. package/dist/client/assets/index-BHbxSLS4.js +0 -65
  54. package/dist/client/assets/index-DqWPr45k.css +0 -2
  55. package/dist/client/assets/refresh-cw-SqPU2sKl.js +0 -1
  56. package/dist/client/assets/square-hda22GRT.js +0 -1
  57. package/dist/console/assets/LocalAccountsApp-Dea93fL3.js +0 -1
  58. package/dist/console/assets/LocalConsole-D-TJ53EA.js +0 -1
  59. package/dist/console/assets/console-DybJNLin.css +0 -2
  60. package/dist/console/assets/console-lpozP2ju.js +0 -51
@@ -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
+ }
@@ -5,6 +5,8 @@
5
5
  // GET /api/agent/boards/:id/threads/:thread one thread
6
6
  // POST /api/agent/boards/:id/threads/:thread/messages send a message (editOf: rerun from an edit; regenerate: a new answer); SSE back
7
7
  // POST /api/agent/boards/:id/threads/:thread/stop stop the answer being written
8
+ // POST /api/agent/boards/:id/threads/:thread/prepare the composer's options before the first message (owner only)
9
+ // POST /api/agent/boards/:id/threads/:thread/options choose one of them { configId, value, choices? }
8
10
  // PATCH /api/agent/boards/:id/threads/:thread rename or archive { title?, archived? }
9
11
  // POST /api/agent/boards/:id/threads/:thread/versions/:v bring back an earlier version (before an edit)
10
12
  // DELETE /api/agent/boards/:id/threads/:thread clear the thread (a chat: delete it)
@@ -35,9 +37,12 @@ import { createHash, randomBytes } from 'node:crypto'
35
37
  import express from 'express'
36
38
  import { addReply, getComment, listComments, setAgentStatus } from '../store.js'
37
39
  import { createBackend } from './backends/index.js'
40
+ import { cleanChoices } from './backends/acp.js'
41
+ import { createOptionsCache, withChoices } from './options-cache.js'
38
42
  import { authFiles } from '../config.js'
39
43
  import { agentSettings, publicAgentInfo } from './config.js'
40
44
  import { AgentError } from './errors.js'
45
+ import { createAgentHealth } from './agent-health.js'
41
46
  import { beginAgentOperation } from './control.js'
42
47
  import { validateFiles, validateMentions } from './composer.js'
43
48
  import { profileForDefault, userAgentEntry } from './user-settings.js'
@@ -191,15 +196,26 @@ export function agentRouter({
191
196
  let cached = null
192
197
  const backends = new Map()
193
198
  const processPool = { epoch: 0, agents: new Set(), max: Math.min(limit.runsMax, limit.acp?.processesMax ?? limit.runsMax) }
199
+ // How each agent is doing (agent-health.js): from the last turn or test.
200
+ const health = createAgentHealth()
201
+ const agentStatus = (current) => health.status(current, processPool)
202
+ router.health = health
194
203
  const profiles = () => {
195
204
  const saved = userAgentEntry(config.dir, env)
196
205
  const locked = acp || env.SHAPEWALL_AGENT_ACP
197
206
  // The default connection runs the same command as a saved profile: the
198
207
  // picker shows that profile once, by name (sameAs), not both.
199
- const same = !locked ? profileForDefault(saved.entry) : null
208
+ const fallback = settings().defaultProfile
209
+ const same = !locked ? profileForDefault(saved.entry) || (fallback ? { id: fallback } : null) : null
200
210
  return [
201
- { id: 'default', ...publicAgentInfo(settings()), ...(same ? { sameAs: same.id } : {}) },
202
- ...(!locked ? (saved.entry?.profiles || []).map((item) => ({ id: item.id, ...publicAgentInfo(settings(item.id)) })) : []),
211
+ { id: 'default', ...publicAgentInfo(settings()), ...agentStatus(settings()), ...(same ? { sameAs: same.id } : {}) },
212
+ ...(!locked
213
+ ? (saved.entry?.profiles || []).map((item) => ({
214
+ id: item.id,
215
+ ...publicAgentInfo(settings(item.id)),
216
+ ...agentStatus(settings(item.id)),
217
+ }))
218
+ : []),
203
219
  ]
204
220
  }
205
221
  const ownerWritesFor = (req) =>
@@ -215,6 +231,8 @@ export function agentRouter({
215
231
  const ownerGate = Boolean(settingsToken) && !shared
216
232
  const chatNeedsOwner = (req, current = settings()) => ownerGate && current.backend === 'acp' && current.configured && !agentOwner(req)
217
233
  router.chatNeedsOwner = chatNeedsOwner
234
+ // The same state fields /status reports, for /api/info.
235
+ router.agentStatus = () => agentStatus(settings())
218
236
  const ownerNeeded = (res) =>
219
237
  fail(
220
238
  res,
@@ -281,18 +299,43 @@ export function agentRouter({
281
299
  const entry = threadModels.get(key)
282
300
  return entry && entry.fingerprint === JSON.stringify(current) ? entry.model : null
283
301
  }
302
+ // What each profile's sessions offer, so a new chat shows its options
303
+ // without starting a process (options-cache.js).
304
+ const optionsCache = createOptionsCache({ ttlMs: limit.optionsTtlMs, failedTtlMs: limit.optionsFailedTtlMs })
305
+ router.optionsCache = optionsCache
306
+ const cachedOptions = (current) => optionsCache.get(current)
307
+ const rememberOptions = (current, options, error = null) => optionsCache.remember(current, options, error)
308
+ // A session's options as it started (the agent's defaults, not one chat's
309
+ // choices), for the next new chat.
310
+ const rememberSession = (current, backend, key) =>
311
+ rememberOptions(current, backend.sessionDefaults?.(key) || backend.sessionOptions?.(key))
284
312
  const pickerOptions = async (current, key) => {
285
313
  const backend = liveOwnerBackend(current)
286
- if (backend?.sessionOptions) return backend.sessionOptions(key)
314
+ if (backend?.sessionOptions) {
315
+ const live = backend.sessionOptions(key)
316
+ if (live?.length) rememberSession(current, backend, key)
317
+ return live
318
+ }
287
319
  if (!backend?.listModels) return null
288
320
  const ids = await backend.listModels()
289
321
  const model = chosenModel(current, key) || current.model
290
322
  const values = [...new Set([model, ...ids])].filter(Boolean).map((id) => ({ value: id, name: id }))
291
323
  return values.length > 1 ? [{ id: 'model', category: 'model', name: 'Model', currentValue: model, values }] : null
292
324
  }
293
- const setPickerOption = async (current, key, configId, value) => {
325
+ const setPickerOption = async (current, key, configId, value, choices = {}) => {
294
326
  const backend = liveOwnerBackend(current)
295
- if (backend?.setSessionOption) return backend.setSessionOption(key, configId, value)
327
+ if (backend?.setSessionOption && backend.sessionOptions(key)) return backend.setSessionOption(key, configId, value)
328
+ // No session yet (a new chat, or one whose session stopped): the choice
329
+ // is checked against what the profile offers and goes with the next
330
+ // message (the composer sends this chat's choices with it).
331
+ const known = cachedOptions(current)?.options
332
+ if (backend?.setSessionOption || (!backend && current.backend === 'acp')) {
333
+ const option = known?.find((item) => item.id === configId)
334
+ if (!option) throw new AgentError('no_session', 'The agent session ended. Send a message, then choose again.', 409)
335
+ if (!option.values.some((item) => item.value === value))
336
+ throw new AgentError('bad_option', 'The agent does not offer that choice.', 400)
337
+ return withChoices(known, { ...choices, [configId]: value })
338
+ }
296
339
  if (!backend?.listModels) throw new AgentError('no_session', 'The agent session ended. Send a message, then choose again.', 409)
297
340
  if (configId !== 'model' || (value !== current.model && !(await backend.listModels()).includes(value)))
298
341
  throw new AgentError('bad_option', 'The endpoint does not list that model.', 400)
@@ -602,6 +645,8 @@ export function agentRouter({
602
645
  modelOverride: ownerWrites ? chosenModel(current, `${board.id}/${threadId}`) : null,
603
646
  // The owner's own feedback notes go to the owner's turns only (ratings-core.js downNotes).
604
647
  ownerTurn: res.locals.viewer === 'owner',
648
+ // The composer's options for this chat (an ACP session's own), owner turns only.
649
+ choices: ownerWrites && backend.id === 'acp' ? cleanChoices(req.body?.options) : null,
605
650
  emit,
606
651
  signal: controller.signal,
607
652
  ownerWrites,
@@ -609,6 +654,11 @@ export function agentRouter({
609
654
  capture,
610
655
  requestedPages,
611
656
  })
657
+ health.record(current, reply)
658
+ // What the profile offers, as this turn's session saw it; a turn that
659
+ // could not sign in drops what was known (the next look starts fresh).
660
+ if (reply.error?.code === 'agent_auth') optionsCache.drop(current)
661
+ else if (backend.id === 'acp') rememberSession(current, backend, `${board.id}/${threadId}`)
612
662
  if (baseline) {
613
663
  try {
614
664
  const { summary, undo } = await finishTurnChanges(config, baseline, {
@@ -668,6 +718,7 @@ export function agentRouter({
668
718
  router.get('/status', (req, res) =>
669
719
  res.json({
670
720
  ...publicAgentInfo(settings()),
721
+ ...agentStatus(settings()),
671
722
  ...(profiles().length > 1 ? { profiles: profiles() } : {}),
672
723
  ownerWrites: ownerWritesFor(req),
673
724
  fixWithAgent: allowCapture && ownerWritesFor(req) && settings().backend === 'acp',
@@ -681,6 +732,7 @@ export function agentRouter({
681
732
  fetchImpl,
682
733
  settings,
683
734
  processPool,
735
+ health,
684
736
  shared,
685
737
  token: settingsToken,
686
738
  busy: () => runs.size > 0 || selecting.size > 0,
@@ -689,6 +741,8 @@ export function agentRouter({
689
741
  reload: () => {
690
742
  for (const entry of backends.values()) entry.backend?.close?.()
691
743
  backends.clear()
744
+ // Connected again or changed: what its sessions offer is learned anew.
745
+ optionsCache.clear()
692
746
  return backendFor(settings())
693
747
  },
694
748
  })
@@ -724,6 +778,7 @@ export function agentRouter({
724
778
  profiles: profiles(),
725
779
  agent: {
726
780
  ...publicAgentInfo(current),
781
+ ...agentStatus(current),
727
782
  ownerWrites: ownerWritesFor(req),
728
783
  fixWithAgent: allowCapture && ownerWritesFor(req) && current.backend === 'acp',
729
784
  },
@@ -833,6 +888,83 @@ export function agentRouter({
833
888
  }
834
889
  }),
835
890
  )
891
+ // The composer's options before the first message: { choices } (this
892
+ // chat's, or the agent's last used) in, { options } out, or { options:
893
+ // null } when the agent offers none, is busy or cannot start (with
894
+ // { error } when it is not signed in). Owner only and from this board's
895
+ // page: nobody else can chat with a native agent, so nobody else starts
896
+ // one. It starts (or reuses) the thread's own session, the one its first
897
+ // turn uses, unless the profile's options are already known (then no
898
+ // process starts; the choices go with the first message). Never evicts
899
+ // another thread's session; an unused one stops when idle, like any.
900
+ router.post(
901
+ '/boards/:id/threads/:thread/prepare',
902
+ findThread,
903
+ handle(async (req, res, board, threadId) => {
904
+ if (!ownerWritesFor(req) || !sameOriginWrite(req)) return controlDenied(res)
905
+ const key = `${board.id}/${threadId}`
906
+ const current = settings(readThread(config, board.id, threadId).profileId)
907
+ if (!current.configured || chatNeedsOwner(req, current)) return res.json({ options: null })
908
+ const choices = cleanChoices(req.body?.choices)
909
+ const force = req.body?.force === true
910
+ const backend = backendFor(current, true)
911
+ if (!backend) return res.json({ options: null })
912
+ if (!backend.prepare) {
913
+ // An endpoint: its model list, and this chat's model when it lists it.
914
+ if (choices.model && choices.model !== chosenModel(current, key)) {
915
+ try {
916
+ await setPickerOption(current, key, 'model', choices.model)
917
+ } catch {
918
+ /* not listed any more: the configured model stays */
919
+ }
920
+ }
921
+ return res.json({ options: (await pickerOptions(current, key).catch(() => null)) || null })
922
+ }
923
+ const live = backend.sessionOptions(key)
924
+ const busy = runs.has(key) || selecting.has(key) || connectionTesting() || undoing
925
+ if (live && (busy || !Object.keys(choices).length)) return res.json({ options: live })
926
+ const known = cachedOptions(current)
927
+ if (busy) return res.json({ options: known?.options ? withChoices(known.options, choices) : null })
928
+ if (!live && known && !force) {
929
+ if (known.error) return res.json({ options: null, ...(known.error.quiet ? {} : { error: known.error }) })
930
+ return res.json({ options: withChoices(known.options, choices), cached: true })
931
+ }
932
+ const admission = new AbortController()
933
+ res.once('close', () => {
934
+ if (!res.writableEnded) admission.abort()
935
+ })
936
+ const release = await beginAgentOperation(config, env, 'turn', { signal: admission.signal }).catch(() => null)
937
+ if (!release) return res.json({ options: null })
938
+ try {
939
+ if (runs.has(key) || selecting.has(key)) return res.json({ options: backend.sessionOptions(key) })
940
+ const options = await backend.prepare(key, { choices, signal: admission.signal })
941
+ ownerThreads.add(key)
942
+ rememberSession(current, backend, key)
943
+ res.json({ options: options?.length ? options : null })
944
+ } catch (error) {
945
+ if (error.code === 'agent_auth') {
946
+ const failure = {
947
+ code: error.code,
948
+ message: error.message,
949
+ ...(error.label ? { label: error.label } : {}),
950
+ ...(error.login ? { login: error.login } : {}),
951
+ }
952
+ health.record(current, { status: 'error', error: failure })
953
+ rememberOptions(current, null, failure)
954
+ return res.json({ options: null, error: failure })
955
+ }
956
+ // Busy or stopped: today's composer, quietly. An agent that does not
957
+ // start is not started again for a while either (it says why on a turn).
958
+ if (!['agent_busy', 'agent_stopped'].includes(error.code)) {
959
+ log(`options: ${error.message}`)
960
+ rememberOptions(current, null, { code: error.code || 'agent_start', quiet: true })
961
+ }
962
+ res.json({ options: null })
963
+ } finally {
964
+ await release()
965
+ }
966
+ }),
967
+ )
836
968
  // The composer's model or effort picker: { configId, value }, one of the
837
969
  // choices the thread's running agent session lists. Owner only, never
838
970
  // while an answer runs; the agent's defaults and Settings > Agent stay as
@@ -847,7 +979,8 @@ export function agentRouter({
847
979
  const { configId, value } = req.body || {}
848
980
  if (typeof configId !== 'string' || typeof value !== 'string' || configId.length > 100 || value.length > 200)
849
981
  return fail(res, 400, 'bad_option', 'configId and value are strings.')
850
- const options = await setPickerOption(settings(readThread(config, board.id, threadId).profileId), key, configId, value)
982
+ const current = settings(readThread(config, board.id, threadId).profileId)
983
+ const options = await setPickerOption(current, key, configId, value, cleanChoices(req.body?.choices))
851
984
  res.json({ options })
852
985
  }),
853
986
  )
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
  }
@@ -7,8 +7,11 @@
7
7
  // (and `detected`: the agent CLIs found on PATH)
8
8
  // POST /api/agent/settings/connect { agentId, confirm } one-click Connect: save that agent's
9
9
  // restricted command (same confirm step), test it, undo on failure
10
- // POST /api/agent/settings/test try the settings in effect: a models list or a one-token answer
11
- // (OpenAI-compatible), the initialize handshake (ACP)
10
+ // POST /api/agent/settings/test { profileId? } try the settings in effect (or that agent's): a models
11
+ // list or a one-token answer (OpenAI-compatible), the initialize handshake (ACP)
12
+ // POST /api/agent/settings/profiles/:id/default make a connected agent (or "endpoint": the saved
13
+ // OpenAI-compatible endpoint) the one new chats and fixes use
14
+ // DELETE /api/agent/settings/profiles/:id remove a connected agent
12
15
  //
13
16
  // These are the server owner's settings: which agent runs on their machine
14
17
  // and where their API key goes. Looking local is not enough (a proxy or TCP
@@ -43,7 +46,7 @@ import {
43
46
  keyHostConfirmed,
44
47
  publicAgentInfo,
45
48
  } from './config.js'
46
- import { legacyProfile, projectKey, saveUserAgentEntry, userAgentEntry, validateUserEntry } from './user-settings.js'
49
+ import { legacyProfile, profileForDefault, projectKey, saveUserAgentEntry, userAgentEntry, validateUserEntry } from './user-settings.js'
47
50
  import { tokenEquals } from '../tokens.js'
48
51
 
49
52
  const TEST_TIMEOUT_MS = 15000
@@ -202,7 +205,8 @@ export async function testConnection(settings, { env = process.env, fetchImpl =
202
205
  return { ...head, ok: false, message: `Not connected: ${settings.problem || 'set a base URL and a model'}.`, details: [] }
203
206
  if (settings.backend === 'acp') {
204
207
  const result = await acpHandshake(settings, { env, root, timeoutMs: timeoutMs || ACP_TEST_TIMEOUT_MS, processPool })
205
- if (!result.ok) return { ...head, ok: false, message: `${settings.label} did not start: ${result.message}`, details: [] }
208
+ if (!result.ok)
209
+ return { ...head, ok: false, code: result.code, message: `${settings.label} did not start: ${result.message}`, details: [] }
206
210
  const info = result.agentInfo
207
211
  const name = info ? `${info.title || info.name}${info.version ? ` ${info.version}` : ''}` : settings.label
208
212
  // The handshake does not show whether the agent is logged in (that needs
@@ -324,7 +328,7 @@ export async function testConnection(settings, { env = process.env, fetchImpl =
324
328
  // `repo` is the config's `agent`. `busy()` is true while an answer is being
325
329
  // written, `reload()` switches the chat over to new settings.
326
330
  // `token` is the per-process settings token (null: the routes are off).
327
- export function settingsRoutes({ config, env, fetchImpl, settings, shared, token, busy, reload, processPool }) {
331
+ export function settingsRoutes({ config, env, fetchImpl, settings, shared, token, busy, reload, processPool, health = null }) {
328
332
  const router = express.Router()
329
333
  const repo = () => config.agent || {}
330
334
  let testing = false
@@ -404,14 +408,35 @@ export function settingsRoutes({ config, env, fetchImpl, settings, shared, token
404
408
  next()
405
409
  })
406
410
 
411
+ // How an agent is doing (agent-health.js): { state, loginHint }.
412
+ const statusOf = (profileId) => (health ? health.status(settings(profileId), processPool) : {})
407
413
  const profileList = (entry) => {
408
414
  const legacy = legacyProfile(entry, KNOWN_AGENTS)
415
+ // Profiles saved without a default connection: the first one (config.js agentSettings).
416
+ const fallback = settings().defaultProfile || null
409
417
  return [...(legacy ? [{ ...legacy, legacy: true }] : []), ...(entry?.profiles || [])].map(({ acpCommand, ...profile }) => ({
410
418
  ...profile,
411
419
  command: acpCommand,
412
- default: entry?.backend === 'acp' && entry.acpCommand === acpCommand,
420
+ default: (entry?.backend === 'acp' && entry.acpCommand === acpCommand) || profile.id === fallback,
421
+ // A legacy command runs as the default connection.
422
+ ...statusOf(profile.legacy ? null : profile.id),
413
423
  }))
414
424
  }
425
+ // The saved OpenAI-compatible endpoint (Settings "Other"), or null.
426
+ const endpointOf = (entry) => {
427
+ const baseUrl = entry.baseUrl ?? repo().baseUrl
428
+ const model = entry.model ?? repo().model
429
+ if (!baseUrl || !model) return null
430
+ const backend = entry.backend ?? repo().backend ?? 'openai-compatible'
431
+ const isDefault = backend === 'openai-compatible' && !settings().defaultProfile
432
+ return {
433
+ label: entry.label || repo().label || model,
434
+ model,
435
+ host: hostOf(baseUrl),
436
+ default: isDefault,
437
+ ...(isDefault ? statusOf(null) : {}),
438
+ }
439
+ }
415
440
 
416
441
  const view = () => {
417
442
  const current = settings()
@@ -425,6 +450,7 @@ export function settingsRoutes({ config, env, fetchImpl, settings, shared, token
425
450
  // show: the saved profiles, and a default command saved before
426
451
  // profiles (legacy) as one of them.
427
452
  profiles: profileList(saved.entry),
453
+ endpoint: endpointOf(saved.entry || {}),
428
454
  project: { root: projectKey(config.dir), configFile: config.file || null },
429
455
  config: Object.fromEntries(SAVED_KEYS.filter((key) => repo()[key] !== undefined).map((key) => [key, repo()[key]])),
430
456
  effective: {
@@ -453,6 +479,8 @@ export function settingsRoutes({ config, env, fetchImpl, settings, shared, token
453
479
  // The agent CLIs found on PATH (looked up, never started), for the
454
480
  // one-click Connect in an unconnected chat panel.
455
481
  detected: detectAgents(env),
482
+ // Every agent Shapewall knows how to run, found or not (the console's Agents page).
483
+ known: KNOWN_AGENTS.map(({ id, label, adapter, cli, install }) => ({ id, label, adapter, cli, install })),
456
484
  knownKeyHosts: [...KNOWN_KEY_HOSTS],
457
485
  defaultKeyVar: DEFAULT_KEY_VAR,
458
486
  keyVarsSet: keyVarsSet(env),
@@ -582,7 +610,9 @@ export function settingsRoutes({ config, env, fetchImpl, settings, shared, token
582
610
  }
583
611
  testing = true
584
612
  try {
585
- const result = await testConnection(settings(profileConnect ? agent.id : null), { env, fetchImpl, root: config.dir, processPool })
613
+ const tested = settings(profileConnect ? agent.id : null)
614
+ const result = await testConnection(tested, { env, fetchImpl, root: config.dir, processPool })
615
+ health?.record(tested, result)
586
616
  if (!result.ok) restore()
587
617
  res.json({ connected: result.ok, result: { ...result, label: agent.label }, ...view() })
588
618
  } catch (error) {
@@ -598,6 +628,37 @@ export function settingsRoutes({ config, env, fetchImpl, settings, shared, token
598
628
  }
599
629
  })
600
630
 
631
+ // The agent new chats and fixes use: a connected agent (its command
632
+ // becomes the default connection) or "endpoint" (the saved
633
+ // OpenAI-compatible endpoint). Every command here was confirmed when it
634
+ // was connected, so this asks nothing new. Chats that chose an agent keep it.
635
+ router.post('/profiles/:id/default', guard, (req, res) => {
636
+ if (testing) return fail(res, 409, 'test_running', 'A connection test is running.')
637
+ const source = settings().sources?.acpCommand
638
+ if (source === 'flag' || source === 'env')
639
+ return fail(res, 409, 'acp_overridden', 'The agent command comes from the command line or the environment, which wins over Settings.')
640
+ const saved = userAgentEntry(config.dir, env)
641
+ if (saved.problem) return fail(res, 409, 'settings_file_invalid', saved.problem)
642
+ const current = saved.entry || {}
643
+ const legacy = legacyProfile(current, KNOWN_AGENTS)
644
+ const entry = { ...current }
645
+ // A default command saved before profiles stays in the list, as a profile.
646
+ if (legacy) entry.profiles = [legacy, ...(current.profiles || [])]
647
+ if (req.params.id === 'endpoint') {
648
+ if (!endpointOf(current)) return fail(res, 400, 'no_endpoint', 'Set up an OpenAI-compatible endpoint first.')
649
+ entry.backend = 'openai-compatible'
650
+ delete entry.acpCommand
651
+ } else {
652
+ const profile = (entry.profiles || []).find((item) => item.id === req.params.id)
653
+ if (!profile) return fail(res, 404, 'unknown_profile', 'That agent is not connected.')
654
+ // The image toggle belonged to the agent that was the default (as on Connect).
655
+ if (profileForDefault(current)?.acpCommand !== profile.acpCommand) delete entry.vision
656
+ entry.backend = 'acp'
657
+ entry.acpCommand = profile.acpCommand
658
+ }
659
+ if (saveEntry(req, res, entry)) res.json(view())
660
+ })
661
+
601
662
  router.delete('/profiles/:id', guard, (req, res) => {
602
663
  if (testing) return fail(res, 409, 'test_running', 'A connection test is running.')
603
664
  const saved = userAgentEntry(config.dir, env)
@@ -622,9 +683,15 @@ export function settingsRoutes({ config, env, fetchImpl, settings, shared, token
622
683
  router.post('/test', guard, async (req, res) => {
623
684
  if (testing) return fail(res, 409, 'test_running', 'A connection test is already running.')
624
685
  if (busy()) return fail(res, 409, 'agent_running', 'Stop the answer or wait for the profile change before testing.')
686
+ const profileId = req.body?.profileId ?? null
687
+ if (profileId !== null && !(userAgentEntry(config.dir, env).entry?.profiles || []).some((item) => item.id === profileId))
688
+ return fail(res, 400, 'unknown_profile', 'profileId: one of the connected agents.')
625
689
  testing = true
626
690
  try {
627
- res.json(await testConnection(settings(), { env, fetchImpl, root: config.dir, processPool }))
691
+ const tested = settings(profileId)
692
+ const result = await testConnection(tested, { env, fetchImpl, root: config.dir, processPool })
693
+ health?.record(tested, result)
694
+ res.json(result)
628
695
  } catch (error) {
629
696
  fail(res, 500, 'test_failed', `The test did not finish: ${redact(error.message)}`)
630
697
  } finally {
@@ -145,6 +145,18 @@ export function validateUserEntry(raw) {
145
145
  // profiles existed (one-click Connect saved only that), a command of its own,
146
146
  // which is shown and kept as a profile from then on (legacyProfile).
147
147
 
148
+ // Which agent is the default is stored as the default connection itself
149
+ // (backend "acp" and the profile's acpCommand, or an endpoint): there is no
150
+ // separate marker to fall out of step with it. Settings that hold profiles
151
+ // but no default connection of their own (hand-edited, or from a version
152
+ // that only kept the list) use the first profile, unless the config's own
153
+ // endpoint is in effect (config.js agentSettings, `defaultProfile`).
154
+ export function implicitDefault(entry) {
155
+ if (!entry?.profiles?.length) return null
156
+ if (['backend', 'acpCommand', 'baseUrl', 'model'].some((key) => entry[key] !== undefined)) return null
157
+ return entry.profiles[0]
158
+ }
159
+
148
160
  // The saved profile that runs the default connection's command, or null.
149
161
  export function profileForDefault(entry) {
150
162
  if (entry?.backend !== 'acp' || !entry.acpCommand) return null
package/src/server/app.js CHANGED
@@ -412,6 +412,7 @@ export function createApp({
412
412
  const agent = chatOn
413
413
  ? {
414
414
  ...publicAgentInfo(app.locals.agentRouter.settings()),
415
+ ...app.locals.agentRouter.agentStatus(),
415
416
  ownerWrites: app.locals.agentRouter.ownerWritesFor(req),
416
417
  // An agent that runs commands answers only its owner (403 control_needs_owner otherwise).
417
418
  chatNeedsOwner: app.locals.agentRouter.chatNeedsOwner(req),
@@ -1 +0,0 @@
1
- import{$ as e,$t as t,C as n,F as r,K as i,Kt as a,Qt as o,S as s,T as c,Xt as l,Yt as u,Zt as d,_t as f,lt as p,mt as m,q as h,qt as ee,st as g,tt as _,v as te,w as v,x as y,y as ne}from"./index-BHbxSLS4.js";import{n as b,t as x}from"./circle-x-B5smn8Mj.js";var S={name:`copy`,size:24,node:[[`rect`,{width:`14`,height:`14`,x:`8`,y:`8`,rx:`2`,ry:`2`,key:`17jyea`}],[`path`,{d:`M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2`,key:`zix9uf`}]]};S.node;var C=u(S),w={name:`key-round`,size:24,node:[[`path`,{d:`M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z`,key:`1s6t7t`}],[`circle`,{cx:`16.5`,cy:`7.5`,r:`.5`,fill:`currentColor`,key:`w0ekpg`}]]};w.node;var re=u(w),T={name:`plug`,size:24,node:[[`path`,{d:`M12 22v-5`,key:`1ega77`}],[`path`,{d:`M15 8V2`,key:`18g5xt`}],[`path`,{d:`M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z`,key:`1xoxul`}],[`path`,{d:`M9 8V2`,key:`14iosj`}]]};T.node;var E=u(T),D={name:`terminal`,size:24,node:[[`path`,{d:`M12 19h8`,key:`baeox8`}],[`path`,{d:`m4 17 6-6-6-6`,key:`1yngyt`}]]};D.node;var O=u(D),k=t(d(),1),A=l(),ie=`On the computer running Shapewall, run shapewall settings --config FILE --open with this project’s config file to open agent settings. For a direct local board, you can also use the owner link printed by shapewall serve.`;function ae(){return(0,A.jsxs)(A.Fragment,{children:[`On the computer running Shapewall, run `,(0,A.jsx)(`code`,{className:`break-words font-mono`,children:`shapewall settings --config FILE --open`}),` with this project’s config file to open agent settings. For a direct local board, you can also use the owner link printed by`,` `,(0,A.jsx)(`code`,{className:`font-mono`,children:`shapewall serve`}),`.`]})}function j({label:e,htmlFor:t,hint:n,problem:r,children:i,...a}){return(0,A.jsxs)(`div`,{className:`space-y-1`,...a,children:[t?(0,A.jsx)(`label`,{htmlFor:t,className:`block text-xs font-medium text-fg`,children:e}):(0,A.jsx)(`p`,{className:`text-xs font-medium text-fg`,children:e}),i,r?(0,A.jsx)(`p`,{id:t?`${t}-problem`:void 0,className:`text-xs text-bad`,role:`alert`,"data-sw-settings-problem":`true`,children:r}):n?(0,A.jsx)(`p`,{className:`text-xs text-muted`,children:n}):null]})}function M({text:e,label:t,touch:n}){let[r,i]=(0,k.useState)(!1),[o,s]=(0,k.useState)(!1),c=(0,k.useRef)(null);return(0,k.useEffect)(()=>{if(!r)return;let e=window.setTimeout(()=>i(!1),1500);return()=>window.clearTimeout(e)},[r]),(0,A.jsxs)(`div`,{children:[(0,A.jsxs)(`div`,{className:`flex items-center gap-1 rounded-md border border-line bg-sunken pl-2`,"data-sw-settings-export":t,children:[(0,A.jsx)(`code`,{ref:c,className:`min-w-0 flex-1 overflow-x-auto py-1.5 font-mono text-[11.5px] whitespace-nowrap text-fg`,children:e}),(0,A.jsx)(h,{variant:`ghost`,size:n?`icon`:`icon-sm`,onClick:async()=>{try{await navigator.clipboard.writeText(e),s(!1),i(!0)}catch{if(c.current){let e=document.createRange();e.selectNodeContents(c.current);let t=window.getSelection();t.removeAllRanges(),t.addRange(e)}s(!0)}},"aria-label":r?`Copied`:`Copy the ${t} line`,children:r?(0,A.jsx)(a,{size:14,"aria-hidden":`true`}):(0,A.jsx)(C,{size:14,"aria-hidden":`true`})})]}),o?(0,A.jsx)(`p`,{className:`mt-1 text-xs text-muted`,role:`status`,children:`This browser did not allow copying. The line is selected: press Ctrl+C (or long-press) to copy it.`}):null]})}function N({children:e}){return(0,A.jsxs)(`p`,{className:`flex items-start gap-1.5 text-xs text-fg`,"data-sw-settings-override":`true`,children:[(0,A.jsx)(f,{size:13,className:`mt-px shrink-0 text-warn`,"aria-hidden":`true`}),(0,A.jsx)(`span`,{children:e})]})}function P({items:e,keyVar:t,onCancel:n,onConfirm:r,busy:a,touch:o,confirmLabel:s=`Allow and save`}){let c=o?`touch`:`md`;return(0,A.jsx)(i,{open:!!e,onClose:()=>a?null:n(),title:`Allow this?`,footer:(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(h,{size:c,onClick:n,disabled:a,children:`Cancel`}),(0,A.jsx)(h,{size:c,variant:`default`,onClick:r,disabled:a,"data-sw-settings-confirm":`true`,children:a?`Saving...`:s})]}),children:(0,A.jsx)(`div`,{className:`space-y-3 p-5 text-sm`,"data-sw-settings-confirm-list":`true`,children:(e||[]).map(e=>e.kind===`command`?(0,A.jsxs)(`div`,{className:`space-y-1.5`,"data-sw-settings-confirm-item":`command`,children:[(0,A.jsxs)(`p`,{className:`flex items-center gap-1.5 font-medium text-fg`,children:[(0,A.jsx)(O,{size:14,"aria-hidden":`true`}),` Run this command on this machine, as you`]}),(0,A.jsx)(`code`,{className:`block rounded-md border border-line bg-sunken p-2 font-mono text-xs break-all text-fg`,children:e.command}),e.projectRoot?(0,A.jsxs)(`p`,{className:`text-xs text-muted`,children:[`Source folder for every board in this project:`,` `,(0,A.jsx)(`code`,{className:`font-mono break-all`,"data-sw-settings-confirm-root":!0,children:e.projectRoot})]}):null,(0,A.jsx)(`p`,{className:`text-xs text-muted`,children:`Shapewall starts it for each chat thread, with your login and a small environment. Anyone who can chat on this board drives it. Only allow a command you installed yourself.`})]},`command:${e.command}`):(0,A.jsxs)(`div`,{className:`space-y-1.5`,"data-sw-settings-confirm-item":`host`,children:[(0,A.jsxs)(`p`,{className:`flex items-center gap-1.5 font-medium text-fg`,children:[(0,A.jsx)(re,{size:14,"aria-hidden":`true`}),` Send your API key to `,e.host]}),(0,A.jsxs)(`p`,{className:`text-xs text-muted`,children:[`Every chat request carries the key in `,(0,A.jsx)(`code`,{className:`font-mono`,children:e.keyVar||t}),` to`,` `,(0,A.jsx)(`span`,{className:`font-medium text-fg`,children:e.host}),`. Allow it only if you trust that host with the key.`]})]},`host:${e.keyVar}@${e.host}`))})})}function oe({result:e}){if(!e)return null;let t=e.ok?b:x;return(0,A.jsxs)(`div`,{className:_(`rounded-md border p-3 text-xs`,e.ok?`border-ok/40 bg-ok/10`:`border-bad/40 bg-bad/10`),role:`status`,"data-sw-settings-test-result":e.ok?`ok`:`failed`,children:[(0,A.jsxs)(`p`,{className:_(`flex items-start gap-1.5 font-medium`,e.ok?`text-fg`:`text-bad`),children:[(0,A.jsx)(t,{size:14,className:_(`mt-px shrink-0`,e.ok?`text-ok`:`text-bad`),"aria-hidden":`true`}),(0,A.jsx)(`span`,{children:e.message})]}),e.details?.length?(0,A.jsx)(`ul`,{className:`mt-1.5 list-disc space-y-0.5 pl-5 text-muted`,children:e.details.map(e=>(0,A.jsx)(`li`,{children:e},e))}):null]})}function se({view:e,disabled:t,touch:n,onBusy:r,onChanged:i,buzz:a}){let[o,s]=(0,k.useState)(!1);(0,k.useEffect)(()=>r?.(o),[o,r]);let[c,l]=(0,k.useState)(null),[u,d]=(0,k.useState)(null),f=async(e,t=null)=>{s(!0),d(null);try{let n=await g.post(`/api/agent/settings/profiles/connect`,{agentId:e,confirm:t});if(n.confirm){l({agentId:e,items:n.confirm,hash:n.confirmHash});return}l(null),d(n.result),n.connected&&await i()}catch(e){l(null),d({ok:!1,message:e.message})}finally{s(!1)}},p=async e=>{s(!0);try{await g.delete(`/api/agent/settings/profiles/${encodeURIComponent(e)}`),await i()}catch(e){d({ok:!1,message:e.message})}finally{s(!1)}},m=e.profiles||e.saved?.profiles||[];return(0,A.jsxs)(`section`,{className:`space-y-3 rounded-md border border-line p-3`,"data-sw-native-profiles":!0,children:[(0,A.jsx)(`h3`,{className:`text-sm font-semibold text-fg`,children:`Native agent profiles`}),(0,A.jsxs)(`p`,{className:`text-xs text-muted`,children:[`Connect several agents, then choose one per chat thread. Each runs its own ACP session using its existing CLI login.`,a?` Buzz conversations are separate.`:``]}),e.env?.acp?(0,A.jsx)(`p`,{className:`text-xs text-muted`,children:`Profiles are locked while an agent command is set on the command line or in the environment (see below).`}):(0,A.jsxs)(A.Fragment,{children:[m.map(e=>(0,A.jsxs)(`div`,{className:`flex items-center justify-between gap-2 text-sm text-fg`,"data-sw-native-profile":e.id,children:[(0,A.jsxs)(`span`,{children:[e.label,e.default?(0,A.jsx)(`span`,{className:`text-xs text-muted`,children:` (new chats use it)`}):null]}),(0,A.jsx)(h,{size:n?`touch`:`sm`,disabled:o||t,onClick:()=>p(e.id),children:`Remove profile`})]},e.id)),(0,A.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:(e.detected||[]).map(e=>(0,A.jsxs)(h,{size:n?`touch`:`sm`,disabled:o||t||e.state!==`ready`,onClick:()=>f(e.id),"data-sw-profile-connect":e.id,children:[m.some(t=>t.id===e.id)?`Reconnect`:`Add`,` `,e.label,e.state===`ready`?``:` (adapter needed)`]},e.id))}),(e.detected||[]).length?null:(0,A.jsx)(`p`,{className:`text-xs text-muted`,children:`No native agent CLI was found on this server's PATH. Install Claude Code with its ACP adapter, Codex with codex-acp, or goose, then reopen Settings.`}),t?(0,A.jsx)(`p`,{className:`text-xs text-muted`,children:`Save or discard your changes below before changing profiles.`}):null]}),u?(0,A.jsx)(`p`,{role:`status`,className:_(`text-xs`,u.ok?`text-muted`:`text-bad`),children:u.message}):null,(0,A.jsx)(P,{items:c?.items||null,keyVar:``,busy:o,touch:n,onCancel:()=>l(null),onConfirm:()=>f(c.agentId,c.hash),confirmLabel:`Allow and connect`})]})}var F=o({SettingsDialog:()=>me}),I=/^(SHAPEWALL_AGENT_[A-Z0-9_]+|[A-Z][A-Z0-9_]*_API_KEY)$/,ce=new Set([`GITHUB_TOKEN`,`GH_TOKEN`,`SHAPEWALL_GITHUB_TOKEN`,`SHAPEWALL_GITHUB_WEBHOOK_SECRET`,`SHAPEWALL_WEBHOOK_SECRET`,`RESEND_API_KEY`,`SHAPEWALL_AGENT_BASE_URL`,`SHAPEWALL_AGENT_MODEL`,`SHAPEWALL_AGENT_KEY_HOSTS`]),le=[{id:`openai-compatible`,label:`OpenAI-compatible`},{id:`acp`,label:`ACP agent`}],ue=[{label:`Claude Code`,command:`claude-agent-acp`},{label:`Codex`,command:`codex-acp`},{label:`goose`,command:`goose acp --with-builtin developer`},{label:`Gemini CLI`,command:`gemini --acp`}];function de(e){return e&&(!I.test(e)||ce.has(e))?`Use SHAPEWALL_AGENT_API_KEY or a name ending in _API_KEY (never another tool’s token).`:null}function fe(e){try{let t=new URL(e);return[`http:`,`https:`].includes(t.protocol)?t.host.toLowerCase():null}catch{return null}}function L(e){let t=e?.saved||{};return{backend:t.backend||e?.effective?.backend||`openai-compatible`,baseUrl:t.baseUrl||``,model:t.model||``,apiKeyEnv:t.apiKeyEnv||``,label:t.label||``,acpCommand:t.acpCommand||``,keyHosts:t.keyHosts||[],vision:typeof t.vision==`boolean`?t.vision:null}}function pe(e,t){return JSON.stringify(e)===JSON.stringify(t)}function R({onSaved:t,touch:n,buzz:i=!1,onDirtyChange:o}){let[s,l]=(0,k.useState)(null),[u,d]=(0,k.useState)(null),[v,y]=(0,k.useState)(L(null)),[b,x]=(0,k.useState)(!1),[S,C]=(0,k.useState)(null),[w,T]=(0,k.useState)(!1),[D,O]=(0,k.useState)(null),[F,I]=(0,k.useState)(!1),[ce,R]=(0,k.useState)(null),[me,he]=(0,k.useState)(!1),z=b||me,B=(0,k.useCallback)(async()=>{try{let e=await g.get(`/api/agent/settings`);l(e),y(L(e)),d(null)}catch(e){e.status===404&&p(),d(e.status===404?ie:e.message)}},[]);(0,k.useEffect)(()=>{B()},[B]);let V=e=>t=>{let n=typeof t==`string`?t:t.target.value;y(t=>({...t,[e]:n})),T(!1)},H=s?!pe(v,L(s)):!1;(0,k.useEffect)(()=>(o?.(H),()=>o?.(!1)),[H,o]);let ge=()=>{y(L(s)),C(null),T(!1)},U=s?.config||{},W=s?.effective||{},G=v.backend===`acp`,K=v.apiKeyEnv.trim()||U.apiKeyEnv||s?.defaultKeyVar||`SHAPEWALL_AGENT_API_KEY`,q=de(v.apiKeyEnv.trim()),J=!!s?.keyVarsSet?.includes(K),Y=s?.env?.baseUrl?W.baseUrl:v.baseUrl.trim()||U.baseUrl||``,X=fe(Y),Z=v.baseUrl.trim()&&!fe(v.baseUrl.trim())?`An http(s) URL, such as https://api.deepseek.com`:null,Q=!J&&!v.apiKeyEnv.trim()&&!U.apiKeyEnv&&/^http:/i.test(Y),_e=!!s?.env?.acp,ve=(0,k.useMemo)(()=>({backend:v.backend,baseUrl:v.baseUrl.trim()||null,model:v.model.trim()||null,apiKeyEnv:v.apiKeyEnv.trim()||null,label:v.label.trim()||null,acpCommand:v.acpCommand.trim()||null,keyHosts:v.keyHosts,vision:v.vision}),[v]),ye=async(e=null)=>{x(!0),C(null);try{let n=await g.post(`/api/agent/settings`,{settings:ve,confirm:e});if(n.confirm){O({items:n.confirm,hash:n.confirmHash});return}l(n),y(L(n)),O(null),T(!0),R(null),t?.()}catch(e){O(null),C(e.message)}finally{x(!1)}},be=async()=>{I(!0),R(null);try{let e=await g.post(`/api/agent/settings/test`,{});R(e),typeof e.vision==`boolean`&&e.vision!==(v.vision??!0)&&y(t=>({...t,vision:e.vision}))}catch(e){R({ok:!1,message:e.message,details:[]})}finally{I(!1)}};if(u)return(0,A.jsxs)(`div`,{className:`space-y-3 p-5`,"data-sw-settings-error":`load`,children:[(0,A.jsx)(`p`,{className:`text-sm text-bad`,role:`alert`,children:u===`On the computer running Shapewall, run shapewall settings --config FILE --open with this project’s config file to open agent settings. For a direct local board, you can also use the owner link printed by shapewall serve.`?(0,A.jsx)(ae,{}):`Could not load the agent settings: ${u}`}),u===`On the computer running Shapewall, run shapewall settings --config FILE --open with this project’s config file to open agent settings. For a direct local board, you can also use the owner link printed by shapewall serve.`?null:(0,A.jsx)(h,{size:n?`touch`:`sm`,onClick:()=>{d(null),B()},children:`Try again`})]});if(!s)return(0,A.jsxs)(`div`,{className:`flex items-center gap-2 p-5 text-sm text-muted`,children:[(0,A.jsx)(c,{}),` Loading`]});if(s.editable===!1)return(0,A.jsxs)(`div`,{className:`space-y-3 p-5`,"data-sw-settings-readonly":!0,children:[(0,A.jsx)(`p`,{className:`text-sm text-muted`,children:s.message}),(0,A.jsx)(`dl`,{className:`space-y-2 text-sm text-fg`,children:[[`Agent`,W.label],[`Backend`,W.backend],[`Command`,W.acpCommand],[`Model`,W.model],[`Endpoint`,W.baseUrl],[`Key variable`,W.keyVar]].filter(([,e])=>e).map(([e,t])=>(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`dt`,{className:`text-xs text-muted`,children:e}),(0,A.jsx)(`dd`,{className:`break-all`,children:t})]},e))})]});let $=n?`touch`:`sm`,xe=e=>W.sources?.[e]===`config`?`from shapewall.config.json`:null,Se=(e,t)=>U[e]?`${U[e]} (${xe(e)||`from the config`})`:t;return(0,A.jsxs)(`div`,{className:`space-y-5`,"data-sw-settings":`agent`,children:[(0,A.jsx)(se,{buzz:i,view:s,disabled:H||b||F,touch:n,onBusy:he,onChanged:async()=>{await B(),t?.()}}),s.project?.root?(0,A.jsxs)(`section`,{className:`space-y-1.5 rounded-md border border-line p-3 text-xs`,"data-sw-agent-project":!0,children:[(0,A.jsx)(`h3`,{className:`font-semibold text-fg`,children:`Source folder on the Shapewall computer`}),(0,A.jsx)(`code`,{className:`block font-mono break-all text-fg`,"data-sw-agent-project-root":!0,children:s.project.root}),(0,A.jsx)(`p`,{className:`text-muted`,children:`Native agents work in this folder for every board in this project. Capturing a website does not give access to its source. To work on another repository, serve a separate project from that checkout on the computer with your agent login.`})]}):null,(0,A.jsxs)(`section`,{className:`flex items-start gap-3 rounded-md border border-line bg-surface-2/60 p-3 text-xs`,"data-sw-settings-status":W.configured?`connected`:`not-connected`,children:[(0,A.jsx)(ee,{size:16,className:`mt-px shrink-0 text-muted`,"aria-hidden":`true`}),(0,A.jsxs)(`div`,{className:`min-w-0 flex-1 space-y-0.5`,children:[(0,A.jsx)(`p`,{className:`font-medium text-fg`,children:W.configured?(0,A.jsxs)(A.Fragment,{children:[`Chat uses `,W.label||`the agent`,W.backend===`acp`?` over ACP, on this machine`:W.host?` at ${W.host}`:``]}):`Chat is not connected yet`}),W.problem?(0,A.jsx)(`p`,{className:`text-bad`,children:W.problem}):null]}),(0,A.jsx)(e,{tone:W.configured?`ok`:`warn`,children:W.configured?W.backend===`acp`?`Command set`:`Connected`:`Not connected`})]}),_e?(0,A.jsxs)(`div`,{className:`space-y-1.5`,"data-sw-settings-acp-override":s.env.acp,children:[(0,A.jsxs)(N,{children:[`The agent command comes from`,` `,s.env.acp===`flag`?`the --agent-acp option on the command line`:`SHAPEWALL_AGENT_ACP in the environment`,` and wins over these settings until Shapewall is started without it.`]}),(0,A.jsx)(`label`,{htmlFor:`sw-agent-acp-in-use`,className:`block text-xs font-medium text-fg`,children:`Command in use`}),(0,A.jsx)(r,{id:`sw-agent-acp-in-use`,size:$,value:W.acpCommand||``,readOnly:!0,className:`font-mono`,"data-sw-settings-acp-in-use":`true`})]}):null,s.fileProblem?(0,A.jsx)(`p`,{className:`text-xs text-bad`,children:s.fileProblem}):null,(0,A.jsx)(j,{label:`Connect to`,children:(0,A.jsx)(te,{label:`Connect to`,options:le,value:v.backend,onChange:e=>{V(`backend`)(e),R(null)},large:n,disabled:z,className:`max-w-sm`})}),G?(0,A.jsxs)(`div`,{className:`space-y-4`,"data-sw-settings-backend":`acp`,children:[(0,A.jsxs)(`section`,{className:`space-y-1.5 rounded-md border border-warn/60 bg-warn/10 p-3 text-xs text-fg`,role:`note`,"data-sw-settings-acp-warning":`true`,children:[(0,A.jsxs)(`p`,{className:`flex items-center gap-1.5 font-medium`,children:[(0,A.jsx)(f,{size:14,className:`shrink-0 text-warn`,"aria-hidden":`true`}),` An ACP agent brings its own tools`]}),(0,A.jsx)(`p`,{children:`It runs with its own tools and extensions (a shell, browser control, MCP servers from its own config), and Shapewall does not sandbox them: Shapewall only asks you before its own file writes and commands. Use a restricted profile:`}),(0,A.jsxs)(`ul`,{className:`list-disc space-y-0.5 pl-5`,children:[(0,A.jsxs)(`li`,{children:[`Claude Code: permission mode `,(0,A.jsx)(`code`,{className:`font-mono`,children:`default`}),` or `,(0,A.jsx)(`code`,{className:`font-mono`,children:`plan`}),` in your Claude settings, never `,(0,A.jsx)(`code`,{className:`font-mono`,children:`bypassPermissions`}),`.`]}),(0,A.jsxs)(`li`,{children:[`Codex: `,(0,A.jsx)(`code`,{className:`font-mono`,children:`sandbox_mode = "workspace-write"`}),` or `,(0,A.jsx)(`code`,{className:`font-mono`,children:`"read-only"`}),`, never `,(0,A.jsx)(`code`,{className:`font-mono`,children:`danger-full-access`}),`.`]}),(0,A.jsxs)(`li`,{children:[`goose: `,(0,A.jsx)(`code`,{className:`font-mono`,children:`goose acp --with-builtin developer`}),` with a profile of its own that has no other extensions (`,(0,A.jsx)(`code`,{className:`font-mono`,children:`GOOSE_PATH_ROOT`}),`).`]})]})]}),(0,A.jsx)(j,{label:_e?`Saved agent command (used when Shapewall starts without the override)`:`Agent command`,htmlFor:`sw-agent-acp`,hint:`One program and its arguments, no shell. It runs on this machine, as you, with its own login; Shapewall asks you before it writes files or runs commands.`,children:(0,A.jsx)(r,{id:`sw-agent-acp`,size:$,value:v.acpCommand,onChange:V(`acpCommand`),placeholder:`claude-agent-acp`,disabled:z,spellCheck:!1,autoCapitalize:`off`,autoComplete:`off`,className:`font-mono`,"data-sw-settings-field":`acpCommand`})}),(0,A.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,"aria-label":`Common agents`,children:ue.map(e=>(0,A.jsx)(h,{size:n?`touch`:`xs`,variant:v.acpCommand.trim()===e.command?`default`:`secondary`,disabled:z,onClick:()=>V(`acpCommand`)(e.command),"data-sw-settings-preset":e.command,children:e.label},e.command))}),(0,A.jsxs)(`p`,{className:`text-xs text-muted`,children:[`Install the adapter first (for Claude Code:`,` `,(0,A.jsx)(`code`,{className:`font-mono`,children:`npm install -g @agentclientprotocol/claude-agent-acp`}),`). See`,` `,(0,A.jsx)(`a`,{className:`text-accent underline-offset-2 hover:underline`,href:`https://shapewall.com/docs/chat`,target:`_blank`,rel:`noreferrer`,children:`the chat docs`}),` `,`for Codex, goose and Gemini CLI.`]})]}):(0,A.jsxs)(`div`,{className:`space-y-4`,"data-sw-settings-backend":`openai-compatible`,children:[(0,A.jsxs)(j,{label:`Base URL`,htmlFor:`sw-agent-url`,problem:Z,hint:`The chat completions endpoint without /chat/completions, such as https://api.deepseek.com or https://api.openai.com/v1.`,children:[(0,A.jsx)(r,{id:`sw-agent-url`,size:$,value:v.baseUrl,onChange:V(`baseUrl`),placeholder:Se(`baseUrl`,`https://api.deepseek.com`),inputMode:`url`,spellCheck:!1,autoCapitalize:`off`,autoComplete:`off`,disabled:s.env.baseUrl||z,"aria-invalid":Z?!0:void 0,"aria-describedby":Z?`sw-agent-url-problem`:void 0,"data-sw-settings-field":`baseUrl`}),s.env.baseUrl?(0,A.jsx)(N,{children:`SHAPEWALL_AGENT_BASE_URL is set in the environment and wins over this field.`}):null]}),(0,A.jsxs)(j,{label:`Model`,htmlFor:`sw-agent-model`,children:[(0,A.jsx)(r,{id:`sw-agent-model`,size:$,value:v.model,onChange:V(`model`),placeholder:Se(`model`,`deepseek-chat`),spellCheck:!1,autoCapitalize:`off`,autoComplete:`off`,disabled:s.env.model||z,"data-sw-settings-field":`model`}),s.env.model?(0,A.jsx)(N,{children:`SHAPEWALL_AGENT_MODEL is set in the environment and wins over this field.`}):null]}),(0,A.jsx)(j,{label:`API key variable`,htmlFor:`sw-agent-keyvar`,problem:q,hint:`The name of the environment variable that holds the key. Not the key itself.`,children:(0,A.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,A.jsx)(r,{id:`sw-agent-keyvar`,size:$,value:v.apiKeyEnv,onChange:e=>V(`apiKeyEnv`)(e.target.value.toUpperCase()),placeholder:U.apiKeyEnv||s.defaultKeyVar,spellCheck:!1,autoCapitalize:`characters`,autoComplete:`off`,disabled:z,className:`font-mono`,"aria-invalid":q?!0:void 0,"aria-describedby":q?`sw-agent-keyvar-problem`:void 0,"data-sw-settings-field":`apiKeyEnv`}),Q?null:(0,A.jsx)(e,{tone:J?`ok`:`warn`,"data-sw-settings-key":J?`set`:`missing`,children:J?`Set`:`Not set`})]})}),(0,A.jsxs)(`div`,{className:`space-y-1`,"data-sw-settings-host":X||`none`,children:[(0,A.jsxs)(`p`,{className:`flex items-center gap-1.5 text-xs font-medium text-fg`,children:[(0,A.jsx)(E,{size:13,"aria-hidden":`true`}),` Where the key goes`]}),(0,A.jsx)(`p`,{className:`text-xs text-muted`,children:X?J?(0,A.jsxs)(A.Fragment,{children:[`Each chat request sends the key in `,(0,A.jsx)(`code`,{className:`font-mono`,children:K}),` to`,` `,(0,A.jsx)(`span`,{className:`font-medium text-fg`,"data-sw-settings-key-host":`true`,children:X}),`, and nowhere else.`]}):Q?(0,A.jsxs)(A.Fragment,{children:[`Requests go to `,(0,A.jsx)(`span`,{className:`font-medium text-fg`,children:X}),`, without a key.`]}):(0,A.jsxs)(A.Fragment,{children:[`Requests go to `,(0,A.jsx)(`span`,{className:`font-medium text-fg`,children:X}),`, without a key until`,` `,(0,A.jsx)(`code`,{className:`font-mono`,children:K}),` is set.`]}):`Set a base URL to see where requests go.`})]}),Q?(0,A.jsx)(`p`,{className:`text-xs text-muted`,"data-sw-settings-key-notice":`none`,children:`No API key needed for a local server like Ollama. If yours wants one, name its variable above.`}):(0,A.jsxs)(`div`,{className:`space-y-2 rounded-md border border-line p-3`,"data-sw-settings-key-notice":`true`,children:[(0,A.jsxs)(`p`,{className:`flex items-center gap-1.5 text-xs font-medium text-fg`,children:[(0,A.jsx)(re,{size:13,"aria-hidden":`true`}),` Keys stay in the environment`]}),(0,A.jsxs)(`p`,{className:`text-xs text-muted`,children:[`Shapewall never asks for your API key, saves it or shows it. Set it in the terminal that runs`,` `,(0,A.jsx)(`code`,{className:`font-mono`,children:`shapewall serve`}),`, then restart it:`]}),(0,A.jsx)(M,{text:`export ${K}="paste-your-key-here"`,label:`shell`,touch:n}),(0,A.jsx)(M,{text:`$env:${K} = "paste-your-key-here"`,label:`PowerShell`,touch:n})]}),v.keyHosts.length?(0,A.jsxs)(`div`,{className:`space-y-1.5`,"data-sw-settings-key-hosts":`true`,children:[(0,A.jsx)(`p`,{className:`text-xs font-medium text-fg`,children:`Hosts you allowed the key to go to`}),(0,A.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:v.keyHosts.map(e=>(0,A.jsxs)(`span`,{className:`inline-flex items-center gap-1 rounded-full border border-line bg-surface-2 py-0.5 pr-0.5 pl-2 text-xs`,"data-sw-settings-key-host-item":e.host,children:[e.host,` `,(0,A.jsx)(`span`,{className:`font-mono text-faint`,children:e.apiKeyEnv}),(0,A.jsx)(h,{variant:`ghost`,size:n?`icon`:`icon-xs`,disabled:z,onClick:()=>y(t=>({...t,keyHosts:t.keyHosts.filter(t=>t!==e)})),"aria-label":`Stop sending ${e.apiKeyEnv} to ${e.host}`,children:(0,A.jsx)(m,{size:12,"aria-hidden":`true`})})]},`${e.apiKeyEnv}@${e.host}`))})]}):null]}),(0,A.jsxs)(`div`,{className:`space-y-1`,"data-sw-settings-vision":v.vision===null?`auto`:String(v.vision),children:[(0,A.jsxs)(ne,{size:$,pressed:v.vision??(!G||W.vision!==!1),disabled:z,onPressedChange:e=>{y(t=>({...t,vision:e})),T(!1)},"data-sw-settings-field":`vision`,children:[v.vision??(!G||W.vision!==!1)?(0,A.jsx)(a,{size:13,"aria-hidden":`true`}):null,`This model takes images`]}),(0,A.jsx)(`p`,{className:`text-xs text-muted`,children:v.vision===!1?`Images are not sent; the chat says so when one is attached.`:G&&v.vision===null?`The agent says itself whether it takes images. Test connection checks it.`:`Turn off for a text-only model (many local models): images are then left out instead of failing.`})]}),(0,A.jsx)(j,{label:`Name in the chat panel (optional)`,htmlFor:`sw-agent-label`,children:(0,A.jsx)(r,{id:`sw-agent-label`,size:$,value:v.label,onChange:V(`label`),placeholder:U.label||(G?`the agent’s name`:`the model name`),maxLength:60,disabled:z,"data-sw-settings-field":`label`})}),(0,A.jsxs)(`p`,{className:`text-xs text-faint`,"data-sw-settings-file":`true`,children:[`Saved for this project in `,(0,A.jsx)(`code`,{className:`font-mono break-all`,children:s.file||`your config folder`}),`, outside the repo, never in shapewall.config.json. The environment and `,(0,A.jsx)(`code`,{className:`font-mono`,children:`--agent-acp`}),` win over these settings; they win over the config.`]}),S?(0,A.jsx)(`p`,{className:`text-xs text-bad`,role:`alert`,"data-sw-settings-error":`save`,children:S}):null,(0,A.jsx)(oe,{result:ce}),(0,A.jsxs)(`div`,{className:_(`flex flex-wrap items-center gap-2`,n&&`flex-col-reverse items-stretch`),children:[(0,A.jsxs)(h,{size:$,onClick:be,disabled:F||b||H,"data-sw-settings-test":`true`,children:[F?(0,A.jsx)(c,{}):(0,A.jsx)(E,{size:14,"aria-hidden":`true`}),` `,F?`Testing...`:`Test connection`]}),H?(0,A.jsx)(`span`,{className:`text-xs text-muted`,children:`Save to test these settings.`}):null,w&&!H?(0,A.jsx)(`span`,{className:`text-xs text-muted`,role:`status`,"data-sw-settings-saved":`true`,children:`Saved. Chat uses it now.`}):null,H?(0,A.jsx)(h,{size:$,variant:`ghost`,className:_(!n&&`ml-auto`),onClick:ge,disabled:b,"data-sw-settings-discard":`true`,children:`Discard changes`}):null,(0,A.jsx)(h,{size:$,variant:`default`,className:_(!n&&!H&&`ml-auto`),onClick:()=>ye(null),disabled:b||!H||!!q||!!Z,"data-sw-settings-save":`true`,children:b?`Saving...`:`Save`})]}),(0,A.jsx)(P,{items:D?.items||null,keyVar:K,busy:b,touch:n,onCancel:()=>O(null),onConfirm:()=>ye(D?.hash||null)})]})}function me({open:e,onClose:t,onSaved:r,touch:a,buzz:o=!1}){let[c,l]=(0,k.useState)(!1);return(0,A.jsx)(i,{open:e,onClose:t,title:`Settings`,size:`md`,sticky:c,children:(0,A.jsxs)(y,{defaultValue:`agent`,className:`p-5`,children:[(0,A.jsx)(n,{className:`mb-4 max-w-40`,"aria-label":`Settings`,children:(0,A.jsx)(v,{value:`agent`,large:a,"data-sw-settings-tab":`agent`,children:`Agent`})}),(0,A.jsx)(s,{value:`agent`,children:e?(0,A.jsx)(R,{onSaved:r,touch:a,buzz:o,onDirtyChange:l}):null})]})})}export{ae as a,E as c,M as i,C as l,F as n,ie as o,P as r,O as s,R as t};