clavarium 0.2.204-beta.1 → 0.2.206-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.
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.204-beta.1",
3
+ "version": "0.2.206-beta.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "clavarium",
9
- "version": "0.2.204-beta.1",
9
+ "version": "0.2.206-beta.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "@xterm/addon-fit": "^0.11.0",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clavarium",
3
- "version": "0.2.204-beta.1",
3
+ "version": "0.2.206-beta.1",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "A conversation is a VM with a terminal in it. Everything else is a folder.",
package/server/api.mjs CHANGED
@@ -127,6 +127,7 @@
127
127
  * GET /api/meshcentral: the remote screen (MeshCentral); POST /api/meshcentral/enable (turned on, in the background) /disable
128
128
  * GET /api/events?kind=&conversation=&q=&before=&limit= what happened, newest first
129
129
  * GET /api/jobs what it is doing: { running, done } (jobs.mjs), its updates of the day among the done
130
+ * GET /api/jobs/log?id= that job, under way or done today, with its log [{at, text}] (404: unknown)
130
131
  * GET /api/history?of=server|<name>&span=1h|24h|7d the curves of memory, CPU and disk (and the reserve, for the server)
131
132
  * GET /api/history/all?span=1h|24h|7d Settings, Usage: the server and every machine (asleep too) on one time axis,
132
133
  * in GB and cores: {t, capacity, server, itself, machines: [{name, alloc, asleep, ...}]}
@@ -176,6 +177,7 @@ import { writeFileSync } from 'node:fs';
176
177
  import { suggest } from './suggest.mjs';
177
178
  import { sameOrigin } from './bridge.mjs';
178
179
  import { Refusal, DISK_GB } from './conversations.mjs';
180
+ import { withUpdates } from './jobs.mjs';
179
181
  import { readRights, typeOf, nameOf } from './grants.mjs';
180
182
  import { VmUnknown } from './vm.mjs';
181
183
  import { list, download, importFile, page, PAGE_HEADERS, changeRoute, IMAGE_HEADERS, mailFile, mailPage } from './files.mjs';
@@ -185,6 +187,7 @@ import { transcribe, AUDIO_MAX } from './voice.mjs';
185
187
  import { FILE_MAX } from './setup.mjs';
186
188
  import { demandeView } from './demandes.mjs';
187
189
  import { mcpAdd, mcpImport, mcpRefresh, mcpRights, mcpSeen, forgetKey } from './mcpx.mjs';
190
+ import { BACK_PATH, backPage } from './mcpoauth.mjs';
188
191
 
189
192
  const BODY_MAX = 16 * 1024;
190
193
  /* A setup file travels inside the JSON of a request: room for it, escaped. */
@@ -408,12 +411,13 @@ export async function handleApi(request, response, conversations, headers, resou
408
411
  const reactOf = /^\/api\/conversations\/([^/]+)\/health-react$/.exec(pathname);
409
412
  if (reactOf && reacting) return send(200, reacting.settings(decodeURIComponent(reactOf[1]))), true;
410
413
  if (pathname === '/api/jobs' && conversations.jobs) {
411
- const said = conversations.jobs.list(conversations.list?.() ?? []);
412
- const day = Date.now() - 24 * 3600_000;
413
- const updated = (updates?.about().history ?? []).filter((h) => h.at && Date.parse(h.at) >= day)
414
- .map((h) => ({ what: `Clavarium ${h.action === 'rollback' ? 'back to' : 'updated to'} ${h.to ?? '?'}`, endedAt: h.at, result: h.result === 'done' ? 'done' : 'failed', ...(h.result === 'done' ? {} : { why: h.why ?? h.result ?? '' }) }));
415
- const done = [...said.done, ...updated].sort((a, b) => String(b.endedAt).localeCompare(String(a.endedAt)));
416
- return send(200, { running: said.running, done }), true;
414
+ return send(200, withUpdates(conversations.jobs, conversations.list?.() ?? [], updates?.about().history ?? [])), true;
415
+ }
416
+ /* A job's log (jobs.mjs): read when its line is opened, never with the list, which stays light. */
417
+ if (pathname === '/api/jobs/log' && conversations.jobs) {
418
+ const job = conversations.jobs.log(query.get('id') ?? '');
419
+ if (!job) throw new Refusal(404, 'No such job.');
420
+ return send(200, job), true;
417
421
  }
418
422
  if (pathname === '/api/events' && events) {
419
423
  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) };
@@ -520,6 +524,15 @@ export async function handleApi(request, response, conversations, headers, resou
520
524
  if (paired && sharing) return send(200, sharing.devices.of(decodeURIComponent(paired[1]))), true;
521
525
  const sending = /^\/api\/conversations\/([^/]+)\/git\/([a-z0-9-]{1,32})\/auto$/.exec(pathname);
522
526
  if (sending && gitKeeper) return send(200, gitKeeper.auto(sending[2], decodeURIComponent(sending[1]))), true;
527
+ /* Back from signing in to an external MCP server (mcpoauth.mjs): the owner's browser, sent here by the
528
+ provider. A page, not JSON; its state is the proof it was started from this page. */
529
+ if (pathname === BACK_PATH && tethers?.oauth) {
530
+ let page;
531
+ 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 }); }
532
+ catch (error) { page = backPage({ ok: false, message: error instanceof Refusal ? error.message : 'The sign-in failed.' }); }
533
+ response.writeHead(200, { ...headers, 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', 'referrer-policy': 'no-referrer' }).end(page);
534
+ return true;
535
+ }
523
536
  return send(404, { error: 'Not found.' }), true;
524
537
  }
525
538
  if (request.method !== 'POST') return send(405, { error: 'Method not allowed.' }), true;
