cotal-ai 0.164.9 → 0.164.11

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 (35) hide show
  1. package/dist/cotal-program.js +52 -0
  2. package/dist/cotal.js +180 -88
  3. package/dist/daemon/command.js +9 -17
  4. package/dist/daemon/desktop.js +16 -2
  5. package/dist/daemon/install-win32.js +7 -0
  6. package/dist/daemon/update-entry.js +13 -5
  7. package/dist/daemon/update-generation-win32.js +88 -0
  8. package/dist/daemon/update-generation.js +44 -35
  9. package/dist/execution-store.js +69 -0
  10. package/package.json +19 -19
  11. package/seeded-connectors/_shared/docs-bundle.bin +0 -0
  12. package/seeded-connectors/_shared/docs-index.bin +0 -0
  13. package/seeded-connectors/_shared/placements.json +2 -2
  14. package/seeded-connectors/claude/dist/index.js +1 -1
  15. package/seeded-connectors/claude/dist/mcp.cjs +2 -2
  16. package/seeded-connectors/claude/package.json +1 -1
  17. package/seeded-connectors/codex/dist/host.js +2 -2
  18. package/seeded-connectors/codex/dist/index.js +1 -1
  19. package/seeded-connectors/codex/dist/personal.js +2 -2
  20. package/seeded-connectors/codex/package.json +1 -1
  21. package/seeded-connectors/hermes/dist/index.js +1 -1
  22. package/seeded-connectors/hermes/dist/launch.js +2 -2
  23. package/seeded-connectors/hermes/package.json +1 -1
  24. package/seeded-connectors/hermes/plugin/cotal/_sidecar/standalone.cjs +2 -2
  25. package/seeded-connectors/jcode/dist/host.js +2 -2
  26. package/seeded-connectors/jcode/dist/index.js +1 -1
  27. package/seeded-connectors/jcode/dist/mcp.js +1 -1
  28. package/seeded-connectors/jcode/package.json +1 -1
  29. package/seeded-connectors/opencode/dist/index.js +1 -1
  30. package/seeded-connectors/opencode/dist/plugin/index.js +2 -2
  31. package/seeded-connectors/opencode/package.json +1 -1
  32. package/seeded-connectors/pi/dist/index.js +2 -2
  33. package/seeded-connectors/pi/dist/standalone.js +2 -2
  34. package/seeded-connectors/pi/package.json +1 -1
  35. package/seeded-connectors/web/package.json +1 -1
@@ -0,0 +1,52 @@
1
+ #!/usr/bin/env node
2
+ /** The generation-local Node preflight and CLI entry. Reached through the built-ins bootstrap. */
3
+ import { setFlagsFromString } from "node:v8";
4
+ setFlagsFromString("--no-maglev");
5
+ setFlagsFromString("--no-concurrent-sparkplug");
6
+ const MIN_NODE = "22.10";
7
+ const [MIN_MAJOR, MIN_MINOR] = MIN_NODE.split(".").map(Number);
8
+ const [nodeMajor, nodeMinor] = process.versions.node.split(".").map((part) => Number.parseInt(part ?? "", 10));
9
+ if (!Number.isInteger(nodeMajor) || !Number.isInteger(nodeMinor) || nodeMajor < MIN_MAJOR ||
10
+ (nodeMajor === MIN_MAJOR && nodeMinor < MIN_MINOR)) {
11
+ const viaInstaller = process.env.COTAL_LAUNCHER === "1";
12
+ const remedy = viaInstaller
13
+ ? `The Node this install was pinned to has been replaced with an older one.\n` +
14
+ `Re-run the installer to repin it:\n curl -fsSL https://get.cotal.ai | sh\n\n` +
15
+ `Or stop depending on the system Node altogether:\n curl -fsSL https://get.cotal.ai | sh -s -- --vendor-node\n\n`
16
+ : `Install a newer Node (https://nodejs.org). With nvm:\n nvm install ${MIN_NODE} && nvm use ${MIN_NODE}\n\n` +
17
+ `If you already ran cotal once under the old Node, also clear the npx cache so the bundled\n` +
18
+ `nats-server is fetched cleanly, then retry:\n rm -rf ~/.npm/_npx # or: npx clear-npx-cache\n\n` +
19
+ `Or let the installer manage the runtime for you:\n curl -fsSL https://get.cotal.ai | sh\n\n`;
20
+ process.stderr.write(`\ncotal-ai requires Node.js >= ${MIN_NODE}, but this is ${process.version}.\n` +
21
+ `Below Node ${MIN_MAJOR}, npm silently skips the bundled nats-server broker and the CLI's UI\n` +
22
+ `stack cannot parse. Below ${MIN_NODE}, Node has no module compile cache and a seat refuses to\nstart.\n\n` + remedy);
23
+ const { unlinkSync } = await import("node:fs");
24
+ const command = process.argv.slice(2).find((arg) => !arg.startsWith("-"));
25
+ for (const [key, path] of Object.entries(process.env)) {
26
+ if (key.toUpperCase() !== "COTAL_MANAGED_HANDOFF_FILE" || !path || (command !== "spawn" && command !== "sp"))
27
+ continue;
28
+ try {
29
+ unlinkSync(path);
30
+ }
31
+ catch (error) {
32
+ if (error.code !== "ENOENT")
33
+ process.stderr.write(`cannot remove the managed handoff file: ${error.message}\n`);
34
+ }
35
+ }
36
+ process.exit(1);
37
+ }
38
+ const emitWarning = process.emitWarning.bind(process);
39
+ process.emitWarning = ((warning, ...rest) => {
40
+ if (warning !== "The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.")
41
+ emitWarning(warning, ...rest);
42
+ });
43
+ const bearerDone = process.argv[2] === "agent-bearer" && await (await import("@cotal-ai/auth/agent-bearer")).runAgentBearerEntry(process.argv.slice(3));
44
+ if (process.argv[2] === "__update-check") {
45
+ await (await import("./update-notice.js")).updateCheckWorker();
46
+ }
47
+ else if (!bearerDone) {
48
+ const commandWord = process.argv.slice(2).find((word) => !word.startsWith("-"));
49
+ if (!commandWord?.startsWith("__"))
50
+ (await import("./startup-interrupt.js")).holdStartupInterrupt();
51
+ await import("./run.js");
52
+ }
package/dist/cotal.js CHANGED
@@ -1,98 +1,190 @@
1
1
  #!/usr/bin/env node
