dal-code 1.0.13 → 1.0.14

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.
Files changed (47) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  3. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  4. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  5. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  6. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  7. package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
  8. package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
  9. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  10. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  11. package/dist/node_modules/@dalcode/dal-router/LICENSE +21 -0
  12. package/dist/node_modules/@dalcode/dal-router/package.json +36 -0
  13. package/dist/node_modules/@dalcode/dal-router/src/classifier.ts +80 -0
  14. package/dist/node_modules/@dalcode/dal-router/src/commands.ts +104 -0
  15. package/dist/node_modules/@dalcode/dal-router/src/config.ts +137 -0
  16. package/dist/node_modules/@dalcode/dal-router/src/features.ts +85 -0
  17. package/dist/node_modules/@dalcode/dal-router/src/index.ts +236 -0
  18. package/dist/node_modules/@dalcode/dal-router/src/router.ts +150 -0
  19. package/dist/node_modules/@dalcode/dal-router/src/runtime.ts +88 -0
  20. package/dist/node_modules/@dalcode/dal-router/src/small-model.ts +36 -0
  21. package/dist/node_modules/@dalcode/dal-router/src/subagent.ts +58 -0
  22. package/dist/node_modules/@dalcode/dal-router/src/tiers.ts +187 -0
  23. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  24. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  25. package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
  26. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  27. package/dist/node_modules/@earendil-works/chord/package.json +1 -1
  28. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  29. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  30. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  31. package/dist/node_modules/@earendil-works/pi-client/package.json +2 -2
  32. package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
  33. package/dist/node_modules/@earendil-works/pi-server/package.json +3 -3
  34. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/package.json +3 -3
  35. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  36. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  37. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  38. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  39. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  40. package/examples/extensions/gondolin/package-lock.json +2 -2
  41. package/examples/extensions/gondolin/package.json +1 -1
  42. package/examples/extensions/sandbox/package-lock.json +2 -2
  43. package/examples/extensions/sandbox/package.json +1 -1
  44. package/examples/extensions/with-deps/package-lock.json +2 -2
  45. package/examples/extensions/with-deps/package.json +1 -1
  46. package/npm-shrinkwrap.json +2 -2
  47. package/package.json +1 -1
