@mycadet/cli 0.13.0-dev.202611131045.a556a8a → 0.13.0-dev.202611140220.fac72d3

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 (25) 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__/hatch-config.test.ts +110 -99
  12. package/node_modules/@mycadet/local-mode/src/__tests__/{hatch-local-overlay.test.ts → hatch-local-config-api.test.ts} +60 -50
  13. package/node_modules/@mycadet/local-mode/src/__tests__/local-exec-invocation.test.ts +15 -5
  14. package/node_modules/@mycadet/local-mode/src/__tests__/teleport-init.test.ts +1 -8
  15. package/node_modules/@mycadet/local-mode/src/index.ts +3 -9
  16. package/node_modules/@mycadet/local-mode/src/remotes/docker/hatch.ts +15 -48
  17. package/node_modules/@mycadet/local-mode/src/remotes/local/common.ts +82 -40
  18. package/node_modules/@mycadet/local-mode/src/remotes/local/exec.ts +8 -61
  19. package/node_modules/@mycadet/local-mode/src/remotes/local/hatch-config.ts +71 -44
  20. package/node_modules/@mycadet/local-mode/src/remotes/local/hatch.ts +15 -8
  21. package/node_modules/@mycadet/local-mode/src/remotes/local/teleport.ts +5 -13
  22. package/node_modules/@mycadet/local-mode/src/remotes/local/wake.ts +10 -38
  23. package/node_modules/@mycadet/service-contracts/package.json +1 -1
  24. package/node_modules/@mycadet/shared/package.json +1 -1
  25. package/package.json +1 -1
@@ -12,13 +12,13 @@
12
12
  */
13
13
 
14
14
  import { randomBytes } from "node:crypto";
15
- import { chmodSync, existsSync, mkdirSync, readFileSync } from "node:fs";
15
+ import { chmodSync, existsSync, mkdirSync } from "node:fs";
16
16
  import { arch, platform } from "node:os";
17
17
  import { dirname, join, resolve } from "node:path";
18
18
  import { isDevVersion } from "@mycadet/shared/version";
19
19
  import {
20
+ applyHatchConfig,
20
21
  buildHatchConfigValues,
21
- writeInitialConfig,
22
22
  } from "../local/hatch-config";
23
23
  import { generateInstanceName } from "../../naming";