2
- /**
3
- * Executable entry for the `cotal` CLI (published as `cotal-ai`): a Node-version preflight, then a
4
- * hand-off to the real composition root (./run.js) via dynamic import.
5
- *
6
- * The floor is the one `engines.node` declares, 22.10, which is where `module.flushCompileCache()`
7
- * lands and therefore the oldest Node a connector's seat entry runs on. It is checked here, at the
8
- * front door, so the binary and the seats it installs agree on one version.
9
- *
10
- * Why this file exists separately: the CLI's UI stack (ink, @clack/prompts, string-width) and the
11
- * bundled `nats-server` optional dependency (@eplightning/nats-server-*) require Node >= 22 —
12
- * and npm SILENTLY SKIPS an optional dependency whose `engines` the running Node doesn't satisfy,
13
- * so on an older Node the bundled broker is never installed at all. On top of that, string-width
14
- * uses a Node-20+ regex flag that is a hard parse error on older Node. An ESM entry parses its whole
15
- * static-import graph before its own body runs, so a version check inside ./run.ts would come too
16
- * late — it would crash while parsing string-width. This shim therefore keeps ZERO static imports
17
- * of that chain: the check runs first, and ./run.js is only pulled in (dynamically) once it passes.
18
- */
2
+ import { createHash } from "node:crypto";
3
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync } from "node:fs";
4
+ import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
+ import { fileURLToPath, pathToFileURL } from "node:url";
19
6
  import { setFlagsFromString } from "node:v8";
20
- // Node 24 can hang forever in process.exit(), after the command has printed its result
21
- // (nodejs/node#64274, #5498): exit joins V8's background threads, and a Maglev or background
22
- // Sparkplug compile parked waiting for a garbage collection never finishes. Turning both off here,
23
- // before the CLI loads, restores Node 22's defaults; cli-entry.smoke.ts checks that Maglev stays off.
24
- // Every command, and every daemon this binary re-execs, starts here. Remove these once the supported
25
- // Node releases carry the fix (nodejs/node#66171).
26
7
  setFlagsFromString("--no-maglev");
27
8
  setFlagsFromString("--no-concurrent-sparkplug");
