@miadi/connector 0.1.26 → 0.1.28

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/dist/approve.js CHANGED
@@ -22,12 +22,14 @@ import { current, newRecordId } from "./records.js";
22
22
  import { APPROVABLE, projectRequest } from "./request-state.js";
23
23
  import { factoryDir, runBriefFile, readQueueState } from "./queue-state.js";
24
24
  import { factoryLedgerPath, readFactoryReceipts, receiptsForRecord } from "./factory-receipt.js";
25
+ import { readSteerDelivery } from "./runtime-steer.js";
26
+ import { adapterOfRoute, readFactoryConfig } from "./steering-adapters.js";
25
27
  import { steerAttempts, steerSession, tmuxAdapter } from "./steer.js";
26
28
  import { contentHash, versionOf } from "./revisions.js";
27
29
  import { TRANSCRIPT_RETRY_MS, transcriptStep } from "./captions.js";
28
30
  import { ReviewClient } from "./reviews.js";
29
31
  import { canReadReading } from "./reading/privacy.js";
30
- import { authorizationReceipt, authorizeProvider, briefAttributes, CHOICE_TTL_MS, CODEX_POLICIES, isPersonId, needsPersonChoice, providerPolicyOf, } from "./provider-policy.js";
32
+ import { authorizationReceipt, authorizeProvider, briefAttributes, CHOICE_TTL_MS, CODEX_POLICIES, isPersonId, needsPersonChoice, HOST_ORDER, providerPolicyOf, } from "./provider-policy.js";
31
33
  export { factoryDir, runBriefFile, readQueueState } from "./queue-state.js";
