@miadi/connector 0.1.27 → 0.1.29

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,15 @@ 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";
29
+ import { modelAttributes, routeModel } from "./claude-models.js";
27
30
  import { TRANSCRIPT_RETRY_MS, transcriptStep } from "./captions.js";
28
31
  import { ReviewClient } from "./reviews.js";
29
32
  import { canReadReading } from "./reading/privacy.js";
30
- import { authorizationReceipt, authorizeProvider, briefAttributes, CHOICE_TTL_MS, CODEX_POLICIES, isPersonId, needsPersonChoice, providerPolicyOf, } from "./provider-policy.js";
33
+ import { authorizationReceipt, authorizeProvider, briefAttributes, CHOICE_TTL_MS, CODEX_POLICIES, isPersonId, needsPersonChoice, HOST_ORDER, providerPolicyOf, } from "./provider-policy.js";
31
34
  export { factoryDir, runBriefFile, readQueueState } from "./queue-state.js";
32
35
  /**
33
36
  * One line per step of a decision, for the journal: the request, a correlation id,
@@ -96,12 +99,14 @@ function attr(v) {
96
99
  function text(v) {
97
100
  return String(v ?? "").replace(/<(?=[\/!?]?[A-Za-z])/g, "‹");
98
101
  }
102
+ /** How a proposal launches, which the brief's attributes carry: not part of the work (jgwill/Miadi#943). */
103
+ const LAUNCH_FIELDS = new Set(["resolved_provider", "model", "model_routing", "task_type", "criticality"]);
99
104
  /** The task a work proposal asks for, written from the proposal's own fields. */
