@vellumai/assistant 0.10.7-dev.202607100313.fffdfea → 0.10.7-dev.202607100720.fba456e

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 (99) hide show
  1. package/openapi.yaml +846 -27
  2. package/package.json +1 -1
  3. package/src/__tests__/config-watcher-skill-reseed.test.ts +1 -0
  4. package/src/__tests__/config-watcher.test.ts +22 -4
  5. package/src/__tests__/credential-security-invariants.test.ts +1 -1
  6. package/src/__tests__/plugin-import-boundary-guard.test.ts +6 -9
  7. package/src/__tests__/plugin-import-boundary-reverse-guard.test.ts +0 -2
  8. package/src/cli/commands/__tests__/inference-models.test.ts +86 -0
  9. package/src/cli/commands/__tests__/inference-profiles.test.ts +254 -0
  10. package/src/cli/commands/__tests__/inference-providers.test.ts +171 -0
  11. package/src/cli/commands/__tests__/schedules.test.ts +133 -1
  12. package/src/cli/commands/__tests__/usage.test.ts +131 -0
  13. package/src/cli/commands/inference-callsites.ts +158 -0
  14. package/src/cli/commands/inference-models.ts +84 -0
  15. package/src/cli/commands/inference-profiles.ts +371 -0
  16. package/src/cli/commands/inference-providers-default.ts +89 -0
  17. package/src/cli/commands/inference-providers.ts +87 -16
  18. package/src/cli/commands/inference.ts +6 -0
  19. package/src/cli/commands/memory/nodes.ts +90 -50
  20. package/src/cli/commands/schedules.ts +17 -2
  21. package/src/cli/commands/usage.ts +59 -21
  22. package/src/cli/lib/__tests__/cli-output.test.ts +20 -0
  23. package/src/cli/lib/cli-output.ts +55 -0
  24. package/src/config/__tests__/loader-last-known-good.test.ts +229 -0
  25. package/src/config/__tests__/loader-sparse-array-cleanup.test.ts +166 -0
  26. package/src/config/default-profile-catalog.ts +28 -0
  27. package/src/config/loader.ts +276 -46
  28. package/src/daemon/config-watcher.ts +65 -20
  29. package/src/daemon/message-types/sync.ts +1 -0
  30. package/src/oauth/byo-connection.test.ts +1 -1
  31. package/src/oauth/connection-resolver.test.ts +140 -0
  32. package/src/oauth/connection-resolver.ts +48 -12
  33. package/src/plugins/defaults/memory/anisotropy.ts +1 -1
  34. package/src/plugins/defaults/memory/config.ts +1 -1
  35. package/src/plugins/defaults/memory/context-search/agent-protocol.ts +1 -1
  36. package/src/plugins/defaults/memory/context-search/search.ts +1 -1
  37. package/src/plugins/defaults/memory/graph/bootstrap.ts +1 -1
  38. package/src/plugins/defaults/memory/graph/consolidation.ts +1 -1
  39. package/src/plugins/defaults/memory/graph/conversation-graph-memory.ts +11 -1
  40. package/src/plugins/defaults/memory/graph/extraction.ts +1 -1
  41. package/src/plugins/defaults/memory/graph/narrative.ts +1 -1
  42. package/src/plugins/defaults/memory/graph/pattern-scan.ts +1 -1
  43. package/src/plugins/defaults/memory/graph/tool-handlers.ts +1 -1
  44. package/src/plugins/defaults/memory/graph/tools.ts +1 -1
  45. package/src/plugins/defaults/memory/graph-topology/build-memory-graph.ts +43 -16
  46. package/src/plugins/defaults/memory/hooks/user-prompt-submit.ts +1 -1
  47. package/src/plugins/defaults/memory/host-utils.ts +80 -0
  48. package/src/plugins/defaults/memory/identity-context.ts +1 -1
  49. package/src/plugins/defaults/memory/injectors.ts +1 -1
  50. package/src/plugins/defaults/memory/jobs/embed-concept-page.ts +2 -2
  51. package/src/plugins/defaults/memory/jobs-worker.ts +2 -9
  52. package/src/plugins/defaults/memory/memory-retrospective-state.ts +1 -1
  53. package/src/plugins/defaults/memory/paths.ts +48 -0
  54. package/src/plugins/defaults/memory/pkb/autoinject.ts +1 -1
  55. package/src/plugins/defaults/memory/pkb/context.ts +2 -2
  56. package/src/plugins/defaults/memory/pkb/types.ts +1 -1
  57. package/src/plugins/defaults/memory/pkb-schedule.ts +2 -2
  58. package/src/plugins/defaults/memory/rerank-local.ts +2 -3
  59. package/src/plugins/defaults/memory/routes/memory-eval-routes.ts +1 -1
  60. package/src/plugins/defaults/memory/routes/memory-item-routes.test.ts +149 -1
  61. package/src/plugins/defaults/memory/routes/memory-item-routes.ts +144 -1
  62. package/src/plugins/defaults/memory/routes/memory-v2-routes.ts +1 -1
  63. package/src/plugins/defaults/memory/startup.ts +1 -1
  64. package/src/plugins/defaults/memory/v2/backfill-jobs.ts +1 -1
  65. package/src/plugins/defaults/memory/v2/consolidation-job.ts +2 -2
  66. package/src/plugins/defaults/memory/v2/injection.ts +1 -1
  67. package/src/plugins/defaults/memory/v2/memory-v2-startup.ts +1 -1
  68. package/src/plugins/defaults/memory/v2/prompts/consolidation.ts +1 -1
  69. package/src/plugins/defaults/memory/v2/qdrant.ts +1 -1
  70. package/src/plugins/defaults/memory/v2/reranker.ts +1 -1
  71. package/src/plugins/defaults/memory/v2/static-context.ts +1 -1
  72. package/src/plugins/defaults/memory/v2/sweep-job.ts +1 -1
  73. package/src/plugins/defaults/memory/v3/candidate-match.ts +1 -1
  74. package/src/plugins/defaults/memory/v3/maintain-job.ts +1 -1
  75. package/src/plugins/defaults/memory/v3/page-content.ts +1 -1
  76. package/src/plugins/defaults/memory/v3/pool-select.ts +1 -2
  77. package/src/plugins/defaults/memory/v3/selection-log-store.ts +1 -1
  78. package/src/plugins/defaults/memory/v3/shadow-plugin.ts +2 -5
  79. package/src/plugins/defaults/memory/worker.ts +1 -1
  80. package/src/plugins/defaults/workspace/injectors.ts +17 -15
  81. package/src/plugins/types.ts +9 -14
  82. package/src/providers/inference/connection-availability.ts +193 -0
  83. package/src/runtime/routes/__tests__/inference-callsites-routes.test.ts +54 -0
  84. package/src/runtime/routes/__tests__/inference-models-routes.test.ts +54 -0
  85. package/src/runtime/routes/__tests__/inference-profiles-routes.test.ts +405 -0
  86. package/src/runtime/routes/__tests__/inference-routes-registration.test.ts +42 -0
  87. package/src/runtime/routes/__tests__/theme-routes.test.ts +66 -0
  88. package/src/runtime/routes/conversation-query-routes.ts +5 -3
  89. package/src/runtime/routes/default-provider-routes.ts +5 -152
  90. package/src/runtime/routes/index.ts +8 -0
  91. package/src/runtime/routes/inference-callsites-routes.ts +211 -0
  92. package/src/runtime/routes/inference-models-routes.ts +104 -0
  93. package/src/runtime/routes/inference-profiles-routes.ts +717 -0
  94. package/src/runtime/routes/theme-routes.ts +36 -0
  95. package/src/runtime/sync/resource-sync-events.ts +4 -0
  96. package/src/theme/workspace-theme.test.ts +269 -0
  97. package/src/theme/workspace-theme.ts +304 -0
  98. package/src/watcher/__tests__/engine-auth-notify.test.ts +316 -0
  99. package/src/watcher/engine.ts +87 -2
