dal-code 1.0.13 → 1.0.15

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 (72) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/core/agent-session-services.d.ts +7 -0
  3. package/dist/core/agent-session-services.d.ts.map +1 -1
  4. package/dist/core/agent-session-services.js +73 -0
  5. package/dist/core/agent-session-services.js.map +1 -1
  6. package/dist/core/model-runtime.d.ts +28 -0
  7. package/dist/core/model-runtime.d.ts.map +1 -1
  8. package/dist/core/model-runtime.js +49 -0
  9. package/dist/core/model-runtime.js.map +1 -1
  10. package/dist/main.d.ts.map +1 -1
  11. package/dist/main.js +8 -7
  12. package/dist/main.js.map +1 -1
  13. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  14. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  15. package/dist/node_modules/@dalcode/dal-gateway/src/index.ts +84 -84
  16. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  17. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  18. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  19. package/dist/node_modules/@dalcode/dal-lsp/package.json +3 -3
  20. package/dist/node_modules/@dalcode/dal-mcp/package.json +5 -5
  21. package/dist/node_modules/@dalcode/dal-mcp/src/index.ts +136 -9
  22. package/dist/node_modules/@dalcode/dal-office/package.json +2 -2
  23. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  24. package/dist/node_modules/@dalcode/dal-router/LICENSE +21 -0
  25. package/dist/node_modules/@dalcode/dal-router/package.json +36 -0
  26. package/dist/node_modules/@dalcode/dal-router/src/classifier.ts +80 -0
  27. package/dist/node_modules/@dalcode/dal-router/src/commands.ts +104 -0
  28. package/dist/node_modules/@dalcode/dal-router/src/config.ts +137 -0
  29. package/dist/node_modules/@dalcode/dal-router/src/features.ts +85 -0
  30. package/dist/node_modules/@dalcode/dal-router/src/index.ts +236 -0
  31. package/dist/node_modules/@dalcode/dal-router/src/router.ts +150 -0
  32. package/dist/node_modules/@dalcode/dal-router/src/runtime.ts +88 -0
  33. package/dist/node_modules/@dalcode/dal-router/src/small-model.ts +36 -0
  34. package/dist/node_modules/@dalcode/dal-router/src/subagent.ts +58 -0
  35. package/dist/node_modules/@dalcode/dal-router/src/tiers.ts +187 -0
  36. package/dist/node_modules/@dalcode/dal-skills/package.json +3 -3
  37. package/dist/node_modules/@dalcode/dal-skills/src/index.ts +65 -33
  38. package/dist/node_modules/@dalcode/dal-subagent/package.json +5 -5
  39. package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
  40. package/dist/node_modules/@dalcode/deepailab/package.json +4 -3
  41. package/dist/node_modules/@dalcode/deepailab/src/cache.ts +62 -0
  42. package/dist/node_modules/@dalcode/deepailab/src/index.ts +286 -127
  43. package/dist/node_modules/@earendil-works/chord/package.json +1 -1
  44. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  45. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  46. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
  47. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/anthropic.json +1 -1
  48. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/azure-openai-responses.json +1 -1
  49. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/cloudflare-workers-ai.json +1 -1
  50. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/github-copilot.json +1 -1
  51. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openai.json +1 -1
  52. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  53. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  54. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  55. package/dist/node_modules/@earendil-works/pi-ai/package.json +2 -2
  56. package/dist/node_modules/@earendil-works/pi-client/package.json +2 -2
  57. package/dist/node_modules/@earendil-works/pi-protocol/package.json +2 -2
  58. package/dist/node_modules/@earendil-works/pi-server/package.json +3 -3
  59. package/dist/node_modules/@earendil-works/pi-session-backend-sqlite-node/package.json +3 -3
  60. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  61. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  62. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  63. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  64. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  65. package/examples/extensions/gondolin/package-lock.json +2 -2
  66. package/examples/extensions/gondolin/package.json +1 -1
  67. package/examples/extensions/sandbox/package-lock.json +2 -2
  68. package/examples/extensions/sandbox/package.json +1 -1
  69. package/examples/extensions/with-deps/package-lock.json +2 -2
  70. package/examples/extensions/with-deps/package.json +1 -1
  71. package/npm-shrinkwrap.json +2 -2
  72. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-lang",
