@mycadet/cli 0.13.0-dev.202611012320.cea2f8a → 0.13.0-dev.202611022129.ce2988d

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 (116) hide show
  1. package/node_modules/@mycadet/assistant-api/node_modules/@mycadet/service-contracts/package.json +1 -1
  2. package/node_modules/@mycadet/avatar-manifest/package.json +1 -1
  3. package/node_modules/@mycadet/environments/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/environments/package.json +1 -1
  7. package/node_modules/@mycadet/local-mode/node_modules/@mycadet/ipc-server-utils/package.json +1 -1
  8. package/node_modules/@mycadet/local-mode/node_modules/@mycadet/service-contracts/package.json +1 -1
  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/local-mode/src/__tests__/guardian-token-refresh.test.ts +0 -1
  12. package/node_modules/@mycadet/local-mode/src/__tests__/guardian-token.test.ts +0 -1
  13. package/{src/__tests__/config-utils.test.ts → node_modules/@mycadet/local-mode/src/__tests__/hatch-config.test.ts} +1 -1
  14. package/{src/__tests__/local-hatch-lock.test.ts → node_modules/@mycadet/local-mode/src/__tests__/hatch-lock.test.ts} +1 -1
  15. package/{src/__tests__/random-name.test.ts → node_modules/@mycadet/local-mode/src/__tests__/naming.test.ts} +1 -4
  16. package/node_modules/@mycadet/local-mode/src/__tests__/operations-hatch.test.ts +60 -0
  17. package/node_modules/@mycadet/local-mode/src/__tests__/operations-resolution.test.ts +340 -0
  18. package/node_modules/@mycadet/local-mode/src/__tests__/operations-retire.test.ts +7 -7
  19. package/node_modules/@mycadet/local-mode/src/__tests__/operations-routes.test.ts +634 -0
  20. package/node_modules/@mycadet/local-mode/src/__tests__/operations-sleep.test.ts +12 -4
  21. package/node_modules/@mycadet/local-mode/src/__tests__/operations-wake.test.ts +9 -3
  22. package/node_modules/@mycadet/local-mode/src/__tests__/pair.test.ts +0 -2
  23. package/node_modules/@mycadet/local-mode/src/__tests__/remotes-docker-pair.test.ts +3 -3
  24. package/node_modules/@mycadet/local-mode/src/__tests__/remotes-local-pair.test.ts +2 -2
  25. package/node_modules/@mycadet/local-mode/src/__tests__/remotes-local-retire.test.ts +0 -11
  26. package/node_modules/@mycadet/local-mode/src/__tests__/status.test.ts +1 -129
  27. package/node_modules/@mycadet/local-mode/src/cloud-registration.ts +614 -0
  28. package/node_modules/@mycadet/local-mode/src/daemon-readiness.ts +87 -11
  29. package/node_modules/@mycadet/local-mode/src/gateway-proxy.ts +0 -1
  30. package/node_modules/@mycadet/local-mode/src/guardian-token.ts +276 -6
  31. package/node_modules/@mycadet/local-mode/src/hatch.ts +0 -1
  32. package/node_modules/@mycadet/local-mode/src/index.ts +72 -18
  33. package/node_modules/@mycadet/local-mode/src/lockfile-contract.ts +5 -5
  34. package/node_modules/@mycadet/local-mode/src/lockfile.ts +1 -2
  35. package/node_modules/@mycadet/local-mode/src/operations/hatch.ts +50 -0
  36. package/node_modules/@mycadet/local-mode/src/operations/list.ts +33 -0
  37. package/node_modules/@mycadet/local-mode/src/operations/machine.ts +1 -1
  38. package/node_modules/@mycadet/local-mode/src/operations/resolve.ts +56 -0
  39. package/node_modules/@mycadet/local-mode/src/operations/routes.ts +487 -32
  40. package/node_modules/@mycadet/local-mode/src/pair.ts +0 -5
  41. package/node_modules/@mycadet/local-mode/src/process.ts +1 -1
  42. package/node_modules/@mycadet/local-mode/src/provider-credentials.ts +495 -0
  43. package/node_modules/@mycadet/local-mode/src/provider-env-vars.ts +22 -0
  44. package/node_modules/@mycadet/local-mode/src/remotes/apple-container/retire.ts +0 -5
  45. package/node_modules/@mycadet/local-mode/src/remotes/docker/common.ts +1 -3
  46. package/node_modules/@mycadet/local-mode/src/remotes/docker/retire.ts +2 -10
  47. package/node_modules/@mycadet/local-mode/src/remotes/docker/wake.ts +0 -1
  48. package/node_modules/@mycadet/local-mode/src/remotes/local/common.ts +0 -4
  49. package/{src/lib/config-utils.ts → node_modules/@mycadet/local-mode/src/remotes/local/hatch-config.ts} +3 -3
  50. package/{src/lib/local-hatch-lock.ts → node_modules/@mycadet/local-mode/src/remotes/local/hatch-lock.ts} +6 -6
  51. package/node_modules/@mycadet/local-mode/src/remotes/local/hatch.ts +124 -0
  52. package/node_modules/@mycadet/local-mode/src/remotes/local/retire.ts +1 -6
  53. package/node_modules/@mycadet/local-mode/src/status.ts +1 -366
  54. package/node_modules/@mycadet/local-mode/src/upgrade.ts +0 -1
  55. package/node_modules/@mycadet/service-contracts/package.json +1 -1
  56. package/node_modules/@mycadet/shared/package.json +1 -1
  57. package/package.json +1 -2
  58. package/src/__tests__/app-command.test.ts +30 -45
  59. package/src/__tests__/app-server-state.test.ts +195 -0
  60. package/src/__tests__/app-tunnel-status.test.ts +1 -1
  61. package/src/__tests__/assistant-client-refresh.test.ts +0 -2
  62. package/src/__tests__/backup.test.ts +1 -1
  63. package/src/__tests__/bun.test.ts +1649 -0
  64. package/src/__tests__/client-tui-refresh.test.ts +0 -1
  65. package/src/__tests__/debug.test.ts +1 -1
  66. package/src/__tests__/devices.test.ts +1 -1
  67. package/src/__tests__/guardian-token.test.ts +5 -7
  68. package/src/__tests__/hatch-provider-secrets.test.ts +4 -2
  69. package/src/__tests__/helpers/guardian-token.ts +1 -2
  70. package/src/__tests__/host-teleport.test.ts +46 -26
  71. package/src/__tests__/llm-provider-env-var-parity.test.ts +1 -1
  72. package/src/__tests__/multi-local.test.ts +1 -1
  73. package/src/__tests__/provider-secrets.test.ts +2 -3
  74. package/src/__tests__/ps-cloud-status.test.ts +7 -7
  75. package/src/__tests__/root-restore-command.test.ts +1 -1
  76. package/src/__tests__/setup.test.ts +0 -3
  77. package/src/__tests__/tui-midsession-refresh.test.ts +0 -1
  78. package/src/__tests__/tunnel.test.ts +15 -296
  79. package/src/__tests__/upgrade-local.test.ts +4 -5
  80. package/src/__tests__/wake.test.ts +6 -544
  81. package/src/__tests__/web-dist.test.ts +39 -5
  82. package/src/commands/app.ts +25 -28
  83. package/src/commands/debug.ts +2 -1
  84. package/src/commands/devices.ts +2 -1
  85. package/src/commands/hatch.ts +70 -2
  86. package/src/commands/login.ts +3 -6
  87. package/src/commands/ps.ts +14 -12
  88. package/src/commands/setup.ts +3 -3
  89. package/src/commands/tunnel.ts +6 -9
  90. package/src/commands/upgrade.ts +1 -4
  91. package/src/commands/wake.ts +0 -11
  92. package/src/lib/api-key-check.ts +1 -1
  93. package/src/lib/assistant-config.ts +1 -43
  94. package/src/lib/cloud-client.ts +0 -404
  95. package/src/lib/cloud-login.ts +7 -110
  96. package/src/lib/guardian-token.ts +4 -297
  97. package/src/lib/host-teleport.ts +82 -51
  98. package/src/lib/provider-secrets.ts +7 -494
  99. package/src/lib/remotes/docker.ts +8 -8
  100. package/src/lib/remotes/local.ts +36 -150
  101. package/src/lib/root-backup.ts +1 -5
  102. package/src/lib/servers/bun.ts +1471 -0
  103. package/src/lib/sync-cloud-assistants.ts +2 -1
  104. package/src/lib/tunnel.ts +4 -239
  105. package/src/lib/tunnels/cloudflare.ts +6 -6
  106. package/src/lib/tunnels/ngrok.ts +3 -5
  107. package/src/lib/tunnels/tailscale.ts +1 -1
  108. package/src/lib/upgrade-lifecycle.ts +0 -35
  109. package/src/lib/web-dist.ts +47 -20
  110. package/src/shared/provider-env-vars.ts +3 -20
  111. package/node_modules/@mycadet/local-mode/src/ingress.ts +0 -229
  112. package/src/__tests__/assistant-api-key-resolution.test.ts +0 -102
  113. package/src/__tests__/nginx.test.ts +0 -2447
  114. package/src/lib/assistant-api-key-resolution.ts +0 -89
  115. package/src/lib/servers/nginx.ts +0 -1241
  116. /package/{src/lib/random-name.ts → node_modules/@mycadet/local-mode/src/naming.ts} +0 -0
