dal-code 1.0.12 → 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 (121) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/core/keybindings.d.ts +1 -1
  3. package/dist/core/keybindings.d.ts.map +1 -1
  4. package/dist/core/keybindings.js +1 -1
  5. package/dist/core/keybindings.js.map +1 -1
  6. package/dist/core/settings-manager.d.ts +3 -0
  7. package/dist/core/settings-manager.d.ts.map +1 -1
  8. package/dist/core/settings-manager.js +8 -0
  9. package/dist/core/settings-manager.js.map +1 -1
  10. package/dist/dal/builtins.d.ts.map +1 -1
  11. package/dist/dal/builtins.js +1 -0
  12. package/dist/dal/builtins.js.map +1 -1
  13. package/dist/modes/interactive/components/bash-execution.d.ts +1 -0
  14. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  15. package/dist/modes/interactive/components/bash-execution.js +7 -4
  16. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  17. package/dist/modes/interactive/components/settings-selector.d.ts +2 -0
  18. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  19. package/dist/modes/interactive/components/settings-selector.js +9 -0
  20. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  21. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  22. package/dist/modes/interactive/external-editor.js +9 -2
  23. package/dist/modes/interactive/external-editor.js.map +1 -1
  24. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  25. package/dist/modes/interactive/interactive-mode.js +13 -12
  26. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  27. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  28. package/dist/node_modules/@dalcode/dal-bridge/src/client.ts +2 -2
  29. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  30. package/dist/node_modules/@dalcode/dal-gateway/src/index.ts +35 -7
  31. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  32. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  33. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  34. package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
  35. package/dist/node_modules/@dalcode/dal-lsp/src/client.ts +14 -0
  36. package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
  37. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  38. package/dist/node_modules/@dalcode/dal-office/src/render/docx.ts +12 -1
  39. package/dist/node_modules/@dalcode/dal-office/src/render/xlsx.ts +31 -2
  40. package/dist/node_modules/@dalcode/dal-office/src/tools/chart-generate.ts +9 -0
  41. package/dist/node_modules/@dalcode/dal-office/src/tools/ppt-generate.ts +10 -6
  42. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.d.ts.map +1 -1
  43. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +31 -2
  44. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js.map +1 -1
  45. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  46. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.ts +35 -3
  47. package/dist/node_modules/@dalcode/dal-router/LICENSE +21 -0
  48. package/dist/node_modules/@dalcode/dal-router/package.json +36 -0
  49. package/dist/node_modules/@dalcode/dal-router/src/classifier.ts +80 -0
  50. package/dist/node_modules/@dalcode/dal-router/src/commands.ts +104 -0
  51. package/dist/node_modules/@dalcode/dal-router/src/config.ts +137 -0
  52. package/dist/node_modules/@dalcode/dal-router/src/features.ts +85 -0
  53. package/dist/node_modules/@dalcode/dal-router/src/index.ts +236 -0
  54. package/dist/node_modules/@dalcode/dal-router/src/router.ts +150 -0
  55. package/dist/node_modules/@dalcode/dal-router/src/runtime.ts +88 -0
  56. package/dist/node_modules/@dalcode/dal-router/src/small-model.ts +36 -0
  57. package/dist/node_modules/@dalcode/dal-router/src/subagent.ts +58 -0
  58. package/dist/node_modules/@dalcode/dal-router/src/tiers.ts +187 -0
  59. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  60. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  61. package/dist/node_modules/@dalcode/dal-subagent/src/index.ts +14 -1
  62. package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
  63. package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
  64. package/dist/node_modules/@dalcode/deepailab/src/oidc.ts +1 -1
  65. package/dist/node_modules/@earendil-works/chord/package.json +1 -1
  66. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  67. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  68. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
  69. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
  70. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/github-copilot.json +1 -1
  71. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/huggingface.json +1 -1
  72. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.json +1 -1
  73. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  74. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  75. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  76. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  77. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xai.json +1 -1
  78. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-ams.json +1 -1
  79. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-cn.json +1 -1
  80. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-sgp.json +1 -1
  81. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi.json +1 -1
  82. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  83. package/dist/node_modules/@earendil-works/pi-client/package.json +2 -2
  84. package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
  85. package/dist/node_modules/@earendil-works/pi-server/package.json +3 -3
  86. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/package.json +3 -3
  87. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  88. package/dist/node_modules/@earendil-works/pi-tui/dist/autocomplete.d.ts.map +1 -1
  89. package/dist/node_modules/@earendil-works/pi-tui/dist/autocomplete.js +1 -1
  90. package/dist/node_modules/@earendil-works/pi-tui/dist/autocomplete.js.map +1 -1
  91. package/dist/node_modules/@earendil-works/pi-tui/dist/components/editor.d.ts.map +1 -1
  92. package/dist/node_modules/@earendil-works/pi-tui/dist/components/editor.js +3 -1
  93. package/dist/node_modules/@earendil-works/pi-tui/dist/components/editor.js.map +1 -1
  94. package/dist/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.d.ts +1 -0
  95. package/dist/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.d.ts.map +1 -1
  96. package/dist/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.js +12 -1
  97. package/dist/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.js.map +1 -1
  98. package/dist/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.d.ts.map +1 -1
  99. package/dist/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.js +3 -1
  100. package/dist/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.js.map +1 -1
  101. package/dist/node_modules/@earendil-works/pi-tui/dist/utils.d.ts.map +1 -1
  102. package/dist/node_modules/@earendil-works/pi-tui/dist/utils.js +13 -4
  103. package/dist/node_modules/@earendil-works/pi-tui/dist/utils.js.map +1 -1
  104. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  105. package/dist/utils/clipboard.d.ts.map +1 -1
  106. package/dist/utils/clipboard.js +25 -2
  107. package/dist/utils/clipboard.js.map +1 -1
  108. package/dist/utils/shell.d.ts.map +1 -1
  109. package/dist/utils/shell.js +9 -1
  110. package/dist/utils/shell.js.map +1 -1
  111. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  112. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  113. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  114. package/examples/extensions/gondolin/package-lock.json +2 -2
  115. package/examples/extensions/gondolin/package.json +1 -1
  116. package/examples/extensions/sandbox/package-lock.json +2 -2
  117. package/examples/extensions/sandbox/package.json +1 -1
  118. package/examples/extensions/with-deps/package-lock.json +2 -2
  119. package/examples/extensions/with-deps/package.json +1 -1
  120. package/npm-shrinkwrap.json +2 -2
  121. package/package.json +1 -1
