clavarium 0.2.236-next.1 → 0.2.237-beta.1

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 (104) hide show
  1. package/config/launch/claude-code.sh +40 -19
  2. package/config/launch/codex.sh +37 -0
  3. package/config/launch/json-set.mjs +5 -2
  4. package/config/launch/mcp-relay.mjs +98 -0
  5. package/config/launch/mcp-sock.sh +31 -0
  6. package/config/launch/screen-watch.mjs +173 -0
  7. package/config/launch/toml-block.mjs +26 -0
  8. package/config/launch/tools-host.mjs +93 -0
  9. package/config/launch/vibe.sh +40 -0
  10. package/config/machine/clavarium-beat +44 -0
  11. package/config/machine/clavarium-beat-one +40 -0
  12. package/config/machine/clavarium-enter +60 -0
  13. package/config/tools.json +170 -12
  14. package/deploy/clavarium-host +385 -31
  15. package/deploy/clavarium-tunnel +14 -3
  16. package/deploy/clavarium.mjs +4 -0
  17. package/deploy/git-read +57 -5
  18. package/deploy/install.sh +11 -5
  19. package/deploy/maintenance.html +5 -2
  20. package/deploy/online.mjs +251 -8
  21. package/deploy/relay.sh +53 -27
  22. package/deploy/tunnel.mjs +7 -5
  23. package/deploy/updater.mjs +168 -25
  24. package/npm-shrinkwrap.json +245 -19
  25. package/package.json +9 -6
  26. package/server/agenda.mjs +140 -0
  27. package/server/api.mjs +392 -28
  28. package/server/apikeys.mjs +1372 -0
  29. package/server/beat.mjs +189 -0
  30. package/server/binders.mjs +42 -0
  31. package/server/boxcollect.mjs +276 -0
  32. package/server/boxes.mjs +348 -29
  33. package/server/bridge.mjs +13 -4
  34. package/server/browsers.mjs +364 -0
  35. package/server/capacity.mjs +37 -10
  36. package/server/carry.mjs +143 -0
  37. package/server/catalog.mjs +48 -0
  38. package/server/contactview.mjs +122 -0
  39. package/server/conversations.mjs +1122 -46
  40. package/server/copywork.mjs +34 -0
  41. package/server/demandes.mjs +251 -0
  42. package/server/desktop.mjs +102 -0
  43. package/server/devices.mjs +1 -0
  44. package/server/dictation-engines.mjs +91 -0
  45. package/server/dockets.mjs +49 -6
  46. package/server/door.mjs +19 -5
  47. package/server/events.mjs +3 -0
  48. package/server/features.mjs +366 -0
  49. package/server/files.mjs +43 -1
  50. package/server/gitaccess.mjs +12 -3
  51. package/server/gitchecks.mjs +17 -3
  52. package/server/gitkeeper.mjs +45 -10
  53. package/server/gitpush.mjs +286 -71
  54. package/server/gitrunner.mjs +144 -10
  55. package/server/grants.mjs +47 -11
  56. package/server/guide.mjs +31 -10
  57. package/server/health.mjs +138 -12
  58. package/server/jobs.mjs +138 -0
  59. package/server/linkguard.mjs +191 -0
  60. package/server/machinelist.mjs +58 -0
  61. package/server/mailref.mjs +90 -0
  62. package/server/mailview.mjs +204 -0
  63. package/server/main.mjs +425 -47
  64. package/server/mcpoauth.mjs +338 -0
  65. package/server/mcpx.mjs +175 -0
  66. package/server/network.mjs +125 -13
  67. package/server/profile.mjs +129 -0
  68. package/server/relayjoin.mjs +67 -0
  69. package/server/resources.mjs +6 -0
  70. package/server/revive.mjs +70 -0
  71. package/server/rooms.mjs +462 -0
  72. package/server/secrets.mjs +25 -12
  73. package/server/serverlogs.mjs +30 -4
  74. package/server/settingswords.mjs +375 -0
  75. package/server/signinhelp.mjs +239 -0
  76. package/server/speech.mjs +40 -4
  77. package/server/spoken.mjs +60 -0
  78. package/server/sshconsole.mjs +99 -0
  79. package/server/sshmachine.mjs +76 -0
  80. package/server/store.mjs +15 -1
  81. package/server/suggest.mjs +66 -0
  82. package/server/talk.mjs +228 -55
  83. package/server/tethers.mjs +223 -13
  84. package/server/toolbox.mjs +30 -7
  85. package/server/tools.mjs +38 -6
  86. package/server/updates.mjs +7 -2
  87. package/server/vm.mjs +215 -46
  88. package/server/vmwatch.mjs +82 -23
  89. package/server/voice.mjs +183 -51
  90. package/server/wakelearn.mjs +214 -0
  91. package/server/wakeups.mjs +42 -2
  92. package/server/watchdog.mjs +102 -0
  93. package/web/app.js +5590 -1237
  94. package/web/desk.js +531 -0
  95. package/web/device.html +15 -2
  96. package/web/features.js +480 -0
  97. package/web/index.html +874 -490
  98. package/web/kit.js +1142 -0
  99. package/web/links.js +2 -2
  100. package/web/mail-view.js +386 -0
  101. package/web/manifest.webmanifest +4 -0
  102. package/web/style.css +1592 -268
  103. package/web/voice-core.js +48 -0
  104. package/web/voice.js +13 -5
package/server/api.mjs CHANGED
@@ -6,22 +6,40 @@
6
6
  * POST /api/conversations {name, tool, memoryMb?}
7
7
  * POST /api/conversations/<name>/sleep
8
8
  * POST /api/conversations/<name>/restart a clean stop (by force if it hangs), then a start
9
+ * GET /api/conversations/<name>/export[?all=1] its tool's state, or everything of it, one archive (#351) POST .../import[?replaceWork=1&reminders=1] put back (same tool)
9
10
  * POST /api/conversations/<name>/machine {memoryMb?, diskGb?, cpus?}: stopped, set, started again (202);
10
11
  * asleep: checked and kept for its wake, as `sizeAtWake` (200)
12
+ * POST /api/conversations/<name>/machine {action: start|stop|restart|sleep|force|force-now}: done on its machine,
13
+ * one at a time (force takes the place of any other; force-now: the next
14
+ * step of the one running) -> its state (202), as below
15
+ * POST /api/conversations/<name>/machine {escalate: true|false}: a stop that hangs goes on to its qemu by itself (default) or asks
16
+ * POST /api/conversations/<name>/machine {watchdog: {on?, delayMin?}}: mute or full that long, its machine is forced off and started, once
17
+ * GET /api/conversations/<name>/machine {action: {kind, since, until, steps: [{id, state, since, s}]} | null, report, limits, escalate, watchdog}
11
18
  * POST /api/conversations/<name>/machine/cancel the size kept for its wake, given up
12
19
  * GET /api/conversations/<name>/health what was last seen of its machine
13
20
  * POST /api/conversations/<name>/health look now (never wakes a machine)
14
21
  * POST /api/conversations/<name>/health/seen what it says now no longer calls its owner (Needs you)
15
22
  * POST /api/conversations/<name>/exit-report why its tool ended: { now (read in its machine, if it runs), last (kept at its end) }
23
+ * POST /api/conversations/<name>/machine {machineMb} in a shared machine: that machine's memory, all in it restarted
16
24
  * POST /api/conversations/<name>/archive
25
+ * POST /api/binder/suggest {id}: at most three quick actions for that card -> {actions: [{key, label, why, on, ask?}]}
17
26
  * POST /api/mailboxes/<name>/live {smtp, email?}: that mailbox connected live too (send, move...), its password reused
18
27
  * POST /api/conversations/<name>/erase {confirm: <its name>}: deleted for good -- its machine and its work files
