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.
Files changed (57) hide show
  1. package/dist/daemon/client.js +11 -1
  2. package/dist/daemon/command.js +38 -10
  3. package/dist/daemon/connect.js +1 -1
  4. package/dist/daemon/endpoint.js +9 -2
  5. package/dist/daemon/execution-preinstall.js +59 -3
  6. package/dist/daemon/execution-update.js +1 -1
  7. package/dist/daemon/generation.js +3 -4
  8. package/dist/daemon/install.js +115 -15
  9. package/dist/daemon/manager-cleanup.js +1 -6
  10. package/dist/daemon/manager.js +59 -27
  11. package/dist/daemon/preinstall-preservation.js +46 -0
  12. package/dist/daemon/protocol.js +2 -2
  13. package/dist/daemon/server.js +1 -1
  14. package/dist/daemon/service.js +1 -1
  15. package/dist/daemon/update-entry.js +96 -6
  16. package/dist/daemon/update-generation.js +11 -3
  17. package/dist/docs.js +1 -1
  18. package/dist/execution-transaction.js +21 -0
  19. package/dist/mcp-host.js +116 -0
  20. package/dist/mcp.js +64 -0
  21. package/dist/run.js +2 -0
  22. package/package.json +19 -19
  23. package/seeded-connectors/_shared/docs-bundle.bin +0 -0
  24. package/seeded-connectors/_shared/docs-index.bin +0 -0
  25. package/seeded-connectors/_shared/placements.json +2 -2
  26. package/seeded-connectors/claude/dist/index.js +2 -2
  27. package/seeded-connectors/claude/dist/mcp.cjs +7 -7
  28. package/seeded-connectors/claude/package.json +1 -1
  29. package/seeded-connectors/codex/dist/host.js +6 -6
  30. package/seeded-connectors/codex/dist/index.js +2 -2
  31. package/seeded-connectors/codex/dist/personal.js +7 -7
  32. package/seeded-connectors/codex/package.json +1 -1
  33. package/seeded-connectors/hermes/dist/index.js +2 -2
  34. package/seeded-connectors/hermes/dist/launch.js +6 -6
  35. package/seeded-connectors/hermes/package.json +1 -1
  36. package/seeded-connectors/hermes/plugin/cotal/_sidecar/standalone.cjs +6 -6
  37. package/seeded-connectors/jcode/dist/host.js +6 -6
  38. package/seeded-connectors/jcode/dist/index.js +2 -2
  39. package/seeded-connectors/jcode/dist/mcp.js +2 -2
  40. package/seeded-connectors/jcode/package.json +1 -1
  41. package/seeded-connectors/opencode/dist/index.js +2 -2
  42. package/seeded-connectors/opencode/dist/plugin/index.js +6 -6
  43. package/seeded-connectors/opencode/package.json +1 -1
  44. package/seeded-connectors/pi/README.md +8 -4
  45. package/seeded-connectors/pi/dist/driver.d.ts +2 -0
  46. package/seeded-connectors/pi/dist/driver.d.ts.map +1 -1
  47. package/seeded-connectors/pi/dist/index.js +6 -6
  48. package/seeded-connectors/pi/dist/standalone.js +9 -9
  49. package/seeded-connectors/pi/package.json +1 -1
  50. package/seeded-connectors/web/dist/service-adapter.d.ts.map +1 -1
  51. package/seeded-connectors/web/dist/service-adapter.js +16 -12
  52. package/seeded-connectors/web/dist/service-adapter.js.map +1 -1
  53. package/seeded-connectors/web/dist/web.d.ts +7 -1
  54. package/seeded-connectors/web/dist/web.d.ts.map +1 -1
  55. package/seeded-connectors/web/dist/web.js +15 -7
  56. package/seeded-connectors/web/dist/web.js.map +1 -1
  57. package/seeded-connectors/web/package.json +1 -1
@@ -14,6 +14,8 @@ import { daemonPaths, daemonPathsFor } from "./endpoint.js";
14
14
  import { daemonStartedByOwnedService, installedDaemonIdentity, unitReceiptFile } from "./install.js";
15
15
  import { readHostedAgents } from "./agents.js";
16
16
  import { readManagerCleanup, writeManagerCleanup, validateManagerCleanupAuthority, managerCleanupFile } from "./manager-cleanup.js";
17
+ import { processBirth } from "./lifetime.js";
18
+ import { probeLiveness } from "@cotal-ai/workspace/liveness";
17
19
  export const daemonManagerRoot = (space, home) => join(home, "daemon", spaceSegment(space), "manager");
18
20
  export const daemonManagerIntentFile = (space, home) => join(home, "daemon", spaceSegment(space), "manager-host.json");
19
21
  /** Forget only the daemon's per-space hosting records after its owned service was removed. */
@@ -67,6 +69,56 @@ export function createHostedManagers(home = homeCotalDir(), version = installedG
67
69
  return task;
68
70
  };
69
71
  const generationAttempts = new Map();
