shapewall 0.0.0-stage → 0.2.2
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 +139 -0
- package/Dockerfile.agent +45 -0
- package/LICENSE +202 -0
- package/NOTICE +12 -0
- package/README.md +651 -2
- package/THIRD_PARTY.md +165 -0
- package/bin/shapewall.js +29 -0
- package/dist/agent/package-lock.json +8384 -0
- package/dist/client/assets/BoardChat-D5SFd8HE.js +28 -0
- package/dist/client/assets/BuzzDialog-HWXBy52W.js +1 -0
- package/dist/client/assets/ChecksPanel-DTdImWoD.js +1 -0
- package/dist/client/assets/History-CEv6b-av.js +1 -0
- package/dist/client/assets/LocalSettings-C4vriEVQ.js +1 -0
- package/dist/client/assets/Management-DCfhcEUY.js +1 -0
- package/dist/client/assets/QuickConnect-DQGgUsl1.js +1 -0
- package/dist/client/assets/ShareDialog-C_plIto0.js +2 -0
- package/dist/client/assets/app-update-dialog-2hPz_N9G.js +1 -0
- package/dist/client/assets/circle-x-BZMPi8Zf.js +1 -0
- package/dist/client/assets/index-ByQRKVit.css +2 -0
- package/dist/client/assets/index-DweQ8Qtu.js +29 -0
- package/dist/client/assets/refresh-cw-CRow0Nbq.js +1 -0
- package/dist/client/assets/runtime-Bft6x_6E.js +4 -0
- package/dist/client/assets/square-A8EnIYLR.js +1 -0
- package/dist/client/assets/tts-dist-DYlBQmwG.js +18 -0
- package/dist/client/assets/tts-en-g2p-BPUtBFGG.js +1 -0
- package/dist/client/assets/tts-ort-wasm-simd-threaded-qh98TCA_.wasm +0 -0
- package/dist/client/assets/tts-ort.wasm.bundle.min-rEkcs_ow.js +12 -0
- package/dist/client/assets/tts-rolldown-runtime-D8NudN84.js +1 -0
- package/dist/client/assets/tts-spacy-en-tokenizer-6SNMl--A.json +1 -0
- package/dist/client/assets/tts-tts.worker-Bzm6aWbv.js +1 -0
- package/dist/client/assets/tts-us_gold-DcjeNMH1.json +92589 -0
- package/dist/client/assets/tts-us_silver-C964mEB5.json +93363 -0
- package/dist/client/assets/ui-CLbws0rx.js +41 -0
- package/dist/client/build-info.json +1 -0
- package/dist/client/favicon.svg +7 -0
- package/dist/client/icons/apple-touch-icon.png +0 -0
- package/dist/client/icons/icon-192.png +0 -0
- package/dist/client/icons/icon-512.png +0 -0
- package/dist/client/icons/maskable-512.png +0 -0
- package/dist/client/index.html +25 -0
- package/dist/client/manifest.webmanifest +15 -0
- package/dist/client/sw.js +53 -0
- package/dist/client/theme-boot.js +27 -0
- package/dist/console/assets/LocalAccountsApp-BQCcmj3x.js +1 -0
- package/dist/console/assets/LocalConsole-Bb2FUDs7.js +1 -0
- package/dist/console/assets/app-update-dialog-DIeYepLZ.js +1 -0
- package/dist/console/assets/console-C7uJLLOn.js +51 -0
- package/dist/console/assets/console-R8IBY3Am.css +2 -0
- package/dist/console/build-info.json +1 -0
- package/dist/console/console.html +21 -0
- package/dist/console/favicon.svg +7 -0
- package/dist/console/icons/apple-touch-icon.png +0 -0
- package/dist/console/icons/icon-192.png +0 -0
- package/dist/console/icons/icon-512.png +0 -0
- package/dist/console/icons/maskable-512.png +0 -0
- package/dist/console/manifest.webmanifest +15 -0
- package/dist/console/theme-boot.js +27 -0
- package/docs/agent-hardening.md +342 -0
- package/docs/agent-recipes.md +187 -0
- package/docs/agent-workflow.md +320 -0
- package/docs/agents.md +894 -0
- package/docs/architecture.md +242 -0
- package/docs/buzz.md +140 -0
- package/docs/capture-warnings.md +57 -0
- package/docs/config.md +489 -0
- package/docs/deployment.md +289 -0
- package/docs/design-system.md +162 -0
- package/docs/github.md +107 -0
- package/docs/hosted.md +764 -0
- package/docs/images/board-overview.png +0 -0
- package/docs/images/journeys.png +0 -0
- package/docs/images/live-comment.png +0 -0
- package/docs/images/phone-comment.png +0 -0
- package/docs/images/phone-overview.png +0 -0
- package/docs/images/variant.png +0 -0
- package/docs/interaction-audits.md +40 -0
- package/docs/journeys.md +137 -0
- package/docs/local-accounts.md +80 -0
- package/docs/notifications.md +237 -0
- package/docs/page-checks.md +69 -0
- package/docs/performance.md +174 -0
- package/docs/starter-agent.md +325 -0
- package/docs/updates.md +87 -0
- package/examples/audits/interaction.audit.json +17 -0
- package/package.json +132 -4
- package/src/accounts/avatar.js +121 -0
- package/src/accounts/local.js +464 -0
- package/src/agent/acp/command.js +204 -0
- package/src/agent/acp/detect.js +75 -0
- package/src/agent/acp/sandbox.js +160 -0
- package/src/agent/agent-health.js +75 -0
- package/src/agent/backends/acp.js +1297 -0
- package/src/agent/backends/index.js +61 -0
- package/src/agent/backends/openai.js +308 -0
- package/src/agent/composer.js +221 -0
- package/src/agent/config.js +338 -0
- package/src/agent/context.js +191 -0
- package/src/agent/control.js +122 -0
- package/src/agent/errors.js +17 -0
- package/src/agent/feedback-loop.js +137 -0
- package/src/agent/manage.js +94 -0
- package/src/agent/next-steps.js +51 -0
- package/src/agent/owner-mcp.js +38 -0
- package/src/agent/plain-text.js +52 -0
- package/src/agent/ratings-core.js +213 -0
- package/src/agent/ratings.js +100 -0
- package/src/agent/reply-text.js +67 -0
- package/src/agent/routes.js +1065 -0
- package/src/agent/run.js +326 -0
- package/src/agent/settings-routes.js +704 -0
- package/src/agent/showable.js +23 -0
- package/src/agent/starter/approvals.js +181 -0
- package/src/agent/starter/build-image.js +90 -0
- package/src/agent/starter/cli.js +163 -0
- package/src/agent/starter/disk.js +53 -0
- package/src/agent/starter/doctor.js +180 -0
- package/src/agent/starter/egress-proxy.js +351 -0
- package/src/agent/starter/gate.js +90 -0
- package/src/agent/starter/loop.js +114 -0
- package/src/agent/starter/model-relay.js +289 -0
- package/src/agent/starter/pause.js +14 -0
- package/src/agent/starter/probe.js +272 -0
- package/src/agent/starter/prompt.js +41 -0
- package/src/agent/starter/push-guard.js +146 -0
- package/src/agent/starter/rpc.js +164 -0
- package/src/agent/starter/runtime.js +287 -0
- package/src/agent/starter/sandbox-main.js +121 -0
- package/src/agent/starter/settings.js +290 -0
- package/src/agent/starter/source.js +69 -0
- package/src/agent/starter/supervisor.js +755 -0
- package/src/agent/starter/sweep.js +46 -0
- package/src/agent/starter/tools.js +524 -0
- package/src/agent/starter/watch.js +84 -0
- package/src/agent/starter/worktree.js +409 -0
- package/src/agent/text-diff.js +210 -0
- package/src/agent/thread-history.js +223 -0
- package/src/agent/threads.js +399 -0
- package/src/agent/tools.js +200 -0
- package/src/agent/turn-changes.js +424 -0
- package/src/agent/undo-state.js +26 -0
- package/src/agent/user-settings.js +308 -0
- package/src/auth/record.js +375 -0
- package/src/broken-links.js +164 -0
- package/src/buzz/client.js +75 -0
- package/src/buzz/config.js +151 -0
- package/src/buzz/environment.js +13 -0
- package/src/buzz/gateway.js +192 -0
- package/src/buzz/routes.js +61 -0
- package/src/buzz/signer-child.js +205 -0
- package/src/buzz/store.js +89 -0
- package/src/buzz/transport.js +60 -0
- package/src/buzz/verify.js +140 -0
- package/src/capture/actions.js +159 -0
- package/src/capture/capture.js +776 -0
- package/src/capture/dom-names.js +189 -0
- package/src/capture/element-map.js +509 -0
- package/src/capture/live.js +827 -0
- package/src/capture/media-scheme.js +317 -0
- package/src/capture/network-summary.js +86 -0
- package/src/capture/pacing.js +34 -0
- package/src/capture/requests.js +167 -0
- package/src/capture/sanitize.js +752 -0
- package/src/checks/accessibility.js +134 -0
- package/src/checks/budgets.js +58 -0
- package/src/checks/cli.js +55 -0
- package/src/checks/comparison.js +113 -0
- package/src/checks/environments.js +32 -0
- package/src/checks/flow-config.js +82 -0
- package/src/checks/flow-origin.js +53 -0
- package/src/checks/flows.js +398 -0
- package/src/checks/lighthouse-auth.js +145 -0
- package/src/checks/lighthouse-findings.js +130 -0
- package/src/checks/lighthouse.js +395 -0
- package/src/checks/robots.js +85 -0
- package/src/checks/routes.js +52 -0
- package/src/checks/run-control.js +259 -0
- package/src/checks/runner.js +724 -0
- package/src/checks/schema.js +133 -0
- package/src/checks/seo-analysis.js +443 -0
- package/src/checks/seo-probe.js +190 -0
- package/src/checks/seo-snapshot.js +99 -0
- package/src/checks/store.js +214 -0
- package/src/checks/transport.js +47 -0
- package/src/cli/args.js +319 -0
- package/src/cli/capture.js +79 -0
- package/src/cli/commands.js +92 -0
- package/src/cli/comments.js +84 -0
- package/src/cli/help.js +243 -0
- package/src/cli/init.js +214 -0
- package/src/cli/misc.js +64 -0
- package/src/cli/notify.js +87 -0
- package/src/cli/open.js +22 -0
- package/src/cli/serve.js +274 -0
- package/src/cli/variant.js +82 -0
- package/src/cli/watch.js +70 -0
- package/src/cli.js +130 -0
- package/src/comment-fields.js +76 -0
- package/src/comments-cli.js +208 -0
- package/src/config-reload.js +100 -0
- package/src/config.js +1061 -0
- package/src/devices-cli.js +21 -0
- package/src/diff.js +95 -0
- package/src/discover.js +284 -0
- package/src/doctor.js +295 -0
- package/src/event-log.js +268 -0
- package/src/events-cli.js +102 -0
- package/src/events.js +113 -0
- package/src/export.js +119 -0
- package/src/feedback.js +246 -0
- package/src/github.js +551 -0
- package/src/hosted/LICENSE.md +105 -0
- package/src/hosted/access-cli.js +78 -0
- package/src/hosted/admin.js +682 -0
- package/src/hosted/agent-approvals.js +163 -0
- package/src/hosted/agent-policy.js +189 -0
- package/src/hosted/app.js +510 -0
- package/src/hosted/auth-routes.js +540 -0
- package/src/hosted/auth.js +536 -0
- package/src/hosted/backup.js +483 -0
- package/src/hosted/board-context.js +35 -0
- package/src/hosted/board-routes.js +486 -0
- package/src/hosted/board-view.js +94 -0
- package/src/hosted/clean-worker.js +24 -0
- package/src/hosted/cleaner.js +89 -0
- package/src/hosted/comments.js +355 -0
- package/src/hosted/console-routes.js +401 -0
- package/src/hosted/cookies.js +18 -0
- package/src/hosted/crypto.js +80 -0
- package/src/hosted/db.js +496 -0
- package/src/hosted/device-routes.js +175 -0
- package/src/hosted/device.js +233 -0
- package/src/hosted/events.js +63 -0
- package/src/hosted/guards.js +172 -0
- package/src/hosted/guest-view.js +65 -0
- package/src/hosted/http.js +39 -0
- package/src/hosted/import.js +300 -0
- package/src/hosted/mail.js +73 -0
- package/src/hosted/mcp-http.js +71 -0
- package/src/hosted/membership.js +114 -0
- package/src/hosted/operator.js +478 -0
- package/src/hosted/ops-cli.js +345 -0
- package/src/hosted/pages.js +146 -0
- package/src/hosted/permissions.js +113 -0
- package/src/hosted/presence.js +372 -0
- package/src/hosted/projects.js +124 -0
- package/src/hosted/public.js +109 -0
- package/src/hosted/push.js +622 -0
- package/src/hosted/quotas.js +115 -0
- package/src/hosted/ratelimit.js +96 -0
- package/src/hosted/rebind.js +316 -0
- package/src/hosted/retention.js +128 -0
- package/src/hosted/server.js +260 -0
- package/src/hosted/setup-link.js +64 -0
- package/src/hosted/setup.js +323 -0
- package/src/hosted/shares.js +444 -0
- package/src/hosted/tailscale.js +204 -0
- package/src/hosted/tenancy.js +301 -0
- package/src/hosted/token-api.js +455 -0
- package/src/hosted/token-events.js +60 -0
- package/src/hosted/tokens.js +57 -0
- package/src/hosted/turnstile.js +49 -0
- package/src/hosted/usercontent.js +154 -0
- package/src/hosted/zip.js +155 -0
- package/src/invocation.js +58 -0
- package/src/journey-paths.js +282 -0
- package/src/journeys.js +189 -0
- package/src/links.js +106 -0
- package/src/local-projects.js +182 -0
- package/src/lock.js +193 -0
- package/src/mcp.js +417 -0
- package/src/mentions.js +151 -0
- package/src/net.js +15 -0
- package/src/notify/config.js +275 -0
- package/src/notify/index.js +301 -0
- package/src/notify/lease.js +73 -0
- package/src/notify/messages.js +212 -0
- package/src/notify/run.js +174 -0
- package/src/pixeldiff.js +49 -0
- package/src/png.js +143 -0
- package/src/reactions.js +111 -0
- package/src/remote/cli.js +133 -0
- package/src/remote/credentials.js +62 -0
- package/src/remote/ids.js +12 -0
- package/src/remote/login.js +155 -0
- package/src/remote/remote-mcp.js +237 -0
- package/src/remote/remote-watch.js +291 -0
- package/src/remote/remote.js +313 -0
- package/src/remote/share-state.js +78 -0
- package/src/remote/share.js +369 -0
- package/src/remote/terminal.js +13 -0
- package/src/serve-state.js +64 -0
- package/src/server/app.js +824 -0
- package/src/server/devices.js +186 -0
- package/src/server/local-console.js +28 -0
- package/src/server/local-user.js +59 -0
- package/src/server/pairing-routes.js +159 -0
- package/src/server/share-routes.js +89 -0
- package/src/server/tailscale.js +97 -0
- package/src/sitemap.js +431 -0
- package/src/store.js +983 -0
- package/src/tokens.js +11 -0
- package/src/update/routes.js +245 -0
- package/src/watch.js +403 -0
- package/src/which.js +58 -0
|
@@ -0,0 +1,704 @@
|
|
|
1
|
+
// /api/agent/settings: the board's Settings > Agent screen.
|
|
2
|
+
//
|
|
3
|
+
// GET /api/agent/settings what is saved, what is in effect and where each value comes from
|
|
4
|
+
// POST /api/agent/settings save { settings, confirm }; the chat switches over at once. A new
|
|
5
|
+
// command or key host without the matching confirm hash saves
|
|
6
|
+
// nothing and answers { confirm: [{ kind, ... }], confirmHash }
|
|
7
|
+
// (and `detected`: the agent CLIs found on PATH)
|
|
8
|
+
// POST /api/agent/settings/connect { agentId, confirm } one-click Connect: save that agent's
|
|
9
|
+
// restricted command (same confirm step), test it, undo on failure
|
|
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
|
|
15
|
+
//
|
|
16
|
+
// These are the server owner's settings: which agent runs on their machine
|
|
17
|
+
// and where their API key goes. Looking local is not enough (a proxy or TCP
|
|
18
|
+
// forwarder on this machine that rewrites Host makes any visitor look like
|
|
19
|
+
// loopback), so the routes need a capability first: the per-process settings
|
|
20
|
+
// token `shapewall serve` prints in its startup link (#settings-token=...),
|
|
21
|
+
// sent back in the X-Shapewall-Settings-Token header. Without it they are a
|
|
22
|
+
// plain 404. Then, as more conditions: a loopback peer and Host, no proxy
|
|
23
|
+
// headers, a board not shared beyond this machine (else 403), and for a POST
|
|
24
|
+
// an Origin of this board (and Sec-Fetch-Site same-origin when sent).
|
|
25
|
+
// Saving a new ACP command or a new (key variable, host) pair also needs the
|
|
26
|
+
// hash of exactly those items, which the board sends after the person said
|
|
27
|
+
// yes to them in a dialog.
|
|
28
|
+
//
|
|
29
|
+
// Keys are never sent, saved or returned: only the name of the variable.
|
|
30
|
+
|
|
31
|
+
import crypto from 'node:crypto'
|
|
32
|
+
import express from 'express'
|
|
33
|
+
import { formatCommand, loginHint } from './acp/command.js'
|
|
34
|
+
import { KNOWN_AGENTS, detectAgents } from './acp/detect.js'
|
|
35
|
+
import { acpHandshake } from './backends/acp.js'
|
|
36
|
+
import { beginAgentOperation } from './control.js'
|
|
37
|
+
import { redact, upstreamError } from './backends/openai.js'
|
|
38
|
+
import {
|
|
39
|
+
DEFAULT_KEY_VAR,
|
|
40
|
+
DENIED_KEY_VARS,
|
|
41
|
+
KEY_VAR_RE,
|
|
42
|
+
KNOWN_KEY_HOSTS,
|
|
43
|
+
SAVED_KEYS,
|
|
44
|
+
agentKey,
|
|
45
|
+
envKeyHosts,
|
|
46
|
+
keyHostConfirmed,
|
|
47
|
+
publicAgentInfo,
|
|
48
|
+
} from './config.js'
|
|
49
|
+
import { legacyProfile, profileForDefault, projectKey, saveUserAgentEntry, userAgentEntry, validateUserEntry } from './user-settings.js'
|
|
50
|
+
import { tokenEquals } from '../tokens.js'
|
|
51
|
+
|
|
52
|
+
const TEST_TIMEOUT_MS = 15000
|
|
53
|
+
const ACP_TEST_TIMEOUT_MS = 30000
|
|
54
|
+
const VISION_PROBE_MS = 3000
|
|
55
|
+
const LOOPBACK_NAMES = new Set(['127.0.0.1', 'localhost', '[::1]', '::1'])
|
|
56
|
+
// Any of these means a proxy or tunnel stands between the person and us.
|
|
57
|
+
export const PROXY_HEADERS = [
|
|
58
|
+
'x-forwarded-for',
|
|
59
|
+
'x-forwarded-host',
|
|
60
|
+
'x-forwarded-proto',
|
|
61
|
+
'x-forwarded-port',
|
|
62
|
+
'x-forwarded-server',
|
|
63
|
+
'forwarded',
|
|
64
|
+
'via',
|
|
65
|
+
'x-real-ip',
|
|
66
|
+
'cf-connecting-ip',
|
|
67
|
+
'true-client-ip',
|
|
68
|
+
'x-client-ip',
|
|
69
|
+
'client-ip',
|
|
70
|
+
'tailscale-user-login',
|
|
71
|
+
'tailscale-user-name',
|
|
72
|
+
'tailscale-user-profile-pic',
|
|
73
|
+
'tailscale-app-capabilities',
|
|
74
|
+
]
|
|
75
|
+
export const SETTINGS_TOKEN_HEADER = 'x-shapewall-settings-token'
|
|
76
|
+
|
|
77
|
+
// A new settings token: printed by `shapewall serve`, never stored.
|
|
78
|
+
export function newSettingsToken() {
|
|
79
|
+
return crypto.randomBytes(24).toString('base64url')
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Does the request carry this process's settings token? Constant time.
|
|
83
|
+
export function settingsTokenOk(req, token) {
|
|
84
|
+
return tokenEquals(req.headers[SETTINGS_TOKEN_HEADER], token)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// A write from this board's own page: Origin present and equal to the Host,
|
|
88
|
+
// and Sec-Fetch-Site (when the browser sends it) same-origin.
|
|
89
|
+
export function sameOriginWrite(req) {
|
|
90
|
+
const origin = req.headers.origin
|
|
91
|
+
if (typeof origin !== 'string') return false
|
|
92
|
+
try {
|
|
93
|
+
if (new URL(origin).host.toLowerCase() !== String(req.headers.host || '').toLowerCase()) return false
|
|
94
|
+
} catch {
|
|
95
|
+
return false
|
|
96
|
+
}
|
|
97
|
+
const site = req.headers['sec-fetch-site']
|
|
98
|
+
return site === undefined || site === 'same-origin'
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function fail(res, status, code, message, details) {
|
|
102
|
+
res.status(status).json({ error: { code, message, ...(details ? { details } : {}) } })
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function loopbackAddress(address) {
|
|
106
|
+
const value = String(address || '').toLowerCase()
|
|
107
|
+
return value === '::1' || value.startsWith('127.') || value.startsWith('::ffff:127.')
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// From this machine, straight to this server: a loopback peer, a loopback
|
|
111
|
+
// Host, no proxy headers (a proxy on this machine would make every visitor
|
|
112
|
+
// look local), and no other site's Origin.
|
|
113
|
+
export function localRequest(req) {
|
|
114
|
+
if (!loopbackAddress(req.socket?.remoteAddress)) return false
|
|
115
|
+
if (PROXY_HEADERS.some((name) => req.headers[name] !== undefined)) return false
|
|
116
|
+
const host = String(req.headers.host || '')
|
|
117
|
+
if (!LOOPBACK_NAMES.has(host.replace(/:\d+$/, '').toLowerCase())) return false
|
|
118
|
+
const origin = req.headers.origin
|
|
119
|
+
if (origin !== undefined) {
|
|
120
|
+
try {
|
|
121
|
+
if (new URL(origin).host.toLowerCase() !== host.toLowerCase()) return false
|
|
122
|
+
} catch {
|
|
123
|
+
return false
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
return true
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Why the screen is not available for this request, or null.
|
|
130
|
+
export function settingsRefusal(req, { shared }) {
|
|
131
|
+
if (shared) {
|
|
132
|
+
return {
|
|
133
|
+
code: 'settings_shared',
|
|
134
|
+
message:
|
|
135
|
+
'This board is shared beyond this machine, so its agent settings cannot be changed from the board. Change them on a board served only to this machine, in the environment, or in shapewall.config.json.',
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
if (!localRequest(req)) {
|
|
139
|
+
return { code: 'settings_remote', message: 'Agent settings can be changed only from a browser on the machine that runs Shapewall.' }
|
|
140
|
+
}
|
|
141
|
+
return null
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// The variables holding a model key that are set, by name only: so the screen
|
|
145
|
+
// can say whether the one typed in is there.
|
|
146
|
+
function keyVarsSet(env) {
|
|
147
|
+
return Object.keys(env)
|
|
148
|
+
.filter((name) => KEY_VAR_RE.test(name) && !DENIED_KEY_VARS.has(name) && typeof env[name] === 'string' && env[name].trim())
|
|
149
|
+
.sort()
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
function hostOf(url) {
|
|
153
|
+
try {
|
|
154
|
+
return new URL(url).host.toLowerCase()
|
|
155
|
+
} catch {
|
|
156
|
+
return null
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// What saving `entry` would need the person to confirm: a new ACP command,
|
|
161
|
+
// and hosts the key would newly go to. Also returns the key hosts to save,
|
|
162
|
+
// with the host of the base URL in effect added when it is not otherwise
|
|
163
|
+
// confirmed.
|
|
164
|
+
//
|
|
165
|
+
// A host is allowed for one key variable: the pair (apiKeyEnv, host). Naming
|
|
166
|
+
// another variable for the same host asks again.
|
|
167
|
+
export function pendingConfirmations(entry, { saved, repo, env }) {
|
|
168
|
+
const confirm = []
|
|
169
|
+
// A command already saved for this project (the default connection or a
|
|
170
|
+
// profile) was confirmed then: moving it between the two asks nothing.
|
|
171
|
+
const approved = new Set([saved.acpCommand, ...(saved.profiles || []).map((item) => item.acpCommand)].filter(Boolean))
|
|
172
|
+
if (entry.acpCommand && !approved.has(entry.acpCommand)) confirm.push({ kind: 'command', command: entry.acpCommand })
|
|
173
|
+
for (const profile of entry.profiles || []) {
|
|
174
|
+
if (!approved.has(profile.acpCommand)) {
|
|
175
|
+
if (!confirm.some((item) => item.kind === 'command' && item.command === profile.acpCommand))
|
|
176
|
+
confirm.push({ kind: 'command', command: profile.acpCommand })
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
const keyHosts = [...(entry.keyHosts || [])]
|
|
180
|
+
const backend = entry.backend ?? repo.backend ?? 'openai-compatible'
|
|
181
|
+
const keyVar = entry.apiKeyEnv ?? repo.apiKeyEnv ?? DEFAULT_KEY_VAR
|
|
182
|
+
const url = env.SHAPEWALL_AGENT_BASE_URL ? null : (entry.baseUrl ?? repo.baseUrl)
|
|
183
|
+
const host = backend === 'openai-compatible' && url ? hostOf(url) : null
|
|
184
|
+
const forVar = keyHosts.filter((pair) => pair.apiKeyEnv === keyVar).map((pair) => pair.host)
|
|
185
|
+
if (host && !keyHostConfirmed(host, { env, hosts: forVar })) keyHosts.push({ host, apiKeyEnv: keyVar })
|
|
186
|
+
const known = (pair) => (saved.keyHosts || []).some((item) => item.host === pair.host && item.apiKeyEnv === pair.apiKeyEnv)
|
|
187
|
+
for (const pair of keyHosts) if (!known(pair)) confirm.push({ kind: 'host', host: pair.host, keyVar: pair.apiKeyEnv })
|
|
188
|
+
return { confirm, keyHosts }
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// Binds a confirmation to the exact items the dialog showed.
|
|
192
|
+
export function confirmHash(items) {
|
|
193
|
+
return crypto.createHash('sha256').update(JSON.stringify(items)).digest('hex').slice(0, 32)
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// Tries the settings in effect. { ok, backend, label, host, sendsKey, message, details }
|
|
197
|
+
export async function testConnection(settings, { env = process.env, fetchImpl = globalThis.fetch, root, timeoutMs, processPool } = {}) {
|
|
198
|
+
const head = {
|
|
199
|
+
backend: settings.backend,
|
|
200
|
+
label: settings.label,
|
|
201
|
+
host: settings.host,
|
|
202
|
+
sendsKey: Boolean(settings.hasKey && settings.host),
|
|
203
|
+
}
|
|
204
|
+
if (!settings.configured)
|
|
205
|
+
return { ...head, ok: false, message: `Not connected: ${settings.problem || 'set a base URL and a model'}.`, details: [] }
|
|
206
|
+
if (settings.backend === 'acp') {
|
|
207
|
+
const result = await acpHandshake(settings, { env, root, timeoutMs: timeoutMs || ACP_TEST_TIMEOUT_MS, processPool })
|
|
208
|
+
if (!result.ok)
|
|
209
|
+
return { ...head, ok: false, code: result.code, message: `${settings.label} did not start: ${result.message}`, details: [] }
|
|
210
|
+
const info = result.agentInfo
|
|
211
|
+
const name = info ? `${info.title || info.name}${info.version ? ` ${info.version}` : ''}` : settings.label
|
|
212
|
+
// The handshake does not show whether the agent is logged in (that needs
|
|
213
|
+
// a prompt, which would spend the subscription): say so, and how to fix it.
|
|
214
|
+
return {
|
|
215
|
+
...head,
|
|
216
|
+
ok: true,
|
|
217
|
+
message: `Handshake ok, login not checked: ${name} started and answered.`,
|
|
218
|
+
vision: Boolean(result.image),
|
|
219
|
+
details: [
|
|
220
|
+
result.image ? 'It takes images.' : 'It does not take images.',
|
|
221
|
+
...(result.choices || []),
|
|
222
|
+
`If the first message says it is not logged in: ${loginHint(settings.acp.argv)}.`,
|
|
223
|
+
'The agent was stopped again; chats start their own.',
|
|
224
|
+
],
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
const key = agentKey(settings, env)
|
|
228
|
+
const details = []
|
|
229
|
+
const call = async (path, init) => {
|
|
230
|
+
const controller = new AbortController()
|
|
231
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs || TEST_TIMEOUT_MS)
|
|
232
|
+
try {
|
|
233
|
+
const headers = { Accept: 'application/json', ...(init.body ? { 'Content-Type': 'application/json' } : {}) }
|
|
234
|
+
if (key) headers.Authorization = `Bearer ${key}`
|
|
235
|
+
const response = await fetchImpl(`${settings.baseUrl}${path}`, { ...init, headers, redirect: 'error', signal: controller.signal })
|
|
236
|
+
const text = (await response.text().catch(() => '')).slice(0, 200000)
|
|
237
|
+
return { response, text }
|
|
238
|
+
} catch (error) {
|
|
239
|
+
const reason = controller.signal.aborted ? 'timed out' : redact(error.cause?.code || error.message, key)
|
|
240
|
+
throw Object.assign(new Error(`Could not reach ${settings.host} (${reason}).`), { unreachable: true })
|
|
241
|
+
} finally {
|
|
242
|
+
clearTimeout(timer)
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
// Does the model take images? Best effort, never a failure: a model list
|
|
246
|
+
// that says (OpenRouter's architecture.input_modalities), then Ollama's
|
|
247
|
+
// /api/show capabilities. null when nothing says.
|
|
248
|
+
const probeVision = async (listedText) => {
|
|
249
|
+
try {
|
|
250
|
+
const entry = (JSON.parse(listedText || '{}')?.data || []).find((item) => item?.id === settings.model)
|
|
251
|
+
const modalities = entry?.architecture?.input_modalities ?? entry?.input_modalities
|
|
252
|
+
if (Array.isArray(modalities)) return modalities.includes('image')
|
|
253
|
+
} catch {
|
|
254
|
+
// not JSON: no answer here
|
|
255
|
+
}
|
|
256
|
+
// Only for a server used without a key (Ollama and the like), never a hosted API.
|
|
257
|
+
if (key || !/\/v1$/.test(settings.baseUrl)) return null
|
|
258
|
+
const controller = new AbortController()
|
|
259
|
+
const timer = setTimeout(() => controller.abort(), VISION_PROBE_MS)
|
|
260
|
+
try {
|
|
261
|
+
// Ollama's own API on the same server: no key needed, none sent.
|
|
262
|
+
const response = await fetchImpl(`${settings.baseUrl.replace(/\/v1$/, '')}/api/show`, {
|
|
263
|
+
method: 'POST',
|
|
264
|
+
headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
|
|
265
|
+
body: JSON.stringify({ model: settings.model }),
|
|
266
|
+
redirect: 'error',
|
|
267
|
+
signal: controller.signal,
|
|
268
|
+
})
|
|
269
|
+
if (!response.ok) return null
|
|
270
|
+
const capabilities = (await response.json().catch(() => null))?.capabilities
|
|
271
|
+
return Array.isArray(capabilities) ? capabilities.includes('vision') : null
|
|
272
|
+
} catch {
|
|
273
|
+
return null
|
|
274
|
+
} finally {
|
|
275
|
+
clearTimeout(timer)
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
const visionLine = (vision) =>
|
|
279
|
+
vision === true ? ['The model takes images.'] : vision === false ? ['The model does not take images.'] : []
|
|
280
|
+
try {
|
|
281
|
+
const listed = await call('/models', { method: 'GET' })
|
|
282
|
+
if (listed.response.ok) {
|
|
283
|
+
let ids = []
|
|
284
|
+
try {
|
|
285
|
+
ids = (JSON.parse(listed.text)?.data || []).map((item) => String(item?.id ?? '')).filter(Boolean)
|
|
286
|
+
} catch {
|
|
287
|
+
ids = []
|
|
288
|
+
}
|
|
289
|
+
if (ids.includes(settings.model)) {
|
|
290
|
+
const vision = await probeVision(listed.text)
|
|
291
|
+
return {
|
|
292
|
+
...head,
|
|
293
|
+
ok: true,
|
|
294
|
+
message: `Connected: ${settings.host} lists ${settings.model}.`,
|
|
295
|
+
vision,
|
|
296
|
+
details: [`${ids.length} models listed.`, ...visionLine(vision)],
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
details.push(
|
|
300
|
+
ids.length
|
|
301
|
+
? `${settings.model} is not in the ${ids.length} models listed; asked it for a one-token answer.`
|
|
302
|
+
: 'No model list; asked for a one-token answer.',
|
|
303
|
+
)
|
|
304
|
+
} else if (listed.response.status === 401 || listed.response.status === 403) {
|
|
305
|
+
return { ...head, ok: false, message: upstreamError(listed.response.status, listed.text, key).message, details }
|
|
306
|
+
} else {
|
|
307
|
+
details.push(`GET /models answered ${listed.response.status}; asked for a one-token answer instead.`)
|
|
308
|
+
}
|
|
309
|
+
const body = { model: settings.model, messages: [{ role: 'user', content: 'Reply with OK.' }], max_tokens: 5, stream: false }
|
|
310
|
+
const answered = await call('/chat/completions', { method: 'POST', body: JSON.stringify(body) })
|
|
311
|
+
if (!answered.response.ok)
|
|
312
|
+
return { ...head, ok: false, message: upstreamError(answered.response.status, answered.text, key).message, details }
|
|
313
|
+
const vision = await probeVision(listed.response.ok ? listed.text : null)
|
|
314
|
+
return {
|
|
315
|
+
...head,
|
|
316
|
+
ok: true,
|
|
317
|
+
message: `Connected: ${settings.model} at ${settings.host} answered.`,
|
|
318
|
+
vision,
|
|
319
|
+
details: [...details, ...visionLine(vision)],
|
|
320
|
+
}
|
|
321
|
+
} catch (error) {
|
|
322
|
+
if (error.unreachable) return { ...head, ok: false, message: error.message, details }
|
|
323
|
+
throw error
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// `settings()` is the router's (src/agent/routes.js): what is in effect now.
|
|
328
|
+
// `repo` is the config's `agent`. `busy()` is true while an answer is being
|
|
329
|
+
// written, `reload()` switches the chat over to new settings.
|
|
330
|
+
// `token` is the per-process settings token (null: the routes are off).
|
|
331
|
+
export function settingsRoutes({ config, env, fetchImpl, settings, shared, token, busy, reload, processPool, health = null }) {
|
|
332
|
+
const router = express.Router()
|
|
333
|
+
const repo = () => config.agent || {}
|
|
334
|
+
let testing = false
|
|
335
|
+
let closing = false
|
|
336
|
+
const pending = new Set()
|
|
337
|
+
router.close = async () => {
|
|
338
|
+
closing = true
|
|
339
|
+
while (pending.size) await Promise.all([...pending])
|
|
340
|
+
}
|
|
341
|
+
// Shared admission lock: a handshake must not overlap live turns or profile changes.
|
|
342
|
+
router.isTesting = () => testing
|
|
343
|
+
|
|
344
|
+
const guard = (req, res, next) => {
|
|
345
|
+
if (closing) return fail(res, 503, 'settings_stopping', 'Agent settings are stopping.')
|
|
346
|
+
if (['device', 'identity'].includes(req.shapewallAccess?.kind))
|
|
347
|
+
return fail(res, 403, 'settings_remote', 'Change this on the computer running Shapewall.')
|
|
348
|
+
if (!settingsTokenOk(req, token)) return fail(res, 404, 'not_found', 'No such API route.')
|
|
349
|
+
const refusal = settingsRefusal(req, { shared })
|
|
350
|
+
if (refusal) return fail(res, 403, refusal.code, refusal.message)
|
|
351
|
+
if (req.method !== 'GET' && !sameOriginWrite(req)) {
|
|
352
|
+
return fail(res, 403, 'settings_origin', 'Agent settings are saved only from the board page itself.')
|
|
353
|
+
}
|
|
354
|
+
next()
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
router.use(async (req, res, next) => {
|
|
358
|
+
if (['GET', 'HEAD', 'OPTIONS'].includes(req.method)) return next()
|
|
359
|
+
// Authorize before taking admission so an outsider cannot block turns.
|
|
360
|
+
let allowed = false
|
|
361
|
+
guard(req, res, () => {
|
|
362
|
+
allowed = true
|
|
363
|
+
})
|
|
364
|
+
if (!allowed) return
|
|
365
|
+
if (testing) return fail(res, 409, 'test_running', 'A connection test is already running.')
|
|
366
|
+
let finishOperation
|
|
367
|
+
const operation = new Promise((resolve) => {
|
|
368
|
+
finishOperation = () => {
|
|
369
|
+
pending.delete(operation)
|
|
370
|
+
resolve()
|
|
371
|
+
}
|
|
372
|
+
})
|
|
373
|
+
pending.add(operation)
|
|
374
|
+
const admission = new AbortController()
|
|
375
|
+
let release
|
|
376
|
+
const finished = () => {
|
|
377
|
+
if (!testing) release?.().catch(() => {})
|
|
378
|
+
}
|
|
379
|
+
res.once('finish', finished)
|
|
380
|
+
res.once('close', () => {
|
|
381
|
+
admission.abort()
|
|
382
|
+
finished()
|
|
383
|
+
})
|
|
384
|
+
if (req.aborted || res.destroyed) admission.abort()
|
|
385
|
+
try {
|
|
386
|
+
const lease = await beginAgentOperation(config, env, 'settings', { signal: admission.signal })
|
|
387
|
+
if (lease) release = () => lease().finally(finishOperation)
|
|
388
|
+
} catch {
|
|
389
|
+
finishOperation()
|
|
390
|
+
if (admission.signal.aborted) return
|
|
391
|
+
return fail(res, 503, 'agent_activity_unavailable', 'Agent activity could not be checked. Inspect this installation before retrying.')
|
|
392
|
+
}
|
|
393
|
+
if (admission.signal.aborted || closing) {
|
|
394
|
+
if (release) await release()
|
|
395
|
+
else finishOperation()
|
|
396
|
+
return
|
|
397
|
+
}
|
|
398
|
+
if (!release) {
|
|
399
|
+
finishOperation()
|
|
400
|
+
return fail(
|
|
401
|
+
res,
|
|
402
|
+
409,
|
|
403
|
+
'agent_running',
|
|
404
|
+
'An agent turn or settings operation is active for this source project. Wait for it to finish.',
|
|
405
|
+
)
|
|
406
|
+
}
|
|
407
|
+
res.locals.releaseSettingsOperation = release
|
|
408
|
+
next()
|
|
409
|
+
})
|
|
410
|
+
|
|
411
|
+
// How an agent is doing (agent-health.js): { state, loginHint }.
|
|
412
|
+
const statusOf = (profileId) => (health ? health.status(settings(profileId), processPool) : {})
|
|
413
|
+
const profileList = (entry) => {
|
|
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
|
|
417
|
+
return [...(legacy ? [{ ...legacy, legacy: true }] : []), ...(entry?.profiles || [])].map(({ acpCommand, ...profile }) => ({
|
|
418
|
+
...profile,
|
|
419
|
+
command: 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),
|
|
423
|
+
}))
|
|
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
|
+
}
|
|
440
|
+
|
|
441
|
+
const view = () => {
|
|
442
|
+
const current = settings()
|
|
443
|
+
const saved = userAgentEntry(config.dir, env)
|
|
444
|
+
return {
|
|
445
|
+
editable: true,
|
|
446
|
+
file: current.settingsFile,
|
|
447
|
+
fileProblem: saved.problem,
|
|
448
|
+
saved: saved.entry || {},
|
|
449
|
+
// Every connected native agent, the one list Settings and the chat
|
|
450
|
+
// show: the saved profiles, and a default command saved before
|
|
451
|
+
// profiles (legacy) as one of them.
|
|
452
|
+
profiles: profileList(saved.entry),
|
|
453
|
+
endpoint: endpointOf(saved.entry || {}),
|
|
454
|
+
project: { root: projectKey(config.dir), configFile: config.file || null },
|
|
455
|
+
config: Object.fromEntries(SAVED_KEYS.filter((key) => repo()[key] !== undefined).map((key) => [key, repo()[key]])),
|
|
456
|
+
effective: {
|
|
457
|
+
backend: current.backend,
|
|
458
|
+
configured: current.configured,
|
|
459
|
+
problem: current.problem,
|
|
460
|
+
label: current.label,
|
|
461
|
+
baseUrl: current.baseUrl,
|
|
462
|
+
model: current.model,
|
|
463
|
+
host: current.host,
|
|
464
|
+
keyVar: current.keyVar,
|
|
465
|
+
hasKey: current.hasKey,
|
|
466
|
+
keyVarNamed: Boolean(current.keyVarNamed),
|
|
467
|
+
vision: current.vision !== false,
|
|
468
|
+
keyHosts: current.keyHosts,
|
|
469
|
+
acpCommand: current.acp?.argv ? formatCommand(current.acp.argv) : null,
|
|
470
|
+
refusedEnv: current.acp?.refusedEnv || [],
|
|
471
|
+
sources: current.sources || {},
|
|
472
|
+
},
|
|
473
|
+
env: {
|
|
474
|
+
baseUrl: Boolean(env.SHAPEWALL_AGENT_BASE_URL),
|
|
475
|
+
model: Boolean(env.SHAPEWALL_AGENT_MODEL),
|
|
476
|
+
acp: current.sources?.acpCommand === 'flag' || current.sources?.acpCommand === 'env' ? current.sources.acpCommand : null,
|
|
477
|
+
keyHosts: envKeyHosts(env),
|
|
478
|
+
},
|
|
479
|
+
// The agent CLIs found on PATH (looked up, never started), for the
|
|
480
|
+
// one-click Connect in an unconnected chat panel.
|
|
481
|
+
detected: detectAgents(env),
|
|
482
|
+
// Every agent Shapewall knows how to run, found or not (Settings > Agents).
|
|
483
|
+
known: KNOWN_AGENTS.map(({ id, label, adapter, cli, install }) => ({ id, label, adapter, cli, install })),
|
|
484
|
+
knownKeyHosts: [...KNOWN_KEY_HOSTS],
|
|
485
|
+
defaultKeyVar: DEFAULT_KEY_VAR,
|
|
486
|
+
keyVarsSet: keyVarsSet(env),
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
// Paired owner devices see the effective configuration, never host paths,
|
|
491
|
+
// detected binaries, environment contents, or editable capabilities.
|
|
492
|
+
router.get(
|
|
493
|
+
'/',
|
|
494
|
+
(req, res, next) => {
|
|
495
|
+
if (!['device', 'identity'].includes(req.shapewallAccess?.kind)) return next()
|
|
496
|
+
// The same public summary the board gets (/api/agent): no command line, endpoint path or key variable.
|
|
497
|
+
res.json({ editable: false, effective: publicAgentInfo(settings()), message: 'Change this on the computer running Shapewall.' })
|
|
498
|
+
},
|
|
499
|
+
guard,
|
|
500
|
+
(req, res) => res.json(view()),
|
|
501
|
+
)
|
|
502
|
+
|
|
503
|
+
// Saves `entry` after its confirmations (a new command, new key hosts):
|
|
504
|
+
// answers { confirm, confirmHash } and saves nothing until the request
|
|
505
|
+
// carries that hash. Returns true when saved; otherwise it answered.
|
|
506
|
+
const saveEntry = (req, res, entry) => {
|
|
507
|
+
if (entry.updatedAt) delete entry.updatedAt
|
|
508
|
+
const saved = userAgentEntry(config.dir, env)
|
|
509
|
+
if (saved.problem) {
|
|
510
|
+
fail(res, 409, 'settings_file_invalid', saved.problem)
|
|
511
|
+
return false
|
|
512
|
+
}
|
|
513
|
+
const { confirm, keyHosts } = pendingConfirmations(entry, { saved: saved.entry || {}, repo: repo(), env })
|
|
514
|
+
for (const item of confirm) if (item.kind === 'command') item.projectRoot = projectKey(config.dir)
|
|
515
|
+
const hash = confirmHash(confirm)
|
|
516
|
+
if (confirm.length && req.body?.confirm !== hash) {
|
|
517
|
+
// Not an error: the board shows these items and sends their hash back
|
|
518
|
+
// (other items, or none, ask again). Nothing is saved.
|
|
519
|
+
res.json({ confirm, confirmHash: hash })
|
|
520
|
+
return false
|
|
521
|
+
}
|
|
522
|
+
if (busy()) {
|
|
523
|
+
fail(res, 409, 'agent_running', 'An answer is still being written. Stop it, then save.')
|
|
524
|
+
return false
|
|
525
|
+
}
|
|
526
|
+
const next = { ...entry }
|
|
527
|
+
if (keyHosts.length) next.keyHosts = keyHosts
|
|
528
|
+
else delete next.keyHosts
|
|
529
|
+
try {
|
|
530
|
+
saveUserAgentEntry(config.dir, next, env)
|
|
531
|
+
} catch (error) {
|
|
532
|
+
fail(
|
|
533
|
+
res,
|
|
534
|
+
500,
|
|
535
|
+
error.code === 'no_settings_file' ? 'no_settings_file' : 'settings_not_saved',
|
|
536
|
+
`The settings were not saved: ${error.message}`,
|
|
537
|
+
)
|
|
538
|
+
return false
|
|
539
|
+
}
|
|
540
|
+
reload()
|
|
541
|
+
return true
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
router.post('/', guard, (req, res) => {
|
|
545
|
+
const input = req.body?.settings
|
|
546
|
+
if (!input || typeof input !== 'object' || Array.isArray(input))
|
|
547
|
+
return fail(res, 400, 'invalid_settings', 'The settings must be an object.')
|
|
548
|
+
// Old clients save only the default connection. Keep their saved profiles.
|
|
549
|
+
const preserved = input && !Object.hasOwn(input, 'profiles') ? userAgentEntry(config.dir, env).entry?.profiles : undefined
|
|
550
|
+
const { entry, problems } = validateUserEntry({ ...input, ...(preserved ? { profiles: preserved } : {}) })
|
|
551
|
+
if (!entry) return fail(res, 400, 'invalid_settings', problems.join('; '))
|
|
552
|
+
// A Connect is testing what it saved and may put the old settings back:
|
|
553
|
+
// a save now would be lost.
|
|
554
|
+
if (testing) return fail(res, 409, 'test_running', 'A connection test is running. Wait for it, then save.')
|
|
555
|
+
if (saveEntry(req, res, entry)) res.json(view())
|
|
556
|
+
})
|
|
557
|
+
|
|
558
|
+
// One-click Connect: { agentId, confirm }. The command is this server's own
|
|
559
|
+
// restricted one for that agent (src/agent/acp/detect.js), never one the
|
|
560
|
+
// board sends, and only for an agent found on PATH. Saving it asks the same
|
|
561
|
+
// confirmation as any new command. Then the connection test runs; when the
|
|
562
|
+
// agent does not start, what was saved before is put back.
|
|
563
|
+
// { connected, result, ...view }
|
|
564
|
+
router.post(['/connect', '/profiles/connect'], guard, async (req, res) => {
|
|
565
|
+
const profileConnect = req.path === '/profiles/connect'
|
|
566
|
+
const agent = KNOWN_AGENTS.find((item) => item.id === req.body?.agentId)
|
|
567
|
+
if (!agent) return fail(res, 400, 'unknown_agent', `agentId: one of ${KNOWN_AGENTS.map((item) => item.id).join(', ')}`)
|
|
568
|
+
const found = detectAgents(env).find((item) => item.id === agent.id)
|
|
569
|
+
if (found?.state !== 'ready') {
|
|
570
|
+
return fail(res, 409, 'agent_not_found', `${agent.label} is not installed on this machine (${agent.adapter} is not on PATH).`)
|
|
571
|
+
}
|
|
572
|
+
if (testing) return fail(res, 409, 'test_running', 'A connection test is already running.')
|
|
573
|
+
// --agent-acp or SHAPEWALL_AGENT_ACP wins over anything saved: Connect would save one thing and run another.
|
|
574
|
+
const source = settings().sources?.acpCommand
|
|
575
|
+
if (source === 'flag' || source === 'env') {
|
|
576
|
+
return fail(
|
|
577
|
+
res,
|
|
578
|
+
409,
|
|
579
|
+
'acp_overridden',
|
|
580
|
+
`The agent command comes from ${source === 'flag' ? '--agent-acp' : 'SHAPEWALL_AGENT_ACP'}, which wins over the board. Change it there, or restart shapewall serve without it.`,
|
|
581
|
+
)
|
|
582
|
+
}
|
|
583
|
+
const before = userAgentEntry(config.dir, env)
|
|
584
|
+
// The label and the image toggle belong to the agent connected before.
|
|
585
|
+
const entry = { ...(before.entry || {}) }
|
|
586
|
+
if (profileConnect) {
|
|
587
|
+
// A default command saved before profiles becomes a profile too, so
|
|
588
|
+
// the list stays the one place every connected agent is shown.
|
|
589
|
+
const legacy = legacyProfile(entry, KNOWN_AGENTS)
|
|
590
|
+
entry.profiles = [
|
|
591
|
+
...(legacy && legacy.id !== agent.id ? [legacy] : []),
|
|
592
|
+
...(entry.profiles || []).filter((item) => item.id !== agent.id),
|
|
593
|
+
{ id: agent.id, label: agent.label, acpCommand: agent.command },
|
|
594
|
+
]
|
|
595
|
+
}
|
|
596
|
+
if (!profileConnect || !settings().configured) {
|
|
597
|
+
entry.backend = 'acp'
|
|
598
|
+
entry.acpCommand = agent.command
|
|
599
|
+
delete entry.label
|
|
600
|
+
delete entry.vision
|
|
601
|
+
}
|
|
602
|
+
if (!saveEntry(req, res, entry)) return
|
|
603
|
+
// Back to what was there: the panel must not claim an agent that does not start.
|
|
604
|
+
const restore = () => {
|
|
605
|
+
try {
|
|
606
|
+
saveUserAgentEntry(config.dir, before.entry || {}, env)
|
|
607
|
+
} finally {
|
|
608
|
+
reload()
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
testing = true
|
|
612
|
+
try {
|
|
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)
|
|
616
|
+
if (!result.ok) restore()
|
|
617
|
+
res.json({ connected: result.ok, result: { ...result, label: agent.label }, ...view() })
|
|
618
|
+
} catch (error) {
|
|
619
|
+
try {
|
|
620
|
+
restore()
|
|
621
|
+
} catch {
|
|
622
|
+
// the message below says the test did not finish; the settings screen shows what is saved
|
|
623
|
+
}
|
|
624
|
+
fail(res, 500, 'test_failed', `The test did not finish: ${redact(error.message)}`)
|
|
625
|
+
} finally {
|
|
626
|
+
testing = false
|
|
627
|
+
await res.locals.releaseSettingsOperation?.()
|
|
628
|
+
}
|
|
629
|
+
})
|
|
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
|
+
|
|
662
|
+
router.delete('/profiles/:id', guard, (req, res) => {
|
|
663
|
+
if (testing) return fail(res, 409, 'test_running', 'A connection test is running.')
|
|
664
|
+
const saved = userAgentEntry(config.dir, env)
|
|
665
|
+
if (saved.problem) return fail(res, 409, 'settings_file_invalid', saved.problem)
|
|
666
|
+
const current = saved.entry || {}
|
|
667
|
+
const legacy = legacyProfile(current, KNOWN_AGENTS)
|
|
668
|
+
const removed = (current.profiles || []).find((item) => item.id === req.params.id) || (legacy?.id === req.params.id ? legacy : null)
|
|
669
|
+
const entry = { ...current, profiles: (current.profiles || []).filter((item) => item.id !== req.params.id) }
|
|
670
|
+
// Removing the agent new chats use moves them to the next profile, or
|
|
671
|
+
// leaves the chat unconnected when it was the last one.
|
|
672
|
+
if (removed && current.backend === 'acp' && current.acpCommand === removed.acpCommand) {
|
|
673
|
+
const next = entry.profiles.find((item) => item.acpCommand === removed.acpCommand) || entry.profiles[0]
|
|
674
|
+
if (next) entry.acpCommand = next.acpCommand
|
|
675
|
+
else {
|
|
676
|
+
delete entry.acpCommand
|
|
677
|
+
delete entry.backend
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
if (saveEntry(req, res, entry)) res.json(view())
|
|
681
|
+
})
|
|
682
|
+
|
|
683
|
+
router.post('/test', guard, async (req, res) => {
|
|
684
|
+
if (testing) return fail(res, 409, 'test_running', 'A connection test is already running.')
|
|
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.')
|
|
689
|
+
testing = true
|
|
690
|
+
try {
|
|
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)
|
|
695
|
+
} catch (error) {
|
|
696
|
+
fail(res, 500, 'test_failed', `The test did not finish: ${redact(error.message)}`)
|
|
697
|
+
} finally {
|
|
698
|
+
testing = false
|
|
699
|
+
await res.locals.releaseSettingsOperation?.()
|
|
700
|
+
}
|
|
701
|
+
})
|
|
702
|
+
|
|
703
|
+
return router
|
|
704
|
+
}
|