@sayknow-cli/coding-agent 0.5.23 → 0.5.24

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/CHANGELOG.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
- ## [0.5.23] - 2026-09-20
5
+ ## [0.5.24] - 2026-09-21
6
6
 
7
7
  ## [0.5.22] - 2026-09-19
8
8
 
@@ -2421,6 +2421,42 @@ export declare const SETTINGS_SCHEMA: {
2421
2421
  readonly description: "Add a model-backed second stage to workflow routing. The keyword table already runs on every turn and costs nothing; this handles the phrasings it cannot express, which is most wording that is not a literal match. Costs one small model call, and only on turns the keyword table did not already answer. Any failure falls back to keyword-only behaviour, but a successful answer can also select a different workflow than the deep-interview ambiguity detector would have.";
2422
2422
  };
2423
2423
  };
2424
+ /**
2425
+ * Per-spawn model routing for subagents.
2426
+ *
2427
+ * A role's configured model is a standing guess about the average task that
2428
+ * role gets; this moves it when a particular assignment is clearly harder or
2429
+ * clearly more mechanical. Subagents only — routing the main loop's model
2430
+ * mid-session invalidates the prompt cache, which on a long context costs
2431
+ * more than the cheaper tier saves.
2432
+ *
2433
+ * Needs `decisions.enabled` and at least two tiers configured. Without both
2434
+ * it never fires and the configured role models are used unchanged.
2435
+ */
2436
+ readonly "task.modelRouting.enabled": {
2437
+ readonly type: "boolean";
2438
+ readonly default: false;
2439
+ readonly ui: {
2440
+ readonly tab: "tasks";
2441
+ readonly label: "Route subagent models per task";
2442
+ readonly description: "Ask a cheap model how demanding each subagent assignment is, and move that spawn to a cheaper or stronger model. Needs typed decisions on and the tier models below set. Moving to a cheaper model requires more confidence than moving to a stronger one, because being wrong about it costs a retry.";
2443
+ };
2444
+ };
2445
+ /** Cheapest tier. Mechanical, local, single-file work. */
2446
+ readonly "task.modelRouting.fastModel": {
2447
+ readonly type: "string";
2448
+ readonly default: "";
2449
+ };
2450
+ /** Middle tier. Ordinary engineering against an existing pattern. */
2451
+ readonly "task.modelRouting.balancedModel": {
2452
+ readonly type: "string";
2453
+ readonly default: "";
2454
+ };
2455
+ /** Most capable tier. Unclear cause, cross-cutting design, hard to undo. */
2456
+ readonly "task.modelRouting.deepModel": {
2457
+ readonly type: "string";
2458
+ readonly default: "";
2459
+ };
2424
2460
  readonly "ttsr.enabled": {
2425
2461
  readonly type: "boolean";
2426
2462
  readonly default: true;
@@ -0,0 +1,44 @@
1
+ import type { DecisionService } from "./index";
2
+ /** Ordered cheapest to most capable. The order *is* the policy's direction. */
3
+ export declare const TASK_TIERS: readonly ["fast", "balanced", "deep"];
4
+ export type TaskTier = (typeof TASK_TIERS)[number];
5
+ export interface TaskTierModels {
6
+ fast?: string;
7
+ balanced?: string;
8
+ deep?: string;
9
+ }
10
+ export interface TaskRoutingPolicy {
11
+ tiers: TaskTierModels;
12
+ /**
13
+ * Bar to move to a more capable model. Being wrong costs money.
14
+ */
15
+ minUpgradeConfidence: number;
16
+ /**
17
+ * Bar to move to a cheaper model. Being wrong means real work handled by a
18
+ * model too small for it, which is discovered late and costs a retry — so
19
+ * this bar sits higher than the upgrade bar on purpose.
20
+ */
21
+ minDowngradeConfidence: number;
22
+ }
23
+ export declare const DEFAULT_TASK_ROUTING_POLICY: Omit<TaskRoutingPolicy, "tiers">;
24
+ export interface TaskRoutingRequest {
25
+ agentName: string;
26
+ /** The assignment text the subagent will act on. */
27
+ assignment: string;
28
+ /** Whatever the role is configured to use today, used as the direction baseline. */
29
+ currentModel: string | undefined;
30
+ signal?: AbortSignal;
31
+ }
32
+ export interface TaskRoutingResult {
33
+ model: string;
34
+ tier: TaskTier;
35
+ reason: string;
36
+ }
37
+ /**
38
+ * Decide the model for one subagent spawn, or null to leave the configured one alone.
39
+ *
40
+ * Every failure path returns null: no tiers configured, decisions disabled, no
41
+ * backend, a timeout, an answer outside the enum. A subagent that runs on its
42
+ * configured model is the status quo, and the status quo is always acceptable.
43
+ */
44
+ export declare function routeTaskModel(service: DecisionService, policy: TaskRoutingPolicy, request: TaskRoutingRequest): Promise<TaskRoutingResult | null>;
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@sayknow-cli/coding-agent",
4
- "version": "0.5.23",
4
+ "version": "0.5.24",
5
5
  "description": "Sayknow-CLI CLI with read, bash, edit, write tools and session management",
6
6
  "homepage": "https://sayknow-cli.com",
7
7
  "author": "jaybeyond",
@@ -54,12 +54,12 @@
54
54
  "@agentclientprotocol/sdk": "1.3.0",
55
55
  "@babel/parser": "^7.29.3",
56
56
  "@mozilla/readability": "^0.6.0",
57
- "@sayknow-cli/stats": "0.5.23",
58
- "@sayknow-cli/agent-core": "0.5.23",
59
- "@sayknow-cli/ai": "0.5.23",
60
- "@sayknow-cli/natives": "0.5.23",
61
- "@sayknow-cli/tui": "0.5.23",
62
- "@sayknow-cli/utils": "0.5.23",
57
+ "@sayknow-cli/stats": "0.5.24",
58
+ "@sayknow-cli/agent-core": "0.5.24",
59
+ "@sayknow-cli/ai": "0.5.24",
60
+ "@sayknow-cli/natives": "0.5.24",
61
+ "@sayknow-cli/tui": "0.5.24",
62
+ "@sayknow-cli/utils": "0.5.24",
63
63
  "@puppeteer/browsers": "^2.13.0",
64
64
  "@types/turndown": "5.0.6",
65
65
  "@xterm/headless": "^6.0.0",
@@ -2011,6 +2011,35 @@ export const SETTINGS_SCHEMA = {
2011
2011
  },
2012
2012
  },
