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.
- package/config/launch/claude-code.sh +40 -19
- package/config/launch/codex.sh +37 -0
- package/config/launch/json-set.mjs +5 -2
- package/config/launch/mcp-relay.mjs +98 -0
- package/config/launch/mcp-sock.sh +31 -0
- package/config/launch/screen-watch.mjs +173 -0
- package/config/launch/toml-block.mjs +26 -0
- package/config/launch/tools-host.mjs +93 -0
- package/config/launch/vibe.sh +40 -0
- package/config/machine/clavarium-beat +44 -0
- package/config/machine/clavarium-beat-one +40 -0
- package/config/machine/clavarium-enter +60 -0
- package/config/tools.json +170 -12
- package/deploy/clavarium-host +385 -31
- package/deploy/clavarium-tunnel +14 -3
- package/deploy/clavarium.mjs +4 -0
- package/deploy/git-read +57 -5
- package/deploy/install.sh +11 -5
- package/deploy/maintenance.html +5 -2
- package/deploy/online.mjs +251 -8
- package/deploy/relay.sh +53 -27
- package/deploy/tunnel.mjs +7 -5
- package/deploy/updater.mjs +168 -25
- package/npm-shrinkwrap.json +245 -19
- package/package.json +9 -6
- package/server/agenda.mjs +140 -0
- package/server/api.mjs +392 -28
- package/server/apikeys.mjs +1372 -0
- package/server/beat.mjs +189 -0
- package/server/binders.mjs +42 -0
- package/server/boxcollect.mjs +276 -0
- package/server/boxes.mjs +348 -29
- package/server/bridge.mjs +13 -4
- package/server/browsers.mjs +364 -0
- package/server/capacity.mjs +37 -10
- package/server/carry.mjs +143 -0
- package/server/catalog.mjs +48 -0
- package/server/contactview.mjs +122 -0
- package/server/conversations.mjs +1122 -46
- package/server/copywork.mjs +34 -0
- package/server/demandes.mjs +251 -0
- package/server/desktop.mjs +102 -0
- package/server/devices.mjs +1 -0
- package/server/dictation-engines.mjs +91 -0
- package/server/dockets.mjs +49 -6
- package/server/door.mjs +19 -5
- package/server/events.mjs +3 -0
- package/server/features.mjs +366 -0
- package/server/files.mjs +43 -1
- package/server/gitaccess.mjs +12 -3
- package/server/gitchecks.mjs +17 -3
- package/server/gitkeeper.mjs +45 -10
- package/server/gitpush.mjs +286 -71
- package/server/gitrunner.mjs +144 -10
- package/server/grants.mjs +47 -11
- package/server/guide.mjs +31 -10
- package/server/health.mjs +138 -12
- package/server/jobs.mjs +138 -0
- package/server/linkguard.mjs +191 -0
- package/server/machinelist.mjs +58 -0
- package/server/mailref.mjs +90 -0
- package/server/mailview.mjs +204 -0
- package/server/main.mjs +425 -47
- package/server/mcpoauth.mjs +338 -0
- package/server/mcpx.mjs +175 -0
- package/server/network.mjs +125 -13
- package/server/profile.mjs +129 -0
- package/server/relayjoin.mjs +67 -0
- package/server/resources.mjs +6 -0
- package/server/revive.mjs +70 -0
- package/server/rooms.mjs +462 -0
- package/server/secrets.mjs +25 -12
- package/server/serverlogs.mjs +30 -4
- package/server/settingswords.mjs +375 -0
- package/server/signinhelp.mjs +239 -0
- package/server/speech.mjs +40 -4
- package/server/spoken.mjs +60 -0
- package/server/sshconsole.mjs +99 -0
- package/server/sshmachine.mjs +76 -0
- package/server/store.mjs +15 -1
- package/server/suggest.mjs +66 -0
- package/server/talk.mjs +228 -55
- package/server/tethers.mjs +223 -13
- package/server/toolbox.mjs +30 -7
- package/server/tools.mjs +38 -6
- package/server/updates.mjs +7 -2
- package/server/vm.mjs +215 -46
- package/server/vmwatch.mjs +82 -23
- package/server/voice.mjs +183 -51
- package/server/wakelearn.mjs +214 -0
- package/server/wakeups.mjs +42 -2
- package/server/watchdog.mjs +102 -0
- package/web/app.js +5590 -1237
- package/web/desk.js +531 -0
- package/web/device.html +15 -2
- package/web/features.js +480 -0
- package/web/index.html +874 -490
- package/web/kit.js +1142 -0
- package/web/links.js +2 -2
- package/web/mail-view.js +386 -0
- package/web/manifest.webmanifest +4 -0
- package/web/style.css +1592 -268
- package/web/voice-core.js +48 -0
- package/web/voice.js +13 -5
|
@@ -0,0 +1,1372 @@
|
|
|
1
|
+
/* API KEYS: what a program elsewhere (an assistant, an automation) may ask of
|
|
2
|
+
* this Clavarium, and the door it asks through.
|
|
3
|
+
*
|
|
4
|
+
* A key is a named USE ("home automation", "steering AI"), global to this
|
|
5
|
+
* Clavarium, never tied to a person. It is a third kind of subject in the one
|
|
6
|
+
* table of rights (grants.mjs, "apikey:<id>"): what it may do is lines of
|
|
7
|
+
* that table, and a new key has none. Its scopes:
|
|
8
|
+
*
|
|
9
|
+
* status read the state: the server's memory, disk and CPU, the
|
|
10
|
+
* conversations (their free name and state, never what they
|
|
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
|
|
16
|
+
* diagnostics the server's load (host commands by 5 min, its event loop),
|
|
17
|
+
* 10 s of its own profiler (what holds it), its logs (as
|
|
18
|
+
* Settings reads them, secrets masked) server:diagnostics r
|
|
19
|
+
*
|
|
20
|
+
* a conversation, given ONE BY ONE (never "all, and those to come"):
|
|
21
|
+
* read read its chat conversation:<name> r
|
|
22
|
+
* talk and post a message in it, as the chat does,
|
|
23
|
+
* signed with the key's name, never as the person conversation:<name> rw
|
|
24
|
+
* act and wake it, put it to sleep, stop its turn --
|
|
25
|
+
* as the owner's buttons do conversation:<name> rwm
|
|
26
|
+
* A conversation archived takes its lines with it (devices.forget). Its
|
|
27
|
+
* terminal ("x") is never given to a key.
|
|
28
|
+
*
|
|
29
|
+
* a room, given ONE BY ONE the same way:
|
|
30
|
+
* read read its thread, as the page reads it (names, never ids;
|
|
31
|
+
* secrets masked) room:<id> r
|
|
32
|
+
* talk and post in it as the person does -- to its host, or to the AIs
|
|
33
|
+
* named -- signed with the key's name and look room:<id> rw
|
|
34
|
+
* manage and rename it, add or take away members, change
|
|
35
|
+
* its host, remove it -- its members only among the
|
|
36
|
+
* conversations and boxes the key was given room:<id> rwm
|
|
37
|
+
* create rooms make a room (its members as above): the room a key
|
|
38
|
+
* makes is given to it at "manage" server:rooms w
|
|
39
|
+
*
|
|
40
|
+
* a voice box, given ONE BY ONE:
|
|
41
|
+
* state online, where it speaks, when it last heard, its volume --
|
|
42
|
+
* nothing it heard, never audio box:<id> r
|
|
43
|
+
* speak and make it say a short text aloud (SPEAK_MAX characters,
|
|
44
|
+
* SPEAK_PER_MIN a minute per key and box): never listen, record,
|
|
45
|
+
* change its settings nor update it box:<id> rw
|
|
46
|
+
* A room removed, a box withdrawn, takes its lines with it (main.mjs).
|
|
47
|
+
*
|
|
48
|
+
* a binder list (Binder), given ONE BY ONE (07-11):
|
|
49
|
+
* read list its records, read one with its notes (secrets masked)
|
|
50
|
+
* write and add a record, change its title, description, fields and
|
|
51
|
+
* due date, move it between states, add a note, archive or
|
|
52
|
+
* restore it -- as a conversation given the list to change may
|
|
53
|
+
* Kept where Binder keeps a conversation's lists: the list's own access
|
|
54
|
+
* ("apikey:<id>": read | write), not this table. The key asks Binder as an
|
|
55
|
+
* agent, signed with its name: Binder's own rules hold -- past a gate only
|
|
56
|
+
* what a person approved; never approve, delete, give access, change a
|
|
57
|
+
* list. Revoked, a key's lists go with it.
|
|
58
|
+
*
|
|
59
|
+
* a conversation's REMINDERS (its tool's Docket), folded into its level:
|
|
60
|
+
* read sees them
|
|
61
|
+
* talk and sets one: at a time, or a cron line, with a short text
|
|
62
|
+
* act and takes one back
|
|
63
|
+
* Its chat must be on (a docket is there only then).
|
|
64
|
+
*
|
|
65
|
+
* THE SECRET IS SHOWN ONCE. It is made here (32 random bytes, "clv_" before
|
|
66
|
+
* them), given back by `create` and never again: only its sha256 is kept, as
|
|
67
|
+
* a pairing's session is (devices.mjs). A 256-bit random secret needs no salt
|
|
68
|
+
* nor slow hash: nobody guesses it, and a copy of the store opens nothing.
|
|
69
|
+
* Compared in constant time, with every key looked at.
|
|
70
|
+
*
|
|
71
|
+
* REVOKED IS AT ONCE: the record and its lines of rights go; the next call is
|
|
72
|
+
* refused. EXPIRED is refused the same way (90 days unless chosen otherwise).
|
|
73
|
+
*
|
|
74
|
+
* EVERY USE IS JOURNALED: the key's id, the route, the answer, the time --
|
|
75
|
+
* never the secret, nor anything of it. Its own file, one JSON line each,
|
|
76
|
+
* cut to its newest half past JOURNAL_MAX. Each key is limited to
|
|
77
|
+
* RATE_PER_MIN calls a minute; calls with a key nobody has are limited too,
|
|
78
|
+
* all together, so that they cannot flood the journal. What a key DOES (a
|
|
79
|
+
* conversation woken, a room made...) is said in What happened too, with
|
|
80
|
+
* its name.
|
|
81
|
+
*
|
|
82
|
+
* THE KEY'S RIGHTS ARE THE SECURITY (07-11, the owner): no approval card for
|
|
83
|
+
* what a key was given. Three limits hold whatever it was given: a key never
|
|
84
|
+
* reads a secret's value; never makes a key or an account; never changes its
|
|
85
|
+
* own rights or any key's -- no route under /api/ext/ reaches any of them.
|
|
86
|
+
*
|
|
87
|
+
* Who manages keys: whoever passes the gate (an administrator), from
|
|
88
|
+
* Settings, Access. A device (/c/) never reaches these routes; a key never
|
|
89
|
+
* makes a key.
|
|
90
|
+
*
|
|
91
|
+
* GET /api/apikeys {keys, scopes, defaultDays}
|
|
92
|
+
* POST /api/apikeys {label, scopes, conversations: {name: 'read'|'talk'}, days|null}
|
|
93
|
+
* -> {key, secret}: the secret this once
|
|
94
|
+
* POST /api/apikeys/<id>/conversations {conversation, level: 'read'|'talk'|null}: one given, changed, taken back
|
|
95
|
+
* POST /api/apikeys/<id>/scopes {scope, on: true|false}: one scope given or taken back afterwards (18-11)
|
|
96
|
+
* POST /api/apikeys/<id>/rooms {room, level: 'read'|'talk'|null}
|
|
97
|
+
* POST /api/apikeys/<id>/boxes {box, level: 'state'|'speak'|null}
|
|
98
|
+
* POST /api/apikeys/<id>/binders {binder, level: 'read'|'write'|null}
|
|
99
|
+
* (and on creation: rooms: {id: level}, boxes: {id: level}, binders: {id: level})
|
|
100
|
+
* POST /api/apikeys/<id>/revoke
|
|
101
|
+
* GET /api/apikeys/<id>/journal its last uses
|
|
102
|
+
*
|
|
103
|
+
* Authorization: Bearer clv_... on each of these:
|
|
104
|
+
* GET /api/ext/v1/status the state, as JSON
|
|
105
|
+
* GET /api/ext/v1/jobs (jobs) what it does: {running, done}, newest first, without their logs
|
|
106
|
+
* GET /api/ext/v1/jobs/<id> (jobs) that job, under way or done today, with its log [{at, text}] (404: unknown)
|
|
107
|
+
* GET /api/ext/v1/conversations those it may read: {conversations: [{id, name, level, chat}]}
|
|
108
|
+
* GET /api/ext/v1/conversations/<name>/messages ?last=1..200 (50) | ?since=<cursor>: {chat, messages, cursor}
|
|
109
|
+
* POST /api/ext/v1/conversations/<name>/messages {text}: posted in its chat, signed with the key's name
|
|
110
|
+
* POST /api/ext/v1/conversations/<name>/wake|sleep|stop (act) woken, put to sleep, its turn stopped (Escape)
|
|
111
|
+
* GET /api/ext/v1/rooms those it may read: {rooms: [{id, name, level, host, members}]}
|
|
112
|
+
* GET /api/ext/v1/rooms/<id>/messages as a conversation's: {messages, cursor}
|
|
113
|
+
* POST /api/ext/v1/rooms/<id>/messages {text, to?: [names of its AIs]}: posted in the room, signed with the key
|
|
114
|
+
* POST /api/ext/v1/rooms (create rooms) {name, conversations?: [ids], boxes?: [ids], host?: id}
|
|
115
|
+
* POST /api/ext/v1/rooms/<id> (manage) {name?, host?: id, add?: {conversations, boxes}, remove?: {conversations, boxes}}
|
|
116
|
+
* POST /api/ext/v1/rooms/<id>/remove (manage) the room removed
|
|
117
|
+
* GET /api/ext/v1/boxes {boxes: [{id, name, level, online, where, heardAt, volume}]}
|
|
118
|
+
* POST /api/ext/v1/boxes/<id>/say {text}: said aloud by the box
|
|
119
|
+
* GET /api/ext/v1/conversations/<name>/reminders (read) {reminders: [{id, text, cron, next}]}
|
|
120
|
+
* POST /api/ext/v1/conversations/<name>/reminders (talk) {text, at: "2026-11-20 09:00" | cron: "0 9 * * 1"}
|
|
121
|
+
* POST /api/ext/v1/conversations/<name>/reminders/<id>/cancel (act) taken back
|
|
122
|
+
* GET /api/ext/v1/binders {binders: [{id, title, level, states, fields, count}]}
|
|
123
|
+
* GET /api/ext/v1/binders/<list>/records ?state=&archived=1: {records}
|
|
124
|
+
* GET /api/ext/v1/binders/<list>/records/<id> {record}: with its notes
|
|
125
|
+
* POST /api/ext/v1/binders/<list>/records (write) {title, description?, state?, fields?, due?}
|
|
126
|
+
* POST /api/ext/v1/binders/<list>/records/<id> (write) {title?, description?, fields?, due?}
|
|
127
|
+
* POST /api/ext/v1/binders/<list>/records/<id>/move (write) {state}: never past a gate a person did not tick
|
|
128
|
+
* POST /api/ext/v1/binders/<list>/records/<id>/notes (write) {text}
|
|
129
|
+
* POST /api/ext/v1/binders/<list>/records/<id>/archive|restore (write)
|
|
130
|
+
* POST /api/ext/mcp the same as MCP tools (clavarium_status, clavarium_jobs, clavarium_job_log, clavarium_conversations,
|
|
131
|
+
* clavarium_read, clavarium_say, clavarium_rooms, clavarium_room_read,
|
|
132
|
+
* clavarium_room_say, clavarium_boxes, clavarium_box_say, clavarium_conversation_wake,
|
|
133
|
+
* clavarium_conversation_sleep, clavarium_conversation_stop, clavarium_room_create,
|
|
134
|
+
* clavarium_room_change, clavarium_room_remove, clavarium_reminders, clavarium_remind,
|
|
135
|
+
* clavarium_reminder_cancel, clavarium_binders, clavarium_binder_records,
|
|
136
|
+
* clavarium_binder_record, clavarium_binder_add, clavarium_binder_edit,
|
|
137
|
+
* clavarium_binder_move, clavarium_binder_note, clavarium_binder_archive), JSON-RPC over HTTP
|
|
138
|
+
* (Streamable HTTP, stateless, JSON answers; also at /api/ext/v1/mcp). A tool
|
|
139
|
+
* that needs a scope (status, jobs, create rooms) is listed only to a key given it.
|
|
140
|
+
* 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.
|
|
141
|
+
*
|
|
142
|
+
* The front lets /api/ext/ through without sign-on, as it does /c/
|
|
143
|
+
* (deploy/install.sh, skip_auth_routes; deploy/updater.mjs for installs made
|
|
144
|
+
* before), and strips the identity headers there: nothing under /api/ext/
|
|
145
|
+
* ever looks at who the operator is, only at the key.
|
|
146
|
+
*/
|
|
147
|
+
import { randomBytes, randomUUID, createHash, timingSafeEqual } from 'node:crypto';
|
|
148
|
+
import { appendFileSync, readFileSync, writeFileSync, renameSync, statSync } from 'node:fs';
|
|
149
|
+
import { Refusal } from './conversations.mjs';
|
|
150
|
+
import { Grants, apiKeySubject } from './grants.mjs';
|
|
151
|
+
import { isConversationName } from './names.mjs';
|
|
152
|
+
import { masked, lookOf } from './rooms.mjs';
|
|
153
|
+
|
|
154
|
+
export const KEY_PREFIX = 'clv_';
|
|
155
|
+
export const DEFAULT_DAYS = 90;
|
|
156
|
+
export const DAYS_MAX = 3650;
|
|
157
|
+
export const KEYS_MAX = 50;
|
|
158
|
+
export const LABEL_MAX = 40;
|
|
159
|
+
export const RATE_PER_MIN = 60;
|
|
160
|
+
/* All calls with a key nobody has, together. */
|
|
161
|
+
export const UNKNOWN_PER_MIN = 60;
|
|
162
|
+
const JOURNAL_MAX = 1024 * 1024;
|
|
163
|
+
const JOURNAL_SHOWN = 200;
|
|
164
|
+
/* The time a key was last used is written at most this often (it is known at once in memory). */
|
|
165
|
+
const USED_SAVE_MS = 60_000;
|
|
166
|
+
export const EXT_PREFIX = '/api/ext/';
|
|
167
|
+
|
|
168
|
+
/* The scopes a key may be given: [asset, rights] in the table. */
|
|
169
|
+
export const SCOPES = Object.freeze({ status: { asset: 'server:status', rights: 'r', label: 'Its state (memory, disk, versions)' },
|
|
170
|
+
jobs: { asset: 'server:jobs', rights: 'r', label: 'Jobs: read what Clavarium does and its logs' },
|
|
171
|
+
diagnostics: { asset: 'server:diagnostics', rights: 'r', label: 'Diagnostics: load, measure, logs' },
|
|
172
|
+
'create-rooms': { asset: 'server:rooms', rights: 'w', label: 'Create rooms' } });
|
|
173
|
+
/* What a key may do in one conversation: [rights in the table]. */
|
|
174
|
+
export const LEVELS = Object.freeze({ read: 'r', talk: 'rw', act: 'rwm' });
|
|
175
|
+
export const levelOf = (rights) => (String(rights).includes('m') ? 'act' : String(rights).includes('w') ? 'talk' : String(rights).includes('r') ? 'read' : null);
|
|
176
|
+
/* The messages one read gives, by default and at most. */
|
|
177
|
+
export const READ_DEFAULT = 50;
|
|
178
|
+
export const READ_MAX = 200;
|
|
179
|
+
export const SAY_MAX = 8000;
|
|
180
|
+
/* What a room and a voice box may be given: [rights in the table]. */
|
|
181
|
+
export const ROOM_LEVELS = Object.freeze({ read: 'r', talk: 'rw', manage: 'rwm' });
|
|
182
|
+
export const roomLevelOf = (rights) => (String(rights).includes('m') ? 'manage' : String(rights).includes('w') ? 'talk' : String(rights).includes('r') ? 'read' : null);
|
|
183
|
+
export const BOX_LEVELS = Object.freeze({ state: 'r', speak: 'rw' });
|
|
184
|
+
export const boxLevelOf = (rights) => (String(rights).includes('w') ? 'speak' : String(rights).includes('r') ? 'state' : null);
|
|
185
|
+
/* What a binder list may be given: Binder's own access words. */
|
|
186
|
+
export const BINDER_LEVELS = Object.freeze({ read: 'read', write: 'write' });
|
|
187
|
+
/* A reminder a key sets: a short text. */
|
|
188
|
+
export const REMINDER_MAX = 200;
|
|
189
|
+
/* A binder list's id, as Binder makes it. */
|
|
190
|
+
const LIST_ID = /^[a-z0-9][a-z0-9-]{0,99}$/;
|
|
191
|
+
/* Said aloud in the home: short, and a few a minute (per key and box). */
|
|
192
|
+
export const SPEAK_MAX = 300;
|
|
193
|
+
export const SPEAK_PER_MIN = 3;
|
|
194
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
195
|
+
|
|
196
|
+
const digest = (text) => createHash('sha256').update(text).digest();
|
|
197
|
+
const oneLine = (value) => typeof value === 'string' && value.trim() !== '' && value.trim().length <= LABEL_MAX
|
|
198
|
+
&& ![...value].some((c) => { const p = c.codePointAt(0); return p < 0x20 || (p >= 0x7f && p < 0xa0) || (p >= 0x200b && p <= 0x200f) || (p >= 0x202a && p <= 0x202e); });
|
|
199
|
+
const SECRET = /^clv_[A-Za-z0-9_-]{43}$/;
|
|
200
|
+
|
|
201
|
+
export class ApiKeys {
|
|
202
|
+
#store; #grants; #now; #journal; #exists; #kinds; #binders;
|
|
203
|
+
#used = new Map(); /* id -> { at, savedAt } */
|
|
204
|
+
#calls = new Map(); /* id ('' for unknown keys) -> [times of the last minute] */
|
|
205
|
+
|
|
206
|
+
/* `exists(name)`: whether a conversation is there (one is given only then); `roomExists(id)`,
|
|
207
|
+
`boxExists(id)`: the same for a room, a voice box (none, without them). `binders`: Binder's lists, as a person
|
|
208
|
+
sees them -- { lists() -> [{ id, title, archived, grants }], grant(list, subject, level | null, who) } (none, without). */
|
|
209
|
+
constructor({ store, grants = new Grants(), journal = null, now = () => Date.now(), exists = () => true, roomExists = () => false, boxExists = () => false, binders = null }) {
|
|
210
|
+
this.#store = store; this.#grants = grants; this.#journal = journal; this.#now = now; this.#exists = exists; this.#binders = binders;
|
|
211
|
+
/* What is given one by one: its asset type, its levels, a valid name, whether it is there, its words. */
|
|
212
|
+
this.#kinds = {
|
|
213
|
+
room: { levels: ROOM_LEVELS, of: roomLevelOf, valid: (v) => typeof v === 'string' && UUID.test(v), exists: roomExists, what: 'room', the: 'a room' },
|
|
214
|
+
box: { levels: BOX_LEVELS, of: boxLevelOf, valid: (v) => typeof v === 'string' && UUID.test(v), exists: boxExists, what: 'voice box', the: 'a voice box' },
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
#scopesOf(id) { return Object.entries(SCOPES).filter(([, s]) => this.#grants.can(apiKeySubject(id), s.asset, s.rights)).map(([name]) => name); }
|
|
219
|
+
#shown(k) {
|
|
220
|
+
const used = this.#used.get(k.name)?.at ?? k.usedAt ?? null;
|
|
221
|
+
return { id: k.name, label: k.label, scopes: this.#scopesOf(k.name), conversations: this.conversationsOf(k.name), rooms: this.roomsOf(k.name), boxes: this.boxesOf(k.name), binders: this.bindersOf(k.name), createdBy: k.createdBy ?? null, createdAt: k.createdAt, expiresAt: k.expiresAt ?? null,
|
|
222
|
+
usedAt: used, expired: Boolean(k.expiresAt && Date.parse(k.expiresAt) <= this.#now()) };
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/* Every key, newest first: never a secret, nor its hash. */
|
|
226
|
+
list() { return this.#store.all().map((k) => this.#shown(k)).sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt))); }
|
|
227
|
+
scopes() { return Object.entries(SCOPES).map(([id, s]) => ({ id, label: s.label })); }
|
|
228
|
+
|
|
229
|
+
/* The conversations a key was given, each with its level: [{ name, level }]. */
|
|
230
|
+
conversationsOf(id) {
|
|
231
|
+
return this.#grants.of(apiKeySubject(id), 'conversation').map((g) => ({ name: g.name, level: levelOf(g.rights) })).filter((c) => c.level)
|
|
232
|
+
.sort((a, b) => a.name.localeCompare(b.name));
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/* The rooms, the voice boxes a key was given, each with its level: [{ id, level }] -- only those still there. */
|
|
236
|
+
#givenOf(id, type) {
|
|
237
|
+
const k = this.#kinds[type];
|
|
238
|
+
return this.#grants.of(apiKeySubject(id), type).map((g) => ({ id: g.name, level: k.of(g.rights) })).filter((x) => x.level && k.exists(x.id))
|
|
239
|
+
.sort((a, b) => a.id.localeCompare(b.id));
|
|
240
|
+
}
|
|
241
|
+
roomsOf(id) { return this.#givenOf(id, 'room'); }
|
|
242
|
+
boxesOf(id) { return this.#givenOf(id, 'box'); }
|
|
243
|
+
#oneAsked(type, ref, level) {
|
|
244
|
+
const k = this.#kinds[type];
|
|
245
|
+
if (!k.valid(ref) || !k.exists(ref)) throw new Refusal(404, `No such ${k.what}.`);
|
|
246
|
+
if (level !== null && !Object.hasOwn(k.levels, level)) throw new Refusal(400, `${k.the[0].toUpperCase()}${k.the.slice(1)} is given at one of: ${Object.keys(k.levels).join(', ')}.`);
|
|
247
|
+
}
|
|
248
|
+
#givenAll(type, given) {
|
|
249
|
+
if (!given || typeof given !== 'object' || Array.isArray(given)) throw new Refusal(400, `${type === 'room' ? 'Rooms' : 'Voice boxes'} are given by id: {id: level}.`);
|
|
250
|
+
for (const [ref, level] of Object.entries(given)) this.#oneAsked(type, ref, level);
|
|
251
|
+
}
|
|
252
|
+
/* One room or voice box given to a key, its level changed, or taken back (level null). */
|
|
253
|
+
#setOne(type, id, ref, level) {
|
|
254
|
+
if (typeof id !== 'string' || !this.#store.get(id)) throw new Refusal(404, 'No such key.');
|
|
255
|
+
this.#oneAsked(type, ref, level);
|
|
256
|
+
if (level === null) this.#grants.take(apiKeySubject(id), `${type}:${ref}`);
|
|
257
|
+
else this.#grants.give(apiKeySubject(id), `${type}:${ref}`, this.#kinds[type].levels[level]);
|
|
258
|
+
return this.get(id);
|
|
259
|
+
}
|
|
260
|
+
setRoom(id, room, level) { return this.#setOne('room', id, room, level); }
|
|
261
|
+
setBox(id, box, level) { return this.#setOne('box', id, box, level); }
|
|
262
|
+
|
|
263
|
+
/* ITS BINDER LISTS: kept in Binder, on each list (see above). Archived lists are not given (nor shown). */
|
|
264
|
+
#lists() { try { return (this.#binders?.lists() ?? []).filter((l) => l && typeof l.id === 'string'); } catch { return []; } }
|
|
265
|
+
bindersOf(id) {
|
|
266
|
+
const subject = apiKeySubject(id);
|
|
267
|
+
return this.#lists().filter((l) => !l.archived && Object.hasOwn(BINDER_LEVELS, l.grants?.[subject] ?? '')).map((l) => ({ id: l.id, level: l.grants[subject] }))
|
|
268
|
+
.sort((a, b) => a.id.localeCompare(b.id));
|
|
269
|
+
}
|
|
270
|
+
#binderAsked(list, level) {
|
|
271
|
+
if (!this.#binders || typeof list !== 'string' || !LIST_ID.test(list) || !this.#lists().some((l) => l.id === list && !l.archived)) throw new Refusal(404, 'No such binder.');
|
|
272
|
+
if (level !== null && !Object.hasOwn(BINDER_LEVELS, level)) throw new Refusal(400, `A binder is given at one of: ${Object.keys(BINDER_LEVELS).join(', ')}.`);
|
|
273
|
+
}
|
|
274
|
+
/* One list given to a key, its level changed, or taken back (level null). `who`: the person, as Binder's history says it. */
|
|
275
|
+
setBinder(id, list, level, who = '') {
|
|
276
|
+
if (typeof id !== 'string' || !this.#store.get(id)) throw new Refusal(404, 'No such key.');
|
|
277
|
+
this.#binderAsked(list, level);
|
|
278
|
+
this.#binders.grant(list, apiKeySubject(id), level, who);
|
|
279
|
+
return this.get(id);
|
|
280
|
+
}
|
|
281
|
+
/* Whether a key (already checked) may read ('read') or change ('write') one list; 403 if not -- the same for one
|
|
282
|
+
not given, archived, or not there. */
|
|
283
|
+
mayBinder(id, list, level = 'read') {
|
|
284
|
+
const l = typeof list === 'string' && LIST_ID.test(list) ? this.#lists().find((x) => x.id === list && !x.archived) : undefined;
|
|
285
|
+
const has = l?.grants?.[apiKeySubject(id)];
|
|
286
|
+
if (!Object.hasOwn(BINDER_LEVELS, has ?? '')) throw Object.assign(new Refusal(403, 'This key was not given this binder.'), { key: id });
|
|
287
|
+
if (level === 'write' && has !== 'write') throw Object.assign(new Refusal(403, 'This key may read this binder, not change it.'), { key: id });
|
|
288
|
+
return has;
|
|
289
|
+
}
|
|
290
|
+
binderTitle(list) { return this.#lists().find((l) => l.id === list)?.title ?? list; }
|
|
291
|
+
/* Who the key is to Binder: an agent, signed with its name -- never a person (a person approves, deletes, gives). */
|
|
292
|
+
binderWho(id) { const k = this.#store.get(id); return k ? { id: apiKeySubject(id), kind: 'agent', name: k.label } : null; }
|
|
293
|
+
|
|
294
|
+
#conversationAsked(name, level) {
|
|
295
|
+
if (!isConversationName(name) || !this.#exists(name)) throw new Refusal(404, 'No such conversation.');
|
|
296
|
+
if (level !== null && !Object.hasOwn(LEVELS, level)) throw new Refusal(400, `A conversation is given to read, to talk or to act: ${Object.keys(LEVELS).join(', ')}.`);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/* One conversation given to a key, its level changed, or taken back (level null). */
|
|
300
|
+
setConversation(id, name, level) {
|
|
301
|
+
if (typeof id !== 'string' || !this.#store.get(id)) throw new Refusal(404, 'No such key.');
|
|
302
|
+
this.#conversationAsked(name, level);
|
|
303
|
+
if (level === null) this.#grants.take(apiKeySubject(id), `conversation:${name}`);
|
|
304
|
+
else this.#grants.give(apiKeySubject(id), `conversation:${name}`, LEVELS[level]);
|
|
305
|
+
return this.get(id);
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/* One scope of the server given to a key afterwards, or taken back (18-11: the owner, rather than a new key). */
|
|
309
|
+
setScope(id, scope, on) {
|
|
310
|
+
if (typeof id !== 'string' || !this.#store.get(id)) throw new Refusal(404, 'No such key.');
|
|
311
|
+
if (!Object.hasOwn(SCOPES, scope)) throw new Refusal(400, `Scopes are among: ${Object.keys(SCOPES).join(', ')}.`);
|
|
312
|
+
if (on === true) this.#grants.give(apiKeySubject(id), SCOPES[scope].asset, SCOPES[scope].rights);
|
|
313
|
+
else if (on === false) this.#grants.take(apiKeySubject(id), SCOPES[scope].asset);
|
|
314
|
+
else throw new Refusal(400, 'on: true or false.');
|
|
315
|
+
return this.get(id);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/* A new key: its secret is in the answer, this once. `days`: its life (null: it does not expire).
|
|
319
|
+
`conversations`: { name: 'read' | 'talk' }, each named -- there is no "all". */
|
|
320
|
+
create({ label, scopes = [], conversations = {}, rooms = {}, boxes = {}, binders = {}, days = DEFAULT_DAYS } = {}, who = '') {
|
|
321
|
+
if (!oneLine(label)) throw new Refusal(400, `A key has a name: one line, ${LABEL_MAX} characters at most.`);
|
|
322
|
+
if (!Array.isArray(scopes) || scopes.some((s) => !Object.hasOwn(SCOPES, s))) throw new Refusal(400, `Scopes are among: ${Object.keys(SCOPES).join(', ')}.`);
|
|
323
|
+
if (!conversations || typeof conversations !== 'object' || Array.isArray(conversations)) throw new Refusal(400, 'Conversations are given by name: {name: "read" | "talk"}.');
|
|
324
|
+
for (const [name, level] of Object.entries(conversations)) this.#conversationAsked(name, level);
|
|
325
|
+
this.#givenAll('room', rooms); this.#givenAll('box', boxes);
|
|
326
|
+
if (!binders || typeof binders !== 'object' || Array.isArray(binders)) throw new Refusal(400, 'Binders are given by id: {id: level}.');
|
|
327
|
+
for (const [list, level] of Object.entries(binders)) this.#binderAsked(list, level);
|
|
328
|
+
if (days !== null && !(Number.isInteger(days) && days >= 1 && days <= DAYS_MAX)) throw new Refusal(400, `A key lasts 1 to ${DAYS_MAX} days, or does not expire.`);
|
|
329
|
+
if (this.#store.all().length >= KEYS_MAX) throw new Refusal(409, `At most ${KEYS_MAX} keys: revoke one first.`);
|
|
330
|
+
const name = label.trim();
|
|
331
|
+
if (this.#store.all().some((k) => k.label.toLowerCase() === name.toLowerCase())) throw new Refusal(409, 'A key has this name already: one name per use.');
|
|
332
|
+
const id = randomUUID();
|
|
333
|
+
const secret = `${KEY_PREFIX}${randomBytes(32).toString('base64url')}`;
|
|
334
|
+
const now = this.#now();
|
|
335
|
+
const record = { name: id, label: name, hash: digest(secret).toString('hex'), createdAt: new Date(now).toISOString(),
|
|
336
|
+
...(who ? { createdBy: String(who).slice(0, 120) } : {}), expiresAt: days === null ? null : new Date(now + days * 86_400_000).toISOString() };
|
|
337
|
+
this.#store.put(record);
|
|
338
|
+
for (const s of new Set(scopes)) this.#grants.give(apiKeySubject(id), SCOPES[s].asset, SCOPES[s].rights);
|
|
339
|
+
for (const [name, level] of Object.entries(conversations)) if (level !== null) this.#grants.give(apiKeySubject(id), `conversation:${name}`, LEVELS[level]);
|
|
340
|
+
for (const [ref, level] of Object.entries(rooms)) if (level !== null) this.#grants.give(apiKeySubject(id), `room:${ref}`, ROOM_LEVELS[level]);
|
|
341
|
+
for (const [ref, level] of Object.entries(boxes)) if (level !== null) this.#grants.give(apiKeySubject(id), `box:${ref}`, BOX_LEVELS[level]);
|
|
342
|
+
for (const [list, level] of Object.entries(binders)) if (level !== null) this.#binders.grant(list, apiKeySubject(id), level, who);
|
|
343
|
+
return { key: this.#shown(record), secret };
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/* At once: the next call with it is refused. */
|
|
347
|
+
revoke(id) {
|
|
348
|
+
if (typeof id !== 'string' || !this.#store.get(id)) throw new Refusal(404, 'No such key.');
|
|
349
|
+
this.#store.remove(id);
|
|
350
|
+
this.#grants.forgetSubject(apiKeySubject(id));
|
|
351
|
+
for (const l of this.#lists()) if (l.grants?.[apiKeySubject(id)]) { try { this.#binders.grant(l.id, apiKeySubject(id), null); } catch { /* gone already */ } }
|
|
352
|
+
this.#used.delete(id); this.#calls.delete(id);
|
|
353
|
+
for (const c of [...this.#calls.keys()]) if (c.startsWith(`speak:${id}:`)) this.#calls.delete(c);
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
get(id) { const k = this.#store.get(id); return k ? this.#shown(k) : undefined; }
|
|
357
|
+
|
|
358
|
+
/* The key a secret is, or undefined -- every key compared, in constant time each. */
|
|
359
|
+
#find(secret) {
|
|
360
|
+
if (typeof secret !== 'string' || !SECRET.test(secret)) return undefined;
|
|
361
|
+
const asked = digest(secret);
|
|
362
|
+
let found;
|
|
363
|
+
for (const k of this.#store.all()) {
|
|
364
|
+
if (typeof k.hash !== 'string' || !/^[0-9a-f]{64}$/.test(k.hash)) continue;
|
|
365
|
+
if (timingSafeEqual(Buffer.from(k.hash, 'hex'), asked) && found === undefined) found = k;
|
|
366
|
+
}
|
|
367
|
+
return found;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
#counted(who, max) {
|
|
371
|
+
const now = this.#now();
|
|
372
|
+
const recent = (this.#calls.get(who) ?? []).filter((t) => now - t < 60_000);
|
|
373
|
+
if (recent.length >= max) { this.#calls.set(who, recent); return Math.max(1, Math.ceil((recent[0] + 60_000 - now) / 1000)); }
|
|
374
|
+
recent.push(now); this.#calls.set(who, recent);
|
|
375
|
+
return 0;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/* WHO ASKS, from the Authorization header, and may it read `scope`? Returns the key's id, or throws:
|
|
379
|
+
401 no key, or one nobody has (unknown, revoked, expired); 429 too many calls; 403 not this scope. */
|
|
380
|
+
check(authorization, scope) {
|
|
381
|
+
const m = /^Bearer\s+(\S+)\s*$/i.exec(String(authorization ?? ''));
|
|
382
|
+
if (!m) throw Object.assign(new Refusal(401, 'An API key is needed: Authorization: Bearer clv_...'), { key: null });
|
|
383
|
+
const k = this.#find(m[1]);
|
|
384
|
+
if (!k || (k.expiresAt && Date.parse(k.expiresAt) <= this.#now())) {
|
|
385
|
+
const wait = this.#counted('', UNKNOWN_PER_MIN);
|
|
386
|
+
if (wait) throw Object.assign(new Refusal(429, 'Too many calls with keys that are not valid. Wait a minute.'), { key: null, retry: wait });
|
|
387
|
+
throw Object.assign(new Refusal(401, 'This API key is not valid: unknown, revoked or expired.'), { key: k?.name ?? null });
|
|
388
|
+
}
|
|
389
|
+
const wait = this.#counted(k.name, RATE_PER_MIN);
|
|
390
|
+
if (wait) throw Object.assign(new Refusal(429, `Too many calls: ${RATE_PER_MIN} a minute per key.`), { key: k.name, retry: wait });
|
|
391
|
+
this.#seen(k.name);
|
|
392
|
+
if (scope !== undefined && !this.#scopesOf(k.name).includes(scope)) throw Object.assign(new Refusal(403, `This key was not given the scope "${SCOPES[scope]?.label ?? scope}".`), { key: k.name });
|
|
393
|
+
return k.name;
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/* Whether a key (already checked) has a scope. */
|
|
397
|
+
may(id, scope) { return this.#scopesOf(id).includes(scope); }
|
|
398
|
+
|
|
399
|
+
/* Whether a key (already checked) may read ('read') or talk in ('talk') one conversation; throws 403
|
|
400
|
+
if not -- the same answer for a conversation not given and one that is not there. */
|
|
401
|
+
mayConversation(id, name, level = 'read') {
|
|
402
|
+
const rights = isConversationName(name) ? this.#grants.rightsOf(apiKeySubject(id), `conversation:${name}`) : '';
|
|
403
|
+
if (!rights.includes('r')) throw Object.assign(new Refusal(403, 'This key was not given this conversation.'), { key: id });
|
|
404
|
+
if (level === 'talk' && !rights.includes('w')) throw Object.assign(new Refusal(403, 'This key may read this conversation, not talk in it.'), { key: id });
|
|
405
|
+
if (level === 'act' && !rights.includes('m')) throw Object.assign(new Refusal(403, 'This key may not act on this conversation (wake, sleep, stop).'), { key: id });
|
|
406
|
+
return levelOf(rights);
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/* Whether a key (already checked) may read ('read') or post in ('talk') one room; 403 if not, the same for one
|
|
410
|
+
not given and one not there. */
|
|
411
|
+
mayRoom(id, room, level = 'read') {
|
|
412
|
+
const rights = typeof room === 'string' && UUID.test(room) && this.#kinds.room.exists(room) ? this.#grants.rightsOf(apiKeySubject(id), `room:${room}`) : '';
|
|
413
|
+
if (!rights.includes('r')) throw Object.assign(new Refusal(403, 'This key was not given this room.'), { key: id });
|
|
414
|
+
if (level === 'talk' && !rights.includes('w')) throw Object.assign(new Refusal(403, 'This key may read this room, not talk in it.'), { key: id });
|
|
415
|
+
if (level === 'manage' && !rights.includes('m')) throw Object.assign(new Refusal(403, 'This key may not manage this room.'), { key: id });
|
|
416
|
+
return roomLevelOf(rights);
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/* A ROOM THE KEY MADE ITSELF (with "create rooms") is given to it at "manage". This is the one right a key ever
|
|
420
|
+
gets on its own, and it is not a key changing its rights: it is scoped to what it created, and nothing else
|
|
421
|
+
of this key or any other changes -- a room made by another, a conversation, a box, a scope stay as they were. */
|
|
422
|
+
madeRoom(id, room) {
|
|
423
|
+
if (!this.may(id, 'create-rooms')) throw Object.assign(new Refusal(403, `This key was not given the scope "${SCOPES['create-rooms'].label}".`), { key: id });
|
|
424
|
+
if (typeof room !== 'string' || !UUID.test(room) || !this.#kinds.room.exists(room)) throw new Refusal(404, 'No such room.');
|
|
425
|
+
this.#grants.give(apiKeySubject(id), `room:${room}`, ROOM_LEVELS.manage);
|
|
426
|
+
}
|
|
427
|
+
/* Whether a key may see the state of ('state') or make speak ('speak') one voice box; 403 if not. */
|
|
428
|
+
mayBox(id, box, level = 'state') {
|
|
429
|
+
const rights = typeof box === 'string' && UUID.test(box) && this.#kinds.box.exists(box) ? this.#grants.rightsOf(apiKeySubject(id), `box:${box}`) : '';
|
|
430
|
+
if (!rights.includes('r')) throw Object.assign(new Refusal(403, 'This key was not given this voice box.'), { key: id });
|
|
431
|
+
if (level === 'speak' && !rights.includes('w')) throw Object.assign(new Refusal(403, 'This key may see this voice box, not make it speak.'), { key: id });
|
|
432
|
+
return boxLevelOf(rights);
|
|
433
|
+
}
|
|
434
|
+
/* One sentence said aloud, counted: SPEAK_PER_MIN a minute for this key and box, then 429. */
|
|
435
|
+
speakCounted(id, box) {
|
|
436
|
+
const wait = this.#counted(`speak:${id}:${box}`, SPEAK_PER_MIN);
|
|
437
|
+
if (wait) throw Object.assign(new Refusal(429, `Too many: ${SPEAK_PER_MIN} sentences a minute per voice box.`), { key: id, retry: wait });
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/* Its name, as its messages are signed in a chat (Parley's "by"). */
|
|
441
|
+
signature(id) { const k = this.#store.get(id); return k ? { id: apiKeySubject(id), name: k.label, kind: 'ai', place: 'API key' } : null; }
|
|
442
|
+
/* In a room: its name and its look (the letter and colour the page draws it with). */
|
|
443
|
+
roomSignature(id) { const s = this.signature(id); return s ? { ...s, look: lookOf(s.name) } : null; }
|
|
444
|
+
|
|
445
|
+
#seen(id) {
|
|
446
|
+
const now = this.#now();
|
|
447
|
+
const u = this.#used.get(id) ?? { at: null, savedAt: 0 };
|
|
448
|
+
u.at = new Date(now).toISOString();
|
|
449
|
+
if (now - u.savedAt >= USED_SAVE_MS) { u.savedAt = now; this.#store.patch(id, { usedAt: u.at }); }
|
|
450
|
+
this.#used.set(id, u);
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/* One line of the journal: never the secret -- only the id of the key, if it is one. */
|
|
454
|
+
note({ key = null, route, status, method = 'GET' }) {
|
|
455
|
+
if (!this.#journal) return;
|
|
456
|
+
const line = { at: new Date(this.#now()).toISOString(), key: typeof key === 'string' ? key : null, method: String(method).slice(0, 8), route: String(route ?? '').replace(/[^\x20-\x7e]/g, '?').slice(0, 120), status };
|
|
457
|
+
try {
|
|
458
|
+
appendFileSync(this.#journal, `${JSON.stringify(line)}\n`, { mode: 0o600 });
|
|
459
|
+
if (statSync(this.#journal).size > JOURNAL_MAX) {
|
|
460
|
+
const lines = readFileSync(this.#journal, 'utf8').split('\n').filter(Boolean);
|
|
461
|
+
writeFileSync(`${this.#journal}.tmp`, `${lines.slice(Math.floor(lines.length / 2)).join('\n')}\n`, { mode: 0o600 });
|
|
462
|
+
renameSync(`${this.#journal}.tmp`, this.#journal);
|
|
463
|
+
}
|
|
464
|
+
} catch { /* said nowhere: never a reason to fail the call */ }
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/* The last uses of one key, newest first. */
|
|
468
|
+
journal(id) {
|
|
469
|
+
if (!this.#store.get(id)) throw new Refusal(404, 'No such key.');
|
|
470
|
+
if (!this.#journal) return [];
|
|
471
|
+
let text = '';
|
|
472
|
+
try { text = readFileSync(this.#journal, 'utf8'); } catch { return []; }
|
|
473
|
+
const out = [];
|
|
474
|
+
for (const l of text.split('\n').reverse()) {
|
|
475
|
+
if (!l) continue;
|
|
476
|
+
try { const e = JSON.parse(l); if (e.key === id) out.push({ at: e.at, method: e.method, route: e.route, status: e.status }); } catch { /* a torn line */ }
|
|
477
|
+
if (out.length >= JOURNAL_SHOWN) break;
|
|
478
|
+
}
|
|
479
|
+
return out;
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/* THE STATE, as a key with "status" reads it. Only what is picked here, field by field: never what a
|
|
484
|
+
conversation says (its messages, its last words), nor a secret, a file or an address. */
|
|
485
|
+
export async function statusOf({ conversations, talk, health, answerer, capacity, history, platform, updates, components = {} }) {
|
|
486
|
+
const needs = (c) => {
|
|
487
|
+
const t = talk?.brief(c.name);
|
|
488
|
+
const asks = Boolean(t && (t.needs ?? (t.waiting > 0 || t.state === 'waiting')));
|
|
489
|
+
const h = health?.of(c.name);
|
|
490
|
+
const unwell = c.phase === 'ready' && (h?.problems ?? []).some((p) => p.level === 'bad' && !(h.seen ?? []).includes(p.key));
|
|
491
|
+
return { asks: asks || Boolean(answerer?.of(c.name)?.needs) || c.phase === 'failed' || unwell, working: t?.state === 'working' };
|
|
492
|
+
};
|
|
493
|
+
const list = (conversations?.list() ?? []).map((c) => {
|
|
494
|
+
const n = needs(c);
|
|
495
|
+
const state = c.asleep === true ? 'asleep' : n.asks ? 'needs-you' : n.working ? 'working' : 'awake';
|
|
496
|
+
return { id: c.name, name: typeof c.title === 'string' && c.title ? c.title : c.name, state, phase: String(c.phase ?? ''), tool: String(c.toolLabel ?? c.tool ?? '') };
|
|
497
|
+
});
|
|
498
|
+
const brief = capacity ? await capacity.brief().catch(() => null) : null;
|
|
499
|
+
const room = capacity ? await capacity.room().catch(() => null) : null;
|
|
500
|
+
const cpu = (() => { const v = history?.series('server', '1h').cpu ?? []; for (let i = v.length - 1; i >= 0; i -= 1) if (v[i] !== null && v[i] !== undefined) return v[i]; return null; })();
|
|
501
|
+
const part = (x) => (x ? { usedPercent: x.usedPercent ?? null, freeMb: x.freeMb ?? null, high: Boolean(x.high) } : null);
|
|
502
|
+
let update = null;
|
|
503
|
+
try { const u = updates?.about(); if (u?.installed) update = { channel: u.channel ?? null, available: u.available ?? null }; } catch { /* not said */ }
|
|
504
|
+
return {
|
|
505
|
+
at: new Date().toISOString(),
|
|
506
|
+
server: { known: Boolean(brief?.known), memory: part(brief?.memory), disk: part(brief?.disk), cpu: { usedPercent: cpu, cores: room?.cpu?.cores ?? null } },
|
|
507
|
+
conversations: list,
|
|
508
|
+
counts: Object.fromEntries(['awake', 'working', 'needs-you', 'asleep'].map((s) => [s, list.filter((c) => c.state === s).length])),
|
|
509
|
+
versions: { clavarium: platform?.version ?? null, ...components, ...(update ? { update } : {}) },
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/* ---- the door for programs: /api/ext/ ---- */
|
|
514
|
+
|
|
515
|
+
/* A CONVERSATION'S THREAD as a key reads it: the messages of the person and of the AI, field by field --
|
|
516
|
+
its words, who said it, when; a file by its name only. Never the machine's own lines, a path, nor
|
|
517
|
+
anything the page keeps for itself. `read`: what talk.of gives. */
|
|
518
|
+
const TEXT_MAX = 20_000;
|
|
519
|
+
const fileName = (p) => String(p ?? '').split('/').filter(Boolean).at(-1)?.slice(0, 120) ?? '';
|
|
520
|
+
export function threadOf(read) {
|
|
521
|
+
if (!read?.on) return { chat: false, messages: [], cursor: null };
|
|
522
|
+
const messages = (Array.isArray(read.messages) ? read.messages : []).filter((m) => m && (m.from === 'person' || m.from === 'agent')).map((m) => {
|
|
523
|
+
const files = [...(Array.isArray(m.files) ? m.files.map((f) => fileName(f?.name || f?.path)) : []), ...(m.kind === 'show' && m.path ? [fileName(m.path)] : [])].filter(Boolean).slice(0, 12);
|
|
524
|
+
const choices = Array.isArray(m.choices) ? m.choices.filter((c) => typeof c === 'string').slice(0, 8).map((c) => c.slice(0, 200)) : [];
|
|
525
|
+
return { id: String(m.id ?? '').slice(0, 80), at: String(m.at ?? '').slice(0, 40), from: m.from, kind: String(m.kind ?? 'say').slice(0, 20),
|
|
526
|
+
text: typeof m.text === 'string' ? m.text.slice(0, TEXT_MAX) : '', ...(typeof m.by?.name === 'string' && m.by.name ? { by: m.by.name.slice(0, 80) } : {}),
|
|
527
|
+
...(choices.length ? { choices } : {}), ...(files.length ? { files } : {}) };
|
|
528
|
+
});
|
|
529
|
+
return { chat: true, messages, cursor: typeof read.cursor === 'string' ? read.cursor : null };
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
/* A ROOM'S THREAD as a key reads it, as the page reads it: who said it by NAME (the person, an AI, a box, a key),
|
|
533
|
+
whom it is for by name, its words with any secret masked, a file by its name only. Never a member's id, a path,
|
|
534
|
+
nor what the page keeps for itself. `read`: what rooms.read gives. */
|
|
535
|
+
export function roomThreadOf(read) {
|
|
536
|
+
const messages = (Array.isArray(read?.messages) ? read.messages : []).filter((m) => m && (m.from === 'person' || m.from === 'agent')).map((m) => {
|
|
537
|
+
const files = [...(Array.isArray(m.files) ? m.files.map((f) => fileName(f?.name || f?.path)) : []), ...(m.kind === 'show' && m.path ? [fileName(m.path)] : [])].filter(Boolean).slice(0, 12);
|
|
538
|
+
const choices = Array.isArray(m.choices) ? m.choices.filter((c) => typeof c === 'string').slice(0, 8).map((c) => masked(c).slice(0, 200)) : [];
|
|
539
|
+
const to = Array.isArray(m.toNames) ? m.toNames.filter((x) => typeof x === 'string' && !UUID.test(x)).slice(0, 20).map((x) => x.slice(0, 80)) : [];
|
|
540
|
+
/* No name: the person (the room's own side), as in a conversation's thread. */
|
|
541
|
+
const by = typeof m.by?.name === 'string' && m.by.name ? m.by.name.slice(0, 80) : '';
|
|
542
|
+
return { id: String(m.id ?? '').slice(0, 80), at: String(m.at ?? '').slice(0, 40), from: m.from, kind: String(m.kind ?? 'say').slice(0, 20),
|
|
543
|
+
text: typeof m.text === 'string' ? masked(m.text).slice(0, TEXT_MAX) : '', ...(by ? { by } : {}),
|
|
544
|
+
...(to.length ? { to } : {}), ...(m.toYou ? { toPerson: true } : {}), ...(choices.length ? { choices } : {}), ...(files.length ? { files } : {}) };
|
|
545
|
+
});
|
|
546
|
+
return { messages, cursor: typeof read?.cursor === 'string' ? read.cursor : null };
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/* What a read asks for: the newest `last` (READ_DEFAULT; READ_MAX at most), or what came `since` a cursor. */
|
|
550
|
+
export function readPart(get) {
|
|
551
|
+
const last = Number(get('last') ?? READ_DEFAULT);
|
|
552
|
+
const since = get('since');
|
|
553
|
+
if (!Number.isInteger(last) || last < 1 || last > READ_MAX) throw new Refusal(400, `last: 1 to ${READ_MAX}.`);
|
|
554
|
+
if (since !== null && since !== undefined && (typeof since !== 'string' || !/^[0-9A-Za-z.~-]{1,80}$/.test(since))) throw new Refusal(400, 'since: a cursor given by a read before.');
|
|
555
|
+
return { last: String(last), ...(since ? { since } : {}) };
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/* A job's id, as jobs.mjs makes it (its conversation and when it started). */
|
|
559
|
+
const JOB_ID = /^[A-Za-z0-9_-]{1,120}$/;
|
|
560
|
+
const MCP_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05'];
|
|
561
|
+
const MCP_BODY_MAX = 64 * 1024;
|
|
562
|
+
const CONVERSATION_ARG = { type: 'string', description: 'The conversation\'s id, as clavarium_conversations gives it.' };
|
|
563
|
+
export const STATUS_TOOL = {
|
|
564
|
+
name: 'clavarium_status',
|
|
565
|
+
title: 'Clavarium status',
|
|
566
|
+
description: 'Read-only state of this Clavarium: server memory, disk and CPU; each conversation with its name and state (asleep, awake, working, needs-you); versions. No conversation content.',
|
|
567
|
+
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
568
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
569
|
+
};
|
|
570
|
+
export const JOBS_TOOL = {
|
|
571
|
+
name: 'clavarium_jobs',
|
|
572
|
+
title: 'Jobs of this Clavarium',
|
|
573
|
+
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.',
|
|
574
|
+
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
575
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
576
|
+
};
|
|
577
|
+
export const JOB_LOG_TOOL = {
|
|
578
|
+
name: 'clavarium_job_log',
|
|
579
|
+
title: 'Log of a job',
|
|
580
|
+
description: 'Read-only: one job, under way or done today, with its log (lines {at, text}).',
|
|
581
|
+
inputSchema: { type: 'object', properties: { id: { type: 'string', description: 'The job\'s id, as clavarium_jobs gives it.' } }, required: ['id'], additionalProperties: false },
|
|
582
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
583
|
+
};
|
|
584
|
+
/* Diagnostics (18-11: to see the owner's server from here when it is slow, without the owner copying). */
|
|
585
|
+
export const LOAD_TOOL = {
|
|
586
|
+
name: 'clavarium_load',
|
|
587
|
+
title: 'Load of this Clavarium',
|
|
588
|
+
description: 'Read-only: what this server asked of the host, by 5-minute window (each kind of command, how many, the time), its own event loop delay (p50/p99/max ms) and processor time. The newest window first.',
|
|
589
|
+
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
590
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
591
|
+
};
|
|
592
|
+
export const PROFILE_TOOL = {
|
|
593
|
+
name: 'clavarium_profile',
|
|
594
|
+
title: 'What holds this Clavarium',
|
|
595
|
+
description: 'Read-only: this server sampled by its own profiler for a few seconds (2 to 30, 10 by default): the functions that took the most time themselves (self) and with what they called (total), idle, garbage collection, processor time. Waits that long.',
|
|
596
|
+
inputSchema: { type: 'object', properties: { seconds: { type: 'integer', minimum: 2, maximum: 30 } }, additionalProperties: false },
|
|
597
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: false, openWorldHint: false },
|
|
598
|
+
};
|
|
599
|
+
export const LOGS_TOOL = {
|
|
600
|
+
name: 'clavarium_logs',
|
|
601
|
+
title: 'Logs of this Clavarium',
|
|
602
|
+
description: 'Read-only: what one of the server\'s programs said over a span, as Settings reads it (secrets masked). source: clavarium (default), machines, updates, web, signin, tunnel, system. span: 10m (default), 1, 6, 24, 168 (hours) or boot. A big journal takes a while: {pending: true} means ask again in a moment.',
|
|
603
|
+
inputSchema: { type: 'object', properties: { source: { type: 'string' }, span: { type: 'string' } }, additionalProperties: false },
|
|
604
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
605
|
+
};
|
|
606
|
+
export const CONVERSATIONS_TOOL = {
|
|
607
|
+
name: 'clavarium_conversations',
|
|
608
|
+
title: 'Conversations of this key',
|
|
609
|
+
description: 'The conversations this key was given, each with its id, name, level (read, talk or act) and whether its chat is on.',
|
|
610
|
+
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
611
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
612
|
+
};
|
|
613
|
+
export const READ_TOOL = {
|
|
614
|
+
name: 'clavarium_read',
|
|
615
|
+
title: 'Read a conversation',
|
|
616
|
+
description: `The newest messages of one conversation's chat (person and AI), oldest first, with a cursor; give the cursor back as "since" for only what came after. ${READ_DEFAULT} by default, ${READ_MAX} at most.`,
|
|
617
|
+
inputSchema: { type: 'object', properties: { conversation: CONVERSATION_ARG, last: { type: 'integer', minimum: 1, maximum: READ_MAX }, since: { type: 'string' } }, required: ['conversation'], additionalProperties: false },
|
|
618
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
619
|
+
};
|
|
620
|
+
export const SAY_TOOL = {
|
|
621
|
+
name: 'clavarium_say',
|
|
622
|
+
title: 'Post a message in a conversation',
|
|
623
|
+
description: 'Post a message in one conversation\'s chat, as the person would; it is shown signed with this key\'s name. The conversation must have been given to this key to talk.',
|
|
624
|
+
inputSchema: { type: 'object', properties: { conversation: CONVERSATION_ARG, text: { type: 'string', minLength: 1, maxLength: SAY_MAX } }, required: ['conversation', 'text'], additionalProperties: false },
|
|
625
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
|
|
626
|
+
};
|
|
627
|
+
const ROOM_ARG = { type: 'string', description: 'The room\'s id, as clavarium_rooms gives it.' };
|
|
628
|
+
const BOX_ARG = { type: 'string', description: 'The voice box\'s id, as clavarium_boxes gives it.' };
|
|
629
|
+
export const ROOMS_TOOL = {
|
|
630
|
+
name: 'clavarium_rooms',
|
|
631
|
+
title: 'Rooms of this key',
|
|
632
|
+
description: 'The rooms this key was given, each with its id, name, level (read, talk or manage), its host and its members by name (with their id when this key was given them).',
|
|
633
|
+
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
634
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
635
|
+
};
|
|
636
|
+
export const ROOM_READ_TOOL = {
|
|
637
|
+
name: 'clavarium_room_read',
|
|
638
|
+
title: 'Read a room',
|
|
639
|
+
description: `The newest messages of one room's thread (the person, its AIs, its voice boxes, keys), oldest first, by names; secrets masked. A cursor as for clavarium_read. ${READ_DEFAULT} by default, ${READ_MAX} at most.`,
|
|
640
|
+
inputSchema: { type: 'object', properties: { room: ROOM_ARG, last: { type: 'integer', minimum: 1, maximum: READ_MAX }, since: { type: 'string' } }, required: ['room'], additionalProperties: false },
|
|
641
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
642
|
+
};
|
|
643
|
+
export const ROOM_SAY_TOOL = {
|
|
644
|
+
name: 'clavarium_room_say',
|
|
645
|
+
title: 'Post a message in a room',
|
|
646
|
+
description: 'Post a message in one room, as the person would: it goes to the room\'s host, or to the AIs named in "to" (their names, as clavarium_rooms gives them). Shown signed with this key\'s name. The room must have been given to this key to talk.',
|
|
647
|
+
inputSchema: { type: 'object', properties: { room: ROOM_ARG, text: { type: 'string', minLength: 1, maxLength: SAY_MAX }, to: { type: 'array', items: { type: 'string' }, maxItems: 20 } }, required: ['room', 'text'], additionalProperties: false },
|
|
648
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
|
|
649
|
+
};
|
|
650
|
+
export const BOXES_TOOL = {
|
|
651
|
+
name: 'clavarium_boxes',
|
|
652
|
+
title: 'Voice boxes of this key',
|
|
653
|
+
description: 'The voice boxes this key was given, each with its id, name, level (state or speak), whether it is online, where it speaks, when it last heard someone, and its volume. Nothing it heard.',
|
|
654
|
+
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
655
|
+
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
|
656
|
+
};
|
|
657
|
+
export const BOX_SAY_TOOL = {
|
|
658
|
+
name: 'clavarium_box_say',
|
|
659
|
+
title: 'Say a short text aloud on a voice box',
|
|
660
|
+
description: `Make one voice box say a short text aloud, in the home: ${SPEAK_MAX} characters at most, ${SPEAK_PER_MIN} a minute. It does not listen after. The box must have been given to this key to speak.`,
|
|
661
|
+
inputSchema: { type: 'object', properties: { box: BOX_ARG, text: { type: 'string', minLength: 1, maxLength: SPEAK_MAX } }, required: ['box', 'text'], additionalProperties: false },
|
|
662
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
|
|
663
|
+
};
|
|
664
|
+
/* To act on a conversation (level "act"), and to manage rooms (level "manage", or "create rooms"). */
|
|
665
|
+
const actTool = (act, title, description, destructive) => ({
|
|
666
|
+
name: `clavarium_conversation_${act}`, title, description: `${description} The conversation must have been given to this key to act.`,
|
|
667
|
+
inputSchema: { type: 'object', properties: { conversation: CONVERSATION_ARG }, required: ['conversation'], additionalProperties: false },
|
|
668
|
+
annotations: { readOnlyHint: false, destructiveHint: destructive, idempotentHint: true, openWorldHint: false },
|
|
669
|
+
});
|
|
670
|
+
export const WAKE_TOOL = actTool('wake', 'Wake a conversation', 'Wake one conversation\'s machine (asleep: it starts again; awake: nothing changes).', false);
|
|
671
|
+
export const SLEEP_TOOL = actTool('sleep', 'Put a conversation to sleep', 'Put one conversation\'s machine to sleep, as the owner\'s Sleep button does: its files and chat are kept.', false);
|
|
672
|
+
export const STOP_TOOL = actTool('stop', 'Stop a conversation\'s turn', 'Stop what one conversation\'s AI is doing now (its current turn, as Escape does); the conversation stays awake.', true);
|
|
673
|
+
const IDS = { type: 'array', items: { type: 'string' }, maxItems: 40 };
|
|
674
|
+
const MEMBERS_ARG = { type: 'object', properties: { conversations: { ...IDS, description: 'Conversation ids, as clavarium_conversations gives them.' }, boxes: { ...IDS, description: 'Voice box ids, as clavarium_boxes gives them.' } }, additionalProperties: false };
|
|
675
|
+
export const ROOM_CREATE_TOOL = {
|
|
676
|
+
name: 'clavarium_room_create',
|
|
677
|
+
title: 'Create a room',
|
|
678
|
+
description: 'Make a room with conversations (AIs) and voice boxes this key was given; one conversation at least, its host (the first by default). The room is then given to this key to manage. Needs the scope "Create rooms".',
|
|
679
|
+
inputSchema: { type: 'object', properties: { name: { type: 'string', minLength: 1, maxLength: 60 }, conversations: { ...IDS, minItems: 1, description: 'Conversation ids, as clavarium_conversations gives them.' }, boxes: { ...IDS, description: 'Voice box ids, as clavarium_boxes gives them.' }, host: CONVERSATION_ARG }, required: ['name', 'conversations'], additionalProperties: false },
|
|
680
|
+
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
|
|
681
|
+
};
|
|
682
|
+
export const ROOM_CHANGE_TOOL = {
|
|
683
|
+
name: 'clavarium_room_change',
|
|
684
|
+
title: 'Change a room',
|
|
685
|
+
description: 'Rename a room, add or take away members (only conversations and voice boxes this key was given), or change its host (one of its conversations). The room must have been given to this key to manage.',
|
|
686
|
+
inputSchema: { type: 'object', properties: { room: ROOM_ARG, name: { type: 'string', minLength: 1, maxLength: 60 }, host: CONVERSATION_ARG, add: MEMBERS_ARG, remove: MEMBERS_ARG }, required: ['room'], additionalProperties: false },
|
|
687
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
|
|
688
|
+
};
|
|
689
|
+
export const ROOM_REMOVE_TOOL = {
|
|
690
|
+
name: 'clavarium_room_remove',
|
|
691
|
+
title: 'Remove a room',
|
|
692
|
+
description: 'Remove one room and its thread, for good. The room must have been given to this key to manage.',
|
|
693
|
+
inputSchema: { type: 'object', properties: { room: ROOM_ARG }, required: ['room'], additionalProperties: false },
|
|
694
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
|
|
695
|
+
};
|
|
696
|
+
/* A conversation's reminders (its tool's Docket): seen at Read, set at Talk, taken back at Act. */
|
|
697
|
+
const tool = (name, title, description, properties, required, write, destructive = false) => ({ name, title, description,
|
|
698
|
+
inputSchema: { type: 'object', properties, required, additionalProperties: false },
|
|
699
|
+
annotations: { readOnlyHint: !write, destructiveHint: destructive, idempotentHint: !write, openWorldHint: false } });
|
|
700
|
+
export const REMINDERS_TOOL = tool('clavarium_reminders', 'Reminders of a conversation',
|
|
701
|
+
'The reminders set in one conversation\'s tool (its Docket): each with its id, text, cron line (if it recurs) and when it is next due. The conversation must have been given to this key, its chat on.',
|
|
702
|
+
{ conversation: CONVERSATION_ARG }, ['conversation'], false);
|
|
703
|
+
export const REMIND_TOOL = tool('clavarium_remind', 'Set a reminder in a conversation',
|
|
704
|
+
`Set a reminder for one conversation's AI: once at a time ("at": "2026-11-20 09:00", in this server's time zone) or recurring ("cron": "0 9 * * 1", Mondays at 9:00), with a short text (${REMINDER_MAX} characters at most). It wakes the AI when due. The conversation must have been given to this key to talk.`,
|
|
705
|
+
{ conversation: CONVERSATION_ARG, text: { type: 'string', minLength: 1, maxLength: REMINDER_MAX }, at: { type: 'string' }, cron: { type: 'string' } }, ['conversation', 'text'], true);
|
|
706
|
+
export const REMINDER_CANCEL_TOOL = tool('clavarium_reminder_cancel', 'Take back a reminder',
|
|
707
|
+
'Take back one reminder of a conversation, by its id (as clavarium_reminders gives it). The conversation must have been given to this key to act.',
|
|
708
|
+
{ conversation: CONVERSATION_ARG, reminder: { type: 'string' } }, ['conversation', 'reminder'], true, true);
|
|
709
|
+
const BINDER_ARG = { type: 'string', description: 'The binder list\'s id, as clavarium_binders gives it.' };
|
|
710
|
+
const RECORD_ARG = { type: 'string', description: 'The record\'s id, as clavarium_binder_records gives it.' };
|
|
711
|
+
const FIELDS_ARG = { type: 'object', description: 'Field values by field id or name, as clavarium_binders gives them; null clears one.', additionalProperties: { type: ['string', 'number', 'null'] } };
|
|
712
|
+
const DUE_ARG = { type: ['string', 'null'], description: 'A due date: "2026-11-20", or "2026-11-20 09:00"; null clears it.' };
|
|
713
|
+
export const BINDERS_TOOL = tool('clavarium_binders', 'Binders of this key',
|
|
714
|
+
'The binder lists this key was given, each with its id, title, level (read or write), its states (a gate is one only a person approves past) and its fields.', {}, [], false);
|
|
715
|
+
export const BINDER_RECORDS_TOOL = tool('clavarium_binder_records', 'Records of a binder',
|
|
716
|
+
'The records of one binder list, in the order of its states: id, title, state, fields, owners, due date. "state" keeps one state; "archived": true lists the archived ones instead.',
|
|
717
|
+
{ binder: BINDER_ARG, state: { type: 'string' }, archived: { type: 'boolean' } }, ['binder'], false);
|
|
718
|
+
export const BINDER_RECORD_TOOL = tool('clavarium_binder_record', 'Read a record',
|
|
719
|
+
'One record of a binder list, with its description and its notes.', { binder: BINDER_ARG, record: RECORD_ARG }, ['binder', 'record'], false);
|
|
720
|
+
export const BINDER_ADD_TOOL = tool('clavarium_binder_add', 'Add a record',
|
|
721
|
+
'Add a record to a binder list, signed with this key\'s name: a title, and a description, a state (not past a gate), fields, a due date. The list must have been given to this key to write.',
|
|
722
|
+
{ binder: BINDER_ARG, title: { type: 'string', minLength: 1, maxLength: 200 }, description: { type: 'string' }, state: { type: 'string' }, fields: FIELDS_ARG, due: DUE_ARG }, ['binder', 'title'], true);
|
|
723
|
+
export const BINDER_EDIT_TOOL = tool('clavarium_binder_edit', 'Change a record',
|
|
724
|
+
'Change a record\'s title, description, fields or due date. The list must have been given to this key to write.',
|
|
725
|
+
{ binder: BINDER_ARG, record: RECORD_ARG, title: { type: 'string', minLength: 1, maxLength: 200 }, description: { type: ['string', 'null'] }, fields: FIELDS_ARG, due: DUE_ARG }, ['binder', 'record'], true);
|
|
726
|
+
export const BINDER_MOVE_TOOL = tool('clavarium_binder_move', 'Move a record',
|
|
727
|
+
'Move a record to another state of its list. Past a gate, only a record a person approved: a key never approves. The list must have been given to this key to write.',
|
|
728
|
+
{ binder: BINDER_ARG, record: RECORD_ARG, state: { type: 'string', description: 'A state\'s id or name.' } }, ['binder', 'record', 'state'], true);
|
|
729
|
+
export const BINDER_NOTE_TOOL = tool('clavarium_binder_note', 'Add a note to a record',
|
|
730
|
+
'Add a note to a record, signed with this key\'s name. The list must have been given to this key to write.',
|
|
731
|
+
{ binder: BINDER_ARG, record: RECORD_ARG, text: { type: 'string', minLength: 1, maxLength: 2000 } }, ['binder', 'record', 'text'], true);
|
|
732
|
+
export const BINDER_ARCHIVE_TOOL = tool('clavarium_binder_archive', 'Archive a record',
|
|
733
|
+
'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.',
|
|
734
|
+
{ binder: BINDER_ARG, record: RECORD_ARG, restore: { type: 'boolean' } }, ['binder', 'record'], true);
|
|
735
|
+
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];
|
|
736
|
+
export const TOOLS = [STATUS_TOOL, JOBS_TOOL, JOB_LOG_TOOL, LOAD_TOOL, PROFILE_TOOL, LOGS_TOOL, CONVERSATIONS_TOOL, READ_TOOL, SAY_TOOL, WAKE_TOOL, SLEEP_TOOL, STOP_TOOL, REMINDERS_TOOL, REMIND_TOOL, REMINDER_CANCEL_TOOL,
|
|
737
|
+
ROOMS_TOOL, ROOM_READ_TOOL, ROOM_SAY_TOOL, ROOM_CREATE_TOOL, ROOM_CHANGE_TOOL, ROOM_REMOVE_TOOL, BOXES_TOOL, BOX_SAY_TOOL, ...BINDER_TOOLS];
|
|
738
|
+
/* The tools that need a scope of the server: listed only to a key given it. */
|
|
739
|
+
const TOOL_SCOPES = Object.freeze({ [STATUS_TOOL.name]: 'status', [JOBS_TOOL.name]: 'jobs', [JOB_LOG_TOOL.name]: 'jobs', [LOAD_TOOL.name]: 'diagnostics', [PROFILE_TOOL.name]: 'diagnostics', [LOGS_TOOL.name]: 'diagnostics', [ROOM_CREATE_TOOL.name]: 'create-rooms' });
|
|
740
|
+
|
|
741
|
+
/* Returns true when the request was under /api/ext/ (answered here). `status()`: the state, as statusOf
|
|
742
|
+
makes it. `chats`: { list() -> [{ id, name }], read(name, part) -> talk.of's answer, chatOn(name),
|
|
743
|
+
say(name, text, by) -> { told } }. `rooms`: { list() -> [{ id, name, host, members: [{ name, kind }] }],
|
|
744
|
+
read(id, part) -> rooms.read's answer, say(id, text, { as, to }) }. `boxes`: { list() -> [{ id, name, online, where,
|
|
745
|
+
heardAt, volume }], say(id, text, by) -> { seconds? } }. `originOk(headers)`: whether an Origin is this site's (gate.mjs); a
|
|
746
|
+
call from a page of another site is refused.
|
|
747
|
+
To act (07-11): `chats` also { wake(name) -> { state }, sleep(name), stop(name) } -- the owner's own calls; `rooms` also
|
|
748
|
+
{ create({ name, conversations, boxes, host }) -> { id }, change(id, { name, host, add, remove }) -- by member ids, as the
|
|
749
|
+
page asks --, remove(id) }, and its list's members carry `ref` (a conversation's name, a box's id) and `id` (the member's).
|
|
750
|
+
`events`: What happened (events.mjs), where each act is said with the key's name.
|
|
751
|
+
07-11: `reminders`: { of(name) -> { on, plans: [{ id, text, cron, next }] }, set(name, { at, cron, text }, by) -> plan,
|
|
752
|
+
cancel(name, plan) -> bool } -- a conversation's Docket (dockets.mjs). `binder`: { act(op, args, who) -> { ok, text, data } }
|
|
753
|
+
-- Binder's keeper, asked as the key (an agent): its rules are Binder's.
|
|
754
|
+
14-11: `jobs`: { list() -> { running, done }, log(id) -> the job with its log | undefined } (jobs.mjs, withUpdates).
|
|
755
|
+
18-11: `diagnostics`: { load() -> HostTally windows, profile(seconds) -> profile.mjs's, logs(source, span) -> serverlogs.mjs start's }. */
|
|
756
|
+
export async function handleExternal(request, response, { keys, status, chats = null, rooms = null, boxes = null, reminders = null, binder = null, jobs = null, diagnostics = null, events = null, headers = {}, originOk = () => false, version = null }) {
|
|
757
|
+
const url = new URL(request.url ?? '/', 'http://local');
|
|
758
|
+
const { pathname } = url;
|
|
759
|
+
if (!pathname.startsWith(EXT_PREFIX) && pathname !== EXT_PREFIX.slice(0, -1)) return false;
|
|
760
|
+
const route = pathname.slice(EXT_PREFIX.length - 1);
|
|
761
|
+
const send = (code, body, more = {}) => {
|
|
762
|
+
response.writeHead(code, { ...headers, 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', ...more });
|
|
763
|
+
response.end(body === undefined ? undefined : JSON.stringify(body));
|
|
764
|
+
return true;
|
|
765
|
+
};
|
|
766
|
+
const note = (key, code, what = route) => keys.note({ key, route: what, status: code, method: request.method });
|
|
767
|
+
/* A browser on another site: never (MCP asks servers to look at Origin). Programs send none. */
|
|
768
|
+
const origin = request.headers.origin;
|
|
769
|
+
if (typeof origin === 'string' && !originOk(request.headers)) { note(null, 403); return send(403, { error: 'Not from another site.' }); }
|
|
770
|
+
const refused = (error, what) => {
|
|
771
|
+
if (!(error instanceof Refusal)) throw error;
|
|
772
|
+
note(error.key ?? null, error.status, what);
|
|
773
|
+
const more = error.status === 401 ? { 'www-authenticate': 'Bearer realm="clavarium"' } : error.status === 429 ? { 'retry-after': String(error.retry ?? 60) } : {};
|
|
774
|
+
return send(error.status, { error: error.message }, more);
|
|
775
|
+
};
|
|
776
|
+
const bodyOf = async (max) => {
|
|
777
|
+
let text = '';
|
|
778
|
+
for await (const piece of request) { text += piece; if (text.length > max) throw new Refusal(413, 'Too long.'); }
|
|
779
|
+
return text;
|
|
780
|
+
};
|
|
781
|
+
/* What a key does with conversations, the same for the API and MCP. Each throws a Refusal. */
|
|
782
|
+
const given = (id) => keys.conversationsOf(id);
|
|
783
|
+
const listed = (id) => {
|
|
784
|
+
const names = new Map((chats?.list() ?? []).map((c) => [c.id, c.name]));
|
|
785
|
+
return { conversations: given(id).filter((c) => names.has(c.name)).map((c) => ({ id: c.name, name: names.get(c.name), level: c.level, chat: Boolean(chats?.chatOn(c.name)) })) };
|
|
786
|
+
};
|
|
787
|
+
const known = (name) => { if (!(chats?.list() ?? []).some((c) => c.id === name)) throw new Refusal(403, 'This key was not given this conversation.'); };
|
|
788
|
+
const reading = (id, name, part) => {
|
|
789
|
+
keys.mayConversation(id, name, 'read'); known(name);
|
|
790
|
+
return threadOf(chats.read(name, part));
|
|
791
|
+
};
|
|
792
|
+
const saying = async (id, name, text) => {
|
|
793
|
+
keys.mayConversation(id, name, 'talk'); known(name);
|
|
794
|
+
if (typeof text !== 'string' || !text.trim()) throw new Refusal(400, 'Say something: text.');
|
|
795
|
+
if (text.length > SAY_MAX) throw new Refusal(400, `${SAY_MAX} characters at most.`);
|
|
796
|
+
const said = await chats.say(name, text, keys.signature(id));
|
|
797
|
+
return { ok: true, told: typeof said?.told === 'string' ? said.told : null };
|
|
798
|
+
};
|
|
799
|
+
/* The same for rooms and voice boxes. */
|
|
800
|
+
const roomsListed = (id) => {
|
|
801
|
+
const there = new Map((rooms?.list() ?? []).map((r) => [r.id, r]));
|
|
802
|
+
/* A member's id only when the key was given it (a conversation's, a box's): what it may add or take away. */
|
|
803
|
+
const convs = new Set(keys.conversationsOf(id).map((c) => c.name)); const bs = new Set(keys.boxesOf(id).map((b) => b.id));
|
|
804
|
+
const mine = (m) => (m.kind === 'ai' && convs.has(m.ref)) || (m.kind === 'box' && bs.has(m.ref));
|
|
805
|
+
return { rooms: keys.roomsOf(id).filter((g) => there.has(g.id)).map((g) => { const r = there.get(g.id);
|
|
806
|
+
return { id: g.id, name: String(r.name ?? ''), level: g.level, host: r.host ?? null, members: (Array.isArray(r.members) ? r.members : []).map((m) => ({ name: String(m.name ?? ''), kind: String(m.kind ?? ''), ...(typeof m.ref === 'string' && mine(m) ? { id: m.ref } : {}) })) }; }) };
|
|
807
|
+
};
|
|
808
|
+
const roomKnown = (room) => { if (!(rooms?.list() ?? []).some((r) => r.id === room)) throw new Refusal(403, 'This key was not given this room.'); };
|
|
809
|
+
const roomReading = (id, room, part) => {
|
|
810
|
+
keys.mayRoom(id, room, 'read'); roomKnown(room);
|
|
811
|
+
return roomThreadOf(rooms.read(room, part));
|
|
812
|
+
};
|
|
813
|
+
const roomSaying = async (id, room, text, to) => {
|
|
814
|
+
keys.mayRoom(id, room, 'talk'); roomKnown(room);
|
|
815
|
+
if (typeof text !== 'string' || !text.trim()) throw new Refusal(400, 'Say something: text.');
|
|
816
|
+
if (text.length > SAY_MAX) throw new Refusal(400, `${SAY_MAX} characters at most.`);
|
|
817
|
+
if (to !== undefined && to !== null && (!Array.isArray(to) || to.length > 20 || to.some((x) => typeof x !== 'string'))) throw new Refusal(400, 'to: the names of AIs of this room.');
|
|
818
|
+
const done = await rooms.say(room, text, { as: keys.roomSignature(id), to: Array.isArray(to) ? to : [] });
|
|
819
|
+
/* Posted; an AI it could not reach (its chat off) said by name. */
|
|
820
|
+
return done?.missed?.length ? { ok: true, notReached: done.missed.map((m) => m.name) } : { ok: true };
|
|
821
|
+
};
|
|
822
|
+
const boxesListed = (id) => {
|
|
823
|
+
const there = new Map((boxes?.list() ?? []).map((b) => [b.id, b]));
|
|
824
|
+
return { boxes: keys.boxesOf(id).filter((g) => there.has(g.id)).map((g) => { const b = there.get(g.id);
|
|
825
|
+
return { id: g.id, name: String(b.name ?? ''), level: g.level, online: Boolean(b.online), where: b.where ?? null, heardAt: b.heardAt ?? null, volume: Number.isFinite(b.volume) ? b.volume : null }; }) };
|
|
826
|
+
};
|
|
827
|
+
const boxSaying = async (id, box, text) => {
|
|
828
|
+
keys.mayBox(id, box, 'speak');
|
|
829
|
+
if (!(boxes?.list() ?? []).some((b) => b.id === box)) throw new Refusal(403, 'This key was not given this voice box.');
|
|
830
|
+
if (typeof text !== 'string' || !text.trim()) throw new Refusal(400, 'Say something: text.');
|
|
831
|
+
if (text.length > SPEAK_MAX) throw new Refusal(400, `${SPEAK_MAX} characters at most, said aloud.`);
|
|
832
|
+
keys.speakCounted(id, box);
|
|
833
|
+
const done = await boxes.say(box, text, keys.signature(id));
|
|
834
|
+
return { ok: true, ...(Number.isFinite(done?.seconds) ? { seconds: done.seconds } : {}) };
|
|
835
|
+
};
|
|
836
|
+
/* SAID IN WHAT HAPPENED, with the key's name: what a key did, never what it read. */
|
|
837
|
+
const said = (id, kind, text, conversation = null) => {
|
|
838
|
+
const label = keys.signature(id)?.name ?? '';
|
|
839
|
+
try { events?.add({ kind, text, ...(conversation ? { conversation } : {}), who: `API key "${label}"` }); } catch { /* never in the way */ }
|
|
840
|
+
};
|
|
841
|
+
/* ACT on a conversation (level "act"): the owner's own calls -- woken, put to sleep, its turn stopped. */
|
|
842
|
+
const ACTS = { wake: 'woken', sleep: 'put to sleep', stop: 'its turn stopped' };
|
|
843
|
+
const acting = async (id, name, act) => {
|
|
844
|
+
keys.mayConversation(id, name, 'act'); known(name);
|
|
845
|
+
if (typeof chats?.[act] !== 'function') throw new Refusal(409, 'Not possible here.');
|
|
846
|
+
const done = await chats[act](name);
|
|
847
|
+
said(id, act === 'stop' ? 'conversation' : 'machine', act === 'stop' ? `${name}: its turn stopped` : `Machine of ${name} ${ACTS[act]}`, name);
|
|
848
|
+
return { ok: true, ...(typeof done?.state === 'string' ? { state: done.state } : {}) };
|
|
849
|
+
};
|
|
850
|
+
/* MANAGE a room (level "manage"), or make one ("create rooms"). Its members are named as the key knows them --
|
|
851
|
+
a conversation by its id, a box by its id -- and only among those this key was given (at any level): else 403,
|
|
852
|
+
the same for one not there. The body takes these fields and no other: never a level, a right, a key. */
|
|
853
|
+
const refs = (value, what) => {
|
|
854
|
+
if (value === undefined || value === null) return [];
|
|
855
|
+
if (!Array.isArray(value) || value.length > 40 || value.some((x) => typeof x !== 'string')) throw new Refusal(400, `${what}: a list of ids.`);
|
|
856
|
+
return [...new Set(value)];
|
|
857
|
+
};
|
|
858
|
+
const sides = (value, what) => {
|
|
859
|
+
if (value === undefined || value === null) return { conversations: [], boxes: [] };
|
|
860
|
+
if (typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some((k) => !['conversations', 'boxes'].includes(k))) throw new Refusal(400, `${what}: {conversations: [ids], boxes: [ids]}.`);
|
|
861
|
+
return { conversations: refs(value.conversations, `${what}.conversations`), boxes: refs(value.boxes, `${what}.boxes`) };
|
|
862
|
+
};
|
|
863
|
+
const onlyFields = (body, fields) => {
|
|
864
|
+
if (!body || typeof body !== 'object' || Array.isArray(body)) throw new Refusal(400, 'Send JSON: an object.');
|
|
865
|
+
const other = Object.keys(body).filter((k) => !fields.includes(k));
|
|
866
|
+
if (other.length) throw new Refusal(400, `Not a field here: ${other[0].slice(0, 40)}. Only: ${fields.join(', ')}.`);
|
|
867
|
+
};
|
|
868
|
+
const givenMembers = (id, { conversations, boxes: bs }) => {
|
|
869
|
+
const convs = new Set(keys.conversationsOf(id).map((c) => c.name));
|
|
870
|
+
const there = new Set((chats?.list() ?? []).map((c) => c.id));
|
|
871
|
+
for (const c of conversations) if (!convs.has(c) || !there.has(c)) throw Object.assign(new Refusal(403, 'This key was not given this conversation.'), { key: id });
|
|
872
|
+
const given = new Set(keys.boxesOf(id).map((b) => b.id));
|
|
873
|
+
const boxesThere = new Set((boxes?.list() ?? []).map((b) => b.id));
|
|
874
|
+
for (const b of bs) if (!given.has(b) || !boxesThere.has(b)) throw Object.assign(new Refusal(403, 'This key was not given this voice box.'), { key: id });
|
|
875
|
+
};
|
|
876
|
+
const roomShown = (id, room) => roomsListed(id).rooms.find((r) => r.id === room) ?? null;
|
|
877
|
+
const roomCreating = (id, body) => {
|
|
878
|
+
if (!keys.may(id, 'create-rooms')) throw Object.assign(new Refusal(403, `This key was not given the scope "${SCOPES['create-rooms'].label}".`), { key: id });
|
|
879
|
+
onlyFields(body, ['name', 'conversations', 'boxes', 'host']);
|
|
880
|
+
const members = { conversations: refs(body.conversations, 'conversations'), boxes: refs(body.boxes, 'boxes') };
|
|
881
|
+
if (body.host !== undefined && body.host !== null && (typeof body.host !== 'string' || !members.conversations.includes(body.host))) throw new Refusal(400, 'host: one of its conversations.');
|
|
882
|
+
givenMembers(id, members);
|
|
883
|
+
if (typeof rooms?.create !== 'function') throw new Refusal(409, 'Not possible here.');
|
|
884
|
+
const made = rooms.create({ name: body.name, conversations: members.conversations, boxes: members.boxes, ...(body.host ? { host: body.host } : {}) });
|
|
885
|
+
/* The one right a key gets on its own: the room it made, at "manage" (see madeRoom). */
|
|
886
|
+
keys.madeRoom(id, made.id);
|
|
887
|
+
const shown = roomShown(id, made.id);
|
|
888
|
+
said(id, 'conversation', `Room "${String(shown?.name ?? made.name ?? '').slice(0, 60)}" made`);
|
|
889
|
+
return { ok: true, room: shown };
|
|
890
|
+
};
|
|
891
|
+
const roomChanging = (id, room, body) => {
|
|
892
|
+
keys.mayRoom(id, room, 'manage'); roomKnown(room);
|
|
893
|
+
onlyFields(body, ['name', 'host', 'add', 'remove']);
|
|
894
|
+
const add = sides(body.add, 'add'); const remove = sides(body.remove, 'remove');
|
|
895
|
+
if (body.host !== undefined && body.host !== null && typeof body.host !== 'string') throw new Refusal(400, 'host: the id of one of its conversations.');
|
|
896
|
+
const host = typeof body.host === 'string' ? body.host : null;
|
|
897
|
+
givenMembers(id, { conversations: [...add.conversations, ...remove.conversations, ...(host ? [host] : [])], boxes: [...add.boxes, ...remove.boxes] });
|
|
898
|
+
const before = rooms.list().find((r) => r.id === room);
|
|
899
|
+
const members = Array.isArray(before?.members) ? before.members : [];
|
|
900
|
+
const member = (kind, ref) => members.find((m) => m.kind === kind && m.ref === ref);
|
|
901
|
+
const gone = [...remove.conversations.map((c) => ['ai', c]), ...remove.boxes.map((b) => ['box', b])].map(([kind, ref]) => {
|
|
902
|
+
const m = member(kind, ref); if (!m) throw new Refusal(400, 'Not a member of this room.'); return m.id; });
|
|
903
|
+
/* The host: one of its AIs once the change is made (one added now, too). */
|
|
904
|
+
if (host && !(member('ai', host) && !remove.conversations.includes(host)) && !add.conversations.includes(host)) throw new Refusal(400, 'host: one of its conversations.');
|
|
905
|
+
const name = body.name === undefined || body.name === null ? undefined : String(body.name);
|
|
906
|
+
rooms.change(room, { ...(name !== undefined ? { name } : {}), add, remove: gone });
|
|
907
|
+
if (host) {
|
|
908
|
+
const now = rooms.list().find((r) => r.id === room)?.members ?? [];
|
|
909
|
+
const m = now.find((x) => x.kind === 'ai' && x.ref === host);
|
|
910
|
+
if (m && !m.host) rooms.change(room, { host: m.id });
|
|
911
|
+
}
|
|
912
|
+
const shown = roomShown(id, room);
|
|
913
|
+
const what = [...(name !== undefined ? [`renamed "${String(shown?.name ?? name).slice(0, 60)}"`] : []), ...(add.conversations.length + add.boxes.length ? [`${add.conversations.length + add.boxes.length} added`] : []),
|
|
914
|
+
...(gone.length ? [`${gone.length} taken away`] : []), ...(host ? [`host ${host}`] : [])];
|
|
915
|
+
said(id, 'conversation', `Room "${String(before?.name ?? '').slice(0, 60)}" changed${what.length ? `: ${what.join(', ')}` : ''}`);
|
|
916
|
+
return { ok: true, room: shown };
|
|
917
|
+
};
|
|
918
|
+
const roomRemoving = (id, room) => {
|
|
919
|
+
keys.mayRoom(id, room, 'manage'); roomKnown(room);
|
|
920
|
+
const name = rooms.list().find((r) => r.id === room)?.name ?? '';
|
|
921
|
+
rooms.remove(room);
|
|
922
|
+
said(id, 'conversation', `Room "${String(name).slice(0, 60)}" removed`);
|
|
923
|
+
return { ok: true, removed: room };
|
|
924
|
+
};
|
|
925
|
+
/* A CONVERSATION'S REMINDERS (its tool's Docket), folded into its level: seen at Read, set at Talk, taken back at Act. */
|
|
926
|
+
const docketOf = (name) => {
|
|
927
|
+
const d = reminders?.of(name);
|
|
928
|
+
if (!d?.on) throw new Refusal(409, 'Its chat is off: it has no reminders.');
|
|
929
|
+
return d;
|
|
930
|
+
};
|
|
931
|
+
const remindersListed = (id, name) => {
|
|
932
|
+
keys.mayConversation(id, name, 'read'); known(name);
|
|
933
|
+
return { reminders: (docketOf(name).plans ?? []).map((p) => ({ id: String(p.id), text: String(p.text ?? ''), cron: typeof p.cron === 'string' ? p.cron : null, next: p.next ?? null })) };
|
|
934
|
+
};
|
|
935
|
+
const reminding = (id, name, body) => {
|
|
936
|
+
keys.mayConversation(id, name, 'talk'); known(name);
|
|
937
|
+
onlyFields(body, ['text', 'at', 'cron']);
|
|
938
|
+
const text = typeof body.text === 'string' ? body.text.trim() : '';
|
|
939
|
+
if (!text) throw new Refusal(400, 'Say what it is for: text.');
|
|
940
|
+
if (text.length > REMINDER_MAX) throw new Refusal(400, `${REMINDER_MAX} characters at most: a short text.`);
|
|
941
|
+
const at = typeof body.at === 'string' && body.at.trim() ? body.at.trim() : null;
|
|
942
|
+
const cron = typeof body.cron === 'string' && body.cron.trim() ? body.cron.trim() : null;
|
|
943
|
+
if (Boolean(at) === Boolean(cron)) throw new Refusal(400, 'Give one of: at ("2026-11-20 09:00") or cron ("0 9 * * 1").');
|
|
944
|
+
docketOf(name);
|
|
945
|
+
let plan;
|
|
946
|
+
try { plan = reminders.set(name, { ...(at ? { at } : { cron }), text }, keys.signature(id)); } catch (error) { if (error instanceof Refusal) throw error; throw new Refusal(400, String(error?.message ?? 'Not a reminder.').slice(0, 200)); }
|
|
947
|
+
said(id, 'conversation', `${name}: reminder set "${text.slice(0, 60)}"`, name);
|
|
948
|
+
return { ok: true, reminder: { id: String(plan.id), text: String(plan.text ?? text), cron: plan.cron ?? null, next: plan.next ?? null } };
|
|
949
|
+
};
|
|
950
|
+
const unreminding = (id, name, plan) => {
|
|
951
|
+
keys.mayConversation(id, name, 'act'); known(name);
|
|
952
|
+
const d = docketOf(name);
|
|
953
|
+
const p = typeof plan === 'string' ? (d.plans ?? []).find((x) => x.id === plan) : undefined;
|
|
954
|
+
if (!p || !reminders.cancel(name, plan)) throw new Refusal(404, 'No such reminder.');
|
|
955
|
+
said(id, 'conversation', `${name}: reminder taken back "${String(p.text ?? '').slice(0, 60)}"`, name);
|
|
956
|
+
return { ok: true, cancelled: plan };
|
|
957
|
+
};
|
|
958
|
+
/* ITS BINDER LISTS: Binder asked as the key -- an agent, its name on what it writes. Only these asks, never a
|
|
959
|
+
person's (approve, delete, grant, settings, a list's columns). What Binder refuses is refused: a gate a person
|
|
960
|
+
did not tick says so (403). A record is reached through its own list only. */
|
|
961
|
+
const asked = (id, op, args) => {
|
|
962
|
+
if (typeof binder?.act !== 'function') throw new Refusal(409, 'Not possible here.');
|
|
963
|
+
const r = binder.act(op, args, keys.binderWho(id));
|
|
964
|
+
if (r?.ok) return r.data;
|
|
965
|
+
const why = String(r?.text ?? 'Not done.').slice(0, 300);
|
|
966
|
+
throw Object.assign(new Refusal(/^only a person/.test(why) ? 403 : 400, why), { key: id });
|
|
967
|
+
};
|
|
968
|
+
const clean = (v) => (typeof v === 'string' ? masked(v) : v);
|
|
969
|
+
const stateOf = (l, sid) => l?.states?.find((x) => x.id === sid)?.name ?? null;
|
|
970
|
+
const recordShown = (r, l, whole = false) => ({ id: String(r.id), title: masked(String(r.title ?? '')), state: String(r.state ?? ''), stateName: stateOf(l, r.state),
|
|
971
|
+
fields: Object.fromEntries(Object.entries(r.fields ?? {}).map(([k, v]) => [k, clean(v)])), owners: Array.isArray(r.owners) ? r.owners.slice(0, 8) : [],
|
|
972
|
+
due: r.due ?? null, ...(r.approved ? { approved: true } : {}), ...(r.archived ? { archived: true } : {}), changed: r.changed ?? null,
|
|
973
|
+
...(whole ? { description: masked(String(r.description ?? '')), created: r.created ?? null,
|
|
974
|
+
notes: (Array.isArray(r.notes) ? r.notes : []).map((n) => ({ at: n.at, by: String(n.by?.name ?? ''), text: masked(String(n.text ?? '')) })),
|
|
975
|
+
attached: (Array.isArray(r.attached) ? r.attached : []).map((a) => ({ kind: String(a.kind ?? ''), title: masked(String(a.title ?? '')) })) } : {}) });
|
|
976
|
+
const bindersListed = (id) => {
|
|
977
|
+
const given = keys.bindersOf(id);
|
|
978
|
+
const shown = given.length ? asked(id, 'lists', {}) : [];
|
|
979
|
+
const lists = new Map((Array.isArray(shown) ? shown : []).map((l) => [l.id, l]));
|
|
980
|
+
return { binders: given.filter((g) => lists.has(g.id)).map((g) => { const l = lists.get(g.id);
|
|
981
|
+
return { id: g.id, title: String(l.title ?? ''), level: g.level, count: l.count ?? 0,
|
|
982
|
+
states: (l.states ?? []).map((x) => ({ id: x.id, name: x.name, ...(x.gate ? { gate: true } : {}), ...(x.done ? { done: true } : {}) })),
|
|
983
|
+
fields: (l.fields ?? []).map((f) => ({ id: f.id, name: f.name, type: f.type })) }; }) };
|
|
984
|
+
};
|
|
985
|
+
const recordsListed = (id, list, { state, archived } = {}) => {
|
|
986
|
+
keys.mayBinder(id, list, 'read');
|
|
987
|
+
if (state !== undefined && state !== null && typeof state !== 'string') throw new Refusal(400, 'state: a state\'s id or name.');
|
|
988
|
+
const d = asked(id, 'show', { list, ...(state ? { state } : {}), archived: archived === true });
|
|
989
|
+
return { records: (d.records ?? []).map((r) => recordShown(r, d.list)) };
|
|
990
|
+
};
|
|
991
|
+
/* The record, as the key may reach it: in this list, the list given. */
|
|
992
|
+
const recordIn = (id, list, record, level) => {
|
|
993
|
+
keys.mayBinder(id, list, level);
|
|
994
|
+
if (typeof record !== 'string' || !/^\d{1,9}$/.test(record)) throw new Refusal(404, 'No such record in this binder.');
|
|
995
|
+
let d;
|
|
996
|
+
try { d = asked(id, 'get', { id: record }); } catch (error) { if (error instanceof Refusal && error.status === 400) throw new Refusal(404, 'No such record in this binder.'); throw error; }
|
|
997
|
+
if (d?.record?.list !== list) throw new Refusal(404, 'No such record in this binder.');
|
|
998
|
+
return d;
|
|
999
|
+
};
|
|
1000
|
+
const recordRead = (id, list, record) => { const d = recordIn(id, list, record, 'read'); return { record: recordShown(d.record, d.list, true) }; };
|
|
1001
|
+
const binderSaid = (id, list, what) => said(id, 'asset', `Binder "${String(keys.binderTitle(list)).slice(0, 60)}": ${what}`);
|
|
1002
|
+
const RECORD_FIELDS = ['title', 'description', 'fields', 'due'];
|
|
1003
|
+
const recordAdding = (id, list, body) => {
|
|
1004
|
+
keys.mayBinder(id, list, 'write');
|
|
1005
|
+
onlyFields(body, ['title', 'description', 'state', 'fields', 'due']);
|
|
1006
|
+
const r = asked(id, 'add', { list, title: body.title, description: body.description, state: body.state, fields: body.fields, due: body.due });
|
|
1007
|
+
binderSaid(id, list, `#${r.id} added`);
|
|
1008
|
+
return { ok: true, record: recordRead(id, list, String(r.id)).record };
|
|
1009
|
+
};
|
|
1010
|
+
const recordEditing = (id, list, record, body) => {
|
|
1011
|
+
recordIn(id, list, record, 'write');
|
|
1012
|
+
onlyFields(body, RECORD_FIELDS);
|
|
1013
|
+
asked(id, 'edit', { id: record, ...Object.fromEntries(RECORD_FIELDS.filter((k) => body[k] !== undefined).map((k) => [k, body[k]])) });
|
|
1014
|
+
binderSaid(id, list, `#${record} changed`);
|
|
1015
|
+
return { ok: true, record: recordRead(id, list, record).record };
|
|
1016
|
+
};
|
|
1017
|
+
const recordMoving = (id, list, record, body) => {
|
|
1018
|
+
recordIn(id, list, record, 'write');
|
|
1019
|
+
onlyFields(body, ['state']);
|
|
1020
|
+
if (typeof body.state !== 'string' || !body.state) throw new Refusal(400, 'state: a state\'s id or name.');
|
|
1021
|
+
const r = asked(id, 'move', { id: record, state: body.state });
|
|
1022
|
+
binderSaid(id, list, `#${record} moved to ${String(r.stateName ?? r.state).slice(0, 40)}`);
|
|
1023
|
+
return { ok: true, record: recordRead(id, list, record).record };
|
|
1024
|
+
};
|
|
1025
|
+
const recordNoting = (id, list, record, body) => {
|
|
1026
|
+
recordIn(id, list, record, 'write');
|
|
1027
|
+
onlyFields(body, ['text']);
|
|
1028
|
+
if (typeof body.text !== 'string' || !body.text.trim()) throw new Refusal(400, 'Say something: text.');
|
|
1029
|
+
asked(id, 'note', { id: record, text: body.text });
|
|
1030
|
+
binderSaid(id, list, `#${record} noted`);
|
|
1031
|
+
return { ok: true, record: recordRead(id, list, record).record };
|
|
1032
|
+
};
|
|
1033
|
+
const recordArchiving = (id, list, record, restore) => {
|
|
1034
|
+
recordIn(id, list, record, 'write');
|
|
1035
|
+
asked(id, 'archive', { id: record, restore: restore === true });
|
|
1036
|
+
binderSaid(id, list, `#${record} ${restore === true ? 'restored' : 'archived'}`);
|
|
1037
|
+
return { ok: true, record: recordRead(id, list, record).record };
|
|
1038
|
+
};
|
|
1039
|
+
/* What Clavarium does (scope "jobs"), its texts masked as a room's are: a log line may quote what a program said. */
|
|
1040
|
+
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 }); };
|
|
1041
|
+
const jobShown = ({ what, step, why, log, ...job }) => ({ ...job, what: masked(what), ...(step !== undefined ? { step: masked(step) } : {}), ...(why !== undefined ? { why: masked(why) } : {}),
|
|
1042
|
+
...(Array.isArray(log) ? { log: log.map((l) => ({ at: l.at, text: masked(l.text) })) } : {}) });
|
|
1043
|
+
const jobsListed = (id) => {
|
|
1044
|
+
mayJobs(id);
|
|
1045
|
+
const { running = [], done = [] } = jobs?.list() ?? {};
|
|
1046
|
+
return { running: running.map(jobShown), done: done.map(jobShown) };
|
|
1047
|
+
};
|
|
1048
|
+
const jobRead = (id, job) => {
|
|
1049
|
+
mayJobs(id);
|
|
1050
|
+
const found = typeof job === 'string' && JOB_ID.test(job) ? jobs?.log(job) : undefined;
|
|
1051
|
+
if (!found) throw new Refusal(404, 'No such job (under way, or done today).');
|
|
1052
|
+
return jobShown(found);
|
|
1053
|
+
};
|
|
1054
|
+
const ownError = (error, id) => (error instanceof Refusal ? Object.assign(error, { key: error.key ?? id }) : error);
|
|
1055
|
+
try {
|
|
1056
|
+
const jobRoute = /^\/v1\/jobs(?:\/([^/]+))?$/.exec(route);
|
|
1057
|
+
if (jobRoute) {
|
|
1058
|
+
if (request.method !== 'GET') return send(405, { error: 'Call this address with GET.' }, { allow: 'GET' });
|
|
1059
|
+
let id;
|
|
1060
|
+
try { id = keys.check(request.headers.authorization, 'jobs'); } catch (error) { return refused(error); }
|
|
1061
|
+
try {
|
|
1062
|
+
let job = '';
|
|
1063
|
+
try { job = jobRoute[1] ? decodeURIComponent(jobRoute[1]) : ''; } catch { job = ''; }
|
|
1064
|
+
const body = jobRoute[1] ? jobRead(id, job) : jobsListed(id);
|
|
1065
|
+
note(id, 200);
|
|
1066
|
+
return send(200, body);
|
|
1067
|
+
} catch (error) { return refused(ownError(error, id)); }
|
|
1068
|
+
}
|
|
1069
|
+
if (route === '/v1/status') {
|
|
1070
|
+
if (request.method !== 'GET') return send(405, { error: 'Call this address with GET.' }, { allow: 'GET' });
|
|
1071
|
+
let id;
|
|
1072
|
+
try { id = keys.check(request.headers.authorization, 'status'); } catch (error) { return refused(error); }
|
|
1073
|
+
const body = await status();
|
|
1074
|
+
note(id, 200);
|
|
1075
|
+
return send(200, body);
|
|
1076
|
+
}
|
|
1077
|
+
/* A JSON body, or a refusal. */
|
|
1078
|
+
const jsonOf = async (max) => {
|
|
1079
|
+
if (!String(request.headers['content-type'] ?? '').startsWith('application/json')) throw new Refusal(415, 'Send JSON.');
|
|
1080
|
+
const text = await bodyOf(max);
|
|
1081
|
+
if (!text) return {};
|
|
1082
|
+
try { return JSON.parse(text); } catch { throw new Refusal(400, 'The request is not JSON.'); }
|
|
1083
|
+
};
|
|
1084
|
+
const reminder = /^\/v1\/conversations\/([^/]+)\/reminders(?:\/([^/]+)\/cancel)?$/.exec(route);
|
|
1085
|
+
if (reminder) {
|
|
1086
|
+
const allowed = reminder[2] ? 'POST' : 'GET, POST';
|
|
1087
|
+
if (!allowed.split(', ').includes(request.method)) return send(405, { error: `Call this address with ${allowed}.` }, { allow: allowed });
|
|
1088
|
+
let id;
|
|
1089
|
+
try { id = keys.check(request.headers.authorization); } catch (error) { return refused(error); }
|
|
1090
|
+
try {
|
|
1091
|
+
let name; let plan = '';
|
|
1092
|
+
try { name = decodeURIComponent(reminder[1]); plan = reminder[2] ? decodeURIComponent(reminder[2]) : ''; } catch { name = ''; }
|
|
1093
|
+
if (reminder[2]) { const done = unreminding(id, name, plan); note(id, 200); return send(200, done); }
|
|
1094
|
+
if (request.method === 'GET') { const body = remindersListed(id, name); note(id, 200); return send(200, body); }
|
|
1095
|
+
const done = reminding(id, name, await jsonOf(4096));
|
|
1096
|
+
note(id, 201); return send(201, done);
|
|
1097
|
+
} catch (error) { return refused(ownError(error, id)); }
|
|
1098
|
+
}
|
|
1099
|
+
const binderRoute = /^\/v1\/binders(?:\/([^/]+)\/records(?:\/([^/]+)(?:\/(move|notes|archive|restore))?)?)?$/.exec(route);
|
|
1100
|
+
if (binderRoute) {
|
|
1101
|
+
const [, listRef, recordRef, verb] = binderRoute;
|
|
1102
|
+
const allowed = !listRef ? 'GET' : verb ? 'POST' : 'GET, POST';
|
|
1103
|
+
if (!allowed.split(', ').includes(request.method)) return send(405, { error: `Call this address with ${allowed}.` }, { allow: allowed });
|
|
1104
|
+
let id;
|
|
1105
|
+
try { id = keys.check(request.headers.authorization); } catch (error) { return refused(error); }
|
|
1106
|
+
try {
|
|
1107
|
+
if (!listRef) { const body = bindersListed(id); note(id, 200); return send(200, body); }
|
|
1108
|
+
let list; let record;
|
|
1109
|
+
try { list = decodeURIComponent(listRef); record = recordRef === undefined ? undefined : decodeURIComponent(recordRef); } catch { list = ''; }
|
|
1110
|
+
if (request.method === 'GET') {
|
|
1111
|
+
const body = record === undefined ? recordsListed(id, list, { state: url.searchParams.get('state') || undefined, archived: url.searchParams.get('archived') === '1' }) : recordRead(id, list, record);
|
|
1112
|
+
note(id, 200); return send(200, body);
|
|
1113
|
+
}
|
|
1114
|
+
if (verb === 'archive' || verb === 'restore') { const done = recordArchiving(id, list, record, verb === 'restore'); note(id, 200); return send(200, done); }
|
|
1115
|
+
const body = await jsonOf(16_384);
|
|
1116
|
+
const done = record === undefined ? recordAdding(id, list, body) : verb === 'move' ? recordMoving(id, list, record, body)
|
|
1117
|
+
: verb === 'notes' ? recordNoting(id, list, record, body) : recordEditing(id, list, record, body);
|
|
1118
|
+
const code = record === undefined || verb === 'notes' ? 201 : 200;
|
|
1119
|
+
note(id, code); return send(code, done);
|
|
1120
|
+
} catch (error) { return refused(ownError(error, id)); }
|
|
1121
|
+
}
|
|
1122
|
+
const one = /^\/v1\/conversations(?:\/([^/]+)\/(messages|wake|sleep|stop))?$/.exec(route);
|
|
1123
|
+
if (one) {
|
|
1124
|
+
const allowed = one[2] && one[2] !== 'messages' ? 'POST' : one[1] ? 'GET, POST' : 'GET';
|
|
1125
|
+
if (!allowed.split(', ').includes(request.method)) return send(405, { error: `Call this address with ${allowed}.` }, { allow: allowed });
|
|
1126
|
+
let id;
|
|
1127
|
+
try { id = keys.check(request.headers.authorization); } catch (error) { return refused(error); }
|
|
1128
|
+
try {
|
|
1129
|
+
if (!one[1]) { const body = listed(id); note(id, 200); return send(200, body); }
|
|
1130
|
+
let name;
|
|
1131
|
+
try { name = decodeURIComponent(one[1]); } catch { name = ''; }
|
|
1132
|
+
if (one[2] !== 'messages') { const done = await acting(id, name, one[2]); const code = one[2] === 'wake' ? 202 : 200; note(id, code); return send(code, done); }
|
|
1133
|
+
if (request.method === 'GET') { const body = reading(id, name, readPart((k) => url.searchParams.get(k))); note(id, 200); return send(200, body); }
|
|
1134
|
+
if (!String(request.headers['content-type'] ?? '').startsWith('application/json')) throw new Refusal(415, 'Send JSON: {"text": "..."}.');
|
|
1135
|
+
let body;
|
|
1136
|
+
try { body = JSON.parse(await bodyOf(SAY_MAX * 4 + 1024)); } catch (error) { if (error instanceof Refusal) throw error; throw new Refusal(400, 'The request is not JSON.'); }
|
|
1137
|
+
const done = await saying(id, name, body?.text);
|
|
1138
|
+
note(id, 201);
|
|
1139
|
+
return send(201, done);
|
|
1140
|
+
} catch (error) { return refused(ownError(error, id)); }
|
|
1141
|
+
}
|
|
1142
|
+
const room = /^\/v1\/rooms(?:\/([^/]+)(\/messages|\/remove)?)?$/.exec(route);
|
|
1143
|
+
if (room) {
|
|
1144
|
+
const allowed = room[2] === '/messages' || !room[1] ? 'GET, POST' : 'POST';
|
|
1145
|
+
if (!allowed.split(', ').includes(request.method)) return send(405, { error: `Call this address with ${allowed}.` }, { allow: allowed });
|
|
1146
|
+
let id;
|
|
1147
|
+
try { id = keys.check(request.headers.authorization); } catch (error) { return refused(error); }
|
|
1148
|
+
try {
|
|
1149
|
+
if (!room[1] && request.method === 'GET') { const body = roomsListed(id); note(id, 200); return send(200, body); }
|
|
1150
|
+
let ref;
|
|
1151
|
+
try { ref = decodeURIComponent(room[1] ?? ''); } catch { ref = ''; }
|
|
1152
|
+
if (room[2] === '/remove') { const done = roomRemoving(id, ref); note(id, 200); return send(200, done); }
|
|
1153
|
+
if (request.method === 'GET') { const body = roomReading(id, ref, readPart((k) => url.searchParams.get(k))); note(id, 200); return send(200, body); }
|
|
1154
|
+
if (room[2] !== '/messages') {
|
|
1155
|
+
if (!String(request.headers['content-type'] ?? '').startsWith('application/json')) throw new Refusal(415, 'Send JSON.');
|
|
1156
|
+
let body;
|
|
1157
|
+
try { body = JSON.parse(await bodyOf(16_384)); } catch (error) { if (error instanceof Refusal) throw error; throw new Refusal(400, 'The request is not JSON.'); }
|
|
1158
|
+
const done = room[1] ? roomChanging(id, ref, body) : roomCreating(id, body);
|
|
1159
|
+
const code = room[1] ? 200 : 201;
|
|
1160
|
+
note(id, code); return send(code, done);
|
|
1161
|
+
}
|
|
1162
|
+
if (!String(request.headers['content-type'] ?? '').startsWith('application/json')) throw new Refusal(415, 'Send JSON: {"text": "..."}.');
|
|
1163
|
+
let body;
|
|
1164
|
+
try { body = JSON.parse(await bodyOf(SAY_MAX * 4 + 4096)); } catch (error) { if (error instanceof Refusal) throw error; throw new Refusal(400, 'The request is not JSON.'); }
|
|
1165
|
+
const done = await roomSaying(id, ref, body?.text, body?.to);
|
|
1166
|
+
note(id, 201);
|
|
1167
|
+
return send(201, done);
|
|
1168
|
+
} catch (error) { return refused(ownError(error, id)); }
|
|
1169
|
+
}
|
|
1170
|
+
const box = /^\/v1\/boxes(?:\/([^/]+)\/say)?$/.exec(route);
|
|
1171
|
+
if (box) {
|
|
1172
|
+
const allowed = box[1] ? 'POST' : 'GET';
|
|
1173
|
+
if (request.method !== allowed) return send(405, { error: `Call this address with ${allowed}.` }, { allow: allowed });
|
|
1174
|
+
let id;
|
|
1175
|
+
try { id = keys.check(request.headers.authorization); } catch (error) { return refused(error); }
|
|
1176
|
+
try {
|
|
1177
|
+
if (!box[1]) { const body = boxesListed(id); note(id, 200); return send(200, body); }
|
|
1178
|
+
let ref;
|
|
1179
|
+
try { ref = decodeURIComponent(box[1]); } catch { ref = ''; }
|
|
1180
|
+
if (!String(request.headers['content-type'] ?? '').startsWith('application/json')) throw new Refusal(415, 'Send JSON: {"text": "..."}.');
|
|
1181
|
+
let body;
|
|
1182
|
+
try { body = JSON.parse(await bodyOf(SPEAK_MAX * 4 + 1024)); } catch (error) { if (error instanceof Refusal) throw error; throw new Refusal(400, 'The request is not JSON.'); }
|
|
1183
|
+
const done = await boxSaying(id, ref, body?.text);
|
|
1184
|
+
note(id, 200);
|
|
1185
|
+
return send(200, done);
|
|
1186
|
+
} catch (error) { return refused(ownError(error, id)); }
|
|
1187
|
+
}
|
|
1188
|
+
/* MCP at /api/ext/mcp and, beside the API it speaks for, /api/ext/v1/mcp: the same. */
|
|
1189
|
+
if (route === '/mcp' || route === '/v1/mcp') {
|
|
1190
|
+
if (request.method !== 'POST') return send(405, { error: 'MCP is spoken with POST here (no event stream).' }, { allow: 'POST' });
|
|
1191
|
+
let id;
|
|
1192
|
+
try { id = keys.check(request.headers.authorization); } catch (error) { return refused(error, route); }
|
|
1193
|
+
let text = '';
|
|
1194
|
+
for await (const piece of request) { text += piece; if (text.length > MCP_BODY_MAX) { note(id, 413, route); return send(413, { error: 'Too long.' }); } }
|
|
1195
|
+
/* A protocol version said in the header, and none spoken here: refused, as the spec asks (none said: the oldest assumed). */
|
|
1196
|
+
const said = request.headers['mcp-protocol-version'];
|
|
1197
|
+
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(', ')})` } }); }
|
|
1198
|
+
let msg;
|
|
1199
|
+
try { msg = JSON.parse(text); } catch { note(id, 400, route); return send(400, { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }); }
|
|
1200
|
+
if (!msg || typeof msg !== 'object' || Array.isArray(msg) || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') {
|
|
1201
|
+
note(id, 400, route); return send(400, { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid Request' } });
|
|
1202
|
+
}
|
|
1203
|
+
const args = msg.params?.arguments && typeof msg.params.arguments === 'object' && !Array.isArray(msg.params.arguments) ? msg.params.arguments : {};
|
|
1204
|
+
/* The journal says which tool, and on which conversation, room or box. */
|
|
1205
|
+
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');
|
|
1206
|
+
const what = `${route} ${msg.method.slice(0, 40)}${msg.method === 'tools/call' ? ` ${String(msg.params?.name ?? '').slice(0, 40)}${on ? ` ${on.slice(0, 36)}` : ''}` : ''}`;
|
|
1207
|
+
/* A notification (no id) is taken, never answered. */
|
|
1208
|
+
if (msg.id === undefined || msg.id === null) { note(id, 202, what); response.writeHead(202, { ...headers, 'cache-control': 'no-store' }).end(); return true; }
|
|
1209
|
+
const answer = (result, code = 200) => { note(id, code, what); return send(200, { jsonrpc: '2.0', id: msg.id, result }); };
|
|
1210
|
+
const fail = (code, message, http = 200) => { note(id, http === 200 ? 400 : http, what); return send(http, { jsonrpc: '2.0', id: msg.id, error: { code, message } }); };
|
|
1211
|
+
const result = (body) => answer({ content: [{ type: 'text', text: JSON.stringify(body) }], structuredContent: body, isError: false });
|
|
1212
|
+
switch (msg.method) {
|
|
1213
|
+
case 'initialize': {
|
|
1214
|
+
const asked = String(msg.params?.protocolVersion ?? '');
|
|
1215
|
+
return answer({ protocolVersion: MCP_VERSIONS.includes(asked) ? asked : MCP_VERSIONS[0], capabilities: { tools: { listChanged: false } },
|
|
1216
|
+
serverInfo: { name: 'clavarium', title: 'Clavarium', version: version ?? '0' },
|
|
1217
|
+
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).' });
|
|
1218
|
+
}
|
|
1219
|
+
case 'ping': return answer({});
|
|
1220
|
+
/* A tool that needs a scope is shown only to a key given it (one called anyway is refused, 403). */
|
|
1221
|
+
case 'tools/list': return answer({ tools: TOOLS.filter((x) => !TOOL_SCOPES[x.name] || keys.may(id, TOOL_SCOPES[x.name])) });
|
|
1222
|
+
case 'tools/call': {
|
|
1223
|
+
const name = msg.params?.name;
|
|
1224
|
+
if (!TOOLS.some((x) => x.name === name)) return fail(-32602, `Unknown tool: ${String(name ?? '').slice(0, 60)}`);
|
|
1225
|
+
try {
|
|
1226
|
+
if (name === STATUS_TOOL.name) {
|
|
1227
|
+
if (!keys.may(id, 'status')) throw new Refusal(403, `This key was not given the scope "${SCOPES.status.label}".`);
|
|
1228
|
+
return result(await status());
|
|
1229
|
+
}
|
|
1230
|
+
if (name === JOBS_TOOL.name) return result(jobsListed(id));
|
|
1231
|
+
if (name === LOAD_TOOL.name || name === PROFILE_TOOL.name || name === LOGS_TOOL.name) {
|
|
1232
|
+
if (!keys.may(id, 'diagnostics')) throw new Refusal(403, `This key was not given the scope "${SCOPES.diagnostics.label}".`);
|
|
1233
|
+
if (!diagnostics) throw new Refusal(404, 'Not available on this server.');
|
|
1234
|
+
if (name === LOAD_TOOL.name) return result(diagnostics.load());
|
|
1235
|
+
if (name === PROFILE_TOOL.name) return result(await diagnostics.profile(args.seconds ?? 10));
|
|
1236
|
+
const r = await diagnostics.logs(typeof args.source === 'string' ? args.source : 'clavarium', typeof args.span === 'string' ? args.span : '10m');
|
|
1237
|
+
return result(r.pending ? r : { ...r, text: masked(r.text ?? '') });
|
|
1238
|
+
}
|
|
1239
|
+
if (name === JOB_LOG_TOOL.name) {
|
|
1240
|
+
if (typeof args.id !== 'string') return fail(-32602, 'id: the id of a job, as clavarium_jobs gives it.');
|
|
1241
|
+
return result(jobRead(id, args.id));
|
|
1242
|
+
}
|
|
1243
|
+
if (name === CONVERSATIONS_TOOL.name) return result(listed(id));
|
|
1244
|
+
if (name === ROOMS_TOOL.name) return result(roomsListed(id));
|
|
1245
|
+
if (name === BOXES_TOOL.name) return result(boxesListed(id));
|
|
1246
|
+
if (name === BINDERS_TOOL.name) return result(bindersListed(id));
|
|
1247
|
+
if (BINDER_TOOLS.some((x) => x.name === name)) {
|
|
1248
|
+
if (typeof args.binder !== 'string') return fail(-32602, 'binder: the id of a binder list.');
|
|
1249
|
+
if (name === BINDER_RECORDS_TOOL.name) return result(recordsListed(id, args.binder, { state: args.state, archived: args.archived === true }));
|
|
1250
|
+
if (name !== BINDER_ADD_TOOL.name && typeof args.record !== 'string') return fail(-32602, 'record: the id of a record.');
|
|
1251
|
+
if (name === BINDER_RECORD_TOOL.name) return result(recordRead(id, args.binder, args.record));
|
|
1252
|
+
const { binder: list, record, ...rest } = args;
|
|
1253
|
+
const done = name === BINDER_ADD_TOOL.name ? recordAdding(id, list, rest) : name === BINDER_EDIT_TOOL.name ? recordEditing(id, list, record, rest)
|
|
1254
|
+
: name === BINDER_MOVE_TOOL.name ? recordMoving(id, list, record, rest) : name === BINDER_NOTE_TOOL.name ? recordNoting(id, list, record, rest)
|
|
1255
|
+
: recordArchiving(id, list, record, rest.restore === true);
|
|
1256
|
+
note(id, 201, what);
|
|
1257
|
+
return send(200, { jsonrpc: '2.0', id: msg.id, result: { content: [{ type: 'text', text: JSON.stringify(done) }], structuredContent: done, isError: false } });
|
|
1258
|
+
}
|
|
1259
|
+
const part = () => readPart((k) => (args[k] === undefined ? null : typeof args[k] === 'number' ? String(args[k]) : args[k]));
|
|
1260
|
+
let done;
|
|
1261
|
+
if (name === ROOM_CREATE_TOOL.name) {
|
|
1262
|
+
done = roomCreating(id, args);
|
|
1263
|
+
} else if (name === ROOM_READ_TOOL.name || name === ROOM_SAY_TOOL.name || name === ROOM_CHANGE_TOOL.name || name === ROOM_REMOVE_TOOL.name) {
|
|
1264
|
+
if (typeof args.room !== 'string') return fail(-32602, 'room: the id of a room.');
|
|
1265
|
+
if (name === ROOM_READ_TOOL.name) return result(roomReading(id, args.room, part()));
|
|
1266
|
+
if (name === ROOM_CHANGE_TOOL.name) { const { room: target, ...change } = args; done = roomChanging(id, target, change); }
|
|
1267
|
+
else if (name === ROOM_REMOVE_TOOL.name) done = roomRemoving(id, args.room);
|
|
1268
|
+
else done = await roomSaying(id, args.room, args.text, args.to);
|
|
1269
|
+
} else if (name === BOX_SAY_TOOL.name) {
|
|
1270
|
+
if (typeof args.box !== 'string') return fail(-32602, 'box: the id of a voice box.');
|
|
1271
|
+
done = await boxSaying(id, args.box, args.text);
|
|
1272
|
+
} else {
|
|
1273
|
+
if (typeof args.conversation !== 'string') return fail(-32602, 'conversation: the id of a conversation.');
|
|
1274
|
+
if (name === READ_TOOL.name) return result(reading(id, args.conversation, part()));
|
|
1275
|
+
if (name === REMINDERS_TOOL.name) return result(remindersListed(id, args.conversation));
|
|
1276
|
+
if (name === REMIND_TOOL.name) { const { conversation: c, ...rest } = args; done = reminding(id, c, rest); }
|
|
1277
|
+
else if (name === REMINDER_CANCEL_TOOL.name) done = unreminding(id, args.conversation, args.reminder);
|
|
1278
|
+
else {
|
|
1279
|
+
const act = { [WAKE_TOOL.name]: 'wake', [SLEEP_TOOL.name]: 'sleep', [STOP_TOOL.name]: 'stop' }[name];
|
|
1280
|
+
done = act ? await acting(id, args.conversation, act) : await saying(id, args.conversation, args.text);
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
note(id, 201, what);
|
|
1284
|
+
return send(200, { jsonrpc: '2.0', id: msg.id, result: { content: [{ type: 'text', text: JSON.stringify(done) }], structuredContent: done, isError: false } });
|
|
1285
|
+
} catch (error) {
|
|
1286
|
+
if (!(error instanceof Refusal)) throw error;
|
|
1287
|
+
/* Not given: refused as the API refuses it (too many, too). Anything else is the tool's own failure, said to the caller. */
|
|
1288
|
+
if (error.status === 429) { note(id, 429, what); return send(429, { jsonrpc: '2.0', id: msg.id, error: { code: -32002, message: error.message } }, { 'retry-after': String(error.retry ?? 60) }); }
|
|
1289
|
+
/* (An HTTP 403 for a scope not given is what the MCP authorization spec says: kept, MCP review 11-11.) */
|
|
1290
|
+
if (error.status === 403) { note(id, 403, what); return send(403, { jsonrpc: '2.0', id: msg.id, error: { code: -32001, message: error.message } }); }
|
|
1291
|
+
note(id, error.status, what);
|
|
1292
|
+
return send(200, { jsonrpc: '2.0', id: msg.id, result: { content: [{ type: 'text', text: error.message }], isError: true } });
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
default: return fail(-32601, 'Method not found');
|
|
1296
|
+
}
|
|
1297
|
+
}
|
|
1298
|
+
note(null, 404);
|
|
1299
|
+
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.' });
|
|
1300
|
+
} catch (error) {
|
|
1301
|
+
if (error instanceof Refusal) return refused(error);
|
|
1302
|
+
note(null, 500);
|
|
1303
|
+
return send(500, { error: 'Something failed on the server.' });
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
/* Settings, Access, "API keys": for whoever passed the gate. */
|
|
1308
|
+
export async function handleApiKeys(request, response, keys, originOk, headers = {}, events = null) {
|
|
1309
|
+
const { pathname } = new URL(request.url ?? '/', 'http://local');
|
|
1310
|
+
if (pathname !== '/api/apikeys' && !pathname.startsWith('/api/apikeys/')) return false;
|
|
1311
|
+
const send = (status, body) => { response.writeHead(status, { ...headers, 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }).end(JSON.stringify(body)); return true; };
|
|
1312
|
+
const who = String(request.headers['x-forwarded-email'] ?? '').trim().toLowerCase();
|
|
1313
|
+
try {
|
|
1314
|
+
if (request.method === 'GET' && pathname === '/api/apikeys') return send(200, { keys: keys.list(), scopes: keys.scopes(), defaultDays: DEFAULT_DAYS, me: who || null });
|
|
1315
|
+
const journal = /^\/api\/apikeys\/([0-9a-f-]{36})\/journal$/.exec(pathname);
|
|
1316
|
+
if (request.method === 'GET' && journal) return send(200, { uses: keys.journal(journal[1]) });
|
|
1317
|
+
if (request.method !== 'POST') return false;
|
|
1318
|
+
if (!originOk(request.headers) || !String(request.headers['content-type'] ?? '').startsWith('application/json')) return send(403, { error: 'This request does not come from this site.' });
|
|
1319
|
+
let text = '';
|
|
1320
|
+
for await (const piece of request) { text += piece; if (text.length > 16_384) return send(413, { error: 'Too long.' }); }
|
|
1321
|
+
let body;
|
|
1322
|
+
try { body = text ? JSON.parse(text) : {}; } catch { return send(400, { error: 'The request is not JSON.' }); }
|
|
1323
|
+
if (!body || typeof body !== 'object') body = {};
|
|
1324
|
+
if (pathname === '/api/apikeys') {
|
|
1325
|
+
const made = keys.create({ label: body.label, scopes: body.scopes ?? [], conversations: body.conversations ?? {}, rooms: body.rooms ?? {}, boxes: body.boxes ?? {}, binders: body.binders ?? {}, days: body.days === undefined ? DEFAULT_DAYS : body.days }, who);
|
|
1326
|
+
/* Its name and scopes; never the secret. */
|
|
1327
|
+
const what = [...made.key.scopes, ...made.key.conversations.map((c) => `${c.name} ${c.level}`), ...made.key.rooms.map((r) => `room ${r.id.slice(0, 8)} ${r.level}`), ...made.key.boxes.map((b) => `voice box ${b.id.slice(0, 8)} ${b.level}`), ...made.key.binders.map((l) => `binder ${l.id.slice(0, 40)} ${l.level}`)];
|
|
1328
|
+
events?.add({ kind: 'access', text: `API key "${made.key.label}" made${what.length ? ` (${what.join(', ')})` : ' (no scope)'}`, who: who || null });
|
|
1329
|
+
return send(201, made);
|
|
1330
|
+
}
|
|
1331
|
+
const scoping = /^\/api\/apikeys\/([0-9a-f-]{36})\/scopes$/.exec(pathname);
|
|
1332
|
+
if (scoping) {
|
|
1333
|
+
const key = keys.setScope(scoping[1], body.scope, body.on);
|
|
1334
|
+
events?.add({ kind: 'access', text: `API key "${key.label}": ${String(body.scope).slice(0, 40)} ${body.on ? 'given' : 'taken back'}`, who: who || null });
|
|
1335
|
+
return send(200, { key });
|
|
1336
|
+
}
|
|
1337
|
+
const giving = /^\/api\/apikeys\/([0-9a-f-]{36})\/conversations$/.exec(pathname);
|
|
1338
|
+
if (giving) {
|
|
1339
|
+
const level = body.level === undefined ? null : body.level;
|
|
1340
|
+
const key = keys.setConversation(giving[1], body.conversation, level);
|
|
1341
|
+
events?.add({ kind: 'access', text: `API key "${key.label}": ${body.conversation} ${level ?? 'taken back'}`, who: who || null });
|
|
1342
|
+
return send(200, { key });
|
|
1343
|
+
}
|
|
1344
|
+
const one = /^\/api\/apikeys\/([0-9a-f-]{36})\/(rooms|boxes)$/.exec(pathname);
|
|
1345
|
+
if (one) {
|
|
1346
|
+
const level = body.level === undefined ? null : body.level;
|
|
1347
|
+
const room = one[2] === 'rooms';
|
|
1348
|
+
const ref = room ? body.room : body.box;
|
|
1349
|
+
const key = room ? keys.setRoom(one[1], ref, level) : keys.setBox(one[1], ref, level);
|
|
1350
|
+
events?.add({ kind: 'access', text: `API key "${key.label}": ${room ? 'room' : 'voice box'} ${String(ref).slice(0, 8)} ${level ?? 'taken back'}`, who: who || null });
|
|
1351
|
+
return send(200, { key });
|
|
1352
|
+
}
|
|
1353
|
+
const binding = /^\/api\/apikeys\/([0-9a-f-]{36})\/binders$/.exec(pathname);
|
|
1354
|
+
if (binding) {
|
|
1355
|
+
const level = body.level === undefined ? null : body.level;
|
|
1356
|
+
const key = keys.setBinder(binding[1], body.binder, level, who);
|
|
1357
|
+
events?.add({ kind: 'access', text: `API key "${key.label}": binder ${String(body.binder).slice(0, 40)} ${level ?? 'taken back'}`, who: who || null });
|
|
1358
|
+
return send(200, { key });
|
|
1359
|
+
}
|
|
1360
|
+
const revoke = /^\/api\/apikeys\/([0-9a-f-]{36})\/revoke$/.exec(pathname);
|
|
1361
|
+
if (revoke) {
|
|
1362
|
+
const label = keys.get(revoke[1])?.label;
|
|
1363
|
+
keys.revoke(revoke[1]);
|
|
1364
|
+
events?.add({ kind: 'access', text: `API key "${label}" revoked`, who: who || null });
|
|
1365
|
+
return send(200, { ok: true });
|
|
1366
|
+
}
|
|
1367
|
+
return false;
|
|
1368
|
+
} catch (error) {
|
|
1369
|
+
if (error instanceof Refusal) return send(error.status, { error: error.message });
|
|
1370
|
+
return send(500, { error: 'Something failed on the server.' });
|
|
1371
|
+
}
|
|
1372
|
+
}
|