@@ -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
+ }
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Tier registry (T1 light / T2 balanced / T3 performance) and the
3
+ * fitness-based model pick.
4
+ *
5
+ * Assignment is by model *capability*, not cost: every candidate gets a
6
+ * capability score (context window, reasoning, output budget, id signals),
7
+ * and the sorted spread is split into tiers — the strongest models form t3
8
+ * (complex work), the weakest form t1 (simple work a light model handles
9
+ * fine), the middle band is t2.
10
+ *
11
+ * The pick then optimizes *fitness for the grade* inside the target tier:
12
+ * l1 prefers the quickest model in the tier, l3 the most capable one. Cost
13
+ * only breaks ties.
14
+ */
15
+
16
+ import type { Grade, TierLevel } from "./config.ts";
17
+
18
+ export interface TierCandidate {
19
+ id: string;
20
+ /** Provider-qualified lookup key for modelRegistry.find(). */
21
+ provider: string;
22
+ contextWindow: number;
23
+ maxTokens: number;
24
+ reasoning: boolean;
25
+ /** $/Mtok, input+output averaged when only those are known; 0 = unknown. */
26
+ costPerMtok: number;
27
+ tier: TierLevel;
28
+ }
29
+
30
+ /**
31
+ * Capability signals carried in model ids. Vendors encode the positioning
32
+ * there ("flash"/"mini" = quick and light, "pro"/"max" = flagship), so a hit
33
+ * is worth real signal in lieu of published benchmarks.
34
+ */
35
+ const LIGHT_ID_PATTERN = /(?:mini|flash|lite|fast|air|small|instant|turbo|nano)/i;
36
+ const HEAVY_ID_PATTERN = /(?:pro|max|ultra|large|heavy|plus|codex|thinking|reasoning)/i;
37
+
38
+ /**
39
+ * Overall capability weight of a model — how much work it can take on. Used
40
+ * for tier assignment (weak models serve simple grades, strong models serve
41
+ * complex grades).
42
+ */
43
+ export function capabilityScore(model: {
44
+ contextWindow: number;
45
+ maxTokens: number;
46
+ reasoning: boolean;
47
+ id: string;
48
+ }): number {
49
+ const id = model.id.toLowerCase();
50
+ let score = 0;
51
+ score += Math.min(model.contextWindow / 1_000_000, 2) * 0.35; // 2M window = max 0.7
52
+ score += Math.min(model.maxTokens / 65_536, 1) * 0.15;
53
+ if (model.reasoning) score += 0.25;
54
+ if (HEAVY_ID_PATTERN.test(id)) score += 0.15;
55
+ if (LIGHT_ID_PATTERN.test(id)) score -= 0.05;
56
+ return score;
57
+ }
58
+
59
+ /**
60
+ * How well a model fits a grade, inside its tier. l1 favors the quickest
61
+ * model in the tier, l3 the most capable one; l2 stays in the middle.
62
+ */
63
+ export function fitnessWithinTier(model: TierCandidate, grade: Grade): number {
64
+ const capability = capabilityScore(model);
65
+ if (grade === "l1") return 1 - capability; // light work: the lightest fits
66
+ if (grade === "l3") return capability; // hard work: the strongest fits
67
+ const mid = 1 - Math.abs(capability - 0.5); // balanced work: the middle fits
68
+ return mid;
69
+ }
70
+
71
+ export interface TierCandidatesInput {
72
+ /** id -> { provider, contextWindow, maxTokens, reasoning, costPerMtok }. */
73
+ models: Array<{
74
+ id: string;
75
+ provider: string;
76
+ contextWindow: number;
77
+ maxTokens: number;
78
+ reasoning: boolean;
79
+ costPerMtok: number;
80
+ }>;
81
+ /** Explicit tier naming from factory.json, in priority order over the heuristic. */
82
+ explicit: { t1: string[]; t2: string[]; t3: string[] };
83
+ autoTiering: boolean;
84
+ }
85
+
86
+ export interface TierRegistry {
87
+ candidates: TierCandidate[];
88
+ tiers: Record<TierLevel, string[]>;
89
+ /** Where each assignment came from, for /factory pool. */
90
+ sources: Record<string, "explicit" | "heuristic" | "default-tier">;
91
+ }
92
+
93
+ /**
94
+ * Builds the tier registry. Models named explicitly land on their named tier
95
+ * first; the rest are capability-ranked — the strongest slice forms t3, the
96
+ * weakest t1, the middle band t2.
97
+ */
98
+ export function buildTierRegistry(input: TierCandidatesInput): TierRegistry {
99
+ const candidates: TierCandidate[] = [];
100
+ const tiers: Record<TierLevel, string[]> = { t1: [], t2: [], t3: [] };
101
+ const sources: Record<string, "explicit" | "heuristic" | "default-tier"> = {};
102
+ const assigned = new Set<string>();
103
+
104
+ const byName = new Map(input.models.map((m) => [m.id, m]));
105
+ for (const level of ["t1", "t2", "t3"] as const) {
106
+ for (const id of input.explicit[level]) {
107
+ const model = byName.get(id);
108
+ if (!model || assigned.has(id)) continue;
109
+ candidates.push({ ...model, tier: level });
110
+ tiers[level].push(id);
111
+ sources[id] = "explicit";
112
+ assigned.add(id);
113
+ }
114
+ }
115
+
116
+ const unassigned = input.models.filter((model) => !assigned.has(model.id));
117
+ if (input.autoTiering && unassigned.length >= 2) {
118
+ // Capability ascending: weakest first. The weakest slice forms t1, the
119
+ // strongest slice forms t3 — a graded ladder of the same catalog.
120
+ const scored = unassigned
121
+ .map((model) => ({ model, capability: capabilityScore(model) }))
122
+ .sort((a, b) => a.capability - b.capability);
123
+ const quarter = Math.max(1, Math.floor(scored.length / 4));
124
+ scored.forEach((entry, index) => {
125
+ let level: TierLevel = "t2";
126
+ if (index < quarter) level = "t1";
127
+ else if (index >= scored.length - quarter) level = "t3";
128
+ candidates.push({ ...entry.model, tier: level });
129
+ tiers[level].push(entry.model.id);
130
+ sources[entry.model.id] = "heuristic";
131
+ });
132
+ } else {
133
+ for (const model of unassigned) {
134
+ candidates.push({ ...model, tier: "t2" });
135
+ tiers.t2.push(model.id);
136
+ sources[model.id] = "default-tier";
137
+ }
138
+ }
139
+
140
+ return { candidates, tiers, sources };
141
+ }
142
+
143
+ export interface PickInput {
144
+ /** The target tier derived from the graded complexity. */
145
+ tier: TierLevel;
146
+ /** The graded complexity — selects the best-fitting model inside the tier. */
147
+ grade: Grade;
148
+ registry: TierRegistry;
149
+ /** Cost breaks ties between equally fitting models. */
150
+ costPerMtok?: number;
151
+ /** Model ids observed failing recently; temporarily out of the pool. */
152
+ unavailable: Set<string>;
153
+ /** The model currently active in the session (preferred on exact fitness ties). */
154
+ currentModelId?: string;
155
+ }
156
+
157
+ /**
158
+ * Five-factor pick: fitness for the grade dominates, cost breaks ties between
159
+ * equally fitting models, and the authorization factor is a veto applied
160
+ * upstream by filtering candidates.
161
+ */
162
+ export function pickModelForGrade(input: PickInput): TierCandidate | undefined {
163
+ const inTier = input.registry.candidates.filter(
164
+ (candidate) => candidate.tier === input.tier && !input.unavailable.has(candidate.id),
165
+ );
166
+ if (inTier.length === 0) return undefined;
167
+
168
+ const best = inTier
169
+ .map((candidate) => ({
170
+ candidate,
171
+ fitness: fitnessForTier(candidate, input.grade),
172
+ cost: candidate.costPerMtok,
173
+ }))
174
+ .sort((a, b) => b.fitness - a.fitness || a.cost - b.cost || a.candidate.id.localeCompare(b.candidate.id));
175
+ return best[0]?.candidate;
176
+ }
177
+
178
+ function fitnessForTier(candidate: TierCandidate, grade: Grade): number {
179
+ if (grade === "l1") return -capabilityScore(candidate); // light work: lightest model wins
180
+ if (grade === "l3") return capabilityScore(candidate); // hard work: strongest model wins
181
+ return 0; // balanced work: middle of the tier
182
+ }
183
+
184
+ /** Grade -> target tier, per the L1/L2/L3 mapping table. */
185
+ export function gradeToTier(grade: Grade): TierLevel {
186
+ return { l1: "t1", l2: "t2", l3: "t3" }[grade] as TierLevel;
187
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-skills",
3
- "version": "1.0.12",
3
+ "version": "1.0.14",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -19,8 +19,8 @@
19
19
  ]