2013
2013
 
2014
+ /**
2015
+ * Per-spawn model routing for subagents.
2016
+ *
2017
+ * A role's configured model is a standing guess about the average task that
2018
+ * role gets; this moves it when a particular assignment is clearly harder or
2019
+ * clearly more mechanical. Subagents only — routing the main loop's model
2020
+ * mid-session invalidates the prompt cache, which on a long context costs
2021
+ * more than the cheaper tier saves.
2022
+ *
2023
+ * Needs `decisions.enabled` and at least two tiers configured. Without both
2024
+ * it never fires and the configured role models are used unchanged.
2025
+ */
2026
+ "task.modelRouting.enabled": {
2027
+ type: "boolean",
2028
+ default: false,
2029
+ ui: {
2030
+ tab: "tasks",
2031
+ label: "Route subagent models per task",
2032
+ description:
2033
+ "Ask a cheap model how demanding each subagent assignment is, and move that spawn to a cheaper or stronger model. Needs typed decisions on and the tier models below set. Moving to a cheaper model requires more confidence than moving to a stronger one, because being wrong about it costs a retry.",
2034
+ },
2035
+ },
2036
+ /** Cheapest tier. Mechanical, local, single-file work. */
2037
+ "task.modelRouting.fastModel": { type: "string", default: "" },
2038
+ /** Middle tier. Ordinary engineering against an existing pattern. */
2039
+ "task.modelRouting.balancedModel": { type: "string", default: "" },
2040
+ /** Most capable tier. Unclear cause, cross-cutting design, hard to undo. */
2041
+ "task.modelRouting.deepModel": { type: "string", default: "" },
2042
+
2014
2043
  // TTSR
