cotal-ai 0.164.8 → 0.164.10

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 (38) hide show
  1. package/dist/cotal-program.js +52 -0
  2. package/dist/cotal.js +180 -88
  3. package/dist/daemon/client.js +25 -3
  4. package/dist/daemon/command.js +49 -18
  5. package/dist/daemon/desktop.js +28 -4
  6. package/dist/daemon/install-win32.js +7 -0
  7. package/dist/daemon/install.js +7 -3
  8. package/dist/daemon/lifetime.js +9 -5
  9. package/dist/daemon/update-entry.js +208 -187
  10. package/dist/daemon/update-generation-win32.js +88 -0
  11. package/dist/daemon/update-generation.js +44 -35
  12. package/dist/execution-store.js +69 -0
  13. package/package.json +19 -19
  14. package/seeded-connectors/_shared/docs-bundle.bin +0 -0
  15. package/seeded-connectors/_shared/docs-index.bin +0 -0
  16. package/seeded-connectors/_shared/placements.json +2 -2
  17. package/seeded-connectors/claude/dist/index.js +1 -1
  18. package/seeded-connectors/claude/dist/mcp.cjs +6 -6
  19. package/seeded-connectors/claude/package.json +1 -1
  20. package/seeded-connectors/codex/dist/host.js +6 -6
  21. package/seeded-connectors/codex/dist/index.js +1 -1
  22. package/seeded-connectors/codex/dist/personal.js +6 -6
  23. package/seeded-connectors/codex/package.json +1 -1
  24. package/seeded-connectors/hermes/dist/index.js +1 -1
  25. package/seeded-connectors/hermes/dist/launch.js +6 -6
  26. package/seeded-connectors/hermes/package.json +1 -1
  27. package/seeded-connectors/hermes/plugin/cotal/_sidecar/standalone.cjs +6 -6
  28. package/seeded-connectors/jcode/dist/host.js +6 -6
  29. package/seeded-connectors/jcode/dist/index.js +1 -1
  30. package/seeded-connectors/jcode/dist/mcp.js +4 -4
  31. package/seeded-connectors/jcode/package.json +1 -1
  32. package/seeded-connectors/opencode/dist/index.js +1 -1
  33. package/seeded-connectors/opencode/dist/plugin/index.js +6 -6
  34. package/seeded-connectors/opencode/package.json +1 -1
  35. package/seeded-connectors/pi/dist/index.js +2 -2
  36. package/seeded-connectors/pi/dist/standalone.js +6 -6
  37. package/seeded-connectors/pi/package.json +1 -1
  38. 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();
@@ -15,7 +15,7 @@ import { randomUUID } from "node:crypto";
15
15
  import { connectPipe, windowsUserSid } from "@cotal-ai/seat";
16
16
  import { DAEMON_PROTOCOL_VERSION, MAX_LINE_BYTES, EndpointRefusal, adoptPipe, assertSupportedPlatform, checkDir, checkSocket, defaultPeerPid, defaultPeerUid } from "./endpoint.js";
17
17
  import { encode } from "./protocol.js";
18
- import { processBirth, readLifetimeRecord } from "./lifetime.js";
18
+ import { observeLifetimeRecord, processBirth, readLifetimeRecord } from "./lifetime.js";
19
19
  import { CommandFailure } from "@cotal-ai/workspace";
20
20
  /** Read or change shared update preferences, or run the existing cached check without installing. */
