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
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Tier registry (T1 light / T2 balanced / T3 performance) and the
3
+ * fitness-based model pick.
4
+ *
5
+ * Assignment is by model *capability*, not cost: every candidate gets a
6
+ * capability score (context window, reasoning, output budget, id signals),
7
+ * and the sorted spread is split into tiers — the strongest models form t3
8
+ * (complex work), the weakest form t1 (simple work a light model handles
9
+ * fine), the middle band is t2.
10
+ *
11
+ * The pick then optimizes *fitness for the grade* inside the target tier:
12
+ * l1 prefers the quickest model in the tier, l3 the most capable one. Cost
13
+ * only breaks ties.
14
+ */
15
+
16
+ import type { Grade, TierLevel } from "./config.ts";
17
+
18
+ export interface TierCandidate {
19
+ id: string;
20
+ /** Provider-qualified lookup key for modelRegistry.find(). */
21
+ provider: string;
22
+ contextWindow: number;
23
+ maxTokens: number;
24
+ reasoning: boolean;
25
+ /** $/Mtok, input+output averaged when only those are known; 0 = unknown. */
26
+ costPerMtok: number;
27
+ tier: TierLevel;
28
+ }
29
+
30
+ /**
31
+ * Capability signals carried in model ids. Vendors encode the positioning
32
+ * there ("flash"/"mini" = quick and light, "pro"/"max" = flagship), so a hit
33
+ * is worth real signal in lieu of published benchmarks.
34
+ */
35
+ const LIGHT_ID_PATTERN = /(?:mini|flash|lite|fast|air|small|instant|turbo|nano)/i;
36
+ const HEAVY_ID_PATTERN = /(?:pro|max|ultra|large|heavy|plus|codex|thinking|reasoning)/i;
37
+
38
+ /**
39
+ * Overall capability weight of a model — how much work it can take on. Used
40
+ * for tier assignment (weak models serve simple grades, strong models serve
41
+ * complex grades).
42
+ */
43
+ export function capabilityScore(model: {
44
+ contextWindow: number;
45
+ maxTokens: number;
46
+ reasoning: boolean;
47
+ id: string;
48
+ }): number {
49
+ const id = model.id.toLowerCase();
50
+ let score = 0;
51
+ score += Math.min(model.contextWindow / 1_000_000, 2) * 0.35; // 2M window = max 0.7
52
+ score += Math.min(model.maxTokens / 65_536, 1) * 0.15;
53
+ if (model.reasoning) score += 0.25;
54
+ if (HEAVY_ID_PATTERN.test(id)) score += 0.15;
55
+ if (LIGHT_ID_PATTERN.test(id)) score -= 0.05;
56
+ return score;
57
+ }
58
+
59
+ /**
60
+ * How well a model fits a grade, inside its tier. l1 favors the quickest
61
+ * model in the tier, l3 the most capable one; l2 stays in the middle.
62
+ */
63
+ export function fitnessWithinTier(model: TierCandidate, grade: Grade): number {
64
+ const capability = capabilityScore(model);
65
+ if (grade === "l1") return 1 - capability; // light work: the lightest fits
66
+ if (grade === "l3") return capability; // hard work: the strongest fits
67
+ const mid = 1 - Math.abs(capability - 0.5); // balanced work: the middle fits
68
+ return mid;
69
+ }
70
+
71
+ export interface TierCandidatesInput {
72
+ /** id -> { provider, contextWindow, maxTokens, reasoning, costPerMtok }. */
73
+ models: Array<{
74
+ id: string;
75
+ provider: string;
76
+ contextWindow: number;
77
+ maxTokens: number;
78
+ reasoning: boolean;
79
+ costPerMtok: number;
80
+ }>;
81
+ /** Explicit tier naming from factory.json, in priority order over the heuristic. */
82
+ explicit: { t1: string[]; t2: string[]; t3: string[] };
83
+ autoTiering: boolean;
84
+ }
85
+
86
+ export interface TierRegistry {
87
+ candidates: TierCandidate[];
88
+ tiers: Record<TierLevel, string[]>;
89
+ /** Where each assignment came from, for /factory pool. */
90
+ sources: Record<string, "explicit" | "heuristic" | "default-tier">;
91
+ }
92
+
93
+ /**
94
+ * Builds the tier registry. Models named explicitly land on their named tier
95
+ * first; the rest are capability-ranked — the strongest slice forms t3, the
96
+ * weakest t1, the middle band t2.
97
+ */
98
+ export function buildTierRegistry(input: TierCandidatesInput): TierRegistry {
99
+ const candidates: TierCandidate[] = [];
100
+ const tiers: Record<TierLevel, string[]> = { t1: [], t2: [], t3: [] };
101
+ const sources: Record<string, "explicit" | "heuristic" | "default-tier"> = {};
102
+ const assigned = new Set<string>();
103
+
104
+ const byName = new Map(input.models.map((m) => [m.id, m]));
105
+ for (const level of ["t1", "t2", "t3"] as const) {
106
+ for (const id of input.explicit[level]) {
107
+ const model = byName.get(id);
108
+ if (!model || assigned.has(id)) continue;
109
+ candidates.push({ ...model, tier: level });
110
+ tiers[level].push(id);
111
+ sources[id] = "explicit";
112
+ assigned.add(id);
113
+ }
114
+ }
115
+
116
+ const unassigned = input.models.filter((model) => !assigned.has(model.id));
117
+ if (input.autoTiering && unassigned.length >= 2) {
118
+ // Capability ascending: weakest first. The weakest slice forms t1, the
119
+ // strongest slice forms t3 — a graded ladder of the same catalog.
120
+ const scored = unassigned
121
+ .map((model) => ({ model, capability: capabilityScore(model) }))
122
+ .sort((a, b) => a.capability - b.capability);
123
+ const quarter = Math.max(1, Math.floor(scored.length / 4));
124
+ scored.forEach((entry, index) => {
125
+ let level: TierLevel = "t2";
126
+ if (index < quarter) level = "t1";
127
+ else if (index >= scored.length - quarter) level = "t3";
128
+ candidates.push({ ...entry.model, tier: level });
129
+ tiers[level].push(entry.model.id);
130
+ sources[entry.model.id] = "heuristic";
131
+ });
132
+ } else {
133
+ for (const model of unassigned) {
134
+ candidates.push({ ...model, tier: "t2" });
135
+ tiers.t2.push(model.id);
136
+ sources[model.id] = "default-tier";
137
+ }
138
+ }
139
+
140
+ return { candidates, tiers, sources };
141
+ }
142
+
143
+ export interface PickInput {
144
+ /** The target tier derived from the graded complexity. */
145
+ tier: TierLevel;
146
+ /** The graded complexity — selects the best-fitting model inside the tier. */
147
+ grade: Grade;
148
+ registry: TierRegistry;
149
+ /** Cost breaks ties between equally fitting models. */
150
+ costPerMtok?: number;
151
+ /** Model ids observed failing recently; temporarily out of the pool. */
152
+ unavailable: Set<string>;
153
+ /** The model currently active in the session (preferred on exact fitness ties). */
154
+ currentModelId?: string;
155
+ }
156
+
157
+ /**
158
+ * Five-factor pick: fitness for the grade dominates, cost breaks ties between
159
+ * equally fitting models, and the authorization factor is a veto applied
160
+ * upstream by filtering candidates.
161
+ */
162
+ export function pickModelForGrade(input: PickInput): TierCandidate | undefined {
163
+ const inTier = input.registry.candidates.filter(
164
+ (candidate) => candidate.tier === input.tier && !input.unavailable.has(candidate.id),
165
+ );
166
+ if (inTier.length === 0) return undefined;
167
+
168
+ const best = inTier
169
+ .map((candidate) => ({
170
+ candidate,
171
+ fitness: fitnessForTier(candidate, input.grade),
172
+ cost: candidate.costPerMtok,
173
+ }))
174
+ .sort((a, b) => b.fitness - a.fitness || a.cost - b.cost || a.candidate.id.localeCompare(b.candidate.id));
175
+ return best[0]?.candidate;
176
+ }
177
+
178
+ function fitnessForTier(candidate: TierCandidate, grade: Grade): number {
179
+ if (grade === "l1") return -capabilityScore(candidate); // light work: lightest model wins
180
+ if (grade === "l3") return capabilityScore(candidate); // hard work: strongest model wins
181
+ return 0; // balanced work: middle of the tier
182
+ }
183
+
184
+ /** Grade -> target tier, per the L1/L2/L3 mapping table. */
185
+ export function gradeToTier(grade: Grade): TierLevel {
186
+ return { l1: "t1", l2: "t2", l3: "t3" }[grade] as TierLevel;
187
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-skills",
3
- "version": "1.0.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-pi-kit": "1.0.13",
23
- "@dalcode/deepailab": "1.0.13",
22
+ "@dalcode/dal-pi-kit": "1.0.15",
23
+ "@dalcode/deepailab": "1.0.15",
24
24
  "typebox": "1.3.7"
25
25
  },
