@vellumai/assistant 0.12.5-dev.202609270227.2575c70 → 0.12.5-dev.202609271314.15fcb5b

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vellumai/assistant",
3
- "version": "0.12.5-dev.202609270227.2575c70",
3
+ "version": "0.12.5-dev.202609271314.15fcb5b",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "exports": {
@@ -26,11 +26,15 @@ import {
26
26
  type AdmissionPolicy,
27
27
  isAdmissionPolicy,
28
28
  } from "@vellumai/gateway-client";
29
+ import { z } from "zod";
29
30
 
30
31
  import type { ChannelId } from "../channels/types.js";
31
32
  import { ipcCall } from "../ipc/gateway-client.js";
32
33
 
33
34
  const CACHE_TTL_MS = 5_000;
35
+ const AdmissionPolicyResponseSchema = z.object({
36
+ policy: z.unknown(),
37
+ });
34
38
 
35
39
  // Short IPC timeout so admission fails closed PROMPTLY: a gateway that accepts
36
40
  // the socket but stalls must never delay a live call handshake. 1s is generous
@@ -64,20 +68,22 @@ async function fetchAdmissionPolicy(
64
68
  // ipcCall() returns undefined on transport failure (socket not found,
65
69
  // timeout, parse error). That, a throw, or a malformed shape is a FAILURE:
66
70
  // fail closed without caching so the next setup re-attempts the IPC.
67
- const result = (await ipcCall(
68
- "get_channel_admission_policy",
69
- { channelType },
70
- ADMISSION_IPC_TIMEOUT_MS,
71
- )) as { policy?: unknown } | null | undefined;
71
+ const parsed = AdmissionPolicyResponseSchema.safeParse(
72
+ await ipcCall(
73
+ "get_channel_admission_policy",
74
+ { channelType },
75
+ ADMISSION_IPC_TIMEOUT_MS,
76
+ ),
77
+ );
72
78
 
73
- if (result === undefined) {
79
+ if (!parsed.success) {
74
80
  return { ok: false };
75
81
  }
76
- if (result && isAdmissionPolicy(result.policy)) {
77
- return { ok: true, policy: result.policy };
82
+ if (isAdmissionPolicy(parsed.data.policy)) {
83
+ return { ok: true, policy: parsed.data.policy };
78
84
  }
79
85
  // Explicit "no enforcement" — the gateway successfully answered. Cacheable.
80
- if (result && result.policy === null) {
86
+ if (parsed.data.policy === null) {
81
87
  return { ok: true, policy: null };
82
88
  }
83
89
  // Anything else (missing/invalid policy field) is a malformed shape.
@@ -16,6 +16,8 @@
16
16
  import { existsSync, readFileSync } from "node:fs";
17
17
  import { dirname, join } from "node:path";
18
18
 
19
+ import { z } from "zod";
20
+
19
21
  import { ipcGetFeatureFlags } from "../ipc/gateway-client.js";
20
22
  import { getLogger } from "../util/logger.js";
21
23
  import {
@@ -47,6 +49,22 @@ export type FeatureFlagDefaultsRegistry = Record<string, FeatureFlagDefault>;
47
49
  let cachedDefaults: FeatureFlagDefaultsRegistry | undefined;
48
50
 
49
51
  const REGISTRY_FILENAME = "feature-flag-registry.json";
52
+ const FeatureFlagRegistryEntrySchema = z
53
+ .object({
54
+ scope: z.enum(["assistant", "both"]).optional().catch(undefined),
55
+ key: z.string().optional().catch(undefined),
56
+ defaultEnabled: z
57
+ .union([z.boolean(), z.string()])
58
+ .optional()
59
+ .catch(undefined),
60
+ description: z.string().catch(""),
61
+ label: z.string().catch(""),
62
+ })
63
+ .optional()
64
+ .catch(undefined);
65
+ const FeatureFlagRegistrySchema = z.object({
66
+ flags: z.array(FeatureFlagRegistryEntrySchema),
67
+ });
50
68
 
51
69
  function loadDefaultsRegistry(): FeatureFlagDefaultsRegistry {
52
70
  if (cachedDefaults) {
@@ -100,39 +118,26 @@ function loadDefaultsRegistry(): FeatureFlagDefaultsRegistry {
100
118
  * filtering to flags the backend consumes (`assistant`- and `both`-scope).
101
119
  */
102
120
  function parseRegistryToDefaults(parsed: unknown): FeatureFlagDefaultsRegistry {
103
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
104
- return {};
105
- }
106
-
107
- const registry = parsed as { version?: number; flags?: unknown[] };
108
- if (!Array.isArray(registry.flags)) {
121
+ const registry = FeatureFlagRegistrySchema.safeParse(parsed);
122
+ if (!registry.success) {
109
123
  return {};
110
124
  }
111
125
 
112
126
  const result: FeatureFlagDefaultsRegistry = {};
113
- for (const flag of registry.flags) {
114
- if (!flag || typeof flag !== "object" || Array.isArray(flag)) {
115
- continue;
116
- }
117
- const entry = flag as Record<string, unknown>;
118
- if (entry.scope !== "assistant" && entry.scope !== "both") {
119
- continue;
120
- }
121
- if (typeof entry.key !== "string") {
122
- continue;
123
- }
127
+ for (const entry of registry.data.flags) {
124
128
  if (
125
- typeof entry.defaultEnabled !== "boolean" &&
126
- typeof entry.defaultEnabled !== "string"
129
+ !entry ||
130
+ entry.scope === undefined ||
131
+ entry.key === undefined ||
132
+ entry.defaultEnabled === undefined
127
133
  ) {
128
134
  continue;
129
135
  }
130
136
 
131
- result[entry.key as string] = {
137
+ result[entry.key] = {
132
138
  defaultEnabled: entry.defaultEnabled,
133
- description:
134
- typeof entry.description === "string" ? entry.description : "",
135
- label: typeof entry.label === "string" ? entry.label : "",
139
+ description: entry.description,
140
+ label: entry.label,
136
141
  };
137
142
  }
138
143
  return result;
@@ -1,5 +1,19 @@
1
+ import { z } from "zod";
2
+
1
3
  import { catalogModelSupportsText } from "../providers/model-catalog.js";
2
4
 
5
+ const ProfileReferenceSchema = z
6
+ .object({
7
+ profile: z.string().optional().catch(undefined),
8
+ })
9
+ .optional()
10
+ .catch(undefined);
11
+ const TextGenerationProfileSchema = z.object({
12
+ provider: z.string().optional().catch(undefined),
13
+ model: z.string().optional().catch(undefined),
14
+ mix: z.array(ProfileReferenceSchema).optional().catch(undefined),
15
+ });
16
+
3
17
  /**
4
18
  * Whether a profile can back the conversation model (active profile or a
5
19
  * per-conversation pin). Mix arms are judged individually: a mix that can
@@ -16,34 +30,24 @@ export function profileSupportsTextGeneration(
16
30
  },
17
31
  siblings: Record<string, unknown>,
18
32
  ): boolean {
19
- const mix = entry.mix;
20
- if (Array.isArray(mix) && mix.length > 0) {
21
- return mix.every((arm) => {
22
- const name =
23
- arm !== null &&
24
- typeof arm === "object" &&
25
- "profile" in arm &&
26
- typeof arm.profile === "string"
27
- ? arm.profile
28
- : undefined;
33
+ const parsed = TextGenerationProfileSchema.safeParse(entry);
34
+ if (!parsed.success) {
35
+ return true;
36
+ }
37
+ if (parsed.data.mix && parsed.data.mix.length > 0) {
38
+ return parsed.data.mix.every((arm) => {
39
+ const name = arm?.profile;
29
40
  if (name === undefined) {
30
41
  return true;
31
42
  }
32
- const target = siblings[name];
33
- if (target === null || typeof target !== "object") {
43
+ const target = TextGenerationProfileSchema.safeParse(siblings[name]);
44
+ if (!target.success) {
34
45
  return true;
35
46
  }
36
- const nested = target as { provider?: unknown; model?: unknown };
37
- return catalogModelSupportsText(
38
- typeof nested.provider === "string" ? nested.provider : undefined,
39
- typeof nested.model === "string" ? nested.model : undefined,
40
- );
47
+ return catalogModelSupportsText(target.data.provider, target.data.model);
41
48
  });
42
49
  }
43
- return catalogModelSupportsText(
44
- typeof entry.provider === "string" ? entry.provider : undefined,
45
- typeof entry.model === "string" ? entry.model : undefined,
46
- );
50
+ return catalogModelSupportsText(parsed.data.provider, parsed.data.model);
47
51
  }
48
52
 
49
53
  export function nonTextConversationProfileMessage(profileName: string): string {
@@ -1,10 +1,14 @@
1
1
  import { GetContactIpcResponseSchema } from "@vellumai/gateway-client/gateway-ipc-contracts";
2
+ import { z } from "zod";
2
3
 
3
4
  import { ipcCallPersistent } from "../ipc/gateway-client.js";
4
5
  import { getLogger } from "../util/logger.js";
5
6
  import type { ContactChannel } from "./types.js";
6
7
 
7
8
  const log = getLogger("gateway-channel-read");
9
+ const ContactEnvelopeSchema = z.object({
10
+ contact: z.unknown().optional(),
11
+ });
8
12
 
9
13
  /**
10
14
  * Read a contact channel's verified state from the gateway contact-channel read
@@ -32,7 +36,8 @@ export async function gatewayContactChannelState(
32
36
  );
33
37
  return undefined;
34
38
  }
35
- if (!result || (result as { contact?: unknown }).contact == null) {
39
+ const envelope = ContactEnvelopeSchema.safeParse(result);
40
+ if (!envelope.success || envelope.data.contact == null) {
36
41
  return undefined;
37
42
  }
38
43
  const parsed = GetContactIpcResponseSchema.safeParse(result);
@@ -2,9 +2,14 @@ import { readdir, readFile, readlink, realpath } from "node:fs/promises";
2
2
  import { createServer } from "node:net";
3
3
  import { join } from "node:path";
4
4
 
5
+ import { z } from "zod";
6
+
5
7
  import { shouldRestoreDesktopChromeSession } from "./desktop-chrome-session.js";
6
8
 
7
9
  export const DESKTOP_CHROME_WINDOW_CLASS = "vellum-desktop-chrome";
10
+ const DesktopVersionResponseSchema = z.object({
11
+ webSocketDebuggerUrl: z.unknown().optional(),
12
+ });
8
13
 
9
14
  export async function allocateDesktopDebugPort(): Promise<number> {
10
15
  const server = createServer();
@@ -119,9 +124,12 @@ export async function discoverDesktopBrowser(
119
124
  if (body.length > 16_384) {
120
125
  throw new Error("Desktop browser discovery exceeded its size limit");
121
126
  }
122
- const data = JSON.parse(body) as { webSocketDebuggerUrl?: unknown };
127
+ const parsed = DesktopVersionResponseSchema.safeParse(JSON.parse(body));
123
128
  await assertDesktopListener(pid, port);
124
- return validateDesktopWebSocket(data.webSocketDebuggerUrl, port);
129
+ return validateDesktopWebSocket(
130
+ parsed.success ? parsed.data.webSocketDebuggerUrl : undefined,
131
+ port,
132
+ );
125
133
  }
126
134
 
127
135
  export function desktopChromeArguments(
@@ -1,3 +1,5 @@
1
+ import { z } from "zod";
2
+
1
3
  import {
2
4
  escapeTagBoundaries,
3
5
  wrapUntrustedContent,
@@ -57,59 +59,43 @@ const ROLE_MAX = 64;
57
59
  const SECTION_MAX = 60;
58
60
  const ID_MAX = 32;
59
61
 
60
- const isFraction = (value: unknown): value is number =>
61
- typeof value === "number" &&
62
- Number.isFinite(value) &&
63
- value >= 0 &&
64
- value <= 1;
65
-
66
- const boundedString = (value: unknown, max: number): string | null => {
67
- if (typeof value !== "string") {
68
- return null;
69
- }
70
- const trimmed = value.trim();
71
- return trimmed.length > 0 && trimmed.length <= max ? trimmed : null;
72
- };
62
+ const boundedString = (max: number) =>
63
+ z
64
+ .string()
65
+ .transform((value) => value.trim())
66
+ .refine((value) => value.length > 0 && value.length <= max);
67
+ const FractionSchema = z
68
+ .number()
69
+ .refine((value) => Number.isFinite(value) && value >= 0 && value <= 1);
70
+ const ShareTargetSchema = z
71
+ .object({
72
+ id: boundedString(ID_MAX),
73
+ label: boundedString(LABEL_MAX),
74
+ role: boundedString(ROLE_MAX),
75
+ section: boundedString(SECTION_MAX).optional().catch(undefined),
76
+ x: FractionSchema,
77
+ y: FractionSchema,
78
+ width: FractionSchema,
79
+ height: FractionSchema,
80
+ duplicates: z
81
+ .number()
82
+ .refine((value) => Number.isSafeInteger(value) && value > 1)
83
+ .optional()
84
+ .catch(undefined),
85
+ })
86
+ .transform(({ section, duplicates, ...target }) => ({
87
+ ...target,
88
+ ...(section !== undefined ? { section } : {}),
89
+ ...(duplicates !== undefined ? { duplicates } : {}),
90
+ }));
91
+ const ShareTargetSnapshotSchema = z.object({
92
+ targets: z.array(z.unknown()),
93
+ total: z.number().refine(Number.isSafeInteger).optional().catch(undefined),
94
+ });
73
95
 
74
96
  function parseShareTarget(value: unknown): ShareTarget | null {
75
- if (typeof value !== "object" || value === null) {
76
- return null;
77
- }
78
- const record = value as Record<string, unknown>;
79
- const id = boundedString(record.id, ID_MAX);
80
- const label = boundedString(record.label, LABEL_MAX);
81
- const role = boundedString(record.role, ROLE_MAX);
82
- const { x, y, width, height } = record;
83
- if (
84
- id === null ||
85
- label === null ||
86
- role === null ||
87
- !isFraction(x) ||
88
- !isFraction(y) ||
89
- !isFraction(width) ||
90
- !isFraction(height)
91
- ) {
92
- return null;
93
- }
94
- const section =
95
- record.section === undefined
96
- ? null
97
- : boundedString(record.section, SECTION_MAX);
98
- const duplicates =
99
- Number.isSafeInteger(record.duplicates) && (record.duplicates as number) > 1
100
- ? (record.duplicates as number)
101
- : null;
102
- return {
103
- id,
104
- label,
105
- role,
106
- ...(section !== null ? { section } : {}),
107
- x,
108
- y,
109
- width,
110
- height,
111
- ...(duplicates !== null ? { duplicates } : {}),
112
- };
97
+ const parsed = ShareTargetSchema.safeParse(value);
98
+ return parsed.success ? parsed.data : null;
113
99
  }
114
100
 
115
101
  /**
@@ -126,21 +112,17 @@ export function parseShareTargetSnapshot(
126
112
  if (value === null) {
127
113
  return null;
128
114
  }
129
- if (
130
- typeof value !== "object" ||
131
- !Array.isArray((value as { targets?: unknown }).targets)
132
- ) {
115
+ const parsed = ShareTargetSnapshotSchema.safeParse(value);
116
+ if (!parsed.success) {
133
117
  return undefined;
134
118
  }
135
- const record = value as { targets: unknown[]; total?: unknown };
136
- const targets = record.targets
119
+ const targets = parsed.data.targets
137
120
  .slice(0, SHARE_TARGETS_ACCEPTED_MAX)
138
121
  .map(parseShareTarget)
139
122
  .filter((target): target is ShareTarget => target !== null);
140
123
  const total =
141
- Number.isSafeInteger(record.total) &&
142
- (record.total as number) >= targets.length
143
- ? (record.total as number)
124
+ parsed.data.total !== undefined && parsed.data.total >= targets.length
125
+ ? parsed.data.total
144
126
  : targets.length;
145
127
  return { targets, total };
146
128
  }
@@ -1,3 +1,5 @@
1
+ import { z } from "zod";
2
+
1
3
  import {
2
4
  DEFAULT_OPENROUTER_IMAGE_MODEL,
3
5
  qualifyImageModelForOpenRouter,
@@ -13,6 +15,31 @@ import {
13
15
  } from "./types.js";
14
16
 
15
17
  const OPENROUTER_IMAGES_URL = "https://openrouter.ai/api/v1/images";
18
+ const OpenRouterImageResponseSchema = z.object({
19
+ data: z
20
+ .array(
21
+ z
22
+ .object({
23
+ b64_json: z.string().optional().catch(undefined),
24
+ media_type: z.string().optional().catch(undefined),
25
+ })
26
+ .optional()
27
+ .catch(undefined),
28
+ )
29
+ .optional()
30
+ .catch(undefined),
31
+ error: z
32
+ .union([
33
+ z.string(),
34
+ z.object({
35
+ message: z.string().optional().catch(undefined),
36
+ }),
37
+ ])
38
+ .optional()
39
+ .catch(undefined),
40
+ });
41
+
42
+ type OpenRouterImageResponse = z.infer<typeof OpenRouterImageResponseSchema>;
16
43
 
17
44
  /**
18
45
  * Qualify a bare built-in ID or alias for OpenRouter. Call sites that skip
@@ -76,21 +103,11 @@ export function mapOpenRouterError(error: unknown): string {
76
103
  return "An unexpected error occurred during image generation.";
77
104
  }
78
105
 
79
- function errorMessage(body: unknown): string {
80
- if (typeof body !== "object" || body === null) {
81
- return "Request failed";
82
- }
83
- const error = (body as { error?: unknown }).error;
84
- if (typeof error === "string") {
85
- return error;
86
- }
87
- if (typeof error === "object" && error !== null) {
88
- const message = (error as { message?: unknown }).message;
89
- if (typeof message === "string" && message) {
90
- return message;
91
- }
106
+ function errorMessage(body: OpenRouterImageResponse | undefined): string {
107
+ if (typeof body?.error === "string") {
108
+ return body.error;
92
109
  }
93
- return "Request failed";
110
+ return body?.error?.message || "Request failed";
94
111
  }
95
112
 
96
113
  export async function generateImageOpenRouter(
@@ -98,7 +115,9 @@ export async function generateImageOpenRouter(
98
115
  request: ImageGenerationRequest,
99
116
  ): Promise<ImageGenerationResult> {
100
117
  if (credentials.type !== "direct") {
101
- throw new Error("OpenRouter image generation requires an OpenRouter API key.");
118
+ throw new Error(
119
+ "OpenRouter image generation requires an OpenRouter API key.",
120
+ );
102
121
  }
103
122
 
104
123
  const model = resolveOpenRouterModel(request.model);
@@ -127,12 +146,10 @@ export async function generateImageOpenRouter(
127
146
  ...(request.signal ? { signal: request.signal } : {}),
128
147
  });
129
148
 
130
- const body = (await response.json().catch(() => undefined)) as
131
- | {
132
- data?: Array<{ b64_json?: string; media_type?: string }>;
133
- error?: unknown;
134
- }
135
- | undefined;
149
+ const parsed = OpenRouterImageResponseSchema.safeParse(
150
+ await response.json().catch(() => undefined),
151
+ );
152
+ const body = parsed.success ? parsed.data : undefined;
136
153
 
137
154
  if (!response.ok) {
138
155
  throw new OpenRouterImageError(response.status, errorMessage(body));
@@ -140,7 +157,7 @@ export async function generateImageOpenRouter(
140
157
 
141
158
  const images: GeneratedImage[] = [];
142
159
  for (const entry of body?.data ?? []) {
143
- if (!entry.b64_json) {
160
+ if (!entry?.b64_json) {
144
161
  continue;
145
162
  }
146
163
  images.push({
@@ -17,6 +17,8 @@
17
17
  * imports — the vellum STT/TTS providers build on top of it.
18
18
  */
19
19
 
20
+ import { z } from "zod";
21
+
20
22
  import { VellumPlatformClient } from "./client.js";
21
23
 
22
24
  export type ManagedSpeechResult<T> =
@@ -43,6 +45,11 @@ export interface ManagedSpeechTranscription {
43
45
  durationSeconds: number;
44
46
  }
45
47
 
48
+ const ManagedSpeechTranscriptionSchema = z.object({
49
+ text: z.string(),
50
+ durationSeconds: z.number(),
51
+ });
52
+
46
53
  export interface ManagedSpeechSynthesis {
47
54
  audio: Buffer;
48
55
  contentType: string;
@@ -125,13 +132,10 @@ export async function managedSpeechTranscribe(input: {
125
132
  return await platformError(response, "transcription");
126
133
  }
127
134
 
128
- const body: unknown = await response.json().catch(() => null);
129
- if (
130
- !body ||
131
- typeof body !== "object" ||
132
- typeof (body as { text?: unknown }).text !== "string" ||
133
- typeof (body as { durationSeconds?: unknown }).durationSeconds !== "number"
134
- ) {
135
+ const parsed = ManagedSpeechTranscriptionSchema.safeParse(
136
+ await response.json().catch(() => null),
137
+ );
138
+ if (!parsed.success) {
135
139
  return {
136
140
  ok: false,
137
141
  kind: "platform-error",
@@ -139,10 +143,12 @@ export async function managedSpeechTranscribe(input: {
139
143
  message: "Managed speech transcription returned a malformed response.",
140
144
  };
141
145
  }
142
- const parsed = body as { text: string; durationSeconds: number };
143
146
  return {
144
147
  ok: true,
145
- value: { text: parsed.text, durationSeconds: parsed.durationSeconds },
148
+ value: {
149
+ text: parsed.data.text,
150
+ durationSeconds: parsed.data.durationSeconds,
151
+ },
146
152
  };
147
153
  }
148
154
 
@@ -211,25 +217,21 @@ export interface ManagedSpeechVoiceCatalog {
211
217
  defaultModel: string | null;
212
218
  }
213
219
 
214
- function parseVoice(value: unknown): ManagedSpeechVoice | null {
215
- const voice = value as Partial<Record<keyof ManagedSpeechVoice, unknown>>;
216
- if (
217
- typeof voice?.model !== "string" ||
218
- typeof voice.label !== "string" ||
219
- typeof voice.description !== "string" ||
220
- typeof voice.sampleUrl !== "string" ||
221
- typeof voice.source !== "string"
222
- ) {
223
- return null;
224
- }
225
- return {
226
- model: voice.model,
227
- label: voice.label,
228
- description: voice.description,
229
- sampleUrl: voice.sampleUrl,
230
- source: voice.source,
231
- };
232
- }
220
+ const ManagedSpeechVoiceSchema = z.object({
221
+ model: z.string(),
222
+ label: z.string(),
223
+ description: z.string(),
224
+ sampleUrl: z.string(),
225
+ source: z.string(),
226
+ });
227
+ const ManagedSpeechVoiceCatalogSchema = z.object({
228
+ voices: z.array(ManagedSpeechVoiceSchema.nullable().catch(null)),
229
+ defaultModel: z.string().nullable().optional().catch(null),
230
+ });
231
+ const ManagedSpeechErrorSchema = z.object({
232
+ code: z.string().optional().catch(undefined),
233
+ detail: z.string().optional().catch(undefined),
234
+ });
233
235
 
234
236
  export async function managedSpeechVoices(input?: {
235
237
  signal?: AbortSignal;
@@ -249,12 +251,10 @@ export async function managedSpeechVoices(input?: {
249
251
  return await platformError(response, "voice listing");
250
252
  }
251
253
 
252
- const body: unknown = await response.json().catch(() => null);
253
- const raw = body as { voices?: unknown; defaultModel?: unknown } | null;
254
- const voices = Array.isArray(raw?.voices)
255
- ? raw.voices.map(parseVoice).filter((v): v is ManagedSpeechVoice => !!v)
256
- : null;
257
- if (!voices) {
254
+ const parsed = ManagedSpeechVoiceCatalogSchema.safeParse(
255
+ await response.json().catch(() => null),
256
+ );
257
+ if (!parsed.success) {
258
258
  return {
259
259
  ok: false,
260
260
  kind: "platform-error",
@@ -265,9 +265,10 @@ export async function managedSpeechVoices(input?: {
265
265
  return {
266
266
  ok: true,
267
267
  value: {
268
- voices,
269
- defaultModel:
270
- typeof raw?.defaultModel === "string" ? raw.defaultModel : null,
268
+ voices: parsed.data.voices.filter(
269
+ (voice): voice is ManagedSpeechVoice => voice !== null,
270
+ ),
271
+ defaultModel: parsed.data.defaultModel ?? null,
271
272
  },
272
273
  };
273
274
  }
@@ -279,15 +280,10 @@ async function platformError(
279
280
  let code: string | undefined;
280
281
  let detail: string | undefined;
281
282
  try {
282
- const body = (await response.json()) as {
283
- code?: unknown;
284
- detail?: unknown;
285
- };
286
- if (typeof body?.code === "string") {
287
- code = body.code;
288
- }
289
- if (typeof body?.detail === "string") {
290
- detail = body.detail;
283
+ const parsed = ManagedSpeechErrorSchema.safeParse(await response.json());
284
+ if (parsed.success) {
285
+ code = parsed.data.code;
286
+ detail = parsed.data.detail;
291
287
  }
292
288
  } catch {
293
289
  // Non-JSON error body; status alone will have to do.
@@ -14,6 +14,8 @@ import { homedir } from "node:os";
14
14
  import { dirname, join, posix, resolve, sep } from "node:path";
15
15
  import { gunzipSync } from "node:zlib";
16
16
 
17
+ import { z } from "zod";
18
+
17
19
  import {
18
20
  MALFORMED_USTAR_SIZE,
19
21
  parseUstarSizeField,
@@ -27,6 +29,7 @@ import { computeSkillHash, writeInstallMeta } from "./install-meta.js";
27
29
  import {
28
30
  isSkillCompatibleWithPlatform,
29
31
  normalizeSkillPlatforms,
32
+ SKILL_PLATFORM_VALUES,
30
33
  type SkillPlatform,
31
34
  skillPlatformUnavailableMessage,
32
35
  } from "./platform-compatibility.js";
@@ -142,21 +145,46 @@ export function getRepoSkillsDir(): string | undefined {
142
145
  * `metadata.vellum.*` shape used by the local `catalog.json`. Both shapes are
143
146
  * accepted here so the daemon has a single canonical representation downstream.
144
147
  */
145
- interface RawCatalogEntry {
146
- id?: unknown;
147
- name?: unknown;
148
- description?: unknown;
149
- icon?: unknown;
150
- emoji?: string;
151
- includes?: string[];
152
- version?: string;
153
- updatedAt?: unknown;
154
- display_name?: unknown;
155
- category?: unknown;
156
- platforms?: unknown;
157
- updated_at?: unknown;
158
- metadata?: CatalogSkill["metadata"];
159
- }
148
+ const CatalogPlatformsSchema = z
149
+ .array(z.enum(SKILL_PLATFORM_VALUES).optional().catch(undefined))
150
+ .transform((platforms) =>
151
+ platforms.filter((platform): platform is SkillPlatform => platform != null),
152
+ );
153
+ const CatalogVellumMetadataSchema = z
154
+ .object({
155
+ "display-name": z.string().optional().catch(undefined),
156
+ "activation-hints": z.array(z.string()).optional().catch(undefined),
157
+ "avoid-when": z.array(z.string()).optional().catch(undefined),
158
+ "feature-flag": z.string().optional().catch(undefined),
159
+ category: z.string().optional().catch(undefined),
160
+ platforms: CatalogPlatformsSchema.optional().catch(undefined),
161
+ })
162
+ .passthrough();
163
+ const CatalogMetadataSchema = z
164
+ .object({
165
+ icon: z.string().optional().catch(undefined),
166
+ emoji: z.string().optional().catch(undefined),
167
+ vellum: CatalogVellumMetadataSchema.optional().catch(undefined),
168
+ })
169
+ .passthrough();
170
+ const RawCatalogEntrySchema = z.object({
171
+ id: z.string().optional().catch(undefined),
172
+ name: z.string().optional().catch(undefined),
173
+ description: z.string().optional().catch(undefined),
174
+ icon: z.string().optional().catch(undefined),
175
+ emoji: z.string().optional().catch(undefined),
176
+ includes: z.array(z.string()).optional().catch(undefined),
177
+ version: z.string().optional().catch(undefined),
178
+ updatedAt: z.string().optional().catch(undefined),
179
+ display_name: z.string().optional().catch(undefined),
180
+ category: z.string().optional().catch(undefined),
181
+ platforms: CatalogPlatformsSchema.optional().catch(undefined),
182
+ updated_at: z.string().optional().catch(undefined),
183
+ metadata: CatalogMetadataSchema.optional().catch(undefined),
184
+ });
185
+ const CatalogManifestSchema = z.object({
186
+ skills: z.array(z.unknown()),
187
+ });
160
188
 
161
189
  function asStr(value: unknown): string | undefined {
162
190
  return typeof value === "string" && value.length > 0 ? value : undefined;
@@ -172,10 +200,11 @@ function asStr(value: unknown): string | undefined {
172
200
  * so a future API change to the nested shape keeps working.
173
201
  */
174
202
  function normalizeCatalogEntry(raw: unknown): CatalogSkill | null {
175
- if (typeof raw !== "object" || raw === null) {
203
+ const parsed = RawCatalogEntrySchema.safeParse(raw);
204
+ if (!parsed.success) {
176
205
  return null;
177
206
  }
178
- const entry = raw as RawCatalogEntry;
207
+ const entry = parsed.data;
179
208
 
180
209
  const id = asStr(entry.id);
181
210
  if (!id) {
@@ -227,11 +256,11 @@ export async function fetchCatalog(): Promise<CatalogSkill[]> {
227
256
  );
228
257
  }
229
258
 
230
- const manifest = (await response.json()) as { skills?: unknown };
231
- if (!Array.isArray(manifest.skills)) {
259
+ const manifest = CatalogManifestSchema.safeParse(await response.json());
260
+ if (!manifest.success) {
232
261
  throw new Error("Platform catalog has invalid skills array");
233
262
  }
234
- return manifest.skills
263
+ return manifest.data.skills
235
264
  .map((s) => normalizeCatalogEntry(s))
236
265
  .filter((s): s is CatalogSkill => s !== null);
237
266
  }
@@ -239,11 +268,11 @@ export async function fetchCatalog(): Promise<CatalogSkill[]> {
239
268
  export function readLocalCatalog(repoSkillsDir: string): CatalogSkill[] {
240
269
  try {
241
270
  const raw = readFileSync(join(repoSkillsDir, "catalog.json"), "utf-8");
242
- const manifest = JSON.parse(raw) as { skills?: unknown };
243
- if (!Array.isArray(manifest.skills)) {
271
+ const manifest = CatalogManifestSchema.safeParse(JSON.parse(raw));
272
+ if (!manifest.success) {
244
273
  return [];
245
274
  }
246
- return manifest.skills
275
+ return manifest.data.skills
247
276
  .map((s) => normalizeCatalogEntry(s))
248
277
  .filter((s): s is CatalogSkill => s !== null);
249
278
  } catch {
@@ -38,6 +38,7 @@ describe("computeWorkerForceRamSizeBytes", () => {
38
38
 
39
39
  describe("workerMemoryEnv", () => {
40
40
  const savedForceRamSize = process.env.BUN_JSC_forceRAMSize;
41
+ const savedGcTimerDisable = process.env.BUN_GC_TIMER_DISABLE;
41
42
 
42
43
  afterEach(() => {
43
44
  if (savedForceRamSize === undefined) {
@@ -45,6 +46,11 @@ describe("workerMemoryEnv", () => {
45
46
  } else {
46
47
  process.env.BUN_JSC_forceRAMSize = savedForceRamSize;
47
48
  }
49
+ if (savedGcTimerDisable === undefined) {
50
+ delete process.env.BUN_GC_TIMER_DISABLE;
51
+ } else {
52
+ process.env.BUN_GC_TIMER_DISABLE = savedGcTimerDisable;
53
+ }
48
54
  });
49
55
 
50
56
  test("adds a clamped BUN_JSC_forceRAMSize on top of the parent environment", () => {
@@ -61,4 +67,14 @@ describe("workerMemoryEnv", () => {
61
67
  const env = workerMemoryEnv();
62
68
  expect(env.BUN_JSC_forceRAMSize).toBe("12345");
63
69
  });
70
+
71
+ test("disables the worker GC timer unless the operator set it", () => {
72
+ delete process.env.BUN_GC_TIMER_DISABLE;
73
+ expect(workerMemoryEnv().BUN_GC_TIMER_DISABLE).toBe("1");
74
+ });
75
+
76
+ test("keeps an operator-provided BUN_GC_TIMER_DISABLE", () => {
77
+ process.env.BUN_GC_TIMER_DISABLE = "0";
78
+ expect(workerMemoryEnv().BUN_GC_TIMER_DISABLE).toBe("0");
79
+ });
64
80
  });
@@ -60,9 +60,14 @@ export function computeWorkerForceRamSizeBytes(
60
60
 
61
61
  /**
62
62
  * Environment for spawning a background worker `bun` process: the parent
63
- * environment plus `BUN_JSC_forceRAMSize`. An operator-provided
64
- * `BUN_JSC_forceRAMSize` in the parent environment wins over the computed
65
- * value.
63
+ * environment plus `BUN_JSC_forceRAMSize` and `BUN_GC_TIMER_DISABLE`. An
64
+ * operator-provided value for either in the parent environment wins.
65
+ *
66
+ * `BUN_GC_TIMER_DISABLE=1` turns off Bun's repeating GC timer in the worker.
67
+ * Under a `forceRAMSize` heap that timer, together with the per-tick
68
+ * collection request, keeps a long-lived worker collecting continuously at
69
+ * roughly one full core; the workers' own allocation still triggers
70
+ * collection normally.
66
71
  *
67
72
  * Bun.spawn replaces (rather than merges) the child environment when `env` is
68
73
  * passed, so this spreads the full parent environment.
@@ -73,5 +78,6 @@ export function workerMemoryEnv(): Record<string, string | undefined> {
73
78
  BUN_JSC_forceRAMSize:
74
79
  process.env.BUN_JSC_forceRAMSize ??
75
80
  String(computeWorkerForceRamSizeBytes(getContainerMemoryLimitBytes())),
81
+ BUN_GC_TIMER_DISABLE: process.env.BUN_GC_TIMER_DISABLE ?? "1",
76
82
  };
77
83
  }
@@ -1,9 +1,14 @@
1
1
  import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
 
4
+ import { z } from "zod";
5
+
4
6
  import { getDataDir } from "../util/platform.js";
5
7
 
6
8
  const HATCHED_SIDECAR_FILENAME = "hatched.json";
9
+ const HatchedSidecarSchema = z.object({
10
+ hatchedAt: z.unknown().optional(),
11
+ });
7
12
 
8
13
  export function getHatchedSidecarPath(): string {
9
14
  return join(getDataDir(), HATCHED_SIDECAR_FILENAME);
@@ -24,10 +29,12 @@ function normalizeHatchedAt(value: unknown): string | undefined {
24
29
 
25
30
  export function readHatchedAtSidecar(): string | undefined {
26
31
  try {
27
- const parsed = JSON.parse(
28
- readFileSync(getHatchedSidecarPath(), "utf-8"),
29
- ) as { hatchedAt?: unknown };
30
- return normalizeHatchedAt(parsed.hatchedAt);
32
+ const parsed = HatchedSidecarSchema.safeParse(
33
+ JSON.parse(readFileSync(getHatchedSidecarPath(), "utf-8")),
34
+ );
35
+ return parsed.success
36
+ ? normalizeHatchedAt(parsed.data.hatchedAt)
37
+ : undefined;
31
38
  } catch {
32
39
  return undefined;
33
40
  }