@miadi/connector 0.1.32 → 0.1.35

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,507 @@
1
+ /**
2
+ * Ensuring a review holds its video's transcript (jgwill/Miadi#995).
3
+ *
4
+ * Processing a review needs the words of the video it reviews. Before this, only an approved `create`
5
+ * stored captions, so a review made anywhere else (the review service's own page, a manual edit,
6
+ * another client) never got a transcript and nothing said so. One job per review now does it:
7
+ *
8
+ * 1. reuse: the review service already holds one, which stays (it is read back and its digest kept);
9
+ * 2. source: a source registered as withheld is neither read nor stored, until it is released;
10
+ * 3. acquire: the video's spoken-language captions, then a local transcription where the host enables it
11
+ * and the source is released. No model service is called and nothing here costs money;
12
+ * 4. store: one POST that never overwrites;
13
+ * 5. readback: the stored text is read from the service and its digest compared with what was sent.
14
+ *
15
+ * The job is a ledger record with a receipt that each stage extends before the next call, so a
16
+ * restart resumes from what was written. A caption track YouTube has not made yet is tried again every
17
+ * 15 minutes for three days. A job states what failed, who can remedy it, and when it tries again.
18
+ * It runs under the authority that already covers processing a review: a person who may contribute and
19
+ * either holds the write tier or registered the source. No separate transcript decision exists.
20
+ */
21
+ import { createHash } from "node:crypto";
22
+ import { TRANSCRIPT_RETRY_MS, TRANSCRIPT_WINDOW_MS, coverage, sourceOf } from "./captions.js";
23
+ import { current, newRecordId } from "./records.js";
24
+ /** The review service's own transcript door, as the connector's token reaches it. */
25
+ export function reviewTranscriptService(config, fetchImpl = fetch) {
26
+ const call = async (method, path, body) => {
27
+ if (!config.reviewToken)
28
+ return { status: 0, error: "The connector host has no review service token." };
29
+ try {
30
+ const res = await fetchImpl(`${config.reviewUrl}${path}`, {
31
+ method,
32
+ redirect: "error",
33
+ headers: { accept: "application/json", authorization: `Bearer ${config.reviewToken}`, ...(body !== undefined ? { "content-type": "application/json" } : {}) },
34
+ ...(body !== undefined ? { body: JSON.stringify(body) } : {}),
35
+ signal: AbortSignal.timeout(60_000),
36
+ });
37
+ let json = null;
38
+ try {
39
+ json = await res.json();
40
+ }
41
+ catch {
42
+ /* an answer without a body */
43
+ }
44
+ return { status: res.status, json };
45
+ }
46
+ catch (error) {
47
+ return { status: 0, error: `The review service could not be reached: ${error instanceof Error ? error.message : String(error)}` };
48
+ }
49
+ };
50
+ return {
51
+ async state(id) {
52
+ const r = await call("GET", `/api/reviews/${id}`);
53
+ if (r.status !== 200)
54
+ return { status: r.status, ...("error" in r ? { error: r.error } : {}) };
55
+ return { status: 200, has_transcript: r.json?.has_transcript === true, source: r.json?.transcript_source ?? null, updated_at: r.json?.transcript_updated_at ?? null };
56
+ },
57
+ async read(id) {
58
+ const r = await call("GET", `/api/reviews/${id}/transcript`);
59
+ if (r.status !== 200)
60
+ return { status: r.status, ...("error" in r ? { error: r.error } : {}) };
61
+ return { status: 200, transcript: String(r.json?.transcript ?? ""), source: r.json?.transcript_source ?? null, updated_at: r.json?.transcript_updated_at ?? null };
62
+ },
63
+ async store(id, transcript, provenance) {
64
+ // overwrite is explicit: an existing transcript is never replaced by a job.
65
+ const r = await call("POST", `/api/reviews/${id}/transcript`, { transcript, overwrite: false, ...(provenance ? { provenance } : {}) });
66
+ return { status: r.status, ok: r.status === 200 || r.status === 201, ...("error" in r ? { error: r.error } : {}) };
67
+ },
68
+ };
69
+ }
70
+ const sha = (text) => createHash("sha256").update(text).digest("hex");
71
+ const clock = (io) => (io.now ?? Date.now)();
72
+ const iso = (ms) => new Date(ms).toISOString();
73
+ /** A job that waits three days keeps the last stages only, so its receipt does not grow with every retry. */
74
+ const MAX_STAGES = 24;
75
+ /** How long an attempt this process does not run may go without writing a stage before it counts as abandoned. */
76
+ export const STALE_MS = 5 * 60_000;
77
+ export const jobKey = (reviewId) => `transcript:${reviewId}`;
78
+ const requested = (at, detail) => ({ stage: "requested", status: "completed", at, detail });
79
+ /** What the ledger says of a video's source: released by its owner, withheld, or never registered. */
80
+ export function sourceStatus(records, videoId) {
81
+ const intents = current(records).filter((r) => r.kind === "source_intent" && r.body.video_id === videoId);
82
+ if (intents.some((r) => r.body.readiness === "withheld"))
83
+ return "withheld";
84
+ return intents.some((r) => r.body.readiness === "released_for_review") ? "released" : "unregistered";
85
+ }
86
+ export function jobOf(records, reviewId) {
87
+ return current(records).find((r) => r.kind === "transcript_job" && r.idempotency_key === jobKey(reviewId));
88
+ }
89
+ export const receiptOf = (job) => job?.completion_receipt?.transcript;
90
+ const STATE_OF = { acquiring: "in_progress", stored: "completed", failed: "blocked", held: "blocked", absent: undefined, unknown: undefined };
91
+ /** Jobs running in this process, by review: a second trigger joins the first and spends nothing. */
92
+ const running = new WeakMap();
93
+ const runningOf = (io) => {
94
+ let m = running.get(io.ledger);
95
+ if (!m)
96
+ running.set(io.ledger, (m = new Map()));
97
+ return m;
98
+ };
99
+ function commit(io, job, receipt, note) {
100
+ const before = receiptOf(job)?.state;
101
+ const next = io.ledger.appendDurable({
102
+ id: newRecordId("transcript_job"),
103
+ kind: "transcript_job",
104
+ created_at: iso(clock(io)),
105
+ actor: { person_id: "system:miadi-connector", name: "Miadi connector", client_id: "transcript-job" },
106
+ refs: job.refs,
107
+ evidence_refs: [],
108
+ supersedes: job.id,
109
+ approval_state: "not_required",
110
+ ...(STATE_OF[receipt.state] ? { state: STATE_OF[receipt.state] } : {}),
111
+ ...(note ? { next_action: note } : {}),
112
+ completion_receipt: { transcript: receipt },
113
+ body: { decision: "transcript_job" },
114
+ });
115
+ io.log?.({ evt: "connector.transcript", job: job.id, review: receipt.review_id, state: receipt.state, phase: receipt.phase, attempts: receipt.attempts });
116
+ const folded = current([...io.ledger.all()]).find((r) => r.id === job.id) ?? next;
117
+ // An ending is announced once per arrival at it: stored, held or failed reached from another state.
118
+ if (io.outcome && before !== receipt.state && (receipt.state === "stored" || receipt.state === "held" || receipt.state === "failed")) {
119
+ Promise.resolve()
120
+ .then(() => io.outcome(folded, receipt))
121
+ .catch((error) => io.log?.({ evt: "connector.transcript", job: job.id, outcome_error: error instanceof Error ? error.message : String(error) }));
122
+ }
123
+ return folded;
124
+ }
125
+ const failures = {
126
+ blocked_permission: (status) => ({
127
+ code: "blocked_permission",
128
+ message: `The review service refused the connector's credential (${status}).`,
129
+ remedy: "Replace MIADI_REVIEW_TOKEN on the connector host (the one literal key in ~/.env), restart miadi-connector, then run ensure_review_transcript again. Nothing was stored.",
130
+ owner: "operator",
131
+ retry: "none until the credential is replaced",
132
+ }),
133
+ review_not_found: () => ({
134
+ code: "review_not_found",
135
+ message: "The review service has no review with this id.",
136
+ remedy: "Check the review id against review_lookup. A review that was deleted cannot hold a transcript.",
137
+ owner: "operator",
138
+ retry: "none",
139
+ }),
140
+ no_captions: (message, local) => ({
141
+ code: "no_captions",
142
+ message: `No transcript after three days of trying, and no model was called. Last answer: ${message}`,
143
+ remedy: local
144
+ ? "The video has no usable captions and local transcription did not produce words. The source owner can supply the exact transcript through request_review_operation store_transcript."
145
+ : "The video has no usable captions. An operator can enable local transcription on the host (MIADI_TRANSCRIPT_LOCAL=faster-whisper) and run ensure_review_transcript again, or the source owner can supply the exact transcript through request_review_operation store_transcript.",
146
+ owner: "operator",
147
+ retry: "none scheduled; ensure_review_transcript starts a new three-day window",
148
+ }),
149
+ no_provider: () => ({
150
+ code: "provider_unavailable",
151
+ message: "This connector host has no way to read captions.",
152
+ remedy: "Start the connector with the captions reader its service wires (bin.ts), then run ensure_review_transcript again.",
153
+ owner: "operator",
154
+ retry: "none until the host is configured",
155
+ }),
156
+ readback_mismatch: (sent, held) => ({
157
+ code: "readback_mismatch",
158
+ message: `The review service's transcript differs from what was sent (sent ${sent.slice(0, 12)}, held ${held.slice(0, 12)}).`,
159
+ remedy: "Nothing was overwritten. Inspect the transcript at the review's transcript link. Replacing it needs overwrite authority on the review service, which is the v0 owner's.",
160
+ owner: "operator",
161
+ retry: "none",
162
+ }),
163
+ store_refused: (status) => ({
164
+ code: "store_refused",
165
+ message: `The review service refused the transcript (${status}).`,
166
+ remedy: "Read the review service's answer in the connector journal (connector.transcript lines), correct the cause, and run ensure_review_transcript again.",
167
+ owner: "operator",
168
+ retry: "none",
169
+ }),
170
+ };
171
+ /** One attempt. Each stage is written before the next call, so a restart reads where it was. */
172
+ async function attempt(io, startJob) {
173
+ let job = startJob;
174
+ const at = () => iso(clock(io));
175
+ let r = { ...receiptOf(job), stages: [...receiptOf(job).stages] };
176
+ const mark = (stage, status, detail) => {
177
+ r.stages = [...r.stages, { stage, status, at: at(), ...(detail ? { detail } : {}), attempt: r.attempts }].slice(-MAX_STAGES);
178
+ };
179
+ const save = (note) => (job = commit(io, job, r, note));
180
+ const fail = (failure, stage, note) => {
181
+ mark(stage, "failed", failure.message);
182
+ r = { ...r, state: "failed", phase: failure.code, failure };
183
+ delete r.next_attempt_at;
184
+ return save(note);
185
+ };
186
+ const wait = (code, message, stage, usedLocal = false) => {
187
+ const expired = clock(io) - Date.parse(r.since) >= TRANSCRIPT_WINDOW_MS;
188
+ if (expired)
189
+ return fail(failures.no_captions(message, usedLocal), stage, "Three days passed without a transcript.");
190
+ mark(stage, "waiting", message);
191
+ const next = clock(io) + TRANSCRIPT_RETRY_MS;
192
+ r = {
193
+ ...r,
194
+ state: "acquiring",
195
+ phase: code,
196
+ next_attempt_at: iso(next),
197
+ give_up_at: iso(Date.parse(r.since) + TRANSCRIPT_WINDOW_MS),
198
+ failure: { code, message, remedy: "None needed: the connector tries again by itself.", owner: "none", retry: `every 15 minutes until ${iso(Date.parse(r.since) + TRANSCRIPT_WINDOW_MS)}` },
199
+ };
200
+ return save(`Tries again at ${r.next_attempt_at}.`);
201
+ };
202
+ // A new attempt starts from a clean slate of the last answer, keeping the history of stages.
203
+ r = { ...r, state: "acquiring", phase: "acquiring", attempts: r.attempts + 1, last_attempt_at: at() };
204
+ delete r.next_attempt_at;
205
+ delete r.failure;
206
+ mark("reuse_check", "started");
207
+ save();
208
+ // 1. Reuse: what the review service holds stays.
209
+ const held = await io.service.state(r.review_id);
210
+ if (held.status === 401 || held.status === 403)
211
+ return fail(failures.blocked_permission(held.status), "reuse_check", "The review service credential must be replaced.");
212
+ if (held.status === 404)
213
+ return fail(failures.review_not_found(), "reuse_check", "The review is unknown to the review service.");
214
+ if (held.status !== 200)
215
+ return wait("review_service_unreachable", held.error ?? `The review service answered ${held.status}.`, "reuse_check");
216
+ if (held.has_transcript) {
217
+ mark("reuse_check", "completed", "The review already holds a transcript, which stays.");
218
+ const verified = await readback(io, r, undefined);
219
+ if (!verified.ok && verified.failure)
220
+ return fail(verified.failure, "readback", "Readback of the held transcript failed.");
221
+ r = { ...r, state: "stored", phase: "already_present", method: "existing", source: held.source ?? "held by the review service", readback: verified.readback, sha256: verified.readback?.sha256, chars: verified.readback?.chars, stored_at: held.updated_at ?? undefined };
222
+ delete r.failure;
223
+ mark("readback", "completed", `Read back ${verified.readback?.chars} characters, sha256 ${verified.readback?.sha256.slice(0, 12)}.`);
224
+ return save("The review already held a transcript; it was read back and kept.");
225
+ }
226
+ mark("reuse_check", "completed", "The review service holds no transcript.");
227
+ // 2. Source: a withheld source is neither read nor stored.
228
+ const source = sourceStatus(io.ledger.all(), r.video_id);
229
+ if (source === "withheld") {
230
+ mark("source_check", "blocked", "The source is registered as withheld.");
231
+ r = {
232
+ ...r,
233
+ state: "held",
234
+ phase: "held_source_withheld",
235
+ failure: {
236
+ code: "held_source_withheld",
237
+ message: "The source is registered as withheld, so its words are not read or stored.",
238
+ remedy: "The source's owner releases it (register_source_intent with readiness released_for_review), or a person in the video decides on its consent link. The job resumes by itself once the source is released.",
239
+ owner: "source_owner",
240
+ retry: "on the next pass after the source is released",
241
+ },
242
+ };
243
+ return save("Waiting for the source to be released.");
244
+ }
245
+ mark("source_check", "completed", source === "released" ? "The source is released for review." : "No source is registered for this video, and none is withheld.");
246
+ // 3. Acquire: captions first, then a local transcription where the host enables it and the source is released.
247
+ if (!io.captions && !io.local)
248
+ return fail(failures.no_provider(), "acquire", "The host has no captions reader.");
249
+ mark("acquire", "started", "YouTube captions in the spoken language");
250
+ save();
251
+ let answer = io.captions ? await io.captions(r.video_id) : undefined;
252
+ let usedLocal = false;
253
+ // The audio is downloaded and transcribed only when the video has no usable caption track. A reader that failed or a
254
+ // track not made yet waits and retries: a transient failure must not start sixteen minutes of work on this host.
255
+ const captionsAbsent = !io.captions || (answer?.state === "none_yet" && answer.absent === true);
256
+ if ((!answer || answer.state !== "found") && io.local && source === "released" && captionsAbsent) {
257
+ mark("acquire", "waiting", `Captions: ${answer?.state === "none_yet" ? answer.message ?? "none yet" : "no reader"}. Trying local transcription.`);
258
+ save();
259
+ usedLocal = true;
260
+ answer = await io.local(r.video_id);
261
+ }
262
+ if (!answer || answer.state !== "found")
263
+ return wait("waiting_for_captions", answer?.message ?? "YouTube has no captions for this video yet.", "acquire", usedLocal);
264
+ const text = answer.text.trim();
265
+ if (!text)
266
+ return wait("waiting_for_captions", "The captions hold no words.", "acquire", usedLocal);
267
+ mark("acquire", "completed", `${answer.words} words from ${sourceOf(answer)}, ${coverage(answer)}.`);
268
+ r = { ...r, method: answer.method ?? "youtube_captions", source: sourceOf(answer), language: answer.language, track: answer.track, ...(answer.basis ? { basis: answer.basis } : {}), words: answer.words, covers: coverage(answer), chars: text.length, sha256: sha(text) };
269
+ save();
270
+ // 4. Store: one POST that never overwrites.
271
+ mark("store", "started");
272
+ save();
273
+ const stored = await io.service.store(r.review_id, text, {
274
+ method: r.method ?? "youtube_captions",
275
+ ...(r.language ? { language: r.language } : {}),
276
+ ...(r.track ? { track: r.track } : {}),
277
+ ...(r.covers ? { covers: r.covers } : {}),
278
+ ...(answer.fetched_at ? { fetched_at: answer.fetched_at } : {}),
279
+ by: "miadi-connector",
280
+ sha256: sha(text),
281
+ });
282
+ if (stored.status === 401 || stored.status === 403)
283
+ return fail(failures.blocked_permission(stored.status), "store", "The review service credential must be replaced.");
284
+ if (stored.status === 404)
285
+ return fail(failures.review_not_found(), "store", "The review is unknown to the review service.");
286
+ if (stored.status === 0 || stored.status >= 500)
287
+ return wait("review_service_unreachable", stored.error ?? `The review service answered ${stored.status}.`, "store");
288
+ if (stored.status === 409) {
289
+ // A second writer stored one between the check and this call: that one stays, and it is read back, not replaced.
290
+ mark("store", "completed", "The review service already held a transcript (another writer), which stays.");
291
+ r = { ...r, phase: "already_present", method: "existing" };
292
+ }
293
+ else if (!stored.ok)
294
+ return fail(failures.store_refused(stored.status), "store", `The review service refused the transcript (${stored.status}).`);
295
+ else {
296
+ mark("store", "completed", `The review service answered ${stored.status}.`);
297
+ r = { ...r, stored_at: at() };
298
+ }
299
+ save();
300
+ // 5. Readback: the stored text, read from the service, must hash to what was sent.
301
+ const back = await readback(io, r, stored.status === 409 ? undefined : r.sha256);
302
+ if (back.failure) {
303
+ if (back.readback)
304
+ r = { ...r, readback: back.readback };
305
+ return fail(back.failure, "readback", "The transcript could not be verified.");
306
+ }
307
+ r = { ...r, state: "stored", phase: r.phase === "already_present" ? "already_present" : "stored", readback: back.readback };
308
+ if (r.phase === "already_present") {
309
+ // Another writer's words stand, so nothing this attempt read describes them.
310
+ r = { ...r, source: back.readback?.source ?? "held by the review service", sha256: back.readback?.sha256, chars: back.readback?.chars };
311
+ for (const k of ["words", "covers", "language", "track", "basis"])
312
+ delete r[k];
313
+ }
314
+ delete r.failure;
315
+ delete r.next_attempt_at;
316
+ mark("readback", "completed", `Read back ${back.readback?.chars} characters, sha256 ${back.readback?.sha256.slice(0, 12)}, matching what was sent.`);
317
+ return save(r.phase === "already_present" ? "Another writer's transcript stays; it was read back." : "The transcript is stored and verified by readback.");
318
+ }
319
+ /** Reads the transcript from the service. With an expected digest, a different one is a failure. */
320
+ async function readback(io, r, expected) {
321
+ const got = await io.service.read(r.review_id);
322
+ if (got.status === 401 || got.status === 403)
323
+ return { ok: false, failure: failures.blocked_permission(got.status) };
324
+ if (got.status !== 200 || got.transcript === undefined) {
325
+ return { ok: false, failure: { code: "readback_unavailable", message: got.error ?? `The review service answered ${got.status} when the transcript was read back.`, remedy: "Run ensure_review_transcript again; the stored transcript is read back without being stored a second time.", owner: "operator", retry: "on the next ensure_review_transcript" } };
326
+ }
327
+ const digest = sha(got.transcript);
328
+ const readbackReceipt = { ok: expected === undefined || digest === expected, sha256: digest, chars: got.transcript.length, source: got.source ?? null, updated_at: got.updated_at ?? null, checked_at: iso(clock(io)) };
329
+ if (!readbackReceipt.ok)
330
+ return { ok: false, readback: readbackReceipt, failure: failures.readback_mismatch(expected, digest) };
331
+ return { ok: true, readback: readbackReceipt };
332
+ }
333
+ /**
334
+ * Whether an approved mission entitles a worker to acquire this review's transcript: the person with the
335
+ * write tier approved a run or a work proposal that names the review. The worker has no Miadi API tier of
336
+ * its own, so the mission is its authority, and the job records it.
337
+ */
338
+ export function missionAuthority(records, missionId, reviewId) {
339
+ const m = current(records).find((r) => r.id === missionId);
340
+ if (!m || (m.kind !== "run_request" && m.kind !== "work_proposal"))
341
+ return { ok: false, reason: `${missionId} is not a run or work proposal in this ledger.` };
342
+ if (m.approval_state !== "approved")
343
+ return { ok: false, reason: `${missionId} is ${m.approval_state ?? "not approved"}; a person approves it before anything runs under it.` };
344
+ if (!m.refs.includes(`miadi-review:${reviewId}`))
345
+ return { ok: false, reason: `${missionId} does not name miadi-review:${reviewId}, so it does not cover this review.` };
346
+ const receipt = (m.completion_receipt ?? {});
347
+ return { ok: true, authority: { basis: "approved_mission", mission: m.id, version: m.version ?? 1, approved_by: receipt.decided_by?.name ?? null, approved_at: receipt.decided_at ?? null } };
348
+ }
349
+ /**
350
+ * The explicit, idempotent operation: one job per review, one attempt at a time. A second trigger
351
+ * while an attempt runs joins it. A stored job is only confirmed against the service. A failed or
352
+ * held job starts a new window, because a person asking again has usually repaired the cause.
353
+ */
354
+ export function ensureTranscript(io, input) {
355
+ const jobs = runningOf(io);
356
+ const existing = jobOf(io.ledger.all(), input.review_id);
357
+ const inFlight = jobs.get(input.review_id);
358
+ if (inFlight && existing)
359
+ return { job: existing, joined: true, done: inFlight };
360
+ const now = clock(io);
361
+ let job = existing;
362
+ let prior;
363
+ if (!job) {
364
+ const receipt = { state: "acquiring", phase: "requested", review_id: input.review_id, video_id: input.video_id, trigger: input.trigger, since: iso(now), attempts: 0, stages: [requested(iso(now), input.trigger)] };
365
+ job = io.ledger.appendDurable({
366
+ id: newRecordId("transcript_job"),
367
+ kind: "transcript_job",
368
+ created_at: iso(now),
369
+ actor: input.actor,
370
+ refs: [...(input.refs ?? []), `miadi-review:${input.review_id}`, `https://youtu.be/${input.video_id}`],
371
+ evidence_refs: [],
372
+ idempotency_key: jobKey(input.review_id),
373
+ approval_state: "not_required",
374
+ state: "in_progress",
375
+ body: { review_id: input.review_id, video_id: input.video_id, trigger: input.trigger, ...(input.authority ? { authority: input.authority } : {}) },
376
+ completion_receipt: { transcript: receipt },
377
+ });
378
+ }
379
+ else {
380
+ prior = receiptOf(job);
381
+ // A person asking again starts a new window when the job failed or was held, because the cause is usually repaired.
382
+ if (prior.state === "failed" || prior.state === "held") {
383
+ const next = { ...prior, state: "acquiring", phase: "requested", trigger: input.trigger, since: iso(now), stages: [...prior.stages, requested(iso(now), input.trigger)].slice(-MAX_STAGES) };
384
+ delete next.failure;
385
+ delete next.next_attempt_at;
386
+ job = commit(io, job, next);
387
+ }
388
+ }
389
+ const start = job;
390
+ const run = (async () => {
391
+ // A stored job is confirmed against the service and written again only if the service no longer holds the words.
392
+ if (prior?.state === "stored") {
393
+ const held = await io.service.state(input.review_id);
394
+ if (held.status !== 200 || held.has_transcript)
395
+ return start;
396
+ const next = { ...prior, state: "acquiring", phase: "requested", trigger: input.trigger, since: iso(clock(io)), stages: [...prior.stages, requested(iso(clock(io)), `${input.trigger} (the review service no longer holds the transcript this job stored)`)].slice(-MAX_STAGES) };
397
+ delete next.readback;
398
+ return attempt(io, commit(io, start, next));
399
+ }
400
+ return attempt(io, start);
401
+ })().catch((error) => {
402
+ io.log?.({ evt: "connector.transcript", job: start.id, error: error instanceof Error ? error.message : String(error) });
403
+ return current(io.ledger.all()).find((r) => r.id === start.id) ?? start;
404
+ });
405
+ const tracked = run.finally(() => {
406
+ if (jobs.get(input.review_id) === tracked)
407
+ jobs.delete(input.review_id);
408
+ });
409
+ jobs.set(input.review_id, tracked);
410
+ return { job: start, joined: false, done: tracked };
411
+ }
412
+ /**
413
+ * Jobs that need a pass: one a restart interrupted (acquiring, with no attempt running here), one whose retry time has
414
+ * come, and one held for a withheld source that has been released since. Called when the connector starts and every 15 minutes.
415
+ */
416
+ export async function settleTranscriptJobs(io, o = {}) {
417
+ const out = [];
418
+ const jobs = runningOf(io);
419
+ for (const job of current(io.ledger.all())) {
420
+ if (job.kind !== "transcript_job")
421
+ continue;
422
+ const r = receiptOf(job);
423
+ if (!r || jobs.has(r.review_id))
424
+ continue;
425
+ // An attempt that is not waiting for a retry and that this process does not run is one a restart interrupted, or one
426
+ // a worker's own process runs. At start (resumeAll) the first is certain. Later, it is resumed only once its last
427
+ // stage is older than STALE_MS, so a worker's attempt in its own process is left alone.
428
+ const heartbeat = Date.parse(r.stages.at(-1)?.at ?? r.last_attempt_at ?? r.since);
429
+ const interrupted = !r.next_attempt_at && (o.resumeAll === true || clock(io) - heartbeat >= STALE_MS);
430
+ const due = (r.state === "acquiring" && (r.next_attempt_at ? Date.parse(r.next_attempt_at) <= clock(io) : interrupted)) ||
431
+ (r.state === "held" && sourceStatus(io.ledger.all(), r.video_id) !== "withheld");
432
+ if (!due)
433
+ continue;
434
+ const resumed = r.state === "held" ? { ...r, since: iso(clock(io)) } : r;
435
+ const base = resumed === r ? job : commit(io, job, resumed);
436
+ const run = attempt(io, base).catch(() => base);
437
+ const tracked = run.finally(() => {
438
+ if (jobs.get(r.review_id) === tracked)
439
+ jobs.delete(r.review_id);
440
+ });
441
+ jobs.set(r.review_id, tracked);
442
+ await tracked;
443
+ out.push(job.id);
444
+ }
445
+ return out;
446
+ }
447
+ export function summaryOf(s) {
448
+ const r = s.job?.receipt;
449
+ const digest = (r?.readback?.sha256 ?? r?.sha256)?.slice(0, 12);
450
+ switch (s.state) {
451
+ case "stored": {
452
+ const from = r?.method === "existing" ? `already held by the review service${r.source ? ` (${r.source})` : ""}` : `from ${r?.source ?? "the review service"}`;
453
+ const size = r?.words ? `${r.words} words` : r?.chars ? `${r.chars} characters` : "text";
454
+ const verified = r?.readback?.ok ? `read back from the review service and matching, sha256 ${digest}…` : s.verified_now?.ok ? `read back now, sha256 ${s.verified_now.sha256.slice(0, 12)}…` : "the connector has not read it back yet";
455
+ return `Transcript stored: ${size} ${from}${r?.covers ? `, covering ${r.covers}` : ""}${r?.language ? `, language ${r.language}` : ""}; ${verified}. No model was called.`;
456
+ }
457
+ case "acquiring":
458
+ return r?.next_attempt_at
459
+ ? `Transcript not stored yet: ${r.failure?.message ?? "waiting"}. Attempt ${r.attempts}, next at ${r.next_attempt_at}, giving up at ${r.give_up_at}. No model is called.`
460
+ : `Transcript acquisition is running (attempt ${r?.attempts ?? 1}, started ${r?.last_attempt_at ?? r?.since}). Ask again for its progress.`;
461
+ case "held":
462
+ return `Transcript held: ${r?.failure?.message ?? "the source is withheld"} ${r?.failure?.remedy ?? ""}`.trim();
463
+ case "failed":
464
+ return `Transcript not stored: ${r?.failure?.message ?? "the job failed"} Remedy (${r?.failure?.owner ?? "operator"}): ${r?.failure?.remedy ?? "see the job's stages"}`;
465
+ case "absent":
466
+ return "The review service holds no transcript for this review and no job is running. ensure_review_transcript acquires it.";
467
+ default:
468
+ return `The transcript's state is unknown: ${s.service.error ?? "the review service could not be asked"}.`;
469
+ }
470
+ }
471
+ /**
472
+ * Where a review's transcript stands, read from the review service and the ledger. It writes nothing:
473
+ * `verify` reads the transcript back from the service and hashes it, and still records nothing.
474
+ */
475
+ export async function transcriptStatus(io, input, links) {
476
+ const job = jobOf(io.ledger.all(), input.review_id);
477
+ const receipt = receiptOf(job);
478
+ const held = await io.service.state(input.review_id);
479
+ const reachable = held.status === 200;
480
+ const service = { reachable, ...(reachable ? { has_transcript: held.has_transcript, source: held.source ?? null, updated_at: held.updated_at ?? null } : { error: held.error ?? `The review service answered ${held.status}.` }) };
481
+ let state;
482
+ if (reachable && held.has_transcript)
483
+ state = "stored";
484
+ else if (receipt && receipt.state !== "stored")
485
+ state = receipt.state;
486
+ else if (receipt?.state === "stored" && reachable)
487
+ state = "absent"; // the job stored one that the service no longer holds
488
+ else
489
+ state = reachable ? "absent" : receipt ? receipt.state : "unknown";
490
+ let verified_now;
491
+ if (input.verify && reachable && held.has_transcript) {
492
+ const back = await readback(io, { review_id: input.review_id }, receipt?.state === "stored" ? receipt.sha256 : undefined);
493
+ verified_now = back.readback;
494
+ }
495
+ const status = {
496
+ state,
497
+ summary: "",
498
+ review_id: input.review_id,
499
+ video_id: input.video_id ?? receipt?.video_id ?? null,
500
+ ...(job && receipt ? { job: { id: job.id, receipt } } : {}),
501
+ service,
502
+ ...(verified_now ? { verified_now } : {}),
503
+ links: links(job?.id),
504
+ };
505
+ status.summary = summaryOf(status);
506
+ return status;
507
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The page and the JSON a review's transcript is followed on, without an embedded card (jgwill/Miadi#995).
3
+ *
4
+ * `GET /transcripts/<review id>` is a link that outlasts the conversation that made it. It reads like
5
+ * `/records/<id>`: a person signs in with their Miadi person token (a form on the page, or a Bearer header
6
+ * for a script) and needs Miadi's read tier. It shows what review_transcript_status shows: the state, the
7
+ * plain summary, the job's stages, the digest and readback, the failure with who can remedy it, and the
8
+ * retry schedule. It only reads. Acquiring a transcript is ensure_review_transcript.
9
+ */
10
+ import { type Express } from "express";
11
+ import { type ApprovalDeps } from "./approve.js";
12
+ import { type TranscriptStatus } from "./transcript-job.js";
13
+ export declare function statusHtml(s: TranscriptStatus): string;
14
+ export declare function registerTranscriptRoutes(app: Express, deps: ApprovalDeps, publicUrl: string): void;
@@ -0,0 +1,92 @@
1
+ /**
2
+ * The page and the JSON a review's transcript is followed on, without an embedded card (jgwill/Miadi#995).
3
+ *
4
+ * `GET /transcripts/<review id>` is a link that outlasts the conversation that made it. It reads like
5
+ * `/records/<id>`: a person signs in with their Miadi person token (a form on the page, or a Bearer header
6
+ * for a script) and needs Miadi's read tier. It shows what review_transcript_status shows: the state, the
7
+ * plain summary, the job's stages, the digest and readback, the failure with who can remedy it, and the
8
+ * retry schedule. It only reads. Acquiring a transcript is ensure_review_transcript.
9
+ */
10
+ import express from "express";
11
+ import { escapeHtml } from "@miadi/node-service-kit/format";
12
+ import { page, transcriptJobIo } from "./approve.js";
13
+ import { MiadiUnavailable } from "./people.js";
14
+ import { reviewIdOf } from "./reviews.js";
15
+ import { transcriptStatus } from "./transcript-job.js";
16
+ const row = (k, v) => (v === undefined || v === null || v === "" ? "" : `<dt>${escapeHtml(k)}</dt><dd>${escapeHtml(String(v))}</dd>`);
17
+ const link = (href, text) => (href ? `<a href="${escapeHtml(href)}">${escapeHtml(text)}</a>` : "");
18
+ export function statusHtml(s) {
19
+ const r = s.job?.receipt;
20
+ const stages = (r?.stages ?? [])
21
+ .map((x) => `<tr><td>${escapeHtml(x.at.slice(11, 19))}</td><td>${escapeHtml(x.stage)}</td><td>${escapeHtml(x.status)}</td><td>${escapeHtml(x.detail ?? "")}</td></tr>`)
22
+ .join("");
23
+ return page(`Transcript: ${s.state}`, `<h1>Transcript: ${escapeHtml(s.state)}</h1>
24
+ <p>${escapeHtml(s.summary)}</p>
25
+ <dl>
26
+ ${row("Review", s.review_id)}${row("Video", s.video_id)}
27
+ ${row("Method", r?.method)}${row("Source", r?.source)}${row("Language", r?.language)}${row("Why this track", r?.basis)}
28
+ ${row("Words", r?.words)}${row("Characters", r?.chars)}${row("Covers", r?.covers)}${row("sha256", r?.sha256)}
29
+ ${row("Readback", r?.readback ? `${r.readback.ok ? "matches" : "differs"}: ${r.readback.chars} characters, sha256 ${r.readback.sha256}, checked ${r.readback.checked_at}` : undefined)}
30
+ ${row("Read back now", s.verified_now ? `${s.verified_now.ok ? "matches" : "differs"}: sha256 ${s.verified_now.sha256}` : undefined)}
31
+ ${row("Attempts", r?.attempts)}${row("Last attempt", r?.last_attempt_at)}${row("Next attempt", r?.next_attempt_at)}${row("Gives up", r?.give_up_at)}
32
+ ${row("Review service", s.service.reachable ? (s.service.has_transcript ? "holds a transcript" : "holds no transcript") : s.service.error)}
33
+ ${r?.failure ? row("Failure", r.failure.message) + row("Remedy", `${r.failure.remedy} (${r.failure.owner})`) + row("Retry", r.failure.retry) : ""}
34
+ </dl>
35
+ ${stages ? `<h2>Stages</h2><table><thead><tr><th>At (UTC)</th><th>Stage</th><th>Status</th><th>Detail</th></tr></thead><tbody>${stages}</tbody></table>` : ""}
36
+ <p>${link(s.links.review, "The review")} · ${link(s.links.job, "The job record")} · <span class="muted">transcript API (token): ${escapeHtml(s.links.transcript_api)}</span></p>
37
+ <p class="muted">No decision is needed for this job. It runs under the authority that already covers processing a review.</p>`);
38
+ }
39
+ const signIn = (id, error) => page("Transcript status", `<h1>Transcript status</h1><p>${escapeHtml(id)}</p>
40
+ ${error ? `<p class="err" role="alert">${escapeHtml(error)}</p>` : ""}
41
+ <form method="post"><label for="t">Your Miadi person token</label><input id="t" name="person_token" type="password" autocomplete="off" required>
42
+ <div class="row"><button class="primary" type="submit">Read</button></div></form>`);
43
+ export function registerTranscriptRoutes(app, deps, publicUrl) {
44
+ const form = express.urlencoded({ extended: false, limit: "16kb" });
45
+ const links = (id) => (job) => ({
46
+ status: `${publicUrl}/transcripts/${id}`,
47
+ review: `${deps.config.reviewUrl}/review/${id}`,
48
+ transcript_api: `${deps.config.reviewUrl}/api/reviews/${id}/transcript`,
49
+ ...(job ? { job: `${publicUrl}/records/${encodeURIComponent(job)}` } : {}),
50
+ decision: null,
51
+ });
52
+ /** The status as this person may read it, or the page that says why not. */
53
+ async function read(req, res, token, wantsJson) {
54
+ const id = reviewIdOf(String(req.params.id));
55
+ if (!id)
56
+ return void res.status(404).type("html").send(page("Not found", "<h1>No review with that id</h1>"));
57
+ let person;
58
+ try {
59
+ person = await deps.identify(token);
60
+ }
61
+ catch (error) {
62
+ if (!(error instanceof MiadiUnavailable))
63
+ throw error;
64
+ return void (wantsJson ? res.status(503).json({ error: "unavailable", message: "Miadi could not be reached." }) : res.status(503).type("html").send(signIn(id, "Miadi could not be reached. Try again in a minute.")));
65
+ }
66
+ if (!person)
67
+ return void (wantsJson ? res.status(401).json({ error: "unauthenticated" }) : res.status(401).type("html").send(signIn(id, "Miadi did not recognise that person token.")));
68
+ if (person.api_tier !== "read" && person.api_tier !== "write") {
69
+ const message = `Reading a transcript's status needs Miadi's read tier; ${person.name} has ${person.api_tier ?? "no API tier"}.`;
70
+ return void (wantsJson ? res.status(403).json({ error: "forbidden", message }) : res.status(403).type("html").send(signIn(id, message)));
71
+ }
72
+ const verify = req.query.verify === "1" || req.query.verify === "true";
73
+ const status = await transcriptStatus(transcriptJobIo(deps), { review_id: id, ...(verify ? { verify } : {}) }, links(id));
74
+ if (wantsJson)
75
+ return void res.json(status);
76
+ res.type("html").send(statusHtml(status));
77
+ }
78
+ app.get("/transcripts/:id", async (req, res) => {
79
+ const bearer = /^Bearer\s+(.+)$/i.exec(String(req.headers.authorization ?? ""))?.[1]?.trim();
80
+ const wantsJson = req.query.format === "json" || String(req.headers.accept ?? "").includes("application/json");
81
+ if (!bearer) {
82
+ const id = reviewIdOf(String(req.params.id));
83
+ if (!id)
84
+ return void res.status(404).type("html").send(page("Not found", "<h1>No review with that id</h1>"));
85
+ return void (wantsJson ? res.status(401).json({ error: "unauthenticated", message: "Send the Miadi person token as a Bearer header, or open this link in a browser." }) : res.type("html").send(signIn(id)));
86
+ }
87
+ await read(req, res, bearer, wantsJson).catch((error) => res.status(500).type("html").send(page("Error", `<h1>The status could not be read</h1><p>${escapeHtml(error instanceof Error ? error.message : String(error))}</p>`)));
88
+ });
89
+ app.post("/transcripts/:id", form, async (req, res) => {
90
+ await read(req, res, String((req.body ?? {}).person_token ?? "").trim(), false).catch((error) => res.status(500).type("html").send(page("Error", `<h1>The status could not be read</h1><p>${escapeHtml(error instanceof Error ? error.message : String(error))}</p>`)));
91
+ });
92
+ }
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.1.32";
1
+ export declare const VERSION = "0.1.35";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = "0.1.32";
1
+ export const VERSION = "0.1.35";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miadi/connector",
3
- "version": "0.1.32",
3
+ "version": "0.1.35",
4
4
  "description": "The Miadi connector: one remote MCP service through which a person signed in with their Miadi person token, from ChatGPT or any MCP client, reads sessions, reviews, episodes and circles and records observations, inquiries, handoffs and proposals with their name on each record.",
5
5
  "license": "MIT",
6
6
  "author": "Miadi",
@@ -43,6 +43,8 @@
43
43
  "STEERING.md"
44
44
  ],
45
45
  "dependencies": {
46
+ "@miadi/hooks-core": "^0.6.0",
47
+ "@miadi/hooks-gateway": "^0.2.0",
46
48
  "@miadi/inquiry-weave": "0.18.13",
47
49
  "@miadi/node-service-kit": "0.1.2",
48
50
  "@modelcontextprotocol/sdk": "^1.30.0",