3
- "version": "1.0.13",
3
+ "version": "1.0.15",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -17,8 +17,8 @@
17
17
  ]
18
18
  },
19
19
  "dependencies": {
20
- "@dalcode/dal-pi-kit": "1.0.13",
21
- "@dalcode/dal-bridge": "1.0.13"
20
+ "@dalcode/dal-pi-kit": "1.0.15",
21
+ "@dalcode/dal-bridge": "1.0.15"
22
22
  },
23
23
  "peerDependencies": {
24
24
  "@earendil-works/pi-coding-agent": "^1.0.9"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-lsp",
3
- "version": "1.0.13",
3
+ "version": "1.0.15",
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-bridge": "1.0.13",
23
- "@dalcode/dal-pi-kit": "1.0.13",
22
+ "@dalcode/dal-bridge": "1.0.15",
23
+ "@dalcode/dal-pi-kit": "1.0.15",
24
24
  "cross-spawn": "7.0.6",
25
25
  "typebox": "1.3.7"
26
26
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-mcp",
3
- "version": "1.0.13",
3
+ "version": "1.0.15",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -23,10 +23,10 @@
23
23
  ]
24
24
  },
25
25
  "dependencies": {
26
- "@dalcode/dal-bridge": "1.0.13",
27
- "@dalcode/dal-guard": "1.0.13",
28
- "@dalcode/dal-pi-kit": "1.0.13",
29
- "@dalcode/deepailab": "1.0.13",
26
+ "@dalcode/dal-bridge": "1.0.15",
27
+ "@dalcode/dal-guard": "1.0.15",
28
+ "@dalcode/dal-pi-kit": "1.0.15",
29
+ "@dalcode/deepailab": "1.0.15",
30
30
  "cross-spawn": "7.0.6"
31
31
  },