100
105
  export function proposalTask(record) {
101
106
  const b = record.body;
102
107
  const lines = ["Carry out this approved work proposal, within its own scope and constraints.", ""];
103
108
  for (const [k, v] of Object.entries(b)) {
104
- if (v === undefined || v === null || v === "")
109
+ if (v === undefined || v === null || v === "" || LAUNCH_FIELDS.has(k))
105
110
  continue;
106
111
  lines.push(`${k.replace(/_/g, " ")}: ${typeof v === "string" ? v : JSON.stringify(v)}`);
107
112
  }
@@ -110,7 +115,8 @@ export function proposalTask(record) {
110
115
  export function runBrief(record, approver, sessions, instructions, providerAttrs = {}, openAspects = []) {
111
116
  const body = (record.kind === "work_proposal" ? { task: proposalTask(record) } : record.body);
112
117
  // A request recorded before providers were resolved (jgwill/Miadi#893) names only what was asked (#926 review RR7).
113
- const provider = body.resolved_provider ?? body.provider;
118
+ // A work proposal resolves its provider too, and one recorded before that names none (jgwill/Miadi#943).
119
+ const provider = record.body.resolved_provider ?? body.provider;
114
120
  const short = record.id.split(":")[1]?.slice(0, 8) ?? "run";
115
121
  const to = body.session && sessions.includes(body.session) ? body.session : `new:${body.session ?? `connector-${yymmdd()}-${short}`}`;
116
122
  // A new session opens where the request says, else where the factory runner's config says (defaultCwd): no host path here (#911).
@@ -231,7 +237,7 @@ export async function executeApproved(record, approver, deps, instructions) {
231
237
  const f = deps.fetchImpl ?? fetch;
232
238
  const b = record.body;
233
239
  const reviewCall = (method, path, payload) => callReview(deps, method, path, payload);
234
- const queueBrief = () => {
240
+ const queueBrief = async () => {
235
241
  // Checked again where the brief is written: an approval, and every rerun of it (jgwill/Miadi#926).
236
242
  const authorization = record.kind === "run_request" ? authorizeProvider(record, deps.ledger.all()) : undefined;
237
243
  if (authorization && !authorization.authorized) {
@@ -247,14 +253,30 @@ export async function executeApproved(record, approver, deps, instructions) {
247
253
  catch {
248
254
  sessions = [];
249
255
  }
250
- const { to, brief } = runBrief(record, approver, sessions, instructions, authorization ? briefAttributes(authorization) : {}, deps.draftReview?.stored(record)?.needs_revision ?? []);
256
+ // A session already running keeps its model: a named one cannot be honoured, and Jev is not asked (jgwill/Miadi#943).
257
+ const existingSession = record.kind === "run_request" && typeof b.session === "string" && sessions.includes(b.session);
258
+ if (existingSession && typeof b.model === "string" && b.model) {
259
+ return { outcome: "failed", message: `No brief was written. Session ${b.session} is already running on its own model, so ${b.model} cannot apply. Run it again once that session has ended, or make a new request with another session name.` };
260
+ }
261
+ const routing = await routeModel(record, { existingSession }, { factoryDir: deps.factoryDir, ...deps.modelRouting });
262
+ if (routing?.source === "unavailable") {
263
+ return { outcome: "failed", model_routing: routing, message: `No brief was written. ${routing.why}, and no other provider stands in for it. Run it again once it is back.` };
264
+ }
265
+ const { to, brief } = runBrief(record, approver, sessions, instructions, { ...(authorization ? briefAttributes(authorization) : {}), ...modelAttributes(routing) }, deps.draftReview?.stored(record)?.needs_revision ?? []);
251
266
  const file = runBriefFile(record);
252
- writeFileSync(join(queue, file), brief, { flag: "wx", mode: 0o640 });
267
+ try {
268
+ writeFileSync(join(queue, file), brief, { flag: "wx", mode: 0o640 });
269
+ }
270
+ catch (error) {
271
+ // The answer stays with the failure, so running it again does not ask Jev a second time.
272
+ return { outcome: "failed", ...(routing ? { model_routing: routing } : {}), message: error instanceof Error ? error.message : String(error) };
273
+ }
253
274
  return {
254
275
  outcome: "queued",
255
276
  to,
256
277
  file,
257
278
  ...(authorization ? { provider_authorization: authorizationReceipt(authorization) } : {}),
279
+ ...(routing ? { model_routing: routing } : {}),
258
280
  note: "The factory intake delivers queued briefs every 5 minutes.",
259
281
  };
260
282
  };
@@ -353,7 +375,7 @@ export async function executeApproved(record, approver, deps, instructions) {
353
375
  return { outcome: "failed", message: "The run whose grant this steer cites is gone." };
354
376
  // The pane the factory delivered the mission to, when it recorded one (jgwill/Miadi#909).
355
377
  const bound = receiptsForRecord(readFactoryReceipts(factoryLedgerPath(deps.factoryDir ?? factoryDir())), grantRecord.id)[0];
356
- const result = await steerSession({ tmux: deps.tmux ?? tmuxAdapter(), stateDir: deps.config.stateDir, ...(deps.steeringRuntime ? { runtime: deps.steeringRuntime } : {}), ...(deps.steerSettleMs !== undefined ? { settleMs: deps.steerSettleMs } : {}) }, {
378
+ 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 } : {}) }, {
357
379
  record,
358
380
  grantRecord,
359
381
  priorAttempts: steerAttempts(current(deps.ledger.all()), grantRecord.id),
@@ -367,6 +389,7 @@ export async function executeApproved(record, approver, deps, instructions) {
367
389
  typed: result.typed,
368
390
  ...(result.forwarded ? { forwarded: true } : {}),
369
391
  ...(result.route ? { route: result.route } : {}),
392
+ ...(result.runtime_session_id ? { runtime_session_id: result.runtime_session_id } : {}),
370
393
  ...(result.transcript_offset !== undefined ? { transcript_offset: result.transcript_offset } : {}),
371
394
  message: result.message,
372
395
  ...(result.target ? { target: result.target } : {}),
@@ -377,12 +400,12 @@ export async function executeApproved(record, approver, deps, instructions) {
377
400
  return { outcome: "nothing_to_run" };
378
401
  }
379
402
  }
380
- function page(title, body) {
403
+ export function page(title, body) {
381
404
  return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
382
405
  <title>${escapeHtml(title)}</title>
383
406
  <style>
384
407
  :root{color-scheme:light dark;--bg:#fbfaf7;--fg:#1d1b18;--muted:#5b5650;--line:#d9d4cc;--accent:#7a4a00;--code:#f1ede6}
385
- @media (prefers-color-scheme:dark){:root{--bg:#141311;--fg:#ece8e1;--muted:#b3ada4;--line:#3a3631;--accent:#ffd700;--code:#1f1d1a}}
408
+ @media (prefers-color-scheme:dark){:root{--bg:#141311;--fg:#ece8e1;--muted:#b3ada4;--line:#3a3631;--accent:#ffd700;--code:#1f1d1a;--err:#ff7b72}}
386
409
  body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.5 system-ui,sans-serif}
387
410
  main{max-width:44rem;margin:0 auto;padding:2rem 1rem}
388
411
  h1{font-size:1.35rem;margin:0 0 .5rem}
@@ -418,6 +441,36 @@ summary:focus-visible,.iconbtn:focus-visible{outline:2px solid var(--accent);out
418
441
  .who{display:flex;gap:.5rem;align-items:center}
419
442
  .iconbtn{width:34px;height:34px;flex:none;display:inline-grid;place-items:center;border:1px solid var(--line);border-radius:.4rem;color:var(--fg)}
420
443
  .state{display:grid;grid-template-columns:1rem 1fr;gap:.5rem;color:var(--muted);font-size:.9rem}
444
+ .steer-delivery .now{display:grid;grid-template-columns:1rem 1fr;gap:.5rem;align-items:start;margin:.4rem 0}
445
+ .steer-delivery .glyph{color:var(--muted);margin-top:.25rem}
446
+ .steer-delivery.stopped .now .glyph,.steer-delivery li.stopped .glyph{color:var(--err,#b00020)}
447
+ .steer-delivery ol,.steer-delivery .actions{list-style:none;margin:.8rem 0 0;padding:0;display:grid;gap:.5rem}
448
+ .steer-delivery ol>li{display:grid;grid-template-columns:1rem 1fr;gap:.5rem;overflow-wrap:anywhere}
449
+ .steer-delivery li.ahead{color:var(--muted)}
450
+ .steer-delivery .facts{display:block;color:var(--muted);font-size:.85rem;font-family:ui-monospace,monospace}
451
+ .steer-delivery .facts>*{white-space:nowrap}
452
+ .steer-delivery .facts>*+*::before{content:" · "}
453
+ .steer-delivery .said{display:block;margin:.2rem 0;color:var(--muted);font-size:.9rem;overflow-wrap:anywhere}
454
+ .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}
455
+ .steer-delivery h3{font-size:.95rem;margin:1rem 0 0}
456
+ .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}
457
+ .steer-delivery .outbound svg{flex:0 0 auto}
458
+ .steer-delivery .outbound .kind{display:inline-flex;align-items:center;gap:.4rem;color:var(--muted)}
459
+ .steer-delivery .outbound .identity{flex:1;text-align:left;color:var(--accent);font-family:ui-monospace,monospace;overflow:hidden;text-overflow:ellipsis}
460
+ .steer-delivery .again{display:flex;align-items:center;justify-content:space-between;gap:.6rem;margin-top:.8rem}
461
+ .steer-delivery .asked{margin:.4rem 0 .8rem;padding:.4rem .7rem;border-left:2px solid var(--line);overflow-wrap:anywhere}
462
+ details>summary{min-height:34px;padding:.3rem 0;box-sizing:border-box;cursor:pointer}
463
+ .steer-delivery .again button.iconbtn{padding:0}
464
+ .steer-delivery .outbound:hover,.steer-delivery .iconbtn:hover{background:color-mix(in srgb,var(--accent) 12%,transparent)}
465
+ .steer-delivery .outbound:active,.steer-delivery .iconbtn:active{transform:scale(.94)}
466
+ .steer-delivery .outbound:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
467
+ @media (prefers-reduced-motion:reduce){.steer-delivery .outbound:active,.steer-delivery .iconbtn:active{transform:none}}
468
+ .state.stopped{color:var(--fg);font-size:1rem}
469
+ .state.stopped .glyph{color:var(--err,#b00020)}
470
+ fieldset{border:1px solid var(--line);border-radius:.4rem;margin:1rem 0;padding:.5rem .8rem;min-width:0}
471
+ fieldset legend{float:left;width:100%;padding:0;margin-bottom:.3rem;font-size:.95rem}
472
+ fieldset label{clear:both;display:flex;align-items:flex-start;gap:.5rem;min-height:34px;margin:.45rem 0;font-weight:400}
473
+ input[type=radio]{accent-color:var(--accent);flex:0 0 auto;margin:.3rem 0 0}
421
474
  .code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.9em}
422
475
  .glyph{margin-top:.25rem;color:var(--muted)}
423
476
  .wordsLabel{margin-bottom:.1rem}
@@ -556,8 +609,10 @@ export async function decide(r, person, choice, deps, opts) {
556
609
  }
557
610
  /**
558
611
  * The kinds whose run is done at once on this host (a brief written to the
559
- * factory queue, an ending recorded): nothing outside is called, so nothing is
560
- * written ahead of it. Every other approved run is recorded as running first.
612
+ * factory queue, an ending recorded), so nothing is written ahead of it. A run may
613
+ * ask Jev for its model first, up to 8 s: a restart then loses the click and that
614
+ * one call, and the request still waits for its decision. Every other approved run
615
+ * is recorded as running first.
561
616
  */
562
617
  const RUNS_AT_ONCE = new Set(["run_request", "work_proposal", "session_completion_proposal"]);
563
618
  /** What the receipt of a run the connector lost to a restart says (jgwill/Miadi#924). */
@@ -795,16 +850,17 @@ async function decideOnce(r, person, choice, deps, opts) {
795
850
  export function isApprovable(r) {
796
851
  return Boolean(r && APPROVABLE.has(r.kind));
797
852
  }
853
+ const modelWords = (b) => (typeof b.model === "string" && b.model ? ` on ${b.model}` : b.model_routing ? " on the model Jev chooses" : "");
798
854
  /** What approving a request does, in one sentence, for the card a person decides on. */
799
- export function consequenceOf(r, authorization, records = []) {
855
+ export function consequenceOf(r, authorization, records = [], steering) {
800
856
  const b = r.body;
801
857
  switch (r.kind) {
802
858
  case "run_request":
803
859
  return authorization && !authorization.authorized
804
860
  ? `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.`
805
- : `Approving queues a brief for the factory intake, which opens or reaches an agent session within minutes${authorization?.provider ? ` with ${authorization.provider}` : ""}.`;
861
+ : `Approving queues a brief for the factory intake, which opens or reaches an agent session within minutes${authorization?.provider ? ` with ${authorization.provider}` : ""}${modelWords(b)}.${!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."}`;
806
862
  case "work_proposal":
807
- return "Approving starts the work: a brief written from the proposal and your instructions is queued for an agent session.";
863
+ return `Approving starts the work: a brief written from the proposal and your instructions is queued for an agent session${typeof b.resolved_provider === "string" ? ` with ${b.resolved_provider}` : ""}${modelWords(b)}.`;
808
864
  case "review_operation_request":
809
865
  if (b.operation === "create") {
810
866
  return `Approving calls the review service once to create the review, then stores the video's YouTube captions as its transcript, with no model call for the transcript. ${sourceWithheld(records, b.video_id)
@@ -1160,12 +1216,127 @@ function projectionOf(r, deps) {
1160
1216
  return requestProjection(r, { reviewBase: deps.config.reviewUrl, factoryDir: deps.factoryDir });
1161
1217
  }
1162
1218
  /** Where a request stands, as a page shows it: the label, each line, the review it produced, and the receipt for audit. */
1219
+ /**
1220
+ * Where a correction stands, for the person who sent it: each state with its glyph, time and whose
1221
+ * record says so, and what is still ahead (jgwill/Miadi#942). The model's words and tool inputs are
1222
+ * operator detail, as mission_status has them, so only the write tier sees them here.
1223
+ */
1224
+ function deliveryBlock(r, deps, o) {
1225
+ if (r.kind !== "session_steer_request" || !deps.steeringRuntime)
1226
+ return "";
1227
+ const delivery = readSteerDelivery(deps.steeringRuntime, r);
1228
+ if (!delivery)
1229
+ return "";
1230
+ const word = (state) => DELIVERY_WORDS[state] ?? state.replace(/_/g, " ");
1231
+ const isStop = (state) => state === "expired" || state === "blocked" || state === "unsupported";
1232
+ const operator = Boolean(o.token);
1233
+ const waiting = delivery.state === "queued_at_runtime" || delivery.state === "forwarded_to_runtime";
1234
+ const notFollowed = delivery.behavior === "expected_action_not_seen";
1235
+ 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>`;
1236
+ const rows = delivery.receipts
1237
+ // The connector's write and the inbox holding it are one fact to the person reading.
1238
+ .filter((x) => x.state !== "queued_at_runtime")
1239
+ .map((x) => {
1240
+ const warned = x.state === "emit_failed" || x.state === "wake_not_submitted" || x.state === "left_provider_queue";
1241
+ const icon = isStop(x.state) ? glyph("Stopped", CIRCLE_X_PATHS) : warned ? glyph("Did not go through", TRIANGLE_ALERT_PATHS) : glyph("Reached", CIRCLE_CHECK_PATHS);
1242
+ const said = operator && x.state === "acknowledged" && typeof x.detail?.text === "string" ? `<q class="said">${escapeHtml(x.detail.text.trim().slice(0, 300))}</q>` : "";
1243
+ const action = x.detail?.action;
1244
+ const did = operator && x.state === "behavior_adjusted" && action ? `<code class="did">${escapeHtml(actionWords(action.tool, action.input))}</code>` : "";
1245
+ 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>`;
1246
+ })
1247
+ .join("");
1248
+ const waitRow = waiting ? `<li>${glyph("Waiting", DASHED_PATHS)}<span>${escapeHtml(word("queued_at_runtime"))}</span></li>` : "";
1249
+ // What has not happened yet, so the list shows the distance left. A stopped or unknown correction has none.
1250
+ const reached = new Set(delivery.receipts.map((x) => x.state));
1251
+ const named = typeof r.body.expect_next_action === "string";
1252
+ const ahead = isStop(delivery.state) || delivery.state === "unknown"
1253
+ ? ""
1254
+ : ["delivered_to_agent_context", "acknowledged", ...(named ? ["behavior_adjusted"] : [])]
1255
+ .filter((state) => !reached.has(state) && !(notFollowed && state === "behavior_adjusted"))
1256
+ .map((state) => `<li class="ahead">${glyph("Not yet", CIRCLE_PATHS)}<span>${escapeHtml(word(state))}</span></li>`)
1257
+ .join("");
1258
+ const nextActions = operator && delivery.state !== "behavior_adjusted" && delivery.next_actions?.length
1259
+ ? `<h3>What it did next</h3><ol>${delivery.next_actions
1260
+ .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>`)
1261
+ .join("")}</ol>`
1262
+ : "";
1263
+ const stopped = isStop(delivery.state);
1264
+ const now = stopped
1265
+ ? glyph("Stopped", CIRCLE_X_PATHS)
1266
+ : delivery.overdue
1267
+ ? glyph("Waiting longer than it should", TRIANGLE_ALERT_PATHS)
1268
+ : notFollowed
1269
+ ? glyph("Not followed yet", TRIANGLE_ALERT_PATHS)
1270
+ : delivery.state === "unknown"
1271
+ ? glyph("Cannot be told", DASHED_PATHS)
1272
+ : waiting
1273
+ ? glyph("Waiting", DASHED_PATHS)
1274
+ : glyph("Reached", CIRCLE_CHECK_PATHS);
1275
+ 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);
1276
+ const asked = String(r.body.instruction ?? "");
1277
+ const run = r.refs.find((x) => x.startsWith("run_request:") || x.startsWith("work_proposal:"));
1278
+ const token = o.token ?? o.chooserToken;
1279
+ const hidden = token ? `<input type="hidden" name="person_token" value="${escapeHtml(token)}">` : "";
1280
+ const readAt = new Date().toISOString();
1281
+ const again = token
1282
+ ? `<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>`
1283
+ : "";
1284
+ // Signed in, the way there stays signed in: the same form as this page.
1285
+ 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}` : "";
1286
+ 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>`;
1287
+ 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>`;
1288
+ }
1289
+ /** A tool call in the words a person reads: its command when it has one, else its input as recorded. */
1290
+ function actionWords(tool, input) {
1291
+ try {
1292
+ const command = JSON.parse(input ?? "").command;
1293
+ if (typeof command === "string")
1294
+ return command;
1295
+ }
1296
+ catch {
1297
+ // The input was cut to its first 200 characters, or was not JSON: shown as recorded.
1298
+ }
1299
+ return `${tool ?? ""} ${input ?? ""}`.trim();
1300
+ }
1301
+ /** The words for a step already passed, where they differ from the state's own. */
1302
+ const PAST_WORDS = {
1303
+ queued_at_runtime: "In the session's inbox",
1304
+ };
1305
+ const DELIVERY_WORDS = {
1306
+ authorized: "Authorized",
1307
+ forwarded_to_runtime: "Handed to the session's inbox",
1308
+ queued_at_runtime: "Waiting for the agent's next step",
1309
+ runtime_hook_emitted: "The agent's runtime took it",
1310
+ in_model_request: "Held in the request going to the model",
1311
+ delivered_to_agent_context: "The model has it",
1312
+ acknowledged: "The model says it received it",
1313
+ behavior_adjusted: "A later action holds what this correction named",
1314
+ emit_failed: "The agent refused it for now, and it goes back in the inbox",
1315
+ wake_not_submitted: "A line to wake the seat did not go in, and the next pass tries again",
1316
+ left_provider_queue: "The agent's run ended before the model read it",
1317
+ seat_was_idle: "The seat was idle",
1318
+ seat_woken: "The factory runner woke the seat",
1319
+ unsupported: "This session cannot be corrected",
1320
+ expired: "Expired before the model read it",
1321
+ blocked: "Stopped before the model read it",
1322
+ unknown: "Whether the model read it cannot be told",
1323
+ };
1324
+ /** Whether this run could be corrected once it works, as a state with its glyph, before and after it is decided (jgwill/Miadi#942). */
1325
+ function runSteeringLine(r, provider, deps) {
1326
+ if (r.kind !== "run_request" || !provider || !deps.steeringOf)
1327
+ return "";
1328
+ const s = deps.steeringOf(provider);
1329
+ if (!s.steerable)
1330
+ 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>`;
1331
+ 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.");
1332
+ }
1333
+ const receiptBlock = (receipt) => (receipt ? `<details><summary>Receipt</summary><pre>${escapeHtml(JSON.stringify(receipt, null, 2))}</pre></details>` : "");
1163
1334
  function projectionBlock(p, receipt) {
1164
1335
  if (!p)
1165
1336
  return "";
1166
1337
  const lines = p.lines.map((l) => `<li>${escapeHtml(l)}</li>`).join("");
1167
1338
  const review = p.receipt_url ? `<p><a href="${escapeHtml(p.receipt_url)}" rel="noopener">${escapeHtml(p.receipt_url)}</a></p>` : "";
1168
- const audit = receipt ? `<details><summary>Receipt</summary><pre>${escapeHtml(JSON.stringify(receipt, null, 2))}</pre></details>` : "";
1339
+ const audit = receiptBlock(receipt);
1169
1340
  return `<section aria-label="Where it stands"><p><strong>${escapeHtml(p.label)}</strong></p>${lines ? `<ul>${lines}</ul>` : ""}${review}${audit}</section>`;
1170
1341
  }
1171
1342
  const SETTLER_WORDS = {
@@ -1174,6 +1345,15 @@ const SETTLER_WORDS = {
1174
1345
  bystander: "Only the person deciding can answer this, in their instructions.",
1175
1346
  local_agent: "A local agent can settle this from the running system.",
1176
1347
  };
1348
+ 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"/>`;
1349
+ 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>`;
1350
+ 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"/>`);
1351
+ const ARROW_UP_RIGHT_ICON = svgIcon(`<path d="M7 7h10v10"/><path d="M7 17 17 7"/>`);
1352
+ 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"/>`);
1353
+ const CIRCLE_PATHS = `<circle cx="12" cy="12" r="10"/>`;
1354
+ const TERMINAL_PATHS = `<path d="M12 19h8"/><path d="m4 17 6-6-6-6"/>`;
1355
+ const CIRCLE_CHECK_PATHS = `<circle cx="12" cy="12" r="10"/><path d="m9 12 2 2 4-4"/>`;
1356
+ const CIRCLE_X_PATHS = `<circle cx="12" cy="12" r="10"/><path d="m15 9-6 6"/><path d="m9 9 6 6"/>`;
1177
1357
  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"/>`;
1178
1358
  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"/>`;
1179
1359
  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>`;
@@ -1233,10 +1413,16 @@ function approvePage(deps, r, o = {}) {
1233
1413
  // Signed in and able to decide: the decision comes before the record's details, and no line says it waits for someone else.
1234
1414
  const asksSomeone = r.kind === "participant_consent_request";
1235
1415
  const canDecideHere = Boolean(actionable && o.token && !asksSomeone);
1236
- const heading = canDecideHere ? "Not approved yet: decide here" : open ? "A request awaiting a decision" : (projectionOf(r, deps)?.label ?? "A decided request");
1416
+ // 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.
1417
+ const steerDecided = !open && r.kind === "session_steer_request" && Boolean(deps.steeringRuntime && readSteerDelivery(deps.steeringRuntime, r));
1418
+ 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");
1237
1419
  const details = canDecideHere
1238
1420
  ? `<details><summary>What exactly is asked</summary>${summary(r, { intention: false })}</details>`
1239
- : `${summary(r)}
1421
+ : steerDecided
1422
+ ? `${deliveryBlock(r, deps, o)}
1423
+ <details><summary>What exactly was sent</summary>${summary(r)}</details>
1424
+ ${receiptBlock(r.completion_receipt)}`
1425
+ : `${summary(r)}
1240
1426
  ${open ? draftReviewSection(r, deps.draftReview?.stored(r), false) : ""}
1241
1427
  ${projectionBlock(projectionOf(r, deps), open ? undefined : r.completion_receipt)}`;
1242
1428
  return page("Approve a Miadi request", `<h1>${escapeHtml(heading)}</h1>
@@ -1244,6 +1430,7 @@ ${canDecideHere ? `<p>You are signed in. Nothing is approved until you press a b
1244
1430
  ${asksSomeone && open && o.token && deps.consentLink ? consentMailSection(r, deps) : ""}
1245
1431
  ${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>` : ""}
1246
1432
  ${actionable ? `<p>${escapeHtml(consequenceOf(r, authorization, current(deps.ledger.all())))} Declining records your refusal. Either is kept in the ledger with your name.</p>` : ""}
1433
+ ${runSteeringLine(r, authorization?.provider ?? undefined, deps)}
1247
1434
  ${canDecideHere && r.intention ? `<p><strong>Intention:</strong> ${escapeHtml(r.intention)}</p>` : ""}
1248
1435
  ${authorization ? providerSection(r, authorization, actionable ? o.chooserToken : undefined) : ""}
1249
1436
  ${canDecideHere ? draftReviewSection(r, deps.draftReview?.stored(r), !blocked) : ""}
@@ -1309,6 +1496,7 @@ export function registerProviderPolicyRoutes(app, deps) {
1309
1496
  ${error ? `<p class="err" role="alert">${escapeHtml(error)}</p>` : ""}
1310
1497
  <form method="post"><label for="t">Your Miadi person token</label><input id="t" name="person_token" type="password" autocomplete="off" required>
1311
1498
  <div class="row"><button class="primary" type="submit">Read my policy</button></div></form>`);
1499
+ const policyOfPerson = (personId) => providerPolicyOf(deps.ledger.all(), personId, readFactoryConfig(deps.factoryDir ?? factoryDir())?.person_default_provider);
1312
1500
  app.get("/providers", (_req, res) => void res.type("html").send(signIn()));
1313
1501
  app.post("/providers", form, async (req, res) => {
1314
1502
  const body = (req.body ?? {});
@@ -1330,7 +1518,13 @@ ${error ? `<p class="err" role="alert">${escapeHtml(error)}</p>` : ""}
1330
1518
  if (body.codex !== undefined) {
1331
1519
  if (!CODEX_POLICIES.includes(body.codex))
1332
1520
  return void res.status(400).type("html").send(signIn("Unknown Codex policy."));
1333
- if (providerPolicyOf(deps.ledger.all(), person.id).codex !== body.codex) {
1521
+ if (body.default_provider && !["claude", "pi", "copilot", HOST_ORDER].includes(body.default_provider))
1522
+ return void res.status(400).type("html").send(signIn("Unknown default provider."));
1523
+ const before = policyOfPerson(person.id);
1524
+ const wanted = body.default_provider ?? "";
1525
+ const had = before.default_provider ?? HOST_ORDER;
1526
+ const changed = before.codex !== body.codex || Boolean(wanted && had !== wanted);
1527
+ if (changed) {
1334
1528
  deps.ledger.append({
1335
1529
  id: newRecordId("provider_policy"),
1336
1530
  kind: "provider_policy",
@@ -1339,22 +1533,31 @@ ${error ? `<p class="err" role="alert">${escapeHtml(error)}</p>` : ""}
1339
1533
  refs: [],
1340
1534
  evidence_refs: [],
1341
1535
  claim_category: "observed",
1342
- body: { codex: body.codex },
1536
+ body: { codex: body.codex, ...(wanted ? { default_provider: wanted } : {}) },
1343
1537
  });
1344
- logDecision(deps, { phase: "provider_policy_set", person: person.id, codex: body.codex });
1538
+ logDecision(deps, { phase: "provider_policy_set", person: person.id, codex: body.codex, ...(wanted ? { default_provider: wanted } : {}) });
1345
1539
  }
1346
- 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>";
1540
+ 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>";
1347
1541
  }
1348
- const policy = providerPolicyOf(deps.ledger.all(), person.id);
1542
+ const policy = policyOfPerson(person.id);
1349
1543
  const option = (value, label) => `<label><input type="radio" name="codex" value="${value}"${policy.codex === value ? " checked" : ""}> ${escapeHtml(label)}</label>`;
1544
+ const providerWord = (id) => (id === "claude" ? "Claude Code" : id === "copilot" ? "Copilot" : id === "pi" ? "Pi" : String(id ?? ""));
1545
+ const defaultOption = (value, label) => `<label><input type="radio" name="default_provider" value="${value}"${(policy.default_provider ?? HOST_ORDER) === value ? " checked" : ""}> ${escapeHtml(label)}</label>`;
1350
1546
  res.type("html").send(page("Your provider policy", `<h1>${escapeHtml(person.name)}'s provider policy</h1>${saved}
1351
1547
  <dl><dt>Codex</dt><dd>${escapeHtml(policy.codex.replace(/_/g, " "))}${policy.source === "default" ? " (the default)" : `, set ${escapeHtml(policy.set_at ?? "")}`}</dd>
1352
- <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>
1548
+ <dt>Other providers</dt><dd>Pi, Copilot and Claude Code run when a request names them and they are installed.</dd></dl>
1353
1549
  <form method="post"><input type="hidden" name="person_token" value="${escapeHtml(token)}">
1354
1550
  <fieldset><legend>When a request in my name names Codex</legend>
1355
1551
  ${option("per_mission_choice", "Codex runs only when I choose it for that mission on its approval page (default).")}
1356
1552
  ${option("selectable", "Codex may be named for my requests without a per-mission choice.")}
1357
1553
  </fieldset>
1554
+ <fieldset class="provider-defaults"><legend>When a request in my name names no provider</legend>
1555
+ ${defaultOption(HOST_ORDER, "The Factory's default, which is Claude Code today")}
1556
+ ${defaultOption("pi", "Pi")}
1557
+ ${defaultOption("copilot", "Copilot")}
1558
+ ${defaultOption("claude", "Claude Code")}
1559
+ ${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>` : ""}
1560
+ </fieldset>
1358
1561
  <div class="row"><button class="primary" type="submit">Save my policy</button></div></form>`));
1359
1562
  });
1360
1563
  }
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
  });
@@ -0,0 +1,95 @@
1
+ import { type Criticality, type JevAdapter, type ModelCandidate, type TaskType } from "./model-preflight.js";
2
+ import { type DiscoveryProbe, type ProviderAvailability, type ProviderId } from "./providers.js";
3
+ import type { ConnectorRecord } from "./records.js";
4
+ export declare const MODEL_ROUTING_CONTRACT = "miadi.claude_model_routing";
5
+ /** The body mark of a request whose model Jev chooses when its brief is written. */
6
+ export declare const JEV_WITHIN_CLAUDE = "jev_within_claude";
7
+ /** Typed into a shell by the factory runner, so one plain word. The runner checks it again. */
8
+ export declare const MODEL_NAME: RegExp;
9
+ export interface ClaudeModel {
10
+ id: string;
11
+ /** What the alias named when it was checked; the runner's receipt says what it names now. */
12
+ resolves_to: string;
13
+ /** What Jev reads: which task this model fits. The Factory's reading of Anthropic's model descriptions, not a measurement. */
14
+ capability_note: string;
15
+ }
16
+ /** Each answered a real prompt under `--model <id>` and under its full name. */
17
+ export declare const CLAUDE_MODELS: readonly ClaudeModel[];
18
+ /** A run under one name proves that name on that host that day, and says nothing of a sign-in elsewhere. */
19
+ export declare const CLAUDE_MODELS_VERIFIED: {
20
+ on: string;
21
+ cli: string;
22
+ how: string;
23
+ };
24
+ export interface ClaudeModelConfig {
25
+ /** The names a request may use and Jev may choose among (factory.json claudeModels; default: CLAUDE_MODELS), always with the fallback. */
26
+ permitted: string[];
27
+ /** The fallback: factory.json claudeDefaultModel, else Claude Code's own setting when the list allows it, else the first listed, else none. */
28
+ configured: string | null;
29
+ }
30
+ export declare function claudeModelConfig(dir?: string, modelOf?: (p: ProviderId) => string | null): ClaudeModelConfig;
31
+ /** A permitted name, or the full name of a permitted alias. */
32
+ export declare function isPermittedModel(model: string, permitted: string[]): boolean;
33
+ export type ModelPlan = {
34
+ fields: Record<string, string>;
35
+ } | {
36
+ refusal: {
37
+ code: "model_provider_mismatch" | "model_not_permitted";
38
+ message: string;
39
+ permitted: string[];
40
+ };
41
+ };
42
+ /** What a request records about its model, or why it may not be recorded. */
43
+ export declare function modelPlan(provider: string | null | undefined, model: string | null | undefined, permitted: string[]): ModelPlan;
44
+ /** One candidate per permitted model, the configured one first: Jev's options, and the preflight's. */
45
+ export declare function claudeModelCandidates(found: ProviderAvailability[], config: ClaudeModelConfig, base?: Pick<ModelCandidate, "eligible" | "policy_reason">): ModelCandidate[];
46
+ export type ModelSource = "request" | "jev" | "configured_fallback" | "cli_default" | "existing_session" | "unavailable";
47
+ export interface ModelRouting {
48
+ contract: typeof MODEL_ROUTING_CONTRACT;
49
+ version: 1;
50
+ decided_for: {
51
+ record: string;
52
+ version: number;
53
+ };
54
+ provider: "claude";
55
+ /** What the launch passes as --model. null: no flag, Claude Code's own default. */
56
+ model: string | null;
57
+ /** request: the request named it. configured_fallback and cli_default: Jev did not choose, and fallback_reasons says why. existing_session: the session keeps its model. unavailable: nothing launches, and why says so. */
58
+ source: ModelSource;
59
+ why?: string;
60
+ fallback_reasons?: string[];
61
+ task?: {
62
+ type: TaskType;
63
+ criticality: Criticality;
64
+ };
65
+ eligible?: string[];
66
+ decider?: Record<string, unknown>;
67
+ authorizes: false;
68
+ }
69
+ export interface ModelRoutingDeps {
70
+ /** A decider for tests. Absent, the environment's Jev key decides. */
71
+ adapter?: JevAdapter;
72
+ env?: NodeJS.ProcessEnv;
73
+ fetchImpl?: typeof fetch;
74
+ providersProbe?: DiscoveryProbe;
75
+ modelOf?: (p: ProviderId) => string | null;
76
+ factoryDir?: string;
77
+ }
78
+ /**
79
+ * The model of one mission's launch, or null when this mission's model is not routed: another
80
+ * provider, or a request recorded before routing. Asked at most once for a version: a brief written
81
+ * again for it (a rerun) keeps the answer, because a lost answer may already have been charged.
82
+ */
83
+ export declare function routeModel(record: ConnectorRecord, opts: {
84
+ existingSession: boolean;
85
+ }, deps?: ModelRoutingDeps): Promise<ModelRouting | null>;
86
+ /** What the brief carries. */
87
+ export declare function modelAttributes(routing: ModelRouting | null): Record<string, string>;
88
+ /**
89
+ * The model that first answered in a session's own transcript, or null when none has yet. A launched
90
+ * session's id is its own, so anything answering in it is this launch. "<synthetic>" is Claude Code's
91
+ * own line, and a sidechain is a subagent: neither is the session's model.
92
+ */
93
+ export declare function firstModelInTranscript(path: string): string | null;
94
+ /** Whether a model answered under a name: the name itself, or the alias of its family (opus answers as claude-opus-5-5). */
95
+ export declare function modelMatches(requested: string, observed: string): boolean;