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.
- package/CHANGELOG.md +11 -0
- package/dist/core/keybindings.d.ts +1 -1
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +1 -1
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/settings-manager.d.ts +3 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +8 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/dal/builtins.d.ts.map +1 -1
- package/dist/dal/builtins.js +1 -0
- package/dist/dal/builtins.js.map +1 -1
- package/dist/modes/interactive/components/bash-execution.d.ts +1 -0
- package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/bash-execution.js +7 -4
- package/dist/modes/interactive/components/bash-execution.js.map +1 -1
- package/dist/modes/interactive/components/settings-selector.d.ts +2 -0
- package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-selector.js +9 -0
- package/dist/modes/interactive/components/settings-selector.js.map +1 -1
- package/dist/modes/interactive/external-editor.d.ts.map +1 -1
- package/dist/modes/interactive/external-editor.js +9 -2
- package/dist/modes/interactive/external-editor.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +13 -12
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-bridge/src/client.ts +2 -2
- package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-gateway/src/index.ts +35 -7
- package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
- package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-lsp/src/client.ts +14 -0
- package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
- package/dist/node_modules/@dalcode/dal-office/src/render/docx.ts +12 -1
- package/dist/node_modules/@dalcode/dal-office/src/render/xlsx.ts +31 -2
- package/dist/node_modules/@dalcode/dal-office/src/tools/chart-generate.ts +9 -0
- package/dist/node_modules/@dalcode/dal-office/src/tools/ppt-generate.ts +10 -6
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.d.ts.map +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +31 -2
- package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js.map +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
- package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.ts +35 -3
- package/dist/node_modules/@dalcode/dal-router/LICENSE +21 -0
- package/dist/node_modules/@dalcode/dal-router/package.json +36 -0
- package/dist/node_modules/@dalcode/dal-router/src/classifier.ts +80 -0
- package/dist/node_modules/@dalcode/dal-router/src/commands.ts +104 -0
- package/dist/node_modules/@dalcode/dal-router/src/config.ts +137 -0
- package/dist/node_modules/@dalcode/dal-router/src/features.ts +85 -0
- package/dist/node_modules/@dalcode/dal-router/src/index.ts +236 -0
- package/dist/node_modules/@dalcode/dal-router/src/router.ts +150 -0
- package/dist/node_modules/@dalcode/dal-router/src/runtime.ts +88 -0
- package/dist/node_modules/@dalcode/dal-router/src/small-model.ts +36 -0
- package/dist/node_modules/@dalcode/dal-router/src/subagent.ts +58 -0
- package/dist/node_modules/@dalcode/dal-router/src/tiers.ts +187 -0
- package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
- package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
- package/dist/node_modules/@dalcode/dal-subagent/src/index.ts +14 -1
- package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
- package/dist/node_modules/@dalcode/deepailab/package.json +3 -3
- package/dist/node_modules/@dalcode/deepailab/src/oidc.ts +1 -1
- package/dist/node_modules/@earendil-works/chord/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-ai-gateway.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/github-copilot.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/huggingface.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/nvidia.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xai.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-ams.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-cn.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi-token-plan-sgp.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/xiaomi.json +1 -1
- package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-client/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
- package/dist/node_modules/@earendil-works/pi-server/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/package.json +3 -3
- package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/dist/autocomplete.d.ts.map +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/dist/autocomplete.js +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/dist/autocomplete.js.map +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/dist/components/editor.d.ts.map +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/dist/components/editor.js +3 -1
- package/dist/node_modules/@earendil-works/pi-tui/dist/components/editor.js.map +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.d.ts +1 -0
- package/dist/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.d.ts.map +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.js +12 -1
- package/dist/node_modules/@earendil-works/pi-tui/dist/stdin-buffer.js.map +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.d.ts.map +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.js +3 -1
- package/dist/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.js.map +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/dist/utils.d.ts.map +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/dist/utils.js +13 -4
- package/dist/node_modules/@earendil-works/pi-tui/dist/utils.js.map +1 -1
- package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
- package/dist/utils/clipboard.d.ts.map +1 -1
- package/dist/utils/clipboard.js +25 -2
- package/dist/utils/clipboard.js.map +1 -1
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +9 -1
- package/dist/utils/shell.js.map +1 -1
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/gondolin/package-lock.json +2 -2
- package/examples/extensions/gondolin/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* /factory — inspect and toggle the model factory.
|
|
3
|
+
*
|
|
4
|
+
* /factory status: mode, recent decisions, current model
|
|
5
|
+
* /factory status same
|
|
6
|
+
* /factory auto on|off main-conversation auto routing (runtime)
|
|
7
|
+
* /factory levels the last decisions' grade and reasons
|
|
8
|
+
* /factory pool tier assignments and where they came from
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { t } from "@dalcode/dal-pi-kit";
|
|
12
|
+
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
13
|
+
import type { TierLevel } from "./config.ts";
|
|
14
|
+
import { autoRouteActive, config, configWarning, registry, router, setAutoRouteRuntime } from "./runtime.ts";
|
|
15
|
+
|
|
16
|
+
const TIERS: TierLevel[] = ["t1", "t2", "t3"];
|
|
17
|
+
|
|
18
|
+
function usage(context: ExtensionCommandContext): void {
|
|
19
|
+
context.ui.notify(
|
|
20
|
+
[
|
|
21
|
+
t("用法:/factory [status]"),
|
|
22
|
+
t("用法:/factory auto on|off — 主对话自动路由开关"),
|
|
23
|
+
t("用法:/factory levels — 最近决策依据"),
|
|
24
|
+
t("用法:/factory pool — 分层结果与来源"),
|
|
25
|
+
].join("\n"),
|
|
26
|
+
"info",
|
|
27
|
+
);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function runFactoryCommand(args: string, ctx: ExtensionCommandContext): Promise<void> {
|
|
31
|
+
const [sub, ...rest] = args.trim().split(/\s+/).filter(Boolean);
|
|
32
|
+
const warning = configWarning();
|
|
33
|
+
if (warning) ctx.ui.notify(warning, "warning");
|
|
34
|
+
const factory = config();
|
|
35
|
+
const tierRegistry = registry();
|
|
36
|
+
|
|
37
|
+
switch (sub ?? "status") {
|
|
38
|
+
case "status": {
|
|
39
|
+
const mode = factory.enabled
|
|
40
|
+
? autoRouteActive()
|
|
41
|
+
? t("主对话自动路由已开启")
|
|
42
|
+
: t("仅辅助任务路由(主对话自动路由关闭,/factory auto on 开启)")
|
|
43
|
+
: t("已禁用");
|
|
44
|
+
const recent = router().decisionLog().slice(-5).reverse();
|
|
45
|
+
const recentLines = recent.length
|
|
46
|
+
? recent.map((d) => ` ${d.grade.toUpperCase()} → ${d.tier}/${d.modelId ?? "?"} — ${d.reason}`).join("\n")
|
|
47
|
+
: ` ${t("暂无路由决策。")}`;
|
|
48
|
+
ctx.ui.notify(`${t("模型工厂:")}${mode}\n${recentLines}`, "info");
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
case "levels": {
|
|
52
|
+
const recent = router().decisionLog().slice(-8).reverse();
|
|
53
|
+
if (recent.length === 0) {
|
|
54
|
+
ctx.ui.notify(t("暂无路由决策。"), "info");
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
ctx.ui.notify(
|
|
58
|
+
recent
|
|
59
|
+
.map(
|
|
60
|
+
(d) =>
|
|
61
|
+
`${d.grade.toUpperCase()} — ${d.reason}${d.gradeSource === "classifier" ? `(${t("小模型复核")})` : ""}`,
|
|
62
|
+
)
|
|
63
|
+
.join("\n"),
|
|
64
|
+
"info",
|
|
65
|
+
);
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
case "pool": {
|
|
69
|
+
if (!tierRegistry) {
|
|
70
|
+
ctx.ui.notify(t("分层注册表尚未构建(等待会话启动)。"), "info");
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const lines = TIERS.map((tier) => {
|
|
74
|
+
const ids = tierRegistry.tiers[tier];
|
|
75
|
+
const detail = ids.length
|
|
76
|
+
? ids
|
|
77
|
+
.map((id) => {
|
|
78
|
+
const source = tierRegistry.sources[id] ?? "default-tier";
|
|
79
|
+
return `${id}${source === "explicit" ? t("(显式指定)") : source === "heuristic" ? t("(自动分层)") : ""}`;
|
|
80
|
+
})
|
|
81
|
+
.join(", ")
|
|
82
|
+
: t("(空)");
|
|
83
|
+
return ` ${tier.toUpperCase()}: ${detail}`;
|
|
84
|
+
});
|
|
85
|
+
ctx.ui.notify(`${t("模型分层:")}\n${lines.join("\n")}`, "info");
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
case "auto": {
|
|
89
|
+
const value = rest[0];
|
|
90
|
+
if (value !== "on" && value !== "off") {
|
|
91
|
+
ctx.ui.notify(t("用法:/factory auto on|off"), "info");
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
setAutoRouteRuntime(value === "on");
|
|
95
|
+
ctx.ui.notify(
|
|
96
|
+
value === "on" ? t("主对话自动路由已开启(仅当前会话)。") : t("主对话自动路由已关闭。"),
|
|
97
|
+
"info",
|
|
98
|
+
);
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
default:
|
|
102
|
+
usage(ctx);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* factory.json — persisted configuration for the model factory, layered over
|
|
3
|
+
* these defaults. Lives at ~/.dal/agent/factory.json (same persistence idiom
|
|
4
|
+
* as the dal-pi-kit language file: plain file, write failures reported, never
|
|
5
|
+
* thrown into the session).
|
|
6
|
+
*
|
|
7
|
+
* A malformed file falls back to every default plus one stderr warning — a
|
|
8
|
+
* broken config must not block startup (models.json semantics).
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import { t } from "@dalcode/dal-pi-kit";
|
|
14
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
15
|
+
|
|
16
|
+
export type Grade = "l1" | "l2" | "l3";
|
|
17
|
+
export type TierLevel = "t1" | "t2" | "t3";
|
|
18
|
+
|
|
19
|
+
export interface CustomRule {
|
|
20
|
+
/** Case-insensitive regex tested against the prompt text. */
|
|
21
|
+
match: string;
|
|
22
|
+
level: Grade;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface ClassifierConfig {
|
|
26
|
+
enabled: boolean;
|
|
27
|
+
/** Model id for the small decision model; empty = first T1 model. */
|
|
28
|
+
model: string;
|
|
29
|
+
timeoutMs: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface FactoryConfig {
|
|
33
|
+
/** Master switch. When false the factory is fully inert. */
|
|
34
|
+
enabled: boolean;
|
|
35
|
+
/** Main-conversation auto routing — off by default, user opts in. */
|
|
36
|
+
mainAutoRoute: boolean;
|
|
37
|
+
auxRoute: { subagent: boolean; compaction: boolean };
|
|
38
|
+
tiers: { t1: string[]; t2: string[]; t3: string[] };
|
|
39
|
+
autoTiering: { enabled: boolean };
|
|
40
|
+
rules: CustomRule[];
|
|
41
|
+
classifier: ClassifierConfig;
|
|
42
|
+
affinity: { switchThreshold: number };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export const DEFAULT_CONFIG: FactoryConfig = {
|
|
46
|
+
enabled: true,
|
|
47
|
+
mainAutoRoute: false,
|
|
48
|
+
auxRoute: { subagent: true, compaction: true },
|
|
49
|
+
// Tiers are derived from the live deepailab catalog at session start
|
|
50
|
+
// (cheapest scores into t1, priciest into t3); name ids here to pin them.
|
|
51
|
+
tiers: { t1: [], t2: [], t3: [] },
|
|
52
|
+
autoTiering: { enabled: true },
|
|
53
|
+
rules: [],
|
|
54
|
+
// The classifier re-checks every grade the rule chain could not decide on a
|
|
55
|
+
// hard signal. Empty model = the cheapest capable deepailab model at route
|
|
56
|
+
// time, so the classifier follows the live catalog.
|
|
57
|
+
classifier: { enabled: true, model: "", timeoutMs: 800 },
|
|
58
|
+
affinity: { switchThreshold: 1 },
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
export function factoryConfigPath(): string {
|
|
62
|
+
return join(getAgentDir(), "factory.json");
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
66
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function stringArray(value: unknown): string[] | undefined {
|
|
70
|
+
return Array.isArray(value) && value.every((v) => typeof v === "string") ? (value as string[]) : undefined;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function numberInRange(value: unknown, min: number, max: number): number | undefined {
|
|
74
|
+
return typeof value === "number" && Number.isFinite(value) && value >= min && value <= max ? value : undefined;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Deep-merges a parsed JSON object over the defaults; unknown keys are ignored. */
|
|
78
|
+
function mergeConfig(base: FactoryConfig, patch: Record<string, unknown>): FactoryConfig {
|
|
79
|
+
const merged: FactoryConfig = { ...base };
|
|
80
|
+
if (typeof patch.enabled === "boolean") merged.enabled = patch.enabled;
|
|
81
|
+
if (typeof patch.mainAutoRoute === "boolean") merged.mainAutoRoute = patch.mainAutoRoute;
|
|
82
|
+
if (isRecord(patch.auxRoute)) {
|
|
83
|
+
merged.auxRoute = {
|
|
84
|
+
subagent: typeof patch.auxRoute.subagent === "boolean" ? patch.auxRoute.subagent : base.auxRoute.subagent,
|
|
85
|
+
compaction:
|
|
86
|
+
typeof patch.auxRoute.compaction === "boolean" ? patch.auxRoute.compaction : base.auxRoute.compaction,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
if (isRecord(patch.tiers)) {
|
|
90
|
+
merged.tiers = {
|
|
91
|
+
t1: stringArray(patch.tiers.t1) ?? base.tiers.t1,
|
|
92
|
+
t2: stringArray(patch.tiers.t2) ?? base.tiers.t2,
|
|
93
|
+
t3: stringArray(patch.tiers.t3) ?? base.tiers.t3,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
if (isRecord(patch.autoTiering) && typeof patch.autoTiering.enabled === "boolean") {
|
|
97
|
+
merged.autoTiering = { enabled: patch.autoTiering.enabled };
|
|
98
|
+
}
|
|
99
|
+
if (Array.isArray(patch.rules)) {
|
|
100
|
+
merged.rules = patch.rules.flatMap((rule) => {
|
|
101
|
+
if (!isRecord(rule) || typeof rule.match !== "string" || rule.match.length === 0) return [];
|
|
102
|
+
if (rule.level !== "l1" && rule.level !== "l2" && rule.level !== "l3") return [];
|
|
103
|
+
return [{ match: rule.match, level: rule.level }];
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
if (isRecord(patch.classifier)) {
|
|
107
|
+
merged.classifier = {
|
|
108
|
+
enabled: typeof patch.classifier.enabled === "boolean" ? patch.classifier.enabled : base.classifier.enabled,
|
|
109
|
+
model: typeof patch.classifier.model === "string" ? patch.classifier.model : base.classifier.model,
|
|
110
|
+
timeoutMs: numberInRange(patch.classifier.timeoutMs, 100, 10_000) ?? base.classifier.timeoutMs,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
if (isRecord(patch.affinity) && typeof patch.affinity.switchThreshold === "number") {
|
|
114
|
+
merged.affinity = { switchThreshold: Math.max(1, Math.floor(patch.affinity.switchThreshold)) };
|
|
115
|
+
}
|
|
116
|
+
return merged;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function loadFactoryConfig(): { config: FactoryConfig; warning?: string } {
|
|
120
|
+
const path = factoryConfigPath();
|
|
121
|
+
if (!existsSync(path)) return { config: DEFAULT_CONFIG };
|
|
122
|
+
try {
|
|
123
|
+
const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
|
|
124
|
+
if (!isRecord(parsed))
|
|
125
|
+
return { config: DEFAULT_CONFIG, warning: t(`${path}: 顶层不是 JSON 对象,已使用默认配置。`) };
|
|
126
|
+
return { config: mergeConfig(DEFAULT_CONFIG, parsed) };
|
|
127
|
+
} catch (error) {
|
|
128
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
129
|
+
return { config: DEFAULT_CONFIG, warning: `${path}: ${t("JSON 解析失败,已使用默认配置。")}${reason}` };
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function saveFactoryConfig(config: FactoryConfig): void {
|
|
134
|
+
const path = factoryConfigPath();
|
|
135
|
+
mkdirSync(join(path, ".."), { recursive: true });
|
|
136
|
+
writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`, "utf-8");
|
|
137
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Feature extraction and grade classification (L1/L2/L3).
|
|
3
|
+
*
|
|
4
|
+
* The rule path is deliberately LLM-free and network-free: every turn must be
|
|
5
|
+
* classifiable within the 100ms budget even with the network down. Only the
|
|
6
|
+
* ambiguous L2 band may be re-checked by the small-model classifier, and that
|
|
7
|
+
* path fail-opens back to the rule result.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import type { FactoryConfig, Grade } from "./config.ts";
|
|
11
|
+
|
|
12
|
+
export interface RouteFeatures {
|
|
13
|
+
/** ~4 chars/token, no tokenizer dependency. */
|
|
14
|
+
promptTokens: number;
|
|
15
|
+
/** Conversation turn count. */
|
|
16
|
+
turns: number;
|
|
17
|
+
hasImages: boolean;
|
|
18
|
+
/** Tool calls observed in recent history. */
|
|
19
|
+
recentToolCalls: number;
|
|
20
|
+
/** Rough session scale: number of entries in the transcript. */
|
|
21
|
+
entryCount: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export interface GradeDecision {
|
|
25
|
+
grade: Grade;
|
|
26
|
+
/** Where the grade came from: a preset rule, a custom rule, the classifier, or the L2 default. */
|
|
27
|
+
source: "preset-rule" | "custom-rule" | "classifier" | "default";
|
|
28
|
+
/** Human-readable reason for /factory status. */
|
|
29
|
+
reason: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** ~4 characters per token: coarse, dependency-free, good enough for gating. */
|
|
33
|
+
export function estimateTokens(text: string): number {
|
|
34
|
+
return Math.ceil(text.length / 4);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function extractFeatures(input: {
|
|
38
|
+
prompt: string;
|
|
39
|
+
turns: number;
|
|
40
|
+
hasImages: boolean;
|
|
41
|
+
recentToolCalls: number;
|
|
42
|
+
entryCount: number;
|
|
43
|
+
}): RouteFeatures {
|
|
44
|
+
return {
|
|
45
|
+
promptTokens: estimateTokens(input.prompt),
|
|
46
|
+
turns: input.turns,
|
|
47
|
+
hasImages: input.hasImages,
|
|
48
|
+
recentToolCalls: input.recentToolCalls,
|
|
49
|
+
entryCount: input.entryCount,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function matchesRule(pattern: string, prompt: string): boolean {
|
|
54
|
+
try {
|
|
55
|
+
return new RegExp(pattern, "i").test(prompt);
|
|
56
|
+
} catch {
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Preset rule chain, evaluated in order, first match wins. Thresholds are the
|
|
63
|
+
* design draft's initial values and are expected to be calibrated against
|
|
64
|
+
* real traffic.
|
|
65
|
+
*/
|
|
66
|
+
export function classifyByRules(features: RouteFeatures, prompt: string, config: FactoryConfig): GradeDecision {
|
|
67
|
+
if (features.hasImages) {
|
|
68
|
+
return { grade: "l3", source: "preset-rule", reason: "含图片输入" };
|
|
69
|
+
}
|
|
70
|
+
if (features.promptTokens > 2000) {
|
|
71
|
+
return { grade: "l3", source: "preset-rule", reason: `prompt 约 ${features.promptTokens} tokens` };
|
|
72
|
+
}
|
|
73
|
+
if (features.recentToolCalls >= 6) {
|
|
74
|
+
return { grade: "l3", source: "preset-rule", reason: `上一轮工具调用 ${features.recentToolCalls} 次` };
|
|
75
|
+
}
|
|
76
|
+
for (const rule of config.rules) {
|
|
77
|
+
if (matchesRule(rule.match, prompt)) {
|
|
78
|
+
return { grade: rule.level, source: "custom-rule", reason: `自定义规则命中 ${rule.match}` };
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (features.promptTokens < 200 && features.turns <= 2 && features.recentToolCalls === 0) {
|
|
82
|
+
return { grade: "l1", source: "preset-rule", reason: "短 prompt、会话初期、无工具调用" };
|
|
83
|
+
}
|
|
84
|
+
return { grade: "l2", source: "default", reason: "未命中强信号,默认中等档" };
|
|
85
|
+
}
|
|
@@ -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
|
+
}
|