2015
2044
  "ttsr.enabled": {
2016
2045
  type: "boolean",
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Pick the model a subagent runs on from the work it was handed.
3
+ *
4
+ * A role's configured model is a standing guess about the *average* task that
5
+ * role gets. It cannot be right for every one: the same executor is handed both
6
+ * a one-line rename and a migration across twelve files. This asks about the
7
+ * actual assignment and moves the model when the answer is clear enough.
8
+ *
9
+ * Only subagents. The main loop's model is deliberately out of scope — changing
10
+ * it mid-session invalidates the prompt cache, and on a long context re-caching
11
+ * routinely costs more than the cheaper tier saves. A subagent starts with its
12
+ * own context, so there is nothing to invalidate.
13
+ */
14
+ import { logger } from "@sayknow-cli/utils";
15
+ import type { DecisionService } from "./index";
16
+ import type { Question } from "./types";
17
+
18
+ /** Ordered cheapest to most capable. The order *is* the policy's direction. */
19
+ export const TASK_TIERS = ["fast", "balanced", "deep"] as const;
20
+ export type TaskTier = (typeof TASK_TIERS)[number];
21
+
22
+ export interface TaskTierModels {
23
+ fast?: string;
24
+ balanced?: string;
25
+ deep?: string;
26
+ }
27
+
28
+ export interface TaskRoutingPolicy {
29
+ tiers: TaskTierModels;
30
+ /**
31
+ * Bar to move to a more capable model. Being wrong costs money.
32
+ */
33
+ minUpgradeConfidence: number;
34
+ /**
35
+ * Bar to move to a cheaper model. Being wrong means real work handled by a
36
+ * model too small for it, which is discovered late and costs a retry — so
37
+ * this bar sits higher than the upgrade bar on purpose.
38
+ */
39
+ minDowngradeConfidence: number;
40
+ }
41
+
42
+ export const DEFAULT_TASK_ROUTING_POLICY: Omit<TaskRoutingPolicy, "tiers"> = {
43
+ // Deliberately higher than the reference implementation's 0.3/0.6. That one
44
+ // assumes a frontier default with a cheap tier to fall to, so "up" is the
45
+ // rare move. Here the configured role models are already chosen per role, so
46
+ // overriding one needs a stronger signal in either direction.
47
+ minUpgradeConfidence: 0.5,
48
+ minDowngradeConfidence: 0.75,
49
+ };
50
+
51
+ /**
52
+ * The questions describe the *work*, never a model name.
53
+ *
54
+ * Naming models in the criteria would bind the classifier to one lineup and
55
+ * make every model swap a prompt change. It also invites the model to reason
56
+ * about price, which is not what it is good at.
57
+ */
58
+ function buildQuestions(): Record<string, Question> {
59
+ return {
60
+ tier: {
61
+ type: "choice",
62
+ instructions: "How demanding is this assignment?",
63
+ criteria: {
64
+ fast: "Mechanical and local. A rename, a typo, a one-file edit, running a command and reporting what it printed.",
65
+ balanced: "Ordinary engineering. Several files, an existing pattern to follow, normal debugging.",
66
+ deep: "Hard or high-stakes. Unclear cause, cross-cutting design, subtle correctness, or work that is hard to undo.",
67
+ },
68
+ },
69
+ risky: {
70
+ type: "noul",
71
+ instructions:
72
+ "Does this assignment touch production, money, credentials, published releases, or state that cannot be undone?",
73
+ },
74
+ };
75
+ }
76
+
77
+ export interface TaskRoutingRequest {
78
+ agentName: string;
79
+ /** The assignment text the subagent will act on. */
80
+ assignment: string;
81
+ /** Whatever the role is configured to use today, used as the direction baseline. */
82
+ currentModel: string | undefined;
83
+ signal?: AbortSignal;
84
+ }
85
+
86
+ export interface TaskRoutingResult {
87
+ model: string;
88
+ tier: TaskTier;
89
+ reason: string;
90
+ }
91
+
92
+ /** Where a concrete model id sits in the ladder, or null when it is not one of ours. */
93
+ function rankOf(model: string | undefined, tiers: TaskTierModels): number | null {
94
+ if (!model) return null;
95
+ const index = TASK_TIERS.findIndex(tier => tiers[tier] && matchesModel(tiers[tier] as string, model));
96
+ return index === -1 ? null : index;
97
+ }
98
+
99
+ /**
100
+ * Compare a configured tier model against the role's current selector.
101
+ *
102
+ * Selectors carry a thinking suffix (`provider/id:high`) that the tier table
103
+ * may or may not repeat, so compare the part before it.
104
+ */
105
+ function matchesModel(a: string, b: string): boolean {
106
+ const base = (value: string) => value.split(":")[0]?.trim().toLowerCase() ?? "";
107
+ return base(a) === base(b);
108
+ }
109
+
110
+ /**
111
+ * Is a move from `current` to `wanted` allowed at this confidence?
112
+ *
113
+ * A backend that cannot report a calibrated confidence may only move a request
114
+ * **up**. Spending less on an unmeasured hunch is the bad trade: the upgrade's
115
+ * worst case is an overpriced answer, the downgrade's is a wrong one.
116
+ */
117
+ function allowed(
118
+ wanted: number,
119
+ current: number | null,
120
+ confidence: number | undefined,
121
+ calibrated: boolean,
122
+ policy: TaskRoutingPolicy,
123
+ ): boolean {
124
+ if (current !== null && wanted === current) return false;
125
+ const isDowngrade = current !== null && wanted < current;
126
+ if (!calibrated || confidence === undefined) return !isDowngrade;
127
+ return confidence >= (isDowngrade ? policy.minDowngradeConfidence : policy.minUpgradeConfidence);
128
+ }
129
+
130
+ /**
131
+ * Decide the model for one subagent spawn, or null to leave the configured one alone.
132
+ *
133
+ * Every failure path returns null: no tiers configured, decisions disabled, no
134
+ * backend, a timeout, an answer outside the enum. A subagent that runs on its
135
+ * configured model is the status quo, and the status quo is always acceptable.
136
+ */
137
+ export async function routeTaskModel(
138
+ service: DecisionService,
139
+ policy: TaskRoutingPolicy,
140
+ request: TaskRoutingRequest,
141
+ ): Promise<TaskRoutingResult | null> {
142
+ const configured = TASK_TIERS.filter(tier => policy.tiers[tier]);
143
+ // One tier is not a ladder; with nothing to move between there is no decision
144
+ // worth paying a model call for.
145
+ if (configured.length < 2) return null;
146
+
147
+ const assignment = request.assignment.trim();
148
+ if (assignment.length < 24) return null;
149
+
150
+ const result = await service.decide({
151
+ state: `Agent: ${request.agentName}\n\nAssignment:\n${assignment.slice(0, 4_000)}`,
152
+ questions: buildQuestions(),
153
+ signal: request.signal,
154
+ });
155
+ if (!result) return null;
156
+
157
+ const answer = result.answers.tier;
158
+ if (answer?.type !== "choice") return null;
159
+ let tier = TASK_TIERS.find(candidate => candidate === answer.choice);
160
+ if (!tier) return null;
161
+
162
+ // Work that cannot be undone takes the most capable tier available and skips
163
+ // the confidence bars — this one is not a confidence question. It may only
164
+ // ever raise the tier, never lower it, or "this is risky" would end up
165
+ // *downgrading* an assignment already running deep.
166
+ const riskAnswer = result.answers.risky;
167
+ const forcedByRisk = riskAnswer?.type === "noul" && riskAnswer.noul > 0.7;
168
+ if (forcedByRisk) {
169
+ const deepest = configured[configured.length - 1] as TaskTier;
170
+ const currentRank = rankOf(request.currentModel, policy.tiers);
171
+ const wantedRank = Math.max(TASK_TIERS.indexOf(deepest), currentRank ?? 0);
172
+ tier = TASK_TIERS[wantedRank] as TaskTier;
173
+ }
174
+
175
+ const model = policy.tiers[tier];
176
+ if (!model || (request.currentModel && matchesModel(model, request.currentModel))) return null;
177
+
178
+ const currentRank = rankOf(request.currentModel, policy.tiers);
179
+ const wantedRank = TASK_TIERS.indexOf(tier);
180
+ if (!forcedByRisk && !allowed(wantedRank, currentRank, answer.confidence, result.calibrated, policy)) {
181
+ logger.debug("decisions/task-routing: below the bar, keeping the configured model", {
182
+ agent: request.agentName,
183
+ wanted: tier,
184
+ current: request.currentModel,
185
+ confidence: answer.confidence,
186
+ calibrated: result.calibrated,
187
+ });
188
+ return null;
189
+ }
190
+
191
+ const reason = forcedByRisk
192
+ ? `${tier}, forced by risk`
193
+ : `${tier} (confidence ${answer.confidence?.toFixed(2) ?? "n/d"})`;
194
+ logger.debug("decisions/task-routing: routed", { agent: request.agentName, model, reason });
195
+ return { model, tier, reason };
196
+ }
package/src/task/index.ts CHANGED
@@ -17,7 +17,7 @@ import * as os from "node:os";
17
17
  import path from "node:path";
18
18
  import type { AgentTool, AgentToolResult, AgentToolUpdateCallback } from "@sayknow-cli/agent-core";
19
19
  import type { Model, Usage } from "@sayknow-cli/ai";
20
- import { $pickenv, prompt, Snowflake } from "@sayknow-cli/utils";
20
+ import { $pickenv, logger, prompt, Snowflake } from "@sayknow-cli/utils";
21
21
  import type { ToolSession } from "..";
22
22
  import { AsyncJobManager, OwnerSubagentShutdownError, type ResumeRunner } from "../async";
23
23
  import { resolveAgentModelPatterns } from "../config/model-resolver";
@@ -461,6 +461,61 @@ export class TaskTool implements AgentTool<TaskToolSchemaInstance, TaskToolDetai
461
461
  return this.session.settings.get("task.simple");
462
462
  }