32
34
  /**
33
35
  * One line per step of a decision, for the journal: the request, a correlation id,
@@ -277,6 +279,28 @@ export async function executeApproved(record, approver, deps, instructions) {
277
279
  logDecision(deps, { phase: "transcript", record: record.id, video: b.video_id, outcome: transcript.outcome });
278
280
  return { ...result, transcript };
279
281
  }
282
+ case "participant_consent_request": {
283
+ // The named person said yes: their source is released, and a transcript held for it lands now, as the words they read.
284
+ const source = current(deps.ledger.all()).find((x) => x.kind === "source_intent" && x.body.video_id === b.video_id);
285
+ if (!source)
286
+ return { outcome: "failed", message: "The source this consent names is gone." };
287
+ if (source.body.readiness !== "released_for_review") {
288
+ deps.ledger.append({
289
+ id: newRecordId("source_intent"),
290
+ kind: "source_intent",
291
+ created_at: new Date().toISOString(),
292
+ actor: { person_id: approver.id, name: approver.name, client_id: "consent-link" },
293
+ refs: source.refs,
294
+ evidence_refs: [record.id],
295
+ supersedes: source.id,
296
+ state: "ready",
297
+ body: { ...source.body, readiness: "released_for_review", source_readiness_transition: true },
298
+ });
299
+ }
300
+ await settleTranscripts(deps);
301
+ const created = current(deps.ledger.all()).find((x) => x.kind === "review_operation_request" && x.body.video_id === b.video_id && x.completion_receipt?.transcript);
302
+ return { outcome: "released", source_intent: source.id, ...(created ? { transcript: created.completion_receipt.transcript } : {}) };
303
+ }
280
304
  case "deep_diver_request": {
281
305
  const r = await reviewCall("PUT", `/api/reviews/${b.review_id}/diver`, { ready: true, version: b.version, by: plainName(approver.name) });
282
306
  return { outcome: r.ok ? "marked_ready" : "failed", status: r.status, response: r.response };
@@ -331,7 +355,7 @@ export async function executeApproved(record, approver, deps, instructions) {
331
355
  return { outcome: "failed", message: "The run whose grant this steer cites is gone." };
332
356
  // The pane the factory delivered the mission to, when it recorded one (jgwill/Miadi#909).
333
357
  const bound = receiptsForRecord(readFactoryReceipts(factoryLedgerPath(deps.factoryDir ?? factoryDir())), grantRecord.id)[0];
334
- const result = await steerSession({ tmux: deps.tmux ?? tmuxAdapter(), stateDir: deps.config.stateDir, ...(deps.steeringRuntime ? { runtime: deps.steeringRuntime } : {}), ...(deps.steerSettleMs !== undefined ? { settleMs: deps.steerSettleMs } : {}) }, {
358
+ const result = await steerSession({ tmux: deps.tmux ?? tmuxAdapter(), stateDir: deps.config.stateDir, ...(deps.steeringRuntime ? { runtime: deps.steeringRuntime } : {}), ...(deps.steerSettleMs !== undefined ? { settleMs: deps.steerSettleMs } : {}), ...(deps.wakeRunner ? { wakeRunner: deps.wakeRunner } : {}) }, {
335
359
  record,
336
360
  grantRecord,
337
361
  priorAttempts: steerAttempts(current(deps.ledger.all()), grantRecord.id),
@@ -345,6 +369,7 @@ export async function executeApproved(record, approver, deps, instructions) {
345
369
  typed: result.typed,
346
370
  ...(result.forwarded ? { forwarded: true } : {}),
347
371
  ...(result.route ? { route: result.route } : {}),
372
+ ...(result.runtime_session_id ? { runtime_session_id: result.runtime_session_id } : {}),
348
373
  ...(result.transcript_offset !== undefined ? { transcript_offset: result.transcript_offset } : {}),
349
374
  message: result.message,
350
375
  ...(result.target ? { target: result.target } : {}),
@@ -355,12 +380,12 @@ export async function executeApproved(record, approver, deps, instructions) {
355
380
  return { outcome: "nothing_to_run" };
356
381
  }
357
382
  }
358
- function page(title, body) {
383
+ export function page(title, body) {
359
384
  return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
360
385
  <title>${escapeHtml(title)}</title>
361
386
  <style>
362
387
  :root{color-scheme:light dark;--bg:#fbfaf7;--fg:#1d1b18;--muted:#5b5650;--line:#d9d4cc;--accent:#7a4a00;--code:#f1ede6}
363
- @media (prefers-color-scheme:dark){:root{--bg:#141311;--fg:#ece8e1;--muted:#b3ada4;--line:#3a3631;--accent:#ffd700;--code:#1f1d1a}}
388
+ @media (prefers-color-scheme:dark){:root{--bg:#141311;--fg:#ece8e1;--muted:#b3ada4;--line:#3a3631;--accent:#ffd700;--code:#1f1d1a;--err:#ff7b72}}
364
389
  body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.5 system-ui,sans-serif}
365
390
  main{max-width:44rem;margin:0 auto;padding:2rem 1rem}
366
391
  h1{font-size:1.35rem;margin:0 0 .5rem}
@@ -396,6 +421,36 @@ summary:focus-visible,.iconbtn:focus-visible{outline:2px solid var(--accent);out
396
421
  .who{display:flex;gap:.5rem;align-items:center}
397
422
  .iconbtn{width:34px;height:34px;flex:none;display:inline-grid;place-items:center;border:1px solid var(--line);border-radius:.4rem;color:var(--fg)}
398
423
  .state{display:grid;grid-template-columns:1rem 1fr;gap:.5rem;color:var(--muted);font-size:.9rem}
424
+ .steer-delivery .now{display:grid;grid-template-columns:1rem 1fr;gap:.5rem;align-items:start;margin:.4rem 0}
425
+ .steer-delivery .glyph{color:var(--muted);margin-top:.25rem}
426
+ .steer-delivery.stopped .now .glyph,.steer-delivery li.stopped .glyph{color:var(--err,#b00020)}
427
+ .steer-delivery ol,.steer-delivery .actions{list-style:none;margin:.8rem 0 0;padding:0;display:grid;gap:.5rem}
428
+ .steer-delivery ol>li{display:grid;grid-template-columns:1rem 1fr;gap:.5rem;overflow-wrap:anywhere}
429
+ .steer-delivery li.ahead{color:var(--muted)}
430
+ .steer-delivery .facts{display:block;color:var(--muted);font-size:.85rem;font-family:ui-monospace,monospace}
431
+ .steer-delivery .facts>*{white-space:nowrap}
432
+ .steer-delivery .facts>*+*::before{content:" · "}
433
+ .steer-delivery .said{display:block;margin:.2rem 0;color:var(--muted);font-size:.9rem;overflow-wrap:anywhere}
434
+ .steer-delivery .did{display:block;margin:.2rem 0;padding:.3rem .5rem;background:var(--code);border-radius:.3rem;font-size:.85rem;overflow-wrap:anywhere;font-family:ui-monospace,monospace}
435
+ .steer-delivery h3{font-size:.95rem;margin:1rem 0 0}
436
+ .steer-delivery .outbound{display:flex;align-items:center;gap:.6rem;width:100%;min-height:40px;margin-top:.8rem;padding:3px 10px;border:1px solid var(--line);border-radius:.4rem;background:transparent;color:var(--fg);font:inherit;text-decoration:none;box-sizing:border-box;cursor:pointer}
437
+ .steer-delivery .outbound svg{flex:0 0 auto}
438
+ .steer-delivery .outbound .kind{display:inline-flex;align-items:center;gap:.4rem;color:var(--muted)}
439
+ .steer-delivery .outbound .identity{flex:1;text-align:left;color:var(--accent);font-family:ui-monospace,monospace;overflow:hidden;text-overflow:ellipsis}
440
+ .steer-delivery .again{display:flex;align-items:center;justify-content:space-between;gap:.6rem;margin-top:.8rem}
441
+ .steer-delivery .asked{margin:.4rem 0 .8rem;padding:.4rem .7rem;border-left:2px solid var(--line);overflow-wrap:anywhere}
442
+ details>summary{min-height:34px;padding:.3rem 0;box-sizing:border-box;cursor:pointer}
443
+ .steer-delivery .again button.iconbtn{padding:0}
444
+ .steer-delivery .outbound:hover,.steer-delivery .iconbtn:hover{background:color-mix(in srgb,var(--accent) 12%,transparent)}
445
+ .steer-delivery .outbound:active,.steer-delivery .iconbtn:active{transform:scale(.94)}
446
+ .steer-delivery .outbound:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
447
+ @media (prefers-reduced-motion:reduce){.steer-delivery .outbound:active,.steer-delivery .iconbtn:active{transform:none}}
448
+ .state.stopped{color:var(--fg);font-size:1rem}
449
+ .state.stopped .glyph{color:var(--err,#b00020)}
450
+ fieldset{border:1px solid var(--line);border-radius:.4rem;margin:1rem 0;padding:.5rem .8rem;min-width:0}
451
+ fieldset legend{float:left;width:100%;padding:0;margin-bottom:.3rem;font-size:.95rem}
452
+ fieldset label{clear:both;display:flex;align-items:flex-start;gap:.5rem;min-height:34px;margin:.45rem 0;font-weight:400}
453
+ input[type=radio]{accent-color:var(--accent);flex:0 0 auto;margin:.3rem 0 0}
399
454
  .code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.9em}
400
455
  .glyph{margin-top:.25rem;color:var(--muted)}
401
456
  .wordsLabel{margin-bottom:.1rem}
@@ -586,12 +641,14 @@ export async function settleTranscripts(deps) {
586
641
  if (waiting?.outcome !== "waiting_for_captions" && waiting?.outcome !== "held_source_withheld")
587
642
  continue;
588
643
  const b = r.body;
644
+ const consented = current(deps.ledger.all()).find((x) => x.kind === "participant_consent_request" && x.approval_state === "approved" && x.body.video_id === waiting.video_id);
645
+ const consentWords = consented && typeof consented.body.transcript === "string" ? consented.body.transcript : undefined;
589
646
  const next = await transcriptStep({
590
647
  video_id: waiting.video_id,
591
648
  review_id: waiting.review_id ?? null,
592
649
  // The three days start when the source is released, not when it was held.
593
650
  since: waiting.outcome === "held_source_withheld" ? new Date().toISOString() : waiting.since,
594
- ...(b.transcript ? { supplied: b.transcript } : {}),
651
+ ...(b.transcript ? { supplied: b.transcript } : consentWords ? { supplied: consentWords, source: `the YouTube captions ${String(consented.body.decider_name)} read and said yes to` } : {}),
595
652
  }, transcriptIo(deps));
596
653
  if (next.outcome === waiting.outcome)
597
654
  continue;
@@ -772,13 +829,13 @@ export function isApprovable(r) {
772
829
  return Boolean(r && APPROVABLE.has(r.kind));
773
830
  }
774
831
  /** What approving a request does, in one sentence, for the card a person decides on. */
