@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,9 @@
1
1
  import { z } from "zod";
2
+ import type { IncomingHttpHeaders } from "node:http";
2
3
 
3
4
  import { loopbackSafeFetch } from "./loopback-fetch";
5
+ import { getGatewayUrl } from "./lockfile-contract";
6
+ import type { LockfileAssistant } from "./lockfile-contract";
4
7
 
5
8
  export type HttpProbeEndpoint = "healthz" | "readyz";
6
9
 
@@ -144,26 +147,99 @@ export async function waitForDaemonMigrationsReady(
144
147
  }
145
148
  }
146
149
 
147
- const GatewayHealthSchema = z.object({ version: z.string().min(1).optional() });
150
+ const GatewayHealthSchema = z.object({
151
+ /** The gateway's own version stamp, when it serves one. */
152
+ version: z.string().min(1).optional(),
153
+ /**
154
+ * Whether the caller's own credentials (the browser access cookie, or a
155
+ * bearer) authenticate against the gateway. A server that does not answer
156
+ * the field (the cloud's /healthz, older gateways) gives no verdict and
157
+ * reads as `true` — the /v1 routes' own 401s stay the signal there. Only a
158
+ * gateway that answers the field can deliver the strict verdict: the
159
+ * served /v1 routes can respond 200 unauthenticated (loopback trust).
160
+ */
161
+ authenticated: z.boolean().default(true),
162
+ });
163
+
164
+ export type GatewayHealth = z.infer<typeof GatewayHealthSchema>;
165
+
166
+ /** The caller's own headers, in either mount spelling: a fetch Request's
167
+ * Headers, or the connect record's IncomingHttpHeaders. */
168
+ type GatewayHealthHeaders = Headers | IncomingHttpHeaders;
148
169
 
149
170
  /**
150
- * Best-effort fetch of the running service group version from the gateway
151
- * `/healthz` endpoint. Returns `undefined` when the endpoint is
152
- * unreachable or does not include a version field.
171
+ * Read a gateway's `/healthz` by URL and return its identity AND the
172
+ * caller's own auth verdict in one round-trip: the version it serves, and
173
+ * whether the request's credentials (the browser access cookie on a
174
+ * same-origin request) authenticate. Best-effort — an unreachable endpoint,
175
+ * a non-2xx, or a malformed body all read as "no version, no verdict"
176
+ * (`authenticated: true`), so callers on servers without the field keep
177
+ * today's behavior.
153
178
  */
