cotal-ai 0.164.14 → 0.164.16

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 (43) hide show
  1. package/dist/cotal.js +25 -14
  2. package/dist/daemon/auto-update.js +18 -3
  3. package/dist/daemon/command.js +5 -3
  4. package/dist/daemon/execution-preinstall-client.js +57 -0
  5. package/dist/daemon/execution-preinstall.js +69 -0
  6. package/dist/daemon/execution-update.js +93 -0
  7. package/dist/daemon/generation.js +10 -7
  8. package/dist/daemon/install-darwin.js +33 -4
  9. package/dist/daemon/install-identity.js +1 -1
  10. package/dist/daemon/install.js +35 -4
  11. package/dist/daemon/update-entry.js +139 -68
  12. package/dist/daemon/update-generation-win32.js +50 -7
  13. package/dist/daemon/update-generation.js +15 -3
  14. package/dist/execution-preinstall.js +27 -0
  15. package/dist/execution-store.js +5 -1
  16. package/dist/execution-transaction.js +117 -0
  17. package/dist/run.js +7 -0
  18. package/package.json +23 -19
  19. package/seeded-connectors/_shared/docs-bundle.bin +0 -0
  20. package/seeded-connectors/_shared/docs-index.bin +0 -0
  21. package/seeded-connectors/_shared/placements.json +2 -2
  22. package/seeded-connectors/claude/dist/index.js +1 -1
  23. package/seeded-connectors/claude/dist/mcp.cjs +2 -2
  24. package/seeded-connectors/claude/package.json +1 -1
  25. package/seeded-connectors/codex/dist/host.js +2 -2
  26. package/seeded-connectors/codex/dist/index.js +1 -1
  27. package/seeded-connectors/codex/dist/personal.js +2 -2
  28. package/seeded-connectors/codex/package.json +1 -1
  29. package/seeded-connectors/hermes/dist/index.js +1 -1
  30. package/seeded-connectors/hermes/dist/launch.js +2 -2
  31. package/seeded-connectors/hermes/package.json +1 -1
  32. package/seeded-connectors/hermes/plugin/cotal/_sidecar/standalone.cjs +2 -2
  33. package/seeded-connectors/jcode/dist/host.js +2 -2
  34. package/seeded-connectors/jcode/dist/index.js +1 -1
  35. package/seeded-connectors/jcode/dist/mcp.js +1 -1
  36. package/seeded-connectors/jcode/package.json +1 -1
  37. package/seeded-connectors/opencode/dist/index.js +1 -1
  38. package/seeded-connectors/opencode/dist/plugin/index.js +2 -2
  39. package/seeded-connectors/opencode/package.json +1 -1
  40. package/seeded-connectors/pi/dist/index.js +2 -2
  41. package/seeded-connectors/pi/dist/standalone.js +2 -2
  42. package/seeded-connectors/pi/package.json +1 -1
  43. package/seeded-connectors/web/package.json +1 -1
package/dist/cotal.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { createHash } from "node:crypto";
3
- import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync } from "node:fs";
3
+ import { closeSync, constants, existsSync, fstatSync, lstatSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync } from "node:fs";
4
4
  import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
5
  import { fileURLToPath, pathToFileURL } from "node:url";
6
6
  import { setFlagsFromString } from "node:v8";
@@ -55,7 +55,7 @@ export function executionStore(root) {
55
55
  }
56
56
  /** Enumerate the whole package, including dependencies, without following a link outside it. */