20
20
  },
21
21
  "dependencies": {
22
- "@dalcode/dal-pi-kit": "1.0.12",
23
- "@dalcode/deepailab": "1.0.12",
22
+ "@dalcode/dal-pi-kit": "1.0.14",
23
+ "@dalcode/deepailab": "1.0.14",
24
24
  "typebox": "1.3.7"
25
25
  },
26
26
  "peerDependencies": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-subagent",
3
- "version": "1.0.12",
3
+ "version": "1.0.14",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -17,10 +17,10 @@
17
17
  ]
18
18
  },
19
19
  "dependencies": {
20
- "@dalcode/dal-pi-kit": "1.0.12",
21
- "@dalcode/dal-guard": "1.0.12",
22
- "@earendil-works/pi-agent-core": "^1.0.12",
23
- "@earendil-works/pi-ai": "^1.0.12",
20
+ "@dalcode/dal-pi-kit": "1.0.14",
21
+ "@dalcode/dal-guard": "1.0.14",
22
+ "@earendil-works/pi-agent-core": "^1.0.14",
23
+ "@earendil-works/pi-ai": "^1.0.14",
24
24
  "typebox": "1.3.7"
25
25
  },
26
26
  "peerDependencies": {
@@ -20,6 +20,7 @@
20
20
 
21
21
  import { evaluateToolCall } from "@dalcode/dal-guard";
22
22
  import { t } from "@dalcode/dal-pi-kit";
23
+ import { routeSubagentModel } from "@dalcode/dal-router/subagent";
23
24
  import { Agent, type AgentMessage, type AgentTool } from "@earendil-works/pi-agent-core";
24
25
  import { streamSimple } from "@earendil-works/pi-ai/compat";
25
26
  import type { ExtensionAPI, ExtensionContext, ToolCallEvent } from "@earendil-works/pi-coding-agent";
@@ -185,6 +186,18 @@ async function runSubagent(
185
186
  if (!model) {
186
187
  throw new Error(t("没有可用的当前模型,无法派发子 agent。"));
187
188
  }
189
+ // Model factory: read-only research lands on the light tier, everything
190
+ // else inherits the main turn. Any failure keeps ctx.model.
191
+ let effectiveModel: typeof model | undefined = model;
192
+ try {
193
+ const routed = await routeSubagentModel(ctx, input.readOnly === true);
194
+ if (routed?.modelId && routed.provider) {
195
+ const resolved = ctx.modelRegistry?.find(routed.provider, routed.modelId);
196
+ if (resolved) effectiveModel = resolved as typeof model;
197
+ }
198
+ } catch {
199
+ // Routing is a cost feature; never let it break a dispatch.
200
+ }
188
201
 
189
202
  const release = await subagentSemaphore.acquire();
190
203
  const changedFiles: string[] = [];
@@ -197,7 +210,7 @@ async function runSubagent(
197
210
  const subagent = new Agent({
198
211
  initialState: {
199
212
  systemPrompt: buildSubagentSystemPrompt(),
200
- model,
213
+ model: effectiveModel,
201
214
  thinkingLevel: "off",
202
215
  tools,
203
216
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-telemetry",
3
- "version": "1.0.12",
3
+ "version": "1.0.14",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -20,7 +20,7 @@
20
20
  ]
21
21
  },
22
22
  "dependencies": {
23
- "@dalcode/dal-pi-kit": "1.0.12"
23
+ "@dalcode/dal-pi-kit": "1.0.14"
24
24
  },
25
25
  "peerDependencies": {
26
26
  "@earendil-works/pi-coding-agent": "^1.0.9"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/deepailab",
3
- "version": "1.0.12",
3
+ "version": "1.0.14",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -19,8 +19,8 @@
19
19
  ]
20
20
  },
21
21
  "dependencies": {
22
- "@dalcode/dal-pi-kit": "1.0.12",
23
- "@earendil-works/pi-ai": "^1.0.12"
22
+ "@dalcode/dal-pi-kit": "1.0.14",
23
+ "@earendil-works/pi-ai": "^1.0.14"
24
24
  },
25
25
  "peerDependencies": {
26
26
  "@earendil-works/pi-coding-agent": "^1.0.9"
@@ -176,7 +176,7 @@ export async function discover(issuer: string): Promise<OidcEndpoints> {
176
176
  throw new Error(`OIDC discovery failed (${res.status}) at ${url}`);
177
177
  }
178
178
  const doc = (await res.json()) as DiscoveryDoc;
179
- const oidc = base + "/protocol/openid-connect";
179
+ const oidc = `${base}/protocol/openid-connect`;
180
180
  const endpoints: OidcEndpoints = {
181
181
  issuer: doc.issuer,
182
182
  deviceAuthorizationEndpoint: doc.device_authorization_endpoint ?? `${oidc}/auth/device`,
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@earendil-works/chord",
3
- "version": "1.0.12",
3
+ "version": "1.0.14",
4
4
  "description": "Application composition runtime for services, replicated state, RPC, and plugins",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@earendil-works/pi-agent-core",
3
- "version": "1.0.12",
3
+ "version": "1.0.14",
4
4
  "description": "General-purpose agent with transport abstraction, state management, and attachment support",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -41,8 +41,8 @@
41
41
  "README.md"
42
42
  ],
43
43
  "dependencies": {
44
- "@earendil-works/pi-ai": "^1.0.12",
45
- "@earendil-works/pi-telemetry": "^1.0.12",
44
+ "@earendil-works/pi-ai": "^1.0.14",
45
+ "@earendil-works/pi-telemetry": "^1.0.14",
46
46
  "diff": "8.0.4",
47
47
  "ignore": "7.0.5",
48
48
  "typebox": "1.3.7",