@@ -1,6 +1,3 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
-
4
1
  import {
5
2
  isLoopbackPublicUrl,
6
3
  parsePairingAddress,
@@ -15,7 +12,6 @@ import {
15
12
  } from "@mycadet/service-contracts/remote-web-pairing";
16
13
  import { nanoid } from "nanoid";
17
14
 
18
- import { guardianTokenPath } from "./config";
19
15
  import { isConfidentialRefreshUrl, saveGuardianToken } from "./guardian-token";
20
16
  import { readLockfile } from "./lockfile";
21
17
 
@@ -264,7 +260,6 @@ export function pairAssistant({ credentials, name }: PairOptions): PairResult {
264
260
  refreshToken: credentials.refreshToken ?? "",
265
261
  refreshTokenExpiresAt: credentials.refreshTokenExpiresAt ?? 0,
266
262
  refreshAfter: credentials.refreshAfter ?? "",
267
- isNew: false,
268
263
  deviceId: credentials.deviceId ?? "",
269
264
  leasedAt: new Date(now).toISOString(),
270
265
  pairedGatewayUrl: credentials.gatewayUrl,
@@ -11,7 +11,7 @@ import {
11
11
 
12
12
  /**
13
13
  * Process inspection and stopping for PID-tracked local services (daemon,
14
- * gateway, credential-executor, file watcher) and the ingress edge.
14
+ * gateway, credential-executor, file watcher) and the app server.
15
15
  *
16
16
  * Lives in `@mycadet/local-mode` because the lifecycle OPERATIONS stop these
17
17
  * processes in-process now (the hosts no longer spawn the CLI for them), and
@@ -0,0 +1,495 @@
1
+ /**
2
+ * The provider API-key setup machinery: the gateway credential-store API
3
+ * (/v1/secrets), the provider vocabulary (env vars + display labels), and
4
+ * the ensure/configure flow every hatch and `cadet setup` runs. The
5
+ * interactive PROMPT CHOICE machinery (provider menus, config-vocab
6
+ * resolution) stays in the CLI — this module is what runs once a provider
7
+ * is chosen.
8
+ */
9
+ import { LLM_PROVIDER_ENV_VAR_NAMES as LLM_PROVIDER_ENV_VAR_NAMES } from "./provider-env-vars";
10
+
11
+ export type LlmProviderId = keyof typeof LLM_PROVIDER_ENV_VAR_NAMES;
12
+
13
+ export type ProviderApiKeySource = "env" | "prompt";
14
+ export type ProviderSecretFetch = (
15
+ input: Parameters<typeof fetch>[0],
16
+ init?: Parameters<typeof fetch>[1],
17
+ ) => ReturnType<typeof fetch>;
18
+
19
+ export type EnsureProviderApiKeyResult =
20
+ | {
21
+ status: "already_configured";
22
+ provider: LlmProviderId;
23
+ }
24
+ | {
25
+ status: "configured";
26
+ provider: LlmProviderId;
27
+ source: ProviderApiKeySource;
28
+ }
29
+ | {
30
+ status: "missing";
31
+ provider: LlmProviderId;
32
+ message: string;
33
+ }
34
+ | {
35
+ status: "failed";
36
+ provider: LlmProviderId;
37
+ message: string;
38
+ }
39
+ | {
40
+ status: "skipped";
41
+ message: string;
42
+ };
43
+
44
+ export interface EnsureProviderApiKeyOptions {
45
+ gatewayUrl: string;
46
+ provider: string | null;
47
+ bearerToken?: string;
48
+ env?: NodeJS.ProcessEnv;
49
+ fetchImpl?: ProviderSecretFetch;
50
+ prompt?: (prompt: string) => Promise<string>;
51
+ stdinIsTTY?: boolean;
52
+ input?: NodeJS.ReadStream;
53
+ output?: NodeJS.WriteStream;
54
+ /** Key collected before startup, right after the provider choice. */
55
+ precollectedKey?: string;
56
+ }
57
+
58
+ export interface GatewayApiKeyReadResult {
59
+ found: boolean;
60
+ unreachable: boolean;
61
+ }
62
+
63
+ export interface HatchProviderApiKeyOptions {
64
+ gatewayUrl: string;
65
+ provider: LlmProviderId | null;
66
+ bearerToken?: string;
67
+ env?: NodeJS.ProcessEnv;
68
+ fetchImpl?: ProviderSecretFetch;
69
+ log?: (message: string) => void;
70
+ prompt?: (prompt: string) => Promise<string>;
71
+ stdinIsTTY?: boolean;
72
+ input?: NodeJS.ReadStream;
73
+ output?: NodeJS.WriteStream;
74
+ /** Key collected before startup, right after the provider choice. */
75
+ precollectedKey?: string;
76
+ }
77
+
78
+ const PROVIDER_LABELS: Record<LlmProviderId, string> = {
79
+ cadet: "Cadet Cloud",
80
+ anthropic: "Anthropic",
81
+ openai: "OpenAI",
82
+ gemini: "Gemini",
83
+ fireworks: "Fireworks",
84
+ openrouter: "OpenRouter",
85
+ "vercel-ai-gateway": "Vercel AI Gateway",
86
+ minimax: "MiniMax",
87
+ atlascloud: "Atlas Cloud",
88
+ together: "Together AI",
89
+ litellm: "LiteLLM",
90
+ opencode: "OpenCode",
91
+ baseten: "Baseten",
92
+ ionet: "IO Intelligence",
93
+ poolside: "Poolside",
94
+ typesafe: "TypeSafe",
95
+ };
96
+
97
+ export function formatProviderName(provider: LlmProviderId): string {
98
+ return PROVIDER_LABELS[provider];
99
+ }
100
+
101
+ export function isSupportedLlmProvider(
102
+ provider: string,
103
+ ): provider is LlmProviderId {
104
+ return Object.hasOwn(LLM_PROVIDER_ENV_VAR_NAMES, provider);
105
+ }
106
+
107
+ function gatewayUrlWithPath(gatewayUrl: string, path: string): string {
108
+ return `${gatewayUrl.replace(/\/+$/, "")}${path}`;
109
+ }
110
+
111
+ function secretHeaders(bearerToken?: string): Record<string, string> {
112
+ const headers: Record<string, string> = {
113
+ "Content-Type": "application/json",
114
+ Accept: "application/json",
115
+ };
116
+ if (bearerToken) {
117
+ headers.Authorization = `Bearer ${bearerToken}`;
118
+ }
119
+ return headers;
120
+ }
121
+
122
+ async function parseErrorMessage(response: Response): Promise<string> {
123
+ let text = "";
124
+ try {
125
+ text = await response.text();
126
+ } catch {
127
+ // Fall through to status text.
128
+ }
129
+
130
+ try {
131
+ const body = JSON.parse(text) as {
132
+ error?: unknown;
133
+ };
134
+ const message = extractErrorMessage(body.error);
135
+ if (message) return message;
136
+ } catch {
137
+ // Fall back to raw text below.
138
+ }
139
+
140
+ if (text.trim().length > 0) {
141
+ return text.trim();
142
+ }
143
+
144
+ return response.statusText || `HTTP ${response.status}`;
145
+ }
146
+
147
+ function extractErrorMessage(error: unknown): string | null {
148
+ if (typeof error === "string" && error.trim().length > 0) {
149
+ return error.trim();
150
+ }
151
+ if (!error || typeof error !== "object") {
152
+ return null;
153
+ }
154
+
155
+ const maybeMessage = (error as { message?: unknown }).message;
156
+ if (typeof maybeMessage === "string" && maybeMessage.trim().length > 0) {
157
+ return maybeMessage.trim();
158
+ }
159
+
160
+ return null;
161
+ }
162
+
163
+ export async function readGatewayApiKey(
164
+ gatewayUrl: string,
165
+ provider: LlmProviderId,
166
+ bearerToken?: string,
167
+ fetchImpl: ProviderSecretFetch = fetch,
168
+ ): Promise<GatewayApiKeyReadResult> {
169
+ const response = await fetchImpl(
170
+ gatewayUrlWithPath(gatewayUrl, "/v1/secrets/read"),
171
+ {
172
+ method: "POST",
173
+ headers: secretHeaders(bearerToken),
174
+ body: JSON.stringify({
175
+ type: "api_key",
176
+ name: provider,
177
+ reveal: false,
178
+ }),
179
+ signal: AbortSignal.timeout(10_000),
180
+ },
181
+ );
182
+
183
+ if (!response.ok) {
184
+ const message = await parseErrorMessage(response);
185
+ if (response.status === 404) {
186
+ throw new Error(
187
+ `Active assistant at ${gatewayUrl} does not expose /v1/secrets/read (${message}). Run \`cadet ps\` to confirm the active assistant, then select a self-hosted assistant with \`cadet use <assistant>\` or wake a current assistant before running setup.`,
188
+ );
189
+ }
190
+ throw new Error(
191
+ `Failed to check ${formatProviderName(provider)} API key: ${message}`,
192
+ );
193
+ }
194
+
195
+ const body = (await response.json()) as {
196
+ found?: unknown;
197
+ unreachable?: unknown;
198
+ };
199
+ return {
200
+ found: body.found === true,
201
+ unreachable: body.unreachable === true,
202
+ };
203
+ }
204
+
205
+ export async function injectGatewayApiKey(
206
+ gatewayUrl: string,
207
+ provider: LlmProviderId,
208
+ value: string,
209
+ bearerToken?: string,
210
+ fetchImpl: ProviderSecretFetch = fetch,
211
+ ): Promise<void> {
212
+ const response = await fetchImpl(
213
+ gatewayUrlWithPath(gatewayUrl, "/v1/secrets"),
214
+ {
215
+ method: "POST",
216
+ headers: secretHeaders(bearerToken),
217
+ body: JSON.stringify({
218
+ type: "api_key",
219
+ name: provider,
220
+ value,
221
+ }),
222
+ signal: AbortSignal.timeout(10_000),
223
+ },
224
+ );
225
+
226
+ if (!response.ok) {
227
+ const message = await parseErrorMessage(response);
228
+ throw new Error(
229
+ `Failed to store ${formatProviderName(provider)} API key: ${message}`,
230
+ );
231
+ }
232
+
233
+ const body = (await response.json().catch(() => ({}))) as {
234
+ success?: unknown;
235
+ error?: unknown;
236
+ };
237
+ if (body.success === false) {
238
+ const message =
239
+ typeof body.error === "string" && body.error.trim().length > 0
240
+ ? body.error
241
+ : "Assistant rejected the API key.";
242
+ throw new Error(message);
243
+ }
244
+ }
245
+
246
+ export async function promptSecret(
247
+ prompt: string,
248
+ streams: {
249
+ input?: NodeJS.ReadStream;
250
+ output?: NodeJS.WriteStream;
251
+ } = {},
252
+ ): Promise<string> {
253
+ const input = streams.input ?? process.stdin;
254
+ const output = streams.output ?? process.stdout;
255
+
256
+ if (!input.isTTY || typeof input.setRawMode !== "function") {
257
+ throw new Error("Hidden secret input requires an interactive terminal.");
258
+ }
259
+
260
+ const wasRaw = input.isRaw;
261
+ let rawModeEnabled = false;
262
+ try {
263
+ input.setRawMode(true);
264
+ rawModeEnabled = true;
265
+ output.write(prompt);
266
+ } catch (error) {
267
+ if (rawModeEnabled) {
268
+ input.setRawMode(wasRaw ?? false);
269
+ }
270
+ throw error;
271
+ }
272
+
273
+ return new Promise((resolve, reject) => {
274
+ input.resume();
275
+
276
+ let value = "";
277
+
278
+ const cleanup = (): void => {
279
+ input.removeListener("data", onData);
280
+ input.setRawMode(wasRaw ?? false);
281
+ input.pause();
282
+ };
283
+
284
+ const finish = (): void => {
285
+ cleanup();
286
+ output.write("\n");
287
+ resolve(value);
288
+ };
289
+
290
+ const cancel = (): void => {
291
+ cleanup();
292
+ output.write("\n");
293
+ reject(new Error("Input cancelled."));
294
+ };
295
+
296
+ const onData = (chunk: Buffer | string): void => {
297
+ const bytes = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
298
+ if (bytes[0] === 27) {
299
+ return;
300
+ }
301
+
302
+ for (const byte of bytes) {
303
+ if (byte === 3) {
304
+ cancel();
305
+ return;
306
+ }
307
+ if (byte === 10 || byte === 13) {
308
+ finish();
309
+ return;
310
+ }
311
+ if (byte === 8 || byte === 127) {
312
+ value = value.slice(0, -1);
313
+ continue;
314
+ }
315
+ if (byte >= 32 && byte <= 126) {
316
+ value += String.fromCharCode(byte);
317
+ }
318
+ }
319
+ };
320
+
321
+ input.on("data", onData);
322
+ });
323
+ }
324
+
325
+ export async function ensureProviderApiKey(
326
+ options: EnsureProviderApiKeyOptions,
327
+ ): Promise<EnsureProviderApiKeyResult> {
328
+ if (options.provider === null) {
329
+ return {
330
+ status: "skipped",
331
+ message: "Selected provider does not require an API key.",
332
+ };
333
+ }
334
+
335
+ const normalizedProvider = options.provider.trim().toLowerCase();
336
+ const providerName = isSupportedLlmProvider(normalizedProvider)
337
+ ? formatProviderName(normalizedProvider)
338
+ : options.provider;
339
+ const envVarName = LLM_PROVIDER_ENV_VAR_NAMES[normalizedProvider];
340
+
341
+ if (!envVarName) {
342
+ // Managed-connection provider (e.g. Cadet Cloud): authenticated through
343
+ // the cloud, not a user-supplied API key. Checked before the
344
+ // supported-provider guard so the keyless flow stays reachable.
345
+ return {
346
+ status: "skipped",
347
+ message: `${providerName} authenticates through the cloud connection; no API key needed.`,
348
+ };
349
+ }
350
+
351
+ if (!isSupportedLlmProvider(normalizedProvider)) {
352
+ throw new Error(
353
+ `Provider '${options.provider}' does not have a supported API-key setup flow.`,
354
+ );
355
+ }
356
+ const provider = normalizedProvider;
357
+ const fetchImpl = options.fetchImpl ?? fetch;
358
+
359
+ const existing = await readGatewayApiKey(
360
+ options.gatewayUrl,
361
+ provider,
362
+ options.bearerToken,
363
+ fetchImpl,
364
+ );
365
+ if (existing.unreachable) {
366
+ return {
367
+ status: "failed",
368
+ provider,
369
+ message:
370
+ "Assistant credential store is unavailable. Try again after the assistant finishes starting.",
371
+ };
372
+ }
373
+ if (existing.found) {
374
+ return {
375
+ status: "already_configured",
376
+ provider,
377
+ };
378
+ }
379
+
380
+ const envValue = options.env?.[envVarName]?.trim();
381
+ const precollected = options.precollectedKey?.trim();
382
+
383
+ // An empty pre-collected answer means the user already chose to skip the
384
+ // key — do not re-prompt after startup.
385
+ if (options.precollectedKey !== undefined && !precollected) {
386
+ return {
387
+ status: "missing",
388
+ provider,
389
+ message: "API key cannot be empty.",
390
+ };
391
+ }
392
+
393
+ let apiKey = precollected || envValue;
394
+ let source: ProviderApiKeySource =
395
+ precollected && precollected !== envValue ? "prompt" : "env";
396
+
397
+ if (!apiKey) {
398
+ source = "prompt";
399
+ if (options.prompt) {
400
+ apiKey = (
401
+ await options.prompt(
402
+ `Enter your ${providerName} API key (${envVarName}): `,
403
+ )
404
+ ).trim();
405
+ } else {
406
+ const stdinIsTTY = options.stdinIsTTY ?? process.stdin.isTTY;
407
+ if (!stdinIsTTY) {
408
+ return {
409
+ status: "missing",
410
+ provider,
411
+ message: `Missing ${envVarName}. Set it in the environment or run cadet setup from an interactive terminal.`,
412
+ };
413
+ }
414
+ apiKey = (
415
+ await promptSecret(
416
+ `Enter your ${providerName} API key (${envVarName}): `,
417
+ {
418
+ input: options.input,
419
+ output: options.output,
420
+ },
421
+ )
422
+ ).trim();
423
+ }
424
+ }
425
+
426
+ if (!apiKey) {
427
+ return {
428
+ status: "missing",
429
+ provider,
430
+ message: "API key cannot be empty.",
431
+ };
432
+ }
433
+
434
+ await injectGatewayApiKey(
435
+ options.gatewayUrl,
436
+ provider,
437
+ apiKey,
438
+ options.bearerToken,
439
+ fetchImpl,
440
+ );
441
+
442
+ return {
443
+ status: "configured",
444
+ provider,
445
+ source,
446
+ };
447
+ }
448
+
449
+ export async function configureHatchProviderApiKey(
450
+ options: HatchProviderApiKeyOptions,
451
+ ): Promise<void> {
452
+ const log = options.log ?? console.log;
453
+ const { provider } = options;
454
+
455
+ if (provider === null) {
456
+ log("Provider credentials not required for the selected provider.");
457
+ return;
458
+ }
459
+
460
+ try {
461
+ const result = await ensureProviderApiKey({
462
+ gatewayUrl: options.gatewayUrl,
463
+ provider,
464
+ bearerToken: options.bearerToken,
465
+ env: options.env,
466
+ fetchImpl: options.fetchImpl,
467
+ prompt: options.prompt,
468
+ stdinIsTTY: options.stdinIsTTY,
469
+ input: options.input,
470
+ output: options.output,
471
+ precollectedKey: options.precollectedKey,
472
+ });
473
+
474
+ if (
475
+ result.status === "already_configured" ||
476
+ result.status === "configured" ||
477
+ result.status === "skipped"
478
+ ) {
479
+ // Success is the expected outcome — stay quiet and let the final
480
+ // summary speak.
481
+ return;
482
+ }
483
+
484
+ log(
485
+ `⚠️ Provider credential setup skipped: ${result.message}\n` +
486
+ ` The assistant is still hatched. Run \`cadet setup --provider ${provider}\` to finish setup.`,
487
+ );
488
+ } catch (error) {
489
+ const message = error instanceof Error ? error.message : String(error);
490
+ log(
491
+ `⚠️ Provider credential setup failed: ${message}\n` +
492
+ ` The assistant is still hatched. Run \`cadet setup --provider ${provider}\` after fixing the issue.`,
493
+ );
494
+ }
495
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * LLM provider env var names, keyed by provider ID. Mirrors the assistant
3
+ * daemon's `PROVIDER_CATALOG` entries with an `envVar`; drift is caught by
4
+ * the CLI's parity tests.
5
+ */
6
+ export const LLM_PROVIDER_ENV_VAR_NAMES: Record<string, string> = {
7
+ anthropic: "ANTHROPIC_API_KEY",
8
+ openai: "OPENAI_API_KEY",
9
+ gemini: "GEMINI_API_KEY",
10
+ fireworks: "FIREWORKS_API_KEY",
11
+ openrouter: "OPENROUTER_API_KEY",
12
+ "vercel-ai-gateway": "AI_GATEWAY_API_KEY",
13
+ minimax: "MINIMAX_API_KEY",
14
+ atlascloud: "ATLASCLOUD_API_KEY",
15
+ together: "TOGETHER_API_KEY",
16
+ litellm: "LITELLM_API_KEY",
17
+ opencode: "OPENCODE_API_KEY",
18
+ baseten: "BASETEN_API_KEY",
19
+ ionet: "IONET_API_KEY",
20
+ poolside: "POOLSIDE_API_KEY",
21
+ typesafe: "TYPESAFE_API_KEY",
22
+ };
@@ -3,7 +3,6 @@ import { existsSync } from "node:fs";
3
3
 
4
4
  import { isAppleContainerEntry } from "../../lockfile-contract";
5
5
  import type { LockfileAssistant } from "../../lockfile-contract";
6
- import { stopContainerAppServer } from "../../ingress";
7
6
 
8
7
  /**
9
8
  * The apple-container topology's retire leg: send a retire command to the
@@ -30,10 +29,6 @@ export async function retireAppleContainer(
30
29
  );
31
30
  }
32
31
 
33
- // Stop the nginx edge fronting this instance's published port FIRST —
34
- // before the pod it fronts is torn down inside the container.
35
- await stopContainerAppServer(entry);
36
-
37
32
  const mgmtSocket = entry.mgmtSocket;
38
33
  if (!mgmtSocket) {
39
34
  throw new Error(
@@ -1,5 +1,4 @@
1
1
  import { join } from "node:path";
2
- import { platform } from "node:os";
3
2
 
4
3
  import { exec } from "../../exec";
5
4
 
@@ -44,7 +43,6 @@ async function waitForDockerDaemon(timeoutMs: number): Promise<boolean> {
44
43
  * Never `colima delete` — the VM disk holds every container image and volume.
45
44
  */
46
45
  export async function startColimaAndAwaitDaemon(
47
- log: (message: string) => void,
48
46
  opts: { startArgs?: string[]; settleTimeoutMs?: number } = {},
49
47
  ): Promise<void> {
50
48
  const startArgs = opts.startArgs ?? [];
@@ -100,7 +98,7 @@ export async function ensureDockerDaemonRunning(
100
98
  // Deliberately no `colima status` probe: it trusts Colima's own state file,
101
99
  // which can be stale (zombie VM) — daemon reachability is the oracle.
102
100
  console.log("🚀 Docker daemon not running. Starting Colima...");
103
- await startColimaAndAwaitDaemon(console.log, opts);
101
+ await startColimaAndAwaitDaemon(opts);
104
102
  }
105
103
 
106
104
  /** The `docker start` failure for a container that was never created. */
@@ -1,8 +1,7 @@
1
1
  import { exec } from "../../exec";
2
2
  import { stopProcess, isCadetProcess } from "../../process";
3
- import { findAssistantByName } from "../../operations/lookup";
4
3
  import { isDockerEntry } from "../../lockfile-contract";
5
- import { stopContainerAppServer } from "../../ingress";
4
+ import { findAssistantByName } from "../../operations/lookup";
6
5
 
7
6
  /**
8
7
  * The docker topology's retire leg: stop the instance's file watcher, remove
@@ -43,15 +42,8 @@ export async function removeContainer(containerName: string): Promise<void> {
43
42
  export async function retireDocker(name: string): Promise<void> {
44
43
  console.log(`\u{1F5D1}\ufe0f Stopping Docker containers for '${name}'...\n`);
45
44
 
46
- // Stop the nginx edge fronting this instance's published port FIRST —
47
- // while the gateway it fronts is still up to answer the edge's health
48
- // state, and so nothing routes to containers about to be removed.
49
- const entry = findAssistantByName(name);
50
- if (entry) {
51
- await stopContainerAppServer(entry);
52
- }
53
-
54
45
  // Stop the file watcher process if one is tracked for this instance.
46
+ const entry = findAssistantByName(name);
55
47
  const watcherPid =
56
48
  entry && isDockerEntry(entry) && typeof entry.watcherPid === "number"
57
49
  ? entry.watcherPid
@@ -1,7 +1,6 @@
1
1
  import { platform } from "node:os";
2
2
 
3
3
  import type { LockfileAssistant } from "../../lockfile-contract";
4
- import { cliCommand } from "../../environment";
5
4
  import { exec } from "../../exec";
6
5
  import { dockerResourceNames } from "./retire";
7
6
  import { ensureDockerDaemonRunning, isNoSuchContainerError } from "./common";
@@ -25,17 +25,14 @@ import {
25
25
 
26
26
  import { resolveDataDir, resolveLogDir } from "../../config";
27
27
  import { DAEMON_STOP_TIMEOUT_MS } from "../../lifecycle-budgets";
28
- import { saveLockfileAssistant } from "../../lockfile";
29
28
  import {
30
29
  GATEWAY_PORT,
31
30
  isLocalEntry,
32
31
  type AppleContainerAssistant,
33
32
  type DockerAssistant,
34
33
  type LocalAssistant,
35
- type LockfileAssistant,
36
34
  } from "../../lockfile-contract";
37
35
  import {
38
- buildDaemonUrl,
39
36
  httpHealthCheck,
40
37
  probeDaemonReadiness,
41
38
  probeDaemonReadinessWithRetry,
@@ -55,7 +52,6 @@ import {
55
52
  import { isValidReleaseVersion } from "../../upgrade";
56
53
  import { stripVersionPrefix } from "../../version";
57
54
  import { openLogFile, openRuntimeLogFile, pipeToLogFile } from "../../xdg-log";
58
- import { healConflictedLocalPorts } from "./port-heal";
59
55
  import { getDaemonPidPath, getLocalInstanceDir } from "./instance";
60
56
 
61
57
  const _require = createRequire(import.meta.url);
@@ -1,6 +1,6 @@
1
- import { writeFileSync } from "fs";
2
- import { tmpdir } from "os";
3
- import { join } from "path";
1
+ import { writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
4
 
5
5
  /**
6
6
  * Convert flat dot-notation key=value pairs into a nested config object.
@@ -1,6 +1,5 @@
1
- import { execFileSync } from "child_process";
2
- import { createHash, randomUUID } from "crypto";
3
- import { z } from "zod";
1
+ import { execFileSync } from "node:child_process";
2
+ import { createHash, randomUUID } from "node:crypto";
4
3
  import {
5
4
  closeSync,
6
5
  mkdirSync,
@@ -10,9 +9,10 @@ import {
10
9
  unlinkSync,
11
10
  utimesSync,
12
11
  writeFileSync,
13
- } from "fs";
14
- import { hostname, platform, userInfo } from "os";
15
- import { dirname, join } from "path";
12
+ } from "node:fs";
13
+ import { hostname, platform, userInfo } from "node:os";
14
+ import { z } from "zod";
15
+ import { dirname, join } from "node:path";
16
16
 
17
17
  const DEFAULT_TIMEOUT_MS = 240_000;
18
18
  const DEFAULT_RETRY_MS = 100;