@@ -0,0 +1,236 @@
1
+ /**
2
+ * dal-router: the model factory. Grades every turn (L1/L2/L3) and routes it
3
+ * to a tiered model pool — small tasks land on cheap models, heavy work keeps
4
+ * the high-performance tier, and auxiliary jobs (subagents, compaction)
5
+ * default to the cheapest capable model.
6
+ *
7
+ * Design contract (docs/MODEL-FACTORY.md):
8
+ * - extension-only, zero engine changes; every failure fail-opens to the
9
+ * user's current model
10
+ * - main-conversation routing is opt-in (/factory auto); auxiliary routing
11
+ * (subagent, compaction) is on by default
12
+ * - decisions are visible: /factory status | levels | pool, plus the
13
+ * "factory" status line
14
+ */
15
+
16
+ import { t } from "@dalcode/dal-pi-kit";
17
+ import {
18
+ type ExtensionAPI,
19
+ type ExtensionCommandContext,
20
+ type ExtensionContext,
21
+ generateSummaryWithUsage,
22
+ } from "@earendil-works/pi-coding-agent";
23
+ import { fuzzyFilter } from "@earendil-works/pi-tui";
24
+ import { classifyWithSmallModel } from "./classifier.ts";
25
+ import { runFactoryCommand } from "./commands.ts";
26
+ import { estimateTokens } from "./features.ts";
27
+ import {
28
+ autoRouteActive,
29
+ clearUnavailable,
30
+ config,
31
+ configWarning,
32
+ markUnavailable,
33
+ registry,
34
+ registryStale,
35
+ reloadConfig,
36
+ router,
37
+ setRegistry,
38
+ unavailableSet,
39
+ } from "./runtime.ts";
40
+ import { pickSmallModel } from "./small-model.ts";
41
+
42
+ type AnyModel = NonNullable<ExtensionContext["model"]>;
43
+
44
+ const GATEWAY_PROVIDER = "deepailab";
45
+
46
+ /** Builds the tier registry from what the session currently knows: every
47
+ * deepailab model the deepailab extension refreshed into the registry at
48
+ * session start — the latest catalog without a second request — plus any
49
+ * factory.json-named ids that are still present. */
50
+ function buildRegistryFrom(ctx: ExtensionContext): void {
51
+ // All deepailab models currently registered (cost and window come from the
52
+ // gateway catalog forwarded at registration time).
53
+ const models = (ctx.modelRegistry?.getAvailable?.() ?? [])
54
+ .filter((model) => model.provider === GATEWAY_PROVIDER)
55
+ .map((model) => {
56
+ const cost = model.cost;
57
+ const costPerMtok =
58
+ cost && typeof cost.input === "number" && typeof cost.output === "number"
59
+ ? (cost.input + cost.output) / 2
60
+ : 0;
61
+ return {
62
+ id: model.id,
63
+ provider: GATEWAY_PROVIDER,
64
+ contextWindow: model.contextWindow ?? 128_000,
65
+ maxTokens: model.maxTokens ?? 8192,
66
+ reasoning: Boolean(model.reasoning),
67
+ costPerMtok,
68
+ };
69
+ });
70
+ if (models.length === 0) return;
71
+ setRegistry(models);
72
+ }
73
+
74
+ export default function (pi: ExtensionAPI) {
75
+ pi.on("session_start", async (_event, ctx: ExtensionContext) => {
76
+ reloadConfig();
77
+ clearUnavailable();
78
+ const warning = configWarning();
79
+ if (warning) process.stderr.write(`dal-router: ${warning}\n`);
80
+ buildRegistryFrom(ctx);
81
+ });
82
+
83
+ pi.on("before_agent_start", async (event, ctx: ExtensionContext) => {
84
+ const factory = config();
85
+ if (!factory.enabled) return;
86
+ buildRegistryFrom(ctx);
87
+ if (registryStale()) return;
88
+ const tierRegistry = registry();
89
+ if (!tierRegistry) return;
90
+
91
+ const entries = ctx.sessionManager?.getEntries?.() ?? [];
92
+ const recentToolCalls = entries.filter(
93
+ (entry) =>
94
+ entry.type === "message" && (entry as { message?: { role?: string } }).message?.role === "toolResult",
95
+ ).length;
96
+
97
+ const decision = await router().route({
98
+ features: {
99
+ promptTokens: estimateTokens(event.prompt),
100
+ turns: entries.length,
101
+ hasImages: Boolean(event.images && event.images.length > 0),
102
+ recentToolCalls,
103
+ entryCount: entries.length,
104
+ },
105
+ prompt: event.prompt,
106
+ config: factory,
107
+ registry: tierRegistry,
108
+ unavailable: unavailableSet(),
109
+ currentModelId: ctx.model?.id,
110
+ classifier: {
111
+ enabled: factory.classifier.enabled,
112
+ run: async (prompt: string) => {
113
+ // Small decision model: explicit from factory.json, else the
114
+ // cheapest capable deepailab model picked at route time.
115
+ const configured = factory.classifier.model.trim();
116
+ const small = configured ? { provider: GATEWAY_PROVIDER, id: configured } : pickSmallModel(ctx);
117
+ if (!small) throw new Error(t("没有可用的 deepailab 小模型用于分类。"));
118
+ return classifyWithSmallModel(
119
+ {
120
+ find: (provider, id) => ctx.modelRegistry?.find(provider, id),
121
+ hasConfiguredAuth: (model) =>
122
+ Boolean(ctx.modelRegistry?.hasConfiguredAuth?.(model as AnyModel)) ?? false,
123
+ complete: async (model, context, options) =>
124
+ ctx.modelRegistry?.complete(
125
+ model as AnyModel,
126
+ context as Parameters<NonNullable<ExtensionContext["modelRegistry"]>["complete"]>[1],
127
+ options,
128
+ ) ?? {},
129
+ },
130
+ prompt,
131
+ { ...factory, classifier: { ...factory.classifier, model: `${small.provider}/${small.id}` } },
132
+ );
133
+ },
134
+ },
135
+ });
136
+
137
+ // Only the graded auto path may switch the session model; a kept affinity
138
+ // or a missing candidate leaves the user's model untouched.
139
+ if (autoRouteActive() && decision.modelId && decision.modelId !== ctx.model?.id) {
140
+ const target =
141
+ decision.provider === GATEWAY_PROVIDER
142
+ ? ctx.modelRegistry?.find(GATEWAY_PROVIDER, decision.modelId)
143
+ : undefined;
144
+ if (target) {
145
+ const applied = await pi.setModel(target as AnyModel);
146
+ if (!applied) {
147
+ markUnavailable(decision.modelId);
148
+ ctx.ui.setStatus("factory", undefined);
149
+ return;
150
+ }
151
+ }
152
+ }
153
+ if (autoRouteActive()) {
154
+ ctx.ui.setStatus?.(
155
+ "factory",
156
+ `→ ${decision.tier.toUpperCase()}/${decision.modelId ?? "?"} · ${decision.reason}`,
157
+ );
158
+ }
159
+ });
160
+
161
+ pi.on("after_provider_response", () => {
162
+ // Availability observation is a P3 item: this event carries the gateway's
163
+ // HTTP status but no model identity, and the pool cannot mark what it
164
+ // cannot name. setModel() failures already mark the pick unavailable.
165
+ });
166
+
167
+ // Compaction takeover: summarize with the cheapest capable model (t1) using
168
+ // the engine's own preparation and generateSummaryWithUsage. Any failure
169
+ // returns undefined and the engine falls back to the default path.
170
+ pi.on("session_before_compact", async (event, ctx: ExtensionContext) => {
171
+ const factory = config();
172
+ if (!factory.enabled || !factory.auxRoute.compaction) return undefined;
173
+ const tierRegistry = registry();
174
+ const preparation = event.preparation;
175
+ if (!tierRegistry || !preparation) return undefined;
176
+
177
+ try {
178
+ const candidate = ((): AnyModel | undefined => {
179
+ for (const tier of ["t1", "t2", "t3"] as const) {
180
+ for (const id of tierRegistry.tiers[tier]) {
181
+ if (unavailableSet().has(id)) continue;
182
+ const found = ctx.modelRegistry?.find(GATEWAY_PROVIDER, id);
183
+ if (found) return found as AnyModel;
184
+ }
185
+ }
186
+ return (ctx.model as AnyModel) ?? undefined;
187
+ })();
188
+ if (!candidate) return undefined;
189
+
190
+ const auth = ctx.modelRegistry?.getApiKeyAndHeaders
191
+ ? await ctx.modelRegistry.getApiKeyAndHeaders(candidate)
192
+ : undefined;
193
+ if (auth && !auth.ok) return undefined;
194
+
195
+ const { text, usage } = await generateSummaryWithUsage(
196
+ preparation.messagesToSummarize,
197
+ candidate,
198
+ preparation.settings.reserveTokens,
199
+ auth?.apiKey,
200
+ auth?.headers as Record<string, string> | undefined,
201
+ event.signal,
202
+ event.customInstructions,
203
+ preparation.previousSummary,
204
+ "off" as const,
205
+ );
206
+ return {
207
+ compaction: {
208
+ summary: text,
209
+ firstKeptEntryId: preparation.firstKeptEntryId,
210
+ tokensBefore: preparation.tokensBefore,
211
+ usage,
212
+ },
213
+ };
214
+ } catch {
215
+ // Fail-open: the engine compacts with the session model instead.
216
+ return undefined;
217
+ }
218
+ });
219
+
220
+ pi.registerCommand("factory", {
221
+ description: t("查看/配置模型工厂(status | auto on|off | levels | pool)"),
222
+ getArgumentCompletions: (prefix: string) => {
223
+ const subcommands = [
224
+ { value: "status", label: "status" },
225
+ { value: "auto on", label: "auto on" },
226
+ { value: "levels", label: "levels" },
227
+ { value: "pool", label: "pool" },
228
+ ];
229
+ return fuzzyFilter(subcommands, prefix, (sub) => sub.value).map((match) => ({
230
+ value: match.value,
231
+ label: match.label,
232
+ }));
233
+ },
234
+ handler: async (args: string, ctx: ExtensionCommandContext) => runFactoryCommand(args, ctx),
235
+ });
236
+ }
@@ -0,0 +1,150 @@
1
+ /**
2
+ * The routing decision core: grade -> tier -> model, with session affinity
3
+ * (anti-flap) and a bounded decision log for /factory status.
4
+ *
5
+ * Pipeline per turn: features -> rules -> (optional small-model classifier on
6
+ * the ambiguous L2 band) -> grade -> tier candidates -> weighted pick, with
7
+ * session affinity on top: staying on the same model keeps prompt-cache hits
8
+ * and avoids cross-model style jumps, so an escalation inside the configured
9
+ * threshold keeps the current model.
10
+ */
11
+
12
+ import type { FactoryConfig, Grade } from "./config.ts";
13
+ import { classifyByRules, type RouteFeatures } from "./features.ts";
14
+ import { gradeToTier, pickModelForGrade, type TierRegistry } from "./tiers.ts";
15
+
16
+ export interface RouteDecision {
17
+ grade: Grade;
18
+ gradeSource: "preset-rule" | "custom-rule" | "classifier" | "default" | "forced";
19
+ reason: string;
20
+ tier: ReturnType<typeof gradeToTier>;
21
+ modelId: string | undefined;
22
+ provider: string | undefined;
23
+ affinity: "switched" | "kept" | "no-previous" | "no-candidate";
24
+ decisionMs: number;
25
+ }
26
+
27
+ export interface RouteInput {
28
+ features: RouteFeatures;
29
+ prompt: string;
30
+ config: FactoryConfig;
31
+ registry: TierRegistry;
32
+ /** Model ids observed failing recently; temporarily out of the pool. */
33
+ unavailable: Set<string>;
34
+ /** The model currently active in the session. */
35
+ currentModelId?: string | undefined;
36
+ /** When set, bypasses grading entirely (read-only subagent -> t1). */
37
+ forceTier?: "t1" | "t2" | "t3";
38
+ /** Small-model classifier, run only when rules land on L2 and it is enabled. */
39
+ classifier?: { enabled: boolean; run: (prompt: string) => Promise<Grade> };
40
+ }
41
+
42
+ const TIER_ORDER: Record<"t1" | "t2" | "t3", number> = { t1: 1, t2: 2, t3: 3 };
43
+
44
+ export class Router {
45
+ private lastGrade: Grade | undefined;
46
+ private escalationStreak = 0;
47
+ private readonly decisions: RouteDecision[] = [];
48
+
49
+ async route(input: RouteInput): Promise<RouteDecision> {
50
+ const started = Date.now();
51
+ let grade: Grade = "l2";
52
+ let gradeSource: RouteDecision["gradeSource"] = "default";
53
+ let reason = "默认中等档";
54
+ let forced = false;
55
+
56
+ if (input.forceTier) {
57
+ grade = input.forceTier === "t1" ? "l1" : input.forceTier === "t3" ? "l3" : "l2";
58
+ gradeSource = "forced";
59
+ reason = input.forceTier === "t1" ? "只读子代理任务" : "强制层级";
60
+ forced = true;
61
+ } else {
62
+ const ruleDecision = classifyByRules(input.features, input.prompt, input.config);
63
+ grade = ruleDecision.grade;
64
+ gradeSource = ruleDecision.source;
65
+ reason = ruleDecision.reason;
66
+
67
+ // The classifier only re-checks the ambiguous band, and only when the
68
+ // user turned it on; any failure keeps the rule result (fail-open).
69
+ if (grade === "l2" && input.classifier?.enabled) {
70
+ try {
71
+ grade = await input.classifier.run(input.prompt);
72
+ gradeSource = "classifier";
73
+ reason = "小模型分类器复核";
74
+ } catch {
75
+ reason = "小模型分类器不可用,保留规则结果";
76
+ }
77
+ }
78
+ }
79
+
80
+ const tier = gradeToTier(grade);
81
+
82
+ // Session affinity applies to the graded path only: a forced tier (e.g.
83
+ // read-only subagent) must land on its tier regardless of history.
84
+ let affinity: RouteDecision["affinity"] = "no-previous";
85
+ let effectiveTier = tier;
86
+ if (!forced && this.lastGrade !== undefined) {
87
+ if (grade === this.lastGrade) {
88
+ affinity = "kept";
89
+ this.escalationStreak = 0;
90
+ } else {
91
+ const escalated = TIER_ORDER[tier] > TIER_ORDER[gradeToTier(this.lastGrade)];
92
+ const distance = Math.abs(TIER_ORDER[tier] - TIER_ORDER[gradeToTier(this.lastGrade)]);
93
+ if (escalated && distance <= input.config.affinity.switchThreshold) {
94
+ this.escalationStreak += 1;
95
+ if (this.escalationStreak < input.config.affinity.switchThreshold) {
96
+ affinity = "kept";
97
+ effectiveTier = gradeToTier(this.lastGrade);
98
+ } else {
99
+ this.escalationStreak = 0;
100
+ affinity = "switched";
101
+ }
102
+ } else {
103
+ this.escalationStreak = 0;
104
+ affinity = "switched";
105
+ }
106
+ }
107
+ }
108
+
109
+ const candidate = pickModelForGrade({
110
+ tier: effectiveTier,
111
+ grade,
112
+ registry: input.registry,
113
+ unavailable: input.unavailable,
114
+ currentModelId: input.currentModelId,
115
+ });
116
+
117
+ // Kept means the current model stays, even if the picked tier differs.
118
+ const modelId = affinity === "kept" && input.currentModelId ? input.currentModelId : candidate?.id;
119
+ const provider = modelId ? input.registry.candidates.find((entry) => entry.id === modelId)?.provider : undefined;
120
+
121
+ const decision: RouteDecision = {
122
+ grade,
123
+ gradeSource,
124
+ reason,
125
+ tier: affinity === "kept" && input.currentModelId ? effectiveTier : tier,
126
+ modelId,
127
+ provider,
128
+ affinity,
129
+ decisionMs: Date.now() - started,
130
+ };
131
+ this.lastGrade = grade;
132
+ this.decisions.push(decision);
133
+ if (this.decisions.length > 20) this.decisions.shift();
134
+ return decision;
135
+ }
136
+
137
+ decisionLog(): readonly RouteDecision[] {
138
+ return this.decisions;
139
+ }
140
+
141
+ lastGradeValue(): Grade | undefined {
142
+ return this.lastGrade;
143
+ }
144
+
145
+ /** Resets affinity state — new session, fork, or a compaction boundary. */
146
+ resetAffinity(): void {
147
+ this.lastGrade = undefined;
148
+ this.escalationStreak = 0;
149
+ }
150
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Module-level shared state for dal-router. The extension entry keeps it
3
+ * warm (config reloaded per session, tier registry rebuilt when the catalog
4
+ * changes); dal-subagent reads the same picture through subagent.ts, which is
5
+ * why this is a package singleton rather than entry-local state.
6
+ */
7
+
8
+ import { type FactoryConfig, loadFactoryConfig } from "./config.ts";
9
+ import { Router } from "./router.ts";
10
+ import { buildTierRegistry, type TierRegistry } from "./tiers.ts";
11
+
12
+ export interface CatalogModel {
13
+ id: string;
14
+ provider: string;
15
+ contextWindow: number;
16
+ maxTokens: number;
17
+ reasoning: boolean;
18
+ costPerMtok: number;
19
+ }
20
+
21
+ const state = {
22
+ config: loadFactoryConfig().config,
23
+ configWarning: loadFactoryConfig().warning,
24
+ router: new Router(),
25
+ registry: undefined as TierRegistry | undefined,
26
+ unavailable: new Set<string>(),
27
+ /** Main-conversation auto-routing runtime switch (/factory auto), not persisted. */
28
+ autoRouteRuntime: undefined as boolean | undefined,
29
+ };
30
+
31
+ export function config(): FactoryConfig {
32
+ return state.config;
33
+ }
34
+
35
+ export function configWarning(): string | undefined {
36
+ return state.configWarning;
37
+ }
38
+
39
+ export function reloadConfig(): void {
40
+ const { config, warning } = loadFactoryConfig();
41
+ state.config = config;
42
+ state.configWarning = warning;
43
+ state.router.resetAffinity();
44
+ }
45
+
46
+ export function router(): Router {
47
+ return state.router;
48
+ }
49
+
50
+ export function registry(): TierRegistry | undefined {
51
+ return state.registry;
52
+ }
53
+
54
+ export function setRegistry(models: CatalogModel[]): void {
55
+ state.registry = buildTierRegistry({
56
+ models,
57
+ explicit: state.config.tiers,
58
+ autoTiering: state.config.autoTiering.enabled,
59
+ });
60
+ }
61
+
62
+ export function registryStale(): boolean {
63
+ return state.registry === undefined;
64
+ }
65
+
66
+ export function markUnavailable(modelId: string): void {
67
+ state.unavailable.add(modelId);
68
+ }
69
+
70
+ export function clearUnavailable(): void {
71
+ state.unavailable.clear();
72
+ }
73
+
74
+ export function isUnavailable(modelId: string): boolean {
75
+ return state.unavailable.has(modelId);
76
+ }
77
+
78
+ export function autoRouteActive(): boolean {
79
+ return state.autoRouteRuntime ?? state.config.mainAutoRoute;
80
+ }
81
+
82
+ export function setAutoRouteRuntime(value: boolean): void {
83
+ state.autoRouteRuntime = value;
84
+ }
85
+
86
+ export function unavailableSet(): Set<string> {
87
+ return state.unavailable;
88
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Picks the small decision model used by the classifier: the cheapest
3
+ * deepailab model with a usable context window. Cost ordering comes from the
4
+ * gateway catalog forwarded by dal-gateway, so the choice tracks the live
5
+ * sales catalog rather than a hardcoded id.
6
+ */
7
+
8
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
9
+
10
+ const MIN_CONTEXT_TOKENS = 32_000;
11
+
12
+ export interface SmallModel {
13
+ provider: string;
14
+ id: string;
15
+ }
16
+
17
+ /**
18
+ * Selects the cheapest usable deepailab model. Unknown costs sort last;
19
+ * models with a tiny catalog window are skipped — the classifier only needs
20
+ * a few hundred tokens, but a model that cannot hold the system prompt is
21
+ * useless.
22
+ */
23
+ export function pickSmallModel(ctx: ExtensionContext): SmallModel | undefined {
24
+ const available = ctx.modelRegistry?.getAvailable?.() ?? [];
25
+ const deepailab = available
26
+ .filter((model) => model.provider === "deepailab")
27
+ .filter((model) => (model.contextWindow ?? 0) >= MIN_CONTEXT_TOKENS)
28
+ .map((model) => ({
29
+ id: model.id,
30
+ provider: model.provider,
31
+ inputCost: model.cost?.input ?? Number.POSITIVE_INFINITY,
32
+ }))
33
+ .sort((a, b) => a.inputCost - b.inputCost || a.id.localeCompare(b.id));
34
+ const first = deepailab[0];
35
+ return first ? { provider: first.provider, id: first.id } : undefined;
36
+ }
@@ -0,0 +1,58 @@
1
+ /**
2
+ * Subagent routing: the one-line seam in dal-subagent. A read-only research
3
+ * task is the textbook L1 job and lands on T1; everything else inherits the
4
+ * main conversation's current tier. Any failure returns undefined, which the
5
+ * caller turns into "keep ctx.model" — routing must never break a subagent.
6
+ */
7
+
8
+ import { t } from "@dalcode/dal-pi-kit";
9
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
10
+ import { config, registry, router } from "./runtime.ts";
11
+
12
+ export interface SubagentRouteResult {
13
+ modelId: string | undefined;
14
+ provider: string | undefined;
15
+ grade: "l1" | "l2" | "l3";
16
+ reason: string;
17
+ }
18
+
19
+ /** readOnly subagents land on t1; the rest inherit the main turn's grade. */
20
+ export async function routeSubagentModel(
21
+ ctx: ExtensionContext,
22
+ readOnly: boolean,
23
+ ): Promise<SubagentRouteResult | undefined> {
24
+ const factory = config();
25
+ if (!factory.enabled || !factory.auxRoute.subagent) return undefined;
26
+ const tierRegistry = registry();
27
+ if (!tierRegistry) return undefined;
28
+
29
+ const entries = ctx.sessionManager?.getEntries?.() ?? [];
30
+ const recentToolCalls = entries.filter((entry) => (entry as { type?: string }).type === "tool_execution_end").length;
31
+ const decision = await router().route({
32
+ features: {
33
+ promptTokens: 0,
34
+ turns: entries.length,
35
+ hasImages: false,
36
+ recentToolCalls,
37
+ entryCount: entries.length,
38
+ },
39
+ prompt: "",
40
+ config: factory,
41
+ registry: tierRegistry,
42
+ unavailable: new Set<string>(),
43
+ currentModelId: ctx.model?.id,
44
+ forceTier: readOnly ? "t1" : undefined,
45
+ });
46
+
47
+ if (!decision.modelId || decision.affinity === "kept") {
48
+ // kept means "stay on the current model", which for the subagent is
49
+ // ctx.model — signal that by returning undefined.
50
+ return { modelId: undefined, provider: undefined, grade: decision.grade, reason: decision.reason };
51
+ }
52
+ return {
53
+ modelId: decision.modelId,
54
+ provider: decision.provider,
55
+ grade: decision.grade,
56
+ reason: `${t("按任务复杂度路由到 ")}${decision.tier}`,
57
+ };
58
+ }