26
26
  "peerDependencies": {
@@ -25,6 +25,7 @@
25
25
  */
26
26
 
27
27
  import { t } from "@dalcode/dal-pi-kit";
28
+ import { accountTag, readCache, writeCache } from "@dalcode/deepailab/cache";
28
29
  import { defaultConfig } from "@dalcode/deepailab/oidc";
29
30
  import {
30
31
  type ExtensionAPI,
@@ -49,6 +50,19 @@ const skillSchema = Type.Object({
49
50
  name: Type.String({ description: t("要加载的技能名称,取自本工具描述中列出的清单") }),
50
51
  });
51
52
 
53
+ function isSkillList(value: unknown): value is SkillSummary[] {
54
+ return (
55
+ Array.isArray(value) &&
56
+ value.every(
57
+ (s) =>
58
+ typeof s?.id === "string" &&
59
+ s.id.length > 0 &&
60
+ typeof s.name === "string" &&
61
+ typeof s.description === "string",
62
+ )
63
+ );
64
+ }
65
+
52
66
  /** Cheap guard against a skill whose body is enormous by accident. */
53
67
  const MAX_BODY_CHARS = 60_000;
54
68
 
@@ -106,41 +120,59 @@ export default function (pi: ExtensionAPI) {
106
120
  else process.stderr.write(`${message}\n`);
107
121
  };
108
122
 
109
- try {
110
- // No ETag is sent, so 304 is not something our own service can answer —
111
- // but a proxy or CDN in front of it can, and returning here would leave
112
- // the tool unregistered with nothing on screen. Treated as "no
113
- // catalogue this session" and reported, rather than silently skipped.
114
- const index = await fetchSkillIndex(cfg.apiBase, vk);
115
- if (index === "not-modified") {
116
- reportFailure(t("服务端返回了意外的 304"));
117
- return;
123
+ // Index: start from the last good copy for this account and revalidate
124
+ // in the background. It used to be fetched before the first turn of
125
+ // every process, 5-6s on a proxied connection; a copy that is a few
126
+ // minutes old lists the same skills, and a skill added since is still
127
+ // resolvable by name once the revalidation lands (resolve() reads the
128
+ // live `catalogue`). With no copy yet, the first fetch is awaited.
129
+ const cacheName = `skills-index-${accountTag(vk)}`;
130
+ const cached = readCache(cacheName, isSkillList);
131
+ const revalidation = (async (): Promise<void> => {
132
+ try {
133
+ // No ETag is sent, so 304 is not something our own service can answer —
134
+ // but a proxy or CDN in front of it can, and taking it as "unchanged"
135
+ // would leave the tool unregistered with nothing on screen. Treated
136
+ // as "no catalogue" and reported, rather than silently skipped.
137
+ const index = await fetchSkillIndex(cfg.apiBase, vk);
138
+ if (index === "not-modified") {
139
+ reportFailure(t("服务端返回了意外的 304"));
140
+ return;
141
+ }
142
+ catalogue = index.skills;
143
+ try {
144
+ writeCache(cacheName, index.skills);
145
+ } catch {
146
+ // An unwritable cache only costs the next process this same fetch.
147
+ }
148
+ } catch (error) {
149
+ // Not silent: skills the user is paying for quietly not being there is
150
+ // exactly the class of failure this codebase keeps getting bitten by.
151
+ // With a cached copy the session keeps working from it, and says so.
152
+ const reason = error instanceof Error && error.name === "AbortError" ? t("请求超时") : String(error);
153
+ reportFailure(reason);
118
154
  }
119
- catalogue = index.skills;
120
- } catch (error) {
121
- // Not silent: skills the user is paying for quietly not being there is
122
- // exactly the class of failure this codebase keeps getting bitten by.
123
- const reason = error instanceof Error && error.name === "AbortError" ? t("请求超时") : String(error);
124
- reportFailure(reason);
125
- return;
126
- }
155
+ })();
156
+ if (cached) catalogue = cached.value;
157
+ else await revalidation;
127
158
 
128
- // Best-effort and quiet on failure: a recommendation list that cannot be
129
- // fetched is not worth interrupting anyone over, unlike skills or MCP which
130
- // change what the agent can do.
131
- try {
132
- const account = await fetchAccountPackages(cfg.apiBase, vk);
133
- const installed = readInstalledSources(getAgentDir());
134
- pendingPackages = missingPackages(account, installed);
135
- if (ctx.hasUI && shouldAnnouncePending(getAgentDir(), pendingPackages)) {
136
- ctx.ui.notify(
137
- `${t("账号里有")}${pendingPackages.length}${t(" 个扩展本机还没装,/install 可直接安装。")}`,
138
- "info",
139
- );
140
- }
141
- } catch {
142
- // Ignored on purpose — see above.
143
- }
159
+ // Best-effort, quiet on failure, and never awaited: a recommendation list
160
+ // is not worth delaying the first turn or interrupting anyone over,
161
+ // unlike skills or MCP which change what the agent can do.
162
+ void fetchAccountPackages(cfg.apiBase, vk)
163
+ .then((account) => {
164
+ const installed = readInstalledSources(getAgentDir());
165
+ pendingPackages = missingPackages(account, installed);
166
+ if (ctx.hasUI && shouldAnnouncePending(getAgentDir(), pendingPackages)) {
167
+ ctx.ui.notify(
168
+ `${t("账号里有")}${pendingPackages.length}${t(" 个扩展本机还没装,/install 可直接安装。")}`,
169
+ "info",
170
+ );
171
+ }
172
+ })
173
+ .catch(() => {
174
+ // Ignored on purpose — see above.
175
+ });
144
176
 
145
177
  if (catalogue.length === 0) return;
146
178
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-subagent",
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,10 +17,10 @@
17
17
  ]
18
18
  },
19
19
  "dependencies": {
20
- "@dalcode/dal-pi-kit": "1.0.13",
21
- "@dalcode/dal-guard": "1.0.13",
22
- "@earendil-works/pi-agent-core": "^1.0.13",
23
- "@earendil-works/pi-ai": "^1.0.13",
20
+ "@dalcode/dal-pi-kit": "1.0.15",
21
+ "@dalcode/dal-guard": "1.0.15",
22
+ "@earendil-works/pi-agent-core": "^1.0.15",
23
+ "@earendil-works/pi-ai": "^1.0.15",
24
24
  "typebox": "1.3.7"
25
25
  },
26
26
  "peerDependencies": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dalcode/dal-telemetry",
3
- "version": "1.0.13",
3
+ "version": "1.0.15",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
@@ -20,7 +20,7 @@
20
20
  ]
