@miadi/connector 0.1.43 → 0.1.45

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.
@@ -0,0 +1,455 @@
1
+ /**
2
+ * The Screenwalk Registry, read through Miadi's registry door as the signed-in person
3
+ * (GET /api/screenwalks/registrations and /api/screenwalks/registrations/<id>), and what relates a
4
+ * registration to the Miadi Review of its video.
5
+ *
6
+ * Three owners, kept apart. The registry owns the registration: its names, its question sets and
7
+ * their answers, its purpose lists, its relations. The connector supplies authorized access: every
8
+ * call carries the person's own Miadi token, so the registry's rights decide what is read and what
9
+ * is written. A review consumes a registered video as its source, under a separate decision.
10
+ *
11
+ * A screenwalk is named by its registry id. The episode that keeps its file is not part of its
12
+ * identity and is never used to find it.
13
+ *
14
+ * A registration is not a review, and its answers are not a transcript: nothing here copies one
15
+ * into the other.
16
+ */
17
+ import { createHash } from "node:crypto";
18
+ import { MiadiError } from "./miadi.js";
19
+ import { reviewIdOf, videoIdOf } from "./reviews.js";
20
+ /** The registry's id rule: six to ten digits, then optional "-word" parts, lower case. */
21
+ const ID = /^[0-9]{6,10}(?:-[0-9a-z]+)*$/;
22
+ const ADDRESS = /^miadi-screenwalk:(?:\/\/)?(.+)$/i;
23
+ const VIDEO_ID = /^[A-Za-z0-9_-]{11}$/;
24
+ const REVIEW_ADDRESS = /^(?:miadi-)?review:(?:\/\/)?([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
25
+ /**
26
+ * The name the connector's records already give a link from a source to the review made of it
27
+ * (link_records, from the source to miadi-review:<uuid>). A registered screenwalk is such a source.
28
+ */
29
+ export const REVIEW_SOURCE_RELATION = "review_created_from_source";
30
+ /** The registry's relation kind for an external record that points at the same work. */
31
+ export const REGISTRY_REVIEW_KIND = "correlates";
32
+ export const DEFAULT_REGISTRATION_BYTES = 100_000;
33
+ export const MAX_REGISTRATION_BYTES = 512 * 1024;
34
+ export const MIN_REGISTRATION_BYTES = 4_000;
35
+ export class ScreenwalkRefusal extends Error {
36
+ code;
37
+ detail;
38
+ constructor(code, message, detail) {
39
+ super(message);
40
+ this.code = code;
41
+ this.detail = detail;
42
+ }
43
+ }
44
+ /** The origins a screenwalk URL may carry: this factory's public address and the address the connector calls. */
45
+ export function registryOrigins(config) {
46
+ const out = new Set();
47
+ for (const url of [config.miadiPublicUrl, config.miadiUrl]) {
48
+ try {
49
+ out.add(new URL(url).origin);
50
+ }
51
+ catch {
52
+ /* an unreadable address names no origin */
53
+ }
54
+ }
55
+ return [...out];
56
+ }
57
+ const FORMS = "Give the registry id (2612021410), miadi-screenwalk:<id>, or the screenwalk's page URL on this factory's registry.";
58
+ function idOf(raw) {
59
+ let value = raw;
60
+ try {
61
+ value = decodeURIComponent(raw);
62
+ }
63
+ catch {
64
+ return null;
65
+ }
66
+ const address = ADDRESS.exec(value.trim());
67
+ const id = (address ? address[1] : value).trim().toLowerCase();
68
+ return ID.test(id) ? id : null;
69
+ }
70
+ /**
71
+ * The screenwalk a reference names. A URL is only read for the id it carries, and only when it is on
72
+ * one of the given origins: nothing is fetched from an address a caller supplies.
73
+ */
74
+ export function screenwalkRefOf(input, origins) {
75
+ const given = input.trim();
76
+ const made = (id, form) => ({ id, reference: `miadi-screenwalk:${id}`, form });
77
+ if (/^https?:\/\//i.test(given)) {
78
+ let url;
79
+ try {
80
+ url = new URL(given);
81
+ }
82
+ catch {
83
+ throw new ScreenwalkRefusal("invalid_ref", `That URL cannot be read. ${FORMS}`);
84
+ }
85
+ if (!origins.includes(url.origin)) {
86
+ throw new ScreenwalkRefusal("invalid_ref", `That URL is not on this factory's screenwalk registry, so it was not opened. ${FORMS}`);
87
+ }
88
+ const page = /^\/screenwalks\/([^/]+)\/?$/.exec(url.pathname);
89
+ const record = /^\/api\/screenwalks\/registrations\/([^/]+)\/?$/.exec(url.pathname);
90
+ const id = idOf((page ?? record)?.[1] ?? "");
91
+ if (!id)
92
+ throw new ScreenwalkRefusal("invalid_ref", `That URL is on the registry but is not one screenwalk's page. ${FORMS}`);
93
+ return made(id, page ? "page_url" : "record_url");
94
+ }
95
+ const address = ADDRESS.test(given);
96
+ const id = idOf(given);
97
+ if (!id)
98
+ throw new ScreenwalkRefusal("invalid_ref", `"${given.slice(0, 80)}" names no screenwalk. ${FORMS}`);
99
+ return made(id, address ? "address" : "id");
100
+ }
101
+ /** True when a reference a caller gave should be read as a screenwalk before anything else: its address, or a registry URL. */
102
+ export function looksLikeScreenwalk(input, origins) {
103
+ const given = input.trim();
104
+ if (ADDRESS.test(given))
105
+ return true;
106
+ if (!/^https?:\/\//i.test(given))
107
+ return false;
108
+ try {
109
+ const url = new URL(given);
110
+ return origins.includes(url.origin) && /^\/(?:api\/screenwalks\/registrations|screenwalks)\/[^/]+\/?$/.test(url.pathname) && !/^\/screenwalks\/(?:new|names)\/?$/.test(url.pathname);
111
+ }
112
+ catch {
113
+ return false;
114
+ }
115
+ }
116
+ const doorPath = (id) => `/api/screenwalks/registrations/${encodeURIComponent(id)}`;
117
+ /** What the registry's refusal means, in words that leak nothing the registry did not say. */
118
+ function failureOf(error, what) {
119
+ if (!(error instanceof MiadiError))
120
+ throw error;
121
+ const s = error.status;
122
+ if (s === 0 || s >= 500)
123
+ return { state: "unavailable", status: s, message: `The screenwalk registry could not be reached${s ? ` (it answered ${s})` : ""}. Nothing is known about ${what} from this call.` };
124
+ if (s === 401)
125
+ return { state: "unauthorized", status: s, message: "The registry did not recognise your sign-in. Sign in to Miadi again." };
126
+ if (s === 403)
127
+ return { state: "forbidden", status: s, message: "Screenwalk registrations are read by their stewards and reviewers. Your sign-in holds neither right." };
128
+ if (s === 404)
129
+ return { state: "not_found", status: s, message: `No screenwalk registration answers to ${what} for your sign-in: none exists, or your rights do not reach it. The registry does not say which.` };
130
+ return { state: "registry_error", status: s, message: `The registry refused the read (${s}).` };
131
+ }
132
+ /** One registration, read as the person. The registry's own rights decide the answer. */
133
+ export async function readRegistration(miadi, token, id) {
134
+ let body;
135
+ try {
136
+ body = await miadi.get(token, doorPath(id));
137
+ }
138
+ catch (error) {
139
+ return failureOf(error, `miadi-screenwalk:${id}`);
140
+ }
141
+ const registration = body?.registration;
142
+ if (!registration || typeof registration !== "object" || registration.screenwalk !== id || !Number.isInteger(registration.revision)) {
143
+ return { state: "registry_error", status: 200, message: "The registry's answer was not this screenwalk's registration." };
144
+ }
145
+ return { state: "found", registration, summary: body.summary && typeof body.summary === "object" ? body.summary : null };
146
+ }
147
+ /** The registry's Markdown brief (the door's own projection), whole or for one purpose list. */
148
+ export async function readBrief(miadi, token, id, purpose) {
149
+ try {
150
+ const text = await miadi.get(token, `${doorPath(id)}?format=brief${purpose ? `&purpose=${encodeURIComponent(purpose)}` : ""}`);
151
+ if (typeof text !== "string" || !text.trim())
152
+ return { state: "registry_error", status: 200, message: "The registry's answer was not a brief." };
153
+ return { state: "found", markdown: text };
154
+ }
155
+ catch (error) {
156
+ return failureOf(error, `miadi-screenwalk:${id}`);
157
+ }
158
+ }
159
+ /** The registry's moment index (the door's own projection): one row per timeframe, with the revision it was read at. */
160
+ export async function readMoments(miadi, token, id) {
161
+ try {
162
+ const body = await miadi.get(token, `${doorPath(id)}?format=moments`);
163
+ if (!body || !Array.isArray(body.moments))
164
+ return { state: "registry_error", status: 200, message: "The registry's answer was not a moment index." };
165
+ return { state: "found", revision: Number.isInteger(body.revision) ? body.revision : null, moments: body.moments };
166
+ }
167
+ catch (error) {
168
+ return failureOf(error, `miadi-screenwalk:${id}`);
169
+ }
170
+ }
171
+ /** The registrations the person may see, as the registry's list door returns them (its own filters applied there). */
172
+ export async function listRegistrations(miadi, token, filters = {}) {
173
+ const query = new URLSearchParams();
174
+ for (const [k, v] of Object.entries(filters))
175
+ if (v)
176
+ query.set(k, v);
177
+ try {
178
+ const body = await miadi.get(token, `/api/screenwalks/registrations${query.size ? `?${query}` : ""}`);
179
+ if (!body || !Array.isArray(body.registrations))
180
+ return { state: "registry_error", status: 200, message: "The registry's answer was not a list of registrations." };
181
+ return { state: "found", registrations: body.registrations };
182
+ }
183
+ catch (error) {
184
+ return failureOf(error, "the registry's list");
185
+ }
186
+ }
187
+ /** Write one relation on a registration, as the person, naming the revision read. The registry validates and lands it. */
188
+ export async function relateRegistration(miadi, token, id, expectedRevision, relation) {
189
+ try {
190
+ const out = await miadi.post(token, doorPath(id), { action: "relate", expected_revision: expectedRevision, relation });
191
+ return { state: "recorded", revision: Number.isInteger(out?.registration?.revision) ? out.registration.revision : null, landing: out?.landing ?? null };
192
+ }
193
+ catch (error) {
194
+ if (!(error instanceof MiadiError))
195
+ throw error;
196
+ const said = typeof error.body?.message === "string" ? String(error.body.message) : "";
197
+ const s = error.status;
198
+ if (s === 409 && /already held/i.test(said))
199
+ return { state: "held" };
200
+ if (s === 409)
201
+ return { state: "not_recorded", reason: "conflict", status: s, message: "The registration changed while this ran. Ask again: the step is safe to repeat." };
202
+ if (s === 403)
203
+ return { state: "not_recorded", reason: "forbidden", status: s, message: "Writing a relation on a registration takes the right to steward screenwalk registrations (screenwalk_steward), which your sign-in does not hold." };
204
+ if (s === 0 || s >= 500)
205
+ return { state: "not_recorded", reason: "unavailable", status: s, message: "The registry could not be reached to write the relation. Ask again later: the step is safe to repeat." };
206
+ return { state: "not_recorded", reason: "refused", status: s, message: said ? `The registry refused the relation: ${said}` : `The registry refused the relation (${s}).` };
207
+ }
208
+ }
209
+ /** The registered video with its canonical YouTube identity. A missing field is null, never guessed. */
210
+ export function videoOf(registration) {
211
+ const v = (registration.video ?? {});
212
+ const url = typeof v.url === "string" && v.url ? v.url : null;
213
+ const found = url ? videoIdOf(url) : null;
214
+ const id = found && VIDEO_ID.test(found) ? found : null;
215
+ const text = (x) => (typeof x === "string" && x ? x : null);
216
+ return {
217
+ url,
218
+ video_id: id,
219
+ canonical_url: id ? `https://www.youtube.com/watch?v=${id}` : null,
220
+ uploaded_title: text(v.uploaded_title),
221
+ duration: text(v.duration),
222
+ published_at: text(v.published_at),
223
+ channel: text(v.channel),
224
+ captions: text(v.captions),
225
+ };
226
+ }
227
+ /**
228
+ * The safe title, title and description as they stand, with the registry's own word for where they stand
229
+ * (proposed, needs_review, approved, approved_with_changes, rejected). The registry's summary gives the
230
+ * approved names once a person approved them, else the last proposal.
231
+ */
232
+ export function namesOf(registration, summary) {
233
+ const rounds = Array.isArray(registration.rounds) ? registration.rounds : [];
234
+ const last = rounds[rounds.length - 1];
235
+ const decisions = Array.isArray(registration.decisions) ? registration.decisions : [];
236
+ const decided = decisions[decisions.length - 1];
237
+ const current = (summary?.current ?? last?.proposal ?? {});
238
+ const text = (x) => (typeof x === "string" && x ? x : null);
239
+ const approved = typeof summary?.approved === "boolean" ? summary.approved : registration.status === "approved" || registration.status === "approved_with_changes";
240
+ return {
241
+ state: text(registration.status),
242
+ approved,
243
+ round: typeof last?.round === "number" ? last.round : rounds.length,
244
+ round_state: text(last?.state),
245
+ safe_title: text(current.safe_title),
246
+ title: text(current.title),
247
+ description: text(current.description),
248
+ uploaded_title: text(registration.video?.uploaded_title),
249
+ last_decision: decided ? { decision: text(decided.decision), by: text(decided.by?.name), at: text(decided.at) } : null,
250
+ };
251
+ }
252
+ const list = (x) => (Array.isArray(x) ? x : []);
253
+ /** What the registration holds, counted from its own parts. Zero means the part is empty; null means the registry records nothing there. */
254
+ export function inventoryOf(registration) {
255
+ const k = (registration.knowledge ?? {});
256
+ const prompts = list(k.prompts);
257
+ const sets = {};
258
+ for (const p of prompts)
259
+ sets[typeof p?.state === "string" ? p.state : "state_not_recorded"] = (sets[typeof p?.state === "string" ? p.state : "state_not_recorded"] ?? 0) + 1;
260
+ const purposes = list(registration.purposes);
261
+ const relations = list(registration.relations);
262
+ const byKind = {};
263
+ for (const r of relations)
264
+ byKind[String(r?.kind)] = (byKind[String(r?.kind)] ?? 0) + 1;
265
+ return {
266
+ question_sets: prompts.length,
267
+ question_set_states: sets,
268
+ transcript: typeof k.transcript?.state === "string" ? k.transcript.state : null,
269
+ transcript_parts: list(k.transcript?.parts).length,
270
+ segments: list(k.segments).length,
271
+ segmentations: list(k.segmentations).length,
272
+ aspects: list(k.aspects).length,
273
+ sources: list(k.sources).length,
274
+ questions: list(k.questions).length,
275
+ observations: list(k.observations).length,
276
+ purpose_lists: purposes.length,
277
+ purpose_items: purposes.reduce((n, l) => n + list(l?.segments).length, 0),
278
+ purposes: purposes.map((l) => ({ id: l?.id ?? null, purpose: l?.purpose ?? null, label: l?.label ?? null, items: list(l?.segments).length, ...(l?.duplicate_of ? { duplicate_of: l.duplicate_of.of ?? null } : {}) })),
279
+ relations: relations.length,
280
+ relations_by_kind: byKind,
281
+ names_heard: list(registration.names).length,
282
+ topics: list(registration.topics).length,
283
+ notices: list(registration.notices).filter((n) => !n?.withdrawn).length,
284
+ resupply_open: list(registration.resupply).filter((q) => !q?.supplied).length,
285
+ testimonies: list(registration.testimonies).length,
286
+ amendments: list(registration.amendments).length,
287
+ };
288
+ }
289
+ /**
290
+ * Where a registration stands, each thing by its own name. The registry records where the names stand with a
291
+ * person, how far the questioning reaches and what a person checked. It records no validation verdict: a
292
+ * registration that exists says nothing about another agent's validation pass.
293
+ */
294
+ export function readinessOf(registration, summary) {
295
+ return {
296
+ names: typeof registration.status === "string" ? registration.status : null,
297
+ coverage: registration.coverage?.level ?? null,
298
+ coverage_note: registration.coverage?.note ?? null,
299
+ checked_by_a_person: summary?.detail?.checked ?? null,
300
+ unverified_items: typeof summary?.counts?.unverified === "number" ? summary.counts.unverified : null,
301
+ transcript: typeof registration.knowledge?.transcript?.state === "string" ? registration.knowledge.transcript.state : null,
302
+ validation: "not recorded by the registry",
303
+ };
304
+ }
305
+ const bytesOf = (value) => Buffer.byteLength(JSON.stringify(value) ?? "", "utf8");
306
+ /** Each top-level part of a registration with its size, so a caller can ask for the parts it needs. */
307
+ export function partIndex(registration) {
308
+ return Object.keys(registration).map((part) => ({ part, bytes: bytesOf(registration[part]), items: Array.isArray(registration[part]) ? registration[part].length : null }));
309
+ }
310
+ const IDENTITY_PARTS = ["schema", "screenwalk", "reference", "revision", "status"];
311
+ /**
312
+ * The registration, or the parts asked for, in the registry's own schema. With parts, the identity keys come with
313
+ * them. With a purpose, only that purpose list stays among the purposes. Whatever was left out is named.
314
+ */
315
+ export function selectRegistration(registration, options = {}) {
316
+ const keys = Object.keys(registration);
317
+ const wanted = options.parts?.length ? [...new Set(options.parts)] : null;
318
+ const unknown = wanted ? wanted.filter((p) => !keys.includes(p)) : [];
319
+ if (unknown.length)
320
+ throw new ScreenwalkRefusal("invalid_part", `This registration has no part ${unknown.map((p) => `"${p}"`).join(", ")}.`, { parts: keys });
321
+ const purposes = list(registration.purposes);
322
+ if (options.purpose && !purposes.some((l) => l?.id === options.purpose)) {
323
+ throw new ScreenwalkRefusal("purpose_not_found", `No purpose list "${options.purpose}" in this registration.`, { purposes: purposes.map((l) => l?.id) });
324
+ }
325
+ const returned = wanted ? keys.filter((k) => IDENTITY_PARTS.includes(k) || wanted.includes(k)) : keys;
326
+ const value = {};
327
+ for (const k of returned)
328
+ value[k] = registration[k];
329
+ let purposesLeftOut = [];
330
+ if (options.purpose && "purposes" in value) {
331
+ value.purposes = purposes.filter((l) => l?.id === options.purpose);
332
+ purposesLeftOut = purposes.filter((l) => l?.id !== options.purpose).map((l) => String(l?.id));
333
+ }
334
+ return {
335
+ value,
336
+ returned,
337
+ left_out: keys.filter((k) => !returned.includes(k)),
338
+ ...(options.purpose ? { purpose: options.purpose, purposes_left_out: purposesLeftOut } : {}),
339
+ };
340
+ }
341
+ const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
342
+ /**
343
+ * One page of a text. A page never starts or ends inside a character. revision, when given, must still be the
344
+ * text's sha256, so pages of two revisions of a registration are never joined.
345
+ */
346
+ export function pageText(content, options = {}) {
347
+ const bytes = Buffer.from(content, "utf8");
348
+ const total = bytes.byteLength;
349
+ const whole = sha256(bytes);
350
+ if (options.revision && options.revision !== whole) {
351
+ throw new ScreenwalkRefusal("changed", "What you were reading changed since that page was read (the registration has a new revision, or the selection differs). Read it again from offset 0.");
352
+ }
353
+ const offset = options.offset ?? 0;
354
+ const max = Math.min(MAX_REGISTRATION_BYTES, Math.max(MIN_REGISTRATION_BYTES, options.maxBytes ?? DEFAULT_REGISTRATION_BYTES));
355
+ if (!Number.isInteger(offset) || offset < 0 || offset > total || (offset < total && (bytes[offset] & 0xc0) === 0x80)) {
356
+ throw new ScreenwalkRefusal("invalid_offset", `offset must be 0 or a next.offset this tool returned (there are ${total} bytes).`);
357
+ }
358
+ let end = Math.min(total, offset + max);
359
+ while (end < total && (bytes[end] & 0xc0) === 0x80)
360
+ end--;
361
+ const complete = offset === 0 && end === total;
362
+ return {
363
+ bytes: total,
364
+ sha256: whole,
365
+ complete,
366
+ page: { offset, end, bytes: end - offset, next: end === total ? null : { offset: end, revision: whole } },
367
+ text: bytes.subarray(offset, end).toString("utf8"),
368
+ };
369
+ }
370
+ /** The review a reference names, when it is a review's address. */
371
+ function reviewOf(value) {
372
+ if (typeof value !== "string")
373
+ return null;
374
+ const m = REVIEW_ADDRESS.exec(value.trim());
375
+ return m ? m[1].toLowerCase() : null;
376
+ }
377
+ /** The screenwalk a reference names, when it is a screenwalk's address. */
378
+ function walkOf(value) {
379
+ if (typeof value !== "string")
380
+ return null;
381
+ const m = ADDRESS.exec(value.trim());
382
+ const id = m ? m[1].trim().toLowerCase() : null;
383
+ return id && ID.test(id) ? id : null;
384
+ }
385
+ /** The relations a registration itself holds toward a review: the registration's side of the relation. */
386
+ export function reviewRelationsOf(registration) {
387
+ return list(registration.relations).flatMap((r) => {
388
+ const review = reviewOf(r?.target);
389
+ return review ? [{ id: String(r.id), kind: String(r.kind), target: String(r.target), review_id: review, by: typeof r.by === "string" ? r.by : null, at: typeof r.at === "string" ? r.at : null }] : [];
390
+ });
391
+ }
392
+ /** True when a connector record names this screenwalk: in what it cites, in a link's ends, or as the source of a request. */
393
+ export function namesScreenwalk(record, id) {
394
+ const is = (value) => walkOf(value) === id;
395
+ const body = record.body;
396
+ return record.refs.some(is) || record.evidence_refs.some(is) || is(body.from) || is(body.to) || is(body.source?.reference);
397
+ }
398
+ /**
399
+ * The connector's records that relate a screenwalk to a review: a link from the registration to a review, and a
400
+ * review operation asked with the registration as its source (its receipt names the review once it is created).
401
+ */
402
+ export function reviewRecordsOf(records, id) {
403
+ const out = [];
404
+ for (const r of records) {
405
+ if (r.kind !== "link" && r.kind !== "review_operation_request")
406
+ continue;
407
+ if (!namesScreenwalk(r, id))
408
+ continue;
409
+ const body = r.body;
410
+ const answered = r.completion_receipt?.response?.id;
411
+ const review = r.kind === "link"
412
+ ? (reviewOf(body.to) ?? reviewOf(body.from))
413
+ : ((typeof answered === "string" ? reviewIdOf(answered) : null) ?? (typeof body.review_id === "string" ? reviewIdOf(body.review_id) : null) ?? r.refs.map(reviewOf).find(Boolean) ?? null);
414
+ if (r.kind === "link" && !review)
415
+ continue;
416
+ out.push({
417
+ record: r.id,
418
+ kind: r.kind,
419
+ created_at: r.created_at,
420
+ by: r.actor.name,
421
+ ...(r.kind === "link" && typeof body.relation === "string" ? { relation: body.relation } : {}),
422
+ review_id: review,
423
+ ...(r.approval_state ? { approval_state: r.approval_state } : {}),
424
+ ...(r.state ? { state: r.state } : {}),
425
+ });
426
+ }
427
+ return out;
428
+ }
429
+ /** The screenwalks the connector's records relate to a review: the review's side of the relation. */
430
+ export function screenwalksOfReview(records, reviewId) {
431
+ const id = reviewId.toLowerCase();
432
+ const out = [];
433
+ for (const r of records) {
434
+ if (r.kind !== "link" && r.kind !== "review_operation_request")
435
+ continue;
436
+ const body = r.body;
437
+ const answered = r.completion_receipt?.response?.id;
438
+ const names = r.refs.some((x) => reviewOf(x) === id) ||
439
+ reviewOf(body.from) === id ||
440
+ reviewOf(body.to) === id ||
441
+ (typeof body.review_id === "string" && body.review_id.toLowerCase() === id) ||
442
+ (typeof answered === "string" && answered.toLowerCase() === id);
443
+ if (!names)
444
+ continue;
445
+ const walks = new Set();
446
+ for (const value of [...r.refs, ...r.evidence_refs, body.from, body.to, body.source?.reference]) {
447
+ const walk = walkOf(value);
448
+ if (walk)
449
+ walks.add(walk);
450
+ }
451
+ for (const walk of walks)
452
+ out.push({ reference: `miadi-screenwalk:${walk}`, record: r.id, kind: r.kind, ...(r.kind === "link" && typeof body.relation === "string" ? { relation: body.relation } : {}) });
453
+ }
454
+ return out;
455
+ }
package/dist/server.d.ts CHANGED
@@ -3,7 +3,8 @@
3
3
  *
4
4
  * /.well-known/oauth-* OAuth discovery (MCP authorization spec)
5
5
  * /authorize /token /register /revoke, /authorize/confirm sign-in
6
- * /mcp the MCP endpoint (streamable HTTP, stateless)
6
+ * /mcp the MCP endpoint (streamable HTTP, stateless; a client with no
7
+ * client id is given a session id, kept only to name its tool list)
7
8
  * /health liveness, no data
8
9
  *
9
10
  * Every MCP request carries the signed-in person, and each tool call runs
@@ -61,4 +62,4 @@ export declare function createConnectorApp(config: ConnectorConfig, deps: Connec
61
62
  provider: MiadiOAuthProvider;
62
63
  ledger: Ledger<ConnectorRecord>;
63
64
  };
64
- export declare const INSTRUCTIONS = "Miadi is a relational software factory: agent sessions, Miadi reviews of screenwalks, Chronicle episodes, talking circles and the five accountable circles (Story, Stewardship, Engineering, Evaluation, Continuity) across three domains (Creative, Ceremonial, Engineering).\n\nStart with get_capabilities: it says who you are signed in as, which tools are live, and which return not_implemented.\n\nEvery tool is offered on every connection. A client that loads tools on demand shows only those its last tool search matched: a tool you do not see is not missing. Search for it by its exact name, get_capabilities first, before telling the person a tool is absent. The main reads are get_capabilities, get_context, search, fetch, list_records, list_sessions, search_sessions, get_session, review_lookup, read_episode_file and show_decisions.\n\nRules every tool keeps:\n- Every record names the person who made it, with a claim category: observed, hypothesis, desired_future, fiction or verified_implementation. Keep fiction and desired futures apart from what was observed.\n- Requests (runs, work proposals, review operations, Deep Diver, review-to-episode links, inquiry-to-episode weaves, session completion) are recorded as awaiting_approval. Nothing runs, publishes or closes until a person decides. After making a request, call show_decisions: it shows the request as a card in the conversation, where the person decides with their own click (or follows its approval page). Never claim a decision the card has not reported. The person may approve, approve with changes (their instructions are carried into what runs), send it back for revision with instructions (approval_state revision_requested; read the instructions with get_run_result and revise it in place with revise_pending_request), or decline.\n- A new or revised run or work proposal answers with draft_review: the aspects of the mission standard to revise, each with why, the question to settle and who can settle it. Read it before show_decisions. It carries no verdict, it advises and blocks nothing, and next_action says what to do. Answer what your conversation holds, ask the person the rest, then revise. preferences lists the person's standing preferences for you to apply. Fill delivery with the one exact place the result lands, and person_words with the person's own words, verbatim, for anything credited to them.\n- A mission is revised, never re-requested: to change a run or work proposal that still awaits a decision, call revise_pending_request with its id and the version you read (expected_version). It keeps one id, one approval page and one card; get_request_history shows every version. A new request_authorized_run or propose_work is for a new mission only. Requests made earlier as separate versions are joined with supersede_pending_requests, naming their exact ids, only when the person names or confirms them.\n- A research report (a Deep Research report) is delivered with save_research exactly as written, never summarised or shortened, with its sources; a long report goes in parts. Check the bytes and first and last lines the answer returns against what you sent.\n- A review's transcript is acquired by ensure_review_transcript, for a review made anywhere. It needs no decision and no pasted text, takes the video's own captions, or transcribes its audio on the Miadi host when the video has none, never overwrites and calls no model service. review_lookup and review_versions carry the transcript's state (unknown, absent, acquiring, stored, held or failed). review_transcript_status follows a job, and every answer carries plain links that work when no card is shown.\n- An unknown id is answered as not found, never invented. A missing backing service is answered as unavailable.\n- Use the miadi-review:<uuid>, miadi-chronicle://<n>, owner/repo#n and session:<uuid> reference forms.";
65
+ export declare const INSTRUCTIONS = "Miadi is a relational software factory: agent sessions, Miadi reviews of screenwalks, Chronicle episodes, talking circles and the five accountable circles (Story, Stewardship, Engineering, Evaluation, Continuity) across three domains (Creative, Ceremonial, Engineering).\n\nStart with get_capabilities: it says who you are signed in as, which tools are live, and which return not_implemented. When its answer carries client_tools, the tool list your client holds is older than this server or not recorded: a tool named there is offered by the server and cannot be called from your client until a person makes it fetch the list again. Tell the person the sentence it gives, and use what until_refresh names meanwhile.\n\nEvery tool is offered on every connection. A client that loads tools on demand shows only those its last tool search matched: a tool you do not see is not missing. Search for it by its exact name, get_capabilities first, before telling the person a tool is absent. The main reads are get_capabilities, get_context, search, fetch, list_records, list_sessions, search_sessions, get_session, review_lookup, get_screenwalk, list_screenwalks, read_episode_file and show_decisions.\n\nRules every tool keeps:\n- Every record names the person who made it, with a claim category: observed, hypothesis, desired_future, fiction or verified_implementation. Keep fiction and desired futures apart from what was observed.\n- Requests (runs, work proposals, review operations, Deep Diver, review-to-episode links, inquiry-to-episode weaves, session completion) are recorded as awaiting_approval. Nothing runs, publishes or closes until a person decides. After making a request, call show_decisions: it shows the request as a card in the conversation, where the person decides with their own click (or follows its approval page). Never claim a decision the card has not reported. The person may approve, approve with changes (their instructions are carried into what runs), send it back for revision with instructions (approval_state revision_requested; read the instructions with get_run_result and revise it in place with revise_pending_request), or decline.\n- A new or revised run or work proposal answers with draft_review: the aspects of the mission standard to revise, each with why, the question to settle and who can settle it. Read it before show_decisions. It carries no verdict, it advises and blocks nothing, and next_action says what to do. Answer what your conversation holds, ask the person the rest, then revise. preferences lists the person's standing preferences for you to apply. Fill delivery with the one exact place the result lands, and person_words with the person's own words, verbatim, for anything credited to them.\n- A mission is revised, never re-requested: to change a run or work proposal that still awaits a decision, call revise_pending_request with its id and the version you read (expected_version). It keeps one id, one approval page and one card; get_request_history shows every version. A new request_authorized_run or propose_work is for a new mission only. Requests made earlier as separate versions are joined with supersede_pending_requests, naming their exact ids, only when the person names or confirms them.\n- A research report (a Deep Research report) is delivered with save_research exactly as written, never summarised or shortened, with its sources; a long report goes in parts. Check the bytes and first and last lines the answer returns against what you sent.\n- A review's transcript is acquired by ensure_review_transcript, for a review made anywhere. It needs no decision and no pasted text, takes the video's own captions, or transcribes its audio on the Miadi host when the video has none, never overwrites and calls no model service. review_lookup and review_versions carry the transcript's state (unknown, absent, acquiring, stored, held or failed). review_transcript_status follows a job, and every answer carries plain links that work when no card is shown.\n- A registered screenwalk is read with get_screenwalk, by its registry id, miadi-screenwalk:<id> or its page URL, and the registrations are listed with list_screenwalks. What it returns is the Screenwalk Registry's own record, read as the signed-in person: the canonical video, the names and where they stand, and the inventory already prepared (question sets, segments, purpose lists, relations). That inventory is not a review and not a transcript, and nothing copies it into a review. request_screenwalk_review is the one step from a registration to its review: it relates the registration to the review that already exists for its video, or prepares one create request that a person approves. Never ask the person to copy a YouTube URL that a registration already holds.\n- An unknown id is answered as not found, never invented. A missing backing service is answered as unavailable.\n- Use the miadi-review:<uuid>, miadi-chronicle://<n>, miadi-screenwalk:<id>, owner/repo#n and session:<uuid> reference forms.";
package/dist/server.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from "node:crypto";
1
2
  import express from "express";
2
3
  import { rateLimit } from "express-rate-limit";
3
4
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
@@ -10,6 +11,7 @@ import { logDecision, reconcileInterrupted, registerApprovalRoutes, registerCons
10
11
  import { DecisionTokens } from "./decisions.js";
11
12
  import { JsonFile, Ledger, ensureStateDir, statePaths } from "./store.js";
12
13
  import { registerTools } from "./tools.js";
14
+ import { ClientLists, clientKeyOf, emptyClientTools, needsSession } from "./client-tools.js";
13
15
  import { MiadiClient } from "./miadi.js";
14
16
  import { ReviewClient } from "./reviews.js";
15
17
  import { readFactoryConfig, runSteering } from "./steering-adapters.js";
@@ -22,6 +24,8 @@ export function createConnectorApp(config, deps) {
22
24
  const paths = statePaths(config.stateDir);
23
25
  const oauthState = new JsonFile(paths.oauth, emptyOAuthState);
24
26
  const ledger = new Ledger(paths.ledger);
27
+ // The tool list each client last fetched, so get_capabilities can say when it is older than this version (jgwill/Miadi#1180).
28
+ const clientLists = new ClientLists(new JsonFile(paths.clientTools, emptyClientTools));
25
29
  // The issuer string exactly as the metadata states it (URL.href, so with its trailing slash).
26
30
  const issuer = new URL(config.publicUrl).href;
27
31
  const provider = new MiadiOAuthProvider(oauthState, deps.identify, issuer);
@@ -133,6 +137,18 @@ export function createConnectorApp(config, deps) {
133
137
  logDecision(approvalDeps, { phase: "card_template_read", uri: String(rpc.params?.uri ?? "").slice(0, 120) });
134
138
  if (rpc.method === "tools/call" && rpc.params?.name === "show_decisions")
135
139
  logDecision(approvalDeps, { phase: "show_decisions" });
140
+ // Whose tool list this request concerns: its OAuth client, else the session id given at initialize. A client
141
+ // with no client id (a person token used directly) is given one there and sends it back on what follows; the
142
+ // endpoint keeps no session for it.
143
+ const methods = (Array.isArray(req.body) ? req.body : [req.body]).map((m) => String(m?.method ?? ""));
144
+ const clientId = req.auth?.clientId;
145
+ const sent = req.headers["mcp-session-id"];
146
+ let sessionId = typeof sent === "string" ? sent : undefined;
147
+ if (needsSession(clientId) && methods.includes("initialize")) {
148
+ sessionId = randomUUID();
149
+ res.setHeader("Mcp-Session-Id", sessionId);
150
+ }
151
+ const listKey = clientKeyOf(clientId, sessionId);
136
152
  const ctx = {
137
153
  config,
138
154
  miadi,
@@ -152,9 +168,14 @@ export function createConnectorApp(config, deps) {
152
168
  ...(deps.steeringRuntime ? { steeringRuntime: deps.steeringRuntime } : {}),
153
169
  ...(deps.wakeRunner ? { wakeRunner: deps.wakeRunner } : {}),
154
170
  ...(deps.clones ? { clones: deps.clones } : {}),
171
+ clientTools: { lists: clientLists, key: listKey },
155
172
  };
156
173
  const server = new McpServer({ name: "miadi", version: VERSION }, { instructions: INSTRUCTIONS });
157
- registerTools(server, ctx);
174
+ const { tools: offered } = registerTools(server, ctx);
175
+ if (methods.includes("tools/list"))
176
+ clientLists.listed(listKey, VERSION, offered);
177
+ else if (methods.includes("tools/call"))
178
+ clientLists.called(listKey, VERSION);
158
179
  const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
159
180
  res.on("close", () => {
160
181
  transport.close().catch(() => { });
@@ -182,9 +203,9 @@ export function createConnectorApp(config, deps) {
182
203
  }
183
204
  export const INSTRUCTIONS = `Miadi is a relational software factory: agent sessions, Miadi reviews of screenwalks, Chronicle episodes, talking circles and the five accountable circles (Story, Stewardship, Engineering, Evaluation, Continuity) across three domains (Creative, Ceremonial, Engineering).
184
205
 
185
- Start with get_capabilities: it says who you are signed in as, which tools are live, and which return not_implemented.
206
+ Start with get_capabilities: it says who you are signed in as, which tools are live, and which return not_implemented. When its answer carries client_tools, the tool list your client holds is older than this server or not recorded: a tool named there is offered by the server and cannot be called from your client until a person makes it fetch the list again. Tell the person the sentence it gives, and use what until_refresh names meanwhile.
186
207
 
187
- Every tool is offered on every connection. A client that loads tools on demand shows only those its last tool search matched: a tool you do not see is not missing. Search for it by its exact name, get_capabilities first, before telling the person a tool is absent. The main reads are get_capabilities, get_context, search, fetch, list_records, list_sessions, search_sessions, get_session, review_lookup, read_episode_file and show_decisions.
208
+ Every tool is offered on every connection. A client that loads tools on demand shows only those its last tool search matched: a tool you do not see is not missing. Search for it by its exact name, get_capabilities first, before telling the person a tool is absent. The main reads are get_capabilities, get_context, search, fetch, list_records, list_sessions, search_sessions, get_session, review_lookup, get_screenwalk, list_screenwalks, read_episode_file and show_decisions.
188
209
 
189
210
  Rules every tool keeps:
190
211
  - Every record names the person who made it, with a claim category: observed, hypothesis, desired_future, fiction or verified_implementation. Keep fiction and desired futures apart from what was observed.
@@ -193,5 +214,6 @@ Rules every tool keeps:
193
214
  - A mission is revised, never re-requested: to change a run or work proposal that still awaits a decision, call revise_pending_request with its id and the version you read (expected_version). It keeps one id, one approval page and one card; get_request_history shows every version. A new request_authorized_run or propose_work is for a new mission only. Requests made earlier as separate versions are joined with supersede_pending_requests, naming their exact ids, only when the person names or confirms them.
194
215
  - A research report (a Deep Research report) is delivered with save_research exactly as written, never summarised or shortened, with its sources; a long report goes in parts. Check the bytes and first and last lines the answer returns against what you sent.
195
216
  - A review's transcript is acquired by ensure_review_transcript, for a review made anywhere. It needs no decision and no pasted text, takes the video's own captions, or transcribes its audio on the Miadi host when the video has none, never overwrites and calls no model service. review_lookup and review_versions carry the transcript's state (unknown, absent, acquiring, stored, held or failed). review_transcript_status follows a job, and every answer carries plain links that work when no card is shown.
217
+ - A registered screenwalk is read with get_screenwalk, by its registry id, miadi-screenwalk:<id> or its page URL, and the registrations are listed with list_screenwalks. What it returns is the Screenwalk Registry's own record, read as the signed-in person: the canonical video, the names and where they stand, and the inventory already prepared (question sets, segments, purpose lists, relations). That inventory is not a review and not a transcript, and nothing copies it into a review. request_screenwalk_review is the one step from a registration to its review: it relates the registration to the review that already exists for its video, or prepares one create request that a person approves. Never ask the person to copy a YouTube URL that a registration already holds.
196
218
  - An unknown id is answered as not found, never invented. A missing backing service is answered as unavailable.
197
- - Use the miadi-review:<uuid>, miadi-chronicle://<n>, owner/repo#n and session:<uuid> reference forms.`;
219
+ - Use the miadi-review:<uuid>, miadi-chronicle://<n>, miadi-screenwalk:<id>, owner/repo#n and session:<uuid> reference forms.`;
package/dist/store.d.ts CHANGED
@@ -24,4 +24,5 @@ export declare class Ledger<R extends {
24
24
  export declare function statePaths(dir: string): {
25
25
  oauth: string;
26
26
  ledger: string;
27
+ clientTools: string;
27
28
  };
package/dist/store.js CHANGED
@@ -9,6 +9,9 @@
9
9
  * - ledger.jsonl the records people contribute through the connector
10
10
  * (observations, handoffs, proposals). Append-only: a record
11
11
  * is never edited, a later record supersedes it.
12
+ * - client-tools.json the tool list each client last fetched: its version and
13
+ * tool names, by OAuth client id or by session id. No token and
14
+ * no person (client-tools.ts).
12
15
  */
13
16
  import { appendFileSync, chmodSync, closeSync, existsSync, fsyncSync, mkdirSync, openSync, readFileSync, statSync, writeSync } from "node:fs";
14
17
  import { createHash, randomBytes } from "node:crypto";
@@ -108,5 +111,6 @@ export function statePaths(dir) {
108
111
  return {
109
112
  oauth: join(dir, "oauth.json"),
110
113
  ledger: join(dir, "ledger.jsonl"),
114
+ clientTools: join(dir, "client-tools.json"),
111
115
  };
112
116
  }
package/dist/tools.d.ts CHANGED
@@ -14,6 +14,7 @@ import { type RuntimeDeps } from "./runtime-steer.js";
14
14
  import { type AdapterProbe } from "./steering-adapters.js";
15
15
  import { type TmuxLike } from "./steer.js";
16
16
  import { type GithubGet } from "./mission-result.js";
17
+ import { type ClientKey, type ClientLists } from "./client-tools.js";
17
18
  export interface ToolContext {
18
19
  config: ConnectorConfig;
19
20
  miadi: MiadiClient;
@@ -46,6 +47,11 @@ export interface ToolContext {
46
47
  steerSettleMs?: number;
47
48
  /** Where a repository's clone lives on this host, for reading the commits of a completion (jgwill/Miadi#993). Default: MIADI_CONNECTOR_CLONES, then the service's own checkout for jgwill/Miadi. */
48
49
  clones?: (repository: string) => string | undefined;
50
+ /** The tool list this request's client last fetched, and under which key it is kept (jgwill/Miadi#1180, client-tools.ts). Absent, get_capabilities says nothing of it. */
51
+ clientTools?: {
52
+ lists: ClientLists;
53
+ key: ClientKey | null;
54
+ };
49
55
  }
50
56
  /**
51
57
  * Why GitHub did not answer a reference (jgwill/Miadi#913 B). A 404 without a
@@ -72,6 +78,9 @@ export declare function steeringTransport(tmux: TmuxLike | undefined): {
72
78
  transport: "operational" | "unavailable";
73
79
  reason?: string;
74
80
  };
75
- export declare function registerTools(server: McpServer, ctx: ToolContext): void;
81
+ /** Registers every tool, and returns the names it registered: what a tools/list of this server answers. */
82
+ export declare function registerTools(server: McpServer, ctx: ToolContext): {
83
+ tools: string[];
84
+ };
76
85
  /** What get_capabilities reports for each tool. */
77
86
  export declare const TOOL_STATUS: Record<string, string>;