@@ -0,0 +1,36 @@
1
+ import { z } from "zod";
2
+
3
+ import {
4
+ readWorkspaceTheme,
5
+ WorkspaceThemeSchema,
6
+ } from "../../theme/workspace-theme.js";
7
+ import { ACTOR_PRINCIPALS } from "../auth/route-policy.js";
8
+ import type { RouteDefinition } from "./types.js";
9
+
10
+ function handleGetWorkspaceTheme() {
11
+ return readWorkspaceTheme();
12
+ }
13
+
14
+ export const ROUTES: RouteDefinition[] = [
15
+ {
16
+ operationId: "workspace_theme_get",
17
+ endpoint: "workspace/theme",
18
+ method: "GET",
19
+ policy: {
20
+ requiredScopes: ["settings.read"],
21
+ allowedPrincipalTypes: ACTOR_PRINCIPALS,
22
+ },
23
+ handler: handleGetWorkspaceTheme,
24
+ summary: "Get workspace theme",
25
+ description:
26
+ "Return validated design-token overrides from the workspace ui/theme.json. " +
27
+ "Absent or rejected files yield theme: null with the rejection reasons in issues; " +
28
+ "clients fall back to built-in theme defaults.",
29
+ tags: ["workspace"],
30
+ responseBody: z.object({
31
+ theme: WorkspaceThemeSchema.nullable(),
32
+ source: z.enum(["workspace", "invalid", "none"]),
33
+ issues: z.array(z.string()),
34
+ }),
35
+ },
36
+ ];
@@ -57,6 +57,10 @@ export function publishSchedulesChanged(originClientId?: string): void {
57
57
  void publishSyncInvalidation([SYNC_TAGS.assistantSchedules], originClientId);
58
58
  }