463
463
 
464
+ /**
465
+ * Pick a model for this spawn from the assignment, or null to keep the configured one.
466
+ *
467
+ * Opt-in twice over: `decisions.enabled` must be on *and* at least two tier
468
+ * models configured. That double gate is deliberate — a user who set explicit
469
+ * per-role models chose them on purpose, and silently overriding those from a
470
+ * classifier would be a worse default than doing nothing.
471
+ *
472
+ * One decision per spawn, not per task: every task in a call runs on the same
473
+ * agent and the same model, so asking per task would pay N times for a value
474
+ * that can only be set once.
475
+ */
476
+ async #routeSpawnModel(
477
+ agentName: string,
478
+ tasks: ReadonlyArray<{ description?: string; assignment?: string }> | undefined,
479
+ currentModel: string | readonly string[] | undefined,
480
+ ): Promise<string | undefined> {
481
+ if (!this.session.settings.get("task.modelRouting.enabled")) return undefined;
482
+ const tiers = {
483
+ fast: this.session.settings.get("task.modelRouting.fastModel") || undefined,
484
+ balanced: this.session.settings.get("task.modelRouting.balancedModel") || undefined,
485
+ deep: this.session.settings.get("task.modelRouting.deepModel") || undefined,
486
+ };
487
+ if (Object.values(tiers).filter(Boolean).length < 2) return undefined;
488
+
489
+ const assignment = (tasks ?? [])
490
+ .map(task => [task.description, task.assignment].filter(Boolean).join("\n"))
491
+ .filter(Boolean)
492
+ .join("\n\n");
493
+ if (!assignment) return undefined;
494
+
495
+ try {
496
+ const { createDecisionService } = await import("../decisions");
497
+ const { DEFAULT_TASK_ROUTING_POLICY, routeTaskModel } = await import("../decisions/task-routing");
498
+ const registry = this.session.modelRegistry;
499
+ if (!registry) return undefined;
500
+ const routed = await routeTaskModel(
501
+ createDecisionService({ registry, settings: this.session.settings, enabled: true }),
502
+ { ...DEFAULT_TASK_ROUTING_POLICY, tiers },
503
+ // A role may be configured with a fallback chain; the first entry is what it
504
+ // actually runs on, so that is the baseline the direction is measured from.
505
+ {
506
+ agentName,
507
+ assignment,
508
+ currentModel: Array.isArray(currentModel) ? currentModel[0] : currentModel,
509
+ },
510
+ );
511
+ return routed?.model;
512
+ } catch (error) {
513
+ // Routing is an optimisation. A failure here must never stop a spawn.
514
+ logger.debug("task: spawn model routing failed", { agent: agentName, error: String(error) });
515
+ return undefined;
516
+ }
517
+ }
518
+
464
519
  /**
465
520
  * Create a TaskTool instance.
466
521
  * Repository authority is captured from session cwd *before* agent discovery so
@@ -1114,9 +1169,14 @@ export class TaskTool implements AgentTool<TaskToolSchemaInstance, TaskToolDetai
1114
1169
  // Apply per-agent model override from settings (highest priority)
1115
1170
  const agentModelOverrides = this.session.settings.get("task.agentModelOverrides");
1116
1171
  const settingsModelOverride = agentModelOverrides[agentName];
1172
+ // Per-spawn routing sits *above* the configured role model but uses it as the
1173
+ // baseline: the decision is "is this particular assignment heavier or lighter
1174
+ // than what this role normally gets", not "pick a model from scratch". Declining
1175
+ // leaves the configured value exactly as it was.
1176
+ const routedModelOverride = await this.#routeSpawnModel(agentName, boundParams.tasks, settingsModelOverride);
1117
1177
  const parentActiveModelPattern = this.session.getActiveModelString?.();
1118
1178
  const modelOverride = resolveAgentModelPatterns({
1119
- settingsOverride: settingsModelOverride,
1179
+ settingsOverride: routedModelOverride ?? settingsModelOverride,
1120
1180
  agentModel: effectiveAgent.model,
1121
1181
  settings: this.session.settings,
1122
1182
  activeModelPattern: parentActiveModelPattern,