shapewall 0.2.2 → 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.
- package/CHANGELOG.md +10 -0
- package/dist/agent/package-lock.json +2 -2
- package/dist/client/assets/BoardChat-C88k4s-W.js +28 -0
- package/dist/client/assets/{BuzzDialog-HWXBy52W.js → BuzzDialog-CZdwIQLF.js} +1 -1
- package/dist/client/assets/{ChecksPanel-DTdImWoD.js → ChecksPanel-B54chcLA.js} +1 -1
- package/dist/client/assets/{History-CEv6b-av.js → History-CVVuuxUK.js} +1 -1
- package/dist/client/assets/LocalSettings-CvlVtNY_.js +1 -0
- package/dist/client/assets/{Management-DCfhcEUY.js → Management-DOJkFY_o.js} +1 -1
- package/dist/client/assets/QuickConnect-D40mj4Ry.js +1 -0
- package/dist/client/assets/{ShareDialog-C_plIto0.js → ShareDialog-CdVAreaw.js} +1 -1
- package/dist/client/assets/{app-update-dialog-2hPz_N9G.js → app-update-dialog-Dox9-LWv.js} +1 -1
- package/dist/client/assets/{circle-x-BZMPi8Zf.js → circle-x-BmT6vHKl.js} +1 -1
- package/dist/client/assets/{index-DweQ8Qtu.js → index-CwvFfwU0.js} +4 -4
- package/dist/client/assets/index-UIYSPHoh.css +2 -0
- package/dist/client/assets/{refresh-cw-CRow0Nbq.js → refresh-cw-ugt3cWKH.js} +1 -1
- package/dist/client/assets/{square-A8EnIYLR.js → square-_KG6tM5A.js} +1 -1
- package/dist/client/assets/{ui-CLbws0rx.js → ui-BAGBTB_P.js} +1 -1
- package/dist/client/build-info.json +1 -1
- package/dist/client/index.html +3 -3
- package/dist/client/sw.js +2 -2
- package/dist/console/assets/LocalAccountsApp-4MtW1QlZ.js +1 -0
- package/dist/console/assets/LocalConsole-CgKqYa8i.js +1 -0
- package/dist/console/assets/app-update-dialog-S2Yyc7Pw.js +1 -0
- package/dist/console/assets/{console-C7uJLLOn.js → console-BPmBRIoz.js} +3 -3
- package/dist/console/assets/console-DgVrGRMD.css +2 -0
- package/dist/console/build-info.json +1 -1
- package/dist/console/console.html +2 -2
- package/docs/agents.md +61 -35
- package/docs/design-system.md +10 -7
- package/package.json +1 -1
- package/src/agent/backends/acp.js +217 -41
- package/src/agent/options-cache.js +52 -0
- package/src/agent/routes.js +119 -4
- package/src/agent/run.js +20 -1
- package/src/agent/settings-routes.js +1 -1
- package/dist/client/assets/BoardChat-D5SFd8HE.js +0 -28
- package/dist/client/assets/LocalSettings-C4vriEVQ.js +0 -1
- package/dist/client/assets/QuickConnect-DQGgUsl1.js +0 -1
- package/dist/client/assets/index-ByQRKVit.css +0 -2
- package/dist/console/assets/LocalAccountsApp-BQCcmj3x.js +0 -1
- package/dist/console/assets/LocalConsole-Bb2FUDs7.js +0 -1
- package/dist/console/assets/app-update-dialog-DIeYepLZ.js +0 -1
- 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
|
|
71
|
-
// the agent lists them,
|
|
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
|
-
|
|
74
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
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')
|
|
@@ -328,11 +409,17 @@ export function modelFailureAnswer(text) {
|
|
|
328
409
|
|
|
329
410
|
// The chat error for an agent that is not logged in, with how to fix it for
|
|
330
411
|
// that agent (from the command: src/agent/acp/command.js loginHint).
|
|
412
|
+
// `login`: the one command that signs that agent in, for the chat's card
|
|
413
|
+
// (copyable), when there is one.
|
|
414
|
+
const LOGIN_COMMANDS = { claude: 'claude auth login', codex: 'codex login', goose: 'goose configure', gemini: 'gemini' }
|
|
331
415
|
export function authError(label, argv) {
|
|
332
|
-
|
|
416
|
+
const error = new AgentError(
|
|
333
417
|
'agent_auth',
|
|
334
418
|
`${label} is not logged in (or not set up) on this machine. To fix it, ${loginHint(argv)}; then send again.`,
|
|
335
419
|
)
|
|
420
|
+
error.login = LOGIN_COMMANDS[acpAgentKind(argv)] || null
|
|
421
|
+
error.label = label
|
|
422
|
+
return error
|
|
336
423
|
}
|
|
337
424
|
|
|
338
425
|
// What the person's turn looks like to the agent: on a new session, the
|
|
@@ -490,6 +577,9 @@ class AcpProcess {
|
|
|
490
577
|
this.sessionId = session.sessionId
|
|
491
578
|
this.choices = sessionChoices(session)
|
|
492
579
|
this.configOptions = Array.isArray(session.configOptions) ? session.configOptions : []
|
|
580
|
+
this.modes = session.modes && typeof session.modes === 'object' ? session.modes : null
|
|
581
|
+
// As the session started, before any chat's choices: what a new chat starts from.
|
|
582
|
+
this.startOptions = sessionOptions(this.configOptions, this.modes)
|
|
493
583
|
this.state = 'ready'
|
|
494
584
|
} catch (error) {
|
|
495
585
|
throw this.startError(error)
|
|
@@ -674,24 +764,61 @@ class AcpProcess {
|
|
|
674
764
|
turn.killTimer.unref?.()
|
|
675
765
|
}
|
|
676
766
|
|
|
677
|
-
// The composer's
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
767
|
+
// The composer's option menus, as sessionOptions lists them.
|
|
768
|
+
options() {
|
|
769
|
+
return sessionOptions(this.configOptions, this.modes)
|
|
770
|
+
}
|
|
771
|
+
// The same menus with the values the session started with (the agent's
|
|
772
|
+
// defaults): what the options cache keeps for the next new chat.
|
|
773
|
+
defaults() {
|
|
774
|
+
const now = this.options()
|
|
775
|
+
const start = new Map((this.startOptions || []).map((option) => [option.id, option.currentValue]))
|
|
776
|
+
return now.map((option) =>
|
|
777
|
+
start.has(option.id) && option.values.some((item) => item.value === start.get(option.id))
|
|
778
|
+
? { ...option, currentValue: start.get(option.id) }
|
|
779
|
+
: option,
|
|
780
|
+
)
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
// One of those options to one of the values it lists: a config option
|
|
784
|
+
// through session/set_config_option, the older modes through
|
|
785
|
+
// session/set_mode. Never while a turn runs; never a value sessionOptions
|
|
786
|
+
// leaves out (one that would let the agent act without asking).
|
|
681
787
|
async setOption(configId, value) {
|
|
682
788
|
if (this.state !== 'ready' || this.turn) throw new AgentError('agent_running', 'Wait for the answer to finish before switching.', 409)
|
|
683
|
-
const option =
|
|
789
|
+
const option = this.options().find((item) => item.id === configId)
|
|
684
790
|
if (!option || !option.values.some((item) => item.value === value))
|
|
685
791
|
throw new AgentError('bad_option', 'The agent does not offer that choice.', 400)
|
|
792
|
+
if (option.currentValue === value) return this.options()
|
|
686
793
|
let result
|
|
687
794
|
try {
|
|
688
|
-
result =
|
|
795
|
+
result =
|
|
796
|
+
configId === MODE_OPTION_ID
|
|
797
|
+
? await this.connection.agent.request('session/set_mode', { sessionId: this.sessionId, modeId: value })
|
|
798
|
+
: await this.connection.agent.request('session/set_config_option', { sessionId: this.sessionId, configId, value })
|
|
689
799
|
} catch (error) {
|
|
690
800
|
throw new AgentError('agent_upstream', `${this.label} did not switch (${cut(errorText(error) || 'no answer', 200)}).`, 502)
|
|
691
801
|
}
|
|
692
|
-
if (
|
|
802
|
+
if (configId === MODE_OPTION_ID) this.modes = { ...this.modes, currentModeId: value }
|
|
803
|
+
else if (Array.isArray(result?.configOptions)) this.configOptions = result.configOptions
|
|
693
804
|
else this.configOptions = this.configOptions.map((item) => (item.id === configId ? { ...item, currentValue: value } : item))
|
|
694
|
-
return
|
|
805
|
+
return this.options()
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
// The composer's choices for this chat ({ configId: value }), before a
|
|
809
|
+
// turn: each one the session still offers and does not have yet. A choice
|
|
810
|
+
// the agent refuses keeps its own value (logged, never fatal).
|
|
811
|
+
async applyChoices(choices) {
|
|
812
|
+
for (const [configId, value] of Object.entries(choices || {})) {
|
|
813
|
+
if (this.state !== 'ready' || this.turn) return
|
|
814
|
+
const option = this.options().find((item) => item.id === configId)
|
|
815
|
+
if (!option || option.currentValue === value || !option.values.some((item) => item.value === value)) continue
|
|
816
|
+
try {
|
|
817
|
+
await this.setOption(configId, value)
|
|
818
|
+
} catch (error) {
|
|
819
|
+
this.log(`acp: ${this.label} kept its ${option.category} (${error.message})`)
|
|
820
|
+
}
|
|
821
|
+
}
|
|
695
822
|
}
|
|
696
823
|
|
|
697
824
|
// ---- What the agent sends ---------------------------------------------------
|
|
@@ -706,6 +833,11 @@ class AcpProcess {
|
|
|
706
833
|
if (Array.isArray(params.update.configOptions)) this.configOptions = params.update.configOptions
|
|
707
834
|
return
|
|
708
835
|
}
|
|
836
|
+
if (params?.sessionId === this.sessionId && params.update?.sessionUpdate === 'current_mode_update') {
|
|
837
|
+
if (this.modes && typeof params.update.currentModeId === 'string')
|
|
838
|
+
this.modes = { ...this.modes, currentModeId: params.update.currentModeId }
|
|
839
|
+
return
|
|
840
|
+
}
|
|
709
841
|
const turn = this.turn
|
|
710
842
|
if (!turn || turn.cancelled || params?.sessionId !== this.sessionId) return
|
|
711
843
|
const update = params.update || {}
|
|
@@ -1141,15 +1273,21 @@ export function createAcpBackend(
|
|
|
1141
1273
|
const starting = new Set()
|
|
1142
1274
|
let closed = false
|
|
1143
1275
|
|
|
1144
|
-
|
|
1276
|
+
// Sessions started for their options only, while they start: a turn (or
|
|
1277
|
+
// another look) for the same thread waits for that one instead of starting
|
|
1278
|
+
// a second process.
|
|
1279
|
+
const preparing = new Map()
|
|
1280
|
+
|
|
1281
|
+
const evictFor = (evict) => {
|
|
1145
1282
|
if (processes.size + starting.size < limit.processesMax) return
|
|
1146
1283
|
const idle = [...processes.values()].filter((item) => !item.turn && item.state === 'ready').sort((a, b) => a.usedAt - b.usedAt)
|
|
1147
|
-
if (!idle.length
|
|
1284
|
+
if (!idle.length || !evict)
|
|
1285
|
+
throw new AgentError('agent_busy', `${settings.label} is busy in other threads. Try again in a moment.`, 429)
|
|
1148
1286
|
idle[0].kill('evicted')
|
|
1149
1287
|
}
|
|
1150
1288
|
|
|
1151
|
-
const start = async (thread, signal) => {
|
|
1152
|
-
evictFor()
|
|
1289
|
+
const start = async (thread, signal, { evict = true } = {}) => {
|
|
1290
|
+
evictFor(evict)
|
|
1153
1291
|
const agent = new AcpProcess({
|
|
1154
1292
|
argv: settings.acp.argv,
|
|
1155
1293
|
label: settings.label,
|
|
@@ -1165,7 +1303,7 @@ export function createAcpBackend(
|
|
|
1165
1303
|
},
|
|
1166
1304
|
})
|
|
1167
1305
|
if (closed) throw new AgentError('agent_start', 'The server is stopping.')
|
|
1168
|
-
if (processPool) await reserveProcessSlot(processPool, agent, signal)
|
|
1306
|
+
if (processPool) await reserveProcessSlot(processPool, agent, signal, { evict })
|
|
1169
1307
|
if (closed) {
|
|
1170
1308
|
agent.kill('shutdown')
|
|
1171
1309
|
await agent.stoppingPromise
|
|
@@ -1201,27 +1339,38 @@ export function createAcpBackend(
|
|
|
1201
1339
|
vision: settings.vision !== false,
|
|
1202
1340
|
label: settings.label,
|
|
1203
1341
|
runMsMax: limit.runMs,
|
|
1204
|
-
|
|
1342
|
+
// `choices`: the composer's options for this chat ({ configId: value },
|
|
1343
|
+
// owner turns only), applied before the prompt. The turn then reports
|
|
1344
|
+
// the model and thinking level it runs with (the answer's meta line).
|
|
1345
|
+
async *stream({ messages, signal, thread = 'default', choices = null }) {
|
|
1205
1346
|
if (signal?.aborted) return
|
|
1347
|
+
await preparing.get(thread)?.catch(() => {})
|
|
1206
1348
|
let agent = processes.get(thread)
|
|
1207
1349
|
if (agent?.turn) await agent.settled()
|
|
1208
1350
|
agent = processes.get(thread)
|
|
1209
1351
|
if (!agent || agent.state !== 'ready') {
|
|
1210
1352
|
yield { type: 'status', text: `Starting ${settings.label}` }
|
|
1211
1353
|
agent = await start(thread, signal)
|
|
1212
|
-
for (const text of agent.choices) yield { type: 'notice', text }
|
|
1213
1354
|
}
|
|
1214
1355
|
if (signal?.aborted) {
|
|
1215
1356
|
agent.kill('aborted')
|
|
1216
1357
|
await agent.settled()
|
|
1217
1358
|
return
|
|
1218
1359
|
}
|
|
1360
|
+
await agent.applyChoices(choices)
|
|
1361
|
+
const used = usedOptions(agent.options())
|
|
1362
|
+
if (used.length) yield { type: 'options', used }
|
|
1219
1363
|
yield { type: 'status', text: `${settings.label} is working` }
|
|
1220
1364
|
const image = agent.image && settings.vision !== false
|
|
1221
1365
|
if (!image && messages.at(-1)?.content?.some((part) => part.type === 'image')) yield { type: 'notice', text: NO_IMAGES_NOTE }
|
|
1222
1366
|
const turn = agent.prompt(promptBlocks({ messages, fresh: agent.fresh, image, thread }), signal)
|
|
1223
1367
|
try {
|
|
1224
1368
|
for await (const event of turn.events) yield event
|
|
1369
|
+
} catch (error) {
|
|
1370
|
+
// Not signed in: this session stops, so Check again (or the next
|
|
1371
|
+
// message) starts the agent afresh with the new login.
|
|
1372
|
+
if (error?.code === 'agent_auth') agent.kill('signed_out')
|
|
1373
|
+
throw error
|
|
1225
1374
|
} finally {
|
|
1226
1375
|
turn.finish()
|
|
1227
1376
|
await agent.settled()
|
|
@@ -1238,11 +1387,38 @@ export function createAcpBackend(
|
|
|
1238
1387
|
answerPermission(thread, id, optionId, answeredBy = null) {
|
|
1239
1388
|
return processes.get(thread)?.answer(id, optionId, answeredBy) ?? null
|
|
1240
1389
|
},
|
|
1241
|
-
// The composer's
|
|
1242
|
-
//
|
|
1390
|
+
// The composer's option menus, for a thread whose session is running
|
|
1391
|
+
// (they come from session/new). Null without a session.
|
|
1243
1392
|
sessionOptions(thread) {
|
|
1244
1393
|
const agent = processes.get(thread)
|
|
1245
|
-
return agent && agent.state === 'ready' ?
|
|
1394
|
+
return agent && agent.state === 'ready' ? agent.options() : null
|
|
1395
|
+
},
|
|
1396
|
+
// The same, with the values the session started with.
|
|
1397
|
+
sessionDefaults(thread) {
|
|
1398
|
+
const agent = processes.get(thread)
|
|
1399
|
+
return agent && agent.state === 'ready' ? agent.defaults() : null
|
|
1400
|
+
},
|
|
1401
|
+
// The options before the first message: the thread's session, started
|
|
1402
|
+
// the way its first turn would start it (and then reused by that turn),
|
|
1403
|
+
// or the one already running. Never evicts another thread's session; an
|
|
1404
|
+
// unused one stops after `idleMs` like any idle session. `choices` are
|
|
1405
|
+
// applied to it as they would be before a turn.
|
|
1406
|
+
async prepare(thread, { choices = null, signal = null } = {}) {
|
|
1407
|
+
if (closed) throw new AgentError('agent_start', 'The server is stopping.')
|
|
1408
|
+
await preparing.get(thread)?.catch(() => {})
|
|
1409
|
+
let agent = processes.get(thread)
|
|
1410
|
+
if (!agent || agent.state !== 'ready') {
|
|
1411
|
+
const pending = start(thread, signal, { evict: false })
|
|
1412
|
+
preparing.set(thread, pending)
|
|
1413
|
+
try {
|
|
1414
|
+
agent = await pending
|
|
1415
|
+
} finally {
|
|
1416
|
+
if (preparing.get(thread) === pending) preparing.delete(thread)
|
|
1417
|
+
}
|
|
1418
|
+
if (!agent.turn) agent.idle()
|
|
1419
|
+
}
|
|
1420
|
+
if (!agent.turn) await agent.applyChoices(choices)
|
|
1421
|
+
return agent.options()
|
|
1246
1422
|
},
|
|
1247
1423
|
async setSessionOption(thread, configId, value) {
|
|
1248
1424
|
const agent = processes.get(thread)
|
|
@@ -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
|
+
}
|
package/src/agent/routes.js
CHANGED
|
@@ -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,6 +37,8 @@ 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'
|
|
@@ -295,18 +299,43 @@ export function agentRouter({
|
|
|
295
299
|
const entry = threadModels.get(key)
|
|
296
300
|
return entry && entry.fingerprint === JSON.stringify(current) ? entry.model : null
|
|
297
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))
|
|
298
312
|
const pickerOptions = async (current, key) => {
|
|
299
313
|
const backend = liveOwnerBackend(current)
|
|
300
|
-
if (backend?.sessionOptions)
|
|
314
|
+
if (backend?.sessionOptions) {
|
|
315
|
+
const live = backend.sessionOptions(key)
|
|
316
|
+
if (live?.length) rememberSession(current, backend, key)
|
|
317
|
+
return live
|
|
318
|
+
}
|
|
301
319
|
if (!backend?.listModels) return null
|
|
302
320
|
const ids = await backend.listModels()
|
|
303
321
|
const model = chosenModel(current, key) || current.model
|
|
304
322
|
const values = [...new Set([model, ...ids])].filter(Boolean).map((id) => ({ value: id, name: id }))
|
|
305
323
|
return values.length > 1 ? [{ id: 'model', category: 'model', name: 'Model', currentValue: model, values }] : null
|
|
306
324
|
}
|
|
307
|
-
const setPickerOption = async (current, key, configId, value) => {
|
|
325
|
+
const setPickerOption = async (current, key, configId, value, choices = {}) => {
|
|
308
326
|
const backend = liveOwnerBackend(current)
|
|
309
|
-
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
|
+
}
|
|
310
339
|
if (!backend?.listModels) throw new AgentError('no_session', 'The agent session ended. Send a message, then choose again.', 409)
|
|
311
340
|
if (configId !== 'model' || (value !== current.model && !(await backend.listModels()).includes(value)))
|
|
312
341
|
throw new AgentError('bad_option', 'The endpoint does not list that model.', 400)
|
|
@@ -616,6 +645,8 @@ export function agentRouter({
|
|
|
616
645
|
modelOverride: ownerWrites ? chosenModel(current, `${board.id}/${threadId}`) : null,
|
|
617
646
|
// The owner's own feedback notes go to the owner's turns only (ratings-core.js downNotes).
|
|
618
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,
|
|
619
650
|
emit,
|
|
620
651
|
signal: controller.signal,
|
|
621
652
|
ownerWrites,
|
|
@@ -624,6 +655,10 @@ export function agentRouter({
|
|
|
624
655
|
requestedPages,
|
|
625
656
|
})
|
|
626
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}`)
|
|
627
662
|
if (baseline) {
|
|
628
663
|
try {
|
|
629
664
|
const { summary, undo } = await finishTurnChanges(config, baseline, {
|
|
@@ -706,6 +741,8 @@ export function agentRouter({
|
|
|
706
741
|
reload: () => {
|
|
707
742
|
for (const entry of backends.values()) entry.backend?.close?.()
|
|
708
743
|
backends.clear()
|
|
744
|
+
// Connected again or changed: what its sessions offer is learned anew.
|
|
745
|
+
optionsCache.clear()
|
|
709
746
|
return backendFor(settings())
|
|
710
747
|
},
|
|
711
748
|
})
|
|
@@ -851,6 +888,83 @@ export function agentRouter({
|
|
|
851
888
|
}
|
|
852
889
|
}),
|
|
853
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
|
+
)
|
|
854
968
|
// The composer's model or effort picker: { configId, value }, one of the
|
|
855
969
|
// choices the thread's running agent session lists. Owner only, never
|
|
856
970
|
// while an answer runs; the agent's defaults and Settings > Agent stay as
|
|
@@ -865,7 +979,8 @@ export function agentRouter({
|
|
|
865
979
|
const { configId, value } = req.body || {}
|
|
866
980
|
if (typeof configId !== 'string' || typeof value !== 'string' || configId.length > 100 || value.length > 200)
|
|
867
981
|
return fail(res, 400, 'bad_option', 'configId and value are strings.')
|
|
868
|
-
const
|
|
982
|
+
const current = settings(readThread(config, board.id, threadId).profileId)
|
|
983
|
+
const options = await setPickerOption(current, key, configId, value, cleanChoices(req.body?.choices))
|
|
869
984
|
res.json({ options })
|
|
870
985
|
}),
|
|
871
986
|
)
|