@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.
@@ -1,27 +1,27 @@
1
1
  /**
2
- * The connector's half of the terminal-agent steering contract (jgwill/Miadi#930).
2
+ * The connector's half of the terminal-agent steering contract (jgwill/Miadi#930, #942; STEERING.md).
3
3
  *
4
4
  * The connector admits a correction and hands it to the bound session's own inbox. It never
5
5
  * watches tools, never waits for idle and never decides when the model reads it: that is the
6
- * runtime's. For Claude Code the runtime half is the hook adapter in the kit plugin
7
- * miadi-session-observability (hooks/steering_inbox.mjs), which holds the file contract:
6
+ * runtime's. Each provider's adapter (jgwill/miadi-orchestration-kit) reads the same file contract:
8
7
  * <root>/<session_id>/{adapter.json,pending,claimed,expired,withdrawn,rejected,revoked,receipts.jsonl}.
8
+ * steering-adapters.ts holds which providers have one and what each was shown to do. A provider with
9
+ * none answers unsupported with the exact reason, and one provider's semantics are never assumed of another.
9
10
  *
10
- * Other providers have no adapter here, so they answer unsupported with the exact reason. Claude
11
- * Code's hook semantics are never assumed of Copilot, Pi or Codex.
12
- *
13
- * Delivery is read from its own evidence: the connector's write, the runtime hook's receipt and
14
- * the transcript record Claude Code itself wrote. A pane echo or a spinner is none of these.
11
+ * Delivery is read from its own evidence: the connector's write, the adapter's receipt and the record
12
+ * the agent itself wrote. A pane echo or a spinner is none of these.
15
13
  */
16
14
  import { createHash } from "node:crypto";
17
15
  import { appendFileSync, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, renameSync, statSync, writeFileSync, writeSync } from "node:fs";
18
16
  import { homedir } from "node:os";
19
17
  import { join } from "node:path";
20
18
  import { factoryDir } from "./queue-state.js";
19
+ import { ADAPTERS, adapterOf, adapterOfRoute, isInboxRoute } from "./steering-adapters.js";
21
20
  export const STEER_PROTOCOL = 1;
22
21
  /** A correction no continuation consumed in a day is stale: the work has moved on. A grant's own expiry comes sooner when it has one. */
23
22
  export const ENVELOPE_TTL_MS = 24 * 60 * 60 * 1000;
24
23
  export const CLAUDE_ADAPTER = "miadi-session-observability 0.1.34 or later";
24
+ export { STEERING_CONTRACT_ID } from "./steering-adapters.js";
25
25
  const INBOX_DIRS = ["pending", "claimed", "expired", "withdrawn", "rejected"];
26
26
  /** How much transcript one read scans after the steer was queued. */
27
27
  const MAX_TRANSCRIPT_SCAN = 32 * 1024 * 1024;
@@ -91,16 +91,96 @@ export function readClaudeSession(deps, sessionId) {
91
91
  }
92
92
  return null;
93
93
  }