57
57
  export function executionInventory(root) {
58
- const physical = realpathSync(root);
58
+ const physical = realpathSync.native(root);
59
59
  const rows = [];
60
60
  const walk = (directory, prefix) => {
61
61
  protectedExecutionEntry(directory);
@@ -65,7 +65,7 @@ export function executionInventory(root) {
65
65
  if (entry.isDirectory())
66
66
  walk(path, name);
67
67
  else if (entry.isSymbolicLink()) {
68
- const target = readlinkSync(path), resolved = realpathSync(path), suffix = relative(physical, resolved);
68
+ const target = readlinkSync(path), resolved = realpathSync.native(path), suffix = relative(physical, resolved);
69
69
  if (isAbsolute(target) || suffix === ".." || suffix.startsWith(`..${sep}`) || isAbsolute(suffix))
70
70
  throw new Error(`execution inventory link escapes its package: ${name}`);
71
71
  rows.push({ path: name, link: target });
@@ -80,10 +80,11 @@ export function executionInventory(root) {
80
80
  return rows;
81
81
  }
82
82
  export function executionLaunchBinding(root, entry) {
83
- const logical = resolve(entry), physical = realpathSync(logical);
84
- if (physical !== join(realpathSync(root), "dist", "cotal.js"))
83
+ const logical = resolve(entry), physical = realpathSync.native(logical);
84
+ const canonicalRoot = realpathSync.native(root);
85
+ if (physical !== join(canonicalRoot, "dist", "cotal.js"))
85
86
  throw new Error("execution launch route does not resolve to this bootstrap");
86
- let path = join(realpathSync(root), "package.json");
87
+ let path = join(canonicalRoot, "package.json");
87
88
  for (let current = dirname(logical); current !== dirname(current); current = dirname(current)) {
88
89
  if (lstatSync(current).isSymbolicLink()) {
89
90
  path = current;
@@ -94,13 +95,18 @@ export function executionLaunchBinding(root, entry) {
94
95
  return { entry: logical, path, dev: String(info.dev), ino: String(info.ino), birth: String(info.birthtimeNs), ctime: String(info.ctimeNs) };
95
96
  }
96
97
  export function executionDescriptorPath(root) {
97
- return join(executionStore(root), `.active-${executionSha256(realpathSync(root))}.json`);
98
+ return join(executionStore(root), `.active-${executionSha256(realpathSync.native(root))}.json`);
98
99
  }
99
100
  /** Select a verified program, or the installed first generation when no matching descriptor exists. */
100
101
  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))
102
+ const installed = realpathSync.native(root), descriptorPath = executionDescriptorPath(installed);
103
+ const initial = () => ({ root: installed, entry: import.meta.url.endsWith(".ts") && installed === realpathSync.native(dirname(fileURLToPath(import.meta.url)))
103
104
  ? join(installed, "cotal-program.ts") : join(installed, "dist", "cotal-program.js"), retained: false });
105
+ if (existsSync(join(installed, "desktop-runtime.json"))) {
106
+ if (existsSync(descriptorPath) || existsSync(executionStore(installed)))
107
+ throw new Error("retained execution generations are unavailable on the desktop runtime");
108
+ return initial();
109
+ }
104
110
  let value;
105
111
  try {
106
112
  value = executionRecord(descriptorPath);
@@ -152,14 +158,15 @@ export function selectExecutionProgram(root) {
152
158
  throw new Error("unsafe execution generation directory");
153
159
  protectedExecutionEntry(path);
154
160
  }
161
+ const canonicalSelected = realpathSync.native(selected);
155
162
  const inventory = executionRecord(join(container, "inventory.json"));
156
163
  if (!Array.isArray(inventory) || executionSha256(JSON.stringify(inventory)) !== generation.inventorySha256 ||
157
- JSON.stringify(executionInventory(selected)) !== JSON.stringify(inventory))
164
+ JSON.stringify(executionInventory(canonicalSelected)) !== JSON.stringify(inventory))
158
165
  throw new Error("retained execution inventory differs");
159
- const meta = object(JSON.parse(readFileSync(join(selected, "package.json"), "utf8")));
166
+ const meta = object(JSON.parse(readFileSync(join(canonicalSelected, "package.json"), "utf8")));
160
167
  if (meta.name !== "cotal-ai" || meta.version !== generation.version)
161
168
  throw new Error("retained execution manifest differs");
162
- return { root: selected, entry: join(selected, "dist", "cotal-program.js"), retained: true };
169
+ return { root: canonicalSelected, entry: join(canonicalSelected, "dist", "cotal-program.js"), retained: true };
163
170
  }
164
171
  const executionStarted = Symbol.for("cotal.execution.started");
165
172
  /** Whether Node was started on this file. Both sides go through the native canonical path, because
@@ -183,11 +190,15 @@ export function startExecutionProgram() {
183
190
  }
184
191
  if (selected) {
185
192
  const direct = startedHere();
186
- if (!import.meta.url.endsWith(".ts"))
193
+ if (!import.meta.url.endsWith(".ts")) {
194
+ const logicalEntry = realpathSync.native(fileURLToPath(import.meta.url));
195
+ const loadedEntry = realpathSync.native(join(selected.root, "dist", "cotal.js"));
196
+ const launchEntry = direct ? resolve(process.argv[1]) : logicalEntry;
187
197
  Object.defineProperty(globalThis, Symbol.for("cotal.execution.identity"), {
188
- value: Object.freeze({ logicalEntry: fileURLToPath(import.meta.url), launchEntry: direct ? resolve(process.argv[1]) : fileURLToPath(import.meta.url), loadedEntry: join(selected.root, "dist", "cotal.js") }),
198
+ value: Object.freeze({ logicalEntry, launchEntry, loadedEntry }),
189
199
  configurable: false, writable: false,
190
200
  });
201
+ }
191
202
  if (selected.retained || !direct)
192
203
  process.argv[1] = join(selected.root, "dist", "cotal.js");
193
204
  void import(pathToFileURL(selected.entry).href);
@@ -3,10 +3,18 @@ import { readFileSync, existsSync, closeSync, ftruncateSync } from "node:fs";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { join } from "node:path";
5
5
  import { openPrivateAppend, writeSecretFileAtomic } from "@cotal-ai/core";
6
- import { checkForUpdate, homeCotalDir, newerUpdate, readUpdateCheck, readUpdateRecovery, readUpdateSettings, recoveryDisposition, UPDATE_DAY_MS, UPDATE_HOUR_MS } from "@cotal-ai/workspace";
6
+ import { checkForUpdate, homeCotalDir, loadExtensionsManifest, newerUpdate, readUpdateCheck, readUpdateRecovery, readUpdateSettings, recoveryDisposition, UPDATE_DAY_MS, UPDATE_HOUR_MS } from "@cotal-ai/workspace";
7
7
  import { cleanWindowsUpdate, startWindowsUpdate } from "./update-windows.js";
8
8
  import { WINDOWS_INTERRUPTED_UPDATE, readWindowsUpdatePause } from "@cotal-ai/workspace";
9
9
  import { cleanLaunchUpdate, startLaunchUpdate } from "./update-launchd.js";
10
+ function reconciliationPending(version) {
11
+ try {
12
+ return loadExtensionsManifest().extensions.some((entry) => entry.pkg.startsWith("@cotal-ai/") && entry.version !== version);
13
+ }
14
+ catch {
15
+ return false;
16
+ }
17
+ }
10
18
  /** Schedule only the existing updater. Manager preparation holds its native empty-seat admission fence. */
11
19
  export function automaticUpdates(host) {
12
20
  const desktop = existsSync(fileURLToPath(new URL("../../desktop-runtime.json", import.meta.url)));
@@ -129,6 +137,12 @@ export function automaticUpdates(host) {
129
137
  }
130
138
  }
131
139
  const settings = readUpdateSettings();
140
+ try {
141
+ const recorded = JSON.parse(readFileSync(file, "utf8"));
142
+ if (recorded && Number.isInteger(recorded.failures) && recorded.failures >= 0 && typeof recorded.result === "string" && Number.isFinite(recorded.next))
143
+ state = recorded;
144
+ }
145
+ catch { /* Keep the last validated attempt state when unreadable. */ }
132
146
  const cached = process.env.COTAL_NO_UPDATE_CHECK !== "1" && (settings.auto || settings.notify) ? await checkForUpdate() : readUpdateCheck();
133
147
  const recovery = readUpdateRecovery();
134
148
  const retiring = recovery !== undefined && recoveryDisposition(recovery).action === "retire";
@@ -148,6 +162,7 @@ export function automaticUpdates(host) {
148
162
  persist();
149
163
  return;
150
164
  }
165
+ const reconciling = !retiring && !newerUpdate(cached.latest, host.version) && reconciliationPending(host.version);
151
166
  if (state.version !== cached.latest)
152
167
  state = { version: cached.latest, failures: 0, result: "new release observed", next: 0 };
153
168
  if (!retiring && state.failures >= 2) {
@@ -155,12 +170,12 @@ export function automaticUpdates(host) {
155
170
  persist();
156
171
  return;
157
172
  }
158
- if (!retiring && !newerUpdate(cached.latest, host.version)) {
173
+ if (!retiring && !reconciling && !newerUpdate(cached.latest, host.version)) {
159
174
  state = { ...state, result: "up to date", next: Date.now() + UPDATE_DAY_MS + Math.random() * UPDATE_HOUR_MS };
160
175
  persist();
161
176
  return;
162
177
  }
163
- if (!retiring && Date.now() - (cached.firstSeenAt ?? Date.now()) < UPDATE_HOUR_MS) {
178
+ if (!retiring && !reconciling && Date.now() - (cached.firstSeenAt ?? Date.now()) < UPDATE_HOUR_MS) {
164
179
  state = { ...state, result: "waiting for release hold", next: (cached.firstSeenAt ?? Date.now()) + UPDATE_HOUR_MS };
165
180
  persist();
166
181
  return;
@@ -514,7 +514,8 @@ async function setupUnderClosure(args) {
514
514
  ] }));
515
515
  }
516
516
  async function serve(args) {
517
- const { recoverInterruptedUpdate } = await import("@cotal-ai/cli/update");
517
+ const { recoverInterruptedUpdate, updateRuntime } = await import("@cotal-ai/cli/update");
518
+ const { recoverExecutionUpdate } = await import("./execution-update.js");
518
519
  // Unusable abandoned records retire under the updater lock. Unknown owners remain paused
519
520
  // without blocking startup. A valid snapshot whose restoration failed still waits for repair.
520
521
  let automaticCustodyPaused = false;
@@ -525,7 +526,8 @@ async function serve(args) {
525
526
  }
526
527
  const deferredRecovery = readUpdateRecovery();
527
528
  const observedLiveUpdater = !automaticCustodyPaused && deferredRecovery !== undefined && liveUpdateClosureOwner(deferredRecovery);
528
- if (!automaticCustodyPaused && await recoverInterruptedUpdate(undefined, true))
529
+ const recoveryRuntime = { ...updateRuntime, recoverExecution: recoverExecutionUpdate };
530
+ if (!automaticCustodyPaused && await recoverInterruptedUpdate(recoveryRuntime, true))
529
531
  throw new Error("interrupted update restored the previous installation; restart the daemon with the restored CLI");
530
532
  const { paths, home } = resolveTarget(args);
531
533
  let running;
@@ -589,7 +591,7 @@ async function serve(args) {
589
591
  recoveryBusy = true;
590
592
  clearInterval(recoveryTimer);
591
593
  process.stderr.write("daemon: observed updater ended; checking guarded interrupted-update recovery\n");
592
- void running.prepareGenerationRestart().then(() => recoverInterruptedUpdate(undefined, true)).then(async (restored) => {
594
+ void running.prepareGenerationRestart().then(() => recoverInterruptedUpdate(recoveryRuntime, true)).then(async (restored) => {
593
595
  if (restored) {
594
596
  process.stderr.write("daemon: interrupted update restored the previous installation; restarting the recorded service\n");
595
597
  await updates?.close();
@@ -0,0 +1,57 @@
1
+ import { spawn } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { readFileSync, realpathSync } from "node:fs";
4
+ import { isAbsolute, join, relative, sep } from "node:path";
5
+ /** Execute only the retained package's declared check, with a bounded single identity-bound receipt. */
6
+ export async function targetExecutionPreinstall(root, installedEntry, daemonArgv, flags) {
7
+ const meta = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
8
+ if (meta.cotalPreinstall?.v !== 1 || typeof meta.cotalPreinstall.entry !== "string")
9
+ throw new Error("target declares no supported read-only pre-install check; run its installer");
10
+ const entry = realpathSync(join(root, meta.cotalPreinstall.entry));
11
+ const rel = relative(realpathSync(root), entry);
12
+ if (isAbsolute(rel) || rel === ".." || rel.startsWith(`..${sep}`))
13
+ throw new Error("target pre-install entry escapes retained package");
14
+ const request = { v: 1, nonce: randomBytes(16).toString("hex"), installedEntry,
15
+ daemonArgv, flags: Object.fromEntries(Object.entries(flags).filter(([key, value]) => ["space", "server", "creds", "on"].includes(key) && typeof value === "string")),
16
+ };
17
+ const result = await new Promise((resolve, reject) => {
18
+ const child = spawn(process.execPath, [entry, JSON.stringify(request)], { env: { ...process.env, COTAL_SKIP_CONNECTOR_SEED: "1" }, stdio: ["ignore", "pipe", "pipe"] });
19
+ let stdout = "", stderr = "", failure = "";
20
+ let escalation;
21
+ const terminate = () => { child.kill("SIGTERM"); escalation ??= setTimeout(() => child.kill("SIGKILL"), 2000); };
22
+ const collect = (chunk, stream) => {
23
+ if (failure)
24
+ return;
25
+ if (stream === "stdout")
26
+ stdout += chunk.toString();
27
+ else
28
+ stderr += chunk.toString();
29
+ if (Buffer.byteLength(stdout) + Buffer.byteLength(stderr) > 1024 * 1024) {
30
+ failure = "target pre-install output exceeded its limit";
31
+ terminate();
32
+ }
33
+ };
34
+ child.stdout.on("data", chunk => collect(chunk, "stdout"));
35
+ child.stderr.on("data", chunk => collect(chunk, "stderr"));
36
+ const timer = setTimeout(() => { failure = "target pre-install checks timed out"; terminate(); }, 120_000);
37
+ const clear = () => { clearTimeout(timer); if (escalation)
38
+ clearTimeout(escalation); };
39
+ child.once("error", error => { clear(); reject(error); });
40
+ child.once("close", status => { clear(); if (failure)
41
+ reject(new Error(failure));
42
+ else
43
+ resolve({ status, stdout, stderr }); });
44
+ });
45
+ if (result.status !== 0)
46
+ throw new Error(`target pre-install checks refused: ${result.stderr.trim()}`);
47
+ const receipts = result.stdout.split("\n").filter(line => line.startsWith("COTAL_PREINSTALL_RESULT "));
48
+ if (receipts.length !== 1)
49
+ throw new Error("target pre-install checks returned no unique result");
50
+ const receipt = JSON.parse(receipts[0].slice("COTAL_PREINSTALL_RESULT ".length));
51
+ if (receipt.v !== 1 || receipt.nonce !== request.nonce || receipt.installedEntry !== installedEntry ||
52
+ !Array.isArray(receipt.hostedSpaces) || receipt.hostedSpaces.some(space => typeof space !== "string") ||
53
+ !Number.isSafeInteger(receipt.occupied) || receipt.occupied < 0 ||
54
+ receipt.daemon !== undefined && (!Number.isSafeInteger(receipt.daemon.pid) || receipt.daemon.pid <= 0 || typeof receipt.daemon.start !== "string" || !receipt.daemon.start))
55
+ throw new Error("target pre-install checks returned invalid evidence");
56
+ return receipt;
57
+ }
@@ -0,0 +1,69 @@
1
+ import { join } from "node:path";
2
+ import { withIdpSessionDir, withRemoteExchangeRetry } from "@cotal-ai/auth";
3
+ import { localUpdateManagers, readManagerContinuity, reportRunningManagers } from "@cotal-ai/cli/update";
4
+ import { CommandFailure, homeCotalDir, resolveControlTarget } from "@cotal-ai/workspace";
5
+ import { askManager } from "@cotal-ai/workspace/control";
6
+ import { queryDaemon } from "./client.js";
7
+ import { daemonPaths, EndpointRefusal } from "./endpoint.js";
8
+ import { preflightInstalledDaemon } from "./install.js";
9
+ import { processBirth, readLifetimeRecord } from "./lifetime.js";
10
+ /** Read-only admission. Consent and all Manager/daemon mutation remain in the parent transaction. */
11
+ export async function readExecutionPreinstall(request) {
12
+ preflightInstalledDaemon({ state: join(homeCotalDir(), "daemon") }, undefined, request.daemonArgv);
13
+ return withRemoteExchangeRetry(async () => {
14
+ const readOne = (flags) => readManagerContinuity(flags, { readOnly: true, retainGraph: true, installedEntry: request.installedEntry });
15
+ const paths = daemonPaths();
16
+ let reply;
17
+ try {
18
+ reply = await queryDaemon({ paths });
19
+ }
20
+ catch (error) {
21
+ if (!(error instanceof EndpointRefusal) || !["NOT_RUNNING", "NO_RUNTIME_DIR"].includes(error.code))
22
+ throw error;
23
+ await reportRunningManagers(request.flags, readOne, flags => localUpdateManagers(flags, request.installedEntry));
24
+ return { hostedSpaces: [], occupied: 0 };
25
+ }
26
+ if (!reply.ok)
27
+ throw new Error(`machine daemon custody is unreadable: ${reply.error.message}`);
28
+ const lifetime = readLifetimeRecord(paths.lock);
29
+ if (!lifetime?.start || lifetime.pid !== reply.result.pid || processBirth(lifetime.pid) !== lifetime.start)
30
+ throw new Error("machine daemon lifetime changed during pre-install check");
31
+ const active = (reply.result.managers ?? []).filter(manager => manager.pid !== undefined);
32
+ let occupied = 0;
33
+ for (const manager of active) {
34
+ if (!manager.instanceId)
35
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", `hosted Manager ${manager.space} has no verified instance identity`);
36
+ await withIdpSessionDir(homeCotalDir(), async () => {
37
+ const target = await resolveControlTarget({ space: manager.space }, "control-caller-privileged", manager.instanceId, { onRefusal: "throw", readOnly: true });
38
+ const status = await askManager({ versionSkew: (text) => text, roster: async () => [] }, manager.space, target.server, "managerStatus", undefined, target.auth, "owner", 3000, { instanceId: manager.instanceId });
39
+ if (!status.ok)
40
+ throw new Error(status.error ?? "hosted Manager status did not answer");
41
+ const count = status.data.agentCount;
42
+ if (!Number.isSafeInteger(count) || count < 0)
43
+ throw new Error("hosted Manager returned an invalid agent count");
44
+ occupied += count;
45
+ });
46
+ }
47
+ if (process.platform === "linux") {
48
+ for (const manager of localUpdateManagers(request.flags, request.installedEntry)) {
49
+ if (active.some(hosted => hosted.instanceId === manager.instanceId))
50
+ continue;
51
+ await readOne({ ...request.flags, space: manager.space, server: manager.server, on: manager.instanceId });
52
+ }
53
+ }
54
+ else {
55
+ await reportRunningManagers(request.flags, readOne);
56
+ if (typeof request.flags.space !== "string" && typeof request.flags.creds !== "string") {
57
+ const { readMeshRegistry } = await import("@cotal-ai/workspace");
58
+ for (const entry of readMeshRegistry().entries) {
59
+ if (active.some(manager => manager.space === entry.space))
60
+ continue;
61
+ await readOne({ ...request.flags, space: entry.space });
62
+ }
63
+ }
64
+ }
65
+ if (processBirth(lifetime.pid) !== lifetime.start)
66
+ throw new Error("machine daemon lifetime changed before pre-install receipt");
67
+ return { daemon: { pid: lifetime.pid, start: lifetime.start }, hostedSpaces: active.map(manager => manager.space), occupied };
68
+ });
69
+ }
@@ -0,0 +1,93 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { existsSync, realpathSync } from "node:fs";
3
+ import { dirname, join, basename } from "node:path";
4
+ import { logicalExecutionEntry, executionIdentity, cmdSpawnSpec } from "@cotal-ai/workspace";
5
+ import { updateRuntime, verifyGlobalEntry } from "@cotal-ai/cli/update";
6
+ import { assertExecutionDestination, executionStagingPrefix, journalExecutionTransaction, publishExecutionTransaction, readExecutionTransaction, retainExecutionGeneration, retireSupersededExecutionDescriptor } from "../execution-transaction.js";
7
+ import { executionInventory, executionSha256 } from "../cotal.js";
8
+ import { daemonServeArgv } from "./install.js";
9
+ import { readExecutionPreinstall } from "./execution-preinstall.js";
10
+ import { targetExecutionPreinstall } from "./execution-preinstall-client.js";
11
+ export function executionInstallRoot() {
12
+ const entry = logicalExecutionEntry();
13
+ if (!entry)
14
+ throw new Error("staged update requires the installed built-ins bootstrap; use the owning installer");
15
+ return dirname(dirname(entry));
16
+ }
17
+ export function preflightExecutionUpdate() {
18
+ const root = executionInstallRoot();
19
+ if (existsSync(join(root, "desktop-runtime.json")))
20
+ throw new Error("staged execution updates are unavailable on the desktop runtime");
21
+ assertExecutionDestination(root);
22
+ if (basename(dirname(root)) !== "node_modules")
23
+ throw new Error("staged update requires an installed npm or pnpm package; use the owning installer");
24
+ }
25
+ function verifySelected(root, version) {
26
+ const entry = join(root, "dist/cotal.js");
27
+ const result = spawnSync(process.execPath, [entry, "--version"], { env: { ...process.env, COTAL_SKIP_CONNECTOR_SEED: "1" }, encoding: "utf8", timeout: 30_000 });
28
+ if (result.status !== 0 || result.stdout.split(/\r?\n/, 1)[0] !== `cotal-ai ${version}`)
29
+ throw new Error(`selected execution did not confirm cotal-ai@${version}: ${result.stderr}`);
30
+ }
31
+ /** Prepare one complete real npm package. No live package file is passed to npm for reification. */
32
+ export async function prepareExecutionUpdate(version, globalRoot, checked) {
33
+ const installed = executionInstallRoot();
34
+ if (realpathSync.native(join(globalRoot, "cotal-ai")) !== installed)
35
+ throw new Error("staged update global root differs from logical installation");
36
+ const staging = executionStagingPrefix(installed);
37
+ const npm = cmdSpawnSpec("npm", ["install", "-g", "--prefix", staging, `cotal-ai@${version}`, "--ignore-scripts", "--no-audit", "--no-fund", "--fetch-retries=0", "--fetch-timeout=15000"]);
38
+ const result = await updateRuntime.spawnGlobal(globalRoot, "install", npm.file, npm.args, process.env, false, npm.windowsVerbatimArguments);
39
+ if (result.status !== 0)
40
+ throw new Error(`target staging failed: ${result.error ?? result.stderr ?? result.stdout}`);
41
+ const source = join(staging, "lib/node_modules/cotal-ai");
42
+ verifyGlobalEntry(join(staging, "lib/node_modules"), version);
43
+ verifySelected(source, version);
44
+ const generation = retainExecutionGeneration(installed, source);
45
+ let journal;
46
+ let accepted = false;
47
+ const getJournal = () => {
48
+ if (!accepted)
49
+ throw new Error("execution journal requested before target checks accepted");
50
+ return journal ??= journalExecutionTransaction(installed, generation, executionIdentity()?.launchEntry ?? logicalExecutionEntry());
51
+ };
52
+ return {
53
+ entry: join(installed, "dist/cotal.js"),
54
+ get journal() { return getJournal(); },
55
+ async preflight(flags) {
56
+ const installedEntry = logicalExecutionEntry();
57
+ const daemonArgv = daemonServeArgv(undefined);
58
+ const floor = await readExecutionPreinstall({ v: 1, nonce: "0".repeat(32), installedEntry, daemonArgv, flags });
59
+ const receipt = await targetExecutionPreinstall(generation.root, installedEntry, daemonArgv, flags);
60
+ if (JSON.stringify(floor.daemon) !== JSON.stringify(receipt.daemon))
61
+ throw new Error("machine daemon lifetime changed during target pre-install checks");
62
+ if (executionSha256(JSON.stringify(executionInventory(generation.root))) !== generation.inventorySha256)
63
+ throw new Error("target changed during pre-install checks");
64
+ checked(receipt);
65
+ accepted = true;
66
+ },
67
+ publish() {
68
+ if (executionSha256(JSON.stringify(executionInventory(generation.root))) !== generation.inventorySha256)
69
+ throw new Error("target changed before execution publication");
70
+ publishExecutionTransaction(installed, getJournal());
71
+ },
72
+ restore() { if (!journal)
73
+ throw new Error("execution transaction has no rollback journal"); publishExecutionTransaction(installed, journal, true); },
74
+ verify(expected) { verifySelected(installed, expected); },
75
+ };
76
+ }
77
+ export function recoverExecutionUpdate(path) {
78
+ const installed = executionInstallRoot();
79
+ const record = readExecutionTransaction(installed, path);
80
+ const previous = record.previous.descriptor?.generation.version ?? JSON.parse(record.previous.manifest).version;
81
+ return {
82
+ entry: join(installed, "dist/cotal.js"), journal: path,
83
+ async preflight() { throw new Error("a recovering execution transaction cannot be prepared again"); },
84
+ publish() { throw new Error("a recovering execution transaction cannot publish a new target"); },
85
+ restore() { publishExecutionTransaction(installed, path, true); },
86
+ verify(version) {
87
+ if (version !== previous)
88
+ throw new Error("execution recovery previous version differs");
89
+ verifySelected(installed, version);
90
+ },
91
+ };
92
+ }
93
+ export { retireSupersededExecutionDescriptor };
@@ -2,11 +2,13 @@
2
2
  import { spawn } from "node:child_process";
3
3
  import { readFileSync } from "node:fs";
4
4
  import { dirname, join } from "node:path";
5
- import { updateActivationBlocked } from "@cotal-ai/workspace";
5
+ import { loadExtensionsManifest, logicalExecutionEntry, updateActivationBlocked } from "@cotal-ai/workspace";
6
6
  import { globalConfigDir } from "@cotal-ai/core";
7
+ import { selectExecutionProgram } from "../cotal.js";
7
8
  import { fileURLToPath } from "node:url";
8
9
  export function installedGenerationVersion() {
9
- const pkg = JSON.parse(readFileSync(packageFile(), "utf8"));
10
+ const selected = selectExecutionProgram(dirname(packageFile()));
11
+ const pkg = JSON.parse(readFileSync(join(selected.root, "package.json"), "utf8"));
10
12
  if (typeof pkg.version !== "string" || !pkg.version)
11
13
  throw new Error("the daemon's CLI version is not identifiable");
12
14
  return pkg.version;
@@ -29,7 +31,8 @@ export async function reconcileHostedConnectors(version) {
29
31
  throw new ReplacedDaemonGeneration(version, installed);
30
32
  try {
31
33
  const stamp = JSON.parse(readFileSync(join(globalConfigDir(), "seed", "stamp.json"), "utf8"));
32
- if (stamp?.generation === version)
34
+ const skewed = loadExtensionsManifest().extensions.some((entry) => entry.pkg.startsWith("@cotal-ai/") && entry.version !== version);
35
+ if (stamp?.generation === version && !skewed)
33
36
  return;
34
37
  }
35
38
  catch (error) {
@@ -39,6 +42,9 @@ export async function reconcileHostedConnectors(version) {
39
42
  await reconcileInstalledGeneration();
40
43
  }
41
44
  function packageFile() {
45
+ const logical = logicalExecutionEntry();
46
+ if (logical)
47
+ return join(dirname(dirname(logical)), "package.json");
42
48
  let dir = dirname(fileURLToPath(import.meta.url));
43
49
  for (let i = 0; i < 4; i++, dir = dirname(dir)) {
44
50
  const path = join(dir, "package.json");
@@ -99,10 +105,7 @@ export function watchDaemonGeneration(version, changed, report, pending = () =>
99
105
  }
100
106
  let next;
101
107
  try {
102
- const pkg = JSON.parse(readFileSync(file, "utf8"));
103
- if (pkg.name !== "cotal-ai" || typeof pkg.version !== "string")
104
- return;
105
- next = pkg.version;
108
+ next = installedGenerationVersion();
106
109
  }
107
110
  catch {
108
111
  return;
@@ -18,11 +18,11 @@
18
18
  import { createHash } from "node:crypto";
19
19
  import { lstatSync, readFileSync, rmSync } from "node:fs";
20
20
  import { homedir, userInfo } from "node:os";
21
- import { basename, isAbsolute, join } from "node:path";
21
+ import { basename, dirname, isAbsolute, join } from "node:path";
22
22
  import { fileURLToPath } from "node:url";
23
23
  import { ensureDirNoSymlink, realDirNoSymlink } from "@cotal-ai/core";
24
24
  import { darwinLaunchdJob } from "@cotal-ai/seat";
25
- import { CommandFailure } from "@cotal-ai/workspace";
25
+ import { CommandFailure, logicalExecutionEntry } from "@cotal-ai/workspace";
26
26
  import { assertSystemdSource, createSystemdSource } from "@cotal-ai/cli";
27
27
  const LAUNCHCTL = "/bin/launchctl";
28
28
  /** `launchctl print`'s exit status when the domain has no service with that label. */
@@ -50,8 +50,9 @@ export function renderLaunchAgent(input) {
50
50
  }
51
51
  // launchd's job dictionary omits WorkingDirectory. Carry it in the exact argument vector instead;
52
52
  // this entry changes directory before importing the CLI, including any cwd-sensitive setup.
53
- // Resolve our entry from this module, not argv's CLI symlink (a global install may live in bin/).
54
- const bootstrap = fileURLToPath(new URL("../daemon-cwd.js", import.meta.url));
53
+ // The validated daemon argv names the logical installation, including from a retained process.
54
+ const logical = logicalExecutionEntry();
55
+ const bootstrap = logical ? join(dirname(logical), "daemon-cwd.js") : fileURLToPath(new URL("../daemon-cwd.js", import.meta.url));
55
56
  const argv = [...input.argv.slice(0, daemon - 1), bootstrap, input.workingDirectory, ...input.argv.slice(daemon)];
56
57
  const entry = (key, value) => `<key>${key}</key>${str(value)}`;
57
58
  const text = [
@@ -211,6 +212,34 @@ export function launchAgentService(run, lookup = darwinLaunchdJob) {
211
212
  check(receipt) {
212
213
  owned(receipt);
213
214
  },
215
+ isEnabled(receipt) {
216
+ const id = uid();
217
+ owned(receipt);
218
+ const read = run(LAUNCHCTL, ["print-disabled", `gui/${id}`]);
219
+ if (read.status !== 0) {
220
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", `launchd's GUI domain gui/${id} did not confirm disabled services for ${receipt.unit} (${read.detail}); nothing was started`);
221
+ }
222
+ const match = /^\s*disabled services = \{([\s\S]*)\}\s*$/.exec(read.stdout);
223
+ if (!match) {
224
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", `launchd's GUI domain gui/${id} returned an unparsed print-disabled block for ${receipt.unit}; nothing was started`);
225
+ }
226
+ const matches = [];
227
+ for (const rawLine of match[1].split("\n")) {
228
+ const line = rawLine.trim();
229
+ if (!line)
230
+ continue;
231
+ const entry = /^"([^"\r\n]+)" => (true|false|disabled|enabled)$/.exec(line);
232
+ if (!entry) {
233
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", `launchd's GUI domain gui/${id} returned an unparsed disabled entry (${line}) while checking ${receipt.unit}; nothing was started`);
234
+ }
235
+ if (entry[1] === receipt.unit)
236
+ matches.push(entry[2]);
237
+ }
238
+ if (matches.length > 1)
239
+ throw new CommandFailure("refused", "CONFLICT", `launchd returned duplicate disabled entries for ${receipt.unit}; nothing was started`);
240
+ const token = matches[0] ?? "false";
241
+ return token === "false" || token === "enabled";
242
+ },
214
243
  start(receipt) {
215
244
  const id = uid();
216
245
  if (owned(receipt))
@@ -46,5 +46,5 @@ export function recordedSourceIdentity(receipt, mechanism, expected) {
46
46
  catch {
47
47
  return path;
48
48
  } };
49
- return { same: canonical(installed.executable) === canonical(current.executable) && canonical(installed.entry) === canonical(current.entry), installed: `${installed.executable} ${installed.entry}`, current: `${current.executable} ${current.entry}` };
49
+ return { same: canonical(installed.executable) === canonical(current.executable) && canonical(installed.entry) === canonical(current.entry), installed: `${installed.executable} ${installed.entry}`, installedEntry: installed.entry, current: `${current.executable} ${current.entry}` };
50
50
  }
@@ -40,7 +40,7 @@ import { Worker } from "node:worker_threads";
40
40
  import { setTimeout as delay } from "node:timers/promises";
41
41
  import { randomUUID } from "node:crypto";
42
42
  import { mkSecretDir, writeSecretFile, writeSecretFileAtomic } from "@cotal-ai/core";
43
- import { codeSpan, CommandFailure, readLocalRecordSource } from "@cotal-ai/workspace";
43
+ import { codeSpan, CommandFailure, executionIdentity, readLocalRecordSource } from "@cotal-ai/workspace";
44
44
  import { assertSystemdSource, assertSystemdSourceDirectory, createSystemdSource, daemonArgv, submitSystemdUnitControl, submitSystemdUnitRegistration, systemdUserUnitDirectory } from "@cotal-ai/cli";
45
45
  import { checkDir, EndpointRefusal, DAEMON_PROTOCOL_VERSION } from "./endpoint.js";
46
46
  import { isStoppingLifetime, openVerified, readLine } from "./client.js";
@@ -355,8 +355,33 @@ export async function startInstalled(paths, daemonHome, expectedVersion, report)
355
355
  submitSystemdUnitControl("start", plan.unit);
356
356
  return plan;
357
357
  }
358
+ /** Start only an enabled, same-installation POSIX unit or LaunchAgent during update, never overriding an operator disable. */
359
+ export async function startEnabledInstalled(paths, daemonHome) {
360
+ assertDesktopSetupComplete();
361
+ const recorded = recordedUnit(paths, daemonHome);
362
+ const identity = recordedDaemonIdentity(recorded);
363
+ if (!identity.same)
364
+ throw new CommandFailure("refused", "CONFLICT", `the recorded daemon source names another installation (${identity.installed}); update did not start it`);
365
+ const { receipt, plan, service } = recorded;
366
+ if (service) {
367
+ if (service.isEnabled && !service.isEnabled(receipt))
368
+ return { started: false, unit: plan.unit, state: "disabled" };
369
+ service.start(receipt);
370
+ return { started: true, unit: plan.unit, state: "enabled" };
371
+ }
372
+ const read = nativeRun("systemctl", ["--user", "--no-ask-password", "--no-pager", "show", plan.unit, "--property=UnitFileState", "--value"]);
373
+ if (read.status !== 0)
374
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", `systemctl --user show ${plan.unit} did not confirm UnitFileState (${read.detail}); nothing was started`);
375
+ const state = read.stdout.trim();
376
+ if (!state)
377
+ throw new CommandFailure("refused", "TARGET_UNAVAILABLE", `systemctl --user show ${plan.unit} reported an empty UnitFileState; nothing was started`);
378
+ if (state !== "enabled")
379
+ return { started: false, unit: plan.unit, state };
380
+ submitSystemdUnitControl("start", plan.unit);
381
+ return { started: true, unit: plan.unit, state: "enabled" };
382
+ }
358
383
  /** Validate a present service receipt from persistent state without runtime discovery. Return false only when absent. */
359
- export function preflightInstalledDaemon(paths, daemonHome) {
384
+ export function preflightInstalledDaemon(paths, daemonHome, expectedArgv) {
360
385
  try {
361
386
  lstatSync(unitReceiptFile(paths));
362
387
  }
@@ -365,7 +390,12 @@ export function preflightInstalledDaemon(paths, daemonHome) {
365
390
  return false;
366
391
  throw error;
367
392
  }
368
- installedDaemonIdentity(paths, daemonHome);
393
+ if (expectedArgv) {
394
+ const { receipt, plan } = recordedUnit(paths, daemonHome);
395
+ recordedSourceIdentity(receipt, plan.mechanism, () => [...expectedArgv]);
396
+ }
397
+ else
398
+ installedDaemonIdentity(paths, daemonHome);
369
399
  return true;
370
400
  }
371
401
  /** The executable and entry pinned by the verified native source, compared with this CLI. */
@@ -428,8 +458,9 @@ export function observeDaemonOwnedService(paths, daemonHome, signal) {
428
458
  const { parentPort, workerData } = require('node:worker_threads');
429
459
  process.argv = workerData.argv;
430
460
  process.execArgv = workerData.execArgv;
461
+ if (workerData.execution) Object.defineProperty(globalThis, Symbol.for('cotal.execution.identity'), { value: Object.freeze(workerData.execution) });
431
462
  import(workerData.module).then(m => parentPort.postMessage(workerData.expected ? m.observeWindowsOwnedService(workerData.paths, workerData.expected) : m.daemonStartedByOwnedService(workerData.paths, workerData.home))).catch(() => parentPort.postMessage({ state: 'unknown', reason: 'worker-failed' }));
432
- `, { eval: true, workerData: { module: expected ? new URL("./ownership-win32.js", import.meta.url).href : import.meta.url, expected, paths, home: daemonHome, argv: process.argv, execArgv: process.execArgv }, stdout: true, stderr: true });
463
+ `, { eval: true, workerData: { module: expected ? new URL("./ownership-win32.js", import.meta.url).href : import.meta.url, expected, paths, home: daemonHome, argv: process.argv, execArgv: process.execArgv, execution: executionIdentity() }, stdout: true, stderr: true });
433
464
  worker.stdout.resume();
434
465
  worker.stderr.resume();
435
466
  let settled = false;