@@ -673,6 +686,8 @@ export async function handleApi(request, response, conversations, headers, resou
673
686
  keeper runs as the owner (person), never as an agent. */
674
687
  /* External MCP servers (mcpx.mjs): added with their key (kept host-only in the vault, Tether given its name),
675
688
  imported from a pasted mcpServers block, listed again, a conversation's rights on their tools, new tools seen. */
689
+ /* Signing in to one with OAuth: the link the owner opens ({ url }), or { need: 'client' } for a client id to paste. */
690
+ 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;
676
691
  const mcpOp = /^\/api\/tether\/mcp-(add|import|refresh|rights|seen)$/.exec(pathname);
677
692
  if (mcpOp && tethers) {
678
693
  const ctx = { tethers, secrets };
@@ -9,6 +9,10 @@
9
9
  * status read the state: the server's memory, disk and CPU, the
10
10
  * conversations (their free name and state, never what they
11
11
  * say), the versions server:status r
12
+ * jobs read what Clavarium does -- conversations built, copied,
13
+ * moved, restarted, its own updates of the day -- and each
14
+ * job's log, as Settings shows them (jobs.mjs; secrets
15
+ * masked) server:jobs r
12
16
  *
13
17
  * a conversation, given ONE BY ONE (never "all, and those to come"):
14
18
  * read read its chat conversation:<name> r
@@ -94,6 +98,8 @@
94
98
  *
95
99
  * Authorization: Bearer clv_... on each of these:
96
100
  * GET /api/ext/v1/status the state, as JSON
101
+ * GET /api/ext/v1/jobs (jobs) what it does: {running, done}, newest first, without their logs
102
+ * GET /api/ext/v1/jobs/<id> (jobs) that job, under way or done today, with its log [{at, text}] (404: unknown)
97
103
  * GET /api/ext/v1/conversations those it may read: {conversations: [{id, name, level, chat}]}
98
104
  * GET /api/ext/v1/conversations/<name>/messages ?last=1..200 (50) | ?since=<cursor>: {chat, messages, cursor}
99
105
  * POST /api/ext/v1/conversations/<name>/messages {text}: posted in its chat, signed with the key's name
@@ -117,7 +123,7 @@
117
123
  * POST /api/ext/v1/binders/<list>/records/<id>/move (write) {state}: never past a gate a person did not tick
118
124
  * POST /api/ext/v1/binders/<list>/records/<id>/notes (write) {text}
119
125
  * POST /api/ext/v1/binders/<list>/records/<id>/archive|restore (write)
120
- * POST /api/ext/mcp the same as MCP tools (clavarium_status, clavarium_conversations,
126
+ * POST /api/ext/mcp the same as MCP tools (clavarium_status, clavarium_jobs, clavarium_job_log, clavarium_conversations,
121
127
  * clavarium_read, clavarium_say, clavarium_rooms, clavarium_room_read,
122
128
  * clavarium_room_say, clavarium_boxes, clavarium_box_say, clavarium_conversation_wake,
123
129
  * clavarium_conversation_sleep, clavarium_conversation_stop, clavarium_room_create,
@@ -125,6 +131,8 @@
125
131
  * clavarium_reminder_cancel, clavarium_binders, clavarium_binder_records,
126
132
  * clavarium_binder_record, clavarium_binder_add, clavarium_binder_edit,
127
133
  * clavarium_binder_move, clavarium_binder_note, clavarium_binder_archive), JSON-RPC over HTTP
134
+ * (Streamable HTTP, stateless, JSON answers; also at /api/ext/v1/mcp). A tool
135
+ * that needs a scope (status, jobs, create rooms) is listed only to a key given it.
128
136
  * A conversation, room, box or list not given, or not there, is the same 403: a key learns nothing of what it was not given.
129
137
  *
130
138
  * The front lets /api/ext/ through without sign-on, as it does /c/
@@ -155,6 +163,7 @@ export const EXT_PREFIX = '/api/ext/';
155
163
 
156
164
  /* The scopes a key may be given: [asset, rights] in the table. */
157
165
  export const SCOPES = Object.freeze({ status: { asset: 'server:status', rights: 'r', label: 'Its state (memory, disk, versions)' },
166
+ jobs: { asset: 'server:jobs', rights: 'r', label: 'Jobs: read what Clavarium does and its logs' },
158
167
  'create-rooms': { asset: 'server:rooms', rights: 'w', label: 'Create rooms' } });
159
168
  /* What a key may do in one conversation: [rights in the table]. */
160
169
  export const LEVELS = Object.freeze({ read: 'r', talk: 'rw', act: 'rwm' });
@@ -531,6 +540,8 @@ export function readPart(get) {
531
540
  return { last: String(last), ...(since ? { since } : {}) };
532
541
  }
533
542
 
543
+ /* A job's id, as jobs.mjs makes it (its conversation and when it started). */
544
+ const JOB_ID = /^[A-Za-z0-9_-]{1,120}$/;
534
545
  const MCP_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05'];
535
546
  const MCP_BODY_MAX = 64 * 1024;
536
547
  const CONVERSATION_ARG = { type: 'string', description: 'The conversation\'s id, as clavarium_conversations gives it.' };
@@ -541,6 +552,20 @@ export const STATUS_TOOL = {
541
552
  inputSchema: { type: 'object', properties: {}, additionalProperties: false },
542
553
  annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
543
554
  };
555
+ export const JOBS_TOOL = {
556
+ name: 'clavarium_jobs',
557
+ title: 'Jobs of this Clavarium',
558
+ description: 'Read-only: what this Clavarium does or did today -- conversations built, copied, moved, restarted, and its own updates -- as {running, done}, newest first, each with its id, what, start and end, result. No logs: clavarium_job_log gives one job\'s.',
559
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
560
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
561
+ };
562
+ export const JOB_LOG_TOOL = {
563
+ name: 'clavarium_job_log',
564
+ title: 'Log of a job',
565
+ description: 'Read-only: one job, under way or done today, with its log (lines {at, text}).',
566
+ inputSchema: { type: 'object', properties: { id: { type: 'string', description: 'The job\'s id, as clavarium_jobs gives it.' } }, required: ['id'], additionalProperties: false },
567
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
568
+ };
544
569
  export const CONVERSATIONS_TOOL = {
545
570
  name: 'clavarium_conversations',
546
571
  title: 'Conversations of this key',
@@ -671,8 +696,10 @@ export const BINDER_ARCHIVE_TOOL = tool('clavarium_binder_archive', 'Archive a r
671
696
  'Archive a record (or restore it: "restore": true). Never deleted: only a person deletes. The list must have been given to this key to write.',
672
697
  { binder: BINDER_ARG, record: RECORD_ARG, restore: { type: 'boolean' } }, ['binder', 'record'], true);
673
698
  const BINDER_TOOLS = [BINDERS_TOOL, BINDER_RECORDS_TOOL, BINDER_RECORD_TOOL, BINDER_ADD_TOOL, BINDER_EDIT_TOOL, BINDER_MOVE_TOOL, BINDER_NOTE_TOOL, BINDER_ARCHIVE_TOOL];
674
- export const TOOLS = [STATUS_TOOL, CONVERSATIONS_TOOL, READ_TOOL, SAY_TOOL, WAKE_TOOL, SLEEP_TOOL, STOP_TOOL, REMINDERS_TOOL, REMIND_TOOL, REMINDER_CANCEL_TOOL,
699
+ export const TOOLS = [STATUS_TOOL, JOBS_TOOL, JOB_LOG_TOOL, CONVERSATIONS_TOOL, READ_TOOL, SAY_TOOL, WAKE_TOOL, SLEEP_TOOL, STOP_TOOL, REMINDERS_TOOL, REMIND_TOOL, REMINDER_CANCEL_TOOL,
675
700
  ROOMS_TOOL, ROOM_READ_TOOL, ROOM_SAY_TOOL, ROOM_CREATE_TOOL, ROOM_CHANGE_TOOL, ROOM_REMOVE_TOOL, BOXES_TOOL, BOX_SAY_TOOL, ...BINDER_TOOLS];
701
+ /* The tools that need a scope of the server: listed only to a key given it. */
702
+ const TOOL_SCOPES = Object.freeze({ [STATUS_TOOL.name]: 'status', [JOBS_TOOL.name]: 'jobs', [JOB_LOG_TOOL.name]: 'jobs', [ROOM_CREATE_TOOL.name]: 'create-rooms' });
676
703
 
677
704
  /* Returns true when the request was under /api/ext/ (answered here). `status()`: the state, as statusOf
678
705
  makes it. `chats`: { list() -> [{ id, name }], read(name, part) -> talk.of's answer, chatOn(name),
@@ -686,8 +713,9 @@ export const TOOLS = [STATUS_TOOL, CONVERSATIONS_TOOL, READ_TOOL, SAY_TOOL, WAKE
686
713
  `events`: What happened (events.mjs), where each act is said with the key's name.
687
714
  07-11: `reminders`: { of(name) -> { on, plans: [{ id, text, cron, next }] }, set(name, { at, cron, text }, by) -> plan,
688
715
  cancel(name, plan) -> bool } -- a conversation's Docket (dockets.mjs). `binder`: { act(op, args, who) -> { ok, text, data } }
689
- -- Binder's keeper, asked as the key (an agent): its rules are Binder's. */
690
- export async function handleExternal(request, response, { keys, status, chats = null, rooms = null, boxes = null, reminders = null, binder = null, events = null, headers = {}, originOk = () => false, version = null }) {
716
+ -- Binder's keeper, asked as the key (an agent): its rules are Binder's.
717
+ 14-11: `jobs`: { list() -> { running, done }, log(id) -> the job with its log | undefined } (jobs.mjs, withUpdates). */
718
+ export async function handleExternal(request, response, { keys, status, chats = null, rooms = null, boxes = null, reminders = null, binder = null, jobs = null, events = null, headers = {}, originOk = () => false, version = null }) {
691
719
  const url = new URL(request.url ?? '/', 'http://local');
692
720
  const { pathname } = url;
693
721
  if (!pathname.startsWith(EXT_PREFIX) && pathname !== EXT_PREFIX.slice(0, -1)) return false;
@@ -970,8 +998,36 @@ export async function handleExternal(request, response, { keys, status, chats =
970
998
  binderSaid(id, list, `#${record} ${restore === true ? 'restored' : 'archived'}`);
971
999
  return { ok: true, record: recordRead(id, list, record).record };
972
1000
  };
1001
+ /* What Clavarium does (scope "jobs"), its texts masked as a room's are: a log line may quote what a program said. */
1002
+ const mayJobs = (id) => { if (!keys.may(id, 'jobs')) throw Object.assign(new Refusal(403, `This key was not given the scope "${SCOPES.jobs.label}".`), { key: id }); };
1003
+ const jobShown = ({ what, step, why, log, ...job }) => ({ ...job, what: masked(what), ...(step !== undefined ? { step: masked(step) } : {}), ...(why !== undefined ? { why: masked(why) } : {}),
1004
+ ...(Array.isArray(log) ? { log: log.map((l) => ({ at: l.at, text: masked(l.text) })) } : {}) });
1005
+ const jobsListed = (id) => {
1006
+ mayJobs(id);
1007
+ const { running = [], done = [] } = jobs?.list() ?? {};
1008
+ return { running: running.map(jobShown), done: done.map(jobShown) };
1009
+ };
1010
+ const jobRead = (id, job) => {
1011
+ mayJobs(id);
1012
+ const found = typeof job === 'string' && JOB_ID.test(job) ? jobs?.log(job) : undefined;
1013
+ if (!found) throw new Refusal(404, 'No such job (under way, or done today).');
1014
+ return jobShown(found);
1015
+ };
973
1016
  const ownError = (error, id) => (error instanceof Refusal ? Object.assign(error, { key: error.key ?? id }) : error);
974
1017
  try {
1018
+ const jobRoute = /^\/v1\/jobs(?:\/([^/]+))?$/.exec(route);
1019
+ if (jobRoute) {
1020
+ if (request.method !== 'GET') return send(405, { error: 'Call this address with GET.' }, { allow: 'GET' });
1021
+ let id;
1022
+ try { id = keys.check(request.headers.authorization, 'jobs'); } catch (error) { return refused(error); }
1023
+ try {
1024
+ let job = '';
1025
+ try { job = jobRoute[1] ? decodeURIComponent(jobRoute[1]) : ''; } catch { job = ''; }
1026
+ const body = jobRoute[1] ? jobRead(id, job) : jobsListed(id);
1027
+ note(id, 200);
1028
+ return send(200, body);
1029
+ } catch (error) { return refused(ownError(error, id)); }
1030
+ }
975
1031
  if (route === '/v1/status') {
976
1032
  if (request.method !== 'GET') return send(405, { error: 'Call this address with GET.' }, { allow: 'GET' });
977
1033
  let id;
@@ -1091,24 +1147,25 @@ export async function handleExternal(request, response, { keys, status, chats =
1091
1147
  return send(200, done);
1092
1148
  } catch (error) { return refused(ownError(error, id)); }
1093
1149
  }
1094
- if (route === '/mcp') {
1150
+ /* MCP at /api/ext/mcp and, beside the API it speaks for, /api/ext/v1/mcp: the same. */
1151
+ if (route === '/mcp' || route === '/v1/mcp') {
1095
1152
  if (request.method !== 'POST') return send(405, { error: 'MCP is spoken with POST here (no event stream).' }, { allow: 'POST' });
1096
1153
  let id;
1097
- try { id = keys.check(request.headers.authorization); } catch (error) { return refused(error, '/mcp'); }
1154
+ try { id = keys.check(request.headers.authorization); } catch (error) { return refused(error, route); }
1098
1155
  let text = '';
1099
- for await (const piece of request) { text += piece; if (text.length > MCP_BODY_MAX) { note(id, 413, '/mcp'); return send(413, { error: 'Too long.' }); } }
1156
+ for await (const piece of request) { text += piece; if (text.length > MCP_BODY_MAX) { note(id, 413, route); return send(413, { error: 'Too long.' }); } }
1100
1157
  /* A protocol version said in the header, and none spoken here: refused, as the spec asks (none said: the oldest assumed). */
1101
1158
  const said = request.headers['mcp-protocol-version'];
1102
- if (typeof said === 'string' && said && !MCP_VERSIONS.includes(said)) { note(id, 400, '/mcp'); return send(400, { jsonrpc: '2.0', id: null, error: { code: -32600, message: `Unsupported MCP-Protocol-Version: ${said.slice(0, 20)} (spoken: ${MCP_VERSIONS.join(', ')})` } }); }
1159
+ if (typeof said === 'string' && said && !MCP_VERSIONS.includes(said)) { note(id, 400, route); return send(400, { jsonrpc: '2.0', id: null, error: { code: -32600, message: `Unsupported MCP-Protocol-Version: ${said.slice(0, 20)} (spoken: ${MCP_VERSIONS.join(', ')})` } }); }
1103
1160
  let msg;
1104
- try { msg = JSON.parse(text); } catch { note(id, 400, '/mcp'); return send(400, { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }); }
1161
+ try { msg = JSON.parse(text); } catch { note(id, 400, route); return send(400, { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }); }
1105
1162
  if (!msg || typeof msg !== 'object' || Array.isArray(msg) || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') {
1106
- note(id, 400, '/mcp'); return send(400, { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid Request' } });
1163
+ note(id, 400, route); return send(400, { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid Request' } });
1107
1164
  }
1108
1165
  const args = msg.params?.arguments && typeof msg.params.arguments === 'object' && !Array.isArray(msg.params.arguments) ? msg.params.arguments : {};
1109
1166
  /* The journal says which tool, and on which conversation, room or box. */
1110
- const on = [args.conversation, args.room, args.box, args.binder].find((v) => typeof v === 'string');
1111
- const what = `/mcp ${msg.method.slice(0, 40)}${msg.method === 'tools/call' ? ` ${String(msg.params?.name ?? '').slice(0, 40)}${on ? ` ${on.slice(0, 36)}` : ''}` : ''}`;
1167
+ const on = [args.conversation, args.room, args.box, args.binder, msg.params?.name === JOB_LOG_TOOL.name ? args.id : undefined].find((v) => typeof v === 'string');
1168
+ const what = `${route} ${msg.method.slice(0, 40)}${msg.method === 'tools/call' ? ` ${String(msg.params?.name ?? '').slice(0, 40)}${on ? ` ${on.slice(0, 36)}` : ''}` : ''}`;
1112
1169
  /* A notification (no id) is taken, never answered. */
1113
1170
  if (msg.id === undefined || msg.id === null) { note(id, 202, what); response.writeHead(202, { ...headers, 'cache-control': 'no-store' }).end(); return true; }
1114
1171
  const answer = (result, code = 200) => { note(id, code, what); return send(200, { jsonrpc: '2.0', id: msg.id, result }); };
@@ -1119,10 +1176,11 @@ export async function handleExternal(request, response, { keys, status, chats =
1119
1176
  const asked = String(msg.params?.protocolVersion ?? '');
1120
1177
  return answer({ protocolVersion: MCP_VERSIONS.includes(asked) ? asked : MCP_VERSIONS[0], capabilities: { tools: { listChanged: false } },
1121
1178
  serverInfo: { name: 'clavarium', title: 'Clavarium', version: version ?? '0' },
1122
- instructions: 'This Clavarium, as far as this key was given it: its state (clavarium_status), the conversations given to it (clavarium_conversations), to read (clavarium_read) or to talk in (clavarium_say); its rooms (clavarium_rooms, clavarium_room_read, clavarium_room_say); its voice boxes (clavarium_boxes; clavarium_box_say says a short text aloud in the home). Where it was given more: a conversation woken, put to sleep, its turn stopped (clavarium_conversation_wake, _sleep, _stop); rooms made, changed, removed (clavarium_room_create, clavarium_room_change, clavarium_room_remove); a conversation\'s reminders seen, set, taken back (clavarium_reminders, clavarium_remind, clavarium_reminder_cancel); binder lists read and written (clavarium_binders, clavarium_binder_records, clavarium_binder_record, clavarium_binder_add, _edit, _move, _note, _archive).' });
1179
+ instructions: 'This Clavarium, as far as this key was given it: its state (clavarium_status), what it does and each job\'s log (clavarium_jobs, clavarium_job_log), the conversations given to it (clavarium_conversations), to read (clavarium_read) or to talk in (clavarium_say); its rooms (clavarium_rooms, clavarium_room_read, clavarium_room_say); its voice boxes (clavarium_boxes; clavarium_box_say says a short text aloud in the home). Where it was given more: a conversation woken, put to sleep, its turn stopped (clavarium_conversation_wake, _sleep, _stop); rooms made, changed, removed (clavarium_room_create, clavarium_room_change, clavarium_room_remove); a conversation\'s reminders seen, set, taken back (clavarium_reminders, clavarium_remind, clavarium_reminder_cancel); binder lists read and written (clavarium_binders, clavarium_binder_records, clavarium_binder_record, clavarium_binder_add, _edit, _move, _note, _archive).' });
1123
1180
  }
1124
1181
  case 'ping': return answer({});
1125
- case 'tools/list': return answer({ tools: TOOLS });
1182
+ /* A tool that needs a scope is shown only to a key given it (one called anyway is refused, 403). */
1183
+ case 'tools/list': return answer({ tools: TOOLS.filter((x) => !TOOL_SCOPES[x.name] || keys.may(id, TOOL_SCOPES[x.name])) });
1126
1184
  case 'tools/call': {
1127
1185
  const name = msg.params?.name;
1128
1186
  if (!TOOLS.some((x) => x.name === name)) return fail(-32602, `Unknown tool: ${String(name ?? '').slice(0, 60)}`);
@@ -1131,6 +1189,11 @@ export async function handleExternal(request, response, { keys, status, chats =
1131
1189
  if (!keys.may(id, 'status')) throw new Refusal(403, `This key was not given the scope "${SCOPES.status.label}".`);
1132
1190
  return result(await status());
1133
1191
  }
1192
+ if (name === JOBS_TOOL.name) return result(jobsListed(id));
1193
+ if (name === JOB_LOG_TOOL.name) {
1194
+ if (typeof args.id !== 'string') return fail(-32602, 'id: the id of a job, as clavarium_jobs gives it.');
1195
+ return result(jobRead(id, args.id));
1196
+ }
1134
1197
  if (name === CONVERSATIONS_TOOL.name) return result(listed(id));
1135
1198
  if (name === ROOMS_TOOL.name) return result(roomsListed(id));
1136
1199
  if (name === BOXES_TOOL.name) return result(boxesListed(id));
@@ -1187,7 +1250,7 @@ export async function handleExternal(request, response, { keys, status, chats =
1187
1250
  }
1188
1251
  }
1189
1252
  note(null, 404);
1190
- return send(404, { error: 'Not found. GET /api/ext/v1/status, /api/ext/v1/conversations, /api/ext/v1/rooms, /api/ext/v1/boxes, /api/ext/v1/binders, or MCP at /api/ext/mcp.' });
1253
+ return send(404, { error: 'Not found. GET /api/ext/v1/status, /api/ext/v1/conversations, /api/ext/v1/rooms, /api/ext/v1/boxes, /api/ext/v1/jobs, /api/ext/v1/binders, or MCP at /api/ext/v1/mcp.' });
1191
1254
  } catch (error) {
1192
1255
  if (error instanceof Refusal) return refused(error);
1193
1256
  note(null, 500);
@@ -14,9 +14,9 @@ import { resumeOrFresh } from './tools.mjs';
14
14
  import { TOOLS_PATH, LAUNCH } from './toolbox.mjs';
15
15
  import { availableParallelism } from 'node:os';
16
16
  import { spawn } from 'node:child_process';
17
- import { readFileSync, createReadStream, createWriteStream, mkdtempSync, rmSync } from 'node:fs';
17
+ import { readFileSync, createReadStream, createWriteStream, mkdtempSync, rmSync, statSync, copyFileSync, mkdirSync } from 'node:fs';
18
18
  import { tmpdir } from 'node:os';
19
- import { join } from 'node:path';
19
+ import { join, dirname } from 'node:path';
20
20
 
21
21
  export const SESSION = 'main';
22
22
  export const STOP_DELAY_MS = 60_000;
@@ -938,7 +938,10 @@ export class Conversations {
938
938
  from its machine, a manifest first (clavarium-conversation.json: its tool, its name, its size). Nothing
939
939
  of the tool is known here: any tool that says where its state is can be exported, imported, moved.
940
940
  The machine must run (its home is in it). -> { name: the file's name, stream } */
941
- async exportState(name) {
941
+ /* `toWork` (14-11): the archive written into its own work folder (/work/.clavarium-carry/<toWork>.tgz), that
942
+ the server reads on its side, rather than sent out through the VM manager's output -- which stalled for good
943
+ past ~36 KB on the owner's server. Its output is then empty. */
944
+ async exportState(name, { toWork } = {}) {
942
945
  const c = this.#store.get(name);
943
946
  if (!c) throw new Refusal(404, 'No such conversation.');
944
947
  const tool = this.#tools.find((t) => t.id === c.tool);
@@ -949,13 +952,15 @@ export class Conversations {
949
952
  (a path it has not made yet left out), the cache left out. */
950
953
  /* (Its paths are plain -- letters, digits, . _ / - -- checked by tools.mjs: given as words.) */
951
954
  /* A reading of an earlier try that never ended (14-11: three left, each holding its pipe): ended first. */
952
- const script = 'for p in $(pgrep -f "^tar -czf - --warning=no-file-changed -C /tmp/"); do kill $p 2>/dev/null; done; m=$(mktemp -d) || exit 2; printf "%s" "$1" > "$m/clavarium-conversation.json"; '
955
+ const script = 'for p in $(pgrep -f "^tar -czf .* clavarium-conversation.json"); do kill $p 2>/dev/null; done; m=$(mktemp -d) || exit 2; printf "%s" "$1" > "$m/clavarium-conversation.json"; '
953
956
  + 'ex=""; for a in $2; do ex="$ex --exclude=./$a"; done; ks=""; for a in $3; do if [ -e "$HOME/$a" ]; then ks="$ks ./$a"; fi; done; '
954
- + 'rc=0; tar -czf - --warning=no-file-changed -C "$m" clavarium-conversation.json -C "$HOME" $ex $ks || rc=$?; rm -rf "$m"; '
957
+ + 'out=-; if [ -n "$4" ]; then mkdir -p /work/.clavarium-carry && out="/work/.clavarium-carry/$4.tgz"; fi; '
958
+ + 'rc=0; tar -czf "$out" --warning=no-file-changed -C "$m" clavarium-conversation.json -C "$HOME" $ex $ks || rc=$?; rm -rf "$m"; '
955
959
  /* 1: a file changed while read (its tool writing its log as it is read, 14-11: a live Claude Code): the
956
960
  archive is whole all the same -- what was there, read; only a real error (2) fails. */
957
961
  + '[ "$rc" -le 1 ]';
958
- const argv = this.#vms.execArgv(name, ['sh', '-c', script, 'export', manifest, tool.state.skip.join(' '), tool.state.keep.join(' ')]);
962
+ const id = typeof toWork === 'string' && /^[a-z0-9-]{1,64}$/.test(toWork) ? toWork : '';
963
+ const argv = this.#vms.execArgv(name, ['sh', '-c', script, 'export', manifest, tool.state.skip.join(' '), tool.state.keep.join(' '), id]);
959
964
  const child = spawn(argv[0], argv.slice(1), { stdio: ['ignore', 'pipe', 'pipe'] });
960
965
  /* What it said when it failed: kept short, for the message that says why (a copy, a move). */
961
966
  child.said = '';
@@ -977,19 +982,35 @@ export class Conversations {
977
982
 
978
983
  /* An exported state unpacked into its home (its tool stopped by the caller): its manifest checked, then each
979
984
  part put in place of the old. -> the manifest's { name, at }, or null. */
985
+ /* `input`: a stream, sent through the VM manager's input; or the path of a file here -- then, when it has a work
986
+ folder here, put there and read from it in its machine (14-11: the VM manager's channel failed past a few tens
987
+ of KB on the owner's server, both ways). */
980
988
  async #unpack(name, toolId, input) {
989
+ let viaWork = '';
990
+ let source = input;
991
+ const workDir = typeof input === 'string' && this.#store.get(name)?.work === 'kept' && typeof this.workFolder === 'function' ? this.workFolder(name) : '';
992
+ if (workDir) {
993
+ const id = `in-${Date.now()}`;
994
+ viaWork = join(workDir, '.clavarium-carry', `${id}.tgz`);
995
+ mkdirSync(dirname(viaWork), { recursive: true });
996
+ copyFileSync(input, viaWork);
997
+ source = id;
998
+ } else if (typeof input === 'string') source = createReadStream(input);
999
+ try { return await this.#unpackFrom(name, toolId, source, Boolean(viaWork)); } finally { if (viaWork) rmSync(viaWork, { force: true }); }
1000
+ }
1001
+ async #unpackFrom(name, toolId, input, fromWork) {
981
1002
  /* Unpacked aside first: its manifest read, its tool checked; then moved into the home. */
982
1003
  /* Aside in the home itself (never /tmp, which may be memory): then each part moved in place of the old. */
983
- const script = 'set -e; m=$(mktemp -d "$HOME/.clavarium-import.XXXXXX"); trap \'rm -rf "$m"\' EXIT; tar -xzf - -C "$m"; '
1004
+ const script = 'set -e; m=$(mktemp -d "$HOME/.clavarium-import.XXXXXX"); trap \'rm -rf "$m"\' EXIT; if [ -n "$2" ]; then tar -xzf "/work/.clavarium-carry/$2.tgz" -C "$m"; else tar -xzf - -C "$m"; fi; '
984
1005
  + 'grep -q "\\"kind\\":\\"clavarium-conversation\\"" "$m/clavarium-conversation.json" || { echo "not an exported conversation" >&2; exit 3; }; '
985
1006
  + 'grep -q "\\"tool\\":\\"$1\\"" "$m/clavarium-conversation.json" || { echo "another tool" >&2; exit 4; }; '
986
1007
  + 'cat "$m/clavarium-conversation.json"; rm -f "$m/clavarium-conversation.json"; '
987
1008
  + 'for e in "$m"/.[!.]* "$m"/*; do if [ ! -e "$e" ]; then continue; fi; b=$(basename "$e"); rm -rf "$HOME/$b"; mv "$e" "$HOME/$b"; done';
988
- const argv = this.#vms.execArgv(name, ['sh', '-c', script, 'import', toolId]);
1009
+ const argv = this.#vms.execArgv(name, ['sh', '-c', script, 'import', toolId, fromWork ? input : '']);
989
1010
  const child = spawn(argv[0], argv.slice(1), { stdio: ['pipe', 'pipe', 'pipe'] });
990
1011
  const out = []; const err = [];
991
1012
  child.stdout.on('data', (d) => out.push(d)); child.stderr.on('data', (d) => err.push(d));
992
- input.pipe(child.stdin);
1013
+ if (fromWork) child.stdin.end(); else input.pipe(child.stdin);
993
1014
  child.stdin.on('error', () => { /* it stopped reading: said below */ });
994
1015
  const code = await new Promise((ok) => child.on('close', ok));
995
1016
  if (code === 3) throw new Refusal(400, 'This is not an exported conversation.');
@@ -1065,37 +1086,52 @@ export class Conversations {
1065
1086
  for (let attempt = 0; attempt < 2 && code !== 0; attempt++) {
1066
1087
  if (attempt) await new Promise((ok) => setTimeout(ok, 10_000));
1067
1088
  this.#store.patch(to, { step: `Copying ${tool.label}'s memory` });
1068
- const out = await this.exportState(from);
1089
+ /* Through its work folder when there is one here (14-11): its folders put back first -- a machine
1090
+ started outside an opening may have them loose -- then its archive written there, its size read
1091
+ on this side as it grows. Else, as before, through the VM manager's output. */
1092
+ const workDir = c.work === 'kept' && typeof this.workFolder === 'function' ? this.workFolder(from) : '';
1093
+ const carryId = workDir ? `copy-${to}-${Date.now()}` : '';
1094
+ const inWork = carryId ? join(workDir, '.clavarium-carry', `${carryId}.tgz`) : '';
1095
+ if (inWork) await Promise.race([Promise.resolve().then(() => this.mounted(from, true)).catch(() => {}), new Promise((r) => { setTimeout(r, MOUNTED_MS).unref?.(); })]);
1096
+ const out = await this.exportState(from, inWork ? { toWork: carryId } : {});
1069
1097
  child = out.child;
1070
1098
  let read = 0; let lastAt = Date.now(); let stalled = false;
1071
- out.stream.on('data', (d) => { read += d.length; lastAt = Date.now(); say(`Copying ${tool.label}'s memory: ${sizeWords(read)} read`); });
1099
+ const grew = (n) => { if (n <= read) return; read = n; lastAt = Date.now(); say(`Copying ${tool.label}'s memory: ${sizeWords(read)} read`); };
1100
+ if (inWork) out.stream.resume(); else out.stream.on('data', (d) => grew(read + d.length));
1101
+ const sizing = inWork ? setInterval(() => { try { grew(statSync(inWork).size); } catch { /* not there yet */ } }, 1000) : null;
1072
1102
  /* Nothing comes for a while: said, with how long; for too long, the reading is ended and why said --
1073
1103
  never an endless wait nobody can read (14-11: stuck at "36 KB read"). */
1074
1104
  /* Quiet for 30 s: its machine asked, once, what its reading does -- the file it is on and its state
1075
- (D: waiting on the disk), its load, its free memory -- or said not to answer at all. Said with the
1076
- wait, and in the end's why (14-11: stuck at 36 KB on the owner's server, never here). */
1105
+ (D: waiting on the disk), its load, its free memory -- or said not to answer at all. Written to the
1106
+ copy's job log; the screen and the end's why stay short (14-11: stuck at 36 KB on the owner's server, never here). */
1077
1107
  let seen = '';
1078
1108
  /* Each tar and gzip: its state, what the kernel has it wait on (wchan), the file it holds and that
1079
1109
  file's filesystem -- enough to tell a disk, a network mount or a pipe nobody empties. */
1080
1110
  const probe = 'for p in $(pgrep -x tar) $(pgrep -x gzip); do f=$(ls -l /proc/$p/fd 2>/dev/null | grep -o "/home/[^ ]*" | tail -1); '
1081
1111
  + 'echo "$(cat /proc/$p/comm) $p $(cut -d" " -f3 /proc/$p/stat) $(cat /proc/$p/wchan 2>/dev/null) ${f#$HOME/}${f:+ [$(stat -f -c %T "$f" 2>/dev/null)]}"; done; '
1082
1112
  + 'echo "load $(cut -d" " -f1 /proc/loadavg)"; awk \'/MemAvailable/{print "free " int($2/1024) " MB"}\' /proc/meminfo';
1083
- const ask = () => { seen = '…'; this.#vms.exec(from, ['sh', '-c', probe], { timeoutMs: 20_000 }).then((r) => { seen = r.code === 0 ? (r.stdout || '').trim().split('\n').join(', ').slice(0, 200) : 'its machine did not answer'; }, () => { seen = 'its machine did not answer'; }); };
1113
+ /* What it said goes to the copy's job log (jobs.mjs), read in Settings and by its AI -- not on screen. */
1114
+ const heard = (said) => { seen = said; this.jobs?.note(to, `Its original's reading: ${said}`); };
1115
+ const ask = () => { seen = '…'; this.#vms.exec(from, ['sh', '-c', probe], { timeoutMs: 20_000 }).then((r) => { heard(r.code === 0 ? (r.stdout || '').trim().split('\n').join(', ').slice(0, 200) : 'its machine did not answer'); }, () => { heard('its machine did not answer'); }); };
1084
1116
  const watch = setInterval(() => {
1085
1117
  const quiet = Math.round((Date.now() - lastAt) / 1000);
1086
1118
  if (quiet >= COPY_QUIET_MS / 1000) { stalled = true; child.kill('SIGKILL'); return; }
1087
1119
  if (quiet >= 30 && !seen) ask();
1088
- if (quiet >= 15) say(`Copying ${tool.label}'s memory: ${sizeWords(read)} read, nothing more for ${quiet} s${seen && seen !== '…' ? ` (${seen})` : ''}`);
1120
+ if (quiet >= 15) say(`Copying ${tool.label}'s memory: ${sizeWords(read)} read, nothing more for ${quiet} s`);
1089
1121
  }, 5000);
1090
1122
  const failed = new Promise((ok) => child.on('error', () => ok(-1)));
1091
- const file = createWriteStream(carried, { mode: 0o600 });
1092
- out.stream.pipe(file);
1093
- code = await Promise.race([new Promise((ok) => child.on('close', ok)), failed]).finally(() => clearInterval(watch));
1123
+ const file = inWork ? null : createWriteStream(carried, { mode: 0o600 });
1124
+ if (file) out.stream.pipe(file);
1125
+ code = await Promise.race([new Promise((ok) => child.on('close', ok)), failed]).finally(() => { clearInterval(watch); if (sizing) clearInterval(sizing); });
1126
+ /* Written in its work folder: taken from there, and the folder left as it was. */
1127
+ if (inWork) {
1128
+ try { if (code === 0 && !stalled) { copyFileSync(inWork, carried); grew(statSync(carried).size); } } finally { rmSync(inWork, { force: true }); }
1129
+ }
1094
1130
  if (stalled) {
1095
1131
  const now = await this.#vms.state(from, { fresh: true }).catch(() => undefined);
1096
- throw new Error(`its original stopped sending its tool's memory (${sizeWords(read)} read, then nothing for ${COPY_QUIET_MS / 60_000} min; its machine is ${now ?? 'in a state that could not be read'}${seen && seen !== '…' ? `; it said: ${seen}` : ''})`);
1132
+ throw new Error(`its original stopped sending its tool's memory: ${sizeWords(read)} read, then nothing for ${COPY_QUIET_MS / 60_000} min, its machine ${now ?? 'unreadable'} (see its job's log in Settings)`);
1097
1133
  }
1098
- await new Promise((ok) => (file.writableFinished ? ok() : file.on('finish', ok)));
1134
+ if (file) await new Promise((ok) => (file.writableFinished ? ok() : file.on('finish', ok)));
1099
1135
  if (code !== 255) break;
1100
1136
  }
1101
1137
  if (code !== 0) throw new Error(`its tool's memory could not be read (exit ${code}${firstLine(child.said) ? `: ${firstLine(child.said)}` : ''}).`);
@@ -1118,7 +1154,7 @@ export class Conversations {
1118
1154
  if (started.code !== 0) throw new Error(`its machine did not start: ${firstLine(started.stderr) || `exit ${started.code}`}.`);
1119
1155
  }
1120
1156
  this.#store.patch(to, { step: `Putting ${tool.label}'s memory in the copy` });
1121
- await this.#unpack(to, c.tool, createReadStream(carried));
1157
+ await this.#unpack(to, c.tool, carried);
1122
1158
  }
1123
1159
  this.#store.patch(to, { step: 'Giving it the same accesses' });
1124
1160
  await this.copyRights(from, to);
@@ -1212,7 +1248,7 @@ export class Conversations {
1212
1248
  /* Not opened while its state is put back: building still, to the end. */
1213
1249
  this.#store.patch(name, { phase: 'building', step: `Putting ${tool.label}'s state back` });
1214
1250
  this.drop(name);
1215
- try { await this.#unpack(name, c.tool, createReadStream(carried)); } catch (error) {
1251
+ try { await this.#unpack(name, c.tool, carried); } catch (error) {
1216
1252
  this.#store.patch(name, { phase: 'ready', step: undefined });
1217
1253
  this.ready(name);
1218
1254
  this.renewed(name, `Moved to the shared machine ${machine}, but ${tool.label}'s state did not come along (${error.message}): it starts afresh. Its old machine is kept, stopped.`, true);
@@ -8,7 +8,7 @@
8
8
  import { cp, lstat } from 'node:fs/promises';
9
9
  import { relative, sep } from 'node:path';
10
10
 
11
- export const NOT_COPIED = Object.freeze(['.docket', '.tether', '.binder', '.parley/pulse.json', '.parley/speakers.json', '.parley/restart-asked', '.parley/server.mjs']);
11
+ export const NOT_COPIED = Object.freeze(['.docket', '.tether', '.binder', '.clavarium-carry', '.parley/pulse.json', '.parley/speakers.json', '.parley/restart-asked', '.parley/server.mjs']);
12
12
 
13
13
  /* Whether a path of the work folder (relative, '' for the folder itself) is copied. */
14
14
  export function copied(path) {
package/server/grants.mjs CHANGED
@@ -35,7 +35,8 @@
35
35
  * in the table: the owner may do everything, always.
36
36
  *
37
37
  * An API key is not a device and not a conversation: it is given only what
38
- * its scopes name -- "server:status" (read), "server:rooms" (make rooms), and conversations one by one,
38
+ * its scopes name -- "server:status" (read), "server:jobs" (read its jobs and their logs), "server:rooms"
39
+ * (make rooms), and conversations one by one,
39
40
  * their chat to read ("r") or to talk in ("rw"), never their terminal ("x")
40
41
  * -- rooms one by one, their thread to read ("r") or to post in ("rw"), and
41
42
  * voice boxes one by one, their state ("r") or a short text said aloud
@@ -63,10 +64,10 @@
63
64
  import { Refusal } from './conversations.mjs';
64
65
 
65
66
  export const RIGHTS = Object.freeze({ conversation: 'rwxm', folder: 'rw', mailbox: 'r', git: 'rw', secret: 'x', server: 'rw', room: 'rwm', box: 'rw' });
66
- /* What each of the server's own assets takes: its state is read, rooms are made. */
67
- const SERVER_RIGHTS = Object.freeze({ 'server:status': 'r', 'server:rooms': 'w' });
67
+ /* What each of the server's own assets takes: its state and its jobs are read, rooms are made. */
68
+ const SERVER_RIGHTS = Object.freeze({ 'server:status': 'r', 'server:jobs': 'r', 'server:rooms': 'w' });
68
69
  const SUBJECT = /^(conversation:[a-z]([a-z0-9-]{0,30}[a-z0-9])?|(pairing|apikey):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/;
69
- const ASSET = /^(conversation|folder|mailbox|git):[a-z]([a-z0-9-]{0,30}[a-z0-9])?$|^secret:[A-Z][A-Z0-9_]{0,39}$|^server:(status|rooms)$|^(room|box):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
70
+ const ASSET = /^(conversation|folder|mailbox|git):[a-z]([a-z0-9-]{0,30}[a-z0-9])?$|^secret:[A-Z][A-Z0-9_]{0,39}$|^server:(status|jobs|rooms)$|^(room|box):[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
70
71
 
71
72
  export const typeOf = (asset) => String(asset).split(':')[0];
72
73
  export const nameOf = (asset) => String(asset).slice(String(asset).indexOf(':') + 1);