cotal-ai 0.166.0 → 0.166.2
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.
- package/dist/daemon/client.js +11 -1
- package/dist/daemon/command.js +38 -10
- package/dist/daemon/connect.js +1 -1
- package/dist/daemon/endpoint.js +9 -2
- package/dist/daemon/execution-preinstall.js +59 -3
- package/dist/daemon/execution-update.js +1 -1
- package/dist/daemon/generation.js +3 -4
- package/dist/daemon/install.js +115 -15
- package/dist/daemon/manager-cleanup.js +1 -6
- package/dist/daemon/manager.js +59 -27
- package/dist/daemon/preinstall-preservation.js +46 -0
- package/dist/daemon/protocol.js +2 -2
- package/dist/daemon/server.js +1 -1
- package/dist/daemon/service.js +1 -1
- package/dist/daemon/update-entry.js +96 -6
- package/dist/daemon/update-generation.js +11 -3
- package/dist/docs.js +1 -1
- package/dist/execution-transaction.js +21 -0
- package/dist/mcp-host.js +116 -0
- package/dist/mcp.js +64 -0
- package/dist/run.js +2 -0
- package/package.json +19 -19
- package/seeded-connectors/_shared/docs-bundle.bin +0 -0
- package/seeded-connectors/_shared/docs-index.bin +0 -0
- package/seeded-connectors/_shared/placements.json +2 -2
- package/seeded-connectors/claude/dist/index.js +2 -2
- package/seeded-connectors/claude/dist/mcp.cjs +7 -7
- package/seeded-connectors/claude/package.json +1 -1
- package/seeded-connectors/codex/dist/host.js +6 -6
- package/seeded-connectors/codex/dist/index.js +2 -2
- package/seeded-connectors/codex/dist/personal.js +7 -7
- package/seeded-connectors/codex/package.json +1 -1
- package/seeded-connectors/hermes/dist/index.js +2 -2
- package/seeded-connectors/hermes/dist/launch.js +6 -6
- package/seeded-connectors/hermes/package.json +1 -1
- package/seeded-connectors/hermes/plugin/cotal/_sidecar/standalone.cjs +6 -6
- package/seeded-connectors/jcode/dist/host.js +6 -6
- package/seeded-connectors/jcode/dist/index.js +2 -2
- package/seeded-connectors/jcode/dist/mcp.js +2 -2
- package/seeded-connectors/jcode/package.json +1 -1
- package/seeded-connectors/opencode/dist/index.js +2 -2
- package/seeded-connectors/opencode/dist/plugin/index.js +6 -6
- package/seeded-connectors/opencode/package.json +1 -1
- package/seeded-connectors/pi/README.md +8 -4
- package/seeded-connectors/pi/dist/driver.d.ts +2 -0
- package/seeded-connectors/pi/dist/driver.d.ts.map +1 -1
- package/seeded-connectors/pi/dist/index.js +6 -6
- package/seeded-connectors/pi/dist/standalone.js +9 -9
- package/seeded-connectors/pi/package.json +1 -1
- package/seeded-connectors/web/dist/service-adapter.d.ts.map +1 -1
- package/seeded-connectors/web/dist/service-adapter.js +16 -12
- package/seeded-connectors/web/dist/service-adapter.js.map +1 -1
- package/seeded-connectors/web/dist/web.d.ts +7 -1
- package/seeded-connectors/web/dist/web.d.ts.map +1 -1
- package/seeded-connectors/web/dist/web.js +15 -7
- package/seeded-connectors/web/dist/web.js.map +1 -1
- package/seeded-connectors/web/package.json +1 -1
package/dist/daemon/client.js
CHANGED
|
@@ -199,6 +199,8 @@ export async function openVerified(opts) {
|
|
|
199
199
|
}
|
|
200
200
|
catch (e) {
|
|
201
201
|
sock.destroy();
|
|
202
|
+
if (process.platform === "darwin" && e.code === "ENOTCONN")
|
|
203
|
+
throw new ClosedPeerRefusal("PEER_UID_MISMATCH", `could not read the daemon's peer credentials: ${e.message}`);
|
|
202
204
|
throw new EndpointRefusal("PEER_UID_MISMATCH", `could not read the daemon's peer credentials: ${e.message}`);
|
|
203
205
|
}
|
|
204
206
|
if (peer !== uid) {
|
|
@@ -213,7 +215,11 @@ export async function openVerified(opts) {
|
|
|
213
215
|
try {
|
|
214
216
|
pid = (opts.peerPid ?? defaultPeerPid)(sock);
|
|
215
217
|
}
|
|
216
|
-
catch {
|
|
218
|
+
catch (e) {
|
|
219
|
+
if (process.platform === "darwin" && e.code === "ENOTCONN") {
|
|
220
|
+
sock.destroy();
|
|
221
|
+
throw new ClosedPeerRefusal("PEER_NOT_LOCK_OWNER", `could not read the daemon's peer credentials: ${e.message}`);
|
|
222
|
+
}
|
|
217
223
|
pid = undefined;
|
|
218
224
|
}
|
|
219
225
|
if (pid === undefined || !isLockOwner(paths.lock, pid, processBirth(pid))) {
|
|
@@ -230,6 +236,10 @@ function isLockOwner(lock, pid, birth) {
|
|
|
230
236
|
/** The pipe-open steps that read the server's identity. A failure in one means that identity could
|
|
231
237
|
* not be established, so nothing may be sent. */
|
|
232
238
|
const IDENTITY_STEPS = new Set(["GetNamedPipeServerProcessId", "OpenProcess", "GetProcessTimes", "OpenProcessToken", "GetTokenInformation", "ConvertSidToStringSidW"]);
|
|
239
|
+
/** A Darwin peer closed before kernel identity could be read. No request was sent and it is not absence. */
|
|
240
|
+
export class ClosedPeerRefusal extends EndpointRefusal {
|
|
241
|
+
constructor(code, message) { super(code, message); }
|
|
242
|
+
}
|
|
233
243
|
/** A refused Windows pipe whose original lifetime read contained zero bytes. It is never writable. */
|
|
234
244
|
export class EmptyLifetimeRefusal extends EndpointRefusal {
|
|
235
245
|
pid;
|
package/dist/daemon/command.js
CHANGED
|
@@ -22,7 +22,8 @@
|
|
|
22
22
|
* and verified; it says nothing about any mesh or Cloud connection.
|
|
23
23
|
*/
|
|
24
24
|
import { readFileSync, realpathSync } from "node:fs";
|
|
25
|
-
import {
|
|
25
|
+
import { spawnSync } from "node:child_process";
|
|
26
|
+
import { basename, dirname, isAbsolute, join } from "node:path";
|
|
26
27
|
import { fileURLToPath } from "node:url";
|
|
27
28
|
import { registry } from "@cotal-ai/core";
|
|
28
29
|
import { CommandFailure, logicalExecutionEntry, codeSpan, homeCotalDir, keptCatalogCredentials, jsonFlag, plainFlag, presentationOf, recordOperationContext, renderReport, writeResult } from "@cotal-ai/workspace";
|
|
@@ -42,7 +43,7 @@ import { watchDaemonGeneration } from "./generation.js";
|
|
|
42
43
|
import { SPACE_PATTERN } from "./protocol.js";
|
|
43
44
|
import { nativeDaemonLog } from "./native-log.js";
|
|
44
45
|
import { liveUpdateClosureOwner, readUpdateRecovery } from "@cotal-ai/workspace";
|
|
45
|
-
|
|
46
|
+
const daemonFlags = [
|
|
46
47
|
jsonFlag,
|
|
47
48
|
plainFlag,
|
|
48
49
|
{ name: "cloud", type: "boolean", description: "sign in to Cotal Cloud" },
|
|
@@ -68,14 +69,24 @@ const loadedBinVersion = (() => {
|
|
|
68
69
|
export function binVersion() { return loadedBinVersion; }
|
|
69
70
|
const peerUid = defaultPeerUid;
|
|
70
71
|
const peerPid = defaultPeerPid;
|
|
71
|
-
function target(args) {
|
|
72
|
+
function target(args, recoverMissingHome = false) {
|
|
72
73
|
const raw = args.values["daemon-home"];
|
|
73
74
|
if (raw === undefined)
|
|
74
75
|
return { paths: daemonPaths() };
|
|
75
76
|
if (!raw || !isAbsolute(raw))
|
|
76
77
|
throw new CommandFailure("refused", "USAGE_INVALID", "--daemon-home needs an absolute directory path");
|
|
77
|
-
|
|
78
|
-
|
|
78
|
+
let home;
|
|
79
|
+
let missing = false;
|
|
80
|
+
try {
|
|
81
|
+
checkDir(raw);
|
|
82
|
+
home = realpathSync(raw);
|
|
83
|
+
}
|
|
84
|
+
catch (error) {
|
|
85
|
+
if (!recoverMissingHome || process.platform !== "linux" || error.code !== "ENOENT")
|
|
86
|
+
throw error;
|
|
87
|
+
home = join(realpathSync(dirname(raw)), basename(raw));
|
|
88
|
+
missing = true;
|
|
89
|
+
}
|
|
79
90
|
let cotalHome;
|
|
80
91
|
try {
|
|
81
92
|
cotalHome = realpathSync(homeCotalDir());
|
|
@@ -86,11 +97,18 @@ function target(args) {
|
|
|
86
97
|
}
|
|
87
98
|
if (home === cotalHome)
|
|
88
99
|
throw new CommandFailure("refused", "USAGE_INVALID", "--daemon-home cannot be the Cotal home; name a separate directory for this daemon's state");
|
|
89
|
-
|
|
100
|
+
const paths = daemonPathsFor(home);
|
|
101
|
+
if (missing)
|
|
102
|
+
planUninstall(paths, home);
|
|
103
|
+
return { paths, home };
|
|
90
104
|
}
|
|
91
|
-
function resolveTarget(args) {
|
|
105
|
+
function resolveTarget(args, recoverMissingHome = false) {
|
|
92
106
|
try {
|
|
93
|
-
|
|
107
|
+
const resolved = target(args, recoverMissingHome);
|
|
108
|
+
// Native user-service tools need the same validated runtime as the socket client.
|
|
109
|
+
if (process.platform === "linux" && !process.env.XDG_RUNTIME_DIR)
|
|
110
|
+
process.env.XDG_RUNTIME_DIR = `/run/user/${process.geteuid()}`;
|
|
111
|
+
return resolved;
|
|
94
112
|
}
|
|
95
113
|
catch (e) {
|
|
96
114
|
if (e.code === "ENOENT")
|
|
@@ -368,12 +386,12 @@ async function serviceCommand(args, op) {
|
|
|
368
386
|
async function unitCommand(args, op) {
|
|
369
387
|
const presentation = presentationOf(args.values);
|
|
370
388
|
const values = args.values;
|
|
371
|
-
const { paths, home } = resolveTarget(args);
|
|
389
|
+
const { paths, home } = resolveTarget(args, true);
|
|
372
390
|
if (op === "install") {
|
|
373
391
|
const dry = values["dry-run"] === true;
|
|
374
392
|
const r = dry ? { ...planInstall(paths, home), state: "would-install" } : applyInstall(paths, home);
|
|
375
393
|
writeResult(presentation, { command: "daemon install", target: { unit: r.unit }, result: r }, () => ({ sections: [
|
|
376
|
-
{ title: dry ? "Would install" : "Installed", blocks: [
|
|
394
|
+
{ title: r.alreadyInstalled ? "Already installed" : dry ? "Would install" : "Installed", blocks: [
|
|
377
395
|
{ kind: "fields", rows: [["Unit", r.unit], ["Path", r.unitPath], ["Digest", r.sha256], ["User", r.user], ...(r.mechanism === "systemd-user" ? [["Linger", r.lingerAlready ? "already enabled" : dry ? "would be enabled" : "enabled by this install"]] : []), ["Restart", r.restart], ["Started by", r.wantedBy], ...(r.daemonHome ? [["Daemon home", r.daemonHome]] : [])] },
|
|
378
396
|
{ kind: "lines", lines: [{ text: dry
|
|
379
397
|
? "Nothing was written, enabled or started."
|
|
@@ -575,6 +593,16 @@ async function serve(args) {
|
|
|
575
593
|
}
|
|
576
594
|
updates = automaticUpdates({ version: binVersion(), eligible: () => home === undefined && owned, prepare: async () => { const seats = await running.generationSeats(); if (seats.some(row => row.seats > 0))
|
|
577
595
|
throw new Error("running agents remain"); }, abort: async () => { }, report: line => process.stderr.write(`${line}\n`) });
|
|
596
|
+
if (process.platform === "linux" && process.env.COTAL_DAEMON_NATIVE_SERVICE === "1" && process.env.NOTIFY_SOCKET) {
|
|
597
|
+
// The helper stays in this unit's cgroup. NotifyAccess=all permits its readiness
|
|
598
|
+
// message, and the default notification barrier waits for systemd to consume it.
|
|
599
|
+
const notified = spawnSync("/usr/bin/systemd-notify", ["--ready"], { timeout: 5000, stdio: "pipe" });
|
|
600
|
+
if (notified.error || notified.status !== 0) {
|
|
601
|
+
await updates.close();
|
|
602
|
+
await running.close();
|
|
603
|
+
throw new Error("could not notify systemd that the daemon is ready");
|
|
604
|
+
}
|
|
605
|
+
}
|
|
578
606
|
process.stdout.write(`daemon ready at ${running.paths.socket}\n`);
|
|
579
607
|
const ownership = observe();
|
|
580
608
|
await new Promise((resolve, reject) => {
|
package/dist/daemon/connect.js
CHANGED
|
@@ -32,7 +32,7 @@ export const ACCOUNT_MISMATCH_MESSAGE = "the space now answers with a different
|
|
|
32
32
|
const IDP_CREDENTIAL_EXPIRED_MESSAGE = "the sign-in provider returned a credential that is expired according to this machine's clock; check this machine's and the authority's clocks, then connect again; nothing is connected";
|
|
33
33
|
const KIND = "cotal-daemon-service-identity";
|
|
34
34
|
/** Where this machine's daemon keeps its identity for `space`. */
|
|
35
|
-
|
|
35
|
+
function daemonIdentityFile(space, home = homeCotalDir()) {
|
|
36
36
|
return join(home, "daemon", spaceSegment(space), "service-identity.json");
|
|
37
37
|
}
|
|
38
38
|
function parseIdentity(space) {
|
package/dist/daemon/endpoint.js
CHANGED
|
@@ -83,10 +83,17 @@ export function daemonPaths(env = process.env, home = homeCotalDir()) {
|
|
|
83
83
|
}
|
|
84
84
|
else {
|
|
85
85
|
assertSupportedPlatform();
|
|
86
|
+
runtime = env.XDG_RUNTIME_DIR || `/run/user/${euid()}`;
|
|
86
87
|
if (!env.XDG_RUNTIME_DIR) {
|
|
87
|
-
|
|
88
|
+
try {
|
|
89
|
+
checkDir(runtime);
|
|
90
|
+
}
|
|
91
|
+
catch (error) {
|
|
92
|
+
if (error.code !== "ENOENT")
|
|
93
|
+
throw error;
|
|
94
|
+
throw new EndpointRefusal("NO_RUNTIME_DIR", `${runtime} is absent and XDG_RUNTIME_DIR is not set, so there is no per-user runtime directory to hold the daemon socket`);
|
|
95
|
+
}
|
|
88
96
|
}
|
|
89
|
-
runtime = env.XDG_RUNTIME_DIR;
|
|
90
97
|
}
|
|
91
98
|
const dir = join(runtime, "cotal");
|
|
92
99
|
const socket = join(dir, "daemon.sock");
|
|
@@ -6,6 +6,8 @@ import { askManager } from "@cotal-ai/workspace/control";
|
|
|
6
6
|
import { queryDaemon } from "./client.js";
|
|
7
7
|
import { daemonPaths, EndpointRefusal } from "./endpoint.js";
|
|
8
8
|
import { preflightInstalledDaemon } from "./install.js";
|
|
9
|
+
import { setTimeout as delay } from "node:timers/promises";
|
|
10
|
+
import { preinstallPreservationObservation, preservingPreinstallRefusal } from "./preinstall-preservation.js";
|
|
9
11
|
import { processBirth, readLifetimeRecord } from "./lifetime.js";
|
|
10
12
|
/** Read-only admission. Consent and all Manager/daemon mutation remain in the parent transaction. */
|
|
11
13
|
export async function readExecutionPreinstall(request) {
|
|
@@ -31,15 +33,69 @@ export async function readExecutionPreinstall(request) {
|
|
|
31
33
|
if (!lifetime?.start || lifetime.pid !== reply.result.pid || processBirth(lifetime.pid) !== lifetime.start)
|
|
32
34
|
throw new Error("machine daemon lifetime changed during pre-install check");
|
|
33
35
|
const active = (reply.result.managers ?? []).filter(manager => manager.pid !== undefined);
|
|
36
|
+
let preservingDeadline;
|
|
37
|
+
const hostedIdentity = (status) => {
|
|
38
|
+
if (!Array.isArray(status.managers))
|
|
39
|
+
throw new Error("hosted Manager inventory is unknown during preserving observation");
|
|
40
|
+
return JSON.stringify(status.managers.filter(row => row.pid !== undefined).map(row => [row.space, row.pid, row.instanceId]).sort((a, b) => String(a[0]).localeCompare(String(b[0]))));
|
|
41
|
+
};
|
|
42
|
+
const initialHostedIdentity = hostedIdentity(reply.result);
|
|
34
43
|
let occupied = 0;
|
|
35
44
|
for (const manager of active) {
|
|
36
45
|
if (!manager.instanceId)
|
|
37
46
|
throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", `hosted Manager ${manager.space} has no verified instance identity`);
|
|
47
|
+
const managerBirth = processBirth(manager.pid);
|
|
48
|
+
if (!managerBirth)
|
|
49
|
+
throw new Error("hosted Manager lifetime is unreadable during pre-install check");
|
|
38
50
|
await withIdpSessionDir(homeCotalDir(), async () => {
|
|
39
51
|
const target = await resolveControlTarget({ space: manager.space }, "control-caller-privileged", manager.instanceId, { onRefusal: "throw", readOnly: true });
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
52
|
+
let observed = reply.result;
|
|
53
|
+
const pin = () => {
|
|
54
|
+
if (processBirth(lifetime.pid) !== lifetime.start || observed.pid !== lifetime.pid || hostedIdentity(observed) !== initialHostedIdentity)
|
|
55
|
+
throw new Error("machine daemon or hosted Manager identities changed during preserving observation");
|
|
56
|
+
if (!Array.isArray(observed.managers))
|
|
57
|
+
throw new Error("hosted Manager inventory is unknown during preserving observation");
|
|
58
|
+
const current = observed.managers.find(row => row.space === manager.space && row.instanceId === manager.instanceId);
|
|
59
|
+
if (!current || current.pid !== manager.pid || processBirth(manager.pid) !== managerBirth)
|
|
60
|
+
throw new Error("hosted Manager lifetime changed during preserving observation");
|
|
61
|
+
};
|
|
62
|
+
const bounded = async (read) => {
|
|
63
|
+
const remaining = preservingDeadline - Date.now();
|
|
64
|
+
if (remaining <= 0)
|
|
65
|
+
throw preservingPreinstallRefusal(preinstallPreservationObservation(observed));
|
|
66
|
+
let timer;
|
|
67
|
+
try {
|
|
68
|
+
const result = await Promise.race([read(), new Promise((_, reject) => { timer = setTimeout(() => reject(preservingPreinstallRefusal(preinstallPreservationObservation(observed))), remaining); })]);
|
|
69
|
+
if (Date.now() >= preservingDeadline)
|
|
70
|
+
throw preservingPreinstallRefusal(preinstallPreservationObservation(observed));
|
|
71
|
+
return result;
|
|
72
|
+
}
|
|
73
|
+
finally {
|
|
74
|
+
clearTimeout(timer);
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
let status;
|
|
78
|
+
for (;;) {
|
|
79
|
+
pin();
|
|
80
|
+
const ask = () => askManager({ versionSkew: (text) => text, roster: async () => [] }, manager.space, target.server, "managerStatus", undefined, target.auth, "owner", preservingDeadline === undefined ? 3000 : Math.max(1, Math.min(3000, preservingDeadline - Date.now())), { instanceId: manager.instanceId });
|
|
81
|
+
status = preservingDeadline === undefined ? await ask() : await bounded(ask);
|
|
82
|
+
if (status.ok)
|
|
83
|
+
break;
|
|
84
|
+
if (!/manager is in preserving mode/.test(status.error ?? ""))
|
|
85
|
+
throw new Error(status.error ?? "hosted Manager status did not answer");
|
|
86
|
+
preservingDeadline ??= Date.now() + 5000;
|
|
87
|
+
const custody = preinstallPreservationObservation(observed);
|
|
88
|
+
if (custody.seats !== 0 || !["gone", "transaction"].includes(custody.owner) || Date.now() >= preservingDeadline)
|
|
89
|
+
throw preservingPreinstallRefusal(custody);
|
|
90
|
+
await delay(Math.min(100, Math.max(1, preservingDeadline - Date.now())));
|
|
91
|
+
const fresh = await bounded(() => queryDaemon({ paths, timeoutMs: Math.max(1, Math.min(1000, preservingDeadline - Date.now())) }));
|
|
92
|
+
if (!fresh.ok)
|
|
93
|
+
throw new Error("machine daemon custody is unreadable during preserving observation");
|
|
94
|
+
observed = fresh.result;
|
|
95
|
+
}
|
|
96
|
+
pin();
|
|
97
|
+
if (status.data.instanceId !== manager.instanceId)
|
|
98
|
+
throw new Error("hosted Manager instance changed before pre-install receipt");
|
|
43
99
|
const count = status.data.agentCount;
|
|
44
100
|
if (!Number.isSafeInteger(count) || count < 0)
|
|
45
101
|
throw new Error("hosted Manager returned an invalid agent count");
|
|
@@ -37,7 +37,7 @@ export async function prepareExecutionUpdate(version, globalRoot, checked) {
|
|
|
37
37
|
const staging = executionStagingPrefix(installed);
|
|
38
38
|
let generation;
|
|
39
39
|
try {
|
|
40
|
-
const npm = cmdSpawnSpec("npm", ["install", "-g", "--prefix", staging, `cotal-ai@${version}`, "--ignore-scripts", "--no-audit", "--no-fund", "--fetch-retries=
|
|
40
|
+
const npm = cmdSpawnSpec("npm", ["install", "-g", "--prefix", staging, `cotal-ai@${version}`, "--ignore-scripts", "--no-audit", "--no-fund", "--fetch-retries=2", "--fetch-retry-mintimeout=1000", "--fetch-retry-maxtimeout=2000", "--fetch-timeout=15000"]);
|
|
41
41
|
const result = await updateRuntime.spawnGlobal(globalRoot, "install", npm.file, npm.args, process.env, false, npm.windowsVerbatimArguments);
|
|
42
42
|
if (result.status !== 0)
|
|
43
43
|
throw new Error(`target staging failed: ${result.error ?? result.stderr ?? result.stdout}`);
|
|
@@ -2,8 +2,7 @@
|
|
|
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 { loadExtensionsManifest, logicalExecutionEntry, updateActivationBlocked } from "@cotal-ai/workspace";
|
|
6
|
-
import { globalConfigDir } from "@cotal-ai/core";
|
|
5
|
+
import { connectorConfigDir, loadExtensionsManifest, logicalExecutionEntry, updateActivationBlocked } from "@cotal-ai/workspace";
|
|
7
6
|
import { selectExecutionProgram } from "../cotal.js";
|
|
8
7
|
import { fileURLToPath } from "node:url";
|
|
9
8
|
export function installedGenerationVersion() {
|
|
@@ -30,7 +29,7 @@ export async function reconcileHostedConnectors(version) {
|
|
|
30
29
|
if (installed !== version)
|
|
31
30
|
throw new ReplacedDaemonGeneration(version, installed);
|
|
32
31
|
try {
|
|
33
|
-
const stamp = JSON.parse(readFileSync(join(
|
|
32
|
+
const stamp = JSON.parse(readFileSync(join(connectorConfigDir(), "seed", "stamp.json"), "utf8"));
|
|
34
33
|
const skewed = loadExtensionsManifest().extensions.some((entry) => entry.pkg.startsWith("@cotal-ai/") && entry.version !== version);
|
|
35
34
|
if (stamp?.generation === version && !skewed)
|
|
36
35
|
return;
|
|
@@ -59,7 +58,7 @@ function packageFile() {
|
|
|
59
58
|
}
|
|
60
59
|
throw new Error("the daemon's CLI package is not identifiable");
|
|
61
60
|
}
|
|
62
|
-
|
|
61
|
+
async function reconcileInstalledGeneration() {
|
|
63
62
|
const file = packageFile();
|
|
64
63
|
await new Promise((resolve, reject) => {
|
|
65
64
|
const child = spawn(process.execPath, [join(dirname(file), "dist", "cotal.js"), "ext", "seed"], { env: { ...process.env, COTAL_SKIP_CONNECTOR_SEED: "1" }, stdio: ["ignore", "ignore", "pipe"], windowsHide: true });
|
package/dist/daemon/install.js
CHANGED
|
@@ -43,7 +43,7 @@ import { mkSecretDir, writeSecretFile, writeSecretFileAtomic } from "@cotal-ai/c
|
|
|
43
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
|
-
import { isStoppingLifetime, openVerified, readLine } from "./client.js";
|
|
46
|
+
import { ClosedPeerRefusal, isStoppingLifetime, openVerified, readLine } from "./client.js";
|
|
47
47
|
import { excludeLifetime, processBirth, readLifetimeRecord } from "./lifetime.js";
|
|
48
48
|
import { lockExclusiveNb, windowsUserSid } from "@cotal-ai/seat";
|
|
49
49
|
import { encode } from "./protocol.js";
|
|
@@ -57,7 +57,7 @@ import { readReceipt, unitReceiptFile } from "./install-receipt.js";
|
|
|
57
57
|
export { unitReceiptFile } from "./install-receipt.js";
|
|
58
58
|
/** `cotal-daemon.service`, or `cotal-daemon-<16 hex>.service` for an explicit daemon home, derived
|
|
59
59
|
* the same way its socket directory is so the two always agree. */
|
|
60
|
-
|
|
60
|
+
function daemonUnitName(daemonHome) {
|
|
61
61
|
if (daemonHome === undefined)
|
|
62
62
|
return "cotal-daemon.service";
|
|
63
63
|
return `cotal-daemon-${createHash("sha256").update(daemonHome).digest("hex").slice(0, 16)}.service`;
|
|
@@ -97,7 +97,9 @@ export function renderDaemonUnit(unitDirectory, daemonHome) {
|
|
|
97
97
|
"Description=Cotal machine daemon",
|
|
98
98
|
"",
|
|
99
99
|
"[Service]",
|
|
100
|
-
"Type=
|
|
100
|
+
"Type=notify",
|
|
101
|
+
"NotifyAccess=all",
|
|
102
|
+
"TimeoutStartSec=60",
|
|
101
103
|
`Environment=PATH=${unitValue(pinnedPath())}`,
|
|
102
104
|
"Environment=COTAL_DAEMON_NATIVE_SERVICE=1",
|
|
103
105
|
`ExecStart=${argv.map((part) => unitValue(part, true)).join(" ")}`,
|
|
@@ -205,7 +207,14 @@ export function planInstall(paths, daemonHome) {
|
|
|
205
207
|
}
|
|
206
208
|
const user = invokingUser();
|
|
207
209
|
const rendered = renderDaemonUnit(systemdUserUnitDirectory(), daemonHome);
|
|
208
|
-
|
|
210
|
+
const existing = readReceipt(paths);
|
|
211
|
+
if (existing) {
|
|
212
|
+
const recorded = recordedUnit(paths, daemonHome);
|
|
213
|
+
if (!recordedDaemonIdentity(recorded).same)
|
|
214
|
+
throw new CommandFailure("refused", "CONFLICT", "the recorded daemon service belongs to another Cotal installation; nothing was changed");
|
|
215
|
+
const source = readFileSync(existing.unitPath, "utf8");
|
|
216
|
+
return { mechanism: "systemd-user", unit: existing.unit, unitPath: existing.unitPath, sha256: existing.unitSha256, user, lingerAlready: lingerEnabled(user), restart: directive(source, "Restart"), wantedBy: directive(source, "WantedBy"), ...(daemonHome !== undefined ? { daemonHome } : {}), alreadyInstalled: true };
|
|
217
|
+
}
|
|
209
218
|
let present = false;
|
|
210
219
|
try {
|
|
211
220
|
lstatSync(rendered.unitPath);
|
|
@@ -215,8 +224,12 @@ export function planInstall(paths, daemonHome) {
|
|
|
215
224
|
if (error.code !== "ENOENT")
|
|
216
225
|
throw new CommandFailure("refused", "TARGET_UNAVAILABLE", `${rendered.unitPath} could not be inspected; no absent unit was inferred`);
|
|
217
226
|
}
|
|
218
|
-
if (present)
|
|
219
|
-
|
|
227
|
+
if (present) {
|
|
228
|
+
const recovered = recoveredLinuxUnit(daemonHome);
|
|
229
|
+
if (!recovered)
|
|
230
|
+
throw new CommandFailure("refused", "CONFLICT", "the surviving daemon source changed while planning recovery; nothing was changed");
|
|
231
|
+
return { mechanism: "systemd-user", unit: recovered.unit, unitPath: recovered.unitPath, sha256: recovered.unitSha256, user, lingerAlready: lingerEnabled(user), restart: directive(rendered.bytes, "Restart"), wantedBy: directive(rendered.bytes, "WantedBy"), ...(daemonHome !== undefined ? { daemonHome } : {}), recovered: true };
|
|
232
|
+
}
|
|
220
233
|
assertSystemdSourceDirectory(dirname(rendered.unitPath));
|
|
221
234
|
return { mechanism: "systemd-user", unit: rendered.unit, unitPath: rendered.unitPath, sha256: rendered.sha256, user, lingerAlready: lingerEnabled(user),
|
|
222
235
|
restart: directive(rendered.bytes, "Restart"), wantedBy: directive(rendered.bytes, "WantedBy"), ...(daemonHome !== undefined ? { daemonHome } : {}) };
|
|
@@ -242,6 +255,18 @@ export function applyInstall(paths, daemonHome, omittedRelativePathEntries) {
|
|
|
242
255
|
return { mechanism, unit, unitPath, sha256, user, restart, wantedBy, ...(daemonHome !== undefined ? { daemonHome } : {}), ...omitted, state: "installed" };
|
|
243
256
|
}
|
|
244
257
|
const plan = planInstall(paths, daemonHome);
|
|
258
|
+
if (plan.alreadyInstalled)
|
|
259
|
+
return { ...plan, lingerEnabled: plan.lingerAlready, ...omitted, state: "installed" };
|
|
260
|
+
if (plan.recovered) {
|
|
261
|
+
submitSystemdUnitControl("stop", plan.unit);
|
|
262
|
+
const stopped = recoveredLinuxUnit(daemonHome);
|
|
263
|
+
if (!stopped || stopped.unitSha256 !== plan.sha256)
|
|
264
|
+
throw new CommandFailure("refused", "CONFLICT", "the surviving daemon source changed during its native stop; no receipt was restored and it was not started");
|
|
265
|
+
mkSecretDir(paths.state);
|
|
266
|
+
writeReceipt(paths, { v: 1, mechanism: "systemd-user", unit: plan.unit, unitPath: plan.unitPath, unitSha256: plan.sha256, installedAt: new Date().toISOString(), ...(daemonHome !== undefined ? { daemonHome } : {}), ...omitted });
|
|
267
|
+
submitSystemdUnitControl("start", plan.unit);
|
|
268
|
+
return { ...plan, lingerEnabled: plan.lingerAlready, ...omitted, state: "installed" };
|
|
269
|
+
}
|
|
245
270
|
const rendered = renderDaemonUnit(dirname(plan.unitPath), daemonHome);
|
|
246
271
|
// This daemon's own state directory, which holds the receipt below. It is ours, so it is created
|
|
247
272
|
// 0700 and checked; the user manager's unit directory is the operator's and is only created when
|
|
@@ -262,10 +287,43 @@ export function applyInstall(paths, daemonHome, omittedRelativePathEntries) {
|
|
|
262
287
|
submitSystemdUnitControl("start", rendered.unit);
|
|
263
288
|
return { ...plan, lingerEnabled: true, ...omitted, state: "installed" };
|
|
264
289
|
}
|
|
290
|
+
function recoveredLinuxUnit(daemonHome) {
|
|
291
|
+
if (process.platform !== "linux")
|
|
292
|
+
return undefined;
|
|
293
|
+
const rendered = renderDaemonUnit(systemdUserUnitDirectory(), daemonHome);
|
|
294
|
+
try {
|
|
295
|
+
lstatSync(rendered.unitPath);
|
|
296
|
+
}
|
|
297
|
+
catch (error) {
|
|
298
|
+
if (error.code === "ENOENT")
|
|
299
|
+
return undefined;
|
|
300
|
+
throw error;
|
|
301
|
+
}
|
|
302
|
+
// A name is not authority. Require this installation's exact protected source and loaded fragment.
|
|
303
|
+
try {
|
|
304
|
+
assertSystemdSource(rendered.unitPath, rendered.sha256);
|
|
305
|
+
}
|
|
306
|
+
catch {
|
|
307
|
+
throw new CommandFailure("refused", "CONFLICT", "the surviving daemon source does not match this installation's protected unit; nothing was changed");
|
|
308
|
+
}
|
|
309
|
+
const names = ["Id", "LoadState", "FragmentPath", "DropInPaths", "NeedDaemonReload"];
|
|
310
|
+
const read = nativeRun("systemctl", ["--user", "show", rendered.unit, "--all", "--no-pager", ...names.map(name => `--property=${name}`)]);
|
|
311
|
+
const values = new Map();
|
|
312
|
+
for (const line of read.stdout.split("\n").filter(Boolean)) {
|
|
313
|
+
const at = line.indexOf("="), key = line.slice(0, at);
|
|
314
|
+
if (at < 1 || !names.includes(key) || values.has(key))
|
|
315
|
+
throw new CommandFailure("refused", "CONFLICT", "the surviving daemon unit's native identity is ambiguous; nothing was changed");
|
|
316
|
+
values.set(key, line.slice(at + 1));
|
|
317
|
+
}
|
|
318
|
+
if (read.status !== 0 || values.size !== names.length || values.get("Id") !== rendered.unit || values.get("LoadState") !== "loaded" || values.get("FragmentPath") !== rendered.unitPath || values.get("DropInPaths") !== "" || values.get("NeedDaemonReload") !== "no")
|
|
319
|
+
throw new CommandFailure("refused", "CONFLICT", "the surviving daemon unit is modified, overridden or not loaded from this installation's exact source; nothing was changed");
|
|
320
|
+
return { v: 1, mechanism: "systemd-user", unit: rendered.unit, unitPath: rendered.unitPath, unitSha256: rendered.sha256, installedAt: lstatSync(rendered.unitPath).birthtime.toISOString(), ...(daemonHome !== undefined ? { daemonHome } : {}) };
|
|
321
|
+
}
|
|
265
322
|
/** The recorded unit, refused unless this OS runs its mechanism and its source and job are unchanged. */
|
|
266
|
-
function recordedUnit(paths, daemonHome, run = nativeRun) {
|
|
323
|
+
function recordedUnit(paths, daemonHome, run = nativeRun, recover = false) {
|
|
267
324
|
const service = nativeService(run);
|
|
268
|
-
const
|
|
325
|
+
const saved = readReceipt(paths);
|
|
326
|
+
const receipt = saved ?? (recover ? recoveredLinuxUnit(daemonHome) : undefined);
|
|
269
327
|
if (!receipt)
|
|
270
328
|
throw new CommandFailure("refused", "TARGET_NOT_FOUND", "this daemon has no installed unit recorded by `cotal daemon install`; nothing was removed");
|
|
271
329
|
const mechanism = receipt.mechanism ?? "systemd-user";
|
|
@@ -296,11 +354,11 @@ function recordedUnit(paths, daemonHome, run = nativeRun) {
|
|
|
296
354
|
throw new CommandFailure("refused", "CONFLICT", `${receipt.unitPath} is not the unit this daemon installed; nothing was removed`);
|
|
297
355
|
}
|
|
298
356
|
}
|
|
299
|
-
return { receipt, plan: { mechanism, unit: receipt.unit, unitPath: receipt.unitPath, installedAt: receipt.installedAt }, service };
|
|
357
|
+
return { receipt, plan: { mechanism, unit: receipt.unit, unitPath: receipt.unitPath, installedAt: receipt.installedAt }, service, recovered: saved === undefined };
|
|
300
358
|
}
|
|
301
359
|
/** The exact recorded unit `uninstall` would remove, refusing a receipt that no longer matches. */
|
|
302
360
|
export function planUninstall(paths, daemonHome) {
|
|
303
|
-
return recordedUnit(paths, daemonHome).plan;
|
|
361
|
+
return recordedUnit(paths, daemonHome, nativeRun, true).plan;
|
|
304
362
|
}
|
|
305
363
|
/** Update only the PATH field the installer wrote. Windows tasks have no PATH pin. */
|
|
306
364
|
export function refreshedDaemonPath(mechanism, source, terminalPath = process.env.PATH ?? "") {
|
|
@@ -398,6 +456,42 @@ export function preflightInstalledDaemon(paths, daemonHome, expectedArgv) {
|
|
|
398
456
|
installedDaemonIdentity(paths, daemonHome);
|
|
399
457
|
return true;
|
|
400
458
|
}
|
|
459
|
+
/** Recreate a shell installation's missing runtime binding without adopting another CLI's service. */
|
|
460
|
+
export function reconcileMissingShellRuntime(paths) {
|
|
461
|
+
if (process.platform !== "linux" || process.env.COTAL_LAUNCHER !== "1" || process.env.COTAL_INSTALL_RECONCILE !== "1")
|
|
462
|
+
return;
|
|
463
|
+
const root = process.env.npm_config_prefix;
|
|
464
|
+
if (!root || !isAbsolute(root))
|
|
465
|
+
return;
|
|
466
|
+
const { receipt, plan } = recordedUnit(paths, undefined);
|
|
467
|
+
const identity = installedDaemonIdentity(paths);
|
|
468
|
+
const argv = daemonServeArgv(undefined);
|
|
469
|
+
const entry = argv[argv.indexOf("daemon") - 1];
|
|
470
|
+
if (identity.same || identity.installedEntry !== entry || entry !== join(root, "lib", "node_modules", "cotal-ai", "dist", "cotal.js"))
|
|
471
|
+
return;
|
|
472
|
+
const source = readFileSync(receipt.unitPath, "utf8");
|
|
473
|
+
const executable = /^ExecStart="((?:\\.|[^"\\])*)"/m.exec(source)?.[1];
|
|
474
|
+
if (!executable)
|
|
475
|
+
return;
|
|
476
|
+
const old = executable.replace(/\\([\\"])/g, "$1").replaceAll("%%", "%").replaceAll("$$", "$");
|
|
477
|
+
if (!recordedSourceMarked(receipt, plan.mechanism) || !old.startsWith(join(root, "runtime") + "/") || old.split("/").includes("..") || existsSync(old))
|
|
478
|
+
return;
|
|
479
|
+
const next = source.replace(/^ExecStart="(?:\\.|[^"\\])*"/m, `ExecStart=${unitValue(argv[0], true)}`);
|
|
480
|
+
const sha256 = createHash("sha256").update(next).digest("hex");
|
|
481
|
+
// Revalidate the receipt and source immediately before publishing the owned rewrite.
|
|
482
|
+
if (recordedUnit(paths, undefined).receipt.unitSha256 !== receipt.unitSha256)
|
|
483
|
+
throw new CommandFailure("refused", "CONFLICT", "the recorded daemon service changed during installation");
|
|
484
|
+
writeSecretFileAtomic(receipt.unitPath, next);
|
|
485
|
+
try {
|
|
486
|
+
writeSecretFileAtomic(unitReceiptFile(paths), `${JSON.stringify({ ...receipt, unitSha256: sha256 })}\n`);
|
|
487
|
+
}
|
|
488
|
+
catch (error) {
|
|
489
|
+
writeSecretFileAtomic(receipt.unitPath, source);
|
|
490
|
+
throw error;
|
|
491
|
+
}
|
|
492
|
+
assertSystemdSource(receipt.unitPath, sha256);
|
|
493
|
+
submitSystemdUnitRegistration("reload", plan.unit);
|
|
494
|
+
}
|
|
401
495
|
/** The executable and entry pinned by the verified native source, compared with this CLI. */
|
|
402
496
|
export function installedDaemonIdentity(paths, daemonHome) {
|
|
403
497
|
return recordedDaemonIdentity(recordedUnit(paths, daemonHome));
|
|
@@ -766,7 +860,11 @@ export async function restartInstalled(paths, daemonHome, reload = false, expect
|
|
|
766
860
|
/** Stop it, disable autostart, erase its service records under lifetime exclusion, remove the unit
|
|
767
861
|
* and receipt, and reload the user manager (on macOS and Windows, the adapter's deregistration). */
|
|
768
862
|
export async function applyUninstall(paths, daemonHome) {
|
|
769
|
-
const { receipt, plan, service } = recordedUnit(paths, daemonHome);
|
|
863
|
+
const { receipt, plan, service, recovered } = recordedUnit(paths, daemonHome, nativeRun, true);
|
|
864
|
+
if (recovered) {
|
|
865
|
+
submitSystemdUnitControl("stop", plan.unit);
|
|
866
|
+
mkSecretDir(paths.state);
|
|
867
|
+
}
|
|
770
868
|
checkDir(paths.state);
|
|
771
869
|
// Pin a kernel-authenticated connection before removing the supervisor. It can
|
|
772
870
|
// stop only that listener, never a reused PID or a later daemon generation.
|
|
@@ -844,9 +942,11 @@ export async function applyUninstall(paths, daemonHome) {
|
|
|
844
942
|
catch (error) {
|
|
845
943
|
if (error instanceof EndpointRefusal && error.code === "NOT_RUNNING")
|
|
846
944
|
absent = true;
|
|
847
|
-
//
|
|
848
|
-
//
|
|
849
|
-
else if (error.code !== "ECONNRESET"
|
|
945
|
+
// Reset or a Darwin peer closed before identification proves neither a live
|
|
946
|
+
// endpoint nor absence. Reobserve under the same shutdown deadline.
|
|
947
|
+
else if (error.code !== "ECONNRESET"
|
|
948
|
+
&& !(process.platform === "darwin" && error instanceof ClosedPeerRefusal)
|
|
949
|
+
&& !(process.platform === "win32" && stopCommitted && isStoppingLifetime(error, owner)))
|
|
850
950
|
throw error;
|
|
851
951
|
}
|
|
852
952
|
if (absent && (!socket || !owner || (owner.start && processBirth(owner.pid) !== owner.start)) && Date.now() >= observeUntil)
|
|
@@ -868,7 +968,7 @@ export async function applyUninstall(paths, daemonHome) {
|
|
|
868
968
|
throw error;
|
|
869
969
|
}
|
|
870
970
|
// The wait above must not turn a changed source/receipt into deletion authority.
|
|
871
|
-
const current = recordedUnit(paths, daemonHome).receipt;
|
|
971
|
+
const current = recordedUnit(paths, daemonHome, nativeRun, recovered === true).receipt;
|
|
872
972
|
if (current.unitSha256 !== receipt.unitSha256 || current.installedAt !== receipt.installedAt)
|
|
873
973
|
throw uncertain("the daemon installation changed during shutdown");
|
|
874
974
|
let removedServiceRecords;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync
|
|
1
|
+
import { closeSync, constants, fstatSync, lstatSync, openSync, readFileSync } from "node:fs";
|
|
2
2
|
import { dirname, isAbsolute, join } from "node:path";
|
|
3
3
|
import { assertLifecycleToken, mkSecretDir, writeSecretFileAtomic } from "@cotal-ai/core";
|
|
4
4
|
import { spaceSegment, workspaceSecretStore } from "@cotal-ai/workspace";
|
|
@@ -96,8 +96,3 @@ export function validateManagerCleanupAuthority(record) {
|
|
|
96
96
|
if (identity.kind !== saved.storeIdentity.kind || identity.root !== saved.storeIdentity.root || identity.id !== saved.storeIdentity.id)
|
|
97
97
|
throw new Error(`Manager cleanup store identity changed: ${file}`);
|
|
98
98
|
}
|
|
99
|
-
export function clearManagerCleanup(home, space) {
|
|
100
|
-
const file = managerCleanupFile(home, space);
|
|
101
|
-
if (regularFile(file))
|
|
102
|
-
unlinkSync(file);
|
|
103
|
-
}
|