@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.
@@ -0,0 +1,227 @@
1
+ /**
2
+ * Which Claude Code model a new mission launches on (jgwill/Miadi#943).
3
+ *
4
+ * - A request that names a model launches on it. A model is a Claude Code model only: a request
5
+ * for another provider that names one is refused, so a model never moves a mission to a
6
+ * provider nobody chose.
7
+ * - A request that names none has Jev choose among the permitted models, once, when its brief is
8
+ * written. Jev sees the task type, the criticality and the candidates: no task text, mission id
9
+ * or repository. It authorizes nothing and never chooses a provider.
10
+ * - When Jev is unconfigured, down, abstains, answers below the floor or breaks the answer
11
+ * contract, the launch uses the configured Claude Code model and the receipt says why. It never
12
+ * falls back to another provider.
13
+ * - Jev knows only the fit notes below about these models. Told only what each model is, it answered
14
+ * below the floor on every task type (0.37 to 0.74, 2026-11-07); told what each fits, 0.96 to 1.
15
+ * So the notes carry the judgment, Jev applies them to the task, and its confidence is
16
+ * uncalibrated. A wrong note is changed here.
17
+ * - A request recorded before this carries no routing mark and launches as it was approved.
18
+ *
19
+ * The brief carries the choice as model= and model_source=. The factory runner passes it as
20
+ * --model and its receipt names the flag. Which model answered is read from the session's own
21
+ * transcript whenever someone asks (firstModelInTranscript, mission_status): that is the proof,
22
+ * and a session slow to answer is only not known yet.
23
+ */
24
+ import { closeSync, openSync, readFileSync, readSync } from "node:fs";
25
+ import { join } from "node:path";
26
+ import { configuredModel, jevAdapter, modelPreflight, } from "./model-preflight.js";
27
+ import { discoverProviders, jevConfigOf, PROVIDERS } from "./providers.js";
28
+ import { factoryDir } from "./queue-state.js";
29
+ import { versionOf } from "./revisions.js";
30
+ export const MODEL_ROUTING_CONTRACT = "miadi.claude_model_routing";
31
+ /** The body mark of a request whose model Jev chooses when its brief is written. */
32
+ export const JEV_WITHIN_CLAUDE = "jev_within_claude";
33
+ /** Jev answered in 239 to 1321 ms when measured. A person pressing Approve waits at most this, and then the configured model launches. */
34
+ const ROUTING_TIMEOUT_MS = 8_000;
35
+ /** Typed into a shell by the factory runner, so one plain word. The runner checks it again. */
36
+ export const MODEL_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,79}$/;
37
+ /** Each answered a real prompt under `--model <id>` and under its full name. */
38
+ export const CLAUDE_MODELS = [
39
+ { id: "opus", resolves_to: "claude-opus-5-5", capability_note: "The fit for a file_relevance task, which needs high recall, and for a review task at normal criticality." },
40
+ { id: "sonnet", resolves_to: "claude-sonnet-5-5", capability_note: "The fit for an implementation task at normal criticality." },
41
+ { id: "haiku", resolves_to: "claude-haiku-5-5", capability_note: "The cheapest model; it misses files on wide searches, so it fits none of these task types unless a task is trivially narrow." },
42
+ { id: "fable", resolves_to: "claude-fable-5-1", capability_note: "The fit for an architecture_refactor task and for any security_critical task: the most capable model." },
43
+ ];
44
+ /** A run under one name proves that name on that host that day, and says nothing of a sign-in elsewhere. */
45
+ export const CLAUDE_MODELS_VERIFIED = {
46
+ on: "2026-11-07",
47
+ cli: "2.1.319",
48
+ how: "claude -p <prompt> --model <name> --output-format json: modelUsage named the model that answered; an unknown name failed with exit 1",
49
+ };
50
+ const plainName = (v) => (typeof v === "string" && MODEL_NAME.test(v) ? v : null);
51
+ export function claudeModelConfig(dir = factoryDir(), modelOf = (p) => configuredModel(p)) {
52
+ let file = {};
53
+ try {
54
+ file = JSON.parse(readFileSync(join(dir, "factory.json"), "utf8"));
55
+ }
56
+ catch {
57
+ file = {};
58
+ }
59
+ const listed = Array.isArray(file.claudeModels) ? file.claudeModels.map(plainName).filter((m) => Boolean(m)) : [];
60
+ const base = listed.length ? listed : CLAUDE_MODELS.map((m) => m.id);
61
+ // A setting that is not one plain word (opus[1m]) is left to Claude Code, which reads it itself. A list that leaves the setting out wins over it.
62
+ const setting = plainName(modelOf("claude"));
63
+ const configured = plainName(file.claudeDefaultModel) ?? (setting && (!listed.length || isPermittedModel(setting, listed)) ? setting : (listed[0] ?? null));
64
+ return { permitted: configured && !isPermittedModel(configured, base) ? [configured, ...base] : base, configured };
65
+ }
66
+ /** A permitted name, or the full name of a permitted alias. */
67
+ export function isPermittedModel(model, permitted) {
68
+ return permitted.includes(model) || CLAUDE_MODELS.some((m) => m.resolves_to === model && permitted.includes(m.id));
69
+ }
70
+ /** What a request records about its model, or why it may not be recorded. */
71
+ export function modelPlan(provider, model, permitted) {
72
+ if (model) {
73
+ if (provider !== "claude") {
74
+ return { refusal: { code: "model_provider_mismatch", message: `${model} is a Claude Code model and this request runs on ${provider ?? "no provider"}. Nothing was recorded; remove the model or run it on claude.`, permitted } };
75
+ }
76
+ if (!isPermittedModel(model, permitted)) {
77
+ return { refusal: { code: "model_not_permitted", message: `${model} is not a permitted Claude Code model on this host (${permitted.join(", ")}). Nothing was recorded.`, permitted } };
78
+ }
79
+ return { fields: { model } };
80
+ }
81
+ return { fields: provider === "claude" ? { model_routing: JEV_WITHIN_CLAUDE } : {} };
82
+ }
83
+ /** One candidate per permitted model, the configured one first: Jev's options, and the preflight's. */
84
+ export function claudeModelCandidates(found, config, base) {
85
+ const a = found.find((p) => p.id === "claude");
86
+ const installed = Boolean(a?.installed);
87
+ const auth = a?.auth_evidence === "found" ? "config_dir_only" : "none";
88
+ // A configured full name stands for its alias, so one model is not offered twice.
89
+ const sameModel = (name) => CLAUDE_MODELS.find((m) => m.id === name)?.resolves_to === config.configured;
90
+ const names = [...new Set([...(config.configured ? [config.configured] : []), ...config.permitted.filter((name) => !sameModel(name))])];
91
+ return names.map((model) => {
92
+ let eligible = base?.eligible ?? true;
93
+ let reason = base?.policy_reason ?? "Installed, with sign-in evidence (config directory only; quota unknown).";
94
+ if (!installed)
95
+ [eligible, reason] = [false, "Not installed on the connector host."];
96
+ else if (auth === "none")
97
+ [eligible, reason] = [false, "No sign-in evidence on this host."];
98
+ const note = CLAUDE_MODELS.find((m) => m.id === model || m.resolves_to === model)?.capability_note;
99
+ return {
100
+ option: `claude:${model}`,
101
+ provider: "claude",
102
+ model_id: model,
103
+ model_id_source: model === config.configured ? "configured_default" : "permitted",
104
+ ...(note ? { capability_note: note } : {}),
105
+ installed,
106
+ ...(a?.version ? { version: a.version } : {}),
107
+ auth,
108
+ quota: "unknown",
109
+ eligible,
110
+ policy_reason: reason,
111
+ };
112
+ });
113
+ }
114
+ const taskOf = (b) => ({
115
+ type: (typeof b.task_type === "string" ? b.task_type : "implementation"),
116
+ criticality: (typeof b.criticality === "string" ? b.criticality : "normal"),
117
+ });
118
+ /**
119
+ * The model of one mission's launch, or null when this mission's model is not routed: another
120
+ * provider, or a request recorded before routing. Asked at most once for a version: a brief written
121
+ * again for it (a rerun) keeps the answer, because a lost answer may already have been charged.
122
+ */
123
+ export async function routeModel(record, opts, deps = {}) {
124
+ const b = (record.body ?? {});
125
+ const version = versionOf(record);
126
+ const base = { contract: MODEL_ROUTING_CONTRACT, version: 1, decided_for: { record: record.id, version }, provider: "claude", authorizes: false };
127
+ const explicit = typeof b.model === "string" && b.model ? b.model : null;
128
+ if (!explicit && b.model_routing !== JEV_WITHIN_CLAUDE)
129
+ return null;
130
+ if (opts.existingSession)
131
+ return { ...base, model: null, source: "existing_session" };
132
+ // The request was checked when it was made. A launch is checked again, because nothing stands in for Claude Code.
133
+ const found = discoverProviders(deps.providersProbe, PROVIDERS.filter((p) => p.id === "claude"));
134
+ const missing = !found[0]?.installed ? "is not installed" : found[0].auth_evidence !== "found" ? "shows no sign-in" : null;
135
+ if (missing)
136
+ return { ...base, model: null, source: "unavailable", why: `Claude Code ${missing} on the connector host` };
137
+ if (explicit)
138
+ return { ...base, model: explicit, source: "request" };
139
+ const prior = record.completion_receipt?.model_routing;
140
+ if (prior?.decided_for?.record === record.id && prior.decided_for.version === version && prior.source !== "unavailable" && prior.source !== "existing_session")
141
+ return prior;
142
+ const config = claudeModelConfig(deps.factoryDir ?? factoryDir(), deps.modelOf);
143
+ const candidates = claudeModelCandidates(found, config);
144
+ const task = taskOf(b);
145
+ const jev = deps.adapter ? null : jevConfigOf(deps.env ?? process.env);
146
+ const adapter = deps.adapter ?? (jev ? jevAdapter(jev, deps.fetchImpl ?? fetch, ROUTING_TIMEOUT_MS) : undefined);
147
+ const answer = await modelPreflight({
148
+ mission: { id: record.id, resolution: "launch", authorizes_actions: false },
149
+ approved_provider: "claude",
150
+ task: task.type,
151
+ criticality: task.criticality,
152
+ candidates,
153
+ ...(adapter ? { adapter } : { routerWhenAbsent: "router_unconfigured" }),
154
+ });
155
+ const chosen = answer.state === "recommended" && answer.decider.router === "answered" ? (answer.recommendation.model_id ?? null) : null;
156
+ const reasons = chosen ? [] : answer.recommendation.abstain_reasons.length ? answer.recommendation.abstain_reasons : [answer.decider.router];
157
+ return {
158
+ ...base,
159
+ model: chosen ?? config.configured,
160
+ source: chosen ? "jev" : config.configured ? "configured_fallback" : "cli_default",
161
+ ...(chosen ? {} : { fallback_reasons: reasons }),
162
+ task,
163
+ eligible: candidates.filter((c) => c.eligible).map((c) => c.model_id),
164
+ decider: {
165
+ source: answer.decider.source,
166
+ router: answer.decider.router,
167
+ ...(answer.decider.model ? { model: answer.decider.model } : {}),
168
+ calibration: answer.decider.calibration,
169
+ ...(answer.decider.confidence_floor !== undefined ? { confidence_floor: answer.decider.confidence_floor } : {}),
170
+ confidence: answer.recommendation.confidence,
171
+ review_tier: answer.recommendation.review_tier,
172
+ input_hash: answer.input_hash,
173
+ explanation: answer.recommendation.explanation,
174
+ ...(answer.decider.detail ? { detail: answer.decider.detail } : {}),
175
+ ...(answer.evidence.latency_ms !== undefined ? { latency_ms: answer.evidence.latency_ms } : {}),
176
+ // What this call cost and how to find it; the account's balances stay out of a receipt others read.
177
+ ...(answer.evidence.jev_billing ? { billing: { credits_charged: answer.evidence.jev_billing.credits_charged, run_id: answer.evidence.jev_billing.run_id } } : {}),
178
+ },
179
+ };
180
+ }
181
+ /** What the brief carries. */
182
+ export function modelAttributes(routing) {
183
+ if (!routing || routing.source === "existing_session" || routing.source === "unavailable")
184
+ return {};
185
+ return { ...(routing.model ? { model: routing.model } : {}), model_source: routing.source };
186
+ }
187
+ const TRANSCRIPT_HEAD_BYTES = 4 * 1024 * 1024;
188
+ /**
189
+ * The model that first answered in a session's own transcript, or null when none has yet. A launched
190
+ * session's id is its own, so anything answering in it is this launch. "<synthetic>" is Claude Code's
191
+ * own line, and a sidechain is a subagent: neither is the session's model.
192
+ */
193
+ export function firstModelInTranscript(path) {
194
+ let head;
195
+ try {
196
+ const fd = openSync(path, "r");
197
+ try {
198
+ const buf = Buffer.alloc(TRANSCRIPT_HEAD_BYTES);
199
+ head = buf.subarray(0, readSync(fd, buf, 0, TRANSCRIPT_HEAD_BYTES, 0)).toString("utf8");
200
+ }
201
+ finally {
202
+ closeSync(fd);
203
+ }
204
+ }
205
+ catch {
206
+ return null;
207
+ }
208
+ for (const line of head.split("\n")) {
209
+ if (!line.includes('"assistant"'))
210
+ continue;
211
+ let r;
212
+ try {
213
+ r = JSON.parse(line);
214
+ }
215
+ catch {
216
+ continue;
217
+ }
218
+ const model = r.type === "assistant" && !r.isSidechain ? r.message?.model : undefined;
219
+ if (typeof model === "string" && model && model !== "<synthetic>")
220
+ return model;
221
+ }
222
+ return null;
223
+ }
224
+ /** Whether a model answered under a name: the name itself, or the alias of its family (opus answers as claude-opus-5-5). */
225
+ export function modelMatches(requested, observed) {
226
+ return observed === requested || observed.startsWith(`claude-${requested}-`);
227
+ }
@@ -17,6 +17,14 @@ export interface FactoryReceipt {
17
17
  launcher?: string;
18
18
  /** The brief file the line pointed the seat at. */
19
19
  brief?: string;
20
+ /** What the launch asked of the model (jgwill/Miadi#943). */
21
+ model?: FactoryModelReceipt;
22
+ }
23
+ export interface FactoryModelReceipt {
24
+ requested: string | null;
25
+ source: string | null;
26
+ /** The flag on the launch line. Which model answered is in the session's transcript, not here. */
27
+ flag: string | null;
20
28
  }