28
- const MIN_NODE = "22.10";
29
- const [MIN_MAJOR, MIN_MINOR] = MIN_NODE.split(".").map(Number);
30
- const [nodeMajor, nodeMinor] = process.versions.node.split(".").map((part) => Number.parseInt(part ?? "", 10));
31
- if (!Number.isInteger(nodeMajor) || !Number.isInteger(nodeMinor) || nodeMajor < MIN_MAJOR ||
32
- (nodeMajor === MIN_MAJOR && nodeMinor < MIN_MINOR)) {
33
- // How cotal was installed decides the fix, so say the one that applies. COTAL_LAUNCHER is set
34
- // by the launcher install.sh writes: that install pinned a Node, and reaching here means the
35
- // pinned Node was replaced with an older one, which re-running the installer repairs.
36
- const viaInstaller = process.env.COTAL_LAUNCHER === "1";
37
- const remedy = viaInstaller
38
- ? `The Node this install was pinned to has been replaced with an older one.\n` +
39
- `Re-run the installer to repin it:\n` +
40
- ` curl -fsSL https://get.cotal.ai | sh\n\n` +
41
- `Or stop depending on the system Node altogether:\n` +
42
- ` curl -fsSL https://get.cotal.ai | sh -s -- --vendor-node\n\n`
43
- : `Install a newer Node (https://nodejs.org). With nvm:\n` +
44
- ` nvm install ${MIN_NODE} && nvm use ${MIN_NODE}\n\n` +
45
- `If you already ran cotal once under the old Node, also clear the npx cache so the bundled\n` +
46
- `nats-server is fetched cleanly, then retry:\n` +
47
- ` rm -rf ~/.npm/_npx # or: npx clear-npx-cache\n\n` +
48
- `Or let the installer manage the runtime for you:\n` +
49
- ` curl -fsSL https://get.cotal.ai | sh\n\n`;
50
- process.stderr.write(`\ncotal-ai requires Node.js >= ${MIN_NODE}, but this is ${process.version}.\n` +
51
- `Below Node ${MIN_MAJOR}, npm silently skips the bundled nats-server broker and the CLI's UI\n` +
52
- `stack cannot parse. Below ${MIN_NODE}, Node has no module compile cache and a seat refuses to\n` +
53
- `start.\n\n` +
54
- remedy);
55
- // A delegated seat's spawn takes its handoff file, which holds its actor token, before anything
56
- // else on a supported Node, so this refusal must not leave it on disk either. Any other command
57
- // leaves the file. The leading global flags take no value, so the first other word is the command.
58
- // Unlink only, never read.
59
- const { unlinkSync } = await import("node:fs");
60
- const command = process.argv.slice(2).find((arg) => !arg.startsWith("-"));
61
- for (const [key, path] of Object.entries(process.env)) {
62
- if (key.toUpperCase() !== "COTAL_MANAGED_HANDOFF_FILE" || !path || (command !== "spawn" && command !== "sp"))
63
- continue;
64
- try {
65
- unlinkSync(path);
9
+ export const executionDescriptorName = ".cotal-execution.json";
10
+ export const executionSha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
11
+ const MAX_RECORD_BYTES = 4 * 1024 * 1024;
12
+ const HASH = /^[a-f0-9]{64}$/;
13
+ const ID = /^[a-f0-9]{32}$/;
14
+ function object(value) {
15
+ if (!value || typeof value !== "object" || Array.isArray(value))
16
+ throw new Error("invalid execution record");
17
+ return value;
18
+ }
19
+ export function executionRecord(path) {
20
+ const before = lstatSync(path);
21
+ if (!before.isFile() || before.isSymbolicLink() || before.size > MAX_RECORD_BYTES)
22
+ throw new Error("unsafe execution record");
23
+ protectedExecutionEntry(path);
24
+ const fd = openSync(path, constants.O_RDONLY | (process.platform === "win32" ? 0 : constants.O_NOFOLLOW));
25
+ try {
26
+ const current = fstatSync(fd);
27
+ if (!current.isFile() || current.size > MAX_RECORD_BYTES ||
28
+ (process.platform !== "win32" && ((current.mode & 0o022) !== 0 ||
29
+ typeof process.getuid !== "function" || (current.uid !== process.getuid() && current.uid !== 0))))
30
+ throw new Error("unsafe opened execution record");
31
+ const bytes = readFileSync(fd);
32
+ if (bytes.length > MAX_RECORD_BYTES)
33
+ throw new Error("execution record exceeded its size limit");
34
+ return JSON.parse(bytes.toString("utf8"));
35
+ }
36
+ finally {
37
+ closeSync(fd);
38
+ }
39
+ }
40
+ /** Read-only checks on a retained object. A missing or unreadable object is never a healthy generation. */
41
+ export function protectedExecutionEntry(path) {
42
+ const info = lstatSync(path);
43
+ if (process.platform !== "win32" && ((!info.isSymbolicLink() && (info.mode & 0o022) !== 0) ||
44
+ typeof process.getuid !== "function" || (info.uid !== process.getuid() && info.uid !== 0)))
45
+ throw new Error(`unprotected execution entry: ${path}`);
46
+ }
47
+ export function executionBinding(root) {
48
+ const meta = object(JSON.parse(readFileSync(join(root, "package.json"), "utf8")));
49
+ if (meta.name !== "cotal-ai" || typeof meta.version !== "string" || !meta.version)
50
+ throw new Error("the installed execution artifact is not cotal-ai");
51
+ return { name: "cotal-ai", version: meta.version, bootstrapSha256: executionSha256(readFileSync(join(root, "dist", "cotal.js"))) };
52
+ }
53
+ export function executionStore(root) {
54
+ return join(dirname(dirname(root)), ".cotal-generations");
55
+ }
56
+ /** Enumerate the whole package, including dependencies, without following a link outside it. */
57
+ export function executionInventory(root) {
58
+ const physical = realpathSync(root);
59
+ const rows = [];
60
+ const walk = (directory, prefix) => {
61
+ protectedExecutionEntry(directory);
62
+ for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {
63
+ const path = join(directory, entry.name), name = prefix ? `${prefix}/${entry.name}` : entry.name;
64
+ protectedExecutionEntry(path);
65
+ if (entry.isDirectory())
66
+ walk(path, name);
67
+ else if (entry.isSymbolicLink()) {
68
+ const target = readlinkSync(path), resolved = realpathSync(path), suffix = relative(physical, resolved);
69
+ if (isAbsolute(target) || suffix === ".." || suffix.startsWith(`..${sep}`) || isAbsolute(suffix))
70
+ throw new Error(`execution inventory link escapes its package: ${name}`);
71
+ rows.push({ path: name, link: target });
72
+ }
73
+ else if (entry.isFile())
74
+ rows.push({ path: name, sha256: executionSha256(readFileSync(path)) });
75
+ else
76
+ throw new Error(`unsupported execution inventory entry: ${name}`);
66
77
  }
67
- catch (e) {
68
- if (e.code !== "ENOENT")
69
- process.stderr.write(`cannot remove the managed handoff file: ${e.message}\n`);
78
+ };
79
+ walk(physical, "");
80
+ return rows;
81
+ }
82
+ export function executionLaunchBinding(root, entry) {
83
+ const logical = resolve(entry), physical = realpathSync(logical);
84
+ if (physical !== join(realpathSync(root), "dist", "cotal.js"))
85
+ throw new Error("execution launch route does not resolve to this bootstrap");
86
+ let path = join(realpathSync(root), "package.json");
87
+ for (let current = dirname(logical); current !== dirname(current); current = dirname(current)) {
88
+ if (lstatSync(current).isSymbolicLink()) {
89
+ path = current;
90
+ break;
70
91
  }
71
92
  }
72
- process.exit(1);
93
+ const info = lstatSync(path, { bigint: true });
94
+ return { entry: logical, path, dev: String(info.dev), ino: String(info.ino), birth: String(info.birthtimeNs), ctime: String(info.ctimeNs) };
95
+ }
96
+ export function executionDescriptorPath(root) {
97
+ return join(executionStore(root), `.active-${executionSha256(realpathSync(root))}.json`);
73
98
  }
74
- // Node warns once, as it loads its own color helpers, when FORCE_COLOR and NO_COLOR are both set.
75
- // The CLI resolves that pair itself (`cotal config` shows FORCE_COLOR winning and NO_COLOR
76
- // outranked), so that one runtime warning is dropped before anything loads. Every other warning
77
- // still prints.
78
- const emitWarning = process.emitWarning.bind(process);
79
- process.emitWarning = ((warning, ...rest) => {
80
- if (warning !== "The 'NO_COLOR' env is ignored due to the 'FORCE_COLOR' env being set.")
81
- emitWarning(warning, ...rest);
82
- });
83
- // A spawned seat execs `cotal agent-bearer` for every bearer, so it runs from its own module before
84
- // the rest of the CLI loads: loading the whole command surface was most of each bearer's cost. A
85
- // command line that does not parse goes on to the full CLI, which refuses it with the command's help.
86
- const bearerDone = process.argv[2] === "agent-bearer" && await (await import("@cotal-ai/auth/agent-bearer")).runAgentBearerEntry(process.argv.slice(3));
87
- if (process.argv[2] === "__update-check") {
88
- await (await import("./update-notice.js")).updateCheckWorker();
99
+ /** Select a verified program, or the installed first generation when no matching descriptor exists. */
100
+ export function selectExecutionProgram(root) {
101
+ const installed = realpathSync(root), descriptorPath = executionDescriptorPath(installed);
102
+ const initial = () => ({ root: installed, entry: import.meta.url.endsWith(".ts") && installed === dirname(fileURLToPath(import.meta.url))
103
+ ? join(installed, "cotal-program.ts") : join(installed, "dist", "cotal-program.js"), retained: false });
104
+ let value;
105
+ try {
106
+ value = executionRecord(descriptorPath);
107
+ }
108
+ catch (error) {
109
+ if (error.code === "ENOENT")
110
+ return initial();
111
+ throw error;
112
+ }
113
+ const descriptor = object(value), binding = object(descriptor.binding), current = executionBinding(installed);
114
+ if (typeof binding.name !== "string" || typeof binding.version !== "string" || !binding.version ||
115
+ typeof binding.bootstrapSha256 !== "string" || !HASH.test(binding.bootstrapSha256))
116
+ throw new Error("invalid execution artifact binding");
117
+ if (descriptor.launch !== undefined) {
118
+ const launch = object(descriptor.launch);
119
+ if (!["entry", "path", "dev", "ino", "birth", "ctime"].every(key => typeof launch[key] === "string") || !isAbsolute(launch.entry) || !isAbsolute(launch.path))
120
+ throw new Error("invalid execution launch binding");
121
+ try {
122
+ if (JSON.stringify(executionLaunchBinding(installed, launch.entry)) !== JSON.stringify(launch))
123
+ return initial();
124
+ }
125
+ catch (error) {
126
+ if (["ENOENT", "ENOTDIR"].includes(error.code ?? ""))
127
+ return initial();
128
+ throw error;
129
+ }
130
+ }
131
+ const matches = (candidate) => candidate.name === current.name && candidate.version === current.version && candidate.bootstrapSha256 === current.bootstrapSha256;
132
+ if (descriptor.bindings !== undefined && (!Array.isArray(descriptor.bindings) || descriptor.bindings.length > 4 ||
133
+ descriptor.bindings.some(value => { const item = object(value); return item.name !== "cotal-ai" || typeof item.version !== "string" || !item.version || typeof item.bootstrapSha256 !== "string" || !HASH.test(item.bootstrapSha256); })))
134
+ throw new Error("invalid execution transition bindings");
135
+ if (!matches(binding) && !descriptor.bindings?.some(matches))
136
+ return initial();
137
+ if (descriptor.v !== 1)
138
+ throw new Error(`unsupported execution descriptor version ${String(descriptor.v)}`);
139
+ if (process.platform === "win32")
140
+ throw new Error("retained execution generations are unavailable on Windows");
141
+ const generation = object(descriptor.generation);
142
+ if (typeof generation.id !== "string" || !ID.test(generation.id) || typeof generation.version !== "string" ||
143
+ typeof generation.inventorySha256 !== "string" || !HASH.test(generation.inventorySha256))
144
+ throw new Error("invalid retained execution identity");
145
+ protectedExecutionEntry(installed);
146
+ for (const ancestor of [dirname(installed), dirname(dirname(installed)), dirname(dirname(dirname(installed)))])
147
+ protectedExecutionEntry(ancestor);
148
+ const store = executionStore(installed), container = join(store, generation.id), selected = join(container, "cotal-ai");
149
+ for (const path of [store, container, selected]) {
150
+ const info = lstatSync(path);
151
+ if (!info.isDirectory() || info.isSymbolicLink())
152
+ throw new Error("unsafe execution generation directory");
153
+ protectedExecutionEntry(path);
154
+ }
155
+ const inventory = executionRecord(join(container, "inventory.json"));
156
+ if (!Array.isArray(inventory) || executionSha256(JSON.stringify(inventory)) !== generation.inventorySha256 ||
157
+ JSON.stringify(executionInventory(selected)) !== JSON.stringify(inventory))
158
+ throw new Error("retained execution inventory differs");
159
+ const meta = object(JSON.parse(readFileSync(join(selected, "package.json"), "utf8")));
160
+ if (meta.name !== "cotal-ai" || meta.version !== generation.version)
161
+ throw new Error("retained execution manifest differs");
162
+ return { root: selected, entry: join(selected, "dist", "cotal-program.js"), retained: true };
89
163
  }
90
- else if (!bearerDone) {
91
- // The notice holds until the command begins, or until the command's own notice takes it over. An
92
- // internal entry, such as a stack member or shell completion, keeps Node's default signal exit.
93
- // Every word before the command word is a flag.
94
- const commandWord = process.argv.slice(2).find((word) => !word.startsWith("-"));
95
- if (!commandWord?.startsWith("__"))
96
- (await import("./startup-interrupt.js")).holdStartupInterrupt();
97
- await import("./run.js");
164
+ const executionStarted = Symbol.for("cotal.execution.started");
165
+ /** Explicit CLI delegation for a wrapper that imports the bootstrap rather than launching it. */
166
+ export function startExecutionProgram() {
167
+ if (Reflect.get(globalThis, executionStarted))
168
+ return;
169
+ Object.defineProperty(globalThis, executionStarted, { value: true });
170
+ let selected;
171
+ try {
172
+ selected = selectExecutionProgram(resolve(dirname(fileURLToPath(import.meta.url)), import.meta.url.endsWith(".ts") ? "." : ".."));
173
+ }
174
+ catch (error) {
175
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}; reinstall with npm install -g cotal-ai@latest\n`);
176
+ process.exitCode = 1;
177
+ }
178
+ if (selected) {
179
+ if (!import.meta.url.endsWith(".ts"))
180
+ Object.defineProperty(globalThis, Symbol.for("cotal.execution.identity"), {
181
+ value: Object.freeze({ logicalEntry: fileURLToPath(import.meta.url), launchEntry: process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url) ? resolve(process.argv[1]) : fileURLToPath(import.meta.url), loadedEntry: join(selected.root, "dist", "cotal.js") }),
182
+ configurable: false, writable: false,
183
+ });
184
+ if (selected.retained || !process.argv[1] || realpathSync(process.argv[1]) !== fileURLToPath(import.meta.url))
185
+ process.argv[1] = join(selected.root, "dist", "cotal.js");
186
+ void import(pathToFileURL(selected.entry).href);
187
+ }
98
188
  }
189
+ if (process.argv[1] && realpathSync(process.argv[1]) === fileURLToPath(import.meta.url))
190
+ startExecutionProgram();
@@ -57,23 +57,15 @@ export const daemonFlags = [
57
57
  { name: "no-manager", type: "boolean", description: "setup: connect only the machine service without hosting a Manager" },
58
58
  { name: "space", short: "s", type: "string", value: "<s>", description: "target space (required except for status, where it selects one hosted Manager)" },
59
59
  ];
60
- /** This binary's own version: the nearest package.json above this module (bin/ in a source run). */
61
- export function binVersion() {
62
- let dir = dirname(fileURLToPath(import.meta.url));
63
- for (let i = 0; i < 4; i++) {
64
- try {
65
- const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
66
- if (pkg.name === "cotal-ai" && typeof pkg.version === "string")
67
- return pkg.version;
68
- }
69
- catch (e) {
70
- if (e.code !== "ENOENT")
71
- throw e;
72
- }
73
- dir = dirname(dir);
74
- }
75
- throw new Error("cannot determine the cotal-ai version: no cotal-ai package.json above the daemon module");
76
- }
60
+ const loadedBinVersion = (() => {
61
+ const root = dirname(dirname(fileURLToPath(import.meta.resolve("@cotal-ai/cli"))));
62
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
63
+ if (pkg.name !== "@cotal-ai/cli" || typeof pkg.version !== "string" || !pkg.version)
64
+ throw new Error("cannot determine the loaded daemon version");
65
+ return pkg.version;
66
+ })();
67
+ /** The daemon's captured loaded release, independent of canonical metadata publication. */
68
+ export function binVersion() { return loadedBinVersion; }
77
69
  const peerUid = defaultPeerUid;
78
70
  const peerPid = defaultPeerPid;
79
71
  function target(args) {
@@ -85,6 +85,16 @@ export async function readDesktopRequest(input) {
85
85
  clearTimeout(timer);
86
86
  }
87
87
  }
88
+ /** The check the install operation makes before it starts a recorded service. Any refusal reads as not installed. */
89
+ function serviceInstalled(target) {
90
+ try {
91
+ planUninstall(target.paths, target.home);
92
+ return true;
93
+ }
94
+ catch {
95
+ return false;
96
+ }
97
+ }
88
98
  /** Run one app operation through the stock local client. Closing the UI never stops the service. */
89
99
  export async function runDesktopBridge(opts) {
90
100
  const output = opts.output ?? process.stdout;
@@ -97,6 +107,7 @@ export async function runDesktopBridge(opts) {
97
107
  emit({ v: 1, event: "result", ok: false, error: { code: "BAD_REQUEST", message: "The app request was incomplete, oversized or unsupported." } });
98
108
  return;
99
109
  }
110
+ let target;
100
111
  try {
101
112
  if (req.op === "update-policy") {
102
113
  const settings = req.auto === undefined ? readUpdateSettings() : setUpdateSetting("auto", req.auto);
@@ -139,7 +150,8 @@ export async function runDesktopBridge(opts) {
139
150
  emit({ v: 1, event: "result", ok: true, result: { assets } });
140
151
  return;
141
152
  }
142
- const { paths, home } = opts.resolveTarget();
153
+ target = opts.resolveTarget();
154
+ const { paths, home } = target;
143
155
  const client = { paths, peerUid: opts.peerUid, peerPid: opts.peerPid };
144
156
  if (req.op === "install" || req.op === "setup")
145
157
  process.env.PATH = await desktopApplicationPath();
@@ -233,7 +245,9 @@ export async function runDesktopBridge(opts) {
233
245
  catch (e) {
234
246
  const code = e instanceof EndpointRefusal || e instanceof CommandFailure ? e.code : "OPERATION_FAILED";
235
247
  const message = e instanceof CommandFailure && (req.op === "setup" || (req.op === "install" && e.native?.code !== "NOT_ANSWERING")) ? e.message
236
- : code === "NOT_RUNNING" ? "The daemon is not running. Install its background service first."
248
+ : code === "NOT_RUNNING" ? (target && serviceInstalled(target)
249
+ ? "The background service is installed but stopped. Choose Start service to start it."
250
+ : "The daemon is not running. Install its background service first.")
237
251
  : e instanceof CommandFailure && e.code === "DEPENDENCY_UNAVAILABLE" && e.native?.code === "NOT_ANSWERING" ? "The background service was installed and a start was requested, but the daemon did not answer within 15 seconds. Use \`cotal daemon status\` for diagnostics."
238
252
  : code === "NO_RUNTIME_DIR" ? "The daemon runtime path is unavailable or too long. On Linux, check XDG_RUNTIME_DIR for the intended operating-system user."
239
253
  : code === "UNSUPPORTED_PLATFORM" ? "This platform does not have the required native daemon support."
@@ -262,6 +262,13 @@ export function scheduledTaskService(run) {
262
262
  check(receipt) {
263
263
  owned(receipt);
264
264
  },
265
+ startEnabled(receipt) {
266
+ const task = owned(receipt, true);
267
+ if (!task.present || task.enabled !== true)
268
+ throw new CommandFailure("refused", "CONFLICT", "the owned task is absent or disabled; update did not enable it");
269
+ if (task.instances === 0)
270
+ step(["/Run", "/TN", receipt.unit]);
271
+ },
265
272
  start(receipt) {
266
273
  const task = owned(receipt, true);
267
274
  if (!task.present)
@@ -3,7 +3,7 @@ import { existsSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { createInterface } from "node:readline/promises";
5
5
  import { registry } from "@cotal-ai/core";
6
- import { update, updateRuntime, localUpdateManagers, readManagerContinuity, updateManagerPin } from "@cotal-ai/cli/update";
6
+ import { update, updateRuntime, installedCliVersion, localUpdateManagers, readManagerContinuity, updateManagerPin } from "@cotal-ai/cli/update";
7
7
  import { withIdpSessionDir, withRemoteExchangeRetry } from "@cotal-ai/auth";
8
8
  import { brokerAddressKey, assertRecordIdentity, CommandFailure, homeCotalDir, readUpdateRecovery, claimUpdateClosureAccess, resolveControlTarget } from "@cotal-ai/workspace";
9
9
  import { askManager } from "@cotal-ai/workspace/control";
@@ -13,6 +13,7 @@ import { installedDaemonIdentity, preflightInstalledDaemon, restartInstalled, un
13
13
  import { excludeLifetime, processBirth, readLifetimeRecord } from "./lifetime.js";
14
14
  import { waitForInstalledDaemonGeneration } from "./update-generation.js";
15
15
  import { adoptAutomaticUpdateChild } from "./update-scope.js";
16
+ import { captureWindowsGeneration, closeWindowsGeneration, windowsGenerationLifecycle } from "./update-generation-win32.js";
16
17
  const command = registry.resolve("command", "update");
17
18
  registry.unregister("command", "update");
18
19
  const composed = { ...command, async run(args) {
@@ -72,7 +73,7 @@ const composed = { ...command, async run(args) {
72
73
  }, waitForInstalledGeneration: async (version) => {
73
74
  if (absentRecoveryHost)
74
75
  return;
75
- await waitForInstalledDaemonGeneration(version);
76
+ await waitForInstalledDaemonGeneration(version, process.platform === "win32" ? { lifecycle: windowsGenerationLifecycle } : {});
76
77
  }, reportRunningManager: (flags) => withRemoteExchangeRetry(async () => {
77
78
  const recovery = readUpdateRecovery();
78
79
  if (recovery?.preparedRestart && process.env.COTAL_UPDATE_PARENT === String(process.ppid) && process.env.COTAL_UPDATE_TARGET_VERSION === updateRuntime.version() && recovery?.owner?.pid === process.ppid && recovery.owner.nonce === process.env.COTAL_UPDATE_CLOSURE_NONCE && recovery.owner.start === process.env.COTAL_UPDATE_CLOSURE_START) {
@@ -103,6 +104,8 @@ const composed = { ...command, async run(args) {
103
104
  }
104
105
  if (!evidence?.prepared || evidence.managers.some(row => !row.fenced || row.seats !== 0))
105
106
  throw new Error("prepared update admission is no longer fenced and empty");
107
+ if (process.platform === "win32")
108
+ await captureWindowsGeneration(paths);
106
109
  console.log("hosted Manager continuity: daemon verified prepared fences and zero seats");
107
110
  return "none";
108
111
  }
@@ -112,6 +115,8 @@ const composed = { ...command, async run(args) {
112
115
  if (!reply.ok)
113
116
  throw new Error(`machine daemon custody is unreadable: ${reply.error.message}`);
114
117
  daemonObserved = true;
118
+ if (process.platform === "win32")
119
+ await captureWindowsGeneration(daemonPaths());
115
120
  managers = reply.result.managers ?? [];
116
121
  }
117
122
  catch (error) {
@@ -236,6 +241,7 @@ const composed = { ...command, async run(args) {
236
241
  }) });
237
242
  }
238
243
  finally {
244
+ closeWindowsGeneration();
239
245
  if (recoveryFence)
240
246
  await managerViaDaemon({ paths: daemonPaths() }, { op: "managers-abort-restart" });
241
247
  }
@@ -245,6 +251,8 @@ const composed = { ...command, async run(args) {
245
251
  // asked for from here would stop this process with the rest of the service.
246
252
  if (process.env.COTAL_AUTO_UPDATE === "1")
247
253
  return;
254
+ // This process keeps the release it loaded. The daemon must run the release now installed.
255
+ const expectedVersion = installedCliVersion();
248
256
  const paths = daemonPaths();
249
257
  const current = await queryDaemon({ paths });
250
258
  if (!current.ok)
@@ -258,12 +266,12 @@ const composed = { ...command, async run(args) {
258
266
  console.log(`machine daemon: ${installation.installed} runs Cotal ${current.result.version}; another installation was left running`);
259
267
  return;
260
268
  }
261
- if (current.result.version !== updateRuntime.version()) {
269
+ if (current.result.version !== expectedVersion) {
262
270
  const hosted = (current.result.managers ?? []).some((manager) => manager.pid !== undefined);
263
271
  if (hosted)
264
272
  await managerViaDaemon({ paths }, { op: "managers-prepare-restart" });
265
273
  try {
266
- await restartInstalled(paths, undefined, false, updateRuntime.version(), detail => console.log(`machine daemon: ${detail}`));
274
+ await restartInstalled(paths, undefined, false, expectedVersion, detail => console.log(`machine daemon: ${detail}`));
267
275
  }
268
276
  catch (error) {
269
277
  if (hosted && process.platform !== "win32") {
@@ -279,7 +287,7 @@ const composed = { ...command, async run(args) {
279
287
  for (;;) {
280
288
  try {
281
289
  const reply = await queryDaemon({ paths });
282
- if (reply.ok && reply.result.version === updateRuntime.version() && hostedSpaces.every((space) => reply.result.managers?.some((manager) => manager.space === space && manager.state === "answering")))
290
+ if (reply.ok && reply.result.version === expectedVersion && hostedSpaces.every((space) => reply.result.managers?.some((manager) => manager.space === space && manager.state === "answering")))
283
291
  return;
284
292
  }
285
293
  catch (error) {
@@ -0,0 +1,88 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { CommandFailure, win32ProcessBinding } from "@cotal-ai/workspace";
3
+ import { queryDaemon } from "./client.js";
4
+ import { EndpointRefusal } from "./endpoint.js";
5
+ import { readLifetimeRecord } from "./lifetime.js";
6
+ import { readReceipt } from "./install-receipt.js";
7
+ import { scheduledTaskService } from "./install-win32.js";
8
+ import { checkWindowsRecordedUnit } from "./ownership-win32.js";
9
+ import { recordedSourceIdentity } from "./install-identity.js";
10
+ import { daemonArgv } from "@cotal-ai/cli";
11
+ let captured;
12
+ /** Retain the authenticated old generation before reconciliation can make it exit. */
13
+ export async function captureWindowsGeneration(paths) {
14
+ if (process.platform !== "win32" || captured)
15
+ return;
16
+ const receipt = readReceipt(paths);
17
+ if (!receipt)
18
+ return;
19
+ try {
20
+ const reply = await queryDaemon({ paths });
21
+ if (!reply.ok)
22
+ throw new Error("the Windows daemon refused its initial generation observation");
23
+ const before = readLifetimeRecord(paths.lock);
24
+ if (!before?.start || before.pid !== reply.result.pid)
25
+ throw new Error("the Windows daemon lifetime changed before capture");
26
+ const pin = win32ProcessBinding().pinProcess(before.pid);
27
+ try {
28
+ const after = readLifetimeRecord(paths.lock);
29
+ if (pin.token !== before.start || pin.exited() || after?.pid !== before.pid || after.start !== before.start)
30
+ throw new Error("the Windows daemon lifetime changed during capture");
31
+ captured = { paths, pin, receipt: JSON.stringify(receipt) };
32
+ }
33
+ finally {
34
+ if (captured?.pin !== pin)
35
+ pin.close();
36
+ }
37
+ }
38
+ catch (error) {
39
+ if (error instanceof EndpointRefusal && error.code === "NOT_RUNNING")
40
+ return;
41
+ throw error;
42
+ }
43
+ }
44
+ /** Release an old-generation observation on every update outcome. */
45
+ export function closeWindowsGeneration() {
46
+ captured?.pin.close();
47
+ captured = undefined;
48
+ }
49
+ /** Native supervision after a published Windows daemon exits successfully needs an explicit Run. */
50
+ export async function windowsGenerationLifecycle(paths, deadline) {
51
+ if (process.platform !== "win32" || !captured || captured.paths.lock !== paths.lock)
52
+ throw new Error("the Windows update has no retained authenticated daemon lifetime");
53
+ const retained = captured;
54
+ let started = false;
55
+ const run = (file, args, env) => {
56
+ const remaining = deadline - Date.now();
57
+ if (remaining <= 0)
58
+ throw new Error("Windows generation startup exceeded the update readiness deadline");
59
+ const result = spawnSync(file, args, { env, encoding: "utf8", timeout: Math.min(30_000, remaining), maxBuffer: 256 * 1024, windowsHide: true, stdio: ["ignore", "pipe", "pipe"] });
60
+ if (result.error || result.signal)
61
+ throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", "Windows generation inspection could not complete within the update readiness deadline");
62
+ return { status: result.status, stdout: result.stdout, detail: result.stderr.trim().slice(0, 300) };
63
+ };
64
+ const task = scheduledTaskService(run);
65
+ return {
66
+ async poll() {
67
+ if (started || !retained.pin.exited())
68
+ return;
69
+ const receipt = readReceipt(paths);
70
+ if (!receipt || JSON.stringify(receipt) !== retained.receipt)
71
+ throw new Error("the Windows daemon installation changed during update");
72
+ checkWindowsRecordedUnit(paths, receipt, task);
73
+ if (!recordedSourceIdentity(receipt, "scheduled-task", [...daemonArgv(), "daemon", "serve"]).same)
74
+ throw new Error("the Windows daemon source names another installation");
75
+ const native = task.inspect(receipt);
76
+ if (!native.present || native.enabled !== true)
77
+ throw new Error("the Windows daemon task is absent or disabled; update did not enable it");
78
+ if (native.instances !== 0) {
79
+ started = true;
80
+ return;
81
+ }
82
+ // startEnabled performs its own fresh source/principal/action/enabled/instance check.
83
+ task.startEnabled(receipt);
84
+ started = true;
85
+ },
86
+ close: closeWindowsGeneration,
87
+ };
88
+ }