dal-code 0.1.2 → 0.1.7

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 (113) hide show
  1. package/dist/core/agent-session.d.ts +5 -0
  2. package/dist/core/agent-session.d.ts.map +1 -1
  3. package/dist/core/agent-session.js +7 -0
  4. package/dist/core/agent-session.js.map +1 -1
  5. package/dist/core/auth-guidance.d.ts.map +1 -1
  6. package/dist/core/auth-guidance.js +5 -1
  7. package/dist/core/auth-guidance.js.map +1 -1
  8. package/dist/core/extensions/types.d.ts +15 -1
  9. package/dist/core/extensions/types.d.ts.map +1 -1
  10. package/dist/core/extensions/types.js.map +1 -1
  11. package/dist/core/house-providers.d.ts +81 -0
  12. package/dist/core/house-providers.d.ts.map +1 -0
  13. package/dist/core/house-providers.js +128 -0
  14. package/dist/core/house-providers.js.map +1 -0
  15. package/dist/core/model-resolver.d.ts.map +1 -1
  16. package/dist/core/model-resolver.js +1 -3
  17. package/dist/core/model-resolver.js.map +1 -1
  18. package/dist/core/model-runtime.d.ts.map +1 -1
  19. package/dist/core/model-runtime.js +11 -0
  20. package/dist/core/model-runtime.js.map +1 -1
  21. package/dist/core/tools/bash.d.ts.map +1 -1
  22. package/dist/core/tools/bash.js +15 -2
  23. package/dist/core/tools/bash.js.map +1 -1
  24. package/dist/core/trust-manager.d.ts.map +1 -1
  25. package/dist/core/trust-manager.js +7 -0
  26. package/dist/core/trust-manager.js.map +1 -1
  27. package/dist/dal/builtins.d.ts +15 -0
  28. package/dist/dal/builtins.d.ts.map +1 -1
  29. package/dist/dal/builtins.js +22 -0
  30. package/dist/dal/builtins.js.map +1 -1
  31. package/dist/main.d.ts.map +1 -1
  32. package/dist/main.js +3 -1
  33. package/dist/main.js.map +1 -1
  34. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  35. package/dist/modes/interactive/components/model-selector.js +3 -2
  36. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  37. package/dist/modes/interactive/interactive-mode.d.ts +6 -0
  38. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  39. package/dist/modes/interactive/interactive-mode.js +81 -42
  40. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  41. package/dist/modes/interactive/session-share.d.ts.map +1 -1
  42. package/dist/modes/interactive/session-share.js +6 -5
  43. package/dist/modes/interactive/session-share.js.map +1 -1
  44. package/dist/node_modules/@dalcode/dal-bridge/package.json +2 -2
  45. package/dist/node_modules/@dalcode/dal-gateway/package.json +2 -2
  46. package/dist/node_modules/@dalcode/dal-gateway/src/index.ts +21 -12
  47. package/dist/node_modules/@dalcode/dal-guard/package.json +4 -4
  48. package/dist/node_modules/@dalcode/dal-halo/package.json +1 -1
  49. package/dist/node_modules/@dalcode/dal-lang/package.json +3 -3
  50. package/dist/node_modules/@dalcode/dal-lang/src/index.ts +19 -2
  51. package/dist/node_modules/@dalcode/dal-lsp/package.json +6 -3
  52. package/dist/node_modules/@dalcode/dal-lsp/src/client.ts +241 -0
  53. package/dist/node_modules/@dalcode/dal-lsp/src/config.ts +176 -0
  54. package/dist/node_modules/@dalcode/dal-lsp/src/format.ts +88 -0
  55. package/dist/node_modules/@dalcode/dal-lsp/src/index.ts +149 -42
  56. package/dist/node_modules/@dalcode/dal-lsp/src/types.ts +21 -0
  57. package/dist/node_modules/@dalcode/dal-mcp/package.json +4 -4
  58. package/dist/node_modules/@dalcode/dal-mcp/src/config.ts +25 -3
  59. package/dist/node_modules/@dalcode/dal-mcp/src/index.ts +6 -1
  60. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.d.ts +8 -1
  61. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.d.ts.map +1 -1
  62. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js +89 -4
  63. package/dist/node_modules/@dalcode/dal-pi-kit/dist/i18n.js.map +1 -1
  64. package/dist/node_modules/@dalcode/dal-pi-kit/package.json +1 -1
  65. package/dist/node_modules/@dalcode/dal-pi-kit/src/i18n.ts +97 -5
  66. package/dist/node_modules/@dalcode/dal-skills/LICENSE +21 -0
  67. package/dist/node_modules/@dalcode/dal-skills/package.json +33 -0
  68. package/dist/node_modules/@dalcode/dal-skills/src/client.ts +96 -0
  69. package/dist/node_modules/@dalcode/dal-skills/src/index.ts +156 -0
  70. package/dist/node_modules/@dalcode/dal-subagent/package.json +3 -3
  71. package/dist/node_modules/@dalcode/dal-telemetry/package.json +2 -2
  72. package/dist/node_modules/@dalcode/dal-telemetry/src/config.ts +31 -8
  73. package/dist/node_modules/@dalcode/dal-telemetry/src/index.ts +12 -4
  74. package/dist/node_modules/@dalcode/dal-telemetry/src/reporter.ts +14 -1
  75. package/dist/node_modules/@dalcode/deepailab/package.json +2 -2
  76. package/dist/node_modules/@dalcode/deepailab/src/index.ts +111 -21
  77. package/dist/node_modules/@dalcode/deepailab/src/model-defaults.ts +109 -5
  78. package/dist/node_modules/@earendil-works/pi-agent-core/package.json +1 -1
  79. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.d.ts.map +1 -1
  80. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js +18 -1
  81. package/dist/node_modules/@earendil-works/pi-ai/dist/api/openai-completions.js.map +1 -1
  82. package/dist/node_modules/@earendil-works/pi-ai/dist/env-api-keys.d.ts +1 -0
  83. package/dist/node_modules/@earendil-works/pi-ai/dist/env-api-keys.d.ts.map +1 -1
  84. package/dist/node_modules/@earendil-works/pi-ai/dist/env-api-keys.js +18 -0
  85. package/dist/node_modules/@earendil-works/pi-ai/dist/env-api-keys.js.map +1 -1
  86. package/dist/node_modules/@earendil-works/pi-ai/dist/index.d.ts +1 -0
  87. package/dist/node_modules/@earendil-works/pi-ai/dist/index.d.ts.map +1 -1
  88. package/dist/node_modules/@earendil-works/pi-ai/dist/index.js +3 -0
  89. package/dist/node_modules/@earendil-works/pi-ai/dist/index.js.map +1 -1
  90. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  91. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/amazon-bedrock.json +1 -1
  92. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/baseten.json +1 -1
  93. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/fireworks.json +1 -1
  94. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/huggingface.json +1 -1
  95. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  96. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  97. package/dist/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  98. package/dist/node_modules/@earendil-works/pi-ai/package.json +1 -1
  99. package/dist/node_modules/@earendil-works/pi-client/package.json +1 -1
  100. package/dist/node_modules/@earendil-works/pi-protocol/package.json +1 -1
  101. package/dist/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  102. package/dist/node_modules/@earendil-works/pi-tui/package.json +1 -1
  103. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  104. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  105. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  106. package/examples/extensions/gondolin/package-lock.json +2 -2
  107. package/examples/extensions/gondolin/package.json +1 -1
  108. package/examples/extensions/sandbox/package-lock.json +2 -2
  109. package/examples/extensions/sandbox/package.json +1 -1
  110. package/examples/extensions/with-deps/package-lock.json +2 -2
  111. package/examples/extensions/with-deps/package.json +1 -1
  112. package/npm-shrinkwrap.json +2 -2
  113. package/package.json +1 -1
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Talks to the DeepAILab skill service.
3
+ *
4
+ * Two calls, split on purpose. The index is what every session pays for, so it
5
+ * carries names and one-line descriptions and nothing else — a few hundred
6
+ * bytes for a catalogue of any size. A body is fetched only once the model has
7
+ * decided it wants that skill, which is also what keeps the system prompt
8
+ * small: the agent sees a menu, not the meals.
9
+ */
10
+
11
+ export interface SkillSummary {
12
+ readonly id: string;
13
+ readonly name: string;
14
+ readonly description: string;
15
+ /** Server-side revision. Shown in /skills so a user can say which they have. */
16
+ readonly version?: string;
17
+ }
18
+
19
+ export interface SkillBody extends SkillSummary {
20
+ readonly body: string;
21
+ }
22
+
23
+ export interface SkillsIndex {
24
+ readonly skills: readonly SkillSummary[];
25
+ /** Opaque; sent back as If-None-Match so an unchanged catalogue costs nothing. */
26
+ readonly etag?: string;
27
+ }
28
+
29
+ /**
30
+ * Bounded so an unreachable gateway delays the session rather than hanging it.
31
+ * The index is on the session-start path, so it gets the tighter budget; a body
32
+ * fetch happens mid-turn, where the model is already waiting.
33
+ */
34
+ const INDEX_TIMEOUT_MS = 8_000;
35
+ const BODY_TIMEOUT_MS = 15_000;
36
+
37
+ async function getJson<T>(url: string, vk: string, timeoutMs: number, etag?: string): Promise<T | "not-modified"> {
38
+ const controller = new AbortController();
39
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
40
+ try {
41
+ const res = await fetch(url, {
42
+ headers: {
43
+ "x-bf-vk": vk,
44
+ Accept: "application/json",
45
+ ...(etag ? { "If-None-Match": etag } : {}),
46
+ },
47
+ signal: controller.signal,
48
+ });
49
+ if (res.status === 304) return "not-modified";
50
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
51
+ return (await res.json()) as T;
52
+ } finally {
53
+ clearTimeout(timer);
54
+ }
55
+ }
56
+
57
+ export async function fetchSkillIndex(
58
+ apiBase: string,
59
+ vk: string,
60
+ etag?: string,
61
+ ): Promise<SkillsIndex | "not-modified"> {
62
+ const body = await getJson<{ skills?: SkillSummary[]; etag?: string }>(
63
+ `${apiBase}/portal/skills`,
64
+ vk,
65
+ INDEX_TIMEOUT_MS,
66
+ etag,
67
+ );
68
+ if (body === "not-modified") return "not-modified";
69
+ const skills = (body.skills ?? []).filter(
70
+ (s): s is SkillSummary =>
71
+ typeof s?.id === "string" &&
72
+ s.id.length > 0 &&
73
+ typeof s.name === "string" &&
74
+ typeof s.description === "string",
75
+ );
76
+ return { skills, etag: body.etag };
77
+ }
78
+
79
+ export async function fetchSkillBody(apiBase: string, vk: string, id: string): Promise<SkillBody> {
80
+ const body = await getJson<Partial<SkillBody>>(
81
+ `${apiBase}/portal/skills/${encodeURIComponent(id)}`,
82
+ vk,
83
+ BODY_TIMEOUT_MS,
84
+ );
85
+ if (body === "not-modified") throw new Error("unexpected 304 for a skill body");
86
+ if (typeof body.body !== "string" || body.body.length === 0) {
87
+ throw new Error("the service returned a skill with no content");
88
+ }
89
+ return {
90
+ id,
91
+ name: typeof body.name === "string" ? body.name : id,
92
+ description: typeof body.description === "string" ? body.description : "",
93
+ version: typeof body.version === "string" ? body.version : undefined,
94
+ body: body.body,
95
+ };
96
+ }
@@ -0,0 +1,156 @@
1
+ /**
2
+ * dal-skills: skills served from DeepAILab, not shipped to disk.
3
+ *
4
+ * pi's own skill system reads markdown out of `~/.dal/agent/skills` and
5
+ * `<project>/.dal/skills`. That model does not fit a commercial product: every
6
+ * user would have to download and then keep re-downloading a growing library,
7
+ * and a correction we make today would only reach the people who happened to
8
+ * update. Nothing here touches the filesystem.
9
+ *
10
+ * How the agent sees them:
11
+ *
12
+ * - At session start we fetch the *index* — names and one-line descriptions,
13
+ * a few hundred bytes — and register a single `skill` tool whose
14
+ * description lists them. That list is the whole of what enters the system
15
+ * prompt, so a catalogue of five and a catalogue of five hundred cost
16
+ * roughly the same.
17
+ * - The model calls `skill` with a name when a task matches. Only then is the
18
+ * body fetched, and only that one body.
19
+ *
20
+ * The effect is that the server is the single source of truth: edit a skill
21
+ * there and the next session everywhere is already using it.
22
+ *
23
+ * This runs alongside pi's local skills rather than replacing them — a user or
24
+ * a project can still keep private ones on disk.
25
+ */
26
+
27
+ import { t } from "@dalcode/dal-pi-kit";
28
+ import { defaultConfig } from "@dalcode/deepailab/oidc";
29
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
30
+ import { Type } from "typebox";
31
+ import { fetchSkillBody, fetchSkillIndex, type SkillSummary } from "./client.ts";
32
+
33
+ const skillSchema = Type.Object({
34
+ name: Type.String({ description: t("要加载的技能名称,取自本工具描述中列出的清单") }),
35
+ });
36
+
37
+ /** Cheap guard against a skill whose body is enormous by accident. */
38
+ const MAX_BODY_CHARS = 60_000;
39
+
40
+ function describeTool(skills: readonly SkillSummary[]): string {
41
+ const lines = [
42
+ t(
43
+ "加载一个 DeepAILab 技能:针对特定任务的专门指引。当手头任务与下列某条描述相符时调用本工具,然后按返回的指引执行。",
44
+ ),
45
+ "",
46
+ t("可用技能:"),
47
+ ...skills.map((s) => `- ${s.name}: ${s.description}`),
48
+ ];
49
+ return lines.join("\n");
50
+ }
51
+
52
+ export default function (pi: ExtensionAPI) {
53
+ const cfg = defaultConfig();
54
+ // Per session, not per call: a skill loaded twice in one conversation should
55
+ // not cost two round trips, while a new session still picks up an edit made
56
+ // on the server a minute ago.
57
+ const bodies = new Map<string, string>();
58
+ let catalogue: readonly SkillSummary[] = [];
59
+
60
+ const resolve = (query: string): SkillSummary | undefined => {
61
+ const needle = query.trim().toLowerCase();
62
+ return (
63
+ catalogue.find((s) => s.name.toLowerCase() === needle || s.id.toLowerCase() === needle) ??
64
+ catalogue.find((s) => s.name.toLowerCase().includes(needle))
65
+ );
66
+ };
67
+
68
+ pi.on("session_start", async (_event, ctx: ExtensionContext) => {
69
+ let vk: string | undefined;
70
+ try {
71
+ vk = await ctx.modelRegistry?.getApiKeyForProvider?.("deepailab");
72
+ } catch {
73
+ vk = undefined;
74
+ }
75
+ // Signed out: say nothing and register nothing. An empty `skill` tool in
76
+ // the prompt is worse than no tool — the model tries it and gets told off.
77
+ if (!vk) return;
78
+
79
+ try {
80
+ const index = await fetchSkillIndex(cfg.apiBase, vk);
81
+ if (index === "not-modified") return;
82
+ catalogue = index.skills;
83
+ } catch (error) {
84
+ // Not silent: skills the user is paying for quietly not being there is
85
+ // exactly the class of failure this codebase keeps getting bitten by.
86
+ const reason = error instanceof Error && error.name === "AbortError" ? t("请求超时") : String(error);
87
+ ctx.ui?.notify?.(`${t("无法获取云端技能列表")}:${reason}`, "warning");
88
+ return;
89
+ }
90
+
91
+ if (catalogue.length === 0) return;
92
+
93
+ pi.registerTool({
94
+ name: "skill",
95
+ label: t("技能"),
96
+ description: describeTool(catalogue),
97
+ promptSnippet: t("skill - 加载 DeepAILab 云端技能(专项任务指引)"),
98
+ parameters: skillSchema,
99
+ execute: async (_id: string, params: { name: string }) => {
100
+ const match = resolve(params.name);
101
+ if (!match) {
102
+ return {
103
+ content: [
104
+ {
105
+ type: "text" as const,
106
+ text: `${t("没有这个技能:")}${params.name}\n${t("可用:")}${catalogue.map((s) => s.name).join(", ")}`,
107
+ },
108
+ ],
109
+ details: { ok: false },
110
+ };
111
+ }
112
+ const cached = bodies.get(match.id);
113
+ if (cached !== undefined) {
114
+ return { content: [{ type: "text" as const, text: cached }], details: { id: match.id, cached: true } };
115
+ }
116
+ try {
117
+ const loaded = await fetchSkillBody(cfg.apiBase, vk, match.id);
118
+ const body =
119
+ loaded.body.length > MAX_BODY_CHARS
120
+ ? `${loaded.body.slice(0, MAX_BODY_CHARS)}\n\n…(truncated)`
121
+ : loaded.body;
122
+ bodies.set(match.id, body);
123
+ return {
124
+ content: [{ type: "text" as const, text: body }],
125
+ details: { id: match.id, version: loaded.version },
126
+ };
127
+ } catch (error) {
128
+ return {
129
+ content: [
130
+ {
131
+ type: "text" as const,
132
+ text: `${t("加载技能失败:")}${match.name} — ${error instanceof Error ? error.message : String(error)}`,
133
+ },
134
+ ],
135
+ details: { ok: false },
136
+ };
137
+ }
138
+ },
139
+ } as never);
140
+ });
141
+
142
+ pi.registerCommand("skills", {
143
+ description: t("查看可用的 DeepAILab 云端技能"),
144
+ handler: async (_args: string, ctx: ExtensionContext) => {
145
+ if (catalogue.length === 0) {
146
+ ctx.ui.notify(t("当前没有可用的云端技能(未登录,或服务端目录为空)。"), "info");
147
+ return;
148
+ }
149
+ ctx.ui.notify(
150
+ `${t("云端技能")} (${catalogue.length})\n` +
151
+ catalogue.map((s) => ` ${s.name}${s.version ? ` v${s.version}` : ""} — ${s.description}`).join("\n"),
152
+ "info",
153
+ );
154
+ },
155
+ });
156
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-subagent",
3
- "version": "0.1.2",
3
+ "version": "0.1.7",
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": "0.1.2",
21
- "@dalcode/dal-guard": "0.1.2",
20
+ "@dalcode/dal-pi-kit": "0.1.7",
21
+ "@dalcode/dal-guard": "0.1.7",
22
22
  "@earendil-works/pi-agent-core": "^0.1.2",
23
23
  "@earendil-works/pi-ai": "^0.1.2",
24
24
  "typebox": "1.3.7"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-telemetry",
3
- "version": "0.1.2",
3
+ "version": "0.1.7",
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": "0.1.2"
23
+ "@dalcode/dal-pi-kit": "0.1.7"
24
24
  },
