@yagni-app/code-staging 1.2.14-staging.2406.1 → 1.2.14-staging.2421.1

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/cli.js CHANGED
@@ -43,7 +43,7 @@ import { PAD_X } from "./padding.js";
43
43
  import { canPromptWorktreeCleanup, parseWorktreeFlag, validateWorktreeLaunchArgs, } from "./worktreeArgs.js";
44
44
  import { promptKeepOrRemoveWorktree } from "./worktreeExitPrompt.js";
45
45
  import { ensureShadowPiPackage } from "./piPackage.js";
46
- import { resolveExtensionPath, resolvePiCliPath, resolvePiPackageDir, resolveSessionWorktreePath } from "./paths.js";
46
+ import { resolveExtensionPath, resolvePiCliPath, resolvePiPackageDir, resolveSessionWorktreePath, } from "./paths.js";
47
47
  import { credentialsFromProfile, getActiveProfileName, listProfiles, migrateLegacyCredentials, persistProfileTokenRotation, profilePath, readActiveProfile, useProfile, } from "./profiles.js";
48
48
  // Present as "yagni" in process listings, not "node".
49
49
  process.title = DISTRIBUTION.commandName;
@@ -321,14 +321,10 @@ export async function spawnPiAndAwait(opts, resolvePiCli = resolvePiCliPath) {
321
321
  const { argv, env, remainingArgs, outputFormat, cwd } = opts;
322
322
  // For json/stream-json output, inject --mode json so pi emits NDJSON events.
323
323
  const userChoseMode = remainingArgs.some((a) => a === "--mode" || a.startsWith("--mode="));
324
- const childArgv = outputFormat === "text" || userChoseMode
325
- ? argv
326
- : [...argv, "--mode", "json"];
324
+ const childArgv = outputFormat === "text" || userChoseMode ? argv : [...argv, "--mode", "json"];
327
325
  // text + stream-json: inherit stdout (passthrough). json: pipe stdout so we
328
326
  // can post-process the NDJSON into a single result object.
329
- const stdio = outputFormat === "json"
330
- ? ["inherit", "pipe", "inherit"]
331
- : "inherit";
327
+ const stdio = outputFormat === "json" ? ["inherit", "pipe", "inherit"] : "inherit";
332
328
  const piCli = resolvePiCli();
333
329
  const startMs = Date.now();
334
330
  return await new Promise((resolve) => {
@@ -532,8 +528,13 @@ const IGNORED_PREVIEW = 5;
532
528
  * launcher must be able to render this even against a stale bundled extension.
533
529
  */
534
530
  export function previewIgnoredPaths(paths) {
535
- const preview = paths.slice(0, IGNORED_PREVIEW).map((path) => JSON.stringify(path)).join(", ");
536
- return paths.length > IGNORED_PREVIEW ? `${preview} (+${paths.length - IGNORED_PREVIEW} more)` : preview;
531
+ const preview = paths
532
+ .slice(0, IGNORED_PREVIEW)
533
+ .map((path) => JSON.stringify(path))
534
+ .join(", ");
535
+ return paths.length > IGNORED_PREVIEW
536
+ ? `${preview} (+${paths.length - IGNORED_PREVIEW} more)`
537
+ : preview;
537
538
  }
538
539
  /**
539
540
  * Pure: how the Remove option and its warning read given the pre-prompt scan.
@@ -547,7 +548,11 @@ export function removeOptionCopy(report) {
547
548
  if (report.error !== undefined) {
548
549
  // Never let "I could not look" render as the same clean prompt as "I looked
549
550
  // and there is nothing to lose". Removal re-checks and refuses on its own.
550
- return { notes: [`could not check what removal would discard: ${report.error.replace(/\s+/g, " ").trim()}`] };
551
+ return {
552
+ notes: [
553
+ `could not check what removal would discard: ${report.error.replace(/\s+/g, " ").trim()}`,
554
+ ],
555
+ };
551
556
  }
552
557
  const count = report.keepworthy.length;
553
558
  if (count === 0)
@@ -684,7 +689,7 @@ export const HELP_TEXT = [
684
689
  " yagni -w [name] Create/resume a worktree and enter a session there.",
685
690
  ' yagni -p "prompt" Print one response and exit (reads piped stdin too).',
686
691
  ' yagni -p "prompt" Use --output-format json for a machine-readable',
687
- ' --output-format json result object with tools, cost, guardian reviews.',
692
+ " --output-format json result object with tools, cost, guardian reviews.",
688
693
  " yagni login Authorize the active environment (device-code flow).",
689
694
  " yagni logout Revoke and clear the active environment's token.",
690
695
  " yagni doctor Check that everything is ready (green/red checklist).",
@@ -718,7 +723,8 @@ export const HELP_TEXT = [
718
723
  " yagni version Print the CLI version.",
719
724
  "",
720
725
  "Common agent flags (passed straight through):",
721
- " --model <tier> advanced (default) | standard | efficient | peak; /tier switches mid-session.",
726
+ " --model <lane> advanced (default) | standard | efficient | peak; /model (Ctrl+L) or /tier",
727
+ " switches mid-session, and /model also lists any models your workspace allows.",
722
728
  " --thinking <level> off | minimal | low | medium | high | xhigh | max",
723
729
  " --session <id> Open a specific session; --fork <id> branches one.",
724
730
  " --output-format <fmt> Output format: text (default), json, stream-json.",
@@ -7,6 +7,7 @@
7
7
  * diagnostics on stderr, e.g. why a /go run could not be recorded (HTTP status +
8
8
  * a token-free body excerpt); off by default and never required.
9
9
  */
10
+ import { type ChosenModelEntry } from "./modelChoice.js";
10
11
  /** A single model entry as returned by the YAGNI backend catalog endpoint. */
11
12
  export interface ModelEntry {
12
13
  id: string;
@@ -105,6 +106,12 @@ export interface CatalogResult {
105
106
  guardianTimeoutMs?: number;
106
107
  /** Number of attempts the backend makes (primary + one failover). */
107
108
  guardianMaxAttempts?: number;
109
+ /**
110
+ * The models the workspace allows a person to pick by name
111
+ * (models.customer_choice). Empty when the flag is off, on an older
112
+ * backend, and for a run's token; absent reads as empty.
113
+ */
114
+ chosenModels?: ChosenModelEntry[];
108
115
  }
109
116
  /**
110
117
  * Fetch the YAGNI model catalog at startup.
@@ -7,6 +7,7 @@
7
7
  * diagnostics on stderr, e.g. why a /go run could not be recorded (HTTP status +
8
8
  * a token-free body excerpt); off by default and never required.
9
9
  */
10
+ import { parseChosenModels } from "./modelChoice.js";
10
11
  import { resilientFetch } from "./resilientFetch.js";
11
12
  const DEFAULT_BASE_URL = "https://yagni.app";
12
13
  /**
@@ -87,15 +88,20 @@ export async function fetchCatalog(opts) {
87
88
  const data = (await res.json());
88
89
  return {
89
90
  models: data.models,
91
+ chosenModels: parseChosenModels(data.chosenModels),
90
92
  guardianEnabled: data.guardianEnabled !== false,
91
93
  judgmentLoopEnabled: data.judgmentLoopEnabled !== false,
92
94
  guardianStorage: data.guardianStorage === "raw" || data.guardianStorage === "hash"
93
95
  ? data.guardianStorage
94
96
  : "off",
95
- ...(typeof data.guardianTimeoutMs === "number" && Number.isFinite(data.guardianTimeoutMs) && data.guardianTimeoutMs > 0
97
+ ...(typeof data.guardianTimeoutMs === "number" &&
98
+ Number.isFinite(data.guardianTimeoutMs) &&
99
+ data.guardianTimeoutMs > 0
96
100
  ? { guardianTimeoutMs: data.guardianTimeoutMs }
97
101
  : {}),
98
- ...(typeof data.guardianMaxAttempts === "number" && Number.isSafeInteger(data.guardianMaxAttempts) && data.guardianMaxAttempts >= 1
102
+ ...(typeof data.guardianMaxAttempts === "number" &&
103
+ Number.isSafeInteger(data.guardianMaxAttempts) &&
104
+ data.guardianMaxAttempts >= 1
99
105
  ? { guardianMaxAttempts: data.guardianMaxAttempts }
100
106
  : {}),
101
107
  };
@@ -185,7 +191,10 @@ export function isDriverCaller(env = process.env) {
185
191
  * sanitizing client-side is what keeps the attribution instead of losing it.
186
192
  */
187
193
  export function sanitizeCallerSegment(name, maxLength = 64) {
188
- const cleaned = name.trim().toLowerCase().replace(/[^a-z0-9_.-]/g, "-");
194
+ const cleaned = name
195
+ .trim()
196
+ .toLowerCase()
197
+ .replace(/[^a-z0-9_.-]/g, "-");
189
198
  const trimmed = cleaned.slice(0, Math.max(0, maxLength));
190
199
  return trimmed || "agent";
191
200
  }
@@ -72,6 +72,7 @@ import { flushSpool as defaultFlushSpool, } from "./spool.js";
72
72
  import { makeAuthedFetch, makeTokenProvider } from "./tokenProvider.js";
73
73
  import { attributionHeaders, fetchCatalog as defaultFetchCatalog, fetchContextBrief as defaultFetchContextBrief, getToken, getTokenExpiresAt as defaultGetTokenExpiresAt, getWorkspaceId as defaultGetWorkspaceId, isDriverCaller, resolveBaseUrl, tokenExpiryNotice, } from "./config.js";
74
74
  import { buildYagniProvider } from "./provider.js";
75
+ import { chosenModelFallback } from "./modelChoice.js";
75
76
  import { orderDriverCatalog, registerStartTierGuard, registerTierCommand, trailReason, } from "./tierCommand.js";
76
77
  import { makeModelPickerListener } from "./modelPicker.js";
77
78
  import { registerChipEditor } from "./chipEditor.js";
@@ -335,7 +336,7 @@ export async function registerYagni(pi, deps = {}) {
335
336
  // after_provider_response event does NOT fire on a 401 (the OpenAI SDK throws
336
337
  // before onResponse is reached), so message_end is the only seam.
337
338
  let lastAuthRecovery = null;
338
- const { models: fullCatalog, guardianEnabled: workspaceGuardianEnabled, judgmentLoopEnabled: workspaceJudgmentLoopEnabled, guardianStorage: guardianStorageTier, guardianTimeoutMs: guardianTimeoutAdvertisedMs, guardianMaxAttempts: guardianMaxAttemptsAdvertised, } = await fetchCatalog({ baseUrl, getToken: getTokenFn, fetchImpl: authedFetch });
339
+ const { models: fullCatalog, guardianEnabled: workspaceGuardianEnabled, judgmentLoopEnabled: workspaceJudgmentLoopEnabled, guardianStorage: guardianStorageTier, guardianTimeoutMs: guardianTimeoutAdvertisedMs, guardianMaxAttempts: guardianMaxAttemptsAdvertised, chosenModels: advertisedChosenModels, } = await fetchCatalog({ baseUrl, getToken: getTokenFn, fetchImpl: authedFetch });
339
340
  // The judgment loop runs only when BOTH halves allow it: the developer's
340
341
  // user-tier config AND the workspace's admin-flipped flag. Either side off
341
342
  // severs the loop in both directions through the one `grounding` gate
@@ -377,7 +378,12 @@ export async function registerYagni(pi, deps = {}) {
377
378
  // — and there is no /model picker to keep tidy. Filtering there turns a
378
379
  // valid tier request into "no models match".
379
380
  const driver = isDriverCaller(env);
380
- const catalog = evalMode || !driver ? fullCatalog : orderDriverCatalog(fullCatalog);
381
+ // The models the workspace allows a person to pick by name
382
+ // (models.customer_choice; modelChoice.ts), after the lanes. A driver
383
+ // session only: a child or an eval lane names its lane and keeps our pick.
384
+ // Empty while the flag is off, so the registry is exactly the lanes.
385
+ const chosenModels = evalMode || !driver ? [] : (advertisedChosenModels ?? []);
386
+ const catalog = evalMode || !driver ? fullCatalog : [...orderDriverCatalog(fullCatalog), ...chosenModels];
381
387
  // YAG-471: the driver's own completions carry attribution headers read from
382
388
  // this process's env (YAGNI_SESSION_ID minted by the launcher; YAGNI_CALLER
383
389
  // defaults to "driver" when unset, i.e. every session that is not a /go
@@ -1440,11 +1446,24 @@ export async function registerYagni(pi, deps = {}) {
1440
1446
  registerTierCommand(pi);
1441
1447
  registerStartTierGuard(pi);
1442
1448
  }
1449
+ // A refused chosen model (the workspace no longer allows it, or nothing it
1450
+ // may use can serve it) moves the session back to YAGNI's pick with one
1451
+ // line, in the message_end guard below. Driver sessions with models listed only.
1452
+ const fallBackFromChosenModel = async (errorMessage, ctx) => {
1453
+ if (chosenModels.length === 0)
1454
+ return null;
1455
+ try {
1456
+ return await chosenModelFallback(pi, ctx, errorMessage);
1457
+ }
1458
+ catch {
1459
+ return null;
1460
+ }
1461
+ };
1443
1462
  // YAG-471: surface the backend's vision reroute header as a quiet notice
1444
1463
  // (see rerouteNotice.ts for the event/header contract). One notifier per
1445
1464
  // session dedupes on the from->to pair so a long session does not repeat
1446
1465
  // itself on every image turn.
1447
- const rerouteNotifier = new RerouteNotifier();
1466
+ const rerouteNotifier = new RerouteNotifier((id) => chosenModels.find((m) => m.id === id));
1448
1467
  pi.on("after_provider_response", (event, ctx) => {
1449
1468
  try {
1450
1469
  if (!ctx.hasUI)
@@ -1835,6 +1854,13 @@ export async function registerYagni(pi, deps = {}) {
1835
1854
  // post-replacement message, and dropping the marker would defeat the very
1836
1855
  // recovery this error exists to trigger.
1837
1856
  if (msg.stopReason === "error" && msg.errorMessage) {
1857
+ // models.customer_choice: the proxy refused the model the session
1858
+ // picked by name. Back to YAGNI's pick, said once, in place of the raw
1859
+ // 400 body. Its markers match none of pi's retryable patterns, so pi
1860
+ // has not retried it.
1861
+ const fellBack = await fallBackFromChosenModel(msg.errorMessage, ctx);
1862
+ if (fellBack)
1863
+ return { message: { ...msg, errorMessage: fellBack } };
1838
1864
  // YAG-500: a 401 from the model proxy means the session token expired
1839
1865
  // (or was revoked). Unlike tool 401s (handled by makeAuthedFetch), the
1840
1866
  // model completion path has no 401-retry seam — pi's retryProviderRequest
@@ -1979,7 +2005,7 @@ export async function registerYagni(pi, deps = {}) {
1979
2005
  // mount modelPicker.ts's panel. Driver sessions only, like /tier.
1980
2006
  if (!evalMode && driver && ctx.hasUI) {
1981
2007
  try {
1982
- ctx.ui?.onTerminalInput?.(makeModelPickerListener(pi, ctx, { footer: footerInvalidateHandle }));
2008
+ ctx.ui?.onTerminalInput?.(makeModelPickerListener(pi, ctx, { footer: footerInvalidateHandle, chosenModels }));
1983
2009
  }
1984
2010
  catch (err) {
1985
2011
  // The picker is a convenience over /tier; it must never break
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Model choice for a local session (the workspace flag
3
+ * `models.customer_choice`): the models a workspace allows, picked by name
4
+ * beside YAGNI's lanes.
5
+ *
6
+ * The backend lists them on `GET /api/yagni-code/models` as `chosenModels`,
7
+ * only while the flag is on. Each is registered with the `yagni` provider
8
+ * like a lane, under its wire id (`model/<catalog id>`), so `pi.setModel`
9
+ * switches to it, pi persists it the way it persists a lane, the footer and
10
+ * the desktop pill show its name, and every request names it as `model`.
11
+ * Subagents, /go stages and the advisor name their own lanes, so they keep
12
+ * YAGNI's picks.
13
+ *
14
+ * When the backend refuses a pick (the workspace no longer allows it, or no
15
+ * provider it may use can serve it), {@link chosenModelFallback} moves the
16
+ * session back to YAGNI's pick with a one-line notice. With the flag off the
17
+ * list is absent and nothing here does anything.
18
+ *
19
+ * Pure helpers first, wiring last, as in `tierCommand.ts`.
20
+ */
21
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
22
+ import type { ModelEntry } from "./config.js";
23
+ import { CHOSEN_MODEL_PREFIX } from "./tierCommand.js";
24
+ export { CHOSEN_MODEL_PREFIX };
25
+ /** One model a workspace allows, as `GET /api/yagni-code/models` lists it. */
26
+ export interface ChosenModelEntry extends ModelEntry {
27
+ /** Catalog id, e.g. "kimi-k3". `id` is the wire id, e.g. "model/kimi-k3". */
28
+ modelId: string;
29
+ maker: string;
30
+ /** More than one provider can serve it. */
31
+ hasBackup: boolean;
32
+ /** The lane its requests bill on. */
33
+ lane: "advanced" | "peak";
34
+ }
35
+ export declare function isChosenModelId(id: string | undefined): boolean;
36
+ /**
37
+ * Read `chosenModels` off a catalog response, keeping only well-formed
38
+ * entries. Absent or malformed reads as none: the lanes still work. PURE.
39
+ */
40
+ export declare function parseChosenModels(raw: unknown): ChosenModelEntry[];
41
+ /** The picker's second line for a model: who made it, where it bills, and whether it has a backup. PURE. */
42
+ export declare function chosenModelDescription(entry: Pick<ChosenModelEntry, "maker" | "lane" | "hasBackup">): string;
43
+ /** The picker's second line for a lane when models are listed beside it. PURE. */
44
+ export declare function lanePickDescription(blurb: string): string;
45
+ /**
46
+ * The chosen model `/model <arg>` names, matched on its name, catalog id or
47
+ * wire id in any case, or undefined. PURE.
48
+ */
49
+ export declare function findChosenModel(arg: string, entries: readonly ChosenModelEntry[]): ChosenModelEntry | undefined;
50
+ /** Why the backend refused a chosen model, read from a failed turn's error text. PURE. */
51
+ export type ChosenModelRefusal = "not_allowed" | "unavailable";
52
+ export declare function chosenModelRefusal(errorMessage: string | undefined): ChosenModelRefusal | null;
53
+ /** The one-line notice when a pick is refused and the session moves back to our pick. PURE. */
54
+ export declare function formatChosenModelFallback(name: string, refusal: ChosenModelRefusal, landed: boolean): string;
55
+ /** The notice when a switch to a chosen model lands. PURE. */
56
+ export declare function formatChosenModelSwitched(entry: Pick<ChosenModelEntry, "name" | "maker" | "lane">): string;
57
+ /** The slice of a context a switch needs (both command and session contexts satisfy it). */
58
+ export type ChosenSwitchContext = Pick<ExtensionContext, "model" | "modelRegistry" | "hasUI" | "ui">;
59
+ /**
60
+ * Move the session to a chosen model, the model picker's path for a model
61
+ * row and `/model <name>`. Mirrors `switchTier`: a switch that does not land
62
+ * is logged and named. Returns true when the model moved.
63
+ */
64
+ export declare function switchChosenModel(pi: ExtensionAPI, ctx: ChosenSwitchContext, entry: ChosenModelEntry): Promise<boolean>;
65
+ /**
66
+ * The backend refused the session's chosen model: move back to YAGNI's pick
67
+ * and say so in one line. Returns the text the failed turn should show in
68
+ * place of the raw error, or null when the error is not a refusal of the
69
+ * model the session is on (nothing is touched then). Never throws.
70
+ *
71
+ * The pick is undone for this session; the next session starts on YAGNI's
72
+ * pick anyway (the launcher opens every session on it).
73
+ */
74
+ export declare function chosenModelFallback(pi: ExtensionAPI, ctx: ChosenSwitchContext, errorMessage: string | undefined): Promise<string | null>;
75
+ /** The label a person reads for the session's model: a lane's name, else the model's name. PURE. */
76
+ export declare function sessionModelLabel(model: {
77
+ id: string;
78
+ name?: string;
79
+ } | undefined): string;
80
+ //# sourceMappingURL=modelChoice.d.ts.map
@@ -0,0 +1,215 @@
1
+ /**
2
+ * Model choice for a local session (the workspace flag
3
+ * `models.customer_choice`): the models a workspace allows, picked by name
4
+ * beside YAGNI's lanes.
5
+ *
6
+ * The backend lists them on `GET /api/yagni-code/models` as `chosenModels`,
7
+ * only while the flag is on. Each is registered with the `yagni` provider
8
+ * like a lane, under its wire id (`model/<catalog id>`), so `pi.setModel`
9
+ * switches to it, pi persists it the way it persists a lane, the footer and
10
+ * the desktop pill show its name, and every request names it as `model`.
11
+ * Subagents, /go stages and the advisor name their own lanes, so they keep
12
+ * YAGNI's picks.
13
+ *
14
+ * When the backend refuses a pick (the workspace no longer allows it, or no
15
+ * provider it may use can serve it), {@link chosenModelFallback} moves the
16
+ * session back to YAGNI's pick with a one-line notice. With the flag off the
17
+ * list is absent and nothing here does anything.
18
+ *
19
+ * Pure helpers first, wiring last, as in `tierCommand.ts`.
20
+ */
21
+ import { logEvent } from "./errorSink.js";
22
+ import { CHOSEN_MODEL_PREFIX, SESSION_START_TIER, TIER_LABEL, YAGNI_PROVIDER, isSelectableTier, trailReason, } from "./tierCommand.js";
23
+ export { CHOSEN_MODEL_PREFIX };
24
+ export function isChosenModelId(id) {
25
+ return !!id && id.startsWith(CHOSEN_MODEL_PREFIX) && id.length > CHOSEN_MODEL_PREFIX.length;
26
+ }
27
+ function isFiniteNumber(value) {
28
+ return typeof value === "number" && Number.isFinite(value);
29
+ }
30
+ /**
31
+ * Read `chosenModels` off a catalog response, keeping only well-formed
32
+ * entries. Absent or malformed reads as none: the lanes still work. PURE.
33
+ */
34
+ export function parseChosenModels(raw) {
35
+ if (!Array.isArray(raw))
36
+ return [];
37
+ const entries = [];
38
+ for (const item of raw) {
39
+ if (!item || typeof item !== "object")
40
+ continue;
41
+ const m = item;
42
+ const cost = m.cost;
43
+ if (typeof m.id !== "string" ||
44
+ !isChosenModelId(m.id) ||
45
+ typeof m.modelId !== "string" ||
46
+ typeof m.name !== "string" ||
47
+ !m.name ||
48
+ typeof m.maker !== "string" ||
49
+ (m.lane !== "advanced" && m.lane !== "peak") ||
50
+ !isFiniteNumber(m.contextWindow) ||
51
+ !isFiniteNumber(m.maxTokens) ||
52
+ !cost ||
53
+ !isFiniteNumber(cost.input) ||
54
+ !isFiniteNumber(cost.output) ||
55
+ !isFiniteNumber(cost.cacheRead) ||
56
+ !isFiniteNumber(cost.cacheWrite)) {
57
+ continue;
58
+ }
59
+ entries.push({
60
+ id: m.id,
61
+ modelId: m.modelId,
62
+ name: m.name,
63
+ maker: m.maker,
64
+ hasBackup: m.hasBackup === true,
65
+ lane: m.lane,
66
+ reasoning: m.reasoning === true,
67
+ contextWindow: m.contextWindow,
68
+ maxTokens: m.maxTokens,
69
+ input: Array.isArray(m.input) && m.input.includes("image") ? ["text", "image"] : ["text"],
70
+ cost: {
71
+ input: cost.input,
72
+ output: cost.output,
73
+ cacheRead: cost.cacheRead,
74
+ cacheWrite: cost.cacheWrite,
75
+ },
76
+ });
77
+ }
78
+ return entries;
79
+ }
80
+ /** The picker's second line for a model: who made it, where it bills, and whether it has a backup. PURE. */
81
+ export function chosenModelDescription(entry) {
82
+ const parts = [entry.maker, `billed on the ${TIER_LABEL[entry.lane]} lane`];
83
+ if (!entry.hasBackup)
84
+ parts.push("no backup provider");
85
+ return parts.join(" · ");
86
+ }
87
+ /** The picker's second line for a lane when models are listed beside it. PURE. */
88
+ export function lanePickDescription(blurb) {
89
+ return `YAGNI's pick, ${blurb}`;
90
+ }
91
+ /**
92
+ * The chosen model `/model <arg>` names, matched on its name, catalog id or
93
+ * wire id in any case, or undefined. PURE.
94
+ */
95
+ export function findChosenModel(arg, entries) {
96
+ const want = arg.trim().toLowerCase();
97
+ if (!want)
98
+ return undefined;
99
+ return entries.find((e) => e.name.toLowerCase() === want ||
100
+ e.modelId.toLowerCase() === want ||
101
+ e.id.toLowerCase() === want);
102
+ }
103
+ export function chosenModelRefusal(errorMessage) {
104
+ if (!errorMessage)
105
+ return null;
106
+ if (/\bmodel_not_allowed\b/.test(errorMessage))
107
+ return "not_allowed";
108
+ if (/\bmodel_unavailable\b/.test(errorMessage))
109
+ return "unavailable";
110
+ return null;
111
+ }
112
+ /** The one-line notice when a pick is refused and the session moves back to our pick. PURE. */
113
+ export function formatChosenModelFallback(name, refusal, landed) {
114
+ const why = refusal === "not_allowed"
115
+ ? `${name} is no longer allowed in this workspace`
116
+ : `${name} has no provider this workspace can use right now`;
117
+ const lane = TIER_LABEL[SESSION_START_TIER];
118
+ return landed
119
+ ? `${why}, so this session is back on YAGNI's pick (${lane}). Send your message again to continue.`
120
+ : `${why}. Pick a lane or another model with /model.`;
121
+ }
122
+ /** The notice when a switch to a chosen model lands. PURE. */
123
+ export function formatChosenModelSwitched(entry) {
124
+ return `Session model is now ${entry.name} (${entry.maker}, billed on the ${TIER_LABEL[entry.lane]} lane).`;
125
+ }
126
+ /**
127
+ * Move the session to a chosen model, the model picker's path for a model
128
+ * row and `/model <name>`. Mirrors `switchTier`: a switch that does not land
129
+ * is logged and named. Returns true when the model moved.
130
+ */
131
+ export async function switchChosenModel(pi, ctx, entry) {
132
+ const notify = (message, type) => {
133
+ if (ctx.hasUI)
134
+ ctx.ui.notify(message, type);
135
+ };
136
+ if (ctx.model?.id === entry.id) {
137
+ notify(`Already on ${entry.name}.`, "info");
138
+ return false;
139
+ }
140
+ const model = ctx.modelRegistry.find(YAGNI_PROVIDER, entry.id);
141
+ let ok = false;
142
+ let reason = model ? "set_model_rejected" : "registry_miss";
143
+ if (model) {
144
+ try {
145
+ ok = await pi.setModel(model);
146
+ }
147
+ catch (err) {
148
+ reason = trailReason(err);
149
+ }
150
+ }
151
+ if (!ok) {
152
+ logEvent({
153
+ source: "tier",
154
+ level: "warn",
155
+ event: "model_switch_failed",
156
+ fields: { from: ctx.model?.id ?? "unknown", to: entry.id, reason },
157
+ });
158
+ }
159
+ notify(ok
160
+ ? formatChosenModelSwitched(entry)
161
+ : `Could not switch to ${entry.name}. Still on ${ctx.model?.name ?? ctx.model?.id ?? "the current model"}.`, ok ? "info" : "error");
162
+ return ok;
163
+ }
164
+ /**
165
+ * The backend refused the session's chosen model: move back to YAGNI's pick
166
+ * and say so in one line. Returns the text the failed turn should show in
167
+ * place of the raw error, or null when the error is not a refusal of the
168
+ * model the session is on (nothing is touched then). Never throws.
169
+ *
170
+ * The pick is undone for this session; the next session starts on YAGNI's
171
+ * pick anyway (the launcher opens every session on it).
172
+ */
173
+ export async function chosenModelFallback(pi, ctx, errorMessage) {
174
+ const refusal = chosenModelRefusal(errorMessage);
175
+ const current = ctx.model;
176
+ if (!refusal || !current || !isChosenModelId(current.id))
177
+ return null;
178
+ const name = current.name || current.id;
179
+ let landed = false;
180
+ let reason = "registry_miss";
181
+ try {
182
+ const ours = ctx.modelRegistry.find(YAGNI_PROVIDER, SESSION_START_TIER);
183
+ if (ours) {
184
+ landed = await pi.setModel(ours);
185
+ reason = landed ? "ok" : "set_model_rejected";
186
+ }
187
+ }
188
+ catch (err) {
189
+ reason = trailReason(err);
190
+ }
191
+ logEvent({
192
+ source: "tier",
193
+ level: landed ? "info" : "warn",
194
+ event: landed ? "chosen_model_fell_back" : "chosen_model_fallback_failed",
195
+ fields: { from: current.id, to: SESSION_START_TIER, refusal, reason },
196
+ });
197
+ const notice = formatChosenModelFallback(name, refusal, landed);
198
+ try {
199
+ if (ctx.hasUI)
200
+ ctx.ui.notify(notice, "warning");
201
+ }
202
+ catch {
203
+ /* the trail entry is the durable half; a dead UI cannot undo it */
204
+ }
205
+ return notice;
206
+ }
207
+ /** The label a person reads for the session's model: a lane's name, else the model's name. PURE. */
208
+ export function sessionModelLabel(model) {
209
+ if (!model)
210
+ return "unknown";
211
+ if (isSelectableTier(model.id))
212
+ return TIER_LABEL[model.id];
213
+ return model.name || model.id;
214
+ }
215
+ //# sourceMappingURL=modelChoice.js.map
@@ -27,19 +27,33 @@
27
27
  * trail entries and notices are one set. Headless (`--mode rpc`, print) is
28
28
  * untouched: the desktop composer has its own pill, and there is no terminal
29
29
  * input to listen to.
30
+ *
31
+ * Model choice (models.customer_choice, modelChoice.ts): when the workspace
32
+ * allows models by name, they follow the lanes in the same panel, each with
33
+ * its maker, the lane it bills on, and whether it has a backup provider; the
34
+ * lanes then read as YAGNI's pick. `/model <name>` switches to one directly.
35
+ * With nothing listed the panel is exactly the lanes.
30
36
  */
31
37
  import type { ExtensionAPI, ExtensionContext, TerminalInputHandler } from "@earendil-works/pi-coding-agent";
32
38
  import { Container } from "@earendil-works/pi-tui";
33
39
  import type { FooterInvalidateHandle } from "./footer.js";
40
+ import { type ChosenModelEntry } from "./modelChoice.js";
34
41
  import type { RenderTheme } from "./subagentRender.js";
35
42
  import { type SelectableTier } from "./tierCommand.js";
36
43
  /** The panel's title line. The provider word is the product's, capitalized. */
37
44
  export declare const MODEL_PICKER_TITLE = "YAGNI model tier";
45
+ /** The title when the workspace's models are listed after the lanes. */
46
+ export declare const MODEL_PICKER_TITLE_WITH_MODELS = "YAGNI lanes and models";
38
47
  /** The panel's footer line: the keys that work, nothing about providers. */
39
48
  export declare const MODEL_PICKER_FOOTER = "up/down to navigate \u00B7 Enter to select \u00B7 Esc to close";
40
49
  /** One row of the picker. PURE data; the panel renders it. */
41
50
  export interface PickerRow {
42
- tier: SelectableTier;
51
+ /** What the panel resolves with: a lane id, or a chosen model's wire id. */
52
+ value: string;
53
+ /** Set on a lane row. */
54
+ tier?: SelectableTier;
55
+ /** Set on a model row. */
56
+ model?: ChosenModelEntry;
43
57
  /** The capitalized lane name, with {@link CURRENT_MARK} when in play. */
44
58
  label: string;
45
59
  description: string;
@@ -51,13 +65,16 @@ export interface PickerRow {
51
65
  * one must not get a row that fails on select), with the rung in play
52
66
  * marked. PURE.
53
67
  */
54
- export declare function pickerRows(available: readonly string[], currentId: string | undefined): PickerRow[];
68
+ export declare function pickerRows(available: readonly string[], currentId: string | undefined, chosen?: readonly ChosenModelEntry[]): PickerRow[];
55
69
  /** What an Enter on the editor's current text is asking for. */
56
70
  export type ModelCommand = {
57
71
  kind: "open";
58
72
  } | {
59
73
  kind: "set";
60
74
  tier: SelectableTier;
75
+ } | {
76
+ kind: "pick";
77
+ model: ChosenModelEntry;
61
78
  };
62
79
  /**
63
80
  * Read a `/model` line the way pi's own ladder would have: a bare `/model`
@@ -67,7 +84,7 @@ export type ModelCommand = {
67
84
  * nothing). Anything that is not a `/model` line is `null` and passes
68
85
  * through to the editor untouched. PURE.
69
86
  */
70
- export declare function parseModelCommand(editorText: string): ModelCommand | null;
87
+ export declare function parseModelCommand(editorText: string, chosen?: readonly ChosenModelEntry[]): ModelCommand | null;
71
88
  /** True for the keystroke pi binds to its own selector (`app.model.select`). */
72
89
  export declare function isModelPickerKey(data: string): boolean;
73
90
  /**
@@ -79,13 +96,15 @@ export declare function isModelPickerKey(data: string): boolean;
79
96
  export declare class ModelPickerPanel extends Container {
80
97
  private readonly list;
81
98
  private readonly done;
82
- constructor(rows: readonly PickerRow[], theme: RenderTheme, done: (tier?: SelectableTier) => void);
99
+ constructor(rows: readonly PickerRow[], theme: RenderTheme, done: (value?: string) => void);
83
100
  handleInput(data: string): void;
84
101
  }
85
102
  /** What the picker needs from the session beyond the pi API. */
86
103
  export interface ModelPickerDeps {
87
104
  /** Repaints the footer after a switch so its tier segment follows. */
88
105
  footer?: Pick<FooterInvalidateHandle, "requestRender">;
106
+ /** The models the workspace allows by name (modelChoice.ts); absent or empty lists the lanes only. */
107
+ chosenModels?: readonly ChosenModelEntry[];
89
108
  }
90
109
  /** The slice of the session context the picker reads. */
91
110
  type PickerContext = Pick<ExtensionContext, "model" | "modelRegistry" | "hasUI" | "ui">;
@@ -94,8 +113,8 @@ type PickerContext = Pick<ExtensionContext, "model" | "modelRegistry" | "hasUI"
94
113
  * panel has closed and any switch has settled.
95
114
  */
96
115
  export declare function openModelPicker(pi: ExtensionAPI, ctx: PickerContext, deps?: ModelPickerDeps): Promise<void>;
97
- /** Mount the panel and resolve with the chosen rung, or undefined on Esc. */
98
- export declare function pickTier(ctx: PickerContext): Promise<SelectableTier | undefined>;
116
+ /** Mount the panel and resolve with the chosen lane or model id, or undefined on Esc. */
117
+ export declare function pickChoice(ctx: PickerContext, deps?: ModelPickerDeps): Promise<string | undefined>;
99
118
  /**
100
119
  * The notice when either path the listener runs (opening the picker, or the
101
120
  * direct switch behind `/model <rung>`) throws. Worded for both: what failed
@@ -27,13 +27,24 @@
27
27
  * trail entries and notices are one set. Headless (`--mode rpc`, print) is
28
28
  * untouched: the desktop composer has its own pill, and there is no terminal
29
29
  * input to listen to.
30
+ *
31
+ * Model choice (models.customer_choice, modelChoice.ts): when the workspace
32
+ * allows models by name, they follow the lanes in the same panel, each with
33
+ * its maker, the lane it bills on, and whether it has a backup provider; the
34
+ * lanes then read as YAGNI's pick. `/model <name>` switches to one directly.
35
+ * With nothing listed the panel is exactly the lanes.
30
36
  */
31
37
  import { Box, Container, Key, SelectList, Text, matchesKey, } from "@earendil-works/pi-tui";
32
38
  import { logEvent } from "./errorSink.js";
39
+ import { chosenModelDescription, findChosenModel, lanePickDescription, switchChosenModel, } from "./modelChoice.js";
33
40
  import { PanelBorder } from "./panelBorder.js";
34
41
  import { SELECTABLE_TIERS, TIER_BLURB, TIER_LABEL, YAGNI_PROVIDER, isSelectableTier, switchTier, trailReason, } from "./tierCommand.js";
35
42
  /** The panel's title line. The provider word is the product's, capitalized. */
36
43
  export const MODEL_PICKER_TITLE = "YAGNI model tier";
44
+ /** The title when the workspace's models are listed after the lanes. */
45
+ export const MODEL_PICKER_TITLE_WITH_MODELS = "YAGNI lanes and models";
46
+ /** The most rows visible at once; the list scrolls past it. */
47
+ const MAX_VISIBLE_ROWS = 10;
37
48
  /** The panel's footer line: the keys that work, nothing about providers. */
38
49
  export const MODEL_PICKER_FOOTER = "up/down to navigate · Enter to select · Esc to close";
39
50
  /** The mark on the rung in play. */
@@ -44,17 +55,29 @@ const CURRENT_MARK = " ✓";
44
55
  * one must not get a row that fails on select), with the rung in play
45
56
  * marked. PURE.
46
57
  */
47
- export function pickerRows(available, currentId) {
58
+ export function pickerRows(available, currentId, chosen = []) {
48
59
  const have = new Set(available);
49
- return SELECTABLE_TIERS.filter((tier) => have.has(tier)).map((tier) => {
60
+ const lanes = SELECTABLE_TIERS.filter((tier) => have.has(tier)).map((tier) => {
50
61
  const current = tier === currentId;
51
62
  return {
63
+ value: tier,
52
64
  tier,
53
65
  label: current ? `${TIER_LABEL[tier]}${CURRENT_MARK}` : TIER_LABEL[tier],
54
- description: TIER_BLURB[tier],
66
+ description: chosen.length > 0 ? lanePickDescription(TIER_BLURB[tier]) : TIER_BLURB[tier],
67
+ current,
68
+ };
69
+ });
70
+ const models = chosen.map((model) => {
71
+ const current = model.id === currentId;
72
+ return {
73
+ value: model.id,
74
+ model,
75
+ label: current ? `${model.name}${CURRENT_MARK}` : model.name,
76
+ description: chosenModelDescription(model),
55
77
  current,
56
78
  };
57
79
  });
80
+ return [...lanes, ...models];
58
81
  }
59
82
  /**
60
83
  * Read a `/model` line the way pi's own ladder would have: a bare `/model`
@@ -64,14 +87,17 @@ export function pickerRows(available, currentId) {
64
87
  * nothing). Anything that is not a `/model` line is `null` and passes
65
88
  * through to the editor untouched. PURE.
66
89
  */
67
- export function parseModelCommand(editorText) {
90
+ export function parseModelCommand(editorText, chosen = []) {
68
91
  const text = editorText.trim();
69
92
  if (text === "/model")
70
93
  return { kind: "open" };
71
94
  if (!text.startsWith("/model "))
72
95
  return null;
73
96
  const arg = text.slice("/model ".length).trim().toLowerCase();
74
- return isSelectableTier(arg) ? { kind: "set", tier: arg } : { kind: "open" };
97
+ if (isSelectableTier(arg))
98
+ return { kind: "set", tier: arg };
99
+ const model = findChosenModel(arg, chosen);
100
+ return model ? { kind: "pick", model } : { kind: "open" };
75
101
  }
76
102
  /** True for the keystroke pi binds to its own selector (`app.model.select`). */
77
103
  export function isModelPickerKey(data) {
@@ -101,22 +127,24 @@ export class ModelPickerPanel extends Container {
101
127
  super();
102
128
  this.done = done;
103
129
  const items = rows.map((row) => ({
104
- value: row.tier,
130
+ value: row.value,
105
131
  label: row.label,
106
132
  description: row.description,
107
133
  }));
108
- this.list = new SelectList(items, SELECTABLE_TIERS.length, selectListTheme(theme));
134
+ const values = new Set(rows.map((row) => row.value));
135
+ const hasModels = rows.some((row) => row.model !== undefined);
136
+ this.list = new SelectList(items, hasModels ? Math.min(rows.length, MAX_VISIBLE_ROWS) : SELECTABLE_TIERS.length, selectListTheme(theme));
109
137
  // The rung in play is where the cursor starts, never the first row: a
110
138
  // stray Enter re-selects what the session already drives on.
111
139
  const currentIndex = rows.findIndex((row) => row.current);
112
140
  if (currentIndex >= 0)
113
141
  this.list.setSelectedIndex(currentIndex);
114
142
  this.list.onSelect = (item) => {
115
- this.done(isSelectableTier(item.value) ? item.value : undefined);
143
+ this.done(values.has(item.value) ? item.value : undefined);
116
144
  };
117
145
  this.list.onCancel = () => this.done();
118
146
  const content = new Box(CONTENT_PADDING_X, 0);
119
- content.addChild(new Text(theme.bold(MODEL_PICKER_TITLE), 0, 0));
147
+ content.addChild(new Text(theme.bold(hasModels ? MODEL_PICKER_TITLE_WITH_MODELS : MODEL_PICKER_TITLE), 0, 0));
120
148
  content.addChild(new Text("", 0, 0));
121
149
  content.addChild(this.list);
122
150
  content.addChild(new Text(theme.fg("muted", MODEL_PICKER_FOOTER), 0, 1));
@@ -138,15 +166,19 @@ export class ModelPickerPanel extends Container {
138
166
  * panel has closed and any switch has settled.
139
167
  */
140
168
  export async function openModelPicker(pi, ctx, deps = {}) {
141
- const tier = await pickTier(ctx);
142
- if (!tier)
169
+ const value = await pickChoice(ctx, deps);
170
+ if (!value)
143
171
  return;
144
- await applyTier(pi, ctx, tier, deps);
172
+ await applyChoice(pi, ctx, value, deps);
145
173
  }
146
- /** Mount the panel and resolve with the chosen rung, or undefined on Esc. */
147
- export async function pickTier(ctx) {
174
+ /** The listed models the registry actually holds: a row must never fail on select. */
175
+ function registeredModels(ctx, deps) {
176
+ return (deps.chosenModels ?? []).filter((model) => ctx.modelRegistry.find(YAGNI_PROVIDER, model.id) !== undefined);
177
+ }
178
+ /** Mount the panel and resolve with the chosen lane or model id, or undefined on Esc. */
179
+ export async function pickChoice(ctx, deps = {}) {
148
180
  const available = SELECTABLE_TIERS.filter((tier) => ctx.modelRegistry.find(YAGNI_PROVIDER, tier) !== undefined);
149
- const rows = pickerRows(available, ctx.model?.id);
181
+ const rows = pickerRows(available, ctx.model?.id, registeredModels(ctx, deps));
150
182
  if (rows.length === 0) {
151
183
  if (ctx.hasUI)
152
184
  ctx.ui.notify("No YAGNI model tiers are available on this workspace.", "error");
@@ -154,9 +186,17 @@ export async function pickTier(ctx) {
154
186
  }
155
187
  return ctx.ui.custom((_tui, theme, _keybindings, done) => new ModelPickerPanel(rows, theme, done));
156
188
  }
157
- /** Switch through the shared path and repaint the footer's tier segment. */
158
- async function applyTier(pi, ctx, tier, deps) {
159
- await switchTier(pi, ctx, tier);
189
+ /** Switch through the shared path (a lane's or a model's) and repaint the footer's segment. */
190
+ async function applyChoice(pi, ctx, value, deps) {
191
+ if (isSelectableTier(value)) {
192
+ await switchTier(pi, ctx, value);
193
+ }
194
+ else {
195
+ const model = registeredModels(ctx, deps).find((entry) => entry.id === value);
196
+ if (!model)
197
+ return;
198
+ await switchChosenModel(pi, ctx, model);
199
+ }
160
200
  deps.footer?.requestRender();
161
201
  }
162
202
  /**
@@ -196,7 +236,12 @@ export function makeModelPickerListener(pi, ctx, deps = {}) {
196
236
  busy = phase;
197
237
  void work()
198
238
  .catch((err) => {
199
- logEvent({ source: "tier", level: "warn", event: "model_picker_failed", fields: { reason: trailReason(err) } });
239
+ logEvent({
240
+ source: "tier",
241
+ level: "warn",
242
+ event: "model_picker_failed",
243
+ fields: { reason: trailReason(err) },
244
+ });
200
245
  try {
201
246
  if (ctx.hasUI)
202
247
  ctx.ui.notify(MODEL_PICKER_FAILED_NOTICE, "error");
@@ -212,11 +257,11 @@ export function makeModelPickerListener(pi, ctx, deps = {}) {
212
257
  // The panel phase ends when the panel closes; the switch that follows a
213
258
  // choice runs with the editor focused again, so it is its own phase.
214
259
  const openThenSwitch = () => run("panel", async () => {
215
- const tier = await pickTier(ctx);
216
- if (!tier)
260
+ const value = await pickChoice(ctx, deps);
261
+ if (!value)
217
262
  return;
218
263
  busy = "switch";
219
- await applyTier(pi, ctx, tier, deps);
264
+ await applyChoice(pi, ctx, value, deps);
220
265
  });
221
266
  return (data) => {
222
267
  if (isModelPickerKey(data)) {
@@ -226,14 +271,17 @@ export function makeModelPickerListener(pi, ctx, deps = {}) {
226
271
  }
227
272
  if (busy === "panel" || !matchesKey(data, Key.enter))
228
273
  return undefined;
229
- const command = parseModelCommand(ctx.ui.getEditorText());
274
+ const command = parseModelCommand(ctx.ui.getEditorText(), registeredModels(ctx, deps));
230
275
  if (!command)
231
276
  return undefined;
232
277
  if (busy === "switch")
233
278
  return { consume: true };
234
279
  ctx.ui.setEditorText("");
235
280
  if (command.kind === "set") {
236
- run("switch", () => applyTier(pi, ctx, command.tier, deps));
281
+ run("switch", () => applyChoice(pi, ctx, command.tier, deps));
282
+ }
283
+ else if (command.kind === "pick") {
284
+ run("switch", () => applyChoice(pi, ctx, command.model.id, deps));
237
285
  }
238
286
  else {
239
287
  openThenSwitch();
@@ -111,8 +111,9 @@ export declare function commitType(ticket: string, ticketBrief?: string): "fix"
111
111
  export declare function commitTitle(ticket: string, ticketBrief?: string): string;
112
112
  /**
113
113
  * The title a run with a plan and no ticket title commits under (the cloud
114
- * session reads its ticket from a file): the line under the plan's Goal
115
- * heading, else its first line of prose. Undefined when the plan has neither.
114
+ * session reads its ticket from a file): the line under the plan's Goal or
115
+ * Summary heading, else its first line of prose. Undefined when the plan has
116
+ * neither.
116
117
  */
117
118
  export declare function planTitle(planText: string | undefined): string | undefined;
118
119
  /**
@@ -125,9 +126,10 @@ export declare function deriveCommitScope(paths: string[]): string | undefined;
125
126
  /** `<type>(<scope>): <title>`, dropping the parens when no scope was derivable. */
126
127
  export declare function commitSubject(type: "fix" | "feat", scope: string | undefined, title: string): string;
127
128
  /**
128
- * A 2-3 sentence summary of the plan stage's output (markdown flattened, first
129
- * three sentences, capped). No LLM call — this is a deterministic excerpt. A
130
- * missing plan (a resumed run skipped the build half) degrades honestly.
129
+ * A 2-3 sentence summary of the plan stage's output (markdown flattened from
130
+ * its Goal or Summary heading on, first three sentences, capped). No LLM call
131
+ * — this is a deterministic excerpt. A missing plan (a resumed run skipped the
132
+ * build half) degrades honestly.
131
133
  */
132
134
  export declare function summarizePlan(planText: string | undefined, ticket: string): string;
133
135
  /**
@@ -83,20 +83,43 @@ export function commitTitle(ticket, ticketBrief) {
83
83
  title = title.slice(echo.length).trim() || ticket;
84
84
  return title.length > TITLE_MAX ? title.slice(0, TITLE_MAX).trimEnd() : title;
85
85
  }
86
+ /**
87
+ * The heading a plan states its goal under: `## Goal` as a plan stage writes
88
+ * it, or `## Summary` as the host renders an approved plan into the session's
89
+ * `plan.md` (`renderPlanMarkdown` in the backend's `workItems/planPage.ts`).
90
+ * That file opens with the host's line naming the plan's version ("Plan v1,
91
+ * as a person approved it."), which is no title: every yak pull request's
92
+ * provenance commit was named after it (#3046, #3051, #3052, #3163).
93
+ */
94
+ const GOAL_HEADING = /^#+\s*(?:goal|summary)\b/i;
95
+ /** The plan from under its goal's heading on, or the whole plan when it has none. */
96
+ function fromGoal(planText) {
97
+ const lines = planText.split("\n");
98
+ const goal = lines.findIndex((line) => GOAL_HEADING.test(line.trim()));
99
+ return goal >= 0 ? lines.slice(goal + 1).join("\n") : planText;
100
+ }
86
101
  /**
87
102
  * The title a run with a plan and no ticket title commits under (the cloud
88
- * session reads its ticket from a file): the line under the plan's Goal
89
- * heading, else its first line of prose. Undefined when the plan has neither.
103
+ * session reads its ticket from a file): the line under the plan's Goal or
104
+ * Summary heading, else its first line of prose. Undefined when the plan has
105
+ * neither.
90
106
  */
91
107
  export function planTitle(planText) {
92
108
  const lines = (planText ?? "").split("\n").map((line) => line.trim());
93
109
  const prose = (from) => lines.slice(from).find((line) => line && !line.startsWith("#") && !line.startsWith("```"));
94
- const goal = lines.findIndex((line) => /^#+\s*goal\b/i.test(line));
110
+ const goal = lines.findIndex((line) => GOAL_HEADING.test(line));
95
111
  const line = (goal >= 0 ? prose(goal + 1) : undefined) ?? prose(0);
96
- return (line
112
+ const title = line
97
113
  ?.replace(/^(?:[-*+]|\d+[.)])\s+/, "")
98
114
  .replace(/`/g, "")
99
- .trim() || undefined);
115
+ .trim();
116
+ if (!title)
117
+ return undefined;
118
+ if (title.length <= TITLE_MAX)
119
+ return title;
120
+ // A Summary runs on past the cap: the title is its first sentence, which
121
+ // ends on a word, never on an abbreviation's stop ("the U.S. Billing cap").
122
+ return title.match(/^.+?[a-z0-9][a-z0-9)][.!?](?=\s+[A-Z])/)?.[0] ?? title;
100
123
  }
101
124
  /**
102
125
  * A conventional-commit scope from the run's changed paths: the package name
@@ -124,12 +147,13 @@ export function commitSubject(type, scope, title) {
124
147
  return scope ? `${type}(${scope}): ${title}` : `${type}: ${title}`;
125
148
  }
126
149
  /**
127
- * A 2-3 sentence summary of the plan stage's output (markdown flattened, first
128
- * three sentences, capped). No LLM call — this is a deterministic excerpt. A
129
- * missing plan (a resumed run skipped the build half) degrades honestly.
150
+ * A 2-3 sentence summary of the plan stage's output (markdown flattened from
151
+ * its Goal or Summary heading on, first three sentences, capped). No LLM call
152
+ * — this is a deterministic excerpt. A missing plan (a resumed run skipped the
153
+ * build half) degrades honestly.
130
154
  */
131
155
  export function summarizePlan(planText, ticket) {
132
- const flat = (planText ?? "")
156
+ const flat = fromGoal(planText ?? "")
133
157
  .replace(/^#+\s*/gm, "")
134
158
  .replace(/^\s*(?:[-*+]|\d+[.)])\s+/gm, "")
135
159
  .replace(/`{1,3}/g, "")
@@ -26,8 +26,17 @@ export type HeaderMap = Record<string, string | undefined>;
26
26
  * known reason (vision or policy; see KNOWN_REASONS).
27
27
  */
28
28
  export declare function parseReroute(headers: HeaderMap): Reroute | null;
29
+ /** What the notice needs to know about a model picked by name (modelChoice.ts). */
30
+ export interface RerouteChosenModel {
31
+ name: string;
32
+ /** The lane its requests bill on. */
33
+ lane: string;
34
+ }
29
35
  export declare class RerouteNotifier {
36
+ private readonly chosen;
30
37
  private readonly seen;
38
+ /** `chosen` names a picked model's wire id (`model/<id>`); absent, none is known. */
39
+ constructor(chosen?: (id: string) => RerouteChosenModel | undefined);
31
40
  observe(headers: HeaderMap): string | null;
32
41
  }
33
42
  //# sourceMappingURL=rerouteNotice.d.ts.map
@@ -54,8 +54,19 @@ export function parseReroute(headers) {
54
54
  * proxy actually bills.
55
55
  */
56
56
  const TIER_LADDER = ["efficient", "standard", "advanced", "peak"];
57
+ const LANE_LABEL = {
58
+ efficient: "Efficient",
59
+ standard: "Standard",
60
+ advanced: "Advanced",
61
+ peak: "Peak",
62
+ };
57
63
  export class RerouteNotifier {
64
+ chosen;
58
65
  seen = new Set();
66
+ /** `chosen` names a picked model's wire id (`model/<id>`); absent, none is known. */
67
+ constructor(chosen = () => undefined) {
68
+ this.chosen = chosen;
69
+ }
59
70
  observe(headers) {
60
71
  const reroute = parseReroute(headers);
61
72
  if (!reroute)
@@ -66,6 +77,20 @@ export class RerouteNotifier {
66
77
  if (this.seen.has(key))
67
78
  return null;
68
79
  this.seen.add(key);
80
+ // A model picked by name that cannot read images: the proxy served that
81
+ // one request on our pick. It bills the cheaper of the picked model's lane
82
+ // and the lane that served, as any vision reroute does.
83
+ if (reroute.from.startsWith("model/")) {
84
+ const picked = this.chosen(reroute.from);
85
+ const served = LANE_LABEL[reroute.to] ?? reroute.to;
86
+ const name = picked?.name ?? "The model you picked";
87
+ if (!picked)
88
+ return `${name} cannot read images, so YAGNI's pick on the ${served} lane read this one.`;
89
+ const billed = TIER_LADDER.indexOf(reroute.to) < TIER_LADDER.indexOf(picked.lane)
90
+ ? reroute.to
91
+ : picked.lane;
92
+ return `${name} cannot read images, so YAGNI's pick on the ${served} lane read this one. Billed as ${LANE_LABEL[billed] ?? billed}.`;
93
+ }
69
94
  // balanced is a ROUTING POLICY, never a price (rateCard.ts's
70
95
  // assertBillableTier throws if it ever reaches pricing) — for a balanced
71
96
  // reroute the bill IS the resolved tier (`reroute.to`; yagniCodeV1.ts's
@@ -71,7 +71,9 @@ export declare const ATTR_GEN_AI_TOOL_TYPE = "gen_ai.tool.type";
71
71
  export declare const ATTR_ERROR_TYPE = "error.type";
72
72
  export declare const ATTR_HTTP_STATUS_CODE = "http.response.status_code";
73
73
  /** The provider name every span carries. The backing model is never exposed:
74
- * `gen_ai.request.model` is the opaque YAGNI tier id. */
74
+ * `gen_ai.request.model` is the opaque YAGNI tier id, or, for a model the
75
+ * person picked by name (models.customer_choice), its catalog wire id
76
+ * (`model/kimi-k3`), which names the model they chose and never a provider. */
75
77
  export declare const GEN_AI_PROVIDER = "yagni";
76
78
  export declare const SPAN_INTERACTION = "yagni_code.interaction";
77
79
  export declare const SPAN_TURN = "yagni_code.turn";
@@ -73,7 +73,9 @@ export const ATTR_GEN_AI_TOOL_TYPE = "gen_ai.tool.type";
73
73
  export const ATTR_ERROR_TYPE = "error.type";
74
74
  export const ATTR_HTTP_STATUS_CODE = "http.response.status_code";
75
75
  /** The provider name every span carries. The backing model is never exposed:
76
- * `gen_ai.request.model` is the opaque YAGNI tier id. */
76
+ * `gen_ai.request.model` is the opaque YAGNI tier id, or, for a model the
77
+ * person picked by name (models.customer_choice), its catalog wire id
78
+ * (`model/kimi-k3`), which names the model they chose and never a provider. */
77
79
  export const GEN_AI_PROVIDER = "yagni";
78
80
  // ── Span names (Claude Code's beta trace tree, prefixed) ────────────────────
79
81
  export const SPAN_INTERACTION = `${PREFIX}.interaction`;
@@ -48,6 +48,12 @@
48
48
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
49
49
  /** The provider the tier models are registered under (see provider.ts). */
50
50
  export declare const YAGNI_PROVIDER = "yagni";
51
+ /**
52
+ * How a model picked by name is registered and sent: this prefix and the
53
+ * catalog id (`model/kimi-k3`). The backend's `CHOSEN_MODEL_WIRE_PREFIX`
54
+ * (`@yagni/shared`); keep them equal. See modelChoice.ts.
55
+ */
56
+ export declare const CHOSEN_MODEL_PREFIX = "model/";
51
57
  /**
52
58
  * The rungs a driver session may sit on, in PICKER ORDER: the rate card's
53
59
  * ladder, strongest first (`peak`, `advanced`, `standard`, `efficient`).
@@ -116,7 +122,7 @@ export type TierRequest = {
116
122
  };
117
123
  export declare function parseTierArg(args: string): TierRequest;
118
124
  /** The `/tier` status line: what is in play, and what else is reachable. PURE. */
119
- export declare function formatTierStatus(currentId: string | undefined): string;
125
+ export declare function formatTierStatus(currentId: string | undefined, currentName?: string): string;
120
126
  /** The notice shown when a switch lands. PURE. */
121
127
  export declare function formatTierSwitched(tier: SelectableTier): string;
122
128
  /** Upper bound on a trail `reason`, in characters. */
@@ -49,6 +49,12 @@ import { logEvent } from "./errorSink.js";
49
49
  import { scrubSecrets } from "./pipeline/scrubSecrets.js";
50
50
  /** The provider the tier models are registered under (see provider.ts). */
51
51
  export const YAGNI_PROVIDER = "yagni";
52
+ /**
53
+ * How a model picked by name is registered and sent: this prefix and the
54
+ * catalog id (`model/kimi-k3`). The backend's `CHOSEN_MODEL_WIRE_PREFIX`
55
+ * (`@yagni/shared`); keep them equal. See modelChoice.ts.
56
+ */
57
+ export const CHOSEN_MODEL_PREFIX = "model/";
52
58
  /**
53
59
  * The rungs a driver session may sit on, in PICKER ORDER: the rate card's
54
60
  * ladder, strongest first (`peak`, `advanced`, `standard`, `efficient`).
@@ -142,11 +148,16 @@ export function parseTierArg(args) {
142
148
  return { kind: "unknown", input: raw };
143
149
  }
144
150
  /** The `/tier` status line: what is in play, and what else is reachable. PURE. */
145
- export function formatTierStatus(currentId) {
151
+ export function formatTierStatus(currentId, currentName) {
146
152
  const current = isSelectableTier(currentId) ? currentId : undefined;
153
+ // A model picked by name (models.customer_choice; modelChoice.ts) is not a
154
+ // rung but is a legitimate place to be, so it is named, not flagged.
155
+ const chosen = !current && currentId?.startsWith(CHOSEN_MODEL_PREFIX) ? currentName || currentId : undefined;
147
156
  const head = current
148
157
  ? `This session is on ${TIER_LABEL[current]} (${TIER_BLURB[current]}).`
149
- : `This session is on "${currentId ?? "unknown"}", which is not one of the selectable rungs.`;
158
+ : chosen
159
+ ? `This session is on ${chosen}, a model your workspace allows.`
160
+ : `This session is on "${currentId ?? "unknown"}", which is not one of the selectable rungs.`;
150
161
  const options = SELECTABLE_TIERS.map((t) => ` /tier ${t} - ${TIER_LABEL[t]}: ${TIER_BLURB[t]}`).join("\n");
151
162
  return `${head}\nSwitch with /tier <rung>, or pick from /model (Ctrl+L):\n${options}\nEvery session starts on ${TIER_LABEL[SESSION_START_TIER]}.`;
152
163
  }
@@ -312,7 +323,7 @@ export function registerTierCommand(pi) {
312
323
  };
313
324
  const request = parseTierArg(args);
314
325
  if (request.kind === "show") {
315
- notify(formatTierStatus(ctx.model?.id), "info");
326
+ notify(formatTierStatus(ctx.model?.id, ctx.model?.name), "info");
316
327
  return;
317
328
  }
318
329
  if (request.kind === "unknown") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yagni-app/code-staging",
3
- "version": "1.2.14-staging.2406.1",
3
+ "version": "1.2.14-staging.2421.1",
4
4
  "description": "YAGNI Code: a terminal coding agent that already knows your company. One YAGNI login routes the model and grounds the agent in your team's context.",
5
5
  "license": "SEE LICENSE IN LICENSE.md",
6
6
  "author": "YAGNI, Inc. <jack@yagni.app> (https://yagni.app)",
@@ -58,5 +58,5 @@
58
58
  "turndown": "^7.2.4",
59
59
  "typebox": "^1.3.15"
60
60
  },
61
- "yagniSourceSha": "028be749156c881690fc451262308059c79524ac"
61
+ "yagniSourceSha": "22aa037b2ba9574c14b2d99ce5a46ae05ccbbe71"
62
62
  }