775
- export function consequenceOf(r, authorization, records = []) {
832
+ export function consequenceOf(r, authorization, records = [], steering) {
776
833
  const b = r.body;
777
834
  switch (r.kind) {
778
835
  case "run_request":
779
836
  return authorization && !authorization.authorized
780
837
  ? `Approving is refused until ${r.actor.name} chooses ${authorization.provider} for this mission on its approval page; approving does not choose it. Declining or sending it back stays possible.`
781
- : `Approving queues a brief for the factory intake, which opens or reaches an agent session within minutes${authorization?.provider ? ` with ${authorization.provider}` : ""}.`;
838
+ : `Approving queues a brief for the factory intake, which opens or reaches an agent session within minutes${authorization?.provider ? ` with ${authorization.provider}` : ""}.${!steering ? "" : !steering.steerable ? ` This session could not be corrected once it works: ${steering.reason ?? "no steering adapter."}` : steering.basis === "tested" ? " A person can correct it while it works." : " A person can correct it while it works, though this version of the agent has not been tested on it."}`;
782
839
  case "work_proposal":
783
840
  return "Approving starts the work: a brief written from the proposal and your instructions is queued for an agent session.";
784
841
  case "review_operation_request":
@@ -788,6 +845,8 @@ export function consequenceOf(r, authorization, records = []) {
788
845
  : "If YouTube has no captions yet, it tries again every 15 minutes for three days."}`;
789
846
  }
790
847
  return `Approving calls the review service once: ${String(b.operation ?? "operation").replace(/_/g, " ")}.`;
848
+ case "participant_consent_request":
849
+ return `Only ${b.decider_name ?? "the person it names"} decides this, on the link made for them. Nobody else can approve it. A yes releases the source and stores the words on the review, and a no keeps them private. Its page shows the email that carries the link, sent only when you press Send.`;
791
850
  case "deep_diver_request":
792
851
  return `Approving marks review version ${b.version ?? "?"} ready for Deep Diver, which queues its pass.`;
793
852
  case "review_episode_link_request":
@@ -876,6 +935,32 @@ export function registerApprovalRoutes(app, deps) {
876
935
  }
877
936
  if (!writer)
878
937
  return void res.status(403).type("html").send(approvePage(deps, r, { error: `Deciding needs Miadi's write tier; ${person.name} has ${person.api_tier ?? "no API tier"}.` }));
938
+ if (r.kind === "participant_consent_request" && body.decision === "send_consent_mail") {
939
+ // The admin read this email on the page and pressed Send: it goes once, to the address Miadi holds for the person.
940
+ const b = r.body;
941
+ const again = (status, error) => void res.status(status).type("html").send(approvePage(deps, find(r.id), { token, ...(error ? { error } : {}) }));
942
+ if (r.approval_state !== "awaiting_approval")
943
+ return again(409, "This request was already answered.");
944
+ if (!b.decider_person_id || !deps.consentLink)
945
+ return again(400, "This request names no Miadi person to mail.");
946
+ if (consentMailSent(deps, r.id))
947
+ return again(409, "This email was already sent.");
948
+ const mail = consentMail(r, deps.consentLink(r.id));
949
+ try {
950
+ await deps.miadi.request(token, "POST", `/api/identity/people/${encodeURIComponent(String(b.decider_person_id))}/mail`, mail, 30_000);
951
+ }
952
+ catch (error) {
953
+ const answer = error instanceof MiadiError ? JSON.stringify(error.body).slice(0, 300) : error instanceof Error ? error.message : String(error);
954
+ logDecision(deps, { phase: "consent_mail", record: r.id, sent: false });
955
+ return again(502, `The email was not sent: ${answer}`);
956
+ }
957
+ deps.ledger.append({ id: newRecordId("observation"), kind: "observation", created_at: new Date().toISOString(), actor: { person_id: person.id, name: person.name, client_id: "approval-page" }, refs: [r.id], evidence_refs: [], circle: "continuity", claim_category: "observed", body: { consent_mail: { request: r.id, subject: mail.subject, sent_at: new Date().toISOString() } } });
958
+ logDecision(deps, { phase: "consent_mail", record: r.id, sent: true });
959
+ return again(200);
960
+ }
961
+ if (r.kind === "participant_consent_request") {
962
+ return void res.status(403).type("html").send(approvePage(deps, r, { token, error: `Only ${String(r.body.decider_name)} decides this, on the link made for them.` }));
963
+ }
879
964
  if (body.decision === "rerun") {
880
965
  let ran;
881
966
  try {
@@ -972,6 +1057,101 @@ export function registerApprovalRoutes(app, deps) {
972
1057
  res.type("html").send(page("Miadi record", `<h1>${escapeHtml(r.kind)}</h1>${summary(r)}`));
973
1058
  });
974
1059
  }
1060
+ /**
1061
+ * The page a person named in a consent request decides on. Their link is the door: a person who never
1062
+ * signed in to Miadi can answer, and it can release only what the source's owner could already release.
1063
+ * The ledger says the answer came through the link, which is what is known (jgwill/Miadi#925).
1064
+ */
1065
+ export function registerConsentRoutes(app, deps, keyOk) {
1066
+ const form = express.urlencoded({ extended: false, limit: "64kb" });
1067
+ const opened = (req, res, key) => {
1068
+ const r = current(deps.ledger.all()).find((x) => x.id === String(req.params.id));
1069
+ res.set("X-Robots-Tag", "noindex");
1070
+ res.set("Referrer-Policy", "no-referrer");
1071
+ if (!r || r.kind !== "participant_consent_request" || !keyOk(r.id, key)) {
1072
+ res.status(404).type("html").send(page("Not found", "<h1>This link opens nothing</h1>"));
1073
+ return null;
1074
+ }
1075
+ return r;
1076
+ };
1077
+ app.get("/consent/:id", (req, res) => {
1078
+ const key = String(req.query.k ?? "");
1079
+ const r = opened(req, res, key);
1080
+ if (r)
1081
+ res.type("html").send(consentPage(r, key));
1082
+ });
1083
+ app.post("/consent/:id", form, async (req, res) => {
1084
+ const body = (req.body ?? {});
1085
+ const key = String(body.k ?? "");
1086
+ const r = opened(req, res, key);
1087
+ if (!r)
1088
+ return;
1089
+ const choice = body.answer === "yes" ? "approve" : body.answer === "not_yet" ? "decline" : null;
1090
+ if (!choice)
1091
+ return void res.status(400).type("html").send(consentPage(r, key, "Choose one of the two buttons."));
1092
+ const b = r.body;
1093
+ const person = { id: String(b.decider_person_id ?? `named:${b.decider_name}`), name: String(b.decider_name), token: "", api_tier: null, permissions: [] };
1094
+ const words = String(body.words ?? "").trim().slice(0, 4000) || undefined;
1095
+ try {
1096
+ await settleWithin(decide(r, person, choice, deps, { instructions: words, via: "consent-link", expectedVersion: versionOf(r) }), decisionWaitOf(deps));
1097
+ }
1098
+ catch (error) {
1099
+ if (!(error instanceof AlreadyDecided))
1100
+ throw error;
1101
+ }
1102
+ res.type("html").send(consentPage(current(deps.ledger.all()).find((x) => x.id === r.id), key));
1103
+ });
1104
+ }
1105
+ /** The email that carries a consent link: short, one question, the same words the page asks. */
1106
+ export function consentMail(r, link) {
1107
+ const b = r.body;
1108
+ const asker = String(b.asked_by ?? r.actor.name);
1109
+ return {
1110
+ subject: `${asker} has one question for you`,
1111
+ text: [`${String(b.decider_name)},`, "", String(b.question), "", `Answer here, no sign-in needed: ${link}`, "", "The page shows the words first. Nothing is published unless you say yes."].join("\n"),
1112
+ };
1113
+ }
1114
+ function consentMailSent(deps, recordId) {
1115
+ const sent = deps.ledger.all().find((x) => x.kind === "observation" && x.body.consent_mail?.request === recordId);
1116
+ return sent ? sent.created_at : null;
1117
+ }
1118
+ function consentMailSection(r, deps) {
1119
+ const b = r.body;
1120
+ const sentAt = consentMailSent(deps, r.id);
1121
+ if (sentAt)
1122
+ return `<p><strong>The email to ${escapeHtml(String(b.decider_name))} was sent</strong> ${escapeHtml(sentAt.slice(0, 16).replace("T", " "))} UTC.</p>`;
1123
+ if (!b.decider_person_id)
1124
+ return `<p>This request names no Miadi person, so there is no address to mail. Send the link yourself.</p>`;
1125
+ const mail = consentMail(r, deps.consentLink(r.id));
1126
+ return `<section aria-label="The email"><p><strong>The email to ${escapeHtml(String(b.decider_name))}, not sent yet.</strong> It goes to the address on their Miadi record.</p>
1127
+ <pre>Subject: ${escapeHtml(mail.subject)}\n\n${escapeHtml(mail.text)}</pre></section>`;
1128
+ }
1129
+ function consentPage(r, key, error) {
1130
+ const b = r.body;
1131
+ const name = String(b.decider_name);
1132
+ const link = (url) => `<a href="${escapeHtml(String(url))}" rel="noreferrer">${escapeHtml(String(url))}</a>`;
1133
+ const where = `<p>The video: ${link(`https://youtu.be/${b.video_id}`)}</p>${b.review_url ? `<p>Its review, already public: ${link(b.review_url)}</p>` : ""}`;
1134
+ const said = String(r.completion_receipt?.instructions ?? "");
1135
+ if (r.approval_state !== "awaiting_approval") {
1136
+ const yes = r.approval_state === "approved";
1137
+ return page("Your answer", `<h1>${yes ? "You said yes" : "You said not yet"}</h1>
1138
+ <p>${yes ? "The words are published beside the review." : "The words stay off the review."} Your answer is kept with your name. To change it, tell ${escapeHtml(r.actor.name)}.</p>
1139
+ ${said ? `<blockquote>${escapeHtml(said)}</blockquote>` : ""}${where}`);
1140
+ }
1141
+ return page(`${name}, one question`, `<h1>${escapeHtml(name)}, one question</h1>
1142
+ <p><strong>${escapeHtml(String(b.question))}</strong></p>
1143
+ ${where}
1144
+ <details><summary>Read the words${b.transcript_words ? ` (${escapeHtml(String(b.transcript_words))} words)` : ""}</summary><pre>${escapeHtml(String(b.transcript ?? ""))}</pre></details>
1145
+ ${error ? `<p class="err" role="alert">${escapeHtml(error)}</p>` : ""}
1146
+ <form method="post">
1147
+ <input type="hidden" name="k" value="${escapeHtml(key)}">
1148
+ <label for="w">Anything you want to say (optional)</label>
1149
+ <textarea id="w" name="words" rows="3"></textarea>
1150
+ <div class="row"><button class="primary" type="submit" name="answer" value="yes">Yes, publish the words</button>
1151
+ <button type="submit" name="answer" value="not_yet">Not yet</button></div>
1152
+ </form>
1153
+ <p class="muted">This asks only about the words. If the video or the review should change, say so in the box. Your answer is kept with your name, and not yet keeps the words off the review.</p>`);
1154
+ }
975
1155
  /** A button that shows where a running request stands now, signed in with the token the person just used. */
976
1156
  function refreshForm(token) {
977
1157
  return `<form method="post"><input type="hidden" name="person_token" value="${escapeHtml(token)}"><div class="row"><button class="primary" type="submit">Show where it stands now</button></div></form>`;
@@ -1013,12 +1193,127 @@ function projectionOf(r, deps) {
1013
1193
  return requestProjection(r, { reviewBase: deps.config.reviewUrl, factoryDir: deps.factoryDir });
1014
1194
  }
1015
1195
  /** Where a request stands, as a page shows it: the label, each line, the review it produced, and the receipt for audit. */
1196
+ /**
1197
+ * Where a correction stands, for the person who sent it: each state with its glyph, time and whose
1198
+ * record says so, and what is still ahead (jgwill/Miadi#942). The model's words and tool inputs are
1199
+ * operator detail, as mission_status has them, so only the write tier sees them here.
1200
+ */
1201
+ function deliveryBlock(r, deps, o) {
1202
+ if (r.kind !== "session_steer_request" || !deps.steeringRuntime)
1203
+ return "";
1204
+ const delivery = readSteerDelivery(deps.steeringRuntime, r);
1205
+ if (!delivery)
1206
+ return "";
1207
+ const word = (state) => DELIVERY_WORDS[state] ?? state.replace(/_/g, " ");
1208
+ const isStop = (state) => state === "expired" || state === "blocked" || state === "unsupported";
1209
+ const operator = Boolean(o.token);
1210
+ const waiting = delivery.state === "queued_at_runtime" || delivery.state === "forwarded_to_runtime";
1211
+ const notFollowed = delivery.behavior === "expected_action_not_seen";
1212
+ const factsOf = (at, source) => `<span class="facts">${at ? `<time datetime="${escapeHtml(at)}">${escapeHtml(at.slice(0, 19).replace("T", " "))} UTC</time>` : ""}<span>${escapeHtml(source.replace(/_/g, " "))}</span></span>`;
1213
+ const rows = delivery.receipts
1214
+ // The connector's write and the inbox holding it are one fact to the person reading.
1215
+ .filter((x) => x.state !== "queued_at_runtime")
1216
+ .map((x) => {
1217
+ const warned = x.state === "emit_failed" || x.state === "wake_not_submitted" || x.state === "left_provider_queue";
1218
+ const icon = isStop(x.state) ? glyph("Stopped", CIRCLE_X_PATHS) : warned ? glyph("Did not go through", TRIANGLE_ALERT_PATHS) : glyph("Reached", CIRCLE_CHECK_PATHS);
1219
+ const said = operator && x.state === "acknowledged" && typeof x.detail?.text === "string" ? `<q class="said">${escapeHtml(x.detail.text.trim().slice(0, 300))}</q>` : "";
1220
+ const action = x.detail?.action;
1221
+ const did = operator && x.state === "behavior_adjusted" && action ? `<code class="did">${escapeHtml(actionWords(action.tool, action.input))}</code>` : "";
1222
+ return `<li class="${isStop(x.state) || warned ? "stopped" : ""}">${icon}<span>${escapeHtml(PAST_WORDS[x.state] ?? word(x.state))}${said}${did}${factsOf(x.at, x.source)}</span></li>`;
1223
+ })
1224
+ .join("");
1225
+ const waitRow = waiting ? `<li>${glyph("Waiting", DASHED_PATHS)}<span>${escapeHtml(word("queued_at_runtime"))}</span></li>` : "";
1226
+ // What has not happened yet, so the list shows the distance left. A stopped or unknown correction has none.
1227
+ const reached = new Set(delivery.receipts.map((x) => x.state));
1228
+ const named = typeof r.body.expect_next_action === "string";
1229
+ const ahead = isStop(delivery.state) || delivery.state === "unknown"
1230
+ ? ""
1231
+ : ["delivered_to_agent_context", "acknowledged", ...(named ? ["behavior_adjusted"] : [])]
1232
+ .filter((state) => !reached.has(state) && !(notFollowed && state === "behavior_adjusted"))
1233
+ .map((state) => `<li class="ahead">${glyph("Not yet", CIRCLE_PATHS)}<span>${escapeHtml(word(state))}</span></li>`)
1234
+ .join("");
1235
+ const nextActions = operator && delivery.state !== "behavior_adjusted" && delivery.next_actions?.length
1236
+ ? `<h3>What it did next</h3><ol>${delivery.next_actions
1237
+ .map((a) => `<li>${glyph("Action", TERMINAL_PATHS)}<span><code class="did">${escapeHtml(actionWords(a.tool, a.input))}</code>${factsOf(a.at, adapterOfRoute(delivery.route)?.evidence ?? "")}</span></li>`)
1238
+ .join("")}</ol>`
1239
+ : "";
1240
+ const stopped = isStop(delivery.state);
1241
+ const now = stopped
1242
+ ? glyph("Stopped", CIRCLE_X_PATHS)
1243
+ : delivery.overdue
1244
+ ? glyph("Waiting longer than it should", TRIANGLE_ALERT_PATHS)
1245
+ : notFollowed
1246
+ ? glyph("Not followed yet", TRIANGLE_ALERT_PATHS)
1247
+ : delivery.state === "unknown"
1248
+ ? glyph("Cannot be told", DASHED_PATHS)
1249
+ : waiting
1250
+ ? glyph("Waiting", DASHED_PATHS)
1251
+ : glyph("Reached", CIRCLE_CHECK_PATHS);
1252
+ const headline = notFollowed ? "The model has it, and no later action holds what this correction named" : delivery.overdue ? "Still waiting, longer than it should" : word(delivery.state);
1253
+ const asked = String(r.body.instruction ?? "");
1254
+ const run = r.refs.find((x) => x.startsWith("run_request:") || x.startsWith("work_proposal:"));
1255
+ const token = o.token ?? o.chooserToken;
1256
+ const hidden = token ? `<input type="hidden" name="person_token" value="${escapeHtml(token)}">` : "";
1257
+ const readAt = new Date().toISOString();
1258
+ const again = token
1259
+ ? `<form method="post" class="again">${hidden}<span class="facts"><span>read <time datetime="${readAt}">${readAt.slice(0, 19).replace("T", " ")} UTC</time></span></span><button class="iconbtn" type="submit" title="Read it again" aria-label="Read it again">${REFRESH_ICON}</button></form>`
1260
+ : "";
1261
+ // Signed in, the way there stays signed in: the same form as this page.
1262
+ const runLabel = run ? `<span class="kind">${TARGET_ICON}mission</span><span class="identity" title="${escapeHtml(run)}">${escapeHtml(run.replace(/^[a-z_]+:/, "").slice(0, 8))}</span>${ARROW_UP_RIGHT_ICON}` : "";
1263
+ const toRun = !run ? "" : token ? `<form method="post" action="/approve/${encodeURIComponent(run)}">${hidden}<button class="outbound" type="submit" aria-label="Open the mission this correction belongs to">${runLabel}</button></form>` : `<a class="outbound" href="/approve/${encodeURIComponent(run)}" aria-label="Open the mission this correction belongs to">${runLabel}</a>`;
1264
+ return `<section class="standard steer-delivery${stopped || notFollowed || delivery.overdue ? " stopped" : ""}" aria-label="Where this correction stands"><h2>Where this correction stands</h2><blockquote class="asked">${escapeHtml(asked.length > 280 ? `${asked.slice(0, 280)}…` : asked)}</blockquote><p class="now">${now}<strong>${escapeHtml(headline)}</strong></p><p class="muted">${escapeHtml(delivery.note)}</p><ol>${rows}${waitRow}${ahead}</ol>${nextActions}${toRun}${again}</section>`;
1265
+ }
1266
+ /** A tool call in the words a person reads: its command when it has one, else its input as recorded. */
1267
+ function actionWords(tool, input) {
1268
+ try {
1269
+ const command = JSON.parse(input ?? "").command;
1270
+ if (typeof command === "string")
1271
+ return command;
1272
+ }
1273
+ catch {
1274
+ // The input was cut to its first 200 characters, or was not JSON: shown as recorded.
1275
+ }
1276
+ return `${tool ?? ""} ${input ?? ""}`.trim();
1277
+ }
1278
+ /** The words for a step already passed, where they differ from the state's own. */
1279
+ const PAST_WORDS = {
1280
+ queued_at_runtime: "In the session's inbox",
1281
+ };
1282
+ const DELIVERY_WORDS = {
1283
+ authorized: "Authorized",
1284
+ forwarded_to_runtime: "Handed to the session's inbox",
1285
+ queued_at_runtime: "Waiting for the agent's next step",
1286
+ runtime_hook_emitted: "The agent's runtime took it",
1287
+ in_model_request: "Held in the request going to the model",
1288
+ delivered_to_agent_context: "The model has it",
1289
+ acknowledged: "The model says it received it",
1290
+ behavior_adjusted: "A later action holds what this correction named",
1291
+ emit_failed: "The agent refused it for now, and it goes back in the inbox",
1292
+ wake_not_submitted: "A line to wake the seat did not go in, and the next pass tries again",
1293
+ left_provider_queue: "The agent's run ended before the model read it",
1294
+ seat_was_idle: "The seat was idle",
1295
+ seat_woken: "The factory runner woke the seat",
1296
+ unsupported: "This session cannot be corrected",
1297
+ expired: "Expired before the model read it",
1298
+ blocked: "Stopped before the model read it",
1299
+ unknown: "Whether the model read it cannot be told",
1300
+ };
1301
+ /** Whether this run could be corrected once it works, as a state with its glyph, before and after it is decided (jgwill/Miadi#942). */
1302
+ function runSteeringLine(r, provider, deps) {
1303
+ if (r.kind !== "run_request" || !provider || !deps.steeringOf)
1304
+ return "";
1305
+ const s = deps.steeringOf(provider);
1306
+ if (!s.steerable)
1307
+ return `<p class="state stopped">${glyph("Cannot be corrected", CIRCLE_X_PATHS)}<span>A person could not correct this run while it works. ${escapeHtml(s.reason ?? "")}</span></p>`;
1308
+ return stateLine("Can be corrected", CIRCLE_CHECK_PATHS, s.basis === "tested" ? "A person can correct this run while it works." : "A person can correct this run while it works, though no real session of this version of the agent has been tested.");
1309
+ }
1310
+ const receiptBlock = (receipt) => (receipt ? `<details><summary>Receipt</summary><pre>${escapeHtml(JSON.stringify(receipt, null, 2))}</pre></details>` : "");
1016
1311
  function projectionBlock(p, receipt) {
1017
1312
  if (!p)
1018
1313
  return "";
1019
1314
  const lines = p.lines.map((l) => `<li>${escapeHtml(l)}</li>`).join("");
1020
1315
  const review = p.receipt_url ? `<p><a href="${escapeHtml(p.receipt_url)}" rel="noopener">${escapeHtml(p.receipt_url)}</a></p>` : "";
1021
- const audit = receipt ? `<details><summary>Receipt</summary><pre>${escapeHtml(JSON.stringify(receipt, null, 2))}</pre></details>` : "";
1316
+ const audit = receiptBlock(receipt);
1022
1317
  return `<section aria-label="Where it stands"><p><strong>${escapeHtml(p.label)}</strong></p>${lines ? `<ul>${lines}</ul>` : ""}${review}${audit}</section>`;
1023
1318
  }
1024
1319
  const SETTLER_WORDS = {
@@ -1027,6 +1322,15 @@ const SETTLER_WORDS = {
1027
1322
  bystander: "Only the person deciding can answer this, in their instructions.",
1028
1323
  local_agent: "A local agent can settle this from the running system.",
1029
1324
  };
1325
+ const TRIANGLE_ALERT_PATHS = `<path d="m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"/><path d="M12 9v4"/><path d="M12 17h.01"/>`;
1326
+ const svgIcon = (paths) => `<svg aria-hidden="true" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round">${paths}</svg>`;
1327
+ const REFRESH_ICON = svgIcon(`<path d="M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"/><path d="M21 3v5h-5"/><path d="M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"/><path d="M8 16H3v5"/>`);
1328
+ const ARROW_UP_RIGHT_ICON = svgIcon(`<path d="M7 7h10v10"/><path d="M7 17 17 7"/>`);
1329
+ const TARGET_ICON = svgIcon(`<circle cx="12" cy="12" r="10"/><circle cx="12" cy="12" r="6"/><circle cx="12" cy="12" r="2"/>`);
1330
+ const CIRCLE_PATHS = `<circle cx="12" cy="12" r="10"/>`;
1331
+ const TERMINAL_PATHS = `<path d="M12 19h8"/><path d="m4 17 6-6-6-6"/>`;
1332
+ const CIRCLE_CHECK_PATHS = `<circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/>`;
1333
+ const CIRCLE_X_PATHS = `<circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/>`;
1030
1334
  const DASHED_PATHS = `<path d="M10.1 2.182a10 10 0 0 1 3.8 0"/><path d="M13.9 21.818a10 10 0 0 1-3.8 0"/><path d="M17.609 3.721a10 10 0 0 1 2.69 2.7"/><path d="M2.182 13.9a10 10 0 0 1 0-3.8"/><path d="M20.279 17.609a10 10 0 0 1-2.7 2.69"/><path d="M21.818 10.1a10 10 0 0 1 0 3.8"/><path d="M3.721 6.391a10 10 0 0 1 2.7-2.69"/><path d="M6.391 20.279a10 10 0 0 1-2.69-2.7"/>`;
1031
1335
  const EYE_PATHS = `<path d="M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"/><circle cx="12" cy="12" r="3"/>`;
1032
1336
  const glyph = (label, paths) => `<svg class="glyph" role="img" aria-label="${label}" viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round">${paths}</svg>`;
@@ -1084,21 +1388,34 @@ function approvePage(deps, r, o = {}) {
1084
1388
  const authorization = r.kind === "run_request" ? authorizeProvider(r, deps.ledger.all(), { requireFresh: open }) : undefined;
1085
1389
  const blocked = Boolean(authorization && !authorization.authorized);
1086
1390
  // Signed in and able to decide: the decision comes before the record's details, and no line says it waits for someone else.
1087
- const canDecideHere = Boolean(actionable && o.token);
1088
- const heading = canDecideHere ? "Not approved yet: decide here" : open ? "A request awaiting a decision" : (projectionOf(r, deps)?.label ?? "A decided request");
1391
+ const asksSomeone = r.kind === "participant_consent_request";
1392
+ const canDecideHere = Boolean(actionable && o.token && !asksSomeone);
1393
+ // A correction's own evidence speaks for it, in its own section: the ledger's word may lag it until the next read settles it.
1394
+ const steerDecided = !open && r.kind === "session_steer_request" && Boolean(deps.steeringRuntime && readSteerDelivery(deps.steeringRuntime, r));
1395
+ const heading = canDecideHere ? "Not approved yet: decide here" : open ? "A request awaiting a decision" : steerDecided ? "A correction to a running agent" : (projectionOf(r, deps)?.label ?? "A decided request");
1089
1396
  const details = canDecideHere
1090
1397
  ? `<details><summary>What exactly is asked</summary>${summary(r, { intention: false })}</details>`
1091
- : `${summary(r)}
1398
+ : steerDecided
1399
+ ? `${deliveryBlock(r, deps, o)}
1400
+ <details><summary>What exactly was sent</summary>${summary(r)}</details>
1401
+ ${receiptBlock(r.completion_receipt)}`
1402
+ : `${summary(r)}
1092
1403
  ${open ? draftReviewSection(r, deps.draftReview?.stored(r), false) : ""}
1093
1404
  ${projectionBlock(projectionOf(r, deps), open ? undefined : r.completion_receipt)}`;
1094
1405
  return page("Approve a Miadi request", `<h1>${escapeHtml(heading)}</h1>
1095
1406
  ${canDecideHere ? `<p>You are signed in. Nothing is approved until you press a button below.</p>` : ""}
1407
+ ${asksSomeone && open && o.token && deps.consentLink ? consentMailSection(r, deps) : ""}
1408
+ ${asksSomeone && open && (o.token || o.chooserToken) && deps.consentLink ? `<p><strong>The link to send ${escapeHtml(String(r.body.decider_name))}:</strong><br><a href="${escapeHtml(deps.consentLink(r.id))}" rel="noreferrer">${escapeHtml(deps.consentLink(r.id))}</a></p>` : ""}
1096
1409
  ${actionable ? `<p>${escapeHtml(consequenceOf(r, authorization, current(deps.ledger.all())))} Declining records your refusal. Either is kept in the ledger with your name.</p>` : ""}
1410
+ ${runSteeringLine(r, authorization?.provider ?? undefined, deps)}
1097
1411
  ${canDecideHere && r.intention ? `<p><strong>Intention:</strong> ${escapeHtml(r.intention)}</p>` : ""}
1098
1412
  ${authorization ? providerSection(r, authorization, actionable ? o.chooserToken : undefined) : ""}
1099
1413
  ${canDecideHere ? draftReviewSection(r, deps.draftReview?.stored(r), !blocked) : ""}
1100
1414
  ${o.error ? `<p class="err" role="alert">${escapeHtml(o.error)}</p>` : ""}
1101
- ${actionable && o.token
1415
+ ${asksSomeone && open && o.token && deps.consentLink && r.body.decider_person_id && !consentMailSent(deps, r.id)
1416
+ ? `<form method="post"><input type="hidden" name="person_token" value="${escapeHtml(o.token)}"><div class="row"><button class="primary" type="submit" name="decision" value="send_consent_mail">Send this email</button></div></form>`
1417
+ : ""}
1418
+ ${canDecideHere
1102
1419
  ? `<form method="post">
1103
1420
  <input type="hidden" name="person_token" value="${escapeHtml(o.token)}">
1104
1421
  <input type="hidden" name="version" value="${versionOf(r)}">
@@ -1156,6 +1473,7 @@ export function registerProviderPolicyRoutes(app, deps) {
1156
1473
  ${error ? `<p class="err" role="alert">${escapeHtml(error)}</p>` : ""}
1157
1474
  <form method="post"><label for="t">Your Miadi person token</label><input id="t" name="person_token" type="password" autocomplete="off" required>
1158
1475
  <div class="row"><button class="primary" type="submit">Read my policy</button></div></form>`);
1476
+ const policyOfPerson = (personId) => providerPolicyOf(deps.ledger.all(), personId, readFactoryConfig(deps.factoryDir ?? factoryDir())?.person_default_provider);
1159
1477
  app.get("/providers", (_req, res) => void res.type("html").send(signIn()));
1160
1478
  app.post("/providers", form, async (req, res) => {
1161
1479
  const body = (req.body ?? {});
@@ -1177,7 +1495,13 @@ ${error ? `<p class="err" role="alert">${escapeHtml(error)}</p>` : ""}
1177
1495
  if (body.codex !== undefined) {
1178
1496
  if (!CODEX_POLICIES.includes(body.codex))
1179
1497
  return void res.status(400).type("html").send(signIn("Unknown Codex policy."));
1180
- if (providerPolicyOf(deps.ledger.all(), person.id).codex !== body.codex) {
1498
+ if (body.default_provider && !["claude", "pi", "copilot", HOST_ORDER].includes(body.default_provider))
1499
+ return void res.status(400).type("html").send(signIn("Unknown default provider."));
1500
+ const before = policyOfPerson(person.id);
1501
+ const wanted = body.default_provider ?? "";
1502
+ const had = before.default_provider ?? HOST_ORDER;
1503
+ const changed = before.codex !== body.codex || Boolean(wanted && had !== wanted);
1504
+ if (changed) {
1181
1505
  deps.ledger.append({
1182
1506
  id: newRecordId("provider_policy"),
1183
1507
  kind: "provider_policy",
@@ -1186,22 +1510,31 @@ ${error ? `<p class="err" role="alert">${escapeHtml(error)}</p>` : ""}
1186
1510
  refs: [],
1187
1511
  evidence_refs: [],
1188
1512
  claim_category: "observed",
1189
- body: { codex: body.codex },
1513
+ body: { codex: body.codex, ...(wanted ? { default_provider: wanted } : {}) },
1190
1514
  });
1191
- logDecision(deps, { phase: "provider_policy_set", person: person.id, codex: body.codex });
1515
+ logDecision(deps, { phase: "provider_policy_set", person: person.id, codex: body.codex, ...(wanted ? { default_provider: wanted } : {}) });
1192
1516
  }
1193
- saved = "<p>Saved. It applies to your requests from now on, including a failed run of yours that is run again. A per-mission choice you already made still covers its mission.</p>";
1517
+ saved = changed ? "<p>Saved. It applies to your requests from now on, including a failed run of yours that is run again. A per-mission choice you already made still covers its mission.</p>" : "<p>Nothing changed: this is already your policy.</p>";
1194
1518
  }
1195
- const policy = providerPolicyOf(deps.ledger.all(), person.id);
1519
+ const policy = policyOfPerson(person.id);
1196
1520
  const option = (value, label) => `<label><input type="radio" name="codex" value="${value}"${policy.codex === value ? " checked" : ""}> ${escapeHtml(label)}</label>`;
1521
+ const providerWord = (id) => (id === "claude" ? "Claude Code" : id === "copilot" ? "Copilot" : id === "pi" ? "Pi" : String(id ?? ""));
1522
+ const defaultOption = (value, label) => `<label><input type="radio" name="default_provider" value="${value}"${(policy.default_provider ?? HOST_ORDER) === value ? " checked" : ""}> ${escapeHtml(label)}</label>`;
1197
1523
  res.type("html").send(page("Your provider policy", `<h1>${escapeHtml(person.name)}'s provider policy</h1>${saved}
1198
1524
  <dl><dt>Codex</dt><dd>${escapeHtml(policy.codex.replace(/_/g, " "))}${policy.source === "default" ? " (the default)" : `, set ${escapeHtml(policy.set_at ?? "")}`}</dd>
1199
- <dt>Other providers</dt><dd>Pi, Copilot and Claude Code run when a request names them and they are installed; Pi and Copilot may also be picked by the host's order.</dd></dl>
1525
+ <dt>Other providers</dt><dd>Pi, Copilot and Claude Code run when a request names them and they are installed.</dd></dl>
1200
1526
  <form method="post"><input type="hidden" name="person_token" value="${escapeHtml(token)}">
1201
1527
  <fieldset><legend>When a request in my name names Codex</legend>
1202
1528
  ${option("per_mission_choice", "Codex runs only when I choose it for that mission on its approval page (default).")}
1203
1529
  ${option("selectable", "Codex may be named for my requests without a per-mission choice.")}
1204
1530
  </fieldset>
1531
+ <fieldset class="provider-defaults"><legend>When a request in my name names no provider</legend>
1532
+ ${defaultOption(HOST_ORDER, "The host's order, which starts with Pi")}
1533
+ ${defaultOption("pi", "Pi")}
1534
+ ${defaultOption("copilot", "Copilot")}
1535
+ ${defaultOption("claude", "Claude Code")}
1536
+ ${policy.default_provider_source === "host_config" ? `<p class="muted">The operator set ${escapeHtml(providerWord(policy.default_provider))} for you. Choosing another here replaces that.</p>` : ""}
1537
+ </fieldset>
1205
1538
  <div class="row"><button class="primary" type="submit">Save my policy</button></div></form>`));
1206
1539
  });
1207
1540
  }
@@ -1210,6 +1543,7 @@ export const KIND_LABELS = {
1210
1543
  run_request: "Agent run",
1211
1544
  work_proposal: "Work proposal",
1212
1545
  review_operation_request: "Review operation",
1546
+ participant_consent_request: "A person's consent",
1213
1547
  deep_diver_request: "Deep Diver",
1214
1548
  review_episode_link_request: "Review into an episode",
1215
1549
  inquiry_episode_request: "Inquiry into an episode",
package/dist/bin.js CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
+ import { execFile } from "node:child_process";
2
3
  import { configFromEnv } from "./config.js";
3
4
  import { createConnectorApp } from "./server.js";
4
5
  import { identifyThroughMiadi } from "./people.js";
@@ -17,6 +18,10 @@ const { app } = createConnectorApp(config, {
17
18
  tmuxSessions: () => tmux.listSessions(),
18
19
  // Each session's own steering inbox and Claude Code's registry of running sessions (jgwill/Miadi#930).
19
20
  steeringRuntime: defaultRuntime(),
21
+ // The factory runner's wake now, for an idle seat a correction just reached. Its timer is the net, so a failure here is nothing (jgwill/Miadi#942).
22
+ wakeRunner: () => {
23
+ execFile(process.env.MIADI_FACTORY_RUNNER_BIN ?? "miadi-factory-runner", ["wake"], { timeout: 60_000 }, () => { });
24
+ },
20
25
  // An approved create stores the video's YouTube captions as the review's transcript, with no model call.
21
26
  captions: youtubeCaptions,
22
27
  });
@@ -38,6 +38,12 @@ export interface TranscriptIo {
38
38
  }>;
39
39
  now?: () => number;
40
40
  }
41
+ /** The covered range in words a person reads: "00:02 to 33:03 of 62:38". */
42
+ export declare function coverage(a: {
43
+ first_ms: number;
44
+ last_ms: number;
45
+ duration_s?: number;
46
+ }): string;
41
47
  /**
42
48
  * YouTube's json3 captions as the plain `[mm:ss] text` paragraphs the review service parses into turns.
43
49
  * The words stay as YouTube wrote them. The first line says what they are. Null when they hold no words.
@@ -63,6 +69,7 @@ export declare function transcriptStep(input: {
63
69
  review_id: string | null;
64
70
  since: string;
65
71
  supplied?: string;
72
+ source?: string;
66
73
  }, io: TranscriptIo): Promise<TranscriptReceipt>;
67
74
  /** What a transcript receipt says on a request's card and approval page. */
68
75
  export declare function transcriptLines(transcript: unknown): string[];
package/dist/captions.js CHANGED
@@ -30,7 +30,7 @@ function clock(ms) {
30
30
  return h ? `${h}:${String(m).padStart(2, "0")}:${s}` : `${String(m).padStart(2, "0")}:${s}`;
31
31
  }
32
32
  /** The covered range in words a person reads: "00:02 to 33:03 of 62:38". */
33
- function coverage(a) {
33
+ export function coverage(a) {
34
34
  return `${clock(a.first_ms)} to ${clock(a.last_ms)}${a.duration_s ? ` of ${clock(a.duration_s * 1000)}` : ""}`;
35
35
  }
36
36
  /**
@@ -157,7 +157,7 @@ export async function transcriptStep(input, io) {
157
157
  return {
158
158
  ...base,
159
159
  outcome: "stored",
160
- source: supplied ? "supplied with the request" : `YouTube captions (${answer.track})`,
160
+ source: input.source ?? (supplied ? "supplied with the request" : `YouTube captions (${answer.track})`),
161
161
  chars: text.length,
162
162
  sha256: createHash("sha256").update(text).digest("hex"),
163
163
  stored_at: new Date(now).toISOString(),