25
25
  "peerDependencies": {
26
26
  "@earendil-works/pi-coding-agent": "^0.1.2"
@@ -18,6 +18,7 @@
18
18
  import { randomUUID } from "node:crypto";
19
19
  import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
20
20
  import { join } from "node:path";
21
+ import { DEFAULT_ENDPOINT } from "./reporter.ts";
21
22
 
22
23
  export interface TelemetryState {
23
24
  enabled: boolean;
@@ -34,7 +35,13 @@ export interface TelemetryDecision {
34
35
  /** Show the one-time notice before anything is sent. */
35
36
  shouldNotify: boolean;
36
37
  /** Why it is off, for `/telemetry` to explain rather than just say "off". */
37
- reason?: "opted-out" | "do-not-track" | "env" | "ci" | "unreadable";
38
+ reason?: "opted-out" | "do-not-track" | "env" | "ci" | "unreadable" | "unconfigured";
39
+ }
40
+
41
+ /** The configured collector URL, or undefined when there is none. */
42
+ export function resolveEndpoint(env: NodeJS.ProcessEnv = process.env): string | undefined {
43
+ const raw = env.DAL_TELEMETRY_ENDPOINT ?? DEFAULT_ENDPOINT;
44
+ return raw.length > 0 ? raw : undefined;
38
45
  }
39
46
 
40
47
  function isCi(env: NodeJS.ProcessEnv): boolean {
@@ -92,20 +99,36 @@ export function resolveTelemetry(agentDir: string, env: NodeJS.ProcessEnv = proc
92
99
  }
93
100
  if (isCi(env)) return { state, active: false, shouldNotify: false, reason: "ci" };
94
101
 
95
- // First run: persist the identity and the fact that we are about to say so.
96
- // If that write fails we stay off — reporting without a durable record of the
97
- // notice would mean showing it on every single run, or never.
98
- if (!existing || !state.notifiedAt) {
99
- const seeded: TelemetryState = { ...state, notifiedAt: new Date().toISOString() };
100
- if (!writeState(agentDir, seeded)) {
102
+ // No collector, no collection — and no notice claiming otherwise. Checked
103
+ // after the opt-outs so `/telemetry` still reports the user's own choice in
104
+ // preference to an infrastructure gap.
105
+ if (!resolveEndpoint(env)) return { state, active: false, shouldNotify: false, reason: "unconfigured" };
106
+
107
+ // First run: persist the identity only. `notifiedAt` is written by
108
+ // markNotified(), after the notice has actually been rendered — stamping it
109
+ // here meant a headless first run (`dal -p`, where there is no UI to show it)
110
+ // recorded the user as told while nothing was ever displayed, and every later
111
+ // run then skipped the notice.
112
+ if (!existing) {
113
+ if (!writeState(agentDir, state)) {
101
114
  return { state, active: false, shouldNotify: false, reason: "unreadable" };
102
115
  }
103
- return { state: seeded, active: true, shouldNotify: true };
104
116
  }
117
+ if (!state.notifiedAt) return { state, active: true, shouldNotify: true };
105
118
 
106
119
  return { state, active: true, shouldNotify: false };
107
120
  }
108
121
 
122
+ /**
123
+ * Records that the one-time notice was shown. Called by the caller that renders
124
+ * it, never by resolveTelemetry — see the comment there.
125
+ */
126
+ export function markNotified(agentDir: string, state: TelemetryState): TelemetryState {
127
+ const next: TelemetryState = { ...state, notifiedAt: new Date().toISOString() };
128
+ writeState(agentDir, next);
129
+ return next;
130
+ }
131
+
109
132
  export function setTelemetryEnabled(agentDir: string, enabled: boolean): TelemetryState {
110
133
  const current = readState(telemetryPath(agentDir)) ?? { enabled, anonymousId: randomUUID() };
111
134
  const next: TelemetryState = { ...current, enabled, notifiedAt: current.notifiedAt ?? new Date().toISOString() };
@@ -36,9 +36,9 @@ interface ModelSelectEventShape {
36
36
  }
37
37
 
38
38
  import { getAgentDir, VERSION } from "@earendil-works/pi-coding-agent";
39
- import { resolveTelemetry, setTelemetryEnabled } from "./config.ts";
39
+ import { markNotified, resolveEndpoint, resolveTelemetry, setTelemetryEnabled } from "./config.ts";
40
40
  import { redactMessage, redactStack, redactToolName } from "./redact.ts";
41
- import { DEFAULT_ENDPOINT, TelemetryReporter } from "./reporter.ts";
41
+ import { TelemetryReporter } from "./reporter.ts";
42
42
 
43
43
  export default function (pi: ExtensionAPI) {
44
44
  const agentDir = getAgentDir();
@@ -70,7 +70,9 @@ export default function (pi: ExtensionAPI) {
70
70
  if (!decision.active) return;
71
71
 
72
72
  const reporter = new TelemetryReporter({
73
- endpoint: process.env.DAL_TELEMETRY_ENDPOINT ?? DEFAULT_ENDPOINT,
73
+ // Non-null: resolveTelemetry returns active:false when there is no
74
+ // endpoint, and we returned above on that.
75
+ endpoint: resolveEndpoint() as string,
74
76
  anonymousId: decision.state.anonymousId,
75
77
  appVersion: VERSION,
76
78
  });
@@ -79,11 +81,17 @@ export default function (pi: ExtensionAPI) {
79
81
  let turns = 0;
80
82
 
81
83
  pi.on("session_start", async (event: SessionStartEvent, ctx: ExtensionContext) => {
82
- if (decision.shouldNotify && ctx.hasUI) {
84
+ if (decision.shouldNotify) {
85
+ // Nothing is reported until the notice has been seen. A headless run
86
+ // has nowhere to show it, so it stays pending for the next TUI launch
87
+ // rather than being reported behind the user's back.
88
+ if (!ctx.hasUI) return;
83
89
  ctx.ui.notify(
84
90
  t("DAL 会发送匿名使用统计(不含代码、提示词和文件路径)以改进产品。/telemetry off 可关闭。"),
85
91
  "info",
86
92
  );
93
+ markNotified(agentDir, decision.state);
94
+ decision.shouldNotify = false;
87
95
  }
88
96
  reporter.record({ name: "session_start", props: { reason: event.reason } });
89
97
  });
@@ -36,7 +36,20 @@ const MAX_QUEUE = 200;
36
36
  const UPLOAD_TIMEOUT_MS = 3000;
37
37
  const SHUTDOWN_TIMEOUT_MS = 1500;
38
38
 
39
- export const DEFAULT_ENDPOINT = "https://telemetry.deepailab.ai/v1/events";
39
+ /**
40
+ * Empty until the collector exists.
41
+ *
42
+ * This pointed at `https://telemetry.deepailab.ai/v1/events`, which has never
43
+ * resolved — NXDOMAIN from an unproxied resolver, verified 2026-09-11. Every
44
+ * upload failed and the reporter swallowed it, so the product carried the cost
45
+ * of a consent notice and a PRIVACY.md section while receiving nothing.
46
+ *
47
+ * An unset endpoint now switches telemetry off outright (see config.ts), which
48
+ * is the truthful state: nothing is collected, and nobody is told otherwise.
49
+ * Publishing the DNS record and setting this constant — or DAL_TELEMETRY_ENDPOINT
50
+ * — turns it back on, notice and all.
51
+ */
52
+ export const DEFAULT_ENDPOINT = "";
40
53
 
41
54
  export class TelemetryReporter {
42
55
  private queue: Array<TelemetryEvent & { ts: number }> = [];
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/deepailab",
3
- "version": "0.1.2",
3
+ "version": "0.1.7",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -19,7 +19,7 @@
19
19
  ]
20
20
  },
21
21
  "dependencies": {
22
- "@dalcode/dal-pi-kit": "0.1.2",
22
+ "@dalcode/dal-pi-kit": "0.1.7",
23
23
  "@earendil-works/pi-ai": "^0.1.2"
24
24
  },
25
25
  "peerDependencies": {
@@ -40,11 +40,17 @@ function toCredentials(tokens: TokenSet, vk: string): OAuthCredentials {
40
40
  }
41
41
 
42
42
  /**
43
- * The gateway (Bifrost) authenticates inference with a long-lived virtual key
44
- * sent in the `x-bf-vk` header — NOT the OIDC bearer. The Bridge mints one from
45
- * a fresh OIDC access_token; the secret is returned exactly once, so it is
46
- * stored inside the OAuth credentials and reused until logout.
47
- * (Verified live 2026-07-04: Bearer <vk> is ignored, x-bf-vk works.)
43
+ * The gateway (Bifrost) authenticates inference with a long-lived virtual key,
44
+ * not the OIDC bearer. The Bridge mints one from a fresh OIDC access_token; the
45
+ * secret is returned exactly once, so it is stored inside the OAuth credentials
46
+ * and reused until logout.
47
+ *
48
+ * The key travels in `Authorization: Bearer`. An earlier note here said the
49
+ * gateway ignored that header and only honoured `x-bf-vk` (checked 2026-07-04);
50
+ * re-checked live 2026-09-11, both are accepted and return identical
51
+ * completions. Bearer is the one to use — it is what every OpenAI-compatible
52
+ * client sends, so a custom header would lock those clients out of the gateway
53
+ * for no gain.
48
54
  */
49
55
  async function createVirtualKey(apiBase: string, accessToken: string): Promise<string> {
50
56
  const res = await fetch(`${apiBase}/portal/keys/lifecycle`, {
@@ -139,11 +145,18 @@ export async function refreshDeepAILab(credentials: OAuthCredentials): Promise<O
139
145
  return toCredentials(tokens, vk);
140
146
  }
141
147
 
142
- // Seed catalog = models verified live against the gateway (2026-07-04);
143
- // metadata/compat come from gatewayModelDefaults (builtin catalog lookup +
144
- // gateway dialect). Others appear via the dynamic catalog once the gateway
145
- // binds their provider keys.
146
- const SEED_MODELS = [gatewayModelDefaults("glm-5.2", "GLM 5.2")];
148
+ // No seed catalog. The gateway's list is the only truth about what can be
149
+ // used, and it needs a credential, so a logged-out user has no models — which
150
+ // is accurate, since they cannot call one either. The UI already says
151
+ // "Use /login to add providers".
152
+ //
153
+ // A hardcoded placeholder was worse than nothing. It went stale twice in one
154
+ // day: it named "glm-5.2" after the gateway namespaced its ids to
155
+ // "aook/glm-5.2", and then named "aook/glm-5.2" after the gateway's published
156
+ // list became deepseek-flash / deepseek-v4-pro / gpt-5.6-sol. Each time it
157
+ // showed a model that could not be selected, and each time the model a user
158
+ // picked before logging in vanished from the list right after.
159
+ const SEED_MODELS: ReturnType<typeof gatewayModelDefaults>[] = [];
147
160
 
148
161
  export default function (pi: ExtensionAPI) {
149
162
  const cfg = defaultConfig();
@@ -171,27 +184,82 @@ export default function (pi: ExtensionAPI) {
171
184
  });
172
185
 
173
186
  // Refresh the model catalog from the gateway once credentials are available.
174
- // Best-effort: any failure keeps the seed list.
175
- pi.on("session_start", async (_event, ctx) => {
187
+ // Not best-effort any more: with no seed list, a failure here means zero
188
+ // models, so it is reported rather than swallowed.
189
+ //
190
+ // Runs on two events, and needs both. At session_start a returning user is
191
+ // already logged in and gets the full list immediately; a new user is not, so
192
+ // the fetch is skipped and they would sit on the seed model until they
193
+ // restarted. provider_authenticated closes that gap — it fires the moment
194
+ // /login completes, before the model picker opens.
195
+ const refreshCatalog = async (ctx: {
196
+ modelRegistry: { getApiKeyForProvider(id: string): Promise<string | undefined> };
197
+ ui?: { notify(message: string, level: "info" | "warning" | "error"): void };
198
+ }) => {
199
+ // The catalog is the only source of models now that the seed list is gone,
200
+ // so a failure has to be visible. `ui` is optional because refreshCatalog
201
+ // also runs in headless (`dal -p`) sessions, where stderr is the channel.
202
+ const reportFailure = (reason: string): void => {
203
+ const message = `${t("无法获取模型列表")}:${reason}`;
204
+ if (ctx.ui) ctx.ui.notify(message, "error");
205
+ else process.stderr.write(`${message}\n`);
206
+ };
207
+ // Hoisted so the finally below can clear it: declared inside the try, an
208
+ // error thrown by fetch or res.json() left the 20s timer running and
209
+ // delayed `dal -p` exiting.
210
+ //
211
+ // The gateway answers /models in a steady ~5.6s (measured 2026-09-11:
212
+ // 5.64 / 5.58 / 5.66). The previous 5s deadline therefore aborted every
213
+ // single refresh, and the catch below swallowed it — a signed-in user saw
214
+ // nothing on screen to say why. The budget is now well clear of that, and
215
+ // still bounded so an unreachable gateway cannot hang the session.
216
+ const controller = new AbortController();
217
+ let timer: ReturnType<typeof setTimeout> | undefined;
176
218
  try {
177
219
  const token = await ctx.modelRegistry.getApiKeyForProvider("deepailab");
178
220
  if (!token) return;
179
- const controller = new AbortController();
180
- const timer = setTimeout(() => controller.abort(), 5000);
221
+ timer = setTimeout(() => controller.abort(), 20_000);
181
222
  const res = await fetch(`${cfg.apiBase}/models`, {
182
223
  headers: { "x-bf-vk": token, Accept: "application/json" },
183
224
  signal: controller.signal,
184
225
  });
185
- clearTimeout(timer);
186
- if (!res.ok) return;
187
- const body = (await res.json()) as { data?: Array<{ id?: string; name?: string }> };
226
+ if (!res.ok) {
227
+ // 401/402/429 used to be swallowed here together with the network
228
+ // errors below. With the seed catalog gone a rejected refresh means
229
+ // zero models, so it has to reach the screen.
230
+ reportFailure(`${t("网关拒绝了请求")} (HTTP ${res.status})`);
231
+ return;
232
+ }
233
+ const body = (await res.json()) as {
234
+ data?: Array<{
235
+ id?: string;
236
+ name?: string;
237
+ display_name?: string;
238
+ context_window?: number;
239
+ max_output_tokens?: number;
240
+ capabilities?: string[];
241
+ reasoning_efforts?: string[];
242
+ pricing?: { input_per_1m?: number; output_per_1m?: number; currency?: string };
243
+ }>;
244
+ };
188
245
  // Known ids keep their verified seed config; new catalog entries get
189
246
  // per-family defaults (builtin metadata + gateway compat dialect)
190
247
  // instead of blind conservative placeholders.
191
- const seedById = new Map(SEED_MODELS.map((m) => [m.id, m]));
248
+ // The gateway publishes context window, output cap and capabilities from
249
+ // its sales catalog. Passing them through is what stops the CLI from
250
+ // inferring them off the model name, which had deepseek-flash at 128K
251
+ // against an actual 1M window.
192
252
  const models = (body.data ?? [])
193
253
  .filter((m) => typeof m.id === "string" && m.id.length > 0)
194
- .map((m) => seedById.get(m.id as string) ?? gatewayModelDefaults(m.id as string, m.name));
254
+ .map((m) =>
255
+ gatewayModelDefaults(m.id as string, m.display_name ?? m.name, {
256
+ contextWindow: m.context_window,
257
+ maxTokens: m.max_output_tokens,
258
+ capabilities: m.capabilities,
259
+ reasoningEfforts: m.reasoning_efforts,
260
+ pricing: m.pricing,
261
+ }),
262
+ );
195
263
  if (models.length > 0) {
196
264
  // Must be the full config: registerProvider validates the incoming
197
265
  // object standalone (models require baseUrl + auth to be present).
@@ -203,9 +271,31 @@ export default function (pi: ExtensionAPI) {
203
271
  models,
204
272
  });
205
273
  }
206
- } catch {
207
- // Offline or gateway unavailable — seed models remain usable.
274
+ } catch (error) {
275
+ // There is no seed catalog any more, so this is not a soft degradation:
276
+ // the model picker ends up empty. Name the reason instead.
277
+ const aborted = error instanceof Error && error.name === "AbortError";
278
+ reportFailure(aborted ? t("请求超时") : t("无法连接 DeepAILab 网关"));
279
+ } finally {
280
+ if (timer !== undefined) clearTimeout(timer);
208
281
  }
282
+ };
283
+
284
+ // Awaited, deliberately. This used to run in the background because the
285
+ // gateway took ~5.6s to answer, which would have been added to every launch.
286
+ // It now answers in well under a second, and with no seed catalog there is
287
+ // nothing to fall back to: a backgrounded refresh means `dal -p` reaches the
288
+ // model lookup before any model exists and reports "no API key found" to a
289
+ // user who is perfectly well logged in.
290
+ pi.on("session_start", async (_event, ctx) => {
291
+ await refreshCatalog(ctx);
292
+ });
293
+ // After /login it is awaited on purpose. The user has just authenticated and
294
+ // is about to open the model picker; showing them the seed list there is the
295
+ // exact failure this is meant to prevent.
296
+ pi.on("provider_authenticated", async (event, ctx) => {
297
+ if (event.providerId !== "deepailab") return;
298
+ await refreshCatalog(ctx);
209
299
  });
210
300
 
211
301
  pi.registerCommand("account", {