32
32
  "peerDependencies": {
@@ -14,8 +14,10 @@
14
14
  * bypass the approval gate even if the pipeline around it changes.
15
15
  */
16
16
 
17
+ import { createHash } from "node:crypto";
17
18
  import { evaluateToolCall } from "@dalcode/dal-guard";
18
19
  import { t } from "@dalcode/dal-pi-kit";
20
+ import { accountTag, readCache, writeCache } from "@dalcode/deepailab/cache";
19
21
  import { defaultConfig } from "@dalcode/deepailab/oidc";
20
22
  import type { ExtensionAPI, ExtensionContext, ToolCallEvent } from "@earendil-works/pi-coding-agent";
21
23
  import { fetchAccountMcpServers } from "./account-layer.ts";
@@ -33,7 +35,13 @@ import { addMcpServerEntry, type McpConfigScope, removeMcpServerEntry } from "./
33
35
  import { McpHttpClient } from "./http-client.ts";
34
36
  import { type McpStatusItem, rememberMcpSessionId, reportMcpStatus } from "./report.ts";
35
37
  import { McpStdioClient } from "./stdio-client.ts";
36
- import { isHttpMcpConfig, type McpClient, type McpServerConfig, type McpTool } from "./types.ts";
38
+ import {
39
+ isHttpMcpConfig,
40
+ type McpClient,
41
+ type McpHttpServerConfig,
42
+ type McpServerConfig,
43
+ type McpTool,
44
+ } from "./types.ts";
37
45
 
38
46
  export type McpServerStatus = "connected" | "disconnected" | "failed";
39
47
 
@@ -52,6 +60,71 @@ export interface McpServerState {
52
60
  const registry = new Map<string, McpServerState>();
53
61
  const autoReconnectAttempted = new Set<string>();
54
62
  const AUTO_RECONNECT_DELAY_MS = 2_000;
63
+ /**
64
+ * Cache key for a server's tool list: the whole config, so a changed URL,
65
+ * command, argument or header is treated as a different server.
66
+ */
67
+ function toolCacheName(name: string, config: McpServerConfig): string {
68
+ return `mcp-tools-${createHash("sha256")
69
+ .update(JSON.stringify([name, config]))
70
+ .digest("hex")
71
+ .slice(0, 16)}`;
72
+ }
73
+
74
+ function isToolList(value: unknown): value is McpTool[] {
75
+ return (
76
+ Array.isArray(value) &&
77
+ value.every(
78
+ (tool) =>
79
+ typeof tool?.name === "string" &&
80
+ tool.name.length > 0 &&
81
+ (tool.description === undefined || typeof tool.description === "string") &&
82
+ (tool.inputSchema === undefined || (typeof tool.inputSchema === "object" && tool.inputSchema !== null)),
83
+ )
84
+ );
85
+ }
86
+
87
+ /**
88
+ * Cached account servers are held to the same rule as fetched ones (see
89
+ * account-layer.ts): https URLs only, never a command to spawn.
90
+ */
91
+ function isAccountServerMap(value: unknown): value is Record<string, McpHttpServerConfig> {
92
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return false;
93
+ return Object.values(value).every((entry) => {
94
+ if (typeof entry !== "object" || entry === null || "command" in entry) return false;
95
+ const { url, headers } = entry as { url?: unknown; headers?: unknown };
96
+ if (typeof url !== "string" || !url.startsWith("https://")) return false;
97
+ return (
98
+ headers === undefined ||
99
+ (typeof headers === "object" &&
100
+ headers !== null &&
101
+ Object.values(headers).every((header) => typeof header === "string"))
102
+ );
103
+ });
104
+ }
105
+
106
+ /**
107
+ * Stands in for a server that is not connected yet: a call first waits for
108
+ * `ensureConnected`, then goes to the live client, or fails with the connect
109
+ * error.
110
+ */
111
+ function pendingClient(name: string, ensureConnected: () => Promise<void>): McpClient {
112
+ return {
113
+ connect: ensureConnected,
114
+ listTools: async () => [],
115
+ callTool: async (tool, args) => {
116
+ await ensureConnected();
117
+ const state = registry.get(name);
118
+ if (!state?.client) {
119
+ throw new Error(
120
+ `${t('dal-mcp:连接 MCP 服务器 "')}${name}${t('" 失败:')}${state?.lastError ?? "not connected"}`,
121
+ );
122
+ }
123
+ return state.client.callTool(tool, args);
124
+ },
125
+ disconnect: () => {},
126
+ };
127
+ }
55
128
 
56
129
  /** Snapshot of every configured server's current connection state, for /mcp. */
57
130
  export function getMcpServerStates(): McpServerState[] {
@@ -182,6 +255,11 @@ async function connectServer(
182
255
  for (const tool of tools) {
183
256
  pi.registerTool(buildMcpToolDefinition(client, name, tool, cwd) as never);
184
257
  }
258
+ try {
259
+ writeCache(toolCacheName(name, config), tools);
260
+ } catch {
261
+ // An unwritable cache only costs the next session this same wait.
262
+ }
185
263
  state.client = client;
186
264
  state.tools = tools;
187
265
  state.status = "connected";
@@ -393,10 +471,29 @@ export default function (pi: ExtensionAPI) {
393
471
  try {
394
472
  const vk = await ctx.modelRegistry?.getApiKeyForProvider?.("deepailab");
395
473
  if (vk) {
396
- const layer = await fetchAccountMcpServers(defaultConfig().apiBase, vk);
397
- accountServers = layer.servers;
398
- for (const name of layer.rejected) {
399
- report(ctx, `${t("已拒绝账号下发的 MCP 条目(只接受 https 远程服务器):")}${name}`, "warning");
474
+ // Start from the last copy for this account and revalidate in the
475
+ // background; with no copy yet, wait for the fetch. A server the
476
+ // account adds is picked up by the next session.
477
+ const cacheName = `mcp-account-${accountTag(vk)}`;
478
+ const cached = readCache(cacheName, isAccountServerMap);
479
+ const revalidation = fetchAccountMcpServers(defaultConfig().apiBase, vk).then((layer) => {
480
+ for (const name of layer.rejected) {
481
+ report(ctx, `${t("已拒绝账号下发的 MCP 条目(只接受 https 远程服务器):")}${name}`, "warning");
482
+ }
483
+ try {
484
+ writeCache(cacheName, layer.servers);
485
+ } catch {
486
+ // An unwritable cache only costs the next session this same wait.
487
+ }
488
+ return layer.servers;
489
+ });
490
+ if (cached) {
491
+ accountServers = cached.value;
492
+ revalidation.catch((error) => {
493
+ report(ctx, `${t("无法获取账号的 MCP 配置:")}${errorMessage(error)}`, "warning");
494
+ });
495
+ } else {
496
+ accountServers = await revalidation;
400
497
  }
401
498
  }
402
499
  } catch (error) {
@@ -412,13 +509,43 @@ export default function (pi: ExtensionAPI) {
412
509
  for (const problem of takeMcpConfigProblems()) {
413
510
  report(ctx, `${t("MCP 配置有问题:")}${problem}`, "warning");
414
511
  }
512
+ // A server whose tool list is cached gets those tools registered now,
513
+ // without waiting for it: with a UI it connects in the background, and a
514
+ // headless run (`dal -p`, one process per DAL Office turn) connects only
515
+ // if the model calls one of its tools. A call made before the server is
516
+ // connected waits for the connection (pendingClient). Only servers seen
517
+ // for the first time hold up the session, and they connect in parallel.
518
+ // Connecting used to be serial and awaited: a hosted server needs three
519
+ // requests (initialize, initialized, tools/list), each a new connection
520
+ // taking 5-6s behind a proxy, so one such server added ~17s before every
521
+ // first turn, and a headless run paid it even when no MCP tool was used.
522
+ const firstConnections: Promise<void>[] = [];
415
523
  for (const [name, config] of Object.entries(servers)) {
416
- try {
417
- await connectServer(pi, name, config, ctx.cwd);
418
- } catch (error) {
419
- ctx.ui.notify(`${t('dal-mcp:连接 MCP 服务器 "')}${name}${t('" 失败:')}${errorMessage(error)}`, "warning");
524
+ let connection: Promise<void> | undefined;
525
+ const ensureConnected = (): Promise<void> => {
526
+ connection ??= connectServer(pi, name, config, ctx.cwd).then(
527
+ () => {},
528
+ (error) => {
529
+ report(
530
+ ctx,
531
+ `${t('dal-mcp:连接 MCP 服务器 "')}${name}${t('" 失败:')}${errorMessage(error)}`,
532
+ "warning",
533
+ );
534
+ },
535
+ );
536
+ return connection;
537
+ };
538
+ const cachedTools = readCache(toolCacheName(name, config), isToolList);
539
+ if (!cachedTools) {
540
+ firstConnections.push(ensureConnected());
541
+ continue;
542
+ }
543
+ for (const tool of cachedTools.value) {
544
+ pi.registerTool(buildMcpToolDefinition(pendingClient(name, ensureConnected), name, tool, ctx.cwd) as never);
420
545
  }
546
+ if (ctx.hasUI) void ensureConnected().then(pushMcpStatus);
421
547
  }
548
+ await Promise.all(firstConnections);
422
549
  pushMcpStatus();
423
550
  });
424
551
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-office",
3
- "version": "1.0.13",
3
+ "version": "1.0.15",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -17,7 +17,7 @@
17
17
  ]
18
18
  },
19
19
  "dependencies": {
20
- "@dalcode/dal-pi-kit": "1.0.13",
20
+ "@dalcode/dal-pi-kit": "1.0.15",
21
21
  "docx": "9.7.1",
22
22
  "echarts": "6.1.0",
23
23
  "exceljs": "4.4.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-pi-kit",
3
- "version": "1.0.13",
3
+ "version": "1.0.15",
4
4
  "private": true,
5
5
  "description": "Shared i18n helpers for DAL pi extensions. No engine peer.",
6
6
  "type": "module",
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Mario Zechner
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@dalcode/dal-router",
3
+ "version": "1.0.15",
4
+ "private": true,
5
+ "type": "module",
6
+ "main": "./src/index.ts",
7
+ "exports": {
8
+ ".": "./src/index.ts",
9
+ "./subagent": "./src/subagent.ts",
10
+ "./config": "./src/config.ts",
11
+ "./features": "./src/features.ts",
12
+ "./tiers": "./src/tiers.ts",
13
+ "./router": "./src/router.ts",
14
+ "./package.json": "./package.json"
15
+ },
16
+ "files": [
17
+ "src"
18
+ ],
19
+ "pi": {
20
+ "extensions": [
21
+ "./src/index.ts"
22
+ ]
23
+ },
24
+ "dependencies": {
25
+ "@dalcode/dal-pi-kit": "1.0.15",
26
+ "@earendil-works/pi-tui": "^1.0.15"
27
+ },
28
+ "peerDependencies": {
29
+ "@earendil-works/pi-coding-agent": "^1.0.0"
30
+ },
31
+ "peerDependenciesMeta": {
32
+ "@earendil-works/pi-coding-agent": {
33
+ "optional": false
34
+ }
35
+ }
36
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Small-model classifier for the ambiguous L2 band.
3
+ *
4
+ * One extra LLM call per trigger works against the cost goal, so this only
5
+ * runs when explicitly enabled, only on rule-graded L2, with a tight timeout
6
+ * and a tiny token budget. Any failure fail-opens to the rule result.
7
+ */
8
+
9
+ import type { FactoryConfig, Grade } from "./config.ts";
10
+
11
+ export interface ClassifierModel {
12
+ provider: string;
13
+ id: string;
14
+ }
15
+
16
+ export interface CompleteDeps {
17
+ find: (provider: string, id: string) => unknown;
18
+ hasConfiguredAuth: (model: unknown) => boolean;
19
+ complete: (model: unknown, context: unknown, options?: unknown) => Promise<unknown>;
20
+ signal?: AbortSignal;
21
+ }
22
+
23
+ const CLASSIFIER_SYSTEM_PROMPT =
24
+ "You are a task-complexity classifier for a coding agent. Answer with exactly one token: L1, L2 or L3. " +
25
+ "L1 = short single-turn Q&A, rewrites, formatting. L2 = normal coding: a small edit, a targeted question, " +
26
+ "a test top-up. L3 = multi-file refactors, architecture work, long context, images, deep debugging chains.";
27
+
28
+ function parseGrade(text: string): Grade | undefined {
29
+ const match = /L3|L2|L1/i.exec(text);
30
+ if (!match) return undefined;
31
+ const value = match[0].toLowerCase() as Grade;
32
+ return value;
33
+ }
34
+
35
+ /** Asks the small model to grade the prompt; throws only on setup failure. */
36
+ export async function classifyWithSmallModel(
37
+ deps: CompleteDeps,
38
+ prompt: string,
39
+ config: FactoryConfig,
40
+ ): Promise<Grade> {
41
+ const configured = config.classifier.model.trim();
42
+ const [provider, ...rest] = configured.split("/");
43
+ const id = rest.join("/") || configured;
44
+ const model = deps.find(provider, id);
45
+ if (!model) throw new Error(`classifier model not found: ${configured}`);
46
+ if (!deps.hasConfiguredAuth(model)) throw new Error(`classifier model has no configured auth: ${configured}`);
47
+
48
+ const controller = new AbortController();
49
+ const timer = setTimeout(() => controller.abort(), config.classifier.timeoutMs);
50
+ try {
51
+ const response = (await deps.complete(
52
+ model,
53
+ {
54
+ messages: [
55
+ {
56
+ role: "user",
57
+ content: [
58
+ {
59
+ type: "text",
60
+ text: `${CLASSIFIER_SYSTEM_PROMPT}\n\nTask:\n${prompt.slice(0, 8000)}`,
61
+ },
62
+ ],
63
+ timestamp: Date.now(),
64
+ },
65
+ ],
66
+ },
67
+ { signal: controller.signal },
68
+ )) as { content?: Array<{ type: string; text?: string }> };
69
+
70
+ const text = (response.content ?? [])
71
+ .filter((part) => part.type === "text" && typeof part.text === "string")
72
+ .map((part) => part.text as string)
73
+ .join(" ");
74
+ const grade = parseGrade(text);
75
+ if (!grade) throw new Error(`classifier returned an unparseable grade: ${text.slice(0, 80)}`);
76
+ return grade;
77
+ } finally {
78
+ clearTimeout(timer);
79
+ }
80
+ }
@@ -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
+ }