94
+ const defaultAlive = (pid) => {
95
+ try {
96
+ process.kill(pid, 0);
97
+ return true;
98
+ }
99
+ catch {
100
+ return false;
101
+ }
102
+ };
103
+ /** A session's inbox folder and its adapter's file, only if this Unix account alone owns them. */
104
+ function ownedAdapter(deps, sessionId) {
105
+ const dir = join(deps.root, safe(sessionId));
106
+ const st = statOrNull(dir);
107
+ if (!st?.isDirectory() || st.uid !== process.getuid?.() || (st.mode & 0o022) !== 0)
108
+ return null;
109
+ const adapter = readJson(join(dir, "adapter.json"));
110
+ return adapter && adapter.protocol === STEER_PROTOCOL && adapter.session_id === sessionId ? adapter : null;
111
+ }
112
+ /** Every living adapter that says it runs in this pane of this tmux server. Exactly one is an address; none or two are not. */
113
+ function adaptersInPane(deps, pane, socket) {
114
+ const alive = deps.isAlive ?? defaultAlive;
115
+ let names;
116
+ try {
117
+ names = readdirSync(deps.root);
118
+ }
119
+ catch {
120
+ return [];
121
+ }
122
+ const out = [];
123
+ for (const name of names) {
124
+ const adapter = ownedAdapter(deps, name);
125
+ // A pane number is unique only within its server, and a host runs several (jgwill/Miadi#942).
126
+ if (adapter?.pane === pane && typeof adapter.pid === "number" && alive(adapter.pid) && (!socket || adapter.tmux_socket === socket))
127
+ out.push(adapter);
128
+ }
129
+ return out;
130
+ }
131
+ /** A provider with no registry of its own: its adapter's file says who it is, and its pid and pane are checked. */
132
+ function resolveAdapterSession(deps, binding, spec) {
133
+ const alive = deps.isAlive ?? defaultAlive;
134
+ const { session_id, pane_id, socket } = binding;
135
+ const notLoaded = `The ${spec.name} session${pane_id ? ` in pane ${pane_id}` : ""} has no steering adapter loaded. Adapters load when a session starts, so one started before ${spec.adapter} ${spec.min_adapter_version} cannot be steered. A session started now can.`;
136
+ let adapter;
137
+ if (session_id) {
138
+ adapter = ownedAdapter(deps, session_id);
139
+ if (!adapter)
140
+ return { route: "none", code: "unsupported", reason: notLoaded };
141
+ }
142
+ else {
143
+ if (!pane_id)
144
+ return { route: "none", code: "unsupported", reason: "The mission's binding names neither a session id nor a pane, so no exact session's inbox can be addressed." };
145
+ const here = adaptersInPane(deps, pane_id, socket);
146
+ if (!here.length)
147
+ return { route: "none", code: "unsupported", reason: notLoaded };
148
+ if (here.length > 1)
149
+ return { route: "none", code: "wrong_pane", reason: `${here.length} sessions claim pane ${pane_id}, so which one the mission means cannot be told.` };
150
+ adapter = here[0];
151
+ }
152
+ if (adapter.provider !== spec.provider)
153
+ return { route: "none", code: "wrong_pane", reason: `The session in pane ${pane_id ?? "(unnamed)"} is ${adapter.provider}, and this mission is bound to ${spec.provider}.` };
154
+ if (typeof adapter.pid !== "number" || !alive(adapter.pid))
155
+ return { route: "none", code: "stale_binding", reason: `${spec.name} session ${adapter.session_id} is not running on this host.` };
156
+ if (pane_id && adapter.pane && adapter.pane !== pane_id)
157
+ return { route: "none", code: "wrong_pane", reason: `${spec.name} session ${adapter.session_id} is in pane ${adapter.pane}, not ${pane_id}, the pane its mission is bound to.` };
158
+ if (socket && adapter.tmux_socket && adapter.tmux_socket !== socket)
159
+ return { route: "none", code: "wrong_pane", reason: `${spec.name} session ${adapter.session_id} runs on another tmux server, not the one its mission is bound to.` };
160
+ const seat = readJson(join(deps.root, safe(adapter.session_id), "seat.json"));
161
+ return {
162
+ route: spec.route,
163
+ provider: spec.provider,
164
+ session_id: adapter.session_id,
165
+ seat: typeof seat?.status === "string" ? seat.status : "unknown",
166
+ self_wakes: spec.self_wakes,
167
+ ...(typeof adapter.transcript_path === "string" ? { transcript_path: adapter.transcript_path } : {}),
168
+ ...(typeof adapter.adapter_version === "string" ? { adapter_version: adapter.adapter_version } : {}),
169
+ };
170
+ }
94
171
  /**
95
- * Mission → session → runtime, from what each one signed: the runner's receipt names the session,
96
- * Claude Code's registry says it runs and in which pane, and the adapter's file says this session
97
- * loaded its hooks. The inbox belongs to this Unix account alone or it is not used.
172
+ * Mission → session → runtime, from what each one signed: the runner's receipt names the session and
173
+ * pane, the agent's own record says it runs there, and the adapter's file says this session loaded
174
+ * its adapter. The inbox belongs to this Unix account alone or it is not used.
98
175
  */
