clavarium 0.2.435-next.1 → 0.2.437-next.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.
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/server/api.mjs +2 -6
- package/server/apikeys.mjs +78 -15
- package/server/conversations.mjs +29 -11
- package/server/copywork.mjs +1 -1
- package/server/grants.mjs +5 -4
- package/server/jobs.mjs +12 -0
- package/server/main.mjs +6 -2
- package/server/settingswords.mjs +1 -0
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "clavarium",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.437-next.1",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "clavarium",
|
|
9
|
-
"version": "0.2.
|
|
9
|
+
"version": "0.2.437-next.1",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@xterm/addon-fit": "^0.11.0",
|
package/package.json
CHANGED
package/server/api.mjs
CHANGED
|
@@ -177,6 +177,7 @@ import { writeFileSync } from 'node:fs';
|
|
|
177
177
|
import { suggest } from './suggest.mjs';
|
|
178
178
|
import { sameOrigin } from './bridge.mjs';
|
|
179
179
|
import { Refusal, DISK_GB } from './conversations.mjs';
|
|
180
|
+
import { withUpdates } from './jobs.mjs';
|
|
180
181
|
import { readRights, typeOf, nameOf } from './grants.mjs';
|
|
181
182
|
import { VmUnknown } from './vm.mjs';
|
|
182
183
|
import { list, download, importFile, page, PAGE_HEADERS, changeRoute, IMAGE_HEADERS, mailFile, mailPage } from './files.mjs';
|
|
@@ -409,12 +410,7 @@ export async function handleApi(request, response, conversations, headers, resou
|
|
|
409
410
|
const reactOf = /^\/api\/conversations\/([^/]+)\/health-react$/.exec(pathname);
|
|
410
411
|
if (reactOf && reacting) return send(200, reacting.settings(decodeURIComponent(reactOf[1]))), true;
|
|
411
412
|
if (pathname === '/api/jobs' && conversations.jobs) {
|
|
412
|
-
|
|
413
|
-
const day = Date.now() - 24 * 3600_000;
|
|
414
|
-
const updated = (updates?.about().history ?? []).filter((h) => h.at && Date.parse(h.at) >= day)
|
|
415
|
-
.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 ?? '' }) }));
|
|
416
|
-
const done = [...said.done, ...updated].sort((a, b) => String(b.endedAt).localeCompare(String(a.endedAt)));
|
|
417
|
-
return send(200, { running: said.running, done }), true;
|
|
413
|
+
return send(200, withUpdates(conversations.jobs, conversations.list?.() ?? [], updates?.about().history ?? [])), true;
|
|
418
414
|
}
|
|
419
415
|
/* A job's log (jobs.mjs): read when its line is opened, never with the list, which stays light. */
|
|
420
416
|
if (pathname === '/api/jobs/log' && conversations.jobs) {
|
package/server/apikeys.mjs
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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,
|
|
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,
|
|
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,
|
|
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,
|
|
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,
|
|
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 =
|
|
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
|
-
|
|
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);
|
package/server/conversations.mjs
CHANGED
|
@@ -14,7 +14,7 @@ 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 } from 'node:fs';
|
|
18
18
|
import { tmpdir } from 'node:os';
|
|
19
19
|
import { join } from 'node:path';
|
|
20
20
|
|
|
@@ -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
|
-
|
|
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
|
|
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
|
-
+ '
|
|
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
|
|
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 = '';
|
|
@@ -1065,10 +1070,19 @@ export class Conversations {
|
|
|
1065
1070
|
for (let attempt = 0; attempt < 2 && code !== 0; attempt++) {
|
|
1066
1071
|
if (attempt) await new Promise((ok) => setTimeout(ok, 10_000));
|
|
1067
1072
|
this.#store.patch(to, { step: `Copying ${tool.label}'s memory` });
|
|
1068
|
-
|
|
1073
|
+
/* Through its work folder when there is one here (14-11): its folders put back first -- a machine
|
|
1074
|
+
started outside an opening may have them loose -- then its archive written there, its size read
|
|
1075
|
+
on this side as it grows. Else, as before, through the VM manager's output. */
|
|
1076
|
+
const workDir = c.work === 'kept' && typeof this.workFolder === 'function' ? this.workFolder(from) : '';
|
|
1077
|
+
const carryId = workDir ? `copy-${to}-${Date.now()}` : '';
|
|
1078
|
+
const inWork = carryId ? join(workDir, '.clavarium-carry', `${carryId}.tgz`) : '';
|
|
1079
|
+
if (inWork) await Promise.race([Promise.resolve().then(() => this.mounted(from, true)).catch(() => {}), new Promise((r) => { setTimeout(r, MOUNTED_MS).unref?.(); })]);
|
|
1080
|
+
const out = await this.exportState(from, inWork ? { toWork: carryId } : {});
|
|
1069
1081
|
child = out.child;
|
|
1070
1082
|
let read = 0; let lastAt = Date.now(); let stalled = false;
|
|
1071
|
-
|
|
1083
|
+
const grew = (n) => { if (n <= read) return; read = n; lastAt = Date.now(); say(`Copying ${tool.label}'s memory: ${sizeWords(read)} read`); };
|
|
1084
|
+
if (inWork) out.stream.resume(); else out.stream.on('data', (d) => grew(read + d.length));
|
|
1085
|
+
const sizing = inWork ? setInterval(() => { try { grew(statSync(inWork).size); } catch { /* not there yet */ } }, 1000) : null;
|
|
1072
1086
|
/* Nothing comes for a while: said, with how long; for too long, the reading is ended and why said --
|
|
1073
1087
|
never an endless wait nobody can read (14-11: stuck at "36 KB read"). */
|
|
1074
1088
|
/* Quiet for 30 s: its machine asked, once, what its reading does -- the file it is on and its state
|
|
@@ -1090,14 +1104,18 @@ export class Conversations {
|
|
|
1090
1104
|
if (quiet >= 15) say(`Copying ${tool.label}'s memory: ${sizeWords(read)} read, nothing more for ${quiet} s`);
|
|
1091
1105
|
}, 5000);
|
|
1092
1106
|
const failed = new Promise((ok) => child.on('error', () => ok(-1)));
|
|
1093
|
-
const file = createWriteStream(carried, { mode: 0o600 });
|
|
1094
|
-
out.stream.pipe(file);
|
|
1095
|
-
code = await Promise.race([new Promise((ok) => child.on('close', ok)), failed]).finally(() => clearInterval(watch));
|
|
1107
|
+
const file = inWork ? null : createWriteStream(carried, { mode: 0o600 });
|
|
1108
|
+
if (file) out.stream.pipe(file);
|
|
1109
|
+
code = await Promise.race([new Promise((ok) => child.on('close', ok)), failed]).finally(() => { clearInterval(watch); if (sizing) clearInterval(sizing); });
|
|
1110
|
+
/* Written in its work folder: taken from there, and the folder left as it was. */
|
|
1111
|
+
if (inWork) {
|
|
1112
|
+
try { if (code === 0 && !stalled) { copyFileSync(inWork, carried); grew(statSync(carried).size); } } finally { rmSync(inWork, { force: true }); }
|
|
1113
|
+
}
|
|
1096
1114
|
if (stalled) {
|
|
1097
1115
|
const now = await this.#vms.state(from, { fresh: true }).catch(() => undefined);
|
|
1098
1116
|
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)`);
|
|
1099
1117
|
}
|
|
1100
|
-
await new Promise((ok) => (file.writableFinished ? ok() : file.on('finish', ok)));
|
|
1118
|
+
if (file) await new Promise((ok) => (file.writableFinished ? ok() : file.on('finish', ok)));
|
|
1101
1119
|
if (code !== 255) break;
|
|
1102
1120
|
}
|
|
1103
1121
|
if (code !== 0) throw new Error(`its tool's memory could not be read (exit ${code}${firstLine(child.said) ? `: ${firstLine(child.said)}` : ''}).`);
|
package/server/copywork.mjs
CHANGED
|
@@ -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:
|
|
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
|
|
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);
|
package/server/jobs.mjs
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
* note(name, text) a line added to the log of that conversation's job under way (none: nothing)
|
|
8
8
|
* list(now?) { running: [...], done: [...] } newest first, done within KEEP_MS; without their logs
|
|
9
9
|
* log(id) that job, under way or done, with its log; undefined if unknown
|
|
10
|
+
* withUpdates(...) list() with Clavarium's own updates of the day among the done (the owner's page, an API key)
|
|
10
11
|
*
|
|
11
12
|
* Each job keeps a LOG (14-11), for the owner in Settings and for the conversation's AI, rather than diagnostics
|
|
12
13
|
* on screen: each new step, the lines noted, its end. A step that only counts on ("… 12 MB read") is kept once
|
|
@@ -36,6 +37,17 @@ export function jobWords(c) {
|
|
|
36
37
|
return `Building ${titleOf(c)}${c.sharedMachine ? ` in « ${c.sharedMachine} »` : ''}`;
|
|
37
38
|
}
|
|
38
39
|
|
|
40
|
+
/* The jobs as the owner's page and an API key read them (/api/jobs, /api/ext/v1/jobs): those of the
|
|
41
|
+
conversations, and Clavarium's own updates of the day (updates.mjs history) among the done, newest first. */
|
|
42
|
+
export function withUpdates(jobs, records = [], history = [], now = Date.now()) {
|
|
43
|
+
const said = jobs.list(records);
|
|
44
|
+
const day = now - KEEP_MS;
|
|
45
|
+
const updated = history.filter((h) => h.at && Date.parse(h.at) >= day)
|
|
46
|
+
.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 ?? '' }) }));
|
|
47
|
+
const done = [...said.done, ...updated].sort((a, b) => String(b.endedAt).localeCompare(String(a.endedAt)));
|
|
48
|
+
return { running: said.running, done };
|
|
49
|
+
}
|
|
50
|
+
|
|
39
51
|
export class Jobs {
|
|
40
52
|
#open = new Map();
|
|
41
53
|
/* A job under way's log, and the count line held back, said only if no other comes after it. */
|
package/server/main.mjs
CHANGED
|
@@ -93,7 +93,7 @@ import { ApiKeys, handleExternal, handleApiKeys, statusOf } from './apikeys.mjs'
|
|
|
93
93
|
import { RelayJoin, handleRelayJoin, RELAY_JOIN_PATH } from './relayjoin.mjs';
|
|
94
94
|
import { WebSocketServer } from 'ws';
|
|
95
95
|
import { copyWorkFolder } from './copywork.mjs';
|
|
96
|
-
import { Jobs } from './jobs.mjs';
|
|
96
|
+
import { Jobs, withUpdates } from './jobs.mjs';
|
|
97
97
|
|
|
98
98
|
const ROOT = fileURLToPath(new URL('..', import.meta.url));
|
|
99
99
|
const MAINTENANCE = 'deploy/maintenance.html';
|
|
@@ -243,7 +243,7 @@ function serve(port, conversations, resources, { gate = () => 'local', originOk,
|
|
|
243
243
|
/* THE DOOR FOR PROGRAMS (apikeys.mjs): an API key is the right, never the gate -- the front lets
|
|
244
244
|
/api/ext/ through without sign-on, and strips the identity headers there. */
|
|
245
245
|
if (apikeys && (pathname === '/api/ext' || pathname.startsWith('/api/ext/'))) {
|
|
246
|
-
await handleExternal(request, response, { keys: apikeys.keys, status: apikeys.status, chats: apikeys.chats, rooms: apikeys.rooms, boxes: apikeys.boxes, reminders: apikeys.reminders, binder: apikeys.binder, events, headers: HEADERS, originOk, version: platform?.version ?? null });
|
|
246
|
+
await handleExternal(request, response, { keys: apikeys.keys, status: apikeys.status, chats: apikeys.chats, rooms: apikeys.rooms, boxes: apikeys.boxes, reminders: apikeys.reminders, binder: apikeys.binder, jobs: apikeys.jobs, events, headers: HEADERS, originOk, version: platform?.version ?? null });
|
|
247
247
|
return;
|
|
248
248
|
}
|
|
249
249
|
if (door && pathname.startsWith('/c/')) {
|
|
@@ -674,6 +674,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
674
674
|
/* A COPY (conversations.copy): its work folder from its original's, host side -- what is its alone left out
|
|
675
675
|
(its reminders, its pending asks to the keepers, its devices, its chat's live files) -- then the same accesses. */
|
|
676
676
|
all.copyWork = (from, to, onProgress) => copyWorkFolder(folders.workFolder(from), folders.workFolder(to), onProgress);
|
|
677
|
+
/* Where a conversation's work folder is on this side: a copy reads its tool's memory through it (14-11). */
|
|
678
|
+
all.workFolder = (name) => folders.workFolder(name);
|
|
677
679
|
all.copyRights = async (from, to) => {
|
|
678
680
|
for (const r of folders.of(from)) {
|
|
679
681
|
if (r.access === 'write') gitKeeper?.beforeWriter(r.name, to, true);
|
|
@@ -791,6 +793,8 @@ export async function startHome({ port, host, dataDir, mntDir = dataDir, gitRese
|
|
|
791
793
|
/* What the host program says of the server is never waited for long: a key gets what is known. */
|
|
792
794
|
const briefly = { brief: () => quick(capacity.brief(), 3000, null), room: () => quick(capacity.room(), 3000, null) };
|
|
793
795
|
const apikeys = { keys: apiKeys, status: () => statusOf({ conversations: all, talk, health, answerer, capacity: briefly, history, platform, updates, components }),
|
|
796
|
+
/* What Clavarium does (jobs.mjs), as Settings shows it: the list without logs, one job with its log. */
|
|
797
|
+
jobs: { list: () => withUpdates(all.jobs, all.list(), updates?.about().history ?? []), log: (id) => all.jobs.log(id) },
|
|
794
798
|
/* A key's conversations (their chat, through talk.mjs): read as the page reads it; a message posted as the page
|
|
795
799
|
posts one (its secrets lifted the same way), signed with the key's name. */
|
|
796
800
|
chats: {
|
package/server/settingswords.mjs
CHANGED
|
@@ -91,6 +91,7 @@ export const SETTINGS_WORDS_FR = {
|
|
|
91
91
|
'set-apikeys-expires': 'Expire', 'set-apikeys-30': 'Dans 30 jours', 'set-apikeys-90': 'Dans 90 jours', 'set-apikeys-365': 'Dans un an',
|
|
92
92
|
'set-apikeys-never': 'Jamais', 'set-apikeys-cancel': 'Annuler', 'set-apikeys-create': 'Créer', 'set-apikeys-new': 'Nouvelle clé',
|
|
93
93
|
'set-apikeys-never-by-key': 'Jamais : secrets, clés, comptes, droits', 'set-apikeys-scope-status': 'Son état (mémoire, disque, versions)',
|
|
94
|
+
'set-apikeys-scope-jobs': 'Tâches : ce que fait Clavarium, ses journaux',
|
|
94
95
|
'set-apikeys-scope-create-rooms': 'Créer des salons', 'set-apikeys-act': 'Agir', 'set-apikeys-manage': 'Gérer',
|
|
95
96
|
'set-apikeys-no-scope': 'Aucune portée', 'set-apikeys-by-you': 'par vous', 'set-apikeys-used': 'Utilisée {when}', 'set-apikeys-unused': 'Jamais utilisée',
|
|
96
97
|
'set-apikeys-expired': 'Expirée', 'set-apikeys-expires-on': 'Expire le {date}', 'set-apikeys-no-expiry': 'N\'expire pas',
|