154
- export async function fetchCurrentVersion(
179
+ async function readGatewayHealth(
155
180
  runtimeUrl: string,
156
- ): Promise<string | undefined> {
181
+ opts: { signal?: AbortSignal; headers?: GatewayHealthHeaders } = {},
182
+ ): Promise<GatewayHealth> {
157
183
  try {
158
- const resp = await loopbackSafeFetch(`${runtimeUrl}/healthz`, {
159
- signal: AbortSignal.timeout(5000),
184
+ const healthUrl = new URL(
185
+ "healthz",
186
+ runtimeUrl.endsWith("/") ? runtimeUrl : `${runtimeUrl}/`,
187
+ );
188
+ // The caller's headers spread under our own Accept — later entries win,
189
+ // so the caller's Accept (if any) overrides ours; the record spelling's
190
+ // array values join and its undefined values drop, exactly what a
191
+ // Headers instance would have done for them.
192
+ const callerEntries: [string, string][] = [];
193
+ if (opts.headers instanceof Headers) {
194
+ for (const entry of opts.headers) {
195
+ callerEntries.push(entry);
196
+ }
197
+ } else {
198
+ for (const [key, value] of Object.entries(opts.headers ?? {})) {
199
+ if (value !== undefined) {
200
+ callerEntries.push([
201
+ key,
202
+ Array.isArray(value) ? value.join(", ") : value,
203
+ ]);
204
+ }
205
+ }
206
+ }
207
+ const resp = await loopbackSafeFetch(healthUrl.href, {
208
+ headers: [["accept", "application/json"], ...callerEntries],
209
+ signal: opts.signal ?? AbortSignal.timeout(5000),
160
210
  });
161
211
  if (resp.ok) {
162
212
  const parsed = GatewayHealthSchema.safeParse(await resp.json());
163
- return parsed.success ? parsed.data.version : undefined;
213
+ if (parsed.success) {
214
+ return parsed.data;
215
+ }
164
216
  }
165
217
  } catch {
166
- // Best-effort
218
+ // Best-effort: no version, no verdict.
167
219
  }
168
- return undefined;
220
+ return { version: undefined, authenticated: true };
221
+ }
222
+
223
+ /**
224
+ * Read the ENTRY's gateway `/healthz` — `getGatewayUrl` resolves the
225
+ * address inside, so consumers pass the lockfile entry and never re-derive
226
+ * (or re-trim) the URL themselves.
227
+ */
228
+ export async function getGatewayHealth(
229
+ entry: LockfileAssistant,
230
+ opts: { signal?: AbortSignal; headers?: GatewayHealthHeaders } = {},
231
+ ): Promise<GatewayHealth> {
232
+ return readGatewayHealth(getGatewayUrl(entry), opts);
233
+ }
234
+
235
+ /**
236
+ * Best-effort fetch of the running service group version from the gateway
237
+ * `/healthz` endpoint. Returns `undefined` when the endpoint is unreachable
238
+ * or does not include a version field.
239
+ */
240
+ export async function fetchCurrentVersion(
241
+ runtimeUrl: string,
242
+ ): Promise<string | undefined> {
243
+ const health = await readGatewayHealth(runtimeUrl);
244
+ return health.version;
169
245
  }
@@ -5,7 +5,6 @@ import { resolveLockfilePath } from "./config";
5
5
  import type { TokenResult } from "./guardian-token";
6
6
  import {
7
7
  FLATTENED_FIRST_SEGMENTS,
8
- GATEWAY_PORT,
9
8
  getGatewayUrl,
10
9
  isCloudEntry,
11
10
  isLoopbackGatewayCloud,
@@ -1,19 +1,24 @@
1
- import { spawn } from "node:child_process";
1
+ import { execSync, spawn } from "node:child_process";
2
+ import { createHash, randomUUID } from "node:crypto";
2
3
  import fs from "node:fs";
4
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { hostname, platform } from "node:os";
3
6
  import path from "node:path";
7
+ import { dirname, join } from "node:path";
4
8
 
5
9
  import { z } from "zod";
6
10
 
7
- import {
8
- isDnsIndependentLoopbackUrl,
9
- isLoopbackPublicUrl,
10
- } from "@mycadet/service-contracts/remote-web-pairing";
11
+ import { isDnsIndependentLoopbackUrl } from "@mycadet/service-contracts/remote-web-pairing";
11
12
 
12
13
  import {
13
14
  basetenTokenPath,
14
15
  guardianTokenPath,
16
+ resolveConfigDir,
15
17
  } from "./config";
18
+ import { getGatewayUrl, type LockfileAssistant } from "./lockfile-contract";
19
+ import { loopbackSafeFetch } from "./loopback-fetch";
16
20
  import { readLockfile } from "./lockfile";
21
+ import { pairDevice } from "./operations/pair";
17
22
  import type { CliInvocation } from "./util";
18
23
  import { resolveCliInvocation } from "./cli-invocation";
19
24
 
@@ -30,7 +35,6 @@ export const GuardianTokenFileSchema = z.object({
30
35
  /** ISO date string or epoch-ms number as returned by the gateway. */
31
36
  refreshTokenExpiresAt: z.union([z.string(), z.number()]),
32
37
  refreshAfter: z.string(),
33
- isNew: z.boolean(),
34
38
  deviceId: z.string(),
35
39
  leasedAt: z.string(),
36
40
  /** Remote gateway bound to a credential imported through the pairing flow. */
@@ -412,3 +416,269 @@ function refreshToken(
412
416
  });
413
417
  });
414
418
  }
419
+
420
+ // ─── The guardian-token lease ────────────────────────────────────────────
421
+ // Pairing IS the lease: the pair operation's transport proves presence
422
+ // (host-loopback POST for local, in-container exec for docker), and the
423
+ // paired response IS the credential. Every local-topology hatch leases
424
+ // after its gateway is up so hosts can import the token instead of
425
+ // re-pairing.
426
+
427
+ const GuardianTokenFieldsSchema = z
428
+ .object({
429
+ guardianPrincipalId: z.string().optional().catch(undefined),
430
+ accessToken: z.string().optional().catch(undefined),
431
+ accessTokenExpiresAt: z
432
+ .union([z.string(), z.number()])
433
+ .optional()
434
+ .catch(undefined),
435
+ refreshToken: z.string().optional().catch(undefined),
436
+ refreshTokenExpiresAt: z
437
+ .union([z.string(), z.number()])
438
+ .optional()
439
+ .catch(undefined),
440
+ refreshAfter: z
441
+ .union([z.string(), z.number()])
442
+ .transform((v) => (typeof v === "number" ? new Date(v).toISOString() : v))
443
+ .optional()
444
+ .catch(undefined),
445
+ deviceId: z.string().optional().catch(undefined),
446
+ })
447
+ .catch({});
448
+
449
+ /** Narrow untrusted JSON to the token fields whose values have the right
450
+ * shape; fields absent or malformed come back undefined for callers to
451
+ * fall back on or reject. */
452
+ export function parseGuardianTokenFields(
453
+ value: unknown,
454
+ ): Partial<GuardianTokenData> {
455
+ return GuardianTokenFieldsSchema.parse(value);
456
+ }
457
+
458
+ const DEVICE_ID_SALT = "mycadet-host-id";
459
+
460
+ function getPersistedDeviceIdPath(): string {
461
+ return join(resolveConfigDir(), "device-id");
462
+ }
463
+
464
+ function hashWithSalt(input: string): string {
465
+ return createHash("sha256")
466
+ .update(input + DEVICE_ID_SALT)
467
+ .digest("hex");
468
+ }
469
+
470
+ function getMacOSPlatformUUID(): string | null {
471
+ try {
472
+ const output = execSync(
473
+ "ioreg -rd1 -c IOPlatformExpertDevice | awk '/IOPlatformUUID/{print $3}'",
474
+ { encoding: "utf-8", timeout: 5000, windowsHide: true },
475
+ ).trim();
476
+ const uuid = output.replace(/"/g, "");
477
+ return uuid.length > 0 ? uuid : null;
478
+ } catch {
479
+ return null;
480
+ }
481
+ }
482
+
483
+ function getLinuxMachineId(): string | null {
484
+ try {
485
+ return readFileSync("/etc/machine-id", "utf-8").trim() || null;
486
+ } catch {
487
+ return null;
488
+ }
489
+ }
490
+
491
+ function getWindowsMachineGuid(): string | null {
492
+ try {
493
+ const output = execSync(
494
+ 'reg query "HKLM\\SOFTWARE\\Microsoft\\Cryptography" /v MachineGuid',
495
+ { encoding: "utf-8", timeout: 5000, windowsHide: true },
496
+ ).trim();
497
+ const match = output.match(/MachineGuid\s+REG_SZ\s+(.+)/);
498
+ return match?.[1]?.trim() ?? null;
499
+ } catch {
500
+ return null;
501
+ }
502
+ }
503
+
504
+ export function getOrCreatePersistedDeviceId(): string {
505
+ const path = getPersistedDeviceIdPath();
506
+ try {
507
+ const existing = readFileSync(path, "utf-8").trim();
508
+ if (existing.length > 0) {
509
+ return existing;
510
+ }
511
+ } catch {
512
+ // File doesn't exist yet
513
+ }
514
+ const newId = randomUUID();
515
+ const dir = dirname(path);
516
+ if (!existsSync(dir)) {
517
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
518
+ }
519
+ writeFileSync(path, newId + "\n", { mode: 0o600 });
520
+ return newId;
521
+ }
522
+
523
+ /**
524
+ * Compute a stable device identifier matching the native client conventions.
525
+ *
526
+ * - macOS: SHA-256 of IOPlatformUUID + salt
527
+ * - Linux: SHA-256 of /etc/machine-id + salt
528
+ * - Windows: SHA-256 of HKLM MachineGuid + salt
529
+ * - Fallback: persisted random UUID in XDG config
530
+ */
531
+ export function computeDeviceId(): string {
532
+ const os = platform();
533
+
534
+ if (os === "darwin") {
535
+ const uuid = getMacOSPlatformUUID();
536
+ if (uuid) return hashWithSalt(uuid);
537
+ } else if (os === "linux") {
538
+ const machineId = getLinuxMachineId();
539
+ if (machineId) return hashWithSalt(machineId);
540
+ } else if (os === "win32") {
541
+ const guid = getWindowsMachineGuid();
542
+ if (guid) return hashWithSalt(guid);
543
+ }
544
+
545
+ return getOrCreatePersistedDeviceId();
546
+ }
547
+
548
+ function readClientHostname(): string | undefined {
549
+ try {
550
+ return hostname() || undefined;
551
+ } catch {
552
+ return undefined;
553
+ }
554
+ }
555
+
556
+ const READY_POLL_INTERVAL_MS = 500;
557
+ const READY_POLL_BUDGET_MS = 60_000;
558
+
559
+ /**
560
+ * The gateway 503s every non-probe route ({status: "starting"}) while its
561
+ * post-assistant-ready backfills run — exactly the window that burns the
562
+ * caller's lease-retry budget. Poll /readyz (body-aware: it is the probe
563
+ * the gateway docs point CLI waits at) until the gate opens before the
564
+ * first pair attempt.
565
+ */
566
+ async function waitForGatewayReady(gatewayUrl: string): Promise<void> {
567
+ const deadline = Date.now() + READY_POLL_BUDGET_MS;
568
+ while (Date.now() < deadline) {
569
+ try {
570
+ const res = await loopbackSafeFetch(`${gatewayUrl}/readyz`, {
571
+ signal: AbortSignal.timeout(3000),
572
+ });
573
+ if (res.ok) return;
574
+ // Only the documented "starting" gate is worth waiting out. Anything
575
+ // else (404, connection refused) means there is no gate here — e.g.
576
+ // test doubles that serve only the leased routes — so proceed and let
577
+ // the caller's own retry budget handle it.
578
+ if (res.status !== 503) return;
579
+ } catch {
580
+ return;
581
+ }
582
+ await new Promise((r) => setTimeout(r, READY_POLL_INTERVAL_MS));
583
+ }
584
+ }
585
+
586
+ export class GuardianLeasePermanentError extends Error {
587
+ constructor(message: string) {
588
+ super(message);
589
+ this.name = "GuardianLeasePermanentError";
590
+ }
591
+ }
592
+
593
+ function describeJsonType(value: unknown): string {
594
+ if (value === undefined) return "absent";
595
+ if (value === null) return "null";
596
+ if (Array.isArray(value)) return "array";
597
+ return typeof value;
598
+ }
599
+
600
+ /** Map /v1/pair's device-bound response onto the token-field names the
601
+ * lease parses (`token` → `accessToken`, `guardianId` → `guardianPrincipalId`). */
602
+ function mapPairResponse(raw: unknown): unknown {
603
+ const rec = z.record(z.string(), z.unknown()).catch({}).parse(raw);
604
+ return {
605
+ guardianPrincipalId: rec.guardianId,
606
+ accessToken: rec.token,
607
+ accessTokenExpiresAt: rec.expiresAt,
608
+ refreshToken: rec.refreshToken,
609
+ refreshTokenExpiresAt: rec.refreshTokenExpiresAt,
610
+ refreshAfter: rec.refreshAfter,
611
+ isNew: rec.isNew,
612
+ };
613
+ }
614
+
615
+ /**
616
+ * Pair with the assistant's gateway and persist the minted credential —
617
+ * the lease every local-topology hatch runs once its gateway is up.
618
+ * The pair operation's transport proves presence; re-pairing IS the repair.
619
+ */
620
+ export async function leaseGuardianToken(
621
+ entry: LockfileAssistant,
622
+ ): Promise<GuardianTokenData> {
623
+ // The gateway address derives from the entry's topology; assistantId and
624
+ // the bootstrap secret ride the entry too. Only the local runtimes lease —
625
+ // they are the topologies a detached hatch records a bootstrap secret for.
626
+ if (entry.cloud !== "local" && entry.cloud !== "docker") {
627
+ throw new Error(
628
+ `Guardian token leasing is not available for '${entry.cloud}' assistants.`,
629
+ );
630
+ }
631
+ const gatewayUrl = getGatewayUrl(entry);
632
+ const assistantId = entry.assistantId;
633
+ await waitForGatewayReady(gatewayUrl);
634
+
635
+ const deviceId = computeDeviceId();
636
+ const clientReportedName = readClientHostname();
637
+
638
+ const paired = await pairDevice(entry, {
639
+ platform: "cli",
640
+ deviceId,
641
+ clientReportedName,
642
+ });
643
+ if (!paired.ok) throw new Error(paired.error);
644
+
645
+ const mapped = mapPairResponse(paired.response);
646
+ const parsed = parseGuardianTokenFields(mapped);
647
+ if (
648
+ parsed.guardianPrincipalId == null ||
649
+ parsed.accessToken == null ||
650
+ parsed.accessTokenExpiresAt == null ||
651
+ parsed.refreshToken == null ||
652
+ parsed.refreshTokenExpiresAt == null ||
653
+ parsed.refreshAfter == null
654
+ ) {
655
+ const raw = z.record(z.string(), z.unknown()).catch({}).parse(mapped);
656
+ const requiredFields: (keyof typeof parsed)[] = [
657
+ "guardianPrincipalId",
658
+ "accessToken",
659
+ "accessTokenExpiresAt",
660
+ "refreshToken",
661
+ "refreshTokenExpiresAt",
662
+ "refreshAfter",
663
+ ];
664
+ const unusable = requiredFields
665
+ .filter((field) => parsed[field] == null)
666
+ .map((field) => `${field} arrived as ${describeJsonType(raw[field])}`);
667
+ throw new GuardianLeasePermanentError(
668
+ `guardian pair returned a malformed token response — ${unusable.join(", ")}`,
669
+ );
670
+ }
671
+ const tokenData: GuardianTokenData = {
672
+ guardianPrincipalId: parsed.guardianPrincipalId,
673
+ accessToken: parsed.accessToken,
674
+ accessTokenExpiresAt: parsed.accessTokenExpiresAt,
675
+ refreshToken: parsed.refreshToken,
676
+ refreshTokenExpiresAt: parsed.refreshTokenExpiresAt,
677
+ refreshAfter: parsed.refreshAfter,
678
+ deviceId,
679
+ leasedAt: new Date().toISOString(),
680
+ };
681
+
682
+ saveGuardianToken(assistantId, tokenData);
683
+ return tokenData;
684
+ }
@@ -5,7 +5,6 @@ import {
5
5
  DAEMON_STOP_TIMEOUT_MS,
6
6
  HOST_WRAPPER_LONG_HEADROOM_MS,
7
7
  } from "./lifecycle-budgets";
8
- import type { CliInvocation } from "./util";
9
8
  import { resolveCliInvocation } from "./cli-invocation";
10
9
 
11
10
  // A hatch whose daemon comes up but never becomes ready spends the readiness
@@ -91,11 +91,31 @@ export {
91
91
  } from "./cli-invocation";
92
92
  export { runHatch } from "./hatch";
93
93
  export type { HatchResult } from "./hatch";
94
- export { matchOperatorRequest } from "./operations/routes";
95
- export type { OperatorRoute, OperatorMatch } from "./operations/routes";
94
+ export {
95
+ matchOperatorRequest,
96
+ forwardOperatorRequest,
97
+ OPERATOR_ROUTES,
98
+ } from "./operations/routes";
99
+ export type {
100
+ OperatorRoute,
101
+ OperatorMatch,
102
+ OperatorRequest,
103
+ } from "./operations/routes";
96
104
  export { retireAssistant } from "./operations/retire";
97
105
  export type { RetireResult } from "./operations/retire";
98
106
  export { sleepAssistant, type SleepOptions } from "./operations/sleep";
107
+ export {
108
+ hatchAssistant,
109
+ type HatchAssistantParams,
110
+ type HatchAssistantResult,
111
+ } from "./operations/hatch";
112
+ export { generateInstanceName } from "./naming";
113
+ export { withLocalHatchLock } from "./remotes/local/hatch-lock";
114
+ export { allocateLocalPlacement } from "./remotes/local/hatch";
115
+ export {
116
+ buildHatchConfigValues,
117
+ writeInitialConfig,
118
+ } from "./remotes/local/hatch-config";
99
119
  export { wakeAssistant, type WakeResult } from "./operations/wake";
100
120
  export { wakeDocker } from "./remotes/docker/wake";
101
121
  export {
@@ -106,7 +126,55 @@ export {
106
126
  isNoSuchContainerError,
107
127
  } from "./remotes/docker/common";
108
128
  export { wakeLocal } from "./remotes/local/wake";
129
+ export { hatchLocal } from "./remotes/local/hatch";
109
130
 
131
+ export {
132
+ computeDeviceId,
133
+ getOrCreatePersistedDeviceId,
134
+ GuardianLeasePermanentError,
135
+ leaseGuardianToken,
136
+ parseGuardianTokenFields,
137
+ } from "./guardian-token";
138
+ export {
139
+ configureHatchProviderApiKey,
140
+ ensureProviderApiKey,
141
+ formatProviderName,
142
+ injectGatewayApiKey,
143
+ isSupportedLlmProvider,
144
+ promptSecret,
145
+ readGatewayApiKey,
146
+ } from "./provider-credentials";
147
+ export { LLM_PROVIDER_ENV_VAR_NAMES } from "./provider-env-vars";
148
+ export {
149
+ ensureSelfHostedLocalRegistration,
150
+ reprovisionAssistantApiKey,
151
+ resolveAssistantApiKeyForInjection,
152
+ registerLocalAssistantWithCloud,
153
+ fetchCurrentUser,
154
+ fetchAssistantIngressUrl,
155
+ injectCredentialsIntoAssistant,
156
+ readGatewayCredential,
157
+ verifyGatewayCloudCredential,
158
+ } from "./cloud-registration";
159
+ export type {
160
+ EnsureRegistrationResponse,
161
+ ReprovisionApiKeyResponse,
162
+ GatewayCredentialResult,
163
+ CredentialInjectionParams,
164
+ AssistantApiKeySource,
165
+ ResolveAssistantApiKeyArgs,
166
+ ResolvedAssistantApiKey,
167
+ PlatformUser,
168
+ } from "./cloud-registration";
169
+ export type {
170
+ EnsureProviderApiKeyOptions,
171
+ EnsureProviderApiKeyResult,
172
+ GatewayApiKeyReadResult,
173
+ HatchProviderApiKeyOptions,
174
+ LlmProviderId,
175
+ ProviderApiKeySource,
176
+ ProviderSecretFetch,
177
+ } from "./provider-credentials";
110
178
  export {
111
179
  ensureLocalRuntime,
112
180
  getLocalRuntimeInstallDir,
@@ -143,7 +211,9 @@ export {
143
211
  probeDaemonReadinessWithRetry,
144
212
  waitForDaemonMigrationsReady,
145
213
  fetchCurrentVersion,
214
+ getGatewayHealth,
146
215
  type DaemonReadiness,
216
+ type GatewayHealth,
147
217
  type HttpProbeEndpoint,
148
218
  } from "./daemon-readiness";
149
219
  export {
@@ -196,17 +266,6 @@ export {
196
266
  retireDocker,
197
267
  } from "./remotes/docker/retire";
198
268
  export { retireAppleContainer } from "./remotes/apple-container/retire";
199
- export {
200
- stopContainerAppServer,
201
- stopIngressNginx,
202
- getIngressPaths,
203
- ingressStatePath,
204
- readIngressState,
205
- getIngressPid,
206
- isIngressRunning,
207
- isPidAlive,
208
- } from "./ingress";
209
- export type { IngressPaths, IngressState } from "./ingress";
210
269
  export { exec, buildExecErrorMessage } from "./exec";
211
270
  export {
212
271
  isCadetCommandLine,
@@ -279,12 +338,7 @@ export type {
279
338
  export { runUpgrade, isValidReleaseVersion } from "./upgrade";
280
339
  export { stripVersionPrefix } from "./version";
281
340
  export type { UpgradeOptions, UpgradeResult } from "./upgrade";
282
- export { getLocalAssistantStatus } from "./status";
283
341
  export { readLockfileAssistantAvatar } from "./avatar";
284
- export type {
285
- LocalAssistantRuntimeState,
286
- LocalAssistantStatusResult,
287
- } from "./status";
288
342
  export {
289
343
  getGuardianAccessToken,
290
344
  isConfidentialRefreshUrl,
@@ -533,15 +533,15 @@ export type TunnelProcessRecord = z.infer<typeof TunnelProcessRecordSchema>;
533
533
 
534
534
  /**
535
535
  * A CLI-managed OS process recorded at the lockfile root under `app`: the
536
- * nginx ingress edge (web artifacts, `/v1` proxying, the outer shell).
537
- * Shares nothing with the tunnel record beyond the pid bookkeeping — a
538
- * tunnel serves a URL, the edge serves a port.
536
+ * app server (web artifacts, `/v1` proxying, the outer shell). Shares
537
+ * nothing with the tunnel record beyond the pid bookkeeping — a tunnel
538
+ * serves a URL, the app server serves a port.
539
539
  */
540
540
  export const AppProcessRecordSchema = z.object({
541
- /** The edge process's bookkeeping, present while the edge runs. */
541
+ /** The app server's bookkeeping, present while it runs. */
542
542
  pid: z.number().optional(),
543
543
  startedAt: z.string().optional(),
544
- /** Listening port for the nginx edge. */
544
+ /** Listening port for the app server. */
545
545
  port: z.number(),
546
546
  /**
547
547
  * The commit the edge's source-built client bundles were last built from
@@ -7,9 +7,8 @@ import {
7
7
  type Lockfile,
8
8
  type LockfileAssistant,
9
9
  } from "./lockfile-contract";
10
- import { isCloudEntry, LockfileAssistantSchema } from "./lockfile-contract";
10
+ import { LockfileAssistantSchema } from "./lockfile-contract";
11
11
  import { resolveLockfilePath } from "./config";
12
- import { z } from "zod";
13
12
 
14
13
  import { withLockfileLock } from "./lockfile-lock";
15
14
  import { stripSensitiveFields } from "./util";
@@ -0,0 +1,50 @@
1
+ import type { LockfileAssistant } from "../lockfile-contract";
2
+ import { hatchLocal } from "../remotes/local/hatch";
3
+
4
+ /**
5
+ * The hatch operation: the scoped surface's provision door. Unlike the
6
+ * other operations it takes NO entry — a hatch creates one — so the router
7
+ * switches on the REQUESTED remote, not `entry.cloud`.
8
+ *
9
+ * The local arm is the pure provision core: allocate, write the fresh
10
+ * daemon's first-boot config, wake, persist — under the machine-wide hatch
11
+ * lock. The interactive provider prompt, the guardian-token lease, the
12
+ * provider credential setup, and the cloud registration are the CLI's
13
+ * ceremony around this door (they need a TTY and cli-side credential
14
+ * machinery); non-TTY callers — the desktop's in-process hatch, the dev
15
+ * server's runHatch spawn — get the mechanics only, which is exactly what
16
+ * they always skipped anyway.
17
+ *
18
+ * The docker arm stays CLI-side for now: its image-source paths, netns
19
+ * handling, and CA-cert staging still live on cli-side seams.
20
+ */
21
+ export interface HatchAssistantParams {
22
+ remote: string;
23
+ name?: string | null;
24
+ watch?: boolean;
25
+ /** The merged hatch config (the CLI folds its provider choice in). */
26
+ configValues?: Record<string, string>;
27
+ }
28
+
29
+ export type HatchAssistantResult =
30
+ | { ok: true; assistant: LockfileAssistant }
31
+ | { ok: false; status: number; error: string; assistantId?: string };
32
+
33
+ export async function hatchAssistant(
34
+ params: HatchAssistantParams,
35
+ ): Promise<HatchAssistantResult> {
36
+ switch (params.remote) {
37
+ case "local": {
38
+ const { name, watch, configValues } = params;
39
+ const result = await hatchLocal({ name, watch, configValues });
40
+ if (!result.ok) return result;
41
+ return { ok: true, assistant: result.entry };
42
+ }
43
+ default:
44
+ return {
45
+ ok: false,
46
+ status: 400,
47
+ error: `the hatch operation does not cover '${params.remote}' yet — use \`cadet hatch --remote ${params.remote}\``,
48
+ };
49
+ }
50
+ }