21
21
  export async function updateViaDaemon(opts, request) {
@@ -230,6 +230,21 @@ function isLockOwner(lock, pid, birth) {
230
230
  /** The pipe-open steps that read the server's identity. A failure in one means that identity could
231
231
  * not be established, so nothing may be sent. */
232
232
  const IDENTITY_STEPS = new Set(["GetNamedPipeServerProcessId", "OpenProcess", "GetProcessTimes", "OpenProcessToken", "GetTokenInformation", "ConvertSidToStringSidW"]);
233
+ /** A refused Windows pipe whose original lifetime read contained zero bytes. It is never writable. */
234
+ export class EmptyLifetimeRefusal extends EndpointRefusal {
235
+ pid;
236
+ birth;
237
+ constructor(message, pid, birth) {
238
+ super("PEER_NOT_LOCK_OWNER", message);
239
+ this.pid = pid;
240
+ this.birth = birth;
241
+ }
242
+ }
243
+ /** Shutdown waits may reobserve only the exact previously pinned lifetime, never treat it as absent. */
244
+ export function isStoppingLifetime(error, owner) {
245
+ return error instanceof EmptyLifetimeRefusal && owner?.start !== undefined && owner.start.length > 0
246
+ && error.pid === owner.pid && error.birth === owner.start;
247
+ }
233
248
  /** Windows: open the daemon's pipe, which the native side authenticates, and keep it only when its
234
249
  * server is this user and the holder of the lifetime lock. Nothing is written before both. */
235
250
  async function openPipe(paths, timeoutMs) {
@@ -259,8 +274,15 @@ async function openPipe(paths, timeoutMs) {
259
274
  const own = windowsUserSid();
260
275
  if (peer.user !== own)
261
276
  refuse("PEER_UID_MISMATCH", `the process answering at ${paths.socket} runs as ${peer.user}, not ${own}; nothing was sent`);
262
- if (!isLockOwner(paths.lock, peer.pid, peer.birth))
263
- refuse("PEER_NOT_LOCK_OWNER", `the process answering at ${paths.socket} is not the daemon holding ${paths.lock}; nothing was sent`);
277
+ const observation = observeLifetimeRecord(paths.lock);
278
+ const owner = observation.record;
279
+ if (!owner || owner.pid !== peer.pid || owner.start === undefined || peer.birth !== owner.start) {
280
+ const message = `the process answering at ${paths.socket} is not the daemon holding ${paths.lock}; nothing was sent`;
281
+ closeSync(peer.fd);
282
+ if (observation.empty)
283
+ throw new EmptyLifetimeRefusal(message, peer.pid, peer.birth);
284
+ throw new EndpointRefusal("PEER_NOT_LOCK_OWNER", message);
285
+ }
264
286
  return adoptPipe(peer.fd);
265
287
  }
266
288
  /** Ask the daemon to sign in, show its prompt, and return its single result. */
@@ -41,6 +41,7 @@ import { automaticUpdates } from "./auto-update.js";
41
41
  import { watchDaemonGeneration } from "./generation.js";
42
42
  import { SPACE_PATTERN } from "./protocol.js";
43
43
  import { nativeDaemonLog } from "./native-log.js";
44
+ import { liveUpdateClosureOwner, readUpdateRecovery } from "@cotal-ai/workspace";
44
45
  export const daemonFlags = [
45
46
  jsonFlag,
46
47
  plainFlag,
@@ -56,23 +57,15 @@ export const daemonFlags = [
56
57
  { name: "no-manager", type: "boolean", description: "setup: connect only the machine service without hosting a Manager" },
57
58
  { name: "space", short: "s", type: "string", value: "<s>", description: "target space (required except for status, where it selects one hosted Manager)" },
58
59
  ];
59
- /** This binary's own version: the nearest package.json above this module (bin/ in a source run). */
60
- export function binVersion() {
61
- let dir = dirname(fileURLToPath(import.meta.url));
62
- for (let i = 0; i < 4; i++) {
63
- try {
64
- const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
65
- if (pkg.name === "cotal-ai" && typeof pkg.version === "string")
66
- return pkg.version;
67
- }
68
- catch (e) {
69
- if (e.code !== "ENOENT")
70
- throw e;
71
- }
72
- dir = dirname(dir);
73
- }
74
- throw new Error("cannot determine the cotal-ai version: no cotal-ai package.json above the daemon module");
75
- }
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; }
76
69
  const peerUid = defaultPeerUid;
77
70
  const peerPid = defaultPeerPid;
78
71
  function target(args) {
@@ -524,6 +517,8 @@ async function serve(args) {
524
517
  const { recoverInterruptedUpdate } = await import("@cotal-ai/cli/update");
525
518
  // Unusable abandoned records retire under the updater lock. Unknown owners remain paused
526
519
  // without blocking startup. A valid snapshot whose restoration failed still waits for repair.
520
+ const deferredRecovery = readUpdateRecovery();
521
+ const observedLiveUpdater = deferredRecovery !== undefined && liveUpdateClosureOwner(deferredRecovery);
527
522
  if (await recoverInterruptedUpdate(undefined, true))
528
523
  throw new Error("interrupted update restored the previous installation; restart the daemon with the restored CLI");
529
524
  const { paths, home } = resolveTarget(args);
@@ -572,6 +567,42 @@ async function serve(args) {
572
567
  await new Promise((resolve, reject) => {
573
568
  let closed = false;
574
569
  let stopWatching = () => { };
570
+ let recoveryTimer;
571
+ let recoveryBusy = false;
572
+ if (observedLiveUpdater) {
573
+ recoveryTimer = setInterval(() => {
574
+ if (closed || recoveryBusy)
575
+ return;
576
+ const record = readUpdateRecovery();
577
+ if (!record) {
578
+ clearInterval(recoveryTimer);
579
+ return;
580
+ }
581
+ if (liveUpdateClosureOwner(record))
582
+ return;
583
+ recoveryBusy = true;
584
+ clearInterval(recoveryTimer);
585
+ process.stderr.write("daemon: observed updater ended; checking guarded interrupted-update recovery\n");
586
+ void running.prepareGenerationRestart().then(() => recoverInterruptedUpdate(undefined, true)).then(async (restored) => {
587
+ if (restored) {
588
+ process.stderr.write("daemon: interrupted update restored the previous installation; restarting the recorded service\n");
589
+ await updates?.close();
590
+ await running.close();
591
+ resolve();
592
+ }
593
+ else if (readUpdateRecovery()) {
594
+ process.stderr.write("daemon: interrupted update remains paused; read daemon status and run `cotal update --self`\n");
595
+ }
596
+ else
597
+ process.stderr.write("daemon: updater completed; no interrupted-update recovery remains\n");
598
+ }).catch((error) => {
599
+ process.stderr.write(`daemon: guarded interrupted-update recovery refused: ${error instanceof Error ? error.message : String(error)}; run \`cotal update --self\`\n`);
600
+ }).finally(() => running.abortGenerationRestart().catch((error) => {
601
+ process.stderr.write(`daemon: interrupted-update admission release refused: ${error instanceof Error ? error.message : String(error)}\n`);
602
+ }));
603
+ }, 1000);
604
+ recoveryTimer.unref();
605
+ }
575
606
  void ownership.then(observation => {
576
607
  if (closed)
577
608
  return;
@@ -597,7 +628,7 @@ async function serve(args) {
597
628
  resolve();
598
629
  }, (line) => process.stderr.write(`${line}\n`), (version, reason) => running.generationPending(version, reason), verified);
599
630
  });
600
- const stop = () => { closed = true; provenance.abort(); stopWatching(); void updates.close().then(() => running.close()).then(resolve, reject); };
631
+ const stop = () => { closed = true; clearInterval(recoveryTimer); provenance.abort(); stopWatching(); void updates.close().then(() => running.close()).then(resolve, reject); };
601
632
  void running.stopped.then(stop, reject);
602
633
  process.once("SIGTERM", stop);
603
634
  process.once("SIGINT", stop);
@@ -3,7 +3,7 @@ import { randomUUID } from "node:crypto";
3
3
  import { defaultComputerName } from "./computer-name.js";
4
4
  import { computerName } from "./name-validation.js";
5
5
  import { arch, platform, release, totalmem } from "node:os";
6
- import { CommandFailure } from "@cotal-ai/workspace";
6
+ import { CommandFailure, readUpdateSettings, setUpdateSetting } from "@cotal-ai/workspace";
7
7
  import { normalizeIdpUrl } from "@cotal-ai/auth";
8
8
  import { loginViaDaemon, updateViaDaemon, openVerified, queryDaemon, readLine } from "./client.js";
9
9
  import { DAEMON_PROTOCOL_VERSION, MAX_LINE_BYTES, EndpointRefusal } from "./endpoint.js";
@@ -18,9 +18,14 @@ export function parseDesktopRequest(value) {
18
18
  const o = value;
19
19
  const simple = ["about", "status", "install", "update-check"].includes(String(o.op));
20
20
  const scoped = ["connect-check", "register", "service-connect", "service-disconnect", "service-status"].includes(String(o.op));
21
- const fields = o.op === "update-release" ? ["op", "version"] : o.op === "update-settings" ? ["op", "auto", "notify"] : o.op === "name" ? ["op", "name"] : o.op === "space-intent" ? ["op", "space", "enabled"] : simple ? ["op"] : scoped ? ["op", "space"] : o.op === "setup" ? ["op", "space", "idp"] : (o.op === "login" || o.op === "logout") ? ["op", "idp"] : o.op === "spaces" ? ["op", "refresh"] : [];
21
+ const fields = o.op === "update-policy" ? ["op", "auto"] : o.op === "update-release" ? ["op", "version"] : o.op === "update-settings" ? ["op", "auto", "notify"] : o.op === "name" ? ["op", "name"] : o.op === "space-intent" ? ["op", "space", "enabled"] : simple ? ["op"] : scoped ? ["op", "space"] : o.op === "setup" ? ["op", "space", "idp"] : (o.op === "login" || o.op === "logout") ? ["op", "idp"] : o.op === "spaces" ? ["op", "refresh"] : [];
22
22
  if (!fields.length || Object.keys(o).some((key) => !fields.includes(key)))
23
23
  throw new Error("unknown operation or field");
24
+ if (o.op === "update-policy") {
25
+ if (o.auto !== undefined && typeof o.auto !== "boolean")
26
+ throw new Error("invalid update preference");
27
+ return { op: "update-policy", ...(o.auto !== undefined ? { auto: o.auto } : {}) };
28
+ }
24
29
  if (o.op === "update-release") {
25
30
  if (typeof o.version !== "string" || !/^\d+\.\d+\.\d+$/.test(o.version))
26
31
  throw new Error("invalid release version");
@@ -80,6 +85,16 @@ export async function readDesktopRequest(input) {
80
85
  clearTimeout(timer);
81
86
  }
82
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
+ }
83
98
  /** Run one app operation through the stock local client. Closing the UI never stops the service. */
84
99
  export async function runDesktopBridge(opts) {
85
100
  const output = opts.output ?? process.stdout;
@@ -92,7 +107,13 @@ export async function runDesktopBridge(opts) {
92
107
  emit({ v: 1, event: "result", ok: false, error: { code: "BAD_REQUEST", message: "The app request was incomplete, oversized or unsupported." } });
93
108
  return;
94
109
  }
110
+ let target;
95
111
  try {
112
+ if (req.op === "update-policy") {
113
+ const settings = req.auto === undefined ? readUpdateSettings() : setUpdateSetting("auto", req.auto);
114
+ emit({ v: 1, event: "result", ok: true, result: settings });
115
+ return;
116
+ }
96
117
  if (req.op === "about") {
97
118
  emit({ v: 1, event: "result", ok: true, result: { version: opts.version, machine: defaultComputerName(), platform: platform(), arch: arch(), release: release(), memoryBytes: totalmem() } });
98
119
  return;
@@ -129,7 +150,8 @@ export async function runDesktopBridge(opts) {
129
150
  emit({ v: 1, event: "result", ok: true, result: { assets } });
130
151
  return;
131
152
  }
132
- const { paths, home } = opts.resolveTarget();
153
+ target = opts.resolveTarget();
154
+ const { paths, home } = target;
133
155
  const client = { paths, peerUid: opts.peerUid, peerPid: opts.peerPid };
134
156
  if (req.op === "install" || req.op === "setup")
135
157
  process.env.PATH = await desktopApplicationPath();
@@ -223,7 +245,9 @@ export async function runDesktopBridge(opts) {
223
245
  catch (e) {
224
246
  const code = e instanceof EndpointRefusal || e instanceof CommandFailure ? e.code : "OPERATION_FAILED";
225
247
  const message = e instanceof CommandFailure && (req.op === "setup" || (req.op === "install" && e.native?.code !== "NOT_ANSWERING")) ? e.message
226
- : 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.")
227
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."
228
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."
229
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)