@mycadet/cli 0.13.0-dev.202611171101.13836af → 0.13.0-dev.202611171301.b3e2e5c

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 (33) hide show
  1. package/node_modules/@mycadet/assistant-api/node_modules/@mycadet/service-contracts/package.json +1 -1
  2. package/node_modules/@mycadet/assistant-api/node_modules/@mycadet/service-contracts/src/remote-web-pairing.ts +7 -0
  3. package/node_modules/@mycadet/avatar-manifest/package.json +1 -1
  4. package/node_modules/@mycadet/ipc-server-utils/package.json +1 -1
  5. package/node_modules/@mycadet/local-mode/node_modules/@mycadet/avatar-manifest/package.json +1 -1
  6. package/node_modules/@mycadet/local-mode/node_modules/@mycadet/ipc-server-utils/package.json +1 -1
  7. package/node_modules/@mycadet/local-mode/node_modules/@mycadet/service-contracts/package.json +1 -1
  8. package/node_modules/@mycadet/local-mode/node_modules/@mycadet/service-contracts/src/remote-web-pairing.ts +7 -0
  9. package/node_modules/@mycadet/local-mode/node_modules/@mycadet/shared/package.json +1 -1
  10. package/node_modules/@mycadet/local-mode/package.json +1 -1
  11. package/node_modules/@mycadet/service-contracts/package.json +1 -1
  12. package/node_modules/@mycadet/service-contracts/src/remote-web-pairing.ts +7 -0
  13. package/node_modules/@mycadet/shared/package.json +1 -1
  14. package/package.json +2 -2
  15. package/src/commands/confirm.ts +5 -1
  16. package/src/commands/devices.ts +2 -2
  17. package/src/commands/hatch.ts +3 -3
  18. package/src/commands/machine.ts +2 -1
  19. package/src/commands/message.ts +5 -4
  20. package/src/commands/pair.ts +4 -3
  21. package/src/commands/ps.ts +2 -9
  22. package/src/commands/tunnel.ts +3 -2
  23. package/src/commands/upgrade.ts +4 -2
  24. package/src/components/DefaultMainScreen.tsx +20 -15
  25. package/src/index.ts +5 -1
  26. package/src/lib/cli-error.ts +25 -15
  27. package/src/lib/cloud-login.ts +1 -2
  28. package/src/lib/constants.ts +5 -0
  29. package/src/lib/live-voice/protocol.ts +3 -1
  30. package/src/lib/live-voice/tunnel.ts +9 -8
  31. package/src/lib/pair.ts +9 -2
  32. package/src/lib/tunnel.ts +5 -0
  33. package/src/lib/tunnels/tailscale.ts +12 -6
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mycadet/service-contracts",
3
- "version": "0.13.0-dev.202611171101.13836af",
3
+ "version": "0.13.0-dev.202611171301.b3e2e5c",
4
4
  "private": true,
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -83,6 +83,13 @@ export interface RemoteWebPairingVerificationRequest {
83
83
  * The gateway maps the `expired` / `invalid` outcomes to error responses, so
84
84
  * the only success shape on the wire is the approved variant.
85
85
  */
86
+ export const RemoteWebPairingVerificationResponseSchema = z.object({
87
+ status: z.literal("approved"),
88
+ verificationUri: z.string(),
89
+ /** ISO-8601 instant the approved challenge expires. */
90
+ expiresAt: z.string(),
91
+ }) satisfies z.ZodType<RemoteWebPairingVerificationResponse>;
92
+
86
93
  export interface RemoteWebPairingVerificationResponse {
87
94
  status: "approved";
88
95
  verificationUri: string;
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mycadet/avatar-manifest",
3
- "version": "0.13.0-dev.202611171101.13836af",
3
+ "version": "0.13.0-dev.202611171301.b3e2e5c",
4
4
  "private": true,
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mycadet/ipc-server-utils",
3
- "version": "0.13.0-dev.202611171101.13836af",
3
+ "version": "0.13.0-dev.202611171301.b3e2e5c",
4
4
  "private": true,
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mycadet/avatar-manifest",
3
- "version": "0.13.0-dev.202611171101.13836af",
3
+ "version": "0.13.0-dev.202611171301.b3e2e5c",
4
4
  "private": true,
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mycadet/ipc-server-utils",
3
- "version": "0.13.0-dev.202611171101.13836af",
3
+ "version": "0.13.0-dev.202611171301.b3e2e5c",
4
4
  "private": true,
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mycadet/service-contracts",
3
- "version": "0.13.0-dev.202611171101.13836af",
3
+ "version": "0.13.0-dev.202611171301.b3e2e5c",
4
4
  "private": true,
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -83,6 +83,13 @@ export interface RemoteWebPairingVerificationRequest {
83
83
  * The gateway maps the `expired` / `invalid` outcomes to error responses, so
84
84
  * the only success shape on the wire is the approved variant.
85
85
  */
86
+ export const RemoteWebPairingVerificationResponseSchema = z.object({
87
+ status: z.literal("approved"),
88
+ verificationUri: z.string(),
89
+ /** ISO-8601 instant the approved challenge expires. */
90
+ expiresAt: z.string(),
91
+ }) satisfies z.ZodType<RemoteWebPairingVerificationResponse>;
92
+
86
93
  export interface RemoteWebPairingVerificationResponse {
87
94
  status: "approved";
88
95
  verificationUri: string;
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mycadet/shared",
3
- "version": "0.13.0-dev.202611171101.13836af",
3
+ "version": "0.13.0-dev.202611171301.b3e2e5c",
4
4
  "private": true,
5
5
  "exports": {
6
6
  ".": "./index.ts",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mycadet/local-mode",
3
- "version": "0.13.0-dev.202611171101.13836af",
3
+ "version": "0.13.0-dev.202611171301.b3e2e5c",
4
4
  "private": true,
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mycadet/service-contracts",
3
- "version": "0.13.0-dev.202611171101.13836af",
3
+ "version": "0.13.0-dev.202611171301.b3e2e5c",
4
4
  "private": true,
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -83,6 +83,13 @@ export interface RemoteWebPairingVerificationRequest {
83
83
  * The gateway maps the `expired` / `invalid` outcomes to error responses, so
84
84
  * the only success shape on the wire is the approved variant.
85
85
  */
86
+ export const RemoteWebPairingVerificationResponseSchema = z.object({
87
+ status: z.literal("approved"),
88
+ verificationUri: z.string(),
89
+ /** ISO-8601 instant the approved challenge expires. */
90
+ expiresAt: z.string(),
91
+ }) satisfies z.ZodType<RemoteWebPairingVerificationResponse>;
92
+
86
93
  export interface RemoteWebPairingVerificationResponse {
87
94
  status: "approved";
88
95
  verificationUri: string;
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mycadet/shared",
3
- "version": "0.13.0-dev.202611171101.13836af",
3
+ "version": "0.13.0-dev.202611171301.b3e2e5c",
4
4
  "private": true,
5
5
  "exports": {
6
6
  ".": "./index.ts",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mycadet/cli",
3
- "version": "0.13.0-dev.202611171101.13836af",
3
+ "version": "0.13.0-dev.202611171301.b3e2e5c",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/vargasjr-dev/mycadet-temp.git"
@@ -17,7 +17,7 @@
17
17
  "scripts": {
18
18
  "format": "prettier --write .",
19
19
  "format:check": "prettier --check .",
20
- "lint": "eslint --max-warnings 183",
20
+ "lint": "eslint --max-warnings 111",
21
21
  "lint:unused": "knip --include files,dependencies,unlisted",
22
22
  "compile:check": "bun build --compile src/index.ts --outfile /dev/null",
23
23
  "test": "bun run scripts/run-tests.ts",
@@ -9,6 +9,8 @@
9
9
  * would otherwise hang waiting for an interactive user.
10
10
  */
11
11
 
12
+ import { z } from "zod";
13
+
12
14
  import { extractFlag } from "../lib/arg-utils.js";
13
15
  import { AssistantClient } from "../lib/assistant-client.js";
14
16
 
@@ -131,7 +133,9 @@ export const confirm = Object.assign(
131
133
  process.exit(1);
132
134
  }
133
135
 
134
- const result = (await response.json()) as { accepted: boolean };
136
+ const result = z
137
+ .object({ accepted: z.boolean() })
138
+ .parse(await response.json());
135
139
 
136
140
  if (jsonOutput) {
137
141
  console.log(JSON.stringify(result, null, 2));
@@ -177,7 +177,7 @@ async function listDevices(
177
177
  } catch (err) {
178
178
  console.error(
179
179
  `Error: could not reach the gateway for '${displayName}' at ${base}: ${
180
- (err as Error).message
180
+ err instanceof Error ? err.message : String(err)
181
181
  }`,
182
182
  );
183
183
  process.exit(1);
@@ -307,7 +307,7 @@ async function revokeDevice(
307
307
  } catch (err) {
308
308
  console.error(
309
309
  `Error: could not reach the gateway for '${displayName}' at ${base}: ${
310
- (err as Error).message
310
+ err instanceof Error ? err.message : String(err)
311
311
  }`,
312
312
  );
313
313
  process.exit(1);
@@ -22,7 +22,7 @@ import {
22
22
  shouldPromptForHatchProvider,
23
23
  } from "../lib/provider-secrets.js";
24
24
  import { green } from "../lib/color";
25
- import { HATCH_ART, HATCHED_EMOJI, VALID_REMOTE_HOSTS } from "../lib/constants";
25
+ import { HATCH_ART, HATCHED_EMOJI, VALID_REMOTE_HOSTS, isRemoteHost } from "../lib/constants";
26
26
  import type { RemoteHost } from "../lib/constants";
27
27
  import { logHatchNextSteps } from "../lib/hatch-next-steps.js";
28
28
  import { printInstanceDetails } from "../lib/instance-details.js";
@@ -117,13 +117,13 @@ function parseArgs(): HatchArgs {
117
117
  i++;
118
118
  } else if (arg === "--remote") {
119
119
  const next = args[i + 1];
120
- if (!next || !VALID_REMOTE_HOSTS.includes(next as RemoteHost)) {
120
+ if (!next || !isRemoteHost(next)) {
121
121
  console.error(
122
122
  `Error: --remote requires one of: ${VALID_REMOTE_HOSTS.join(", ")}`,
123
123
  );
124
124
  process.exit(1);
125
125
  }
126
- remote = next as RemoteHost;
126
+ remote = next;
127
127
  i++;
128
128
  } else if (arg === "--config") {
129
129
  const next = args[i + 1];
@@ -130,7 +130,8 @@ export const machine = Object.assign(
130
130
  `Machine policy for '${entry.assistantId}' (${entry.cloud} assistant):`,
131
131
  );
132
132
  for (const p of paths) {
133
- const leaf = p.split(".")[1] as "max" | "high";
133
+ const leaf = p.split(".")[1];
134
+ if (leaf !== "max" && leaf !== "high") continue;
134
135
  console.log(storedLine(p, result.machine?.memory?.[leaf]));
135
136
  }
136
137
  return;
@@ -8,6 +8,8 @@
8
8
 
9
9
  import { readFileSync } from "node:fs";
10
10
 
11
+ import { z } from "zod";
12
+
11
13
  import { extractFlag } from "../lib/arg-utils.js";
12
14
  import { AssistantClient } from "../lib/assistant-client.js";
13
15
 
@@ -184,10 +186,9 @@ export const message = Object.assign(
184
186
  process.exit(1);
185
187
  }
186
188
 
187
- const result = (await response.json()) as {
188
- accepted: boolean;
189
- messageId: string;
190
- };
189
+ const result = z
190
+ .object({ accepted: z.boolean(), messageId: z.string() })
191
+ .parse(await response.json());
191
192
 
192
193
  if (jsonOutput) {
193
194
  console.log(JSON.stringify(result, null, 2));
@@ -26,9 +26,9 @@ import {
26
26
 
27
27
  import {
28
28
  buildRemoteWebPairingUrl,
29
+ RemoteWebPairingVerificationResponseSchema,
29
30
  type RemoteWebPairingChallengeResponse,
30
31
  type RemoteWebPairingVerificationRequest,
31
- type RemoteWebPairingVerificationResponse,
32
32
  } from "@mycadet/service-contracts/remote-web-pairing";
33
33
 
34
34
  import {
@@ -357,8 +357,9 @@ export const pair = Object.assign(
357
357
  );
358
358
  process.exit(1);
359
359
  }
360
- const result =
361
- (await response.json()) as RemoteWebPairingVerificationResponse;
360
+ const result = RemoteWebPairingVerificationResponseSchema.parse(
361
+ await response.json(),
362
+ );
362
363
  if (jsonOutput) {
363
364
  console.log(JSON.stringify(result, null, 2));
364
365
  return;
@@ -2,11 +2,7 @@ import { getGatewayUrl } from "@mycadet/local-mode/contract";
2
2
  import { getAppServerPaths } from "../lib/servers/common.js";
3
3
  import { join } from "path";
4
4
 
5
- import {
6
- TUNNEL_PROVIDERS,
7
- type TunnelProviderName,
8
- } from "@mycadet/service-contracts/ingress";
9
- import { DEFAULT_TUNNEL_PROVIDER } from "../lib/tunnel.js";
5
+ import { DEFAULT_TUNNEL_PROVIDER, isTunnelProvider } from "../lib/tunnel.js";
10
6
  import { loadNgrokDomain } from "../lib/tunnels/ngrok.js";
11
7
  import {
12
8
  checkHealth,
@@ -368,10 +364,7 @@ export async function printRootProcessDetail(
368
364
  }
369
365
 
370
366
  const provider: string | null = tunnel?.provider ?? null;
371
- if (
372
- name === "tunnel" ||
373
- TUNNEL_PROVIDERS.includes(name as TunnelProviderName)
374
- ) {
367
+ if (name === "tunnel" || isTunnelProvider(name)) {
375
368
  console.log(
376
369
  name === "tunnel" ? "Tunnel agent:" : `Tunnel agent (${name}):`,
377
370
  );
@@ -10,6 +10,7 @@ import {
10
10
  DEFAULT_TUNNEL_PROVIDER,
11
11
  PROVIDER_META,
12
12
  clearReservedDomain,
13
+ isTunnelProvider,
13
14
  providerSupportsReservedDomain,
14
15
  runProviderTunnel,
15
16
  stopTunnelProcess,
@@ -134,7 +135,7 @@ function parseArgs(): TunnelArgs {
134
135
  );
135
136
  process.exit(1);
136
137
  }
137
- if (!TUNNEL_PROVIDERS.includes(next as TunnelProviderName)) {
138
+ if (!isTunnelProvider(next)) {
138
139
  console.error(
139
140
  `Error: unknown tunnel provider '${next}'. Valid providers: ${TUNNEL_PROVIDERS.join(", ")}.`,
140
141
  );
@@ -143,7 +144,7 @@ function parseArgs(): TunnelArgs {
143
144
  );
144
145
  process.exit(1);
145
146
  }
146
- provider = next as TunnelProviderName;
147
+ provider = next;
147
148
  i++;
148
149
  } else if (arg === "--domain") {
149
150
  const next = args[i + 1];
@@ -23,7 +23,7 @@ import {
23
23
  import {
24
24
  emitCliError,
25
25
  categorizeUpgradeError,
26
- type CliErrorCategory,
26
+ isCliErrorCategory,
27
27
  } from "../lib/cli-error.js";
28
28
  import { parseAssistantTargetArg } from "../lib/assistant-target-args.js";
29
29
 
@@ -209,7 +209,9 @@ function reportUpgradeFailure(result: {
209
209
  const msg = `Error: Upgrade failed: ${result.error ?? "unknown error"}`;
210
210
  console.error(`\n❌ ${msg}`);
211
211
  emitCliError(
212
- (result.code as CliErrorCategory) ?? categorizeUpgradeError(result.error),
212
+ isCliErrorCategory(result.code)
213
+ ? result.code
214
+ : categorizeUpgradeError(result.error),
213
215
  msg,
214
216
  );
215
217
  process.exit(1);
@@ -7,6 +7,7 @@ import {
7
7
  type ReactElement,
8
8
  } from "react";
9
9
  import { Box, render as inkRender, Text, useInput, useStdout } from "ink";
10
+ import { z } from "zod";
10
11
 
11
12
  import { checkHealth, getAssistantDisplayName } from "@mycadet/local-mode";
12
13
  import { HATCH_ART, HATCHED_EMOJI } from "../lib/constants";
@@ -165,9 +166,13 @@ interface HealthResponse {
165
166
  /** Extract human-readable message from a daemon JSON error response. */
166
167
  function friendlyErrorMessage(status: number, body: string): string {
167
168
  try {
168
- const parsed = JSON.parse(body) as { error?: { message?: string } };
169
- if (parsed?.error?.message) {
170
- return parsed.error.message;
169
+ const parsed = z
170
+ .object({ error: z.object({ message: z.string() }).partial() })
171
+ .partial()
172
+ .safeParse(JSON.parse(body));
173
+ const message = parsed.success ? parsed.data.error?.message : undefined;
174
+ if (message) {
175
+ return message;
171
176
  }
172
177
  } catch {
173
178
  // Not JSON — fall through
@@ -233,7 +238,9 @@ async function runtimeRequest<T>(
233
238
  headers: {
234
239
  "Content-Type": "application/json",
235
240
  ...auth,
236
- ...(init?.headers as Record<string, string> | undefined),
241
+ ...(init?.headers
242
+ ? Object.fromEntries(new Headers(init?.headers).entries())
243
+ : undefined),
237
244
  },
238
245
  });
239
246
 
@@ -335,17 +342,17 @@ async function setRuntimeConfigValue(
335
342
  }
336
343
 
337
344
  /** Resolve a dotted config path within the fetched config object. */
345
+ function isRecord(value: unknown): value is Record<string, unknown> {
346
+ return typeof value === "object" && value !== null;
347
+ }
348
+
338
349
  function resolveConfigPath(config: unknown, dottedPath: string): unknown {
339
350
  let current: unknown = config;
340
351
  for (const segment of dottedPath.split(".")) {
341
- if (
342
- current === null ||
343
- typeof current !== "object" ||
344
- !(segment in (current as Record<string, unknown>))
345
- ) {
352
+ if (!isRecord(current) || !(segment in current)) {
346
353
  return undefined;
347
354
  }
348
- current = (current as Record<string, unknown>)[segment];
355
+ current = current[segment];
349
356
  }
350
357
  return current;
351
358
  }
@@ -1298,8 +1305,9 @@ function ChatApp({
1298
1305
 
1299
1306
  const visibleWindow = useMemo(() => {
1300
1307
  if (feed.length === 0) {
1308
+ const items: FeedItem[] = [];
1301
1309
  return {
1302
- items: [] as FeedItem[],
1310
+ items,
1303
1311
  startIndex: 0,
1304
1312
  endIndex: 0,
1305
1313
  hiddenAbove: 0,
@@ -2356,10 +2364,7 @@ function ChatApp({
2356
2364
  }
2357
2365
  if (item.type === "status") {
2358
2366
  return (
2359
- <Text
2360
- key={feedIndex}
2361
- color={item.color as "green" | "yellow" | "red" | undefined}
2362
- >
2367
+ <Text key={feedIndex} color={item.color}>
2363
2368
  {item.text}
2364
2369
  </Text>
2365
2370
  );
package/src/index.ts CHANGED
@@ -86,6 +86,10 @@ const commands = {
86
86
 
87
87
  type CommandName = keyof typeof commands;
88
88
 
89
+ function isCommandName(name: string): name is CommandName {
90
+ return name in commands;
91
+ }
92
+
89
93
  function printHelp(): void {
90
94
  console.log("Usage: cadet <command> [options]");
91
95
  console.log("");
@@ -238,7 +242,7 @@ async function main() {
238
242
  process.exit(0);
239
243
  }
240
244
 
241
- const command = commands[commandName as CommandName];
245
+ const command = isCommandName(commandName) ? commands[commandName] : undefined;
242
246
 
243
247
  if (!command) {
244
248
  console.error(red(`Unknown command: ${commandName}`));
@@ -8,21 +8,31 @@
8
8
  */
9
9
 
10
10
  /** Known error categories emitted by CLI commands. */
11
- export type CliErrorCategory =
12
- | "CLI_UPDATE_FAILED"
13
- | "DOCKER_NOT_RUNNING"
14
- | "IMAGE_PULL_FAILED"
15
- | "MISSING_VERSION"
16
- | "READINESS_TIMEOUT"
17
- | "ROLLBACK_FAILED"
18
- | "ROLLBACK_NO_STATE"
19
- | "VERSION_DIRECTION"
20
- | "AUTH_FAILED"
21
- | "NETWORK_ERROR"
22
- | "UNSUPPORTED_TOPOLOGY"
23
- | "ASSISTANT_NOT_FOUND"
24
- | "CLOUD_API_ERROR"
25
- | "UNKNOWN";
11
+ export const CLI_ERROR_CATEGORIES = [
12
+ "CLI_UPDATE_FAILED",
13
+ "DOCKER_NOT_RUNNING",
14
+ "IMAGE_PULL_FAILED",
15
+ "MISSING_VERSION",
16
+ "READINESS_TIMEOUT",
17
+ "ROLLBACK_FAILED",
18
+ "ROLLBACK_NO_STATE",
19
+ "VERSION_DIRECTION",
20
+ "AUTH_FAILED",
21
+ "NETWORK_ERROR",
22
+ "UNSUPPORTED_TOPOLOGY",
23
+ "ASSISTANT_NOT_FOUND",
24
+ "CLOUD_API_ERROR",
25
+ "UNKNOWN",
26
+ ] as const;
27
+
28
+ export type CliErrorCategory = (typeof CLI_ERROR_CATEGORIES)[number];
29
+
30
+ /** Whether `value` is a category CLI commands may emit. */
31
+ export function isCliErrorCategory(
32
+ value: string | undefined,
33
+ ): value is CliErrorCategory {
34
+ return CLI_ERROR_CATEGORIES.some((category) => category === value);
35
+ }
26
36
 
27
37
  interface CliErrorPayload {
28
38
  error: CliErrorCategory;
@@ -11,7 +11,6 @@ import { fetchCurrentUser, readCloudToken } from "@mycadet/local-mode";
11
11
  import { getCloudBaseUrl } from "@mycadet/shared";
12
12
  import { randomBytes } from "crypto";
13
13
  import { createServer } from "http";
14
- import type { AddressInfo } from "net";
15
14
 
16
15
  import { openBrowser } from "./open-browser.js";
17
16
  import { saveCloudToken } from "./cloud-client.js";
@@ -231,7 +230,7 @@ export function startLoopbackListener(
231
230
  rejectListener(new Error("Failed to start local server."));
232
231
  return;
233
232
  }
234
- const { port } = addr as AddressInfo;
233
+ const { port } = addr;
235
234
  resolveListener({
236
235
  redirectUri: `http://127.0.0.1:${port}${CALLBACK_PATH}`,
237
236
  waitForCode,
@@ -23,6 +23,11 @@ export const VALID_REMOTE_HOSTS = [
23
23
  "baseten",
24
24
  ] as const;
25
25
  export type RemoteHost = (typeof VALID_REMOTE_HOSTS)[number];
26
+
27
+ /** Whether `value` names a remote host the CLI can target. */
28
+ export function isRemoteHost(value: string): value is RemoteHost {
29
+ return VALID_REMOTE_HOSTS.some((host) => host === value);
30
+ }
26
31
  const ANSI = {
27
32
  reset: "\x1b[0m",
28
33
  bold: "\x1b[1m",
@@ -14,6 +14,8 @@
14
14
  * leniently, so a newer daemon adding fields never breaks an older CLI.
15
15
  */
16
16
 
17
+ import { z } from "zod";
18
+
17
19
  /**
18
20
  * Capture format, declared on the `start` frame.
19
21
  *
@@ -187,7 +189,7 @@ export function parseServerFrame(payload: string): LiveVoiceServerFrame {
187
189
  if (typeof value !== "object" || value === null) {
188
190
  return { type: "malformed", raw: payload };
189
191
  }
190
- const frameType = (value as { type?: unknown }).type;
192
+ const frameType = z.object({ type: z.unknown() }).partial().catch({}).parse(value).type;
191
193
  if (typeof frameType !== "string") {
192
194
  return { type: "malformed", raw: payload };
193
195
  }
@@ -30,6 +30,7 @@
30
30
 
31
31
  import { tunnelHostForCloudHost } from "@mycadet/service-contracts/ingress";
32
32
  import { cloudAuthHeaders } from "@mycadet/local-mode";
33
+ import { z } from "zod";
33
34
 
34
35
  /** Production tunnel, when the cloud host implies nothing more specific. */
35
36
  const DEFAULT_TUNNEL_HOST = "tunnel.mycadet.ai";
@@ -116,10 +117,10 @@ export function buildTunnelLiveVoiceUrl(args: {
116
117
  return url.toString();
117
118
  }
118
119
 
119
- interface LiveVoiceTokenResponse {
120
- token?: unknown;
121
- expiresAt?: unknown;
122
- }
120
+ const LiveVoiceTokenResponseSchema = z.object({
121
+ token: z.string().optional(),
122
+ expiresAt: z.unknown(),
123
+ });
123
124
 
124
125
  /**
125
126
  * Mint a single-use tunnel WS token for one assistant.
@@ -170,10 +171,10 @@ export async function mintTunnelWsToken(args: {
170
171
  );
171
172
  }
172
173
 
173
- const body = (await response.json().catch(() => ({}))) as
174
- | LiveVoiceTokenResponse
175
- | undefined;
176
- const token = typeof body?.token === "string" ? body.token.trim() : "";
174
+ const body = LiveVoiceTokenResponseSchema.safeParse(
175
+ await response.json().catch(() => ({})),
176
+ );
177
+ const token = body.success ? (body.data.token?.trim() ?? "") : "";
177
178
  if (!token) {
178
179
  throw new TunnelWsTokenError(
179
180
  response.status,
package/src/lib/pair.ts CHANGED
@@ -10,6 +10,7 @@
10
10
 
11
11
  import { resolveEnvironmentName } from "@mycadet/local-mode";
12
12
  import { REMOTE_WEB_PAIRING_CODE_TTL_MS } from "@mycadet/service-contracts/remote-web-pairing";
13
+ import { z } from "zod";
13
14
 
14
15
  const CODE_TTL_MINUTES = Math.round(REMOTE_WEB_PAIRING_CODE_TTL_MS / 60_000);
15
16
 
@@ -18,13 +19,19 @@ const CODE_TTL_MINUTES = Math.round(REMOTE_WEB_PAIRING_CODE_TTL_MS / 60_000);
18
19
  * (`{"error":{"code":...,"message":...}}`). Returns null when the body is not
19
20
  * JSON or carries no string code.
20
21
  */
22
+ const GatewayErrorEnvelopeSchema = z
23
+ .object({ error: z.object({ code: z.string() }).partial() })
24
+ .partial();
25
+
21
26
  export function parseGatewayErrorCode(body: string): string | null {
27
+ let raw: unknown;
22
28
  try {
23
- const parsed = JSON.parse(body) as { error?: { code?: unknown } };
24
- return typeof parsed.error?.code === "string" ? parsed.error.code : null;
29
+ raw = JSON.parse(body);
25
30
  } catch {
26
31
  return null;
27
32
  }
33
+ const parsed = GatewayErrorEnvelopeSchema.safeParse(raw);
34
+ return parsed.success ? (parsed.data.error?.code ?? null) : null;
28
35
  }
29
36
 
30
37
  /**
package/src/lib/tunnel.ts CHANGED
@@ -120,6 +120,11 @@ const providers: Record<TunnelProviderName, TunnelProvider> = {
120
120
  };
121
121
  const providerNameSchema = z.enum(TUNNEL_PROVIDERS);
122
122
 
123
+ /** Whether `value` names a tunnel provider the CLI can drive. */
124
+ export function isTunnelProvider(value: string): value is TunnelProviderName {
125
+ return providerNameSchema.safeParse(value).success;
126
+ }
127
+
123
128
  /**
124
129
  * A tunnelable assistant plus the gateway port and workspace the app server fronts.
125
130
  */
@@ -10,6 +10,8 @@ import type {
10
10
  import { spawnSync } from "node:child_process";
11
11
  import { win32 } from "node:path";
12
12
 
13
+ import { z } from "zod";
14
+
13
15
  import { GATEWAY_PORT } from "../constants.js";
14
16
  import { cliCommand } from "@mycadet/local-mode";
15
17
  import { ensureBinaryInstalled } from "../ensure-binary.js";
@@ -150,11 +152,6 @@ function realTailscaleDeps(): TailscaleDeps {
150
152
 
151
153
  // ── Status parsing ──────────────────────────────────────────────────────────
152
154
 
153
- interface TailscaleStatus {
154
- BackendState?: string;
155
- Self?: { DNSName?: string; Online?: boolean };
156
- }
157
-
158
155
  /** Trim the trailing dot tailscale appends to MagicDNS names. */
159
156
  export function normalizeDnsName(dnsName: string): string {
160
157
  return dnsName.replace(/\.$/, "");
@@ -165,10 +162,19 @@ export function normalizeDnsName(dnsName: string): string {
165
162
  * (without trailing dot) this machine serves at. Throws a clear error when the
166
163
  * daemon is logged out or otherwise not ready to serve.
167
164
  */
165
+ const TailscaleStatusSchema = z.looseObject({
166
+ BackendState: z.string().optional(),
167
+ Self: z
168
+ .looseObject({ DNSName: z.string().optional(), Online: z.boolean().optional() })
169
+ .optional(),
170
+ });
171
+
172
+ type TailscaleStatus = z.infer<typeof TailscaleStatusSchema>;
173
+
168
174
  export function resolveServeHostname(statusJson: string): string {
169
175
  let status: TailscaleStatus;
170
176
  try {
171
- status = JSON.parse(statusJson) as TailscaleStatus;
177
+ status = TailscaleStatusSchema.parse(JSON.parse(statusJson));
172
178
  } catch {
173
179
  throw new Error("Could not parse `tailscale status --json` output.");
174
180
  }