21
29
  /** The runner's ledger file: MIADI_FACTORY_LEDGER, else `<factory>/delivered.jsonl`, as the runner resolves it. */
22
30
  export declare function factoryLedgerPath(dir?: string, env?: NodeJS.ProcessEnv): string;
@@ -55,6 +55,7 @@ export function readFactoryReceipts(file) {
55
55
  ...(str(r.provider) ? { provider: str(r.provider) } : {}),
56
56
  ...(str(r.launcher) ? { launcher: str(r.launcher) } : {}),
57
57
  ...(str(r.brief) ? { brief: str(r.brief) } : {}),
58
+ ...(r.model && typeof r.model === "object" ? { model: r.model } : {}),
58
59
  });
59
60
  }
60
61
  return out;
@@ -22,6 +22,7 @@
22
22
  import type { ConnectorRecord } from "./records.js";
23
23
  import type { RequestProjection } from "./request-state.js";
24
24
  import type { SteerDelivery } from "./runtime-steer.js";
25
+ import type { SteeringSupport } from "./steering-adapters.js";
25
26
  import type { FactoryReceipt } from "./factory-receipt.js";
26
27
  import { type GithubGet, type MissionResult } from "./mission-result.js";
27
28
  export interface MissionSession {
@@ -57,6 +58,21 @@ export interface MissionSession {
57
58
  /** Present when Miadi's session view was joined (write tier). */
58
59
  miadi?: unknown;
59
60
  }
61
+ /** The model a mission's launch used: who chose it, what the launch line asked, and which model answered (jgwill/Miadi#943). */
62
+ export interface MissionModel {
63
+ /** What the launch was told to use; null when it passed no flag. */
64
+ chosen: string | null;
65
+ /** request, jev, configured_fallback, cli_default, existing_session or unavailable. */
66
+ source: string | null;
67
+ fallback_reasons?: string[];
68
+ confidence?: number | null;
69
+ /** The flag on the launch line, from the runner's receipt, once it delivered. */
70
+ flag?: string | null;
71
+ /** The model the session's own transcript says answered, read now. null: none has yet. */
72
+ observed?: string | null;
73
+ /** False when another model answered than the one chosen. */
74
+ match: boolean | "unknown";
75
+ }
60
76
  /** The provider the mission asked for, the one resolved on the host, and the one that ran. */
61
77
  export interface MissionProvider {
62
78
  requested: string | null;
@@ -158,6 +174,8 @@ export interface MissionIdentity {
158
174
  candidates: MissionCandidate[];
159
175
  }
160
176
  export interface MissionStatus {
177
+ /** The model its launch used, for the write tier. */
178
+ model?: MissionModel;
161
179
  ref: string;
162
180
  found: boolean;
163
181
  via?: string;
@@ -197,6 +215,8 @@ export interface MissionStatus {
197
215
  route: string;
198
216
  delivery: SteerDelivery;
199
217
  }[];
218
+ /** What a session of this mission's provider can promise on this host, and how that is known. */
219
+ support?: SteeringSupport;
200
220
  };
201
221
  stage_truth?: MissionStageTruth;
202
222
  /**
@@ -228,8 +248,12 @@ export interface MissionStatusDeps {
228
248
  paneBusy?: (session: string, paneId?: string) => "busy" | "idle" | "unknown";
229
249
  /** Where one steer stands, read from the runtime's inbox and the session's transcript (write tier only). */
230
250
  steerDeliveryOf?: (steer: ConnectorRecord) => SteerDelivery | null;
251
+ /** The steering support of a provider on this host (write tier only). */
252
+ steeringSupportOf?: (provider: string) => SteeringSupport;
231
253
  /** Whether the tmux session still holds the pane id (write tier only); undefined when it cannot be listed. */
232
254
  panePresent?: (session: string, paneId: string) => boolean | undefined;
255
+ /** The model that first answered in a session, from its own transcript (write tier only). */
256
+ modelAnsweredOf?: (sessionId: string) => string | null;
233
257
  /** The factory runner's delivery receipts for one record, newest first (write tier only). */
234
258
  factoryReceiptsOf?: (recordId: string) => FactoryReceipt[];
235
259
  /** The records the factory delivered to one Claude Code session id (write tier only). */
@@ -1,5 +1,27 @@
1
1
  import { steerAttempts, steeringGrantOf, steeringRevoked, checkGrant } from "./steer.js";
2
+ import { modelMatches } from "./claude-models.js";
2
3
  import { missionResult, redactResult, submittedWithWriteTier } from "./mission-result.js";
4
+ function missionModel(record, receipt, answeredOf) {
5
+ const routing = (record.completion_receipt ?? {}).model_routing;
6
+ const ran = receipt?.model;
7
+ if (!routing && !ran)
8
+ return undefined;
9
+ const chosen = routing?.model ?? ran?.requested ?? null;
10
+ const source = routing?.source ?? ran?.source ?? null;
11
+ // A session that was already running answers on its own model, from long before this mission.
12
+ const observed = source !== "existing_session" && receipt?.session_id && answeredOf ? answeredOf(receipt.session_id) : undefined;
13
+ return {
14
+ chosen,
15
+ source,
16
+ ...(routing?.fallback_reasons ? { fallback_reasons: routing.fallback_reasons } : {}),
17
+ ...(routing?.decider ? { confidence: routing.decider.confidence ?? null } : {}),
18
+ ...(receipt ? { flag: ran?.flag ?? null } : {}),
19
+ ...(observed !== undefined ? { observed } : {}),
20
+ match: chosen && observed ? modelMatches(chosen, observed) : "unknown",
21
+ };
22
+ }
23
+ /** How long a delivered session may name no model before a reader is told. */
24
+ const NO_ANSWER_NOTE_MS = 5 * 60 * 1000;
3
25
  const ISSUE_REF = /^([\w.-]+)\/([\w.-]+)#(\d+)$/;
4
26
  const SESSION_REF = /^session:([0-9a-f-]{36})$/;
5
27
  const MISSION_KINDS = new Set(["run_request", "work_proposal"]);
@@ -109,7 +131,7 @@ function nextAction(record, standing, queue, result) {
109
131
  return queue?.state === "delivered"
110
132
  ? "The brief is with its session. Follow it, or steer it with request_session_steer inside the approved grant."
111
133
  : queue?.state === "refused"
112
- ? "The factory runner refused to launch its provider; nothing runs. The requester decides on a new request with a provider they chose."
134
+ ? "The factory runner refused to launch it, and the queue says why; nothing runs. The requester decides on a new request."
113
135
  : "Wait for the factory intake to deliver the brief.";
114
136
  case "failed":
115
137
  return standing.rerun.available ? "A write-tier person may run it again with the same approval." : "Read the failure and decide.";
@@ -324,6 +346,16 @@ export async function missionStatus(ref, records, deps) {
324
346
  }
325
347
  }
326
348
  }
349
+ const model = deps.factoryReceiptsOf ? missionModel(record, receipts[0], deps.modelAnsweredOf) : undefined;
350
+ if (model?.match === false) {
351
+ notes.push(`The launch asked for ${model.chosen}; the session's transcript says ${model.observed} answered. Nothing was re-run because of it.`);
352
+ }
353
+ if (model && receipts[0] && model.chosen && model.source !== "existing_session" && !model.flag) {
354
+ notes.push(`${model.chosen} was chosen, but the runner's receipt shows no --model: a factory runner older than 0.1.5 ignores it, so read observed for what ran.`);
355
+ }
356
+ if (model?.observed === null && receipts[0] && Date.now() - Date.parse(receipts[0].at) > NO_ANSWER_NOTE_MS) {
357
+ notes.push("Five minutes after delivery, the session's transcript names no model that answered. It may be slow, or its model may have been refused at launch: read the pane.");
358
+ }
327
359
  const addSession = (session, association) => {
328
360
  if (seen.has(session))
329
361
  return;
@@ -470,8 +502,15 @@ export async function missionStatus(ref, records, deps) {
470
502
  ...(queue ? { queue } : {}),
471
503
  sessions,
472
504
  issues,
473
- steering: { grant: grantState, attempts_used: attempts, ...(grant?.max_attempts !== undefined ? { max_attempts: grant.max_attempts } : {}), ...(steers.length ? { steers } : {}) },
505
+ steering: {
506
+ grant: grantState,
507
+ attempts_used: attempts,
508
+ ...(grant?.max_attempts !== undefined ? { max_attempts: grant.max_attempts } : {}),
509
+ ...(steers.length ? { steers } : {}),
510
+ ...(deps.steeringSupportOf && (provider?.actual ?? provider?.resolved) ? { support: deps.steeringSupportOf(String(provider.actual ?? provider.resolved)) } : {}),
511
+ },
474
512
  ...(provider ? { provider } : {}),
513
+ ...(model ? { model } : {}),
475
514
  stage_truth: stageTruth,
476
515
  mission_stage: missionStage(standing ?? null, stageTruth),
477
516
  pending_human_gates: pendingGates(record, records, result, deps.approvalUrl),
@@ -17,8 +17,8 @@ export interface ModelCandidate {
17
17
  provider: ProviderId;
18
18
  /** A concrete model id when the host shows one, else null. */
19
19
  model_id: string | null;
20
- /** configured_default: the provider's own config names it; it is not proof of what a launch will use. */
21
- model_id_source: "configured_default" | "fixture" | "unknown";
20
+ /** configured_default: the provider's own config names it; it is not proof of what a launch will use. permitted: on this host's list of Claude Code models (claude-models.ts). */
21
+ model_id_source: "configured_default" | "permitted" | "fixture" | "unknown";
22
22
  /** What is known of the model's strength, with its source; absent on a live host, where nothing is measured yet. */
23
23
  capability_note?: string;
24
24
  installed: boolean;
@@ -4,7 +4,7 @@
4
4
  * how do we know?" — never an authorization.
5
5
  *
6
6
  * - Policy is deterministic and decided here, not by Jev: the approved provider
7
- * is kept (no switching without a person), Claude Code only when named, an
7
+ * is kept (no switching without a person), only Claude Code runs unnamed, an
8
8
  * uninstalled or sign-in-less provider is ineligible, and a reported launch on
9
9
  * another provider fails closed as provider_mismatch before anything is asked.
10
10
  * - Codex is eligible only with its requester's own choice for the mission or
@@ -269,7 +269,7 @@ export async function modelPreflight(input) {
269
269
  source: "static_fallback",
270
270
  router,
271
271
  calibration: "not_applicable",
272
- derivation: approved_provider ? `deterministic policy: the ${input.provider_basis ?? "approved"} provider and its configured default model` : "deterministic policy: preference order codex, pi, copilot; claude only when named",
272
+ derivation: approved_provider ? `deterministic policy: the ${input.provider_basis ?? "approved"} provider and its configured default model` : "deterministic policy: Claude Code when no provider is named; the others only by name",
273
273
  ...(detail ? { detail } : {}),
274
274
  },
275
275
  recommendation: {
@@ -31,15 +31,23 @@ export declare const CHOICE_TTL_MS: number;
31
31
  export declare function needsPersonChoice(provider: string | null | undefined): boolean;
32
32
  /** Whether a person id may make a choice or set a policy: a person, never a service token. */
33
33
  export declare function isPersonId(personId: string | undefined): boolean;
34
+ /** What may stand in for naming a provider. Codex never does: it runs only on a choice for one mission or an explicit policy (jgwill/Miadi#926). */
35
+ export declare const DEFAULT_PROVIDERS: readonly string[];
36
+ /** The value a person picks on /providers to mean no default of their own, whatever the operator set. */
37
+ export declare const HOST_ORDER = "host_order";
34
38
  export interface ProviderPolicy {
35
39
  person_id: string;
36
40
  codex: CodexPolicy;
37
41
  source: "default" | "person";
38
42
  record?: string;
39
43
  set_at?: string;
44
+ /** The provider a request of theirs runs on when it names none (jgwill/Miadi#942). Absent: Claude Code, the Factory's default (jgwill/Miadi#943). */
45
+ default_provider?: string;
46
+ /** Who said so: the person on /providers, or the operator's factory.json for this person. */
47
+ default_provider_source?: "person" | "host_config";
40
48
  }
41
49
  /** A person's provider policy: the latest one they set themself, else the default. */
42
- export declare function providerPolicyOf(records: ConnectorRecord[], personId: string): ProviderPolicy;
50
+ export declare function providerPolicyOf(records: ConnectorRecord[], personId: string, hostDefaults?: Record<string, string> | null): ProviderPolicy;
43
51
  export interface ProviderChoiceView {
44
52
  record: string;
45
53
  provider: string;
@@ -12,19 +12,29 @@ export function needsPersonChoice(provider) {
12
12
  export function isPersonId(personId) {
13
13
  return typeof personId === "string" && personId.length > 0 && !personId.startsWith("system:");
14
14
  }
15
+ /** What may stand in for naming a provider. Codex never does: it runs only on a choice for one mission or an explicit policy (jgwill/Miadi#926). */
16
+ export const DEFAULT_PROVIDERS = ["claude", "pi", "copilot"];
17
+ /** The value a person picks on /providers to mean no default of their own, whatever the operator set. */
18
+ export const HOST_ORDER = "host_order";
15
19
  /** A person's provider policy: the latest one they set themself, else the default. */
16
- export function providerPolicyOf(records, personId) {
20
+ export function providerPolicyOf(records, personId, hostDefaults) {
17
21
  let latest;
22
+ let chosenDefault;
18
23
  for (const r of records) {
19
24
  if (r.kind !== "provider_policy" || r.actor.person_id !== personId || !isPersonId(r.actor.person_id))
20
25
  continue;
21
- if (!CODEX_POLICIES.includes(String(r.body.codex)))
26
+ const body = r.body;
27
+ if (!CODEX_POLICIES.includes(String(body.codex)))
22
28
  continue;
23
29
  latest = r;
30
+ chosenDefault = typeof body.default_provider === "string" && body.default_provider ? body.default_provider : chosenDefault;
24
31
  }
32
+ const hostDefault = hostDefaults?.[personId];
33
+ const default_provider = chosenDefault === HOST_ORDER ? undefined : (chosenDefault ?? hostDefault);
34
+ const defaults = default_provider && DEFAULT_PROVIDERS.includes(default_provider) ? { default_provider, default_provider_source: (chosenDefault ? "person" : "host_config") } : {};
25
35
  if (!latest)
26
- return { person_id: personId, codex: DEFAULT_CODEX_POLICY, source: "default" };
27
- return { person_id: personId, codex: latest.body.codex, source: "person", record: latest.id, set_at: latest.created_at };
36
+ return { person_id: personId, codex: DEFAULT_CODEX_POLICY, source: "default", ...defaults };
37
+ return { person_id: personId, codex: latest.body.codex, source: "person", record: latest.id, set_at: latest.created_at, ...defaults };
28
38
  }
29
39
  function str(v) {
30
40
  return typeof v === "string" && v ? v : null;
@@ -52,7 +62,7 @@ export function authorizeProvider(record, records, opts = {}) {
52
62
  state: "not_required",
53
63
  authorized: true,
54
64
  explanation: provider
55
- ? `${provider} needs no per-mission choice; it was ${requested ? "named in the request" : "picked by the host's preference order"} and verified installed.`
65
+ ? `${provider} needs no per-mission choice; it was ${requested ? "named in the request" : "the default provider"} and verified installed.`
56
66
  : "No provider is named: the factory runner's configured default launches, and the runner never starts Codex for a connector brief without the brief's own authorization.",
57
67
  };
58
68
  }
@@ -9,9 +9,9 @@ export interface ProviderSpec {
9
9
  auth_evidence: string[];
10
10
  }
11
11
  /**
12
- * Preference order when a run request names no provider (jgwill/Miadi#893). Codex is never
13
- * picked by default: a request names it, and it runs only on the requester's own choice for
14
- * that mission or their own policy (provider-policy.ts, jgwill/Miadi#926).
12
+ * Claude Code is what a run request that names no provider launches (jgwill/Miadi#943). Every
13
+ * other provider runs only when a request names it. Codex also needs the requester's own choice
14
+ * for that mission or their own policy (provider-policy.ts, jgwill/Miadi#926).
15
15
  */
16
16
  export declare const PROVIDERS: ProviderSpec[];
17
17
  export interface ProviderAvailability {
@@ -41,11 +41,11 @@ export type ProviderResolution = {
41
41
  };
42
42
  /**
43
43
  * Resolve the provider a run will ask the intake for. A requested provider must
44
- * be known and installed; with no request the first installed provider in the
45
- * preference order that may be selected by default wins. Codex and Claude Code
46
- * only ever by name; whether a named Codex may run is provider-policy.ts's answer.
44
+ * be known and installed. With no request it is Claude Code, and a host where Claude
45
+ * Code is missing or shows no sign-in leaves the mission unstarted: no other provider
46
+ * stands in for it. Whether a named Codex may run is provider-policy.ts's answer.
47
47
  */
48
- export declare function resolveProvider(requested: string | undefined, found: ProviderAvailability[]): ProviderResolution;
48
+ export declare function resolveProvider(requested: string | undefined, found: ProviderAvailability[], personDefault?: string): ProviderResolution;
49
49
  /**
50
50
  * Where Jev is reached from this host (jgwill/Miadi#913 C1), by the names
51
51
  * smcraft's lane-check decider uses (examples/decision-gate/lane-check,
package/dist/providers.js CHANGED
@@ -3,12 +3,11 @@
3
3
  *
4
4
  * The connector never assumes a provider works because a task text names one:
5
5
  * it reports what is installed on this host, what sign-in evidence exists (the
6
- * presence of the provider's own config directory — never its contents), and
7
- * applies an explicit preference order. Codex and Claude Code are never selected
8
- * silently: each requires the request to name it, and Codex also needs the
9
- * requester's own choice for that mission (provider-policy.ts, jgwill/Miadi#926).
10
- * When nothing safe is configured the answer is `provider_unavailable` and the
11
- * mission is left unstarted.
6
+ * presence of the provider's own config directory — never its contents, and never
7
+ * proof of a live sign-in), and applies one default. A request that names no provider
8
+ * runs on Claude Code (jgwill/Miadi#943) and on nothing else: without it the mission
9
+ * is left unstarted. Pi, Copilot and Codex run only when named, and Codex also needs
10
+ * the requester's own choice for that mission (provider-policy.ts, jgwill/Miadi#926).
12
11
  *
13
12
  * No bearer token is read, logged or returned here. Version probes run the
14
13
  * provider's own `--version` with a short timeout.
@@ -18,15 +17,15 @@ import { existsSync } from "node:fs";
18
17
  import { homedir } from "node:os";
19
18
  import { join } from "node:path";
20
19
  /**
21
- * Preference order when a run request names no provider (jgwill/Miadi#893). Codex is never
22
- * picked by default: a request names it, and it runs only on the requester's own choice for
23
- * that mission or their own policy (provider-policy.ts, jgwill/Miadi#926).
20
+ * Claude Code is what a run request that names no provider launches (jgwill/Miadi#943). Every
21
+ * other provider runs only when a request names it. Codex also needs the requester's own choice
22
+ * for that mission or their own policy (provider-policy.ts, jgwill/Miadi#926).
24
23
  */
25
24
  export const PROVIDERS = [
25
+ { id: "claude", cli: "claude", name: "Claude Code", selectable_by_default: true, auth_evidence: [".claude"] },
26
26
  { id: "codex", cli: "codex", name: "Codex CLI", selectable_by_default: false, auth_evidence: [".codex"] },
27
- { id: "pi", cli: "pi", name: "Pi coding agent", selectable_by_default: true, auth_evidence: [".pi", ".config/pi"] },
28
- { id: "copilot", cli: "copilot", name: "GitHub Copilot CLI", selectable_by_default: true, auth_evidence: [".copilot"] },
29
- { id: "claude", cli: "claude", name: "Claude Code", selectable_by_default: false, auth_evidence: [".claude"] },
27
+ { id: "pi", cli: "pi", name: "Pi coding agent", selectable_by_default: false, auth_evidence: [".pi", ".config/pi"] },
28
+ { id: "copilot", cli: "copilot", name: "GitHub Copilot CLI", selectable_by_default: false, auth_evidence: [".copilot"] },
30
29
  ];
31
30
  const defaultWhich = (cli) => {
32
31
  try {
@@ -64,12 +63,23 @@ export function discoverProviders(probe = {}, specs = PROVIDERS) {
64
63
  }
65
64
  /**
66
65
  * Resolve the provider a run will ask the intake for. A requested provider must
67
- * be known and installed; with no request the first installed provider in the
68
- * preference order that may be selected by default wins. Codex and Claude Code
69
- * only ever by name; whether a named Codex may run is provider-policy.ts's answer.
66
+ * be known and installed. With no request it is Claude Code, and a host where Claude
67
+ * Code is missing or shows no sign-in leaves the mission unstarted: no other provider
68
+ * stands in for it. Whether a named Codex may run is provider-policy.ts's answer.
70
69
  */
71
- export function resolveProvider(requested, found) {
70
+ export function resolveProvider(requested, found, personDefault) {
72
71
  const installed = found.filter((p) => p.installed);
72
+ // A person's own default stands in for naming it, and never silently becomes another provider (jgwill/Miadi#942).
73
+ if (!requested && personDefault) {
74
+ const avail = found.find((p) => p.id === personDefault);
75
+ if (avail?.installed && avail.auth_evidence === "found")
76
+ return { state: "ok", provider: avail, explicit: false };
77
+ return {
78
+ state: "provider_unavailable",
79
+ message: `Your default provider, ${personDefault}, ${avail?.installed ? "shows no sign-in" : "is not installed"} on the connector host. The mission is left unstarted; name an available provider.`,
80
+ available: installed,
81
+ };
82
+ }
73
83
  if (requested) {
74
84
  const spec = PROVIDERS.find((p) => p.id === requested || p.cli === requested);
75
85
  if (!spec) {
@@ -90,12 +100,19 @@ export function resolveProvider(requested, found) {
90
100
  return { state: "ok", provider: avail, explicit: true };
91
101
  }
92
102
  const first = PROVIDERS.map((s) => found.find((p) => p.id === s.id)).find((p) => p.installed && p.selectable_by_default);
93
- if (first)
103
+ if (first?.auth_evidence === "found")
94
104
  return { state: "ok", provider: first, explicit: false };
105
+ if (first) {
106
+ return {
107
+ state: "provider_unavailable",
108
+ message: `${first.name}, the default provider, shows no sign-in on the connector host. The mission is left unstarted; sign it in or name another provider.`,
109
+ available: installed,
110
+ };
111
+ }
95
112
  if (installed.length) {
96
113
  return {
97
114
  state: "provider_needs_explicit_selection",
98
- message: `Only providers that need an explicit request are installed (${installed.map((p) => p.id).join(", ")}). Name one in the request; none is chosen silently.`,
115
+ message: `Claude Code, the default provider, is not installed on the connector host, and the others run only by name (${installed.map((p) => p.id).join(", ")}). Name one in the request; none is chosen silently.`,
99
116
  available: installed,
100
117
  };
101
118
  }
@@ -129,7 +146,7 @@ export async function routerPreflight(env = process.env, fetchImpl = fetch) {
129
146
  if (!jev) {
130
147
  return {
131
148
  state: "unconfigured",
132
- note: `No ${JEV_KEY_NAMES.join(" or ")} in the connector's environment: model choice falls back to the explicit provider policy and the person's choice, never to a silent default.`,
149
+ note: `No ${JEV_KEY_NAMES.join(" or ")} in the connector's environment: a launch uses the configured Claude Code model and says so in its receipt.`,
133
150
  };
134
151
  }
135
152
  const where = { service: jev.service, key_name: jev.key_name, url: jev.base };