72
+ const abortGenerationRestart = (owner) => queueGeneration(async () => {
73
+ if (!generationOwners.delete(owner) && !generationReleases.has(owner))
74
+ return;
75
+ if (generationOwners.size !== 0)
76
+ return;
77
+ generationReleases.add(owner);
78
+ generationPrepared = false;
79
+ for (const [child, attemptId] of generationAttempts) {
80
+ await generationCall(child, attemptId, "abort");
81
+ generationAttempts.delete(child);
82
+ }
83
+ generationReleases.clear();
84
+ generationPending = generationAcquisitions !== 0;
85
+ if (!generationPending)
86
+ for (const l of live.values()) {
87
+ if (!l.child && !l.starting && !l.timer && l.view.state === "restarting")
88
+ schedule(l);
89
+ else if (l.child)
90
+ observe(l);
91
+ }
92
+ });
93
+ let reapingGeneration = false;
94
+ const generationReaper = setInterval(() => {
95
+ if (closed || reapingGeneration)
96
+ return;
97
+ reapingGeneration = true;
98
+ void (async () => {
99
+ for (const owner of new Set([...generationOwners, ...generationReleases])) {
100
+ let record;
101
+ try {
102
+ record = JSON.parse(owner);
103
+ }
104
+ catch {
105
+ continue;
106
+ }
107
+ if (!Array.isArray(record) || record[0] !== "peer" || !Number.isSafeInteger(record[2]) || typeof record[3] !== "string")
108
+ continue;
109
+ const pid = record[2];
110
+ try {
111
+ const start = processBirth(pid);
112
+ if (start !== undefined ? start !== record[3] : probeLiveness(pid) === "dead") {
113
+ await abortGenerationRestart(owner);
114
+ console.log(`machine daemon: released the preserving hold of updater ${pid} because that process ended`);
115
+ }
116
+ }
117
+ catch { /* Unknown custody keeps the fence and retries on the next bounded observation. */ }
118
+ }
119
+ })().finally(() => { reapingGeneration = false; });
120
+ }, 1000);
121
+ generationReaper.unref();
70
122
  const generationCall = (child, attemptId, op) => new Promise((resolve, reject) => {
71
123
  if (child.exitCode !== null || child.signalCode !== null) {
72
124
  resolve(undefined);
@@ -807,13 +859,13 @@ export function createHostedManagers(home = homeCotalDir(), version = installedG
807
859
  },
808
860
  prepareGenerationRestart(owner) {
809
861
  generationPending = true;
862
+ generationOwners.add(owner);
810
863
  generationAcquisitions++;
811
864
  return queueGeneration(async () => {
812
865
  generationAcquisitions--;
813
- if (generationPrepared) {
814
- generationOwners.add(owner);
866
+ generationOwners.add(owner);
867
+ if (generationPrepared)
815
868
  return;
816
- }
817
869
  try {
818
870
  await Promise.all([...live.values()].map((l) => l.healthTask));
819
871
  // A timed-out prepare can still have landed. Roll back every retained attempt before retrying.
@@ -881,6 +933,8 @@ export function createHostedManagers(home = homeCotalDir(), version = installedG
881
933
  }
882
934
  catch { /* Retain the exact attempt for rollback on the next automatic retry. */ }
883
935
  }
936
+ if (generationAttempts.size === 0)
937
+ generationOwners.delete(owner);
884
938
  generationPending = generationAttempts.size !== 0 || generationAcquisitions !== 0;
885
939
  if (!generationPending)
886
940
  for (const l of live.values()) {
@@ -893,30 +947,7 @@ export function createHostedManagers(home = homeCotalDir(), version = installedG
893
947
  }
894
948
  });
895
949
  },
896
- abortGenerationRestart(owner) {
897
- return queueGeneration(async () => {
898
- if (!generationOwners.delete(owner) && !generationReleases.has(owner))
899
- return;
900
- if (generationOwners.size !== 0)
901
- return;
902
- // Keep release authority and exact child attempts if an abort is unconfirmed.
903
- generationReleases.add(owner);
904
- generationPrepared = false;
905
- for (const [child, attemptId] of generationAttempts) {
906
- await generationCall(child, attemptId, "abort");
907
- generationAttempts.delete(child);
908
- }
909
- generationReleases.clear();
910
- generationPending = generationAcquisitions !== 0;
911
- if (!generationPending)
912
- for (const l of live.values()) {
913
- if (!l.child && !l.starting && !l.timer && l.view.state === "restarting")
914
- schedule(l);
915
- else if (l.child)
916
- observe(l);
917
- }
918
- });
919
- },
950
+ abortGenerationRestart,
920
951
  all: () => [...new Set([...spaces(true), ...live.keys()])].map(status),
921
952
  async disconnect(space, options) {
922
953
  // A crash during child shutdown must not restore a withdrawn hosting intent.
@@ -1064,6 +1095,7 @@ export function createHostedManagers(home = homeCotalDir(), version = installedG
1064
1095
  },
1065
1096
  async close() {
1066
1097
  closed = true;
1098
+ clearInterval(generationReaper);
1067
1099
  await Promise.all([...live.values()].map(async (l) => {
1068
1100
  l.stopping = true;
1069
1101
  closeProbeSession(l);
@@ -0,0 +1,46 @@
1
+ import { constants, closeSync, fstatSync, openSync, readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { homeCotalDir } from "@cotal-ai/workspace";
4
+ import { probeLiveness } from "@cotal-ai/workspace/liveness";
5
+ import { processStartToken } from "@cotal-ai/core";
6
+ /** Inspect existing records only. Missing or unreadable ownership never proves death. */
7
+ export function preinstallPreservationObservation(status) {
8
+ if (!Array.isArray(status.managers))
9
+ return { owner: "unknown", age: "unknown", seats: "unknown" };
10
+ const active = status.managers.filter(row => row.pid !== undefined);
11
+ const evidence = status.update?.restartEvidence;
12
+ const complete = evidence?.prepared === true && evidence.managers.length === active.length
13
+ && new Set(evidence.managers.map(row => row.space)).size === active.length
14
+ && active.every(manager => evidence.managers.some(row => row.space === manager.space && row.fenced === true && Number.isSafeInteger(row.seats) && row.seats >= 0));
15
+ const seats = complete ? evidence.managers.reduce((sum, row) => sum + row.seats, 0) : "unknown";
16
+ let owner = "unknown", age = "unknown";
17
+ let fd;
18
+ try {
19
+ fd = openSync(join(homeCotalDir(), ".update-closure.lock"), constants.O_RDONLY | constants.O_NOFOLLOW);
20
+ const st = fstatSync(fd);
21
+ if (!st.isFile() || st.nlink !== 1 || st.size > 65536 || (st.mode & 0o022) !== 0 || (process.getuid && st.uid !== process.getuid()))
22
+ return { owner, age, seats };
23
+ const record = JSON.parse(readFileSync(fd, "utf8"));
24
+ if (!Number.isSafeInteger(record.pid) || Number(record.pid) <= 0 || typeof record.start !== "string" || !record.start || typeof record.nonce !== "string" || !record.nonce)
25
+ return { owner, age, seats };
26
+ if (typeof record.ts === "number" && Number.isFinite(record.ts) && record.ts <= Date.now())
27
+ age = `${Math.floor((Date.now() - record.ts) / 1000)} s since the recorded update closure`;
28
+ const pid = Number(record.pid), birth = processStartToken(pid);
29
+ if (birth !== undefined && birth !== record.start || birth === undefined && probeLiveness(pid) === "dead")
30
+ owner = "gone";
31
+ else if (birth === record.start) {
32
+ const env = process.env;
33
+ const delegated = env.COTAL_UPDATE_CLOSURE_OWNER === String(pid) && env.COTAL_UPDATE_CLOSURE_START === record.start && env.COTAL_UPDATE_CLOSURE_NONCE === record.nonce;
34
+ owner = pid === process.pid || delegated ? "transaction" : "live";
35
+ }
36
+ }
37
+ catch { /* Unknown custody is a refusal, not recovery authority. */ }
38
+ finally {
39
+ if (fd !== undefined)
40
+ closeSync(fd);
41
+ }
42
+ return { owner, age, seats };
43
+ }
44
+ export function preservingPreinstallRefusal(observation) {
45
+ return new Error(`manager is in preserving mode; hold age ${observation.age}; seats ${observation.seats}; update owner ${observation.owner}. Wait for a running update to finish, then run \`cotal update --self\` again. No hold was released by this check.`);
46
+ }
@@ -15,7 +15,7 @@
15
15
  import { computerName } from "./name-validation.js";
16
16
  import { normalizeIdpUrl } from "@cotal-ai/auth";
17
17
  import { DAEMON_PROTOCOL_VERSION, MAX_LINE_BYTES } from "./endpoint.js";
18
- export const DAEMON_OPS = ["update-settings", "update-check", "name", "daemon-stop", "space-intent", "status", "spaces", "manager-start", "manager-status", "managers-stop", "managers-prepare-restart", "managers-abort-restart", "login-start", "login-cancel", "logout", "connect-check", "register", "service-connect", "service-disconnect", "service-status"];
18
+ const DAEMON_OPS = ["update-settings", "update-check", "name", "daemon-stop", "space-intent", "status", "spaces", "manager-start", "manager-status", "managers-stop", "managers-prepare-restart", "managers-abort-restart", "login-start", "login-cancel", "logout", "connect-check", "register", "service-connect", "service-disconnect", "service-status"];
19
19
  /** The fields each op takes besides `v`, `id` and `op`. Required ones must be present. */
20
20
  const OP_FIELDS = {
21
21
  "update-settings": { required: [], optional: ["auto", "notify"] },
@@ -42,7 +42,7 @@ const OP_FIELDS = {
42
42
  const ENVELOPE_KEYS = new Set(["v", "id", "op"]);
43
43
  const ID_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
44
44
  /** An attempt id is daemon-minted: 22 characters of base64url. */
45
- export const ATTEMPT_PATTERN = /^[A-Za-z0-9_-]{22}$/;
45
+ const ATTEMPT_PATTERN = /^[A-Za-z0-9_-]{22}$/;
46
46
  const MAX_CLIENT_ID = 128;
47
47
  /** A space name as it appears in a subject token. */
48
48
  export const SPACE_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
@@ -33,7 +33,7 @@ import { createHostedManagers, HostedManagerRefusal } from "./manager.js";
33
33
  import { createAccountReconciler } from "./account-reconcile.js";
34
34
  import { createAccountComputer } from "./account.js";
35
35
  /** Requests one connection may send. A sign-in needs two (start, cancel); status polling a few. */
36
- export const MAX_REQUESTS_PER_CONNECTION = 64;
36
+ const MAX_REQUESTS_PER_CONNECTION = 64;
37
37
  function listen(server, path) {
38
38
  return new Promise((resolve, reject) => {
39
39
  const onError = (e) => {
@@ -148,7 +148,7 @@ function intentSpace(path) {
148
148
  return daemonConnectIntentFile(r.space, join(path, "..", "..", "..")) === path ? r.space : undefined;
149
149
  }
150
150
  /** Whether this daemon already recorded a successful per-space connection. */
151
- export function hasDaemonConnectIntent(space, home) {
151
+ function hasDaemonConnectIntent(space, home) {
152
152
  return intentSpace(daemonConnectIntentFile(space, home)) === space;
153
153
  }
154
154
  export function createServiceConnections(home = homeCotalDir()) {
@@ -3,18 +3,19 @@ import { existsSync } from "node:fs";
3
3
  import { dirname, join } from "node:path";
4
4
  import { createInterface } from "node:readline/promises";
5
5
  import { registry } from "@cotal-ai/core";
6
- import { update, updateRuntime, installedCliVersion, localUpdateManagers, readManagerContinuity, updateManagerPin } from "@cotal-ai/cli/update";
6
+ import { update, updateRuntime, installedCliVersion, localUpdateManagers, readManagerContinuity, updateManagerPin, repairInstallModes } from "@cotal-ai/cli/update";
7
7
  import { withIdpSessionDir, withRemoteExchangeRetry } from "@cotal-ai/auth";
8
8
  import { brokerAddressKey, assertRecordIdentity, CommandFailure, homeCotalDir, readUpdateRecovery, claimUpdateClosureAccess, resolveControlTarget } from "@cotal-ai/workspace";
9
9
  import { askManager } from "@cotal-ai/workspace/control";
10
10
  import { daemonPaths, EndpointRefusal } from "./endpoint.js";
11
11
  import { managerViaDaemon, queryDaemon } from "./client.js";
12
- import { installedDaemonIdentity, preflightInstalledDaemon, restartInstalled, startEnabledInstalled, unitReceiptFile } from "./install.js";
12
+ import { installedDaemonIdentity, preflightInstalledDaemon, reconcileMissingShellRuntime, restartInstalled, startEnabledInstalled, unitReceiptFile } from "./install.js";
13
13
  import { excludeLifetime, processBirth, readLifetimeRecord } from "./lifetime.js";
14
14
  import { waitForInstalledDaemonGeneration } from "./update-generation.js";
15
15
  import { cleanupExecutionStore } from "../execution-store.js";
16
+ import { repairExecutionInstallModes } from "../execution-transaction.js";
16
17
  import { prepareExecutionUpdate, preflightExecutionUpdate, recoverExecutionUpdate, executionInstallRoot } from "./execution-update.js";
17
- import { logicalExecutionEntry } from "@cotal-ai/workspace";
18
+ import { findMesh, logicalExecutionEntry, pruneRetainedConnectorConfig, retainConnectorConfig, shellPath } from "@cotal-ai/workspace";
18
19
  import { reportRunningManagers } from "@cotal-ai/cli/update";
19
20
  import { adoptAutomaticUpdateChild } from "./update-scope.js";
20
21
  import { captureWindowsGeneration, closeWindowsGeneration, windowsGenerationLifecycle } from "./update-generation-win32.js";
@@ -69,6 +70,56 @@ function assertDaemonReachable() {
69
70
  if (lifetime?.start && processBirth(lifetime.pid) === lifetime.start)
70
71
  throw new Error("the machine daemon is running and this session has no XDG_RUNTIME_DIR to reach it; run the update from a login session of this account, or leave it to the daemon's automatic update");
71
72
  }
73
+ async function collectConnectorSets() {
74
+ try {
75
+ const entry = logicalExecutionEntry();
76
+ if (!entry || updateRuntime.checkout())
77
+ return;
78
+ const release = claimUpdateClosureAccess();
79
+ try {
80
+ const holders = [];
81
+ const managers = localUpdateManagers({}, entry);
82
+ for (const manager of managers) {
83
+ if (!manager.process || assertRecordIdentity(manager.process).kind !== "match")
84
+ return;
85
+ const target = await resolveControlTarget({ space: manager.space, server: manager.server }, "control-caller-admin", manager.instanceId, { onRefusal: "throw", readOnly: true });
86
+ const reply = await askManager({ versionSkew: text => text, roster: async () => [] }, manager.space, target.server, "managerStatus", undefined, target.auth, "owner", 3000, { instanceId: manager.instanceId });
87
+ if (!reply.ok || assertRecordIdentity(manager.process).kind !== "match")
88
+ return;
89
+ const version = reply.data?.version;
90
+ holders.push(typeof version === "string" ? version : undefined);
91
+ }
92
+ try {
93
+ const paths = daemonPaths();
94
+ const reply = await queryDaemon({ paths });
95
+ if (!reply.ok)
96
+ return;
97
+ const lifetime = readLifetimeRecord(paths.lock);
98
+ if (!lifetime?.start || lifetime.pid !== reply.result.pid || processBirth(lifetime.pid) !== lifetime.start)
99
+ return;
100
+ // Hosted Managers can remain on an earlier generation than their daemon.
101
+ // Their separate records must all have appeared in the authenticated inventory.
102
+ if ((reply.result.managers ?? []).some(row => row.pid !== undefined && !managers.some(manager => manager.pid === row.pid && manager.instanceId === row.instanceId)))
103
+ return;
104
+ holders.push(reply.result.version);
105
+ }
106
+ catch (error) {
107
+ if (!(error instanceof EndpointRefusal) || !["NOT_RUNNING", "NO_RUNTIME_DIR"].includes(error.code))
108
+ return;
109
+ if (error.code === "NO_RUNTIME_DIR" && existsSync(join(homeCotalDir(), "daemon", "daemon.lock")))
110
+ return;
111
+ assertDaemonReachable();
112
+ }
113
+ if (managers.some(manager => !manager.process || assertRecordIdentity(manager.process).kind !== "match"))
114
+ return;
115
+ pruneRetainedConnectorConfig(holders);
116
+ }
117
+ finally {
118
+ release();
119
+ }
120
+ }
121
+ catch { /* An incomplete inventory or failed collection never fails the update. */ }
122
+ }
72
123
  const command = registry.resolve("command", "update");
73
124
  registry.unregister("command", "update");
74
125
  const composed = { ...command, async run(args) {
@@ -76,13 +127,14 @@ const composed = { ...command, async run(args) {
76
127
  let daemonObserved = false;
77
128
  let preparedRestart = false;
78
129
  let currentPackages = false;
130
+ let retainedReconciliation = false;
79
131
  let askedToStop = false;
80
132
  let targetReceipt;
81
133
  let replacementVersion;
82
134
  let targetAdmissionChecked = false;
83
135
  let recoveryFence = false;
84
136
  const retainsExecution = () => targetReceipt !== undefined || readUpdateRecovery()?.execution !== undefined;
85
- const reportsRetainedExecution = () => retainsExecution() || (currentPackages && logicalExecutionEntry() !== undefined && !updateRuntime.checkout() && (process.platform === "linux" || process.platform === "darwin"));
137
+ const reportsRetainedExecution = () => retainedReconciliation || retainsExecution() || (currentPackages && logicalExecutionEntry() !== undefined && !updateRuntime.checkout() && (process.platform === "linux" || process.platform === "darwin"));
86
138
  const retainedReads = (flags) => readManagerContinuity(flags, { readOnly: true, retainGraph: true, installedEntry: logicalExecutionEntry() });
87
139
  const retainedReport = (flags) => reportRunningManagers(flags, retainedReads, selected => localUpdateManagers(selected, logicalExecutionEntry()));
88
140
  try {
@@ -91,6 +143,7 @@ const composed = { ...command, async run(args) {
91
143
  const runtime = { ...updateRuntime,
92
144
  ...(logicalExecutionEntry() && !updateRuntime.checkout() && (process.platform === "linux" || process.platform === "darwin") ? {
93
145
  preflightExecution: preflightExecutionUpdate,
146
+ repairInstallModes: (root) => repairExecutionInstallModes(executionInstallRoot(), () => repairInstallModes(root)),
94
147
  executionGlobalRoot: () => dirname(executionInstallRoot()),
95
148
  prepareExecution: async (version, root) => {
96
149
  assertDaemonReachable();
@@ -99,7 +152,41 @@ const composed = { ...command, async run(args) {
99
152
  return execution;
100
153
  },
101
154
  recoverExecution: recoverExecutionUpdate,
102
- } : {}), isCurrent() {
155
+ } : {}), async prepareReconciliation(flags) {
156
+ const entry = logicalExecutionEntry();
157
+ if (!entry || updateRuntime.checkout() || !["linux", "darwin"].includes(process.platform) || process.env.COTAL_UPDATE_PARENT || readUpdateRecovery())
158
+ return;
159
+ try {
160
+ const daemon = await queryDaemon({ paths: daemonPaths() });
161
+ if (!daemon.ok)
162
+ throw new Error(`machine daemon custody is unreadable: ${daemon.error.message}`);
163
+ return; // Hosted daemon admission and restart handling remain unchanged.
164
+ }
165
+ catch (error) {
166
+ if (!(error instanceof EndpointRefusal) || !["NOT_RUNNING", "NO_RUNTIME_DIR"].includes(error.code))
167
+ throw error;
168
+ if (error.code === "NO_RUNTIME_DIR")
169
+ assertDaemonReachable();
170
+ }
171
+ const managers = localUpdateManagers(flags, entry);
172
+ if (!managers.length)
173
+ return;
174
+ for (const manager of managers) {
175
+ if (!manager.process || assertRecordIdentity(manager.process).kind !== "match")
176
+ throw new Error(`local Manager ${manager.instanceId} changed before reconciliation admission`);
177
+ await retainedReads({ ...flags, space: manager.space, server: manager.server, on: manager.instanceId });
178
+ if (assertRecordIdentity(manager.process).kind !== "match")
179
+ throw new Error(`local Manager ${manager.instanceId} changed during reconciliation admission`);
180
+ }
181
+ retainConnectorConfig();
182
+ retainedReconciliation = true;
183
+ for (const manager of managers) {
184
+ const command = findMesh(manager.space)?.userAuth?.remote
185
+ ? `cotal manager restart --with-agents --yes --space ${shellPath(manager.space)}`
186
+ : `cotal down --with-agents --yes --space ${shellPath(manager.space)} && cotal up --space ${shellPath(manager.space)}`;
187
+ console.log(`Manager ${manager.instanceId} keeps its agents on the previous version and takes the installed version at its next restart. When their work is finished, restart from its recorded folder: cd ${shellPath(manager.root)} && ${command}`);
188
+ }
189
+ }, isCurrent() {
103
190
  currentPackages = updateRuntime.isCurrent?.() === true;
104
191
  return currentPackages;
105
192
  }, async automaticUpdateAdvice() {
@@ -342,6 +429,7 @@ const composed = { ...command, async run(args) {
342
429
  await update(args, runtime);
343
430
  if (args.values.check === true || args.values.auto || args.values.notify || process.exitCode)
344
431
  return;
432
+ await collectConnectorSets();
345
433
  // The daemon started this update and restarts itself once this process has exited. A restart
346
434
  // asked for from here would stop this process with the rest of the service.
347
435
  if (process.env.COTAL_AUTO_UPDATE === "1")
@@ -351,7 +439,7 @@ const composed = { ...command, async run(args) {
351
439
  // A version-changing update already waited for the installed generation before it returned.
352
440
  // Waiting again prints the same line a second time in this process.
353
441
  if (!daemonObserved) {
354
- if (args.values.self === true && runtime.generationWaited !== true) {
442
+ if ((args.values.self === true || process.env.COTAL_INSTALL_RECONCILE === "1") && runtime.generationWaited !== true) {
355
443
  await waitForInstalledDaemonGeneration(expectedVersion, {
356
444
  lifecycle: (paths, deadline) => process.platform === "win32" ? windowsGenerationLifecycle(paths, deadline) : posixGenerationLifecycle(paths),
357
445
  });
@@ -368,6 +456,8 @@ const composed = { ...command, async run(args) {
368
456
  console.log(`machine daemon: PID ${current.result.pid} runs Cotal ${current.result.version}; no recorded user service, left running`);
369
457
  return;
370
458
  }
459
+ if (process.env.COTAL_INSTALL_RECONCILE === "1")
460
+ reconcileMissingShellRuntime(paths);
371
461
  const installation = installedDaemonIdentity(paths);
372
462
  if (!installation.same) {
373
463
  console.log(`machine daemon: ${installation.installed} runs Cotal ${current.result.version}; another installation was left running`);
@@ -3,7 +3,7 @@ import { existsSync } from "node:fs";
3
3
  import { CommandFailure, homeCotalDir } from "@cotal-ai/workspace";
4
4
  import { queryDaemon } from "./client.js";
5
5
  import { daemonPaths, EndpointRefusal } from "./endpoint.js";
6
- import { installedDaemonIdentity, unitReceiptFile } from "./install.js";
6
+ import { installedDaemonIdentity, reconcileMissingShellRuntime, unitReceiptFile } from "./install.js";
7
7
  import { daemonManagerIntentFile } from "./manager.js";
8
8
  export async function waitForInstalledDaemonGeneration(version, probe = {}) {
9
9
  let paths;
@@ -23,16 +23,19 @@ export async function waitForInstalledDaemonGeneration(version, probe = {}) {
23
23
  else {
24
24
  if (!existsSync(unitReceiptFile(paths)))
25
25
  return;
26
+ reconcileMissingShellRuntime(paths);
26
27
  const installation = installedDaemonIdentity(paths);
27
28
  if (!installation.same) {
28
- console.log(`machine daemon: the background service belongs to another Cotal installation (${installation.installedEntry}). This update left it stopped.`);
29
+ if (!probe.quiet)
30
+ console.log(`machine daemon: the background service belongs to another Cotal installation (${installation.installedEntry}). This update left it stopped.`);
29
31
  return;
30
32
  }
31
33
  }
32
34
  const query = probe.query ?? queryDaemon;
33
35
  const bound = probe.timeoutMs ?? 120_000;
36
+ const waitLine = `machine daemon: waiting up to ${Math.round(bound / 1000)}s for Cotal ${version} and its hosted Managers before the continuity check`;
34
37
  if (!probe.quiet)
35
- console.log(`machine daemon: waiting up to ${Math.round(bound / 1000)}s for Cotal ${version} and its hosted Managers before the continuity check`);
38
+ console.log(waitLine);
36
39
  const deadline = Date.now() + bound;
37
40
  let waiting = "the recorded daemon has not answered";
38
41
  const lifecycle = await probe.lifecycle?.(paths, deadline);
@@ -81,6 +84,11 @@ export async function waitForInstalledDaemonGeneration(version, probe = {}) {
81
84
  await new Promise(resolve => setTimeout(resolve, Math.min(250, Math.max(0, deadline - Date.now()))));
82
85
  }
83
86
  }
87
+ catch (error) {
88
+ if (probe.quiet)
89
+ console.log(waitLine);
90
+ throw error;
91
+ }
84
92
  finally {
85
93
  lifecycle?.close();
86
94
  }
package/dist/docs.js CHANGED
@@ -9,7 +9,7 @@ import { registry } from "@cotal-ai/core";
9
9
  import { CommandFailure, jsonFlag, plainFlag, presentationOf, writeResult } from "@cotal-ai/workspace";
10
10
  const searchFlag = { name: "search", type: "string", value: "<query>", description: "show the sections that best match a query" };
11
11
  const refreshFlag = { name: "refresh", type: "boolean", description: "also try the version-pinned copy of the page on docs.cotal.ai" };
12
- export const docsFlags = [searchFlag, refreshFlag, jsonFlag, plainFlag];
12
+ const docsFlags = [searchFlag, refreshFlag, jsonFlag, plainFlag];
13
13
  const usage = (message) => new CommandFailure("refused", "USAGE_INVALID", message);
14
14
  /** Every page name `docs <page>` reads. */
15
15
  const pageSlugs = (d) => ["spec", "lang", "schema", ...d.docsIndex().pages.map((p) => p.slug)];
@@ -111,6 +111,27 @@ export function executionStagingPrefix(installed) {
111
111
  protectedExecutionEntry(store);
112
112
  return mkdtempSync(join(store, ".installing-"));
113
113
  }
114
+ /** Rebind only the already selected launch route after our own mode-only hardening. */
115
+ export function repairExecutionInstallModes(installed, repair) {
116
+ const selected = selectExecutionProgram(installed);
117
+ const descriptor = selected.retained ? executionRecord(executionDescriptorPath(installed)) : undefined;
118
+ const changed = repair();
119
+ if (descriptor?.launch) {
120
+ const launch = executionLaunchBinding(installed, descriptor.launch.entry);
121
+ const { ctime: before, ...previous } = descriptor.launch;
122
+ const { ctime: after, ...current } = launch;
123
+ if (JSON.stringify(previous) !== JSON.stringify(current))
124
+ throw new Error("execution launch route changed during permission repair");
125
+ if (before !== after) {
126
+ if (!changed)
127
+ throw new Error("execution launch route changed without a permission repair");
128
+ writeExecutionDescriptor(installed, { ...descriptor, launch });
129
+ }
130
+ if (selectExecutionProgram(installed).root !== selected.root)
131
+ throw new Error("selected execution changed during permission repair");
132
+ }
133
+ return changed;
134
+ }
114
135
  /** Remove a superseded active descriptor after an in-place package-manager install took over. */
115
136
  export function retireSupersededExecutionDescriptor(installed) {
116
137
  if (existsSync(join(installed, "desktop-runtime.json")) || (process.platform !== "linux" && process.platform !== "darwin"))
@@ -0,0 +1,116 @@
1
+ /** Identity custody for an MCP-only host. One stdio process owns one local mesh connection. */
2
+ import { execFile } from "node:child_process";
3
+ import { randomUUID } from "node:crypto";
4
+ import { configFromEnv, MeshAgent, NameTaken, } from "@cotal-ai/connector-core";
5
+ import { resolveTargetOrThrow } from "@cotal-ai/workspace";
6
+ import { selfArgv } from "@cotal-ai/cli/self-exec";
7
+ /** The host never invents a native conversation for a signed-in space. Static identities use the
8
+ * terminal-seat contract: the credential and generation last to its horizon, without renewal. */
9
+ export function createMcpHost(space) {
10
+ const session = `mcp-${randomUUID()}`;
11
+ const account = "stdio";
12
+ const cotal = selfArgv();
13
+ let held;
14
+ let ending = false;
15
+ let operations = Promise.resolve();
16
+ const serial = (fn) => {
17
+ const next = operations.then(fn);
18
+ operations = next.catch(() => { });
19
+ return next;
20
+ };
21
+ const plumbing = (args) => new Promise((resolve, reject) => {
22
+ execFile(cotal[0], [...cotal.slice(1), "app-identity", ...args], { timeout: 60_000 }, (_error, stdout) => {
23
+ try {
24
+ resolve(JSON.parse(stdout));
25
+ }
26
+ catch {
27
+ reject(new Error("the CLI returned no identity result; any recovery record was retained"));
28
+ }
29
+ });
30
+ });
31
+ const release = async () => {
32
+ if (!held)
33
+ return;
34
+ // A failed retirement remains owned, but may never route another tool to a stopped agent.
35
+ held.stopped = true;
36
+ await held.connection?.agent.stop();
37
+ const result = await plumbing(["retire", "--dir", held.dir]);
38
+ if (!result.ok)
39
+ throw new Error("identity cleanup is unfinished; call cotal_disconnect again to retry it");
40
+ held = undefined;
41
+ };
42
+ const open = async (name, selection) => {
43
+ if (ending)
44
+ throw new Error("the MCP host is shutting down");
45
+ if (held && !held.stopped)
46
+ throw new Error("this stdio host already has a connection; disconnect it before connecting again");
47
+ await release();
48
+ const target = await resolveTargetOrThrow(space === undefined ? {} : { space });
49
+ if (target.mode === "user")
50
+ throw new Error("cotal mcp has no native conversation identity for a signed-in space; use its hosted connector or a native Cotal connector instead");
51
+ const result = await plumbing(["provision", "--name", name, "--space", target.space, "--session", session,
52
+ ...(selection ? ["--selection", JSON.stringify(selection)] : [])]);
53
+ if (!result.ok) {
54
+ if (result.taken)
55
+ throw new NameTaken(name);
56
+ throw new Error(result.error ?? "identity provisioning failed");
57
+ }
58
+ if (!result.retire?.dir)
59
+ throw new Error("the CLI returned no identity retirement handle");
60
+ held = { dir: result.retire.dir, stopped: false };
61
+ try {
62
+ // Inherited launch metadata must never override the identity just issued for this host.
63
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("COTAL_")));
64
+ Object.assign(env, result.env);
65
+ const config = configFromEnv(env);
66
+ config.connector = "mcp";
67
+ config.turnRelay = false;
68
+ const agent = new MeshAgent(config, env, { withholdProcessCwd: true });
69
+ const connection = { id: randomUUID(), agent, config };
70
+ held.connection = connection;
71
+ agent.on("error", () => process.stderr.write("[cotal mcp] connection error; inspect cotal_connection_status\n"));
72
+ // Keep the startup promise observed even when the bounded readiness wait fails first.
73
+ const start = agent.start();
74
+ void start.catch(() => { });
75
+ await agent.waitUntilConnected(20_000);
76
+ await start;
77
+ if (ending)
78
+ throw new Error("the MCP host is shutting down");
79
+ return connection;
80
+ }
81
+ catch (error) {
82
+ try {
83
+ await release();
84
+ }
85
+ catch {
86
+ throw new Error("connection startup failed and identity cleanup is unfinished; connect again to retry cleanup");
87
+ }
88
+ throw error;
89
+ }
90
+ };
91
+ return {
92
+ account: () => account,
93
+ open: (caller, name, _context, selection) => serial(async () => {
94
+ if (caller !== account)
95
+ throw new Error("this connection belongs to another account");
96
+ return open(name, selection);
97
+ }),
98
+ async find(caller, id) {
99
+ if (caller !== account || held?.connection?.id !== id)
100
+ return undefined;
101
+ if (held.stopped || ending)
102
+ throw new Error("this connection stopped serving; disconnect to finish its identity cleanup");
103
+ return held.connection;
104
+ },
105
+ close: (caller, id) => serial(async () => {
106
+ if (caller !== account || held?.connection?.id !== id)
107
+ return false;
108
+ await release();
109
+ return true;
110
+ }),
111
+ closeAll() {
112
+ ending = true;
113
+ return serial(release);
114
+ },
115
+ };
116
+ }
package/dist/mcp.js ADDED
@@ -0,0 +1,64 @@
1
+ /** Stock stdio MCP entry point, composed here so the CLI implementation stays adapter-independent. */
2
+ import { registry } from "@cotal-ai/core";
3
+ import { CommandFailure } from "@cotal-ai/workspace";
4
+ import { ownStdoutErrors } from "@cotal-ai/cli/dispatch";
5
+ const flags = [
6
+ { name: "space", type: "string", value: "<name>", description: "the registered local space to connect to" },
7
+ ];
8
+ const command = {
9
+ kind: "command",
10
+ name: "mcp",
11
+ group: "Agents",
12
+ summary: "serve Cotal tools over stdio for an MCP-only host",
13
+ usage: "cotal mcp [--space <name>]",
14
+ flags,
15
+ validate(args) {
16
+ if (args.positionals.length || (args.values.space !== undefined && !String(args.values.space).trim()))
17
+ throw new CommandFailure("refused", "USAGE_INVALID", "usage: cotal mcp [--space <name>]");
18
+ },
19
+ async run(args) {
20
+ const { serveGatewayStdio } = await import("@cotal-ai/connector-core");
21
+ const { createMcpHost } = await import("./mcp-host.js");
22
+ const host = createMcpHost(args.values.space);
23
+ let served;
24
+ let ending;
25
+ let finish;
26
+ const done = new Promise((resolve) => { finish = resolve; });
27
+ const end = () => ending ??= (async () => {
28
+ try {
29
+ await host.closeAll();
30
+ }
31
+ catch {
32
+ process.stderr.write("[cotal mcp] identity cleanup is unfinished; recovery records were retained\n");
33
+ process.exitCode = 1;
34
+ }
35
+ finally {
36
+ await served?.close();
37
+ finish();
38
+ }
39
+ })();
40
+ const onEnd = () => { void end(); };
41
+ const releaseOutput = ownStdoutErrors(onEnd);
42
+ process.stdin.once("end", onEnd);
43
+ process.stdin.once("close", onEnd);
44
+ process.on("SIGINT", onEnd);
45
+ process.on("SIGTERM", onEnd);
46
+ try {
47
+ served = await serveGatewayStdio(host, { source: "mcp", selection: true });
48
+ if (ending)
49
+ await served.close();
50
+ if (process.stdin.readableEnded || process.stdin.destroyed)
51
+ onEnd();
52
+ await done;
53
+ }
54
+ finally {
55
+ await end();
56
+ process.stdin.off("end", onEnd);
57
+ process.stdin.off("close", onEnd);
58
+ process.off("SIGINT", onEnd);
59
+ process.off("SIGTERM", onEnd);
60
+ releaseOutput();
61
+ }
62
+ },
63
+ };
64
+ registry.register(command);