59
59
 
60
+ export function publishWorkspaceThemeChanged(originClientId?: string): void {
61
+ void publishSyncInvalidation([SYNC_TAGS.assistantTheme], originClientId);
62
+ }
63
+
60
64
  export function publishAppsChanged(originClientId?: string): void {
61
65
  void publishSyncInvalidation([SYNC_TAGS.appsList], originClientId);
62
66
  }
@@ -0,0 +1,269 @@
1
+ import { execSync } from "node:child_process";
2
+ import {
3
+ mkdirSync,
4
+ mkdtempSync,
5
+ rmSync,
6
+ symlinkSync,
7
+ writeFileSync,
8
+ } from "node:fs";
9
+ import { tmpdir } from "node:os";
10
+ import { join } from "node:path";
11
+ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
12
+
13
+ import {
14
+ contrastRatio,
15
+ MAX_THEME_FILE_BYTES,
16
+ MIN_TEXT_CONTRAST_RATIO,
17
+ readWorkspaceTheme,
18
+ WORKSPACE_THEME_RELATIVE_PATH,
19
+ } from "./workspace-theme.js";
20
+
21
+ describe("readWorkspaceTheme", () => {
22
+ let workspaceDir: string;
23
+ let prevWorkspaceDir: string | undefined;
24
+
25
+ beforeEach(() => {
26
+ workspaceDir = mkdtempSync(join(tmpdir(), "workspace-theme-test-"));
27
+ prevWorkspaceDir = process.env.VELLUM_WORKSPACE_DIR;
28
+ process.env.VELLUM_WORKSPACE_DIR = workspaceDir;
29
+ });
30
+
31
+ afterEach(() => {
32
+ if (prevWorkspaceDir === undefined) {
33
+ delete process.env.VELLUM_WORKSPACE_DIR;
34
+ } else {
35
+ process.env.VELLUM_WORKSPACE_DIR = prevWorkspaceDir;
36
+ }
37
+ rmSync(workspaceDir, { recursive: true, force: true });
38
+ });
39
+
40
+ function writeTheme(content: string): void {
41
+ const themePath = join(workspaceDir, WORKSPACE_THEME_RELATIVE_PATH);
42
+ mkdirSync(join(workspaceDir, "ui"), { recursive: true });
43
+ writeFileSync(themePath, content);
44
+ }
45
+
46
+ test("absent file yields source none with no issues", () => {
47
+ const result = readWorkspaceTheme();
48
+ expect(result).toEqual({ theme: null, source: "none", issues: [] });
49
+ });
50
+
51
+ test("valid theme parses with all token slots", () => {
52
+ writeTheme(
53
+ JSON.stringify({
54
+ version: 1,
55
+ base: "dark",
56
+ tokens: {
57
+ accent: "#e8a04c",
58
+ background: "#1c1512",
59
+ surface: "#2b2018",
60
+ surfaceRaised: "#332619",
61
+ border: "#43301f",
62
+ text: "#f2e4d4",
63
+ textMuted: "#a68d75",
64
+ assistantBubbleBackground: "#33202a",
65
+ assistantBubbleText: "#ffd7e4",
66
+ userBubbleBackground: "#26201a",
67
+ userBubbleText: "#efe3d2",
68
+ },
69
+ }),
70
+ );
71
+ const result = readWorkspaceTheme();
72
+ expect(result.source).toBe("workspace");
73
+ expect(result.issues).toEqual([]);
74
+ expect(result.theme?.base).toBe("dark");
75
+ expect(result.theme?.tokens?.accent).toBe("#e8a04c");
76
+ });
77
+
78
+ test("minimal theme (version only) is valid", () => {
79
+ writeTheme(JSON.stringify({ version: 1 }));
80
+ const result = readWorkspaceTheme();
81
+ expect(result.source).toBe("workspace");
82
+ expect(result.theme).toEqual({ version: 1 });
83
+ });
84
+
85
+ test("3-digit hex colors are accepted", () => {
86
+ writeTheme(JSON.stringify({ version: 1, tokens: { accent: "#f0a" } }));
87
+ const result = readWorkspaceTheme();
88
+ expect(result.source).toBe("workspace");
89
+ });
90
+
91
+ test("unknown top-level keys are rejected", () => {
92
+ writeTheme(JSON.stringify({ version: 1, css: "body { display: none }" }));
93
+ const result = readWorkspaceTheme();
94
+ expect(result.source).toBe("invalid");
95
+ expect(result.theme).toBeNull();
96
+ expect(result.issues.length).toBeGreaterThan(0);
97
+ });
98
+
99
+ test("unknown token slots are rejected", () => {
100
+ writeTheme(
101
+ JSON.stringify({ version: 1, tokens: { zIndexOverlay: "#000000" } }),
102
+ );
103
+ const result = readWorkspaceTheme();
104
+ expect(result.source).toBe("invalid");
105
+ expect(result.theme).toBeNull();
106
+ });
107
+
108
+ test("non-hex values are rejected, including alpha hex and CSS functions", () => {
109
+ for (const value of ["#aabbccdd", "red", "url(http://evil)", "#12"]) {
110
+ writeTheme(JSON.stringify({ version: 1, tokens: { accent: value } }));
111
+ const result = readWorkspaceTheme();
112
+ expect(result.source).toBe("invalid");
113
+ expect(result.theme).toBeNull();
114
+ }
115
+ });
116
+
117
+ test("unsupported version is rejected", () => {
118
+ writeTheme(JSON.stringify({ version: 2 }));
119
+ const result = readWorkspaceTheme();
120
+ expect(result.source).toBe("invalid");
121
+ });
122
+
123
+ test("malformed JSON is rejected with a readable issue", () => {
124
+ writeTheme("{ version: 1 ");
125
+ const result = readWorkspaceTheme();
126
+ expect(result.source).toBe("invalid");
127
+ expect(result.issues[0]).toContain("not valid JSON");
128
+ });
129
+
130
+ test("illegible text/background pair is rejected by the contrast floor", () => {
131
+ writeTheme(
132
+ JSON.stringify({
133
+ version: 1,
134
+ tokens: {
135
+ text: "#fefefe",
136
+ textMuted: "#555555",
137
+ background: "#ffffff",
138
+ surface: "#f2f2f2",
139
+ surfaceRaised: "#e8e8e8",
140
+ },
141
+ }),
142
+ );
143
+ const result = readWorkspaceTheme();
144
+ expect(result.source).toBe("invalid");
145
+ expect(result.theme).toBeNull();
146
+ expect(result.issues[0]).toContain("contrast");
147
+ });
148
+
149
+ test("partial core override group is rejected, naming the missing tokens", () => {
150
+ writeTheme(
151
+ JSON.stringify({ version: 1, tokens: { background: "#000000" } }),
152
+ );
153
+ const result = readWorkspaceTheme();
154
+ expect(result.source).toBe("invalid");
155
+ expect(result.theme).toBeNull();
156
+ expect(result.issues[0]).toContain("incomplete override group");
157
+ expect(result.issues[0]).toContain("tokens.text");
158
+ });
159
+
160
+ test("partial bubble pair is rejected", () => {
161
+ writeTheme(
162
+ JSON.stringify({
163
+ version: 1,
164
+ tokens: { assistantBubbleBackground: "#33202a" },
165
+ }),
166
+ );
167
+ const result = readWorkspaceTheme();
168
+ expect(result.source).toBe("invalid");
169
+ expect(result.issues[0]).toContain("incomplete override group");
170
+ });
171
+
172
+ test("group-exempt tokens (accent, border) are valid alone", () => {
173
+ writeTheme(
174
+ JSON.stringify({
175
+ version: 1,
176
+ tokens: { accent: "#e8a04c", border: "#43301f" },
177
+ }),
178
+ );
179
+ const result = readWorkspaceTheme();
180
+ expect(result.source).toBe("workspace");
181
+ expect(result.issues).toEqual([]);
182
+ });
183
+
184
+ test("bubble text/background pairs are contrast-checked", () => {
185
+ writeTheme(
186
+ JSON.stringify({
187
+ version: 1,
188
+ tokens: {
189
+ assistantBubbleText: "#111111",
190
+ assistantBubbleBackground: "#141414",
191
+ },
192
+ }),
193
+ );
194
+ const result = readWorkspaceTheme();
195
+ expect(result.source).toBe("invalid");
196
+ expect(result.issues[0]).toContain("contrast");
197
+ });
198
+
199
+ test("muted text is contrast-checked against surfaces, not just background", () => {
200
+ writeTheme(
201
+ JSON.stringify({
202
+ version: 1,
203
+ tokens: {
204
+ background: "#0a0a0a",
205
+ surface: "#6b6b6b",
206
+ surfaceRaised: "#6f6f6f",
207
+ text: "#ffffff",
208
+ textMuted: "#777777",
209
+ },
210
+ }),
211
+ );
212
+ const result = readWorkspaceTheme();
213
+ expect(result.source).toBe("invalid");
214
+ expect(result.issues.join("\n")).toContain("textMuted on tokens.surface");
215
+ });
216
+
217
+ test("symlinked theme file is rejected without following it", () => {
218
+ const target = join(workspaceDir, "elsewhere.json");
219
+ writeFileSync(target, JSON.stringify({ version: 1 }));
220
+ mkdirSync(join(workspaceDir, "ui"), { recursive: true });
221
+ symlinkSync(target, join(workspaceDir, WORKSPACE_THEME_RELATIVE_PATH));
222
+ const result = readWorkspaceTheme();
223
+ expect(result.source).toBe("invalid");
224
+ expect(result.theme).toBeNull();
225
+ expect(result.issues[0]).toContain("symbolic link");
226
+ });
227
+
228
+ test("oversized theme file is rejected before parsing", () => {
229
+ writeTheme(`{"version":1}${" ".repeat(MAX_THEME_FILE_BYTES)}`);
230
+ const result = readWorkspaceTheme();
231
+ expect(result.source).toBe("invalid");
232
+ expect(result.issues[0]).toContain("maximum");
233
+ });
234
+
235
+ test("FIFO at the theme path is rejected without blocking", () => {
236
+ const fifoPath = join(workspaceDir, WORKSPACE_THEME_RELATIVE_PATH);
237
+ mkdirSync(join(workspaceDir, "ui"), { recursive: true });
238
+ execSync(`mkfifo "${fifoPath}"`);
239
+ const result = readWorkspaceTheme();
240
+ expect(result.source).toBe("invalid");
241
+ expect(result.theme).toBeNull();
242
+ expect(result.issues[0]).toContain("regular file");
243
+ });
244
+ });
245
+
246
+ describe("contrastRatio", () => {
247
+ test("black on white is the maximum 21:1", () => {
248
+ expect(contrastRatio("#000000", "#ffffff")).toBeCloseTo(21, 0);
249
+ });
250
+
251
+ test("identical colors are 1:1", () => {
252
+ expect(contrastRatio("#336699", "#336699")).toBeCloseTo(1, 5);
253
+ });
254
+
255
+ test("is order-independent", () => {
256
+ expect(contrastRatio("#000000", "#ffffff")).toBe(
257
+ contrastRatio("#ffffff", "#000000"),
258
+ );
259
+ });
260
+
261
+ test("floor constant catches near-invisible text", () => {
262
+ expect(contrastRatio("#fefefe", "#ffffff")).toBeLessThan(
263
+ MIN_TEXT_CONTRAST_RATIO,
264
+ );
265
+ expect(contrastRatio("#f2e4d4", "#1c1512")).toBeGreaterThan(
266
+ MIN_TEXT_CONTRAST_RATIO,
267
+ );
268
+ });
269
+ });
@@ -0,0 +1,304 @@
1
+ /**
2
+ * Workspace theme: user- or assistant-authored design-token overrides read
3
+ * from `ui/theme.json` in the workspace. Clients apply the validated tokens
4
+ * on top of the built-in themes (light/dark/velvet).
5
+ *
6
+ * Security posture is a strict whitelist:
7
+ * - only the semantic token slots below are accepted (unknown keys reject),
8
+ * - values must be plain 3- or 6-digit hex colors (no alpha, so the
9
+ * contrast floor stays meaningful),
10
+ * - tokens that resolve against each other are all-or-none per override
11
+ * group, so a partial override can never pair an authored color with an
12
+ * unknown base-theme color,
13
+ * - text/background pairs must clear a minimum contrast ratio so an
14
+ * authored theme can never render core copy illegible,
15
+ * - the file itself is read through a no-follow, non-blocking, size-capped
16
+ * guard so a symlink, FIFO, or oversized file cannot stall the event
17
+ * loop or escape the workspace.
18
+ *
19
+ * Trust-critical chrome (permission prompts, credential entry) does not
20
+ * consume these tokens; this module only governs the expressive surface.
21
+ */
22
+ import {
23
+ closeSync,
24
+ constants,
25
+ fstatSync,
26
+ openSync,
27
+ readFileSync,
28
+ } from "node:fs";
29
+ import { join } from "node:path";
30
+
31
+ import { z } from "zod";
32
+
33
+ import { getWorkspaceDir } from "../util/platform.js";
34
+
35
+ /** Workspace-relative path clients and the config watcher both key on. */
36
+ export const WORKSPACE_THEME_RELATIVE_PATH = "ui/theme.json";
37
+
38
+ const HEX_COLOR_RE = /^#(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
39
+
40
+ const hexColor = z
41
+ .string()
42
+ .regex(HEX_COLOR_RE, "must be a 3- or 6-digit hex color like #1a2b3c");
43
+
44
+ const ThemeTokensSchema = z
45
+ .object({
46
+ accent: hexColor,
47
+ background: hexColor,
48
+ surface: hexColor,
49
+ surfaceRaised: hexColor,
50
+ border: hexColor,
51
+ text: hexColor,
52
+ textMuted: hexColor,
53
+ assistantBubbleBackground: hexColor,
54
+ assistantBubbleText: hexColor,
55
+ userBubbleBackground: hexColor,
56
+ userBubbleText: hexColor,
57
+ })
58
+ .partial()
59
+ .strict();
60
+
61
+ export type WorkspaceThemeTokens = z.infer<typeof ThemeTokensSchema>;
62
+
63
+ export const WorkspaceThemeSchema = z
64
+ .object({
65
+ version: z.literal(1),
66
+ base: z.enum(["light", "dark", "velvet", "system"]).optional(),
67
+ tokens: ThemeTokensSchema.optional(),
68
+ })
69
+ .strict();
70
+
71
+ export type WorkspaceTheme = z.infer<typeof WorkspaceThemeSchema>;
72
+
73
+ /**
74
+ * Readability floor, not an accessibility certification: blocks themes whose
75
+ * core text would be effectively invisible against its own background.
76
+ */
77
+ export const MIN_TEXT_CONTRAST_RATIO = 3;
78
+
79
+ /**
80
+ * Token pairs that must clear the contrast floor: [foreground, background].
81
+ * Group completeness (below) guarantees both sides are present whenever
82
+ * either is, so every pair is always checkable.
83
+ */
84
+ const CONTRAST_PAIRS: readonly [
85
+ keyof WorkspaceThemeTokens,
86
+ keyof WorkspaceThemeTokens,
87
+ ][] = [
88
+ ["text", "background"],
89
+ ["text", "surface"],
90
+ ["text", "surfaceRaised"],
91
+ ["textMuted", "background"],
92
+ ["textMuted", "surface"],
93
+ ["textMuted", "surfaceRaised"],
94
+ ["assistantBubbleText", "assistantBubbleBackground"],
95
+ ["userBubbleText", "userBubbleBackground"],
96
+ ];
97
+
98
+ /**
99
+ * Tokens that resolve against each other must be overridden together.
100
+ * Clients layer these tokens over a base theme whose palette the daemon
101
+ * does not know, so a half-overridden pairing (e.g. a dark `background`
102
+ * with the base's dark `text` inherited) would bypass the contrast floor.
103
+ * `accent` and `border` are exempt: no body copy resolves against them.
104
+ */
105
+ const OVERRIDE_GROUPS: readonly (keyof WorkspaceThemeTokens)[][] = [
106
+ ["background", "surface", "surfaceRaised", "text", "textMuted"],
107
+ ["assistantBubbleBackground", "assistantBubbleText"],
108
+ ["userBubbleBackground", "userBubbleText"],
109
+ ];
110
+
111
+ function groupCompletenessIssues(tokens: WorkspaceThemeTokens): string[] {
112
+ const issues: string[] = [];
113
+ for (const group of OVERRIDE_GROUPS) {
114
+ const set = group.filter((key) => tokens[key] !== undefined);
115
+ if (set.length === 0 || set.length === group.length) {
116
+ continue;
117
+ }
118
+ const missing = group.filter((key) => tokens[key] === undefined);
119
+ issues.push(
120
+ `incomplete override group: setting ${set.map((k) => `tokens.${k}`).join(", ")} also requires ` +
121
+ `${missing.map((k) => `tokens.${k}`).join(", ")} — a partial override mixes with unknown ` +
122
+ `base-theme colors, which would bypass the contrast floor`,
123
+ );
124
+ }
125
+ return issues;
126
+ }
127
+
128
+ function expandHex(hex: string): string {
129
+ const raw = hex.slice(1);
130
+ if (raw.length === 6) {
131
+ return raw;
132
+ }
133
+ return raw
134
+ .split("")
135
+ .map((c) => c + c)
136
+ .join("");
137
+ }
138
+
139
+ function relativeLuminance(hex: string): number {
140
+ const expanded = expandHex(hex);
141
+ const channels = [0, 2, 4].map((offset) => {
142
+ const value = parseInt(expanded.slice(offset, offset + 2), 16) / 255;
143
+ return value <= 0.04045
144
+ ? value / 12.92
145
+ : Math.pow((value + 0.055) / 1.055, 2.4);
146
+ });
147
+ return 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2];
148
+ }
149
+
150
+ /** WCAG contrast ratio between two hex colors (order-independent). */
151
+ export function contrastRatio(a: string, b: string): number {
152
+ const la = relativeLuminance(a);
153
+ const lb = relativeLuminance(b);
154
+ const [lighter, darker] = la >= lb ? [la, lb] : [lb, la];
155
+ return (lighter + 0.05) / (darker + 0.05);
156
+ }
157
+
158
+ function contrastIssues(tokens: WorkspaceThemeTokens): string[] {
159
+ const issues: string[] = [];
160
+ for (const [fgKey, bgKey] of CONTRAST_PAIRS) {
161
+ const fg = tokens[fgKey];
162
+ const bg = tokens[bgKey];
163
+ if (!fg || !bg) {
164
+ continue;
165
+ }
166
+ const ratio = contrastRatio(fg, bg);
167
+ if (ratio < MIN_TEXT_CONTRAST_RATIO) {
168
+ issues.push(
169
+ `tokens.${fgKey} on tokens.${bgKey} has contrast ${ratio.toFixed(2)}:1 — minimum is ${MIN_TEXT_CONTRAST_RATIO}:1`,
170
+ );
171
+ }
172
+ }
173
+ return issues;
174
+ }
175
+
176
+ export interface WorkspaceThemeReadResult {
177
+ /** Validated theme, or null when the file is absent or rejected. */
178
+ theme: WorkspaceTheme | null;
179
+ /**
180
+ * "workspace" = valid file applied; "invalid" = file present but rejected
181
+ * (see issues); "none" = no theme file in the workspace.
182
+ */
183
+ source: "workspace" | "invalid" | "none";
184
+ issues: string[];
185
+ }
186
+
187
+ function formatZodIssues(error: z.ZodError): string[] {
188
+ return error.issues.map((issue) => {
189
+ const path = issue.path.join(".");
190
+ return path ? `${path}: ${issue.message}` : issue.message;
191
+ });
192
+ }
193
+
194
+ /** Generous ceiling for a token-override file; anything larger is not a theme. */
195
+ export const MAX_THEME_FILE_BYTES = 64 * 1024;
196
+
197
+ /**
198
+ * Open the theme file without following a final-component symlink and
199
+ * without blocking (opening a FIFO read-only would otherwise suspend the
200
+ * event loop until a writer appears), then require a bounded regular file
201
+ * before reading. Returns the file content or a rejection issue.
202
+ */
203
+ function readThemeFileGuarded(
204
+ themePath: string,
205
+ ): { raw: string } | { missing: true } | { issue: string } {
206
+ let fd: number;
207
+ try {
208
+ fd = openSync(
209
+ themePath,
210
+ constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK,
211
+ );
212
+ } catch (err) {
213
+ const code = (err as NodeJS.ErrnoException).code;
214
+ if (code === "ENOENT") {
215
+ return { missing: true };
216
+ }
217
+ if (code === "ELOOP" || code === "EMLINK") {
218
+ return {
219
+ issue: `${WORKSPACE_THEME_RELATIVE_PATH} must be a regular file, not a symbolic link`,
220
+ };
221
+ }
222
+ const message = err instanceof Error ? err.message : String(err);
223
+ return {
224
+ issue: `failed to open ${WORKSPACE_THEME_RELATIVE_PATH}: ${message}`,
225
+ };
226
+ }
227
+
228
+ try {
229
+ const stat = fstatSync(fd);
230
+ if (!stat.isFile()) {
231
+ return {
232
+ issue: `${WORKSPACE_THEME_RELATIVE_PATH} must be a regular file`,
233
+ };
234
+ }
235
+ if (stat.size > MAX_THEME_FILE_BYTES) {
236
+ return {
237
+ issue:
238
+ `${WORKSPACE_THEME_RELATIVE_PATH} is ${stat.size} bytes — ` +
239
+ `maximum is ${MAX_THEME_FILE_BYTES}`,
240
+ };
241
+ }
242
+ return { raw: readFileSync(fd, "utf-8") };
243
+ } catch (err) {
244
+ const message = err instanceof Error ? err.message : String(err);
245
+ return {
246
+ issue: `failed to read ${WORKSPACE_THEME_RELATIVE_PATH}: ${message}`,
247
+ };
248
+ } finally {
249
+ closeSync(fd);
250
+ }
251
+ }
252
+
253
+ /**
254
+ * Read and validate the workspace theme file. Never throws: an unreadable,
255
+ * unparsable, or out-of-policy file yields `source: "invalid"` with
256
+ * human-readable issues so callers (and the authoring assistant) can surface
257
+ * exactly what was rejected.
258
+ */
259
+ export function readWorkspaceTheme(): WorkspaceThemeReadResult {
260
+ const themePath = join(getWorkspaceDir(), WORKSPACE_THEME_RELATIVE_PATH);
261
+
262
+ const file = readThemeFileGuarded(themePath);
263
+ if ("missing" in file) {
264
+ return { theme: null, source: "none", issues: [] };
265
+ }
266
+ if ("issue" in file) {
267
+ return { theme: null, source: "invalid", issues: [file.issue] };
268
+ }
269
+ const raw = file.raw;
270
+
271
+ let parsed: unknown;
272
+ try {
273
+ parsed = JSON.parse(raw);
274
+ } catch (err) {
275
+ const message = err instanceof Error ? err.message : String(err);
276
+ return {
277
+ theme: null,
278
+ source: "invalid",
279
+ issues: [`not valid JSON: ${message}`],
280
+ };
281
+ }
282
+
283
+ const result = WorkspaceThemeSchema.safeParse(parsed);
284
+ if (!result.success) {
285
+ return {
286
+ theme: null,
287
+ source: "invalid",
288
+ issues: formatZodIssues(result.error),
289
+ };
290
+ }
291
+
292
+ if (result.data.tokens) {
293
+ const completeness = groupCompletenessIssues(result.data.tokens);
294
+ if (completeness.length > 0) {
295
+ return { theme: null, source: "invalid", issues: completeness };
296
+ }
297
+ const legibility = contrastIssues(result.data.tokens);
298
+ if (legibility.length > 0) {
299
+ return { theme: null, source: "invalid", issues: legibility };
300
+ }
301
+ }
302
+
303
+ return { theme: result.data, source: "workspace", issues: [] };
304
+ }