24
24
  import {
@@ -34,7 +34,7 @@ import {
34
34
  import { loopbackSafeFetch } from "../../loopback-fetch";
35
35
  import { configureHatchProviderApiKey } from "../../provider-credentials";
36
36
  import { saveLockfileAssistant } from "../../lockfile";
37
- import { exec, execOutput, execWithStdin } from "../../exec";
37
+ import { exec, execOutput } from "../../exec";
38
38
  import { buildImage, serviceImageConfigs, startFileWatcher } from "./watch";
39
39
  import type {
40
40
  DockerAssistant,
@@ -838,53 +838,11 @@ export async function hatchDocker(
838
838
  "chown 1001:1001 /workspace /run/assistant-ipc /run/gateway-ipc",
839
839
  ]);
840
840
 
841
- // Stage the BYOK default-workspace-config overlay *inside* the workspace
842
- // volume so the daemon's startup loader can consume it. The loader
843
- // (`mergeDefaultWorkspaceConfig` in assistant/src/config/loader.ts) does:
844
- // 1. JSON.parse + deep-merge into the workspace's config.json.
845
- // 2. `renameSync(defaultConfigPath, <workspace>/default-config.json)`
846
- // to mark the overlay consumed so subsequent restarts skip it.
847
- //
848
- // The rename must be same-filesystem. Bind-mounting the host file into
849
- // `/tmp/...` (the pre-#32025 design) crossed filesystems and silently
850
- // failed with EXDEV, so every `docker start` re-applied the overlay.
851
- // Staging into the workspace volume keeps the rename in-place.
852
- //
853
- // Streaming the JSON via stdin (instead of bind-mounting the host file
854
- // into the staging container) sidesteps macOS Colima's virtiofs share,
855
- // which doesn't expose `/var/folders/...` (where `os.tmpdir()` resolves
856
- // on macOS) and would otherwise materialize an empty directory at the
857
- // bind-mount target.
858
- //
859
- // @deprecated stopgap. Replacement direction is one of:
860
- // 1. Post-hatch API calls (POST /v1/secrets + a small endpoint that
861
- // returns canonical inference-profile templates).
862
- // 2. Move inference-profile seeds out of workspace config and into
863
- // Assistant code, eliminating the overlay entirely.
864
- // See `cli/src/lib/config-utils.ts` JSDoc for context.
841
+ // The hatch's config values ride the assistant's public config API once
842
+ // the container is up (see the `if (ready)` block below) — no side
843
+ // channel, the same route a local hatch and the web client use.
865
844
  const hatchConfigValues = buildHatchConfigValues(configValues, provider);
866
- const hostOverlayPath = writeInitialConfig(hatchConfigValues);
867
- const stagedOverlayInContainer = "/workspace/.default-config-overlay.json";
868
845
  const extraAssistantEnv: Record<string, string> = {};
869
- if (hostOverlayPath) {
870
- await execWithStdin(
871
- "docker",
872
- [
873
- "run",
874
- "--rm",
875
- "-i",
876
- "-v",
877
- `${res.workspaceVolume}:/workspace`,
878
- "busybox",
879
- "sh",
880
- "-c",
881
- `cat > ${stagedOverlayInContainer} && chown 1001:1001 ${stagedOverlayInContainer}`,
882
- ],
883
- readFileSync(hostOverlayPath, "utf-8"),
884
- );
885
- extraAssistantEnv.CADET_DEFAULT_WORKSPACE_CONFIG_PATH =
886
- stagedOverlayInContainer;
887
- }
888
846
 
889
847
  const cesServiceToken = randomBytes(32).toString("hex");
890
848
 
@@ -974,6 +932,15 @@ export async function hatchDocker(
974
932
  }
975
933
 
976
934
  if (ready) {
935
+ // The hatch's config values go through the assistant's public config
936
+ // API — the same route the web client and a local hatch use.
937
+ await applyHatchConfig({
938
+ gatewayUrl,
939
+ bearerToken: guardianAccessToken,
940
+ configValues: hatchConfigValues,
941
+ log,
942
+ });
943
+
977
944
  const providerSetupAction = resolveDockerProviderCredentialSetupAction({
978
945
  provider,
979
946
  guardianAccessToken,
@@ -2,6 +2,7 @@ import { execFileSync, spawn, spawnSync, execSync } from "node:child_process";
2
2
  import type { ChildProcess } from "node:child_process";
3
3
  import { createHash } from "node:crypto";
4
4
  import {
5
+ chmodSync,
5
6
  existsSync,
6
7
  mkdirSync,
7
8
  readdirSync,
@@ -13,7 +14,7 @@ import {
13
14
  import { createRequire } from "node:module";
14
15
  import { Socket } from "node:net";
15
16
  import { homedir, platform, tmpdir } from "node:os";
16
- import { dirname, isAbsolute, join, resolve } from "node:path";
17
+ import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
17
18
 
18
19
  import {
19
20
  isNamedPipePath,
@@ -525,7 +526,6 @@ function resolveDaemonMainPath(assistantIndex: string): string {
525
526
  * signing key end-to-end; the CLI never touches it.
526
527
  */
527
528
  type DaemonStartOptions = {
528
- defaultWorkspaceConfigPath?: string;
529
529
  requireReady?: boolean;
530
530
  };
531
531
 
@@ -549,40 +549,93 @@ function resolveCesBootstrapSocketDir(
549
549
  }
550
550
 
551
551
  /**
552
- * Apply per-instance resource overrides and shared daemon options to an
553
- * environment object. Called from all daemon spawn paths (source, watch,
554
- * bundled binary) to eliminate drift between the three.
552
+ * The cadet binaries a local assistant resolves from source, as shim
553
+ * executables in the instance's own `bin/` dir: `assistant`, `gateway`,
554
+ * `ces`. Everything else keeps the host PATH.
555
555
  */
556
- function applyDaemonEnvOverrides(
557
- env: Record<string, string | undefined>,
558
- entry: LocalAssistant,
559
- options?: DaemonStartOptions,
560
- ): void {
561
- {
562
- env.CADET_WORKSPACE_DIR = join(getLocalInstanceDir(entry), "workspace");
563
- env.GATEWAY_SECURITY_DIR = join(
564
- getLocalInstanceDir(entry),
565
- "gateway-security",
566
- );
567
- env.CREDENTIAL_SECURITY_DIR = join(
568
- getLocalInstanceDir(entry),
569
- "ces-security",
556
+ const SHIMMED_COMMANDS = ["assistant", "gateway", "ces"] as const;
557
+
558
+ /**
559
+ * Materialize the instance's XDG `bin/` folder: one executable shim per
560
+ * cadet binary, each running that binary's source entry through bun — the
561
+ * same resolution the daemon stack uses (`localSourceCommandEntry`), baked
562
+ * at write time and refreshed by every assistant env build (hatch, wake,
563
+ * exec) so an upgrade's new runtime install is picked up. The env builder
564
+ * prepends the returned dir to PATH, which fixes compound commands, pipes,
565
+ * and shell scripts that invoke the binaries — argv rewriting only ever
566
+ * reached command[0]. A shim whose source cannot be resolved is simply not
567
+ * written and reported in `unresolved`.
568
+ */
569
+ export function ensureLocalBinShims(entry: LocalAssistant): {
570
+ dir: string;
571
+ unresolved: string[];
572
+ } {
573
+ const dir = join(getLocalInstanceDir(entry), "bin");
574
+ mkdirSync(dir, { recursive: true });
575
+ const bunPath = resolveBunExecutable();
576
+ const unresolved: string[] = [];
577
+ for (const name of SHIMMED_COMMANDS) {
578
+ const entryPath = localSourceCommandEntry(name, entry);
579
+ if (!entryPath) {
580
+ unresolved.push(name);
581
+ continue;
582
+ }
583
+ const shim = join(dir, name);
584
+ writeFileSync(
585
+ shim,
586
+ `#!/bin/sh\n# Generated by cadet — runs this binary from the local assistant's source.\nexec "${bunPath}" run "${entryPath}" "$@"\n`,
570
587
  );
571
- env.CES_DATA_DIR = join(getLocalInstanceDir(entry), "ces-data");
572
- if (entry.daemonPort !== undefined)
573
- env.RUNTIME_HTTP_PORT = String(entry.daemonPort);
574
- if (entry.port !== undefined) env.GATEWAY_PORT = String(entry.port);
575
- delete env.QDRANT_URL;
588
+ chmodSync(shim, 0o755);
576
589
  }
577
- if (options?.defaultWorkspaceConfigPath) {
578
- env.CADET_DEFAULT_WORKSPACE_CONFIG_PATH =
579
- options.defaultWorkspaceConfigPath;
590
+ return { dir, unresolved };
591
+ }
592
+
593
+ /**
594
+ * The one shared instance env for daemon starts, wakes, hatches, and exec
595
+ * legs: reads the caller's process.env, applies the instance's
596
+ * workspace/security dirs, ports, and CES/IPC sockets, prepends the
597
+ * instance's bin/ shims, and returns the spawn-ready copy. process.env is
598
+ * left untouched — the returned env must be passed to the spawn explicitly.
599
+ */
600
+ export function applyAssistantEnvironment(
601
+ entry: LocalAssistant,
602
+ ): Record<string, string | undefined> {
603
+ const env: Record<string, string | undefined> = { ...process.env };
604
+ env.RUNTIME_HTTP_PORT = env.RUNTIME_HTTP_PORT || "7821";
605
+ env.CADET_CLOUD = "local";
606
+ env.CADET_ENVIRONMENT = env.CADET_ENVIRONMENT || "local";
607
+ env.CADET_WORKSPACE_DIR = join(getLocalInstanceDir(entry), "workspace");
608
+ env.GATEWAY_SECURITY_DIR = join(
609
+ getLocalInstanceDir(entry),
610
+ "gateway-security",
611
+ );
612
+ env.CREDENTIAL_SECURITY_DIR = join(
613
+ getLocalInstanceDir(entry),
614
+ "ces-security",
615
+ );
616
+ env.CES_DATA_DIR = join(getLocalInstanceDir(entry), "ces-data");
617
+ if (entry.daemonPort !== undefined) {
618
+ env.RUNTIME_HTTP_PORT = String(entry.daemonPort);
580
619
  }
620
+ if (entry.port !== undefined) env.GATEWAY_PORT = String(entry.port);
621
+ delete env.QDRANT_URL;
581
622
  // CES and the assistant resolve the socket from CES_BOOTSTRAP_SOCKET_DIR.
582
623
  const bootstrapDir = resolveCesBootstrapSocketDir(entry, env);
583
624
  env.CES_BOOTSTRAP_SOCKET_DIR = bootstrapDir;
584
625
  mkdirSync(bootstrapDir, { recursive: true });
585
626
  applyIpcSocketDirOverride(env);
627
+ // The instance's bin/ shims first on PATH: the cadet binaries then
628
+ // resolve to the source build the daemons run (freshened on every call,
629
+ // so an upgrade's new runtime is picked up). Best-effort — a shim that
630
+ // cannot resolve just stays off the PATH.
631
+ try {
632
+ env.PATH = [ensureLocalBinShims(entry).dir, env.PATH]
633
+ .filter(Boolean)
634
+ .join(delimiter);
635
+ } catch {
636
+ // shim materialization never blocks env application
637
+ }
638
+ return env;
586
639
  }
587
640
 
588
641
  let startupLogging = true;
@@ -772,13 +825,7 @@ async function startDaemonFromSource(
772
825
  return null;
773
826
  }
774
827
 
775
- const env: Record<string, string | undefined> = {
776
- ...process.env,
777
- RUNTIME_HTTP_PORT: process.env.RUNTIME_HTTP_PORT || "7821",
778
- CADET_CLOUD: "local",
779
- CADET_ENVIRONMENT: process.env.CADET_ENVIRONMENT || "local",
780
- };
781
- applyDaemonEnvOverrides(env, entry, options);
828
+ const env = applyAssistantEnvironment(entry);
782
829
 
783
830
  // Write a sentinel PID file before spawning so concurrent hatch() calls
784
831
  // detect the in-progress spawn and wait instead of racing.
@@ -849,12 +896,7 @@ async function startDaemonWatchFromSource(
849
896
  return null;
850
897
  }
851
898
 
852
- const env: Record<string, string | undefined> = {
853
- ...process.env,
854
- RUNTIME_HTTP_PORT: process.env.RUNTIME_HTTP_PORT || "7821",
855
- CADET_ENVIRONMENT: process.env.CADET_ENVIRONMENT || "local",
856
- };
857
- applyDaemonEnvOverrides(env, entry, options);
899
+ const env = applyAssistantEnvironment(entry);
858
900
 
859
901
  // Write a sentinel PID file before spawning so concurrent hatch() calls
860
902
  // detect the in-progress spawn and wait instead of racing.
@@ -9,14 +9,17 @@
9
9
  * inside the sandbox) and the local spawn cannot drift.
10
10
  */
11
11
 
12
- import { chmodSync, existsSync, mkdirSync, writeFileSync } from "node:fs";
13
- import { delimiter, join } from "node:path";
12
+ import { existsSync } from "node:fs";
13
+ import { join } from "node:path";
14
14
  import { spawn } from "node:child_process";
15
15
 
16
16
  import type { ServiceName } from "../docker/statefulset";
17
- import type { ExecCommandOptions, ExecCommandResult } from "../../operations/exec";
17
+ import type {
18
+ ExecCommandOptions,
19
+ ExecCommandResult,
20
+ } from "../../operations/exec";
18
21
  import type { LocalAssistant } from "../../lockfile-contract";
19
- import { localSourceCommandEntry, resolveBunExecutable } from "./common";
22
+ import { applyAssistantEnvironment } from "./common";
20
23
  import { getLocalInstanceDir } from "./instance";
21
24
 
22
25
  export function localExecDirForService(
@@ -32,49 +35,6 @@ export function localExecDirForService(
32
35
  return join(instanceDir, "workspace");
33
36
  }
34
37
 
35
- /**
36
- * The cadet binaries a local assistant's exec surface resolves from source,
37
- * as shim executables in the instance's own `bin/` dir: `assistant`,
38
- * `gateway`, `ces`. Everything else keeps the host PATH.
39
- */
40
- const SHIMMED_COMMANDS = ["assistant", "gateway", "ces"] as const;
41
-
42
- /**
43
- * Materialize the instance's XDG `bin/` folder: one executable shim per
44
- * cadet binary, each running that binary's source entry through bun — the
45
- * same resolution the daemon stack uses (`localSourceCommandEntry`), baked
46
- * at write time and refreshed by every hatch/wake/exec so an upgrade's new
47
- * runtime install is picked up. Exec prepends the returned dir to the
48
- * child's PATH, which fixes compound commands, pipes, and shell scripts
49
- * that invoke the binaries — argv rewriting only ever reached command[0].
50
- * A shim whose source cannot be resolved is simply not written and reported
51
- * in `unresolved`; exec turns that into an error for the command the user
52
- * actually ran, while hatch/wake treat shims as best-effort.
53
- */
54
- export function ensureLocalBinShims(entry: LocalAssistant): {
55
- dir: string;
56
- unresolved: string[];
57
- } {
58
- const dir = join(getLocalInstanceDir(entry), "bin");
59
- mkdirSync(dir, { recursive: true });
60
- const bunPath = resolveBunExecutable();
61
- const unresolved: string[] = [];
62
- for (const name of SHIMMED_COMMANDS) {
63
- const entryPath = localSourceCommandEntry(name, entry);
64
- if (!entryPath) {
65
- unresolved.push(name);
66
- continue;
67
- }
68
- const shim = join(dir, name);
69
- writeFileSync(
70
- shim,
71
- `#!/bin/sh\n# Generated by cadet — runs this binary from the local assistant's source.\nexec "${bunPath}" run "${entryPath}" "$@"\n`,
72
- );
73
- chmodSync(shim, 0o755);
74
- }
75
- return { dir, unresolved };
76
- }
77
-
78
38
  /**
79
39
  * The local topology's exec leg: run the command on the host, in the
80
40
  * service's directory, with the instance's `bin/` shims prepended to PATH.
@@ -103,24 +63,11 @@ export async function execLocal(
103
63
  };
104
64
  }
105
65
 
106
- let shimDir: string | undefined;
107
- try {
108
- shimDir = ensureLocalBinShims(entry).dir;
109
- } catch {
110
- // shim materialization never blocks an exec
111
- }
112
-
113
66
  const child = spawn(opts.command[0], opts.command.slice(1), {
114
67
  stdio: "inherit",
115
68
  windowsHide: true,
116
69
  cwd: serviceDir,
117
- env: {
118
- ...process.env,
119
- CADET_WORKSPACE_DIR: workspaceDir,
120
- ...(shimDir
121
- ? { PATH: [shimDir, process.env.PATH].filter(Boolean).join(delimiter) }
122
- : {}),
123
- },
70
+ env: applyAssistantEnvironment(entry),
124
71
  });
125
72
  const code = await new Promise<number>((resolve) => {
126
73
  child.on("close", (c) => resolve(c ?? 1));
@@ -1,6 +1,12 @@
1
- import { writeFileSync } from "node:fs";
2
- import { tmpdir } from "node:os";
3
- import { join } from "node:path";
1
+ /**
2
+ * Hatch-time config values and their delivery to the assistant.
3
+ *
4
+ * Hatch collects flat dot-notation key=value pairs (plus the onboarding
5
+ * provider) and applies them through the assistant's public config API
6
+ * (`POST /v1/config/set`) after the assistant is up — the same API the web
7
+ * client and `assistant config set` use. There is no side channel: a remote
8
+ * hatch and a local hatch speak the same route.
9
+ */
4
10
 
5
11
  /**
6
12
  * Convert flat dot-notation key=value pairs into a nested config object.
@@ -35,21 +41,6 @@ export function buildNestedConfig(
35
41
  /**
36
42
  * Ensure hatch always provides enough initial LLM config for the assistant to
37
43
  * detect a fresh off-cloud hatch and seed BYOK profiles.
38
- *
39
- * @deprecated Part of the workspace-config overlay path — a CLI→Assistant
40
- * side channel that bypasses the Assistant's public APIs and has no
41
- * equivalent in web/desktop. Two replacement paths are on the table:
42
- *
43
- * 1. Post-hatch API calls — the CLI calls public Assistant routes after
44
- * boot (`POST /v1/secrets`, plus a small read-only endpoint that
45
- * returns the canonical inference-profile templates so the CLI can
46
- * PATCH them in). See the closed alternatives in PR #32061 and
47
- * PR #32131 for the shape this would take.
48
- * 2. Move inference-profile seeds out of workspace config and into
49
- * Assistant code, so there is nothing for the CLI to inject in the
50
- * first place.
51
- *
52
- * Either path removes the need for this helper.
53
44
  */
54
45
  export function buildHatchConfigValues(
55
46
  configValues: Record<string, string>,
@@ -65,34 +56,70 @@ export function buildHatchConfigValues(
65
56
  };
66
57
  }
67
58
 
59
+ export interface ApplyHatchConfigOptions {
60
+ /** The assistant's gateway base URL. */
61
+ gatewayUrl: string;
62
+ /** Guardian bearer token leased for this hatch (settings.write scope). */
63
+ bearerToken?: string;
64
+ /** Flat dot-notation config values to set, e.g. `llm.default.provider`. */
65
+ configValues: Record<string, string>;
66
+ fetchImpl?: typeof fetch;
67
+ log?: (message: string) => void;
68
+ }
69
+
68
70
  /**
69
- * Write arbitrary key-value pairs to a temporary JSON file and return its
70
- * path. The caller is responsible for getting the file to the daemon — for
71
- * the local hatch flow that means setting `CADET_DEFAULT_WORKSPACE_CONFIG_PATH`
72
- * on the daemon process; for the Docker hatch flow the caller stages the
73
- * file into the workspace volume so the rename-after-consume step in
74
- * `mergeDefaultWorkspaceConfig` is a same-filesystem rename.
75
- *
76
- * Keys use dot-notation to address nested fields. For example:
77
- * "llm.default.provider" → {llm: {default: {provider: ...}}}
78
- * "llm.default.model" → {llm: {default: {model: ...}}}
71
+ * Apply hatch config values through the assistant's config API after it
72
+ * wakes. One `POST /v1/config/set` per dotted path — the same route the web
73
+ * client and `assistant config set` use — so local and remote hatches behave
74
+ * identically and every value rides the daemon's validated, hot-applied
75
+ * config write.
79
76
  *
80
- * Returns undefined when configValues is empty (nothing to write).
81
- *
82
- * @deprecated See {@link buildHatchConfigValues} for the replacement
83
- * direction. This overlay path is a CLI→Assistant side channel and will be
84
- * removed once one of the documented replacements lands.
77
+ * Best-effort: a failed key logs a warning and the remaining keys still try,
78
+ * mirroring the provider-credential step that follows it. The assistant is
79
+ * still hatched; the values can be re-applied with `assistant config set`.
85
80
  */
86
- export function writeInitialConfig(
87
- configValues: Record<string, string>,
88
- ): string | undefined {
89
- if (Object.keys(configValues).length === 0) return undefined;
81
+ export async function applyHatchConfig(
82
+ options: ApplyHatchConfigOptions,
83
+ ): Promise<void> {
84
+ const log = options.log ?? console.log;
85
+ const keys = Object.keys(options.configValues);
86
+ if (keys.length === 0) {
87
+ return;
88
+ }
89
+
90
+ if (!options.bearerToken) {
91
+ log(
92
+ "⚠️ Initial config skipped because the guardian token was not leased.\n" +
93
+ " The assistant is still hatched. Re-apply with `assistant config set <path> <value>`.",
94
+ );
95
+ return;
96
+ }
90
97
 
91
- const config = buildNestedConfig(configValues);
92
- const tempPath = join(
93
- tmpdir(),
94
- `cadet-default-workspace-config-${process.pid}-${Date.now()}.json`,
95
- );
96
- writeFileSync(tempPath, JSON.stringify(config, null, 2) + "\n");
97
- return tempPath;
98
+ const fetchImpl = options.fetchImpl ?? fetch;
99
+ for (const path of keys) {
100
+ try {
101
+ const response = await fetchImpl(
102
+ `${options.gatewayUrl.replace(/\/$/, "")}/v1/config/set`,
103
+ {
104
+ method: "POST",
105
+ headers: {
106
+ "Content-Type": "application/json",
107
+ Authorization: `Bearer ${options.bearerToken}`,
108
+ },
109
+ body: JSON.stringify({ path, value: options.configValues[path] }),
110
+ signal: AbortSignal.timeout(10_000),
111
+ },
112
+ );
113
+ if (!response.ok) {
114
+ const body = await response.text().catch(() => "");
115
+ throw new Error(`HTTP ${response.status}${body ? `: ${body}` : ""}`);
116
+ }
117
+ } catch (error) {
118
+ const message = error instanceof Error ? error.message : String(error);
119
+ log(
120
+ `⚠️ Failed to apply ${path}: ${message}\n` +
121
+ " The assistant is still hatched. Re-apply with `assistant config set`.",
122
+ );
123
+ }
124
+ }
98
125
  }
@@ -10,7 +10,7 @@ import { sleepLocal } from "./sleep";
10
10
  import { wakeLocal } from "./wake";
11
11
  import { setStartupLogging } from "./common";
12
12
  import { withLocalHatchLock } from "./hatch-lock";
13
- import { buildHatchConfigValues, writeInitialConfig } from "./hatch-config";
13
+ import { applyHatchConfig, buildHatchConfigValues } from "./hatch-config";
14
14
  import { generateInstanceName } from "../../naming";
15
15
  import { mkdirSync } from "node:fs";
16
16
  import { join } from "node:path";
@@ -120,14 +120,10 @@ export async function hatchLocal(params: {
120
120
  ...(await allocateLocalPlacement(instanceName)),
121
121
  };
122
122
 
123
- const defaultWorkspaceConfigPath = writeInitialConfig(
124
- buildHatchConfigValues(configValues, provider),
125
- );
126
-
127
123
  try {
128
- // The wake leg owns starting — the hatch only threads the fresh
129
- // daemon's first-boot config through.
130
- await wakeLocal(fresh, { watch, defaultWorkspaceConfigPath });
124
+ // The wake leg owns starting; the config values ride the assistant's
125
+ // public config API once it is up.
126
+ await wakeLocal(fresh, { watch });
131
127
  } catch (error) {
132
128
  await sleepLocal(fresh, { force: true });
133
129
  throw error;
@@ -163,6 +159,8 @@ export async function hatchLocal(params: {
163
159
  log(`🥚 Hatching local assistant: ${instanceName}`);
164
160
  log("");
165
161
 
162
+ const hatchConfigValues = buildHatchConfigValues(configValues, provider);
163
+
166
164
  // Lease a guardian token so the desktop app can import it on first launch
167
165
  // instead of hitting /v1/guardian/init itself.
168
166
  const maxLeaseAttempts = 3;
@@ -192,6 +190,15 @@ export async function hatchLocal(params: {
192
190
  }
193
191
  }
194
192
 
193
+ // Apply the hatch's config values through the assistant's public config
194
+ // API — the same route the web client uses — now that it is up. Mirrors
195
+ // the overlay's old place in the flow; non-fatal on failure.
196
+ await applyHatchConfig({
197
+ gatewayUrl: getGatewayUrl(entry),
198
+ bearerToken: guardianAccessToken,
199
+ configValues: hatchConfigValues,
200
+ });
201
+
195
202
  if (provider !== undefined && provider !== null && !guardianAccessToken) {
196
203
  log(
197
204
  `⚠️ Provider credential setup skipped because the guardian token was not leased.\n` +
@@ -2,20 +2,16 @@ import type { LockfileAssistant } from "../../lockfile-contract";
2
2
  import { findAssistantByName } from "../../operations/lookup";
3
3
  import { allocateLocalPlacement } from "../../remotes/local/hatch";
4
4
  import { withLocalHatchLock } from "../../remotes/local/hatch-lock";
5
- import {
6
- buildHatchConfigValues,
7
- writeInitialConfig,
8
- } from "../../remotes/local/hatch-config";
9
5
  import { initializeRootArchive } from "../../root-backup";
10
6
  import { saveLockfileAssistant } from "../../lockfile";
11
7
 
12
8
  /**
13
9
  * Initialize a fresh teleport target's local placement: allocate the
14
- * instance dir and ports under the hatch lock, write the first-boot config,
15
- * install the transferred archive (gateway-security included, so the gateway
16
- * boots with the archived signing identity), and persist the entry. The wake
17
- * is the caller's — a hatch is just initialize-data + wake, and the teleport
18
- * owns both halves itself.
10
+ * instance dir and ports under the hatch lock, install the transferred
11
+ * archive (gateway-security included, so the gateway boots with the archived
12
+ * signing identity), and persist the entry. The wake is the caller's — a
13
+ * hatch is just initialize-data + wake, and the teleport owns both halves
14
+ * itself.
19
15
  */
20
16
  export async function initializeLocalTeleportTarget(
21
17
  instanceName: string,
@@ -27,13 +23,9 @@ export async function initializeLocalTeleportTarget(
27
23
  cloud: "local",
28
24
  ...(await allocateLocalPlacement(instanceName)),
29
25
  };
30
- const defaultWorkspaceConfigPath = writeInitialConfig(
31
- buildHatchConfigValues({}, undefined),
32
- );
33
26
  await initializeRootArchive(entry, archive);
34
27
  entry.hatchedAt = new Date().toISOString();
35
28
  saveLockfileAssistant(entry, instanceName);
36
- return defaultWorkspaceConfigPath;
37
29
  });
38
30
  const entry = findAssistantByName(instanceName);
39
31
  if (!entry) {