99
176
  export function resolveRuntime(deps, binding) {
100
177
  const { session_id, pane_id, provider } = binding;
101
- if (provider && provider !== "claude") {
102
- return { route: "none", code: "unsupported", reason: `No steering adapter is installed for provider "${provider}". Claude Code's hooks are not assumed of it.` };
178
+ const spec = provider ? adapterOf(provider) : ADAPTERS.claude;
179
+ if (provider && !spec) {
180
+ return { route: "none", code: "unsupported", reason: `No steering adapter exists for provider "${provider}". Another provider's hooks are not assumed of it.` };
103
181
  }
182
+ if (provider && provider !== "claude")
183
+ return resolveAdapterSession(deps, binding, spec);
104
184
  if (!session_id)
105
185
  return { route: "none", code: "unsupported", reason: "The mission's binding names no session id, so no exact session's inbox can be addressed." };
106
186
  const record = readClaudeSession(deps, session_id);
@@ -110,17 +190,23 @@ export function resolveRuntime(deps, binding) {
110
190
  if (pane_id && seatPane && seatPane !== pane_id) {
111
191
  return { route: "none", code: "wrong_pane", reason: `Claude Code session ${session_id} is in pane ${seatPane}, not ${pane_id}, the pane its mission is bound to.` };
112
192
  }
113
- const dir = join(deps.root, safe(session_id));
114
- const st = statOrNull(dir);
115
- const adapter = st?.isDirectory() && st.uid === process.getuid?.() && (st.mode & 0o022) === 0 ? readJson(join(dir, "adapter.json")) : null;
116
- if (!adapter || adapter.protocol !== STEER_PROTOCOL || adapter.session_id !== session_id) {
193
+ const adapter = ownedAdapter(deps, session_id);
194
+ if (!adapter) {
117
195
  return {
118
196
  route: "none",
119
197
  code: "unsupported",
120
198
  reason: `Claude Code session ${session_id} has no steering adapter loaded. Hooks load at session start, so a session started before ${CLAUDE_ADAPTER} cannot receive a correction mid-turn.`,
121
199
  };
122
200
  }
123
- return { route: "claude_hook_inbox", session_id, seat: record.status ?? "unknown", ...(typeof adapter.transcript_path === "string" ? { transcript_path: adapter.transcript_path } : {}) };
201
+ return {
202
+ route: "claude_hook_inbox",
203
+ provider: "claude",
204
+ session_id,
205
+ seat: record.status ?? "unknown",
206
+ self_wakes: false,
207
+ ...(typeof adapter.transcript_path === "string" ? { transcript_path: adapter.transcript_path } : {}),
208
+ ...(typeof adapter.adapter_version === "string" ? { adapter_version: adapter.adapter_version } : {}),
209
+ };
124
210
  }
125
211
  function findEnvelope(root, sessionId, steer) {
126
212
  const dir = join(root, safe(sessionId));
@@ -184,6 +270,7 @@ export function enqueueSteer(deps, args) {
184
270
  queued_at: now.toISOString(),
185
271
  expires_at: new Date(Number.isNaN(grantEnd) ? ttl : Math.min(ttl, grantEnd)).toISOString(),
186
272
  ...(args.decided ? { decided: true } : {}),
273
+ ...(args.provider ? { provider: args.provider } : {}),
187
274
  ...(args.transcript_path ? { transcript_path: args.transcript_path, transcript_offset: transcriptSize(args.transcript_path) } : {}),
188
275
  };
189
276
  // Ordered by name: never before an envelope already waiting.
@@ -345,6 +432,99 @@ export function readTranscriptEvidence(path, offset, steer) {
345
432
  }
346
433
  return out;
347
434
  }
435
+ const blockText = (content) => {
436
+ if (typeof content === "string")
437
+ return content;
438
+ if (!Array.isArray(content))
439
+ return "";
440
+ return content.map((b) => (b && typeof b === "object" && typeof b.text === "string" ? b.text : "")).join("\n");
441
+ };
442
+ /**
443
+ * The record each provider writes, read from real sessions of it (jgwill/Miadi#942). A role a person
444
+ * or the runtime speaks in counts as given to the model. A tool's output quoting the words never does.
445
+ */
446
+ const LINE_READERS = {
447
+ // ~/.pi/agent/sessions/.../<id>.jsonl
448
+ pi: (d) => {
449
+ if (d.type !== "message")
450
+ return null;
451
+ const m = d.message ?? {};
452
+ if (m.role === "user")
453
+ return { kind: "input", at: d.timestamp, text: blockText(m.content), tools: [], record: "user_message" };
454
+ if (m.role !== "assistant")
455
+ return null;
456
+ const blocks = Array.isArray(m.content) ? m.content : [];
457
+ return { kind: "assistant", at: d.timestamp, text: blockText(blocks), tools: blocks.filter((b) => b?.type === "toolCall").map((b) => ({ name: String(b.name), input: b.arguments ?? {} })), record: "assistant_message" };
458
+ },
459
+ // ~/.copilot/session-state/<id>/events.jsonl
460
+ copilot: (d) => {
461
+ const data = d.data ?? {};
462
+ if (d.type === "user.message")
463
+ return { kind: "input", at: d.timestamp, text: String(data.content ?? ""), tools: [], record: "user.message" };
464
+ if (d.type !== "assistant.message")
465
+ return null;
466
+ return { kind: "assistant", at: d.timestamp, text: String(data.content ?? ""), tools: (Array.isArray(data.toolRequests) ? data.toolRequests : []).map((t) => ({ name: String(t.name), input: t.arguments ?? {} })), record: "assistant.message" };
467
+ },
468
+ // ~/.codex/sessions/.../rollout-*.jsonl
469
+ codex: (d) => {
470
+ if (d.type !== "response_item")
471
+ return null;
472
+ const p = d.payload ?? {};
473
+ if (p.type === "message" && (p.role === "developer" || p.role === "user"))
474
+ return { kind: "input", at: d.timestamp, text: blockText(p.content), tools: [], record: `${p.role}_message` };
475
+ if (p.type === "message" && p.role === "assistant")
476
+ return { kind: "assistant", at: d.timestamp, text: blockText(p.content), tools: [], record: "assistant_message" };
477
+ if (p.type === "function_call" || p.type === "custom_tool_call" || p.type === "local_shell_call") {
478
+ return { kind: "assistant", at: d.timestamp, text: "", tools: [{ name: String(p.name ?? p.type), input: p.arguments ?? p.input ?? p.action ?? {} }], record: p.type };
479
+ }
480
+ return null;
481
+ },
482
+ };
483
+ /** What a provider other than Claude Code recorded about this steer, by the same rule as readTranscriptEvidence. */
484
+ export function readAgentEvidence(provider, path, offset, steer) {
485
+ if (provider === "claude")
486
+ return readTranscriptEvidence(path, offset, steer);
487
+ const out = { next_actions: [], actions_seen: 0, raw_inputs: [] };
488
+ const text = readTail(path, offset);
489
+ if (text === null)
490
+ return out;
491
+ const token = `${ackToken(steer)} received`.toLowerCase();
492
+ const reader = LINE_READERS[provider];
493
+ for (const line of text.split("\n")) {
494
+ if (!line.trim())
495
+ continue;
496
+ if (!out.delivered && !line.includes(steer))
497
+ continue;
498
+ let d;
499
+ try {
500
+ d = JSON.parse(line);
501
+ }
502
+ catch {
503
+ continue;
504
+ }
505
+ const seen = reader(d);
506
+ if (!seen)
507
+ continue;
508
+ if (!out.delivered) {
509
+ if (seen.kind === "input" && seen.text.includes(steer))
510
+ out.delivered = { at: seen.at, attachment: seen.record, hook_event: adapterOf(provider).route };
511
+ continue;
512
+ }
513
+ if (seen.kind !== "assistant")
514
+ continue;
515
+ if (!out.acknowledged && seen.text.toLowerCase().includes(token))
516
+ out.acknowledged = { at: seen.at, text: seen.text.slice(0, 500) };
517
+ for (const tool of seen.tools) {
518
+ out.actions_seen++;
519
+ const input = typeof tool.input === "string" ? tool.input : JSON.stringify(tool.input ?? {});
520
+ if (out.next_actions.length < MAX_NEXT_ACTIONS) {
521
+ out.next_actions.push({ at: seen.at, tool: tool.name, input: input.slice(0, 200) });
522
+ out.raw_inputs.push(input);
523
+ }
524
+ }
525
+ }
526
+ return out;
527
+ }
348
528
  /** Whether a prompt typed into the bound pane reached the session: Claude Code's own user or queued-prompt record. A pane echo proves nothing. */
349
529
  export function typedLineInTranscript(path, offset, instruction) {
350
530
  const text = readTail(path, offset);
@@ -400,11 +580,13 @@ export function readSteerDelivery(deps, record, now = new Date()) {
400
580
  return null;
401
581
  const binding = record.body.binding;
402
582
  const route = String(receipt.route ?? (receipt.typed ? "tmux_exact_pane" : "none"));
403
- const session_id = binding?.session_id;
583
+ // A session the runner could not name was found by its pane: the connector kept which one it reached.
584
+ const session_id = binding?.session_id ?? (typeof receipt.runtime_session_id === "string" ? receipt.runtime_session_id : undefined);
404
585
  const receipts = [];
405
586
  const authorizedAt = receipt.decided_at;
406
587
  receipts.push({ state: "authorized", at: authorizedAt, source: "connector", detail: { by: receipt.decided_by, decision: receipt.decision } });
407
- const base = { route, ...(session_id ? { session_id } : {}) };
588
+ const spec = adapterOfRoute(route);
589
+ const base = { route, ...(spec ? { provider: spec.provider } : {}), ...(session_id ? { session_id } : {}) };
408
590
  if (route === "tmux_exact_pane") {
409
591
  receipts.push({ state: "seat_was_idle", at: authorizedAt, source: "connector", detail: { target: receipt.target } });
410
592
  receipts.push({ state: "forwarded_to_runtime", at: authorizedAt, source: "connector", detail: { target: receipt.target, typed: receipt.typed } });
@@ -416,9 +598,10 @@ export function readSteerDelivery(deps, record, now = new Date()) {
416
598
  }
417
599
  return { ...base, state: "unknown", receipts, note: "It was typed into the bound pane of an idle seat. No transcript record of it has been read, and a pane echo is not proof the model read it." };
418
600
  }
419
- if (route !== "claude_hook_inbox" || !session_id) {
601
+ if (!isInboxRoute(route) || !session_id || !spec) {
420
602
  const status = String(receipt.steer_status ?? "");
421
603
  const state = status === "unsupported" ? "unsupported" : status === "expired_grant" ? "expired" : "blocked";
604
+ receipts.push({ state, at: authorizedAt, source: "connector" });
422
605
  return { ...base, state, receipts, note: String(receipt.message ?? "Nothing was forwarded.") };
423
606
  }
424
607
  const found = findEnvelope(deps.root, session_id, record.id);
@@ -428,11 +611,24 @@ export function readSteerDelivery(deps, record, now = new Date()) {
428
611
  return { ...base, state: "unknown", receipts, note: "The session's inbox no longer holds this steer, so where it went cannot be read." };
429
612
  receipts.push({ state: "queued_at_runtime", at: forwardedAt, source: "runtime_inbox", detail: { file: found.file, expires_at: found.envelope?.expires_at } });
430
613
  const hook = hookReceipts(deps.root, session_id, record.id);
614
+ // Everything the adapter and the runner recorded, whatever state it stands in now.
431
615
  for (const r of hook) {
432
616
  if (r.state === "emitted") {
433
617
  const { at, state: _state, source: _source, steer: _steer, ...detail } = r;
434
618
  receipts.push({ state: "runtime_hook_emitted", at, source: "runtime_hook", detail });
435
619
  }
620
+ else if (r.state === "woken") {
621
+ receipts.push({ state: "seat_woken", at: r.at, source: "factory_runner", detail: { pane: r.pane, via: r.via } });
622
+ }
623
+ else if (r.state === "wake_not_submitted") {
624
+ receipts.push({ state: "wake_not_submitted", at: r.at, source: "factory_runner", detail: { pane: r.pane, via: r.via } });
625
+ }
626
+ else if (r.state === "emit_failed") {
627
+ receipts.push({ state: "emit_failed", at: r.at, source: "runtime_hook", detail: { reason: r.reason, returned: r.returned } });
628
+ }
629
+ else if (r.state === "left_provider_queue") {
630
+ receipts.push({ state: "left_provider_queue", at: r.at, source: "runtime_hook", detail: { reason: r.reason } });
631
+ }
436
632
  }
437
633
  const refused = hook.find((r) => r.state === "expired" || r.state === "revoked" || r.state === "blocked");
438
634
  if (found.state === "pending") {
@@ -441,14 +637,25 @@ export function readSteerDelivery(deps, record, now = new Date()) {
441
637
  receipts.push({ state: "expired", at: expiresAt, source: "connector_clock" });
442
638
  return { ...base, state: "expired", receipts, note: "It expired in the inbox before any continuation consumed it. It will not reach the model." };
443
639
  }
444
- const seat = readClaudeSession(deps, session_id);
445
- for (const r of hook.filter((x) => x.state === "woken"))
446
- receipts.push({ state: "seat_woken", at: r.at, source: "factory_runner", detail: { pane: r.pane } });
447
- if (!seat)
640
+ const running = sessionRunning(deps, spec.provider, session_id);
641
+ if (!running.alive)
448
642
  return { ...base, state: "queued_at_runtime", continuation: "session_not_running", receipts, note: `It waits in the inbox of a session that is not running. It reaches the model if that session resumes before ${expiresAt}, and otherwise expires.` };
449
- if (seat.status === "idle")
643
+ const when = (at) => (at ? `${at.slice(0, 19).replace("T", " ")} UTC` : "");
644
+ const waitedMs = forwardedAt ? now.getTime() - Date.parse(forwardedAt) : 0;
645
+ if (running.status === "idle" && !spec.self_wakes) {
646
+ const failedWake = hook.some((x) => x.state === "wake_not_submitted");
647
+ // The runner's timer passes every five minutes, so three passes without a wake is late.
648
+ if (failedWake || waitedMs > 15 * 60_000)
649
+ return { ...base, state: "queued_at_runtime", continuation: "runner_wakes_idle_seat", overdue: true, receipts, note: `The seat is idle and has not been woken since ${when(forwardedAt)}. The factory runner tries again on each pass, every five minutes, until it expires at ${when(expiresAt)}.` };
450
650
  return { ...base, state: "queued_at_runtime", continuation: "runner_wakes_idle_seat", receipts, note: "The seat went idle before a continuation carried it. The factory runner's next pass, within minutes, prompts the seat, and the correction arrives with that prompt. Nobody has to send it again." };
451
- return { ...base, state: "queued_at_runtime", continuation: "next_tool_or_turn_end", receipts, note: "It waits in the session's inbox. The agent's next tool end, or the end of its turn, presents it. This does not yet show the model read it." };
651
+ }
652
+ const refusedDoor = hook.filter((x) => x.state === "emit_failed").at(-1);
653
+ if (refusedDoor)
654
+ return { ...base, state: "queued_at_runtime", continuation: "next_tool_or_turn_end", overdue: true, receipts, note: `${spec.name} refused the hand-off (${refusedDoor.reason}), so it went back in the inbox and is tried again every ten seconds until it expires at ${when(expiresAt)}.` };
655
+ // An adapter takes it within a second or two. Longer than a minute, it did not, and saying "soon" would be false.
656
+ if (spec.self_wakes && waitedMs > 60_000)
657
+ return { ...base, state: "queued_at_runtime", continuation: "next_tool_or_turn_end", overdue: true, receipts, note: `It has waited since ${when(forwardedAt)}, longer than ${spec.name} should take. The session runs, and has not taken it. It expires at ${when(expiresAt)}.` };
658
+ return { ...base, state: "queued_at_runtime", continuation: "next_tool_or_turn_end", receipts, note: spec.self_wakes ? `It waits in the session's inbox. ${spec.name} takes it within a second or two, and it reaches the model at the agent's next step. This does not yet show the model read it.` : "It waits in the session's inbox. The agent's next tool end, or the end of its turn, presents it. This does not yet show the model read it." };
452
659
  }
453
660
  if (found.state === "expired") {
454
661
  receipts.push({ state: "expired", at: refused?.at, source: "runtime_hook", detail: { reason: refused?.reason } });
@@ -459,24 +666,36 @@ export function readSteerDelivery(deps, record, now = new Date()) {
459
666
  return { ...base, state: "blocked", receipts, note: `It never reached the model: ${refused?.reason ?? found.state}.` };
460
667
  }
461
668
  // Claimed: taken for delivery, exactly once, never again whatever happens next.
462
- const path = found.envelope?.transcript_path;
463
- const evidence = path ? readTranscriptEvidence(path, found.envelope?.transcript_offset ?? 0, record.id) : null;
669
+ const path = found.envelope?.transcript_path ?? adapterTranscript(deps, session_id);
670
+ const evidence = path ? readAgentEvidence(spec.provider, path, found.envelope?.transcript_offset ?? 0, record.id) : null;
671
+ for (const r of hook.filter((x) => x.state === "in_model_request"))
672
+ receipts.push({ state: "in_model_request", at: r.at, source: "runtime_hook", detail: { hook_event: r.hook_event } });
464
673
  if (!evidence?.delivered) {
465
674
  const emitted = hook.some((r) => r.state === "emitted");
675
+ if (hook.some((r) => r.state === "left_provider_queue")) {
676
+ return { ...base, state: "unknown", receipts, note: `${spec.name}'s run ended before a model request held it. If a person stopped the run, the words went back to their editor. It is not sent again.` };
677
+ }
678
+ // A provider's own queue holds it until its next continuation: waiting there is not ambiguity, while the session lives.
679
+ if (emitted && spec.self_wakes && sessionRunning(deps, spec.provider, session_id).alive) {
680
+ return { ...base, state: "queued_at_runtime", continuation: "provider_queue", receipts, note: `It sits in ${spec.name}'s own queue, which drains at the agent's next step. ${spec.name}'s record does not show the model read it yet.` };
681
+ }
466
682
  return {
467
683
  ...base,
468
684
  state: "unknown",
469
685
  receipts,
470
686
  note: emitted
471
- ? "The runtime hook printed it, and the transcript does not show it entered the model's context yet."
687
+ ? spec.self_wakes
688
+ ? `The adapter handed it to ${spec.name}, the session has ended and its record does not show the model read it. It is not sent again.`
689
+ : "The runtime hook printed it, and the transcript does not show it entered the model's context yet."
472
690
  : "The hook claimed it and left no receipt, so delivery is ambiguous. It is not sent again.",
473
691
  };
474
692
  }
475
- receipts.push({ state: "delivered_to_agent_context", at: evidence.delivered.at, source: "claude_transcript", detail: { attachment: evidence.delivered.attachment, hook_event: evidence.delivered.hook_event, tool_use_id: evidence.delivered.tool_use_id } });
693
+ const source = spec.evidence;
694
+ receipts.push({ state: "delivered_to_agent_context", at: evidence.delivered.at, source, detail: { attachment: evidence.delivered.attachment, hook_event: evidence.delivered.hook_event, tool_use_id: evidence.delivered.tool_use_id } });
476
695
  let state = "delivered_to_agent_context";
477
696
  if (evidence.acknowledged) {
478
697
  state = "acknowledged";
479
- receipts.push({ state: "acknowledged", at: evidence.acknowledged.at, source: "claude_transcript", detail: { text: evidence.acknowledged.text } });
698
+ receipts.push({ state: "acknowledged", at: evidence.acknowledged.at, source, detail: { text: evidence.acknowledged.text } });
480
699
  }
481
700
  const expect = typeof record.body.expect_next_action === "string" ? record.body.expect_next_action : undefined;
482
701
  let behavior = evidence.actions_seen ? "not_judged" : "not_observed_yet";
@@ -485,7 +704,7 @@ export function readSteerDelivery(deps, record, now = new Date()) {
485
704
  behavior = seen >= 0 ? "expected_action_seen" : "expected_action_not_seen";
486
705
  if (seen >= 0) {
487
706
  state = "behavior_adjusted";
488
- receipts.push({ state: "behavior_adjusted", at: evidence.next_actions[seen]?.at, source: "claude_transcript", detail: { expected: expect, action: evidence.next_actions[seen] } });
707
+ receipts.push({ state: "behavior_adjusted", at: evidence.next_actions[seen]?.at, source, detail: { expected: expect, action: evidence.next_actions[seen] } });
489
708
  }
490
709
  }
491
710
  return {
@@ -495,10 +714,28 @@ export function readSteerDelivery(deps, record, now = new Date()) {
495
714
  next_actions: evidence.next_actions,
496
715
  behavior,
497
716
  note: state === "behavior_adjusted"
498
- ? "The transcript shows the action this steer named, after it entered the model's context."
499
- : "The transcript shows it entered the model's context. Whether the next actions follow it is a person's judgment unless the steer named expect_next_action.",
717
+ ? `${spec.name}'s record shows the action this correction named, after it entered the model's context.`
718
+ : behavior === "expected_action_not_seen"
719
+ ? `${spec.name}'s record shows it entered the model's context, and the model's next actions do not hold what this correction named.`
720
+ : `${spec.name}'s record shows it entered the model's context. Whether the next actions follow it is a person's judgment.`,
500
721
  };
501
722
  }
723
+ /** The adapter's file names the agent's own record. A steer queued before the file named it still reads it here. */
724
+ function adapterTranscript(deps, sessionId) {
725
+ const path = readJson(join(deps.root, safe(sessionId), "adapter.json"))?.transcript_path;
726
+ return typeof path === "string" ? path : undefined;
727
+ }
728
+ /** Whether the session is running now and what it says it is doing, from its own registry or its adapter's files. */
729
+ function sessionRunning(deps, provider, sessionId) {
730
+ if (provider === "claude") {
731
+ const seat = readClaudeSession(deps, sessionId);
732
+ return { alive: Boolean(seat), ...(seat?.status ? { status: seat.status } : {}) };
733
+ }
734
+ const adapter = readJson(join(deps.root, safe(sessionId), "adapter.json"));
735
+ const alive = deps.isAlive ?? defaultAlive;
736
+ const status = readJson(join(deps.root, safe(sessionId), "seat.json"))?.status;
737
+ return { alive: typeof adapter?.pid === "number" && alive(adapter.pid), ...(typeof status === "string" ? { status } : {}) };
738
+ }
502
739
  function hookReceipts(root, sessionId, steer) {
503
740
  let text;
504
741
  try {
package/dist/server.d.ts CHANGED
@@ -17,7 +17,7 @@ import { Ledger } from "./store.js";
17
17
  import type { ConnectorRecord } from "./records.js";
18
18
  import type { ConnectorConfig } from "./config.js";
19
19
  import type { TmuxLike } from "./steer.js";
20
- import type { DiscoveryProbe, ProviderId } from "./providers.js";
20
+ import { type DiscoveryProbe, type ProviderId } from "./providers.js";
21
21
  import type { JevAdapter } from "./model-preflight.js";
22
22
  import type { StandardSource } from "./mission-standard.js";
23
23
  export interface ConnectorDeps {
@@ -41,6 +41,8 @@ export interface ConnectorDeps {
41
41
  steerSettleMs?: number;
42
42
  /** Where sessions and their steering inboxes live (jgwill/Miadi#930). */
43
43
  steeringRuntime?: RuntimeDeps;
44
+ /** Asks the factory runner for a pass now. Its timer is the net (jgwill/Miadi#942). */
45
+ wakeRunner?: () => void;
44
46
  /** Reads a video's captions for an approved create; the service passes youtubeCaptions, tests their own. */
45
47
  captions?: FetchCaptions;
46
48
  /** Person-token attempts allowed per address in 15 minutes on each sign-in form (default 30). */
package/dist/server.js CHANGED
@@ -5,12 +5,15 @@ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/
5
5
  import { mcpAuthRouter, createOAuthMetadata, getOAuthProtectedResourceMetadataUrl } from "@modelcontextprotocol/sdk/server/auth/router.js";
6
6
  import { requireBearerAuth } from "@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js";
7
7
  import { MiadiOAuthProvider, SCOPES, SCOPE_CONTRIBUTE, SCOPE_READ, emptyOAuthState } from "./oauth.js";
8
- import { logDecision, reconcileInterrupted, registerApprovalRoutes, registerProviderPolicyRoutes, startTranscriptSettling } from "./approve.js";
8
+ import { logDecision, reconcileInterrupted, registerApprovalRoutes, registerConsentRoutes, registerProviderPolicyRoutes, startTranscriptSettling, page } from "./approve.js";
9
9
  import { DecisionTokens } from "./decisions.js";
10
10
  import { JsonFile, Ledger, ensureStateDir, statePaths } from "./store.js";
11
11
  import { registerTools } from "./tools.js";
12
12
  import { MiadiClient } from "./miadi.js";
13
13
  import { ReviewClient } from "./reviews.js";
14
+ import { readFactoryConfig, runSteering } from "./steering-adapters.js";
15
+ import { discoverProviders } from "./providers.js";
16
+ import { factoryDir } from "./queue-state.js";
14
17
  import { draftReviewService } from "./draft-review.js";
15
18
  import { VERSION } from "./version.js";
16
19
  export function createConnectorApp(config, deps) {
@@ -61,7 +64,15 @@ export function createConnectorApp(config, deps) {
61
64
  const attempts = deps.tokenAttemptsPerWindow ?? 30;
62
65
  const limitTokens = () => rateLimit({ windowMs: 15 * 60 * 1000, limit: attempts, standardHeaders: "draft-7", legacyHeaders: false });
63
66
  const confirmLimit = limitTokens();
64
- const formLimit = limitTokens();
67
+ // Only a failed sign-in counts: a person reading a correction again, or deciding, spends nothing (jgwill/Miadi#942).
68
+ const formLimit = rateLimit({
69
+ windowMs: 15 * 60 * 1000,
70
+ limit: attempts,
71
+ skipSuccessfulRequests: true,
72
+ standardHeaders: "draft-7",
73
+ legacyHeaders: false,
74
+ handler: (_req, res) => void res.status(429).type("html").send(page("Too many tries", `<h1>Too many failed tries</h1><p>Too many requests from this address failed, usually with a token Miadi did not recognise. Try again in 15 minutes. Nothing was approved or changed by a try that failed.</p>`)),
75
+ });
65
76
  app.use(["/approve", "/records"], (req, res, next) => (req.method === "POST" ? formLimit(req, res, next) : next()));
66
77
  app.use("/mcp", rateLimit({ windowMs: 15 * 60 * 1000, limit: attempts, skipSuccessfulRequests: true, standardHeaders: "draft-7", legacyHeaders: false }));
67
78
  app.post("/authorize/confirm", confirmLimit, express.urlencoded({ extended: false, limit: "16kb" }), (req, res, next) => {
@@ -76,10 +87,12 @@ export function createConnectorApp(config, deps) {
76
87
  identify: deps.identify,
77
88
  fetchImpl: deps.fetchImpl,
78
89
  factoryDir: deps.factoryDir,
90
+ steeringOf: runSteering(() => discoverProviders(deps.providersProbe), () => ({ factory: readFactoryConfig(deps.factoryDir ?? factoryDir()) })),
79
91
  tmuxSessions: deps.tmuxSessions,
80
92
  tmux: deps.tmux,
81
93
  steerSettleMs: deps.steerSettleMs,
82
94
  ...(deps.steeringRuntime ? { steeringRuntime: deps.steeringRuntime } : {}),
95
+ ...(deps.wakeRunner ? { wakeRunner: deps.wakeRunner } : {}),
83
96
  ...(deps.captions ? { captions: deps.captions } : {}),
84
97
  log: deps.log,
85
98
  };
@@ -89,6 +102,8 @@ export function createConnectorApp(config, deps) {
89
102
  registerApprovalRoutes(app, approvalDeps);
90
103
  registerProviderPolicyRoutes(app, approvalDeps);
91
104
  const decisionTokens = new DecisionTokens(config.stateDir, config.decisionTokenTtl);
105
+ approvalDeps.consentLink = (id) => `${config.publicUrl}/consent/${encodeURIComponent(id)}?k=${decisionTokens.consentKey(id)}`;
106
+ registerConsentRoutes(app, approvalDeps, (id, key) => decisionTokens.consentKeyOk(id, key));
92
107
  const bearer = requireBearerAuth({
93
108
  verifier: provider,
94
109
  requiredScopes: [SCOPE_READ],
@@ -130,6 +145,7 @@ export function createConnectorApp(config, deps) {
130
145
  draftReview,
131
146
  steerSettleMs: deps.steerSettleMs,
132
147
  ...(deps.steeringRuntime ? { steeringRuntime: deps.steeringRuntime } : {}),
148
+ ...(deps.wakeRunner ? { wakeRunner: deps.wakeRunner } : {}),
133
149
  };
134
150
  const server = new McpServer({ name: "miadi", version: VERSION }, { instructions: INSTRUCTIONS });
135
151
  registerTools(server, ctx);
package/dist/steer.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { execFileSync } from "node:child_process";
2
2
  import { type RuntimeDeps } from "./runtime-steer.js";
3
+ import { type InboxRoute } from "./steering-adapters.js";
3
4
  import type { ConnectorRecord } from "./records.js";
4
5
  export declare const STEER_STATUSES: readonly ["prepared", "submitted", "accepted", "busy", "blocked", "wrong_pane", "stale_binding", "expired_grant", "duplicate", "composing", "queued_at_runtime", "unsupported"];
5
6
  export type SteerStatus = (typeof STEER_STATUSES)[number];
@@ -30,6 +31,8 @@ export interface TmuxLike {
30
31
  available?(): boolean;
31
32
  /** Every live tmux session name. */
32
33
  listSessions?(): string[];
34
+ /** This server's socket: a pane number is unique only within its server. */
35
+ socketPath?(): string | null;
33
36
  }
34
37
  /** Commands that mark a pane as an agent seat a steer may land in. */
35
38
  export declare const AGENT_COMMANDS: string[];
@@ -72,6 +75,8 @@ export interface SteerDeps {
72
75
  agentCommands?: string[];
73
76
  /** Where sessions and their inboxes live (jgwill/Miadi#930). Absent, no runtime route is known. */
74
77
  runtime?: RuntimeDeps;
78
+ /** Asks the factory runner for a pass now, for a seat with nothing coming to carry a correction. Its timer is the net. */
79
+ wakeRunner?: () => void;
75
80
  }
76
81
  export interface SteerResult {
77
82
  status: SteerStatus;
@@ -81,7 +86,9 @@ export interface SteerResult {
81
86
  typed: boolean;
82
87
  /** Whether it was handed to the runtime's inbox. That is not proof the model read it. */
83
88
  forwarded?: boolean;
84
- route?: "claude_hook_inbox" | "tmux_exact_pane";
89
+ route?: InboxRoute | "tmux_exact_pane";
90
+ /** The session the inbox belongs to, when the runner's receipt could name only its pane. */
91
+ runtime_session_id?: string;
85
92
  transcript_path?: string;
86
93
  transcript_offset?: number;
87
94
  artifact?: {