21
21
  },
22
22
  "dependencies": {
23
- "@dalcode/dal-pi-kit": "1.0.13"
23
+ "@dalcode/dal-pi-kit": "1.0.15"
24
24
  },
25
25
  "peerDependencies": {
26
26
  "@earendil-works/pi-coding-agent": "^1.0.9"
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "@dalcode/deepailab",
3
- "version": "1.0.13",
3
+ "version": "1.0.15",
4
4
  "private": true,
5
5
  "type": "module",
6
6
  "main": "./src/index.ts",
7
7
  "exports": {
8
8
  ".": "./src/index.ts",
9
+ "./cache": "./src/cache.ts",
9
10
  "./model-defaults": "./src/model-defaults.ts",
10
11
  "./oidc": "./src/oidc.ts",
11
12
  "./package.json": "./package.json"
@@ -19,8 +20,8 @@
19
20
  ]
20
21
  },
21
22
  "dependencies": {
22
- "@dalcode/dal-pi-kit": "1.0.13",
23
- "@earendil-works/pi-ai": "^1.0.13"
23
+ "@dalcode/dal-pi-kit": "1.0.15",
24
+ "@earendil-works/pi-ai": "^1.0.15"
24
25
  },
25
26
  "peerDependencies": {
26
27
  "@earendil-works/pi-coding-agent": "^1.0.9"
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Last-known-good copies of account data fetched from the DeepAILab gateway.
3
+ *
4
+ * Every `dal` process used to fetch the skill index, the account's MCP
5
+ * servers and each MCP server's tool list before the first model request,
6
+ * one after another. Each is a fresh HTTPS connection, and on a machine
7
+ * behind a proxy each took 5-6s (measured 2026-09-23), so a one-line headless
8
+ * prompt spent ~40s before it reached the model. DAL Office spawns a process
9
+ * per chat turn and paid that every turn.
10
+ *
11
+ * Callers use these to start from the last good copy and revalidate in the
12
+ * background (stale-while-revalidate). Files live under
13
+ * `<agent dir>/cache/`, written 0600 like auth.json: an account MCP entry can
14
+ * carry request headers.
15
+ */
16
+
17
+ import { createHash } from "node:crypto";
18
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
19
+ import { dirname, join } from "node:path";
20
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
21
+
22
+ export interface Cached<T> {
23
+ value: T;
24
+ /** Unix ms when the value was fetched. */
25
+ savedAt: number;
26
+ }
27
+
28
+ function cachePath(name: string): string {
29
+ return join(getAgentDir(), "cache", `${name}.json`);
30
+ }
31
+
32
+ /**
33
+ * Short, non-reversible tag for a credential, used to key per-account caches
34
+ * so a different sign-in never starts from another account's data.
35
+ */
36
+ export function accountTag(key: string): string {
37
+ return createHash("sha256").update(key).digest("hex").slice(0, 16);
38
+ }
39
+
40
+ export function readCache<T>(name: string, isValue: (value: unknown) => value is T): Cached<T> | undefined {
41
+ let parsed: { value?: unknown; savedAt?: unknown };
42
+ try {
43
+ parsed = JSON.parse(readFileSync(cachePath(name), "utf8")) as typeof parsed;
44
+ } catch {
45
+ // Missing or unreadable: the caller fetches, exactly as with no cache.
46
+ return undefined;
47
+ }
48
+ if (typeof parsed.savedAt !== "number" || !isValue(parsed.value)) return undefined;
49
+ return { value: parsed.value, savedAt: parsed.savedAt };
50
+ }
51
+
52
+ /**
53
+ * Atomic (temp file + rename), so a concurrent reader never sees half a file.
54
+ * Throws on failure; callers decide whether that is worth reporting.
55
+ */
56
+ export function writeCache(name: string, value: unknown): void {
57
+ const path = cachePath(name);
58
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
59
+ const temporary = `${path}.${process.pid}.tmp`;
60
+ writeFileSync(temporary, JSON.stringify({ savedAt: Date.now(), value }), { mode: 0o600 });
61
+ renameSync(temporary, path);
62
+ }