28
+ * POST /api/conversations/<name>/into-machine {machine, machineMb?}: moved into a shared machine (#221), its tool's state along (202);
29
+ * {} (no machine): out of its shared machine, into one of its own (15-11)
30
+ * POST /api/conversations/<name>/copy {title?, machine?, machineMb?, reminders?}: a copy -- its work, its tool's state, its accesses (its reminders and wake-ups when asked); it untouched (202)
19
31
  * POST /api/conversations/<name>/rebuild {reset?, confirm?}: built again; reset (confirm: its name) for a working one too
32
+ * POST /api/signin-companion {companion}: the conversation that signs the others' tools in with its browser ('' none; 15-11); {clicks}: it clicks Authorize itself
33
+ * POST /api/conversations/<name>/signin-companion {companion}: its own (a conversation, "none"), or null for the general one; never itself
34
+ * POST /api/conversations/<name>/signin-link its sign-in handed to a companion: shown to the person instead
20
35
  * POST /api/conversations/<name>/ask-first {on}: its tool asks before acting (true), or acts without asking in its machine (false, the default), from its next start
21
36
  * POST /api/conversations/<name>/resume {on}: its tool takes up its last session when it starts (true), or starts fresh
22
37
  * POST /api/conversations/<name>/terminal/repair its terminal does not come though its machine runs: repaired
23
38
  * POST /api/conversations/<name>/talk {text, answers?, files?, via?}: written in its chat; files from .../talk/file; via 'voice': dictated
24
39
  * POST /api/conversations/<name>/talk/react {to, reaction}: the owner's reaction to a message of the tool (null: taken back)
40
+ * POST /api/conversations/<name>/talk/pin {to, on}: the owner pins a message of the chat (on: false unpins); 5 at most
41
+ * POST /api/conversations/<name>/talk/split {messages: 500..100000} | {days: 0.5..365} | {off: true}: when its thread is
42
+ * archived into volumes (nothing deleted) -> {split}; read back as `split` in GET .../talk
25
43
  * POST /api/conversations/<name>/chat-name {name}: the name the chat gives its tool ('' : the neutral word of the dictionary)
26
44
  * POST /api/conversations/<name>/tasks-binder {binder}: the binder shown beside its chat ('' automatic, '-' none, else an id)
27
45
  * POST /api/conversations/<name>/voice-mark {on}: what is dictated into its terminal starts with a microphone sign (AI tools only)
@@ -58,6 +76,8 @@
58
76
  * POST /api/updates/apply { version }: update to the version that is out (in the background)
59
77
  * POST /api/updates/back { version }: go back to a release that is kept (in the background)
60
78
  * GET /api/git/<name>/outgoing?target=<branch>&branch=<branch> what would go from the agent's branch, to that branch of the remote
79
+ * GET /api/git/<name>/known To send at once: what is known here, no remote asked, no repository read
80
+ * GET /api/git/<name>/outgoing-all To send: one fetch, one read, the branches that moved last reviewed
61
81
  * GET /api/git/<name>/graph the branch diagram: branches and their last commits
62
82
  * GET /api/git/<name>/commit?id=<sha> one commit, as a review shows it (&base=<sha>: the commits from base to it)
63
83
  * POST /api/git/<name>/push {head, target?, sure?}: exactly that reviewed commit, to exactly that branch
@@ -88,6 +108,19 @@
88
108
  * POST /api/asset-groups/place {asset, group}: put an asset in a group (group null to take it out)
89
109
  * POST /api/asset-groups/<id>/rename {label}
90
110
  * POST /api/asset-groups/<id>/remove
111
+ * GET /api/rooms the rooms (#268): [{id, name, host, members: [{id, kind, name, ref, host?}], unread, last, thinking: [names]}]
112
+ * POST /api/rooms {name, conversations: [names], boxes: [ids], host?}: a new room
113
+ * POST /api/rooms/<id> {name?, host?, add?: {conversations, boxes}, remove?: [member ids]}
114
+ * quiet?: true/false (muted in the list: no dot, at the bottom)
115
+ * POST /api/rooms/<id>/remove the room and its thread
116
+ * POST /api/rooms/<id>/give {asset, rights, shared?}: the same right given to each AI of it, its own
117
+ * conversation's -> {asset, rights, given: [{conversation, ok, kept?, error?}]}
118
+ * GET /api/rooms/<id>/talk?last= its thread, with the room: {room, messages, ...}
119
+ * POST /api/rooms/<id>/talk {text, to?: [AI member ids], files?}: said in it; to its host, or to the AIs named
120
+ * POST /api/rooms/<id>/talk/file?name= the body IS a file the person attaches there -> {path, name, size}
121
+ * GET /api/rooms/<id>/file?p=<id>/<name> a file attached in it
122
+ * GET /api/rooms/<id>/shown?o=ai:<member>:<r>:<p>[&thumb=1] a file an AI of it showed or cited there, read from ITS conversation
123
+ * GET /api/rooms/<id>/mail/open|page?ref=mail:... a mail an AI of it cited there, opened as its conversation's chat opens it
91
124
  * GET /api/conversations/<name>/health-react POST the same {on?, message?, command?}: what it does when its machine is short
92
125
  * GET /api/machines/places GET /api/machines/moving POST /api/machines/move {to}: all the machines to another disk
93
126
  * POST /api/machines/forget-old: the copy a move left behind, removed
@@ -99,20 +132,34 @@
99
132
  * POST /api/wifi/handover: the network handed over to NetworkManager (back as it was if it does not work)
100
133
  * GET /api/meshcentral: the remote screen (MeshCentral); POST /api/meshcentral/enable (turned on, in the background) /disable
101
134
  * GET /api/events?kind=&conversation=&q=&before=&limit= what happened, newest first
135
+ * GET /api/jobs what it is doing: { running, done } (jobs.mjs), its updates of the day among the done
136
+ * GET /api/jobs/log?id= that job, under way or done today, with its log [{at, text}] (404: unknown)
102
137
  * GET /api/history?of=server|<name>&span=1h|24h|7d the curves of memory, CPU and disk (and the reserve, for the server)
103
138
  * GET /api/history/all?span=1h|24h|7d Settings, Usage: the server and every machine (asleep too) on one time axis,
104
139
  * in GB and cores: {t, capacity, server, itself, machines: [{name, alloc, asleep, ...}]}
105
- * GET /api/server/logs?source=&span= what the server's programs said POST /api/server/restart
140
+ * POST /api/server/pressure {way: force|sleep|alert}: memory short, the machine that takes the most forced off (default), put to sleep, or only said
141
+ * GET /api/server/machines {machines: [{name, state, rssMb, sizeMb, since, action}], manager: {ok, downSince, mode, asked, last, reviving}, pressure}
142
+ * POST /api/server/machines/<name>/force its machine forced off, as from its conversation (202)
143
+ * POST /api/server/vm-manager {mode: night|always|ask}: when it hangs, restarted by itself at night (default), always, or never
144
+ * POST /api/server/vm-manager/restart {confirm: true}: restarted now; every machine is suspended and resumed
145
+ * GET /api/server/load host commands by 5-minute window, event-loop delay
146
+ * POST /api/server/profile {seconds}: this server sampled by its own profiler (2-30 s), what holds it
147
+ * GET /api/server/logs?source=&span= what the server's programs said POST /api/server/restart POST /api/server/reboot (the whole server)
106
148
  * GET /api/operators who may sign in POST /api/operators {email} -> {email, password}: shown once
107
149
  * POST /api/operators/<email>/password -> {email, password} POST /api/operators/<email>/disable|enable|remove
108
150
  * POST /api/conversations/<name>/secrets {secret, attached}
109
151
  * GET /api/shortcuts
110
152
  * POST /api/shortcuts {label, text, enter}
111
153
  * POST /api/shortcuts/<id>/remove
154
+ * GET /api/features POST /api/features/dismiss|goals|sharing|welcome what this Clavarium can do, and its next step
155
+ * (features.mjs, answered before this: main.mjs)
112
156
  * GET /api/voice is dictation available?
113
157
  * POST /api/voice?lang= the body IS a WAV recording -> {text}; lang: the device's language
114
158
  * GET /api/dictation the engine chosen in Settings (never a key: a secret's name)
115
- * POST /api/dictation {provider, url, model, secret, language}: chosen, at once
159
+ * POST /api/dictation {language, main: {provider, url, model, secret}, backup: {...} | {provider: 'none'}}: chosen, at once
160
+ * (a body of before, {provider, url, model, secret, language}, sets the main one)
161
+ * GET /api/dictation/models?provider=&secret= that provider's speech-to-text models [{id, label}] (read with the key, kept 24 h)
162
+ * GET /api/dictation/suggestions {providers: [{id, label, models, keys}], suggestions: [{slot, provider, model, secret}]}
116
163
  * POST /api/dictation/off the environment's engine, if any, again
117
164
  * POST /api/dictation/try?provider=&url=&model=&secret=&language=&lang= a WAV -> {text}, nothing saved
118
165
  * GET /api/files?c=<conversation>&r=<resource>&p=<path> a listing
@@ -126,19 +173,41 @@
126
173
  * POST /api/setup/pair {label}: what a device to pair will get (the code is made by /api/shares)
127
174
  * POST /api/setup/drop {id}: something an import waits for, not wanted after all
128
175
  * GET /api/files/download?c=...&r=...&p=<path> one file
176
+ * GET /api/mail/open?ref=mail:...&c= GET /api/mail/page?ref=... a mail cited by its reference, read now (mailref.mjs)
177
+ * POST /api/tether/agenda {target, from?, to?}: a calendar's events of a window, read now (agenda.mjs)
178
+ * POST /api/tether/mail-list|mail-read {target, folder?, text?} | {target, id, folder?}: a mailbox's latest messages, one as text (mailview.mjs)
179
+ * POST /api/tether/contacts|contact {target, text?} | {target, id}: an address book's contacts, one (contactview.mjs)
180
+ * POST /api/tether/ssh-add {title, host, port?, user, key, pin?}: a machine over SSH, opened with a key made
181
+ * here; its host key read and pinned first (sshmachine.mjs)
182
+ * POST /api/tether/console-journal {target}: a machine's shared console, its short journal (sshconsole.mjs);
183
+ * the console itself is a WebSocket, /api/tether/console?target=ID
129
184
  * POST /api/files/import?c=...&r=...&p=<folder>&name=<file name>[&dir=<subfolders>&exists=keep|replace|skip&batch=<id>] the body IS the file
130
185
  * GET /api/files/thumb|text POST /api/files/save|make|rename|move|remove|taken ?c=...&r=...&p=... (see files.mjs)
131
186
  *
132
187
  * A request that changes something must come from this site's own pages: the
133
188
  * Origin header is compared, and the body must be JSON, which a form on
134
189
  * another site cannot send. */
190
+ import { addMachine } from './sshmachine.mjs';
191
+ import { openCodeConfig } from './catalog.mjs';
192
+ import { writeFileSync } from 'node:fs';
193
+ import { suggest } from './suggest.mjs';
135
194
  import { sameOrigin } from './bridge.mjs';
136
195
  import { Refusal, DISK_GB } from './conversations.mjs';
196
+ import { withUpdates } from './jobs.mjs';
197
+ import { readRights, typeOf, nameOf } from './grants.mjs';
137
198
  import { VmUnknown } from './vm.mjs';
138
- import { list, download, importFile, page, PAGE_HEADERS, changeRoute, IMAGE_HEADERS } from './files.mjs';
199
+ import { list, download, importFile, page, PAGE_HEADERS, changeRoute, IMAGE_HEADERS, mailFile, mailPage } from './files.mjs';
200
+ import { mailRoute } from './mailref.mjs';
201
+ import { readAgenda } from './agenda.mjs';
202
+ import { consoleJournal } from './sshconsole.mjs';
203
+ import { readMailList, readMail } from './mailview.mjs';
204
+ import { readContacts, readContact } from './contactview.mjs';
139
205
  import { WORK_TAB } from './resources.mjs';
140
206
  import { transcribe, AUDIO_MAX } from './voice.mjs';
141
207
  import { FILE_MAX } from './setup.mjs';
208
+ import { demandeView } from './demandes.mjs';
209
+ import { mcpAdd, mcpImport, mcpRefresh, mcpRights, mcpSeen, mcpNewTools, forgetKey } from './mcpx.mjs';
210
+ import { BACK_PATH, backPage } from './mcpoauth.mjs';
142
211
 
143
212
  const BODY_MAX = 16 * 1024;
144
213
  /* A setup file travels inside the JSON of a request: room for it, escaped. */
@@ -161,7 +230,7 @@ function readBody(request, max = BODY_MAX) {
161
230
  /* This run of the server: a page's count of binder changes is of one run, and starts again with the next. */
162
231
  const BOOT = Math.random().toString(36).slice(2, 10);
163
232
 
164
- export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts, groups) {
233
+ export async function handleApi(request, response, conversations, headers, resources, originOk = sameOrigin, shortcuts, voice, sharing, secrets, network, signin, mailboxes, gitReview, platform, answerer, wakeups, alerts, talk, gitAccess, gitKeeper, shelf, health, setup, repair, guide, capacity, updates, instance, certificate, team, reacting, machinesMove, serverLogs, history, events, bundles, wifi, binders, meshcentral, tethers, accounts, groups, catalogue, rooms, machineList) {
165
234
  const { pathname } = new URL(request.url ?? '/', 'http://local');
166
235
  if (!pathname.startsWith('/api/')) return false;
167
236
  let send = (status, body) => {
@@ -195,6 +264,8 @@ export async function handleApi(request, response, conversations, headers, resou
195
264
  try {
196
265
  if (request.method === 'GET' && pathname === '/api/voice') return send(200, { available: voice?.current() !== undefined, engine: voice?.model ?? null }), true;
197
266
  if (request.method === 'GET' && pathname === '/api/dictation' && voice) return send(200, voice.about()), true;
267
+ if (request.method === 'GET' && pathname === '/api/dictation/models' && voice) return send(200, await voice.models(query.get('provider') ?? '', query.get('secret') ?? '')), true;
268
+ if (request.method === 'GET' && pathname === '/api/dictation/suggestions' && voice) return send(200, await voice.suggestions()), true;
198
269
  if (request.method === 'POST' && (pathname === '/api/voice' || (pathname === '/api/dictation/try' && voice))) {
199
270
  if (!originOk(request.headers) || request.headers['content-type'] !== 'audio/wav') {
200
271
  return send(403, { error: 'This request does not come from this site.' }), true;
@@ -223,6 +294,19 @@ export async function handleApi(request, response, conversations, headers, resou
223
294
  file.stream.pipe(response);
224
295
  return true;
225
296
  }
297
+ if (request.method === 'GET' && pathname === '/api/files/mail') {
298
+ /* A mail with its remote pictures (asked for, never on opening): as a page is, not for a conversation that is offline. */
299
+ if (conversations.list().find((x) => x.name === query.get('c'))?.offline === true) throw new Refusal(403, 'This conversation is offline: remote pictures stay blocked.');
300
+ const shown = mailPage(await mailFile(attached(), query.get('p') ?? ''));
301
+ response.writeHead(200, shown.headers);
302
+ response.end(shown.body);
303
+ return true;
304
+ }
305
+ if (request.method === 'GET' && (pathname === '/api/mail/open' || pathname === '/api/mail/page')) {
306
+ /* A mail cited by its reference (mailref.mjs), read now through Tether: the owner may read every mailbox. */
307
+ const c = query.get('c') ?? '';
308
+ return await mailRoute(pathname.slice('/api'.length), query, response, { tethers, headers, who: { id: `person:${identity || 'owner'}`, name: identity || 'Owner' }, may: () => true, offline: conversations.list().find((x) => x.name === c)?.offline === true, of: c });
309
+ }
226
310
  if (request.method === 'GET' && pathname === '/api/files/download') {
227
311
  const file = await download(attached(), query.get('p') ?? '');
228
312
  response.writeHead(200, { ...headers, 'content-type': 'application/octet-stream', 'content-length': file.size,
@@ -236,6 +320,23 @@ export async function handleApi(request, response, conversations, headers, resou
236
320
  }
237
321
  return send(201, await importFile(attached('write'), query.get('p') ?? '', query.get('name') ?? '', request, { exists: query.get('exists') ?? 'keep', dir: query.get('dir') ?? '', batch: query.get('batch') ?? undefined })), true;
238
322
  }
323
+ /* A CONVERSATION CARRIED ELSEWHERE (#351): its tool's state as one archive, streamed from its machine;
324
+ put back into a conversation of the same tool. Downloaded and sent by the person, from the page. */
325
+ const carry = /^\/api\/conversations\/([^/]+)\/(export|import)$/.exec(pathname);
326
+ if (carry && request.method === 'GET' && carry[2] === 'export') {
327
+ /* ?all=1: everything of it -- its home, its work, what it was given (conversations.exportWhole). */
328
+ const n = decodeURIComponent(carry[1]);
329
+ const out = query.get('all') === '1' ? await conversations.exportWhole(n) : await conversations.exportState(n);
330
+ response.writeHead(200, { ...headers, 'content-type': 'application/gzip', 'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(out.name)}` });
331
+ out.stream.pipe(response);
332
+ response.on('close', () => { try { out.child?.kill(); } catch { /* ended */ } });
333
+ return true;
334
+ }
335
+ if (carry && request.method === 'POST' && carry[2] === 'import') {
336
+ if (!originOk(request.headers) || request.headers['content-type'] !== 'application/octet-stream') return send(403, { error: 'This request does not come from this site.' }), true;
337
+ /* ?replaceWork=1: a whole export may replace the work folder that holds files (asked first, on the page). */
338
+ return send(200, await conversations.importState(decodeURIComponent(carry[1]), request, { replaceWork: query.get('replaceWork') === '1', reminders: query.get('reminders') === '1' })), true;
339
+ }
239
340
  if (pathname.startsWith('/api/files/')) {
240
341
  if (request.method === 'POST' && !originOk(request.headers)) return send(403, { error: 'This request does not come from this site.' }), true;
241
342
  const answer = await changeRoute(request.method, pathname.slice('/api'.length), query, request, attached);
@@ -255,28 +356,96 @@ export async function handleApi(request, response, conversations, headers, resou
255
356
  if (pathname === '/api/resources' && resources) return send(200, resources.list()), true;
256
357
  if (pathname === '/api/shortcuts' && shortcuts) return send(200, shortcuts.list()), true;
257
358
  if (pathname === '/api/secrets' && secrets) return send(200, secrets.list()), true;
359
+ /* The providers and models OpenCode knows (models.dev), for a conversation made with it (03-11). */
360
+ if (pathname === '/api/catalog/models' && catalogue) return send(200, { providers: await catalogue.providers() }), true;
258
361
  /* The owner's asset groups (groups.mjs): a label and the asset ids each
259
362
  holds. Distinct from /api/groups/* above, which are the conversation
260
363
  list's folders. */
261
364
  if (pathname === '/api/asset-groups' && groups) return send(200, groups.list()), true;
365
+ /* Rooms (#268, rooms.mjs): a thread shared by several AIs, the person and boxes. */
366
+ if (pathname === '/api/rooms' && rooms) return send(200, rooms.list()), true;
367
+ const roomTalk = /^\/api\/rooms\/([0-9a-f-]{36})\/talk$/.exec(pathname);
368
+ /* A file attached in a room, opened from its thread. */
369
+ const roomFile = /^\/api\/rooms\/([0-9a-f-]{36})\/file$/.exec(pathname);
370
+ if (roomFile && rooms) {
371
+ const file = await download(rooms.filesOf(roomFile[1]), query.get('p') ?? '');
372
+ response.writeHead(200, { ...headers, 'content-type': 'application/octet-stream', 'content-length': file.size,
373
+ 'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(file.name)}` });
374
+ file.stream.pipe(response);
375
+ return true;
376
+ }
377
+ /* WHAT AN AI SHOWED IN A ROOM (06-11): read from its own conversation, with that conversation's rights --
378
+ its work folder, a folder attached to it -- only when it showed or cited it in this room (rooms.shownFile). */
379
+ const roomShown = /^\/api\/rooms\/([0-9a-f-]{36})\/shown$/.exec(pathname);
380
+ if (roomShown && rooms) {
381
+ const { conversation, tab, inner } = rooms.shownFile(roomShown[1], query.get('o') ?? '');
382
+ const folder = (need) => {
383
+ if (need === 'write') throw new Refusal(403, 'Read only, from a room.');
384
+ if (tab === WORK_TAB) {
385
+ if (conversations.list().find((x) => x.name === conversation)?.work !== 'kept' || !resources) throw new Refusal(404, 'This conversation works on the disk of its machine: its files are not kept here.');
386
+ return resources.workFolder(conversation);
387
+ }
388
+ if (!resources?.of(conversation).some((r) => r.name === tab)) throw new Refusal(404, 'No such folder.');
389
+ return resources.folder(tab);
390
+ };
391
+ if (query.get('thumb') === '1') {
392
+ const answer = await changeRoute('GET', '/files/thumb', new URLSearchParams({ p: inner }), request, folder);
393
+ response.writeHead(200, { ...headers, ...IMAGE_HEADERS, 'content-type': answer.picture.type, 'content-length': answer.picture.bytes.length, etag: `"${answer.picture.version}"` });
394
+ response.end(answer.picture.bytes);
395
+ return true;
396
+ }
397
+ const file = await download(folder(), inner);
398
+ response.writeHead(200, { ...headers, 'content-type': 'application/octet-stream', 'content-length': file.size,
399
+ 'content-disposition': `attachment; filename*=UTF-8''${encodeURIComponent(file.name)}`, 'x-shown-by': encodeURIComponent(conversation) });
400
+ file.stream.pipe(response);
401
+ return true;
402
+ }
403
+ /* A mail an AI of a room cited there: opened as in its conversation's chat (Reply goes to that chat, x-mail-of). */
404
+ const roomMail = /^\/api\/rooms\/([0-9a-f-]{36})(\/mail\/open|\/mail\/page)$/.exec(pathname);
405
+ if (roomMail && rooms) {
406
+ const c = rooms.mailFrom(roomMail[1], query.get('ref') ?? '');
407
+ return await mailRoute(roomMail[2], query, response, { tethers, headers: { ...headers, 'x-mail-of': encodeURIComponent(c) }, who: { id: `person:${identity || 'owner'}`, name: identity || 'Owner' }, may: () => true, offline: conversations.list().find((x) => x.name === c)?.offline === true, of: c });
408
+ }
409
+ if (roomTalk && rooms) { const last = Number(query.get('last')); return send(200, rooms.read(roomTalk[1], Number.isInteger(last) && last > 0 ? { last } : undefined)), true; }
262
410
  if (pathname === '/api/mailboxes' && mailboxes) return send(200, mailboxes.list()), true;
263
411
  /* Which providers and kinds an account can be connected for here. */
264
412
  if (pathname === '/api/accounts' && accounts) return send(200, { supported: accounts.supported() }), true;
265
413
  /* Assets > Access: the targets, who was given each at which level, the
266
414
  calls waiting, and the recent journal -- all the page needs to read. */
267
- if (pathname === '/api/tether' && tethers) { const r = await tethers.act('state', { agent: query.get('agent') ?? undefined }, ''); return send(200, { given: tethers.given(), changes: tethers.changes(), ...(r.data ?? {}) }), true; }
415
+ /* Each call waiting carries `view`: the card Parley draws for it (demandes.mjs), the same as in the thread. */
416
+ if (pathname === '/api/tether' && tethers) {
417
+ const r = await tethers.act('state', { agent: query.get('agent') ?? undefined }, '');
418
+ const data = r.data ?? {};
419
+ const approvals = Array.isArray(data.approvals) ? data.approvals.map((q) => { try { return { ...q, view: demandeView(q) }; } catch { return q; } }) : data.approvals;
420
+ /* Each paired browser: connected or not, and the tabs its person granted (browsers.mjs). Never a token. */
421
+ const browsersNow = tethers.browsers ? { browsers: tethers.browsers.all(), browsersWaiting: tethers.browsers.waiting() } : {};
422
+ /* Each MCP server's kept sign-in client, as the page shows it: its id, a secret kept or not -- never the secret. */
423
+ const targets = Array.isArray(data.targets) && tethers.oauth?.shown ? data.targets.map((x) => { if (x.kind !== 'mcp') return x; const client = tethers.oauth.shown(x.id); return client ? { ...x, client } : x; }) : data.targets;
424
+ return send(200, { given: tethers.given(), changes: tethers.changes(), ...data, ...(targets ? { targets } : {}), ...(approvals ? { approvals } : {}), ...browsersNow }), true;
425
+ }
268
426
  /* Every device, each with all it was given. */
269
427
  if (pathname === '/api/devices' && sharing) return send(200, sharing.devices.all()), true;
270
428
  if (pathname === '/api/git-keys' && gitAccess) return send(200, gitAccess.keys()), true;
271
429
  if (pathname === '/api/git-hosts' && gitAccess) return send(200, gitAccess.hosts()), true;
272
430
  if (pathname === '/api/platform' && platform) return send(200, platform), true;
273
431
  if (pathname === '/api/instance' && instance) return send(200, instance.about()), true;
432
+ /* The sign-in companions (signinhelp.mjs, 15-11): the general one, each conversation's own, their browsers. */
433
+ if (pathname === '/api/signin-companion' && conversations.signinHelp) return send(200, conversations.signinHelp.view()), true;
274
434
  if (pathname === '/api/shelf' && shelf) return send(200, shelf.about()), true;
275
435
  /* Settings, Updates (updates.mjs): what runs, what is out, the mode, what happened. */
276
436
  if (pathname === '/api/updates' && updates) return send(200, updates.about()), true;
277
437
  /* Who may sign in (operators.mjs): none in local mode. */
278
438
  const reactOf = /^\/api\/conversations\/([^/]+)\/health-react$/.exec(pathname);
279
439
  if (reactOf && reacting) return send(200, reacting.settings(decodeURIComponent(reactOf[1]))), true;
440
+ if (pathname === '/api/jobs' && conversations.jobs) {
441
+ return send(200, withUpdates(conversations.jobs, conversations.list?.() ?? [], updates?.about().history ?? [])), true;
442
+ }
443
+ /* A job's log (jobs.mjs): read when its line is opened, never with the list, which stays light. */
444
+ if (pathname === '/api/jobs/log' && conversations.jobs) {
445
+ const job = conversations.jobs.log(query.get('id') ?? '');
446
+ if (!job) throw new Refusal(404, 'No such job.');
447
+ return send(200, job), true;
448
+ }
280
449
  if (pathname === '/api/events' && events) {
281
450
  const ask = { kind: query.get('kind') ?? '', conversation: query.get('conversation') ?? '', q: query.get('q') ?? '', before: query.get('before') ?? '', limit: Math.min(1000, Number(query.get('limit')) || 200) };
282
451
  const said = events.list(ask);
@@ -313,6 +482,8 @@ export async function handleApi(request, response, conversations, headers, resou
313
482
  }));
314
483
  return send(200, history.together(query.get('span') ?? '1h', machines, { memoryMb: a?.memory?.totalMb, cores: room?.cpu?.cores, diskMb: a?.disk?.sizeMb })), true;
315
484
  }
485
+ /* What this server asked of the host, by 5-minute window, and its own event loop (vm.mjs HostTally). */
486
+ if (pathname === '/api/server/load' && serverLogs) return send(200, serverLogs.load()), true;
316
487
  if (pathname === '/api/server/logs' && serverLogs) { const r = await serverLogs.start(query.get('source') ?? 'clavarium', query.get('span') ?? '10m'); return send(r.pending ? 202 : 200, r), true; }
317
488
  if (pathname === '/api/machines/disks' && machinesMove) return send(200, await machinesMove.disks()), true;
318
489
  if (pathname === '/api/machines/places' && machinesMove) return send(200, await machinesMove.places()), true;
@@ -325,6 +496,8 @@ export async function handleApi(request, response, conversations, headers, resou
325
496
  if (pathname === '/api/certificate' && certificate) return send(200, await certificate.about({ fresh: query.get('fresh') === '1' })), true;
326
497
  /* This server's disk and memory (capacity.mjs): everything for Settings; only whether it is high for the list. */
327
498
  if (pathname === '/api/server' && capacity) return send(200, await capacity.about()), true;
499
+ /* Settings, Machines: each machine, the VM manager, this server's two choices (machinelist.mjs). */
500
+ if (pathname === '/api/server/machines' && machineList) return send(200, await machineList.list()), true;
328
501
  if (pathname === '/api/server/brief' && capacity) return send(200, { ...(await capacity.brief()), machines: platform?.machines ?? true }), true;
329
502
  if (pathname === '/api/alerts' && alerts) return send(200, alerts.about()), true;
330
503
  if (pathname === '/api/flows' && setup) return send(200, setup.graph()), true;
@@ -358,10 +531,12 @@ export async function handleApi(request, response, conversations, headers, resou
358
531
  const answered = /^\/api\/conversations\/([^/]+)\/answerer\/log$/.exec(pathname);
359
532
  if (answered && answerer) return send(200, answerer.log(decodeURIComponent(answered[1]))), true;
360
533
  /* A repository: where its commits go, and what would go now. */
361
- const repo = /^\/api\/git\/([a-z0-9-]{1,32})(\/outgoing|\/keep)?$/.exec(pathname);
534
+ const repo = /^\/api\/git\/([a-z0-9-]{1,32})(\/outgoing|\/outgoing-all|\/known|\/keep)?$/.exec(pathname);
362
535
  const drawn = /^\/api\/git\/([a-z0-9-]{1,32})\/(graph|commit)$/.exec(pathname);
363
536
  if (drawn && gitReview) return send(200, drawn[2] === 'graph' ? await gitReview.graph(drawn[1]) : await gitReview.commit(drawn[1], query.get('id'), query.get('base'))), true;
364
537
  if (repo && repo[2] === '/keep' && gitKeeper) return send(200, gitKeeper.about(repo[1])), true;
538
+ if (repo && repo[2] === '/known' && gitReview) return send(200, await gitReview.known(repo[1])), true;
539
+ if (repo && repo[2] === '/outgoing-all' && gitReview) return send(200, await gitReview.outgoingAll(repo[1])), true;
365
540
  if (repo && gitReview) return send(200, repo[2] ? await gitReview.outgoing(repo[1], { target: query.get('target') ?? undefined, branch: query.get('branch') ?? undefined }) : gitReview.settings(repo[1])), true;
366
541
  const watched = /^\/api\/conversations\/([^/]+)\/signin$/.exec(pathname);
367
542
  if (watched && signin) {
@@ -371,10 +546,24 @@ export async function handleApi(request, response, conversations, headers, resou
371
546
  const items = settings.configured ? await signin.recent(conversation).catch((e) => ({ failure: e.message })) : [];
372
547
  return send(200, { ...settings, items: Array.isArray(items) ? items : [], failure: items.failure ?? null }), true;
373
548
  }
549
+ /* Its machine: the action running, step by step, and the last report (conversations.mjs, machineState). */
550
+ const machineOf = /^\/api\/conversations\/([^/]+)\/machine$/.exec(pathname);
551
+ if (machineOf) return send(200, conversations.machineState(decodeURIComponent(machineOf[1]))), true;
374
552
  const paired = /^\/api\/conversations\/([^/]+)\/devices$/.exec(pathname);
375
553
  if (paired && sharing) return send(200, sharing.devices.of(decodeURIComponent(paired[1]))), true;
376
554
  const sending = /^\/api\/conversations\/([^/]+)\/git\/([a-z0-9-]{1,32})\/auto$/.exec(pathname);
377
555
  if (sending && gitKeeper) return send(200, gitKeeper.auto(sending[2], decodeURIComponent(sending[1]))), true;
556
+ /* Back from signing in to an external MCP server (mcpoauth.mjs): the owner's browser, sent here by the
557
+ provider. A page, not JSON; its state is the proof it was started from this page. */
558
+ if (pathname === BACK_PATH && tethers?.oauth) {
559
+ let page;
560
+ /* Said in the language of the page that started it; one never started here, in the browser's. */
561
+ const lang = String(request.headers['accept-language'] ?? '').slice(0, 2);
562
+ try { const done = await tethers.oauth.finish({ tethers }, { code: query.get('code'), state: query.get('state'), error: query.get('error') }); page = backPage({ ok: true, title: done.title, lang: done.lang, back: done.back, sameTab: done.sameTab }); }
563
+ catch (error) { page = backPage({ ok: false, message: error instanceof Refusal ? error.message : '', why: error?.why ?? 'failed', lang: error?.lang ?? lang, back: error?.back }); }
564
+ response.writeHead(200, { ...headers, 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'referrer-policy': 'no-referrer' }).end(page);
565
+ return true;
566
+ }
378
567
  return send(404, { error: 'Not found.' }), true;
379
568
  }
380
569
  if (request.method !== 'POST') return send(405, { error: 'Method not allowed.' }), true;
@@ -384,6 +573,12 @@ export async function handleApi(request, response, conversations, headers, resou
384
573
  if (!originOk(request.headers) || request.headers['content-type'] !== 'application/octet-stream') return send(403, { error: 'This request does not come from this site.' }), true;
385
574
  return send(201, await talk.attach(decodeURIComponent(attaching[1]), query.get('name') ?? '', request)), true;
386
575
  }
576
+ /* A file the person attaches in a room (06-11): the same as in a chat, kept in the room. */
577
+ const roomAttaching = /^\/api\/rooms\/([0-9a-f-]{36})\/talk\/file$/.exec(pathname);
578
+ if (roomAttaching && rooms) {
579
+ if (!originOk(request.headers) || request.headers['content-type'] !== 'application/octet-stream') return send(403, { error: 'This request does not come from this site.' }), true;
580
+ return send(201, await rooms.attach(roomAttaching[1], query.get('name') ?? '', request)), true;
581
+ }
387
582
  /* A flow with its files, sent from the page: the body is the .tar.gz. */
388
583
  if (pathname === '/api/setup/bundle' && setup && bundles) {
389
584
  if (!originOk(request.headers) || request.headers['content-type'] !== 'application/octet-stream') return send(403, { error: 'This request does not come from this site.' }), true;
@@ -396,9 +591,53 @@ export async function handleApi(request, response, conversations, headers, resou
396
591
  const body = await readBody(request, pathname === '/api/setup/preview' || pathname === '/api/setup/import' ? SETUP_BODY_MAX : BODY_MAX);
397
592
  /* What was done, once it was done: said in What happened (events.mjs), for those worth saying. */
398
593
  if (events) { const answer = send; send = (status, out) => { if (status < 300) { try { events.fromRequest(pathname, body, identity, out); } catch { /* never in the way */ } } answer(status, out); }; }
399
- if (pathname === '/api/conversations') { await conversations.admit?.(body); return send(201, conversations.create(body)), true; }
594
+ if (rooms && pathname.startsWith('/api/rooms')) {
595
+ if (pathname === '/api/rooms') return send(201, rooms.create(body ?? {})), true;
596
+ const r = /^\/api\/rooms\/([0-9a-f-]{36})(\/remove|\/talk)?$/.exec(pathname);
597
+ if (r && !r[2]) return send(200, rooms.change(r[1], body ?? {})), true;
598
+ if (r && r[2] === '/remove') { rooms.remove(r[1]); return send(200, { removed: r[1] }), true; }
599
+ if (r && r[2] === '/talk') return send(201, await rooms.say(r[1], body?.text, { to: body?.to, files: body?.files })), true;
600
+ }
601
+ if (pathname === '/api/conversations') {
602
+ await conversations.admit?.(body);
603
+ const made = conversations.create(body);
604
+ /* Its chat on from the start (02-11), unless asked otherwise ("More": Chat off); a work folder on the
605
+ machine's disk has no place for it. */
606
+ /* Made with OpenCode and its settings (03-11): its key given to it, and its model written where OpenCode
607
+ reads it (its work folder's opencode.json), once its machine is built. */
608
+ const oc = made.tool === 'opencode' && body?.opencode ? openCodeConfig(body.opencode) : null;
609
+ if (oc) {
610
+ const name = made.name; const until = Date.now() + 30 * 60_000;
611
+ const setUp = async () => {
612
+ const c = conversations.list().find((x) => x.name === name);
613
+ if (!c || Date.now() > until) return;
614
+ if (c.phase !== 'ready') { setTimeout(() => { void setUp(); }, 2000).unref?.(); return; }
615
+ try { secrets?.attach(name, String(body.opencode.secret), true); await secrets?.deliver(name).catch(() => {}); } catch { /* given from its settings */ }
616
+ try { const dir = resources.workFolder(name); writeFileSync(`${dir}/opencode.json`, `${JSON.stringify(oc, null, 2)}\n`, { flag: 'wx', mode: 0o644 }); } catch { /* one there already is kept */ }
617
+ };
618
+ void setUp();
619
+ }
620
+ if (body?.chat !== false && talk) {
621
+ /* Its work folder exists once it is built: the chat is put in then (a few minutes at most). */
622
+ const name = made.name; const until = Date.now() + 30 * 60_000;
623
+ const tryOn = async () => {
624
+ const c = conversations.list().find((x) => x.name === name);
625
+ if (!c || Date.now() > until) return;
626
+ if (c.phase === 'ready') { try { await talk.set(name, true); void guide?.changed(name).catch(() => {}); } catch { /* left off: its settings turn it on */ } return; }
627
+ setTimeout(() => { void tryOn(); }, 2000).unref?.();
628
+ };
629
+ void tryOn();
630
+ }
631
+ return send(201, made), true;
632
+ }
400
633
  /* The lists: every answer is 200, a refusal said in it ({ ok: false, text }), as the keeper says it to a tool. */
401
634
  if (pathname === '/api/binder' && binders) return send(200, binders.act(body.op, body.args, identity)), true;
635
+ /* Quick actions on a card: suggested from its content (suggest.mjs), done by the page. */
636
+ if (pathname === '/api/binder/suggest' && binders) {
637
+ const got = binders.act('get', { id: String(body?.id ?? '') }, identity);
638
+ if (!got?.ok || !got.data?.record) return send(404, { error: 'No such card.' }), true;
639
+ return send(200, { actions: await suggest(got.data.record, got.data.list, { chat: voice?.chat?.() ?? null }) }), true;
640
+ }
402
641
  /* Who gets what, and a whole setup in one file: see setup.mjs. */
403
642
  if (pathname.startsWith('/api/setup/') || pathname === '/api/flows/name') {
404
643
  if (!setup) return send(404, { error: 'Not found.' }), true;
@@ -431,6 +670,16 @@ export async function handleApi(request, response, conversations, headers, resou
431
670
  if (pathname === '/api/updates/settings' && updates) return send(200, await updates.settings({ mode: body.mode, channel: body.channel, window: body.window })), true;
432
671
  if (pathname === '/api/updates/apply' && updates) return send(202, await updates.apply(body.version)), true;
433
672
  if (pathname === '/api/updates/back' && updates) return send(202, await updates.back(body.version)), true;
673
+ /* Memory short: the machine that takes the most forced off (default), put to sleep, or only said. */
674
+ if (pathname === '/api/server/pressure' && capacity) { capacity.setPressureWay(body.way); return send(200, await capacity.about()), true; }
675
+ /* Settings, Machines: Force stop from the list; the VM manager restarted (confirmed: every machine is resumed); what is done when it hangs. */
676
+ const forcedOf = /^\/api\/server\/machines\/([^/]+)\/force$/.exec(pathname);
677
+ if (forcedOf && machineList) return send(202, await machineList.force(decodeURIComponent(forcedOf[1]))), true;
678
+ if (pathname === '/api/server/vm-manager/restart' && machineList) {
679
+ if (body?.confirm !== true) throw new Refusal(400, 'Restarting the machine manager resumes every machine: confirm it.');
680
+ return send(200, await machineList.revive()), true;
681
+ }
682
+ if (pathname === '/api/server/vm-manager' && machineList) return send(200, await machineList.setManagerMode(body?.mode)), true;
434
683
  if (pathname === '/api/server/reserve' && capacity) { capacity.setReserve({ diskMb: body.diskMb, diskPercent: body.diskPercent, memoryMb: body.memoryMb, memoryPercent: body.memoryPercent }); return send(200, await capacity.about()), true; }
435
684
  if (pathname === '/api/git-hosts/forget' && gitAccess) return send(200, gitAccess.forgetHost(body.host)), true;
436
685
  const unkeyed = /^\/api\/git-keys\/([a-z0-9-]{1,32})\/remove$/.exec(pathname);
@@ -466,8 +715,41 @@ export async function handleApi(request, response, conversations, headers, resou
466
715
  /* Assets > Access: the owner sets a conversation's level and rules on a
467
716
  target, decides a call that waited, or removes a target. Each is an op the
468
717
  keeper runs as the owner (person), never as an agent. */
718
+ /* External MCP servers (mcpx.mjs): added with their key (kept host-only in the vault, Tether given its name),
719
+ imported from a pasted mcpServers block, listed again, a conversation's rights on their tools, new tools seen. */
720
+ /* Signing in to one with OAuth: the link the owner opens ({ url }), or { need: 'client' } for a client id to paste. */
721
+ if (pathname === '/api/tether/ssh-add' && tethers && gitAccess) return send(201, await addMachine({ tethers, keys: gitAccess, ...(tethers.sshProbe ? { probe: tethers.sshProbe } : {}) }, body ?? {})), true;
722
+ if (pathname === '/api/tether/mcp-oauth' && tethers?.oauth) return send(200, await tethers.oauth.start({ tethers }, body ?? {}, sharing?.origin?.(request.headers) ?? `http://${request.headers.host}`)), true;
723
+ const mcpOp = /^\/api\/tether\/mcp-(add|import|refresh|rights|seen|new-tools)$/.exec(pathname);
724
+ if (mcpOp && tethers) {
725
+ const ctx = { tethers, secrets };
726
+ const done = await { add: mcpAdd, import: mcpImport, refresh: mcpRefresh, rights: mcpRights, seen: mcpSeen, 'new-tools': mcpNewTools }[mcpOp[1]](ctx, body ?? {});
727
+ return send(mcpOp[1] === 'add' || mcpOp[1] === 'import' ? 201 : 200, done), true;
728
+ }
729
+ /* A browser paired through the Tether extension (browsers.mjs): the code its popup shows, and its name; or paired
730
+ again ({ code, target }). The token it is handed is never in the answer. */
731
+ /* The sites a conversation acts on without asking, at frame: { target, agent, sites: [host | *.host] }. */
732
+ if (pathname === '/api/tether/browser-sites' && tethers?.browsers) return send(200, await tethers.browsers.setSites(tethers, body ?? {})), true;
733
+ /* A configuration to paste in the extension ({ name?, target? } -> { offer, key, expires }: the key said this once,
734
+ kept only as its hash), and where it is ({ offer } -> waiting | claimed (its target) | expired). */
735
+ if (pathname === '/api/tether/browser-offer' && tethers?.browsers) return send(201, tethers.browsers.offer({ name: body?.name, target: body?.target })), true;
736
+ if (pathname === '/api/tether/browser-offer-state' && tethers?.browsers) return send(200, tethers.browsers.offerState(body?.offer)), true;
737
+ if (pathname === '/api/tether/browser-pair' && tethers?.browsers) return send(201, tethers.browsers.pair({ code: body?.code, name: body?.name, target: body?.target })), true;
738
+ /* A server taken away: the key kept for it goes too. */
739
+ const mcpGone = pathname === '/api/tether/remove-target' && tethers ? tethers.store().target(String(body?.target ?? '')) : null;
469
740
  const tetherOp = /^\/api\/tether\/(level|allow|unallow|decide|remove-target|stop|resume|job-done|job-file)$/.exec(pathname);
741
+ if (tetherOp && tethers && mcpGone?.kind === 'mcp') { const r = await tethers.act('remove-target', body, ''); if (!r.ok) throw new Refusal(400, r.text); forgetKey(secrets, mcpGone); return send(200, r.data ?? { ok: true }), true; }
742
+ /* A browser taken away: its tokens and its socket go too. */
743
+ if (tetherOp && tethers && mcpGone?.kind === 'browser') { const r = await tethers.act('remove-target', body, ''); if (!r.ok) throw new Refusal(400, r.text); tethers.browsers?.forget(mcpGone.id); return send(200, r.data ?? { ok: true }), true; }
470
744
  if (tetherOp && tethers) { const r = await tethers.act(tetherOp[1], body, ''); if (!r.ok) throw new Refusal(400, r.text); return send(200, r.data ?? { ok: true }), true; }
745
+ /* A calendar's agenda, read now through Tether as the owner's own read (agenda.mjs, 16-11): seen in its asset
746
+ panel, so the calendar need not stay open elsewhere. A POST, for this site's own pages only (checked above). */
747
+ if (pathname === '/api/tether/agenda' && tethers) return send(200, await readAgenda(tethers, body ?? {}, { who: { id: `person:${identity || 'owner'}`, name: identity || 'Owner' } })), true;
748
+ /* A mailbox's latest messages and one as text, an address book's contacts and one, read the same way (16-11:
749
+ mailview.mjs, contactview.mjs): never marked read, nothing changed. */
750
+ const peek = { '/api/tether/mail-list': readMailList, '/api/tether/mail-read': readMail, '/api/tether/contacts': readContacts, '/api/tether/contact': readContact }[pathname];
751
+ if (pathname === '/api/tether/console-journal' && tethers) return send(200, await consoleJournal(tethers, body ?? {})), true;
752
+ if (peek && tethers) return send(200, await peek(tethers, body ?? {}, { who: { id: `person:${identity || 'owner'}`, name: identity || 'Owner' } })), true;
471
753
  /* A mailbox's signature (Markdown), added under what the agent sends from it. */
472
754
  if (pathname === '/api/tether/signature' && tethers) {
473
755
  const t = tethers.store().target(String(body.target ?? ''));
@@ -491,7 +773,9 @@ export async function handleApi(request, response, conversations, headers, resou
491
773
  const reactSet = /^\/api\/conversations\/([^/]+)\/health-react$/.exec(pathname);
492
774
  if (reactSet && reacting) { const n = decodeURIComponent(reactSet[1]); if (!conversations.list().some((c) => c.name === n)) throw new Refusal(404, 'No such conversation.'); return send(200, reacting.set(n, body)), true; }
493
775
  if (pathname === '/api/machines/move' && machinesMove) return send(202, await machinesMove.move(String(body.to ?? ''))), true;
776
+ if (pathname === '/api/server/profile' && serverLogs) return send(200, await serverLogs.profile(body?.seconds ?? 10)), true;
494
777
  if (pathname === '/api/server/restart' && serverLogs) return send(202, await serverLogs.restart()), true;
778
+ if (pathname === '/api/server/reboot' && serverLogs) return send(202, await serverLogs.reboot()), true;
495
779
  if (pathname === '/api/machines/grow' && machinesMove) return send(200, await machinesMove.grow(String(body.mount ?? ''))), true;
496
780
  if (pathname === '/api/machines/mount' && machinesMove) return send(200, await machinesMove.mount(String(body.path ?? ''))), true;
497
781
  if (pathname === '/api/machines/prepare' && machinesMove) return send(200, await machinesMove.prepare(String(body.path ?? ''), body.typed)), true;
@@ -516,7 +800,13 @@ export async function handleApi(request, response, conversations, headers, resou
516
800
  if (renaming && secrets) { const done = secrets.rename(renaming[1], String(body.name ?? '').trim()); await redeliver(String(body.name ?? '').trim()); return send(200, done), true; }
517
801
  /* A new value (never sent back) and/or a new expiry, in place. */
518
802
  const replacing = /^\/api\/secrets\/([A-Z][A-Z0-9_]{0,39})\/replace$/.exec(pathname);
519
- if (replacing && secrets) { const done = secrets.replace(replacing[1], { value: body.value, expires: body.expires }); await redeliver(replacing[1]); return send(200, done), true; }
803
+ if (replacing && secrets) {
804
+ const done = secrets.replace(replacing[1], { value: body.value, expires: body.expires });
805
+ await redeliver(replacing[1]);
806
+ /* Its new value is in each machine's /run/secrets now; their tools are told again what that means (guide.mjs). */
807
+ for (const c of conversations.list()) if (secrets.of(c.name).includes(replacing[1])) void guide?.changed(c.name).catch(() => {});
808
+ return send(200, done), true;
809
+ }
520
810
  const dropped = /^\/api\/secrets\/([A-Z][A-Z0-9_]{0,39})\/remove$/.exec(pathname);
521
811
  if (dropped && secrets) { secrets.remove(dropped[1]); return send(200, { ok: true }), true; }
522
812
  if (pathname === '/api/alerts' && alerts) return send(201, alerts.add(body.subscription, body.label)), true;
@@ -533,15 +823,70 @@ export async function handleApi(request, response, conversations, headers, resou
533
823
  }
534
824
  /* A setting its tool is told about changed: its guide follows (never waking a machine). */
535
825
  const retell = (conversation) => { void guide?.changed(conversation).catch(() => {}); };
536
- const talking = /^\/api\/conversations\/([^/]+)\/talk(\/invite|\/remind|\/react)?$/.exec(pathname);
826
+ /* THE ONE GIVE TO A CONVERSATION, as its own settings do it: a folder, a repository, a mailbox attached at
827
+ an access; a secret handed or taken back. A room's « give to all its AIs » calls the same, once for each. */
828
+ const attachResource = async (conversation, name, access, shared) => {
829
+ if (!conversations.list().some((c) => c.name === conversation && c.phase === 'ready')) throw new Refusal(404, 'No such conversation, or it is not ready.');
830
+ /* A second writer next to one that sends by itself: confirmed first. */
831
+ if (access === 'write') gitKeeper?.beforeWriter(name, conversation, shared === true);
832
+ /* Its automatic sending goes with the write attachment -- forgotten
833
+ BEFORE the change, so that a change that fails half-way (unmounted,
834
+ not mounted again) never leaves settings to come back later. */
835
+ if (access !== 'write') gitKeeper?.forgetAttachment(name, conversation);
836
+ await resources.attach(conversation, name, access);
837
+ retell(conversation);
838
+ /* Newly attached: its links looked at (and its mounts), not waited for. */
839
+ if (access !== 'none') void health?.check?.(conversation, { asked: true })?.catch?.(() => {});
840
+ };
841
+ const handSecret = async (conversation, name, attached) => {
842
+ if (!conversations.list().some((c) => c.name === conversation)) throw new Refusal(404, 'No such conversation.');
843
+ secrets.attach(conversation, name, attached);
844
+ /* A machine that runs gets it (or loses it) now, in /run/secrets -- not only at the next
845
+ opening of a terminal; its tool's variables still wait for the tool's next start. */
846
+ const c = conversations.list().find((x) => x.name === conversation);
847
+ if (c?.phase === 'ready' && !c.asleep) await secrets.deliver(conversation).catch(() => {});
848
+ retell(conversation);
849
+ };
850
+ /* GIVE ONE ASSET TO EVERY AI OF A ROOM (06-11): there is no room asset -- each AI of the room gets the same
851
+ ordinary right of its own conversation, taken back one by one. A box or the person gets nothing; a secret
852
+ goes to conversations only. Checked once before any is given (the asset, its rights as for one
853
+ conversation); then each gets it whole or not at all, and the answer says which: {asset, rights, given:
854
+ [{conversation, ok, kept?, error?}]}. A right already wider is kept, never lowered. */
855
+ const roomGive = /^\/api\/rooms\/([0-9a-f-]{36})\/give$/.exec(pathname);
856
+ if (roomGive && rooms) {
857
+ const asset = String(body.asset ?? ''); const rights = readRights(asset, body.rights);
858
+ const type = typeOf(asset); const name = nameOf(asset);
859
+ if (type === 'secret') { if (!secrets?.list({ held: true }).some((x) => x.name === name)) throw new Refusal(404, 'No such secret.'); }
860
+ else if (['folder', 'git', 'mailbox'].includes(type)) { if (!resources?.list().some((r) => resources.assetOf(r) === asset)) throw new Refusal(404, 'No such asset.'); }
861
+ else throw new Refusal(400, 'A folder, a repository, a mailbox or a secret is given to the AIs of a room.');
862
+ const ais = rooms.ais(roomGive[1]);
863
+ if (!ais.length) throw new Refusal(409, 'This room has no AI.');
864
+ const given = [];
865
+ for (const conversation of ais) {
866
+ try {
867
+ if (type === 'secret') await handSecret(conversation, name, true);
868
+ else {
869
+ const access = rights.includes('w') ? 'write' : 'read';
870
+ const had = resources.of(conversation).find((r) => r.name === name)?.access;
871
+ if (had === 'write' && access === 'read') { given.push({ conversation, ok: true, kept: 'write' }); continue; }
872
+ await attachResource(conversation, name, access, body.shared === true);
873
+ }
874
+ given.push({ conversation, ok: true });
875
+ } catch (error) { given.push({ conversation, ok: false, error: error.message, ...(error.kind ? { kind: error.kind } : {}) }); }
876
+ }
877
+ return send(200, { asset, rights, given }), true;
878
+ }
879
+ const talking = /^\/api\/conversations\/([^/]+)\/talk(\/invite|\/remind|\/react|\/pin|\/split)?$/.exec(pathname);
537
880
  if (talking && talk) {
538
881
  const conversation = decodeURIComponent(talking[1]);
539
882
  if (talking[2] === '/invite') return send(200, await talk.invite(conversation, typeof body.lang === 'string' ? body.lang : 'en')), true;
540
- if (talking[2] === '/remind') return send(200, await talk.remind(conversation)), true;
883
+ if (talking[2] === '/remind') return send(200, await talk.remind(conversation, { urgent: body?.urgent === true })), true;
541
884
  if (talking[2] === '/react') return send(200, await talk.react(conversation, body.to, body.reaction ?? null)), true;
885
+ if (talking[2] === '/pin') return send(200, await talk.pin(conversation, body.to, body.on !== false)), true;
886
+ if (talking[2] === '/split') return send(200, talk.setSplit(conversation, { messages: body.messages, days: body.days, off: body.off })), true;
542
887
  if (typeof body.on === 'boolean') { const now = await talk.set(conversation, body.on); retell(conversation); return send(200, now), true; }
543
888
  /* What the chat may add to an answer: the choices ticked, the answers of a group, the zone of a picture it is about (Parley checks each). */
544
- return send(201, await talk.say(conversation, body.text, body.answers, body.files, body.via, { picked: body.picked, replies: body.replies, about: body.about })), true;
889
+ return send(201, await talk.say(conversation, body.text, body.answers, body.files, body.via, { picked: body.picked, replies: body.replies, about: body.about, quick: body.quick === true })), true;
545
890
  }
546
891
  const docketed = /^\/api\/conversations\/([^/]+)\/docket(\/cancel)?$/.exec(pathname);
547
892
  if (docketed && wakeups) {
@@ -578,13 +923,7 @@ export async function handleApi(request, response, conversations, headers, resou
578
923
  const handed = /^\/api\/conversations\/([^/]+)\/secrets$/.exec(pathname);
579
924
  if (handed && secrets) {
580
925
  const conversation = decodeURIComponent(handed[1]);
581
- if (!conversations.list().some((c) => c.name === conversation)) throw new Refusal(404, 'No such conversation.');
582
- secrets.attach(conversation, String(body.secret ?? ''), body.attached === true);
583
- /* A machine that runs gets it (or loses it) now, in /run/secrets -- not only at the next
584
- opening of a terminal; its tool's variables still wait for the tool's next start. */
585
- const c = conversations.list().find((x) => x.name === conversation);
586
- if (c?.phase === 'ready' && !c.asleep) await secrets.deliver(conversation).catch(() => {});
587
- retell(conversation);
926
+ await handSecret(conversation, String(body.secret ?? ''), body.attached === true);
588
927
  return send(200, { ok: true, secrets: secrets.of(conversation) }), true;
589
928
  }
590
929
  /* Forget an ephemeral secret now (its stars in the chat have a button): gone from the vault and the machine. */
@@ -647,16 +986,7 @@ export async function handleApi(request, response, conversations, headers, resou
647
986
  const attach = /^\/api\/conversations\/([^/]+)\/resources$/.exec(pathname);
648
987
  if (attach && resources) {
649
988
  const conversation = decodeURIComponent(attach[1]);
650
- if (!conversations.list().some((c) => c.name === conversation && c.phase === 'ready')) throw new Refusal(404, 'No such conversation, or it is not ready.');
651
- const name = String(body.resource ?? ''); const access = String(body.access ?? '');
652
- /* A second writer next to one that sends by itself: confirmed first. */
653
- if (access === 'write') gitKeeper?.beforeWriter(name, conversation, body.shared === true);
654
- /* Its automatic sending goes with the write attachment -- forgotten
655
- BEFORE the change, so that a change that fails half-way (unmounted,
656
- not mounted again) never leaves settings to come back later. */
657
- if (access !== 'write') gitKeeper?.forgetAttachment(name, conversation);
658
- await resources.attach(conversation, name, access);
659
- retell(conversation);
989
+ await attachResource(conversation, String(body.resource ?? ''), String(body.access ?? ''), body.shared === true);
660
990
  return send(200, { ok: true, resources: resources.of(conversation) }), true;
661
991
  }
662
992
  const moved = /^\/api\/conversations\/([^/]+)\/work$/.exec(pathname);
@@ -677,6 +1007,13 @@ export async function handleApi(request, response, conversations, headers, resou
677
1007
  if (!conversations.list().some((c) => c.name === conversation)) throw new Refusal(404, 'No such conversation.');
678
1008
  return send(200, health.markSeen(conversation)), true;
679
1009
  }
1010
+ /* "Check shared folders": each mounted and readable (put back when loose), each link the share cannot serve (health.mjs). */
1011
+ const foldersOf = /^\/api\/conversations\/([^/]+)\/folders\/check$/.exec(pathname);
1012
+ if (foldersOf && health) {
1013
+ const conversation = decodeURIComponent(foldersOf[1]);
1014
+ if (!conversations.list().some((c) => c.name === conversation)) throw new Refusal(404, 'No such conversation.');
1015
+ return send(200, await health.checkFolders(conversation)), true;
1016
+ }
680
1017
  const machine = /^\/api\/conversations\/([^/]+)\/(restart|machine|health)$/.exec(pathname);
681
1018
  if (machine) {
682
1019
  const conversation = decodeURIComponent(machine[1]);
@@ -685,12 +1022,25 @@ export async function handleApi(request, response, conversations, headers, resou
685
1022
  await health.check(conversation, { asked: true }); return send(200, health.of(conversation)), true;
686
1023
  }
687
1024
  if (machine[2] === 'restart') return send(202, await conversations.restart(conversation)), true;
1025
+ /* One action on its machine, or the owner's choice for its way down (conversations.mjs, machineAction). */
1026
+ if (typeof body?.action === 'string') return send(202, await conversations.machineAction(conversation, body.action)), true;
1027
+ if (typeof body?.escalate === 'boolean') return send(200, conversations.setStopEscalate(conversation, body.escalate)), true;
1028
+ /* Its watchdog (watchdog.mjs): on or off, and how long it waits. */
1029
+ if (body?.watchdog && typeof body.watchdog === 'object') return send(200, conversations.setWatchdog(conversation, { on: typeof body.watchdog.on === 'boolean' ? body.watchdog.on : undefined, delayMin: body.watchdog.delayMin })), true;
1030
+ /* Its shared machine's own memory (#221): the whole machine restarted, every conversation in it. */
1031
+ if (body?.machineMb !== undefined) return send(200, await conversations.resizeShared(conversation, { machineMb: body.machineMb })), true;
688
1032
  const resized = await conversations.resize(conversation, { memoryMb: body.memoryMb, diskGb: body.diskGb, cpus: body.cpus });
689
1033
  /* Asleep, nothing was started: the choice is only kept, for its wake. */
690
1034
  return send(resized.phase === 'restarting' ? 202 : 200, resized), true;
691
1035
  }
692
1036
  const later = /^\/api\/conversations\/([^/]+)\/machine\/cancel$/.exec(pathname);
693
1037
  if (later) return send(200, conversations.cancelResize(decodeURIComponent(later[1]))), true;
1038
+ /* DELEGATED SIGN-IN (signinhelp.mjs, 15-11): the companion of all, of one conversation, and the link shown to the person instead. */
1039
+ if (pathname === '/api/signin-companion' && conversations.signinHelp) return send(200, body.clicks !== undefined ? conversations.signinHelp.setClicks(body.clicks) : conversations.signinHelp.setGeneral(body.companion)), true;
1040
+ const companionOf = /^\/api\/conversations\/([^/]+)\/signin-companion$/.exec(pathname);
1041
+ if (companionOf && conversations.signinHelp) return send(200, conversations.signinHelp.setFor(decodeURIComponent(companionOf[1]), body.companion ?? null)), true;
1042
+ const linkOf = /^\/api\/conversations\/([^/]+)\/signin-link$/.exec(pathname);
1043
+ if (linkOf && conversations.signinHelp) return send(200, conversations.signinHelp.showLink(decodeURIComponent(linkOf[1]))), true;
694
1044
  const asking = /^\/api\/conversations\/([^/]+)\/ask-first$/.exec(pathname);
695
1045
  if (asking) return send(200, conversations.setAskFirst(decodeURIComponent(asking[1]), body.on)), true;
696
1046
  const naming = /^\/api\/conversations\/([^/]+)\/chat-name$/.exec(pathname);
@@ -720,6 +1070,20 @@ export async function handleApi(request, response, conversations, headers, resou
720
1070
  if (!conversations.list().some((c) => c.name === conversation)) throw new Refusal(404, 'No such conversation.');
721
1071
  return send(200, await repair(conversation)), true;
722
1072
  }
1073
+ /* Moved into a shared machine (#221): one there already, or a new one of the size given. */
1074
+ const moving = /^\/api\/conversations\/([^/]+)\/into-machine$/.exec(pathname);
1075
+ if (moving) {
1076
+ if (body?.machine === undefined) return send(202, await conversations.moveToOwn(decodeURIComponent(moving[1]))), true;
1077
+ const machineMb = body?.machineMb === undefined ? undefined : Number(body.machineMb);
1078
+ return send(202, await conversations.moveToShared(decodeURIComponent(moving[1]), { machine: body?.machine, machineMb })), true;
1079
+ }
1080
+ /* A copy of it (#221): a new conversation with its work, its tool's memory and its accesses; it untouched. */
1081
+ const copying = /^\/api\/conversations\/([^/]+)\/copy$/.exec(pathname);
1082
+ if (copying) {
1083
+ const machineMb = body?.machineMb === undefined ? undefined : Number(body.machineMb);
1084
+ const machine = typeof body?.machine === 'string' && body.machine ? body.machine : undefined;
1085
+ return send(202, await conversations.copy(decodeURIComponent(copying[1]), { title: body?.title, machine, machineMb, reminders: body?.reminders === true })), true;
1086
+ }
723
1087
  const again = /^\/api\/conversations\/([^/]+)\/rebuild$/.exec(pathname);
724
1088
  if (again) {
725
1089
  const reset = body?.reset === true;