cotal-ai 0.164.4 → 0.164.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/daemon/auto-update.js +34 -5
  2. package/dist/daemon/client.js +1 -1
  3. package/dist/daemon/command.js +24 -30
  4. package/dist/daemon/login.js +1 -0
  5. package/dist/daemon/protocol.js +24 -2
  6. package/dist/daemon/server.js +1 -0
  7. package/dist/daemon/setup.js +10 -1
  8. package/dist/daemon/update-launchd-runner.js +46 -0
  9. package/dist/daemon/update-launchd.js +157 -0
  10. package/package.json +19 -19
  11. package/seeded-connectors/_shared/docs-bundle.bin +0 -0
  12. package/seeded-connectors/_shared/docs-index.bin +0 -0
  13. package/seeded-connectors/_shared/placements.json +2 -2
  14. package/seeded-connectors/claude/dist/index.js +5 -5
  15. package/seeded-connectors/claude/dist/mcp.cjs +8 -8
  16. package/seeded-connectors/claude/package.json +1 -1
  17. package/seeded-connectors/codex/dist/host.js +8 -8
  18. package/seeded-connectors/codex/dist/index.js +5 -5
  19. package/seeded-connectors/codex/dist/personal.js +8 -8
  20. package/seeded-connectors/codex/package.json +1 -1
  21. package/seeded-connectors/hermes/dist/index.js +5 -5
  22. package/seeded-connectors/hermes/dist/launch.js +8 -8
  23. package/seeded-connectors/hermes/package.json +1 -1
  24. package/seeded-connectors/hermes/plugin/cotal/_sidecar/standalone.cjs +8 -8
  25. package/seeded-connectors/jcode/dist/host.js +8 -8
  26. package/seeded-connectors/jcode/dist/index.js +5 -5
  27. package/seeded-connectors/jcode/dist/mcp.js +5 -5
  28. package/seeded-connectors/jcode/package.json +1 -1
  29. package/seeded-connectors/opencode/dist/index.js +5 -5
  30. package/seeded-connectors/opencode/dist/plugin/index.js +8 -8
  31. package/seeded-connectors/opencode/package.json +1 -1
  32. package/seeded-connectors/pi/dist/index.js +7 -7
  33. package/seeded-connectors/pi/dist/standalone.js +8 -8
  34. package/seeded-connectors/pi/package.json +1 -1
  35. package/seeded-connectors/web/package.json +1 -1
@@ -4,6 +4,7 @@ import { fileURLToPath } from "node:url";
4
4
  import { join } from "node:path";
5
5
  import { openPrivateAppend, writeSecretFileAtomic } from "@cotal-ai/core";
6
6
  import { checkForUpdate, homeCotalDir, newerUpdate, readUpdateCheck, readUpdateRecovery, readUpdateSettings, UPDATE_DAY_MS, UPDATE_HOUR_MS } from "@cotal-ai/workspace";
7
+ import { cleanLaunchUpdate, startLaunchUpdate } from "./update-launchd.js";
7
8
  /** Schedule only the existing updater. Manager preparation holds its native empty-seat admission fence. */
8
9
  export function automaticUpdates(host) {
9
10
  const desktop = existsSync(fileURLToPath(new URL("../../desktop-runtime.json", import.meta.url)));
@@ -19,7 +20,7 @@ export function automaticUpdates(host) {
19
20
  if (error.code !== "ENOENT")
20
21
  state = { ...state, result: "automatic updates paused: unreadable attempt record", next: Number.MAX_SAFE_INTEGER };
21
22
  }
22
- let child, busy, closed = false;
23
+ let child, busy, closed = false, launchdPending = process.platform === "darwin" && (existsSync(join(homeCotalDir(), "update-launchd.json")) || existsSync(join(homeCotalDir(), "update-launchd-result.json")));
23
24
  const persist = () => writeSecretFileAtomic(file, `${JSON.stringify(state)}\n`);
24
25
  try {
25
26
  persist();
@@ -42,7 +43,7 @@ export function automaticUpdates(host) {
42
43
  try {
43
44
  const settings = readUpdateSettings();
44
45
  notify = settings.notify;
45
- automatic = process.platform === "linux" && !desktop && settings.auto && process.env.COTAL_NO_UPDATE_CHECK !== "1" && host.eligible();
46
+ automatic = ["linux", "darwin"].includes(process.platform) && !desktop && settings.auto && process.env.COTAL_NO_UPDATE_CHECK !== "1" && host.eligible();
46
47
  const recovery = readUpdateRecovery();
47
48
  if (recovery) {
48
49
  automatic = false;
@@ -53,8 +54,8 @@ export function automaticUpdates(host) {
53
54
  automatic = false;
54
55
  reason = `automatic updates paused: ${String(error)}`;
55
56
  }
56
- if (process.platform !== "linux")
57
- reason = `${reason}. Automatic installation is available on Linux in this release. Run \`cotal update --self\` here`;
57
+ if (!["linux", "darwin"].includes(process.platform))
58
+ reason = `${reason}. Automatic installation is unavailable on ${process.platform === "win32" ? "Windows" : process.platform} in this release. Run \`cotal update --self\` here`;
58
59
  if (desktop)
59
60
  reason = "update the desktop app with its signed platform installer";
60
61
  return { channel: desktop ? "desktop" : "npm", current: host.version, latest: cached?.latest, lastCheck: cached?.checkedAt ? new Date(cached.checkedAt).toISOString() : undefined, automatic, notify, failures: state.failures, lastResult: reason, ...(state.next < Number.MAX_SAFE_INTEGER ? { nextAttempt: new Date(state.next).toISOString() } : {}) };
@@ -62,6 +63,22 @@ export function automaticUpdates(host) {
62
63
  const tick = async () => {
63
64
  if (closed)
64
65
  return;
66
+ if (process.platform === "darwin") {
67
+ try {
68
+ launchdPending = true;
69
+ if (cleanLaunchUpdate() === "pending")
70
+ return;
71
+ launchdPending = false;
72
+ state = JSON.parse(readFileSync(file, "utf8"));
73
+ }
74
+ catch (error) {
75
+ launchdPending = true;
76
+ state = { ...state, result: `launchd automatic update custody unresolved: ${error instanceof Error ? error.message : String(error)}; retrying observation automatically`, next: Date.now() + UPDATE_HOUR_MS };
77
+ persist();
78
+ host.report(state.result);
79
+ return;
80
+ }
81
+ }
65
82
  const settings = readUpdateSettings();
66
83
  const cached = process.env.COTAL_NO_UPDATE_CHECK !== "1" && (settings.auto || settings.notify) ? await checkForUpdate() : readUpdateCheck();
67
84
  if (closed || Date.now() < state.next)
@@ -110,6 +127,18 @@ export function automaticUpdates(host) {
110
127
  return;
111
128
  state = { ...state, failures: state.failures, result: `updating to ${cached.latest}`, next: Date.now() + UPDATE_HOUR_MS };
112
129
  persist();
130
+ if (process.platform === "darwin") {
131
+ try {
132
+ launchdPending = true;
133
+ startLaunchUpdate(state.failures);
134
+ }
135
+ catch (error) {
136
+ state = { ...state, result: `launchd automatic update handoff refused: ${error instanceof Error ? error.message : String(error)}. Run \`cotal update --self\``, next: Date.now() + UPDATE_HOUR_MS };
137
+ persist();
138
+ host.report(state.result);
139
+ }
140
+ return;
141
+ }
113
142
  await new Promise(resolve => {
114
143
  const logPath = join(homeCotalDir(), "update-attempt.log");
115
144
  const outputFd = openPrivateAppend(logPath);
@@ -142,7 +171,7 @@ export function automaticUpdates(host) {
142
171
  busy = tick().catch(error => { host.report(`automatic update: ${String(error)}`); }).finally(() => { busy = undefined; });
143
172
  }, 30_000);
144
173
  timer.unref();
145
- return { status, async check() { await checkForUpdate(); return status(); }, updating: () => child !== undefined, async close() {
174
+ return { status, async check() { await checkForUpdate(); return status(); }, updating: () => child !== undefined || launchdPending, async close() {
146
175
  closed = true;
147
176
  clearInterval(timer);
148
177
  if (child) {
@@ -308,7 +308,7 @@ export async function loginViaDaemon(opts) {
308
308
  if (opts.signal?.aborted)
309
309
  return finish(abandoned);
310
310
  opts.signal?.addEventListener("abort", onAbort, { once: true });
311
- sock.write(encode({ v: DAEMON_PROTOCOL_VERSION, id, op: "login-start", idp: opts.idp, ...(opts.clientId !== undefined ? { clientId: opts.clientId } : {}) }));
311
+ sock.write(encode({ v: DAEMON_PROTOCOL_VERSION, id, op: "login-start", idp: opts.idp, ...(opts.discoveryPins !== undefined ? { discoveryPins: opts.discoveryPins } : {}), ...(opts.clientId !== undefined ? { clientId: opts.clientId } : {}) }));
312
312
  });
313
313
  }
314
314
  finally {
@@ -26,8 +26,8 @@ import { dirname, isAbsolute, join } from "node:path";
26
26
  import { fileURLToPath } from "node:url";
27
27
  import { registry } from "@cotal-ai/core";
28
28
  import { CommandFailure, codeSpan, homeCotalDir, keptCatalogCredentials, readUpdateRecovery, jsonFlag, plainFlag, presentationOf, recordOperationContext, renderReport, writeResult } from "@cotal-ai/workspace";
29
- import { openLoginBrowser, cloudAuthUrl } from "@cotal-ai/workspace";
30
- import { chooseAccount, IdpConfigurationError, normalizeIdpUrl } from "@cotal-ai/auth";
29
+ import { openLoginBrowser, isDiscoveryName, resolveDiscoveryLogin } from "@cotal-ai/workspace";
30
+ import { chooseAccountChoice, IdpConfigurationError, normalizeIdpUrl } from "@cotal-ai/auth";
31
31
  import { EndpointRefusal, defaultPeerUid, defaultPeerPid, checkDir, daemonPaths, daemonPathsFor } from "./endpoint.js";
32
32
  import { serveDaemon } from "./server.js";
33
33
  import { loginFromCli } from "./cli-login.js";
@@ -46,7 +46,7 @@ export const daemonFlags = [
46
46
  plainFlag,
47
47
  { name: "cloud", type: "boolean", description: "sign in to Cotal Cloud" },
48
48
  { name: "no-browser", type: "boolean", description: "print approval instructions without opening a browser" },
49
- { name: "idp", type: "string", value: "<auth base URL>", description: "the provider's auth base URL, e.g. <origin>/api/auth" },
49
+ { name: "idp", type: "string", value: "<auth URL or name>", description: "the provider's auth base URL or issuer-authorized discovery hostname" },
50
50
  { name: "client-id", type: "string", value: "<id>", description: "the OAuth device-flow client id" },
51
51
  { name: "daemon-home", type: "string", value: "<abs dir>", completion: "files", description: "run or reach the daemon whose state lives in this directory (absolute, yours, mode 0700, not the Cotal home): its own sign-in, identity and registration, its own socket and lifetime lock. Without it, run or reach the default daemon, whose state lives in the Cotal home." },
52
52
  { name: "refresh", type: "boolean", description: "spaces: refresh catalogs through the daemon-held sign-in" },
@@ -173,26 +173,27 @@ async function status(args) {
173
173
  const result = space ? { ...reply.result, agents: reply.result.agents?.filter(row => row.space === space), managers: [await managerViaDaemon({ paths, peerUid, peerPid }, { op: "manager-status", space })] } : reply.result;
174
174
  writeResult(presentation, { command: "daemon status", target: space ? { space } : null, result }, statusView);
175
175
  }
176
- /** Sign in through the running daemon. The daemon talks to the IdP and keeps the session; this
177
- * process only shows the approval prompt and the result, and never sees a token. Ctrl-C or SIGTERM
178
- * asks the daemon to cancel the attempt and waits for its answer. */
176
+ /** Select the provider before approval or native setup effects. */
177
+ async function daemonAccountChoice(args) {
178
+ if (args.values.cloud && args.values.idp !== undefined)
179
+ throw new CommandFailure("refused", "USAGE_INVALID", "--cloud and --idp cannot be combined");
180
+ const idp = args.values.idp;
181
+ if (typeof idp === "string" && isDiscoveryName(idp)) {
182
+ const discoveryPins = await resolveDiscoveryLogin(idp);
183
+ return { url: discoveryPins.url, discoveryPins };
184
+ }
185
+ return chooseAccountChoice({ ...args, positionals: [] }, "login");
186
+ }
187
+ /** Sign in through the daemon, which retains the session. Cancellation waits for its answer. */
179
188
  async function login(args) {
180
189
  const presentation = presentationOf(args.values);
181
190
  const values = args.values;
182
- if (values.idp !== undefined) {
183
- try {
184
- normalizeIdpUrl(cloudAuthUrl(values.idp));
185
- }
186
- catch {
187
- throw new CommandFailure("refused", "USAGE_INVALID", "use an HTTPS provider auth URL, or an HTTP loopback IP URL, without embedded credentials, a query or a fragment");
188
- }
189
- }
190
- const chosen = await chooseAccount(args, "login");
191
+ const chosen = await daemonAccountChoice(args);
191
192
  if (chosen === undefined)
192
193
  return;
193
194
  let idp;
194
195
  try {
195
- idp = normalizeIdpUrl(chosen);
196
+ idp = normalizeIdpUrl(chosen.url);
196
197
  }
197
198
  catch {
198
199
  throw new CommandFailure("refused", "USAGE_INVALID", "use an HTTPS provider auth URL, or an HTTP loopback IP URL, without embedded credentials, a query or a fragment");
@@ -204,7 +205,7 @@ async function login(args) {
204
205
  let reply;
205
206
  try {
206
207
  reply = await loginFromCli({
207
- paths, peerUid, peerPid, idp,
208
+ paths, peerUid, peerPid, idp, discoveryPins: chosen.discoveryPins,
208
209
  ...(values["client-id"] !== undefined ? { clientId: values["client-id"] } : {}),
209
210
  onPrompt: (p) => {
210
211
  process.stderr.write(`${renderReport({ sections: [{ title: "Approve sign-in", blocks: [
@@ -426,17 +427,8 @@ async function setupUnderClosure(args) {
426
427
  throw new CommandFailure("refused", "USAGE_INVALID", "space must be 1-64 characters of [A-Za-z0-9_-]", { native: { code: "BAD_FIELD" } });
427
428
  if (args.values.cloud && values.idp !== undefined)
428
429
  throw new CommandFailure("refused", "USAGE_INVALID", "--cloud and --idp cannot be combined");
429
- let idp;
430
- if (args.values.cloud === true)
431
- idp = await chooseAccount(args, "login");
432
- if (values.idp !== undefined) {
433
- try {
434
- idp = normalizeIdpUrl(cloudAuthUrl(values.idp));
435
- }
436
- catch {
437
- throw new CommandFailure("refused", "USAGE_INVALID", "use an HTTPS provider auth URL, or an HTTP loopback IP URL, without embedded credentials, a query or a fragment");
438
- }
439
- }
430
+ let choice = values.idp !== undefined || args.values.cloud === true ? await daemonAccountChoice(args) : undefined;
431
+ let idp = choice?.url;
440
432
  if (values["client-id"] !== undefined && !values["client-id"].trim())
441
433
  throw new CommandFailure("refused", "USAGE_INVALID", "--client-id cannot be empty");
442
434
  const waitSeconds = values.wait === undefined ? 900 : Number(values.wait);
@@ -455,7 +447,8 @@ async function setupUnderClosure(args) {
455
447
  installed = false;
456
448
  }
457
449
  if (!installed) {
458
- idp = await chooseAccount(args, "login");
450
+ choice = await daemonAccountChoice(args);
451
+ idp = choice?.url;
459
452
  if (idp === undefined)
460
453
  return;
461
454
  newSignIn = true;
@@ -488,7 +481,7 @@ async function setupUnderClosure(args) {
488
481
  throw new CommandFailure("refused", "USAGE_INVALID", `The daemon is signed in to several providers (${providers.join(", ")}); pass --idp <url> to choose one`);
489
482
  idp = providers[0];
490
483
  }
491
- const r = await runAccountSetup({ paths, daemonHome: home, peerUid, peerPid, report, version: binVersion(), idp: idp, existingSignInOnly: !newSignIn,
484
+ const r = await runAccountSetup({ paths, daemonHome: home, peerUid, peerPid, report, version: binVersion(), idp: idp, discoveryPins: choice?.discoveryPins, existingSignInOnly: !newSignIn,
492
485
  ...(values["client-id"] !== undefined ? { clientId: values["client-id"] } : {}),
493
486
  onPrompt: p => { process.stderr.write(`Approve this machine\nOpen: ${p.verificationUriComplete}\nApproval code: ${p.userCode}\n`); openLoginBrowser(p.verificationUriComplete, args.values); }, });
494
487
  writeResult(presentation, { command: "daemon setup", target: { idp: idp }, result: r }, () => ({ sections: [
@@ -502,6 +495,7 @@ async function setupUnderClosure(args) {
502
495
  r = await runSetup({
503
496
  paths, daemonHome: home, space, peerUid, peerPid, waitSeconds, report, version: binVersion(), noManager: values["no-manager"] === true,
504
497
  ...(idp !== undefined ? { idp } : {}),
498
+ discoveryPins: choice?.discoveryPins,
505
499
  ...(values["client-id"] !== undefined ? { clientId: values["client-id"] } : {}),
506
500
  onPrompt: (p) => {
507
501
  process.stderr.write(`${renderReport({ sections: [{ title: "Approve this machine", blocks: [
@@ -46,6 +46,7 @@ export function createLoginCoordinator(opts) {
46
46
  const r = await establish({
47
47
  dir: opts.sessionDir,
48
48
  idpUrl: req.idp,
49
+ expectedPins: req.discoveryPins && { idpUrl: req.discoveryPins.url, issuer: req.discoveryPins.issuer, audience: req.discoveryPins.audience },
49
50
  clientId: req.clientId ?? DEFAULT_CLIENT_ID,
50
51
  signal: abort.signal,
51
52
  onPrompt: (p) => req.onPrompt(id, {
@@ -30,7 +30,7 @@ const OP_FIELDS = {
30
30
  "managers-prepare-restart": { required: [], optional: [] },
31
31
  "managers-abort-restart": { required: [], optional: [] },
32
32
  spaces: { required: [], optional: ["refresh"] },
33
- "login-start": { required: ["idp"], optional: ["clientId"] },
33
+ "login-start": { required: ["idp"], optional: ["clientId", "discoveryPins"] },
34
34
  logout: { required: ["idp"], optional: [] },
35
35
  "login-cancel": { required: ["attempt"], optional: [] },
36
36
  "connect-check": { required: ["space"], optional: [] },
@@ -134,7 +134,29 @@ export function parseRequest(line) {
134
134
  return { ok: true, request: { v, id, op, idp } };
135
135
  if (obj.clientId !== undefined && (typeof obj.clientId !== "string" || !obj.clientId.trim() || obj.clientId.length > MAX_CLIENT_ID))
136
136
  return bad(id, `clientId must be a non-empty string of at most ${MAX_CLIENT_ID} characters`);
137
- return { ok: true, request: { v, id, op, idp, ...(obj.clientId !== undefined ? { clientId: obj.clientId } : {}) } };
137
+ let discoveryPins;
138
+ if (obj.discoveryPins !== undefined) {
139
+ const pins = obj.discoveryPins;
140
+ if (!pins || typeof pins !== "object" || Array.isArray(pins))
141
+ return bad(id, "discoveryPins must contain url, issuer and audience");
142
+ const p = pins;
143
+ if (Object.keys(p).length !== 3 || !["url", "issuer", "audience"].every(key => typeof p[key] === "string" && p[key].trim().length > 0))
144
+ return bad(id, "discoveryPins must contain only non-empty url, issuer and audience strings");
145
+ try {
146
+ for (const value of [p.url, p.issuer]) {
147
+ const u = new URL(value);
148
+ if (value !== value.trim() || u.protocol !== "https:" || u.username || u.password || value.includes("?") || value.includes("#"))
149
+ throw new Error("invalid pins");
150
+ }
151
+ if (normalizeIdpUrl(p.url) !== idp)
152
+ throw new Error("provider mismatch");
153
+ }
154
+ catch {
155
+ return bad(id, "discoveryPins must use HTTPS URLs and match idp");
156
+ }
157
+ discoveryPins = { url: p.url, issuer: p.issuer, audience: p.audience };
158
+ }
159
+ return { ok: true, request: { v, id, op, idp, ...(discoveryPins ? { discoveryPins } : {}), ...(obj.clientId !== undefined ? { clientId: obj.clientId } : {}) } };
138
160
  }
139
161
  export function encode(msg) {
140
162
  return `${JSON.stringify(msg)}\n`;
@@ -374,6 +374,7 @@ async function serveLocked(opts, uid, lock) {
374
374
  }
375
375
  const started = login.start({
376
376
  idp: req.idp,
377
+ discoveryPins: req.discoveryPins,
377
378
  ...(req.clientId !== undefined ? { clientId: req.clientId } : {}),
378
379
  onPrompt: (attempt, prompt) => void write({ v: DAEMON_PROTOCOL_VERSION, id: req.id, ok: true, event: "login-prompt", attempt, prompt }),
379
380
  onResult: async (attempt, result) => {
@@ -203,7 +203,7 @@ export async function runAccountSetup(opts) {
203
203
  const discovery = await exchangeDesktopRequest(opts, { op: "spaces", refresh: true });
204
204
  const signedIn = discovery.ok && !("event" in discovery) && "signedInProviders" in discovery.result
205
205
  && discovery.result.signedInProviders?.includes(opts.idp);
206
- if (!signedIn) {
206
+ if (!signedIn || opts.discoveryPins) {
207
207
  if (opts.existingSignInOnly)
208
208
  throw new CommandFailure("refused", "AUTH_REQUIRED", "The daemon is not signed in; pass --idp <url> to connect an account");
209
209
  const signed = await loginFromCli(opts);
@@ -282,6 +282,7 @@ async function ensureSignedIn(opts, steps) {
282
282
  opts.report("sign-in: approve this machine on another device", { step: "sign-in", outcome: "running", detail: "approve this machine on another device" });
283
283
  const reply = await loginFromCli({
284
284
  paths: opts.paths, peerUid: opts.peerUid, peerPid: opts.peerPid, idp: opts.idp,
285
+ discoveryPins: opts.discoveryPins,
285
286
  ...(opts.clientId !== undefined ? { clientId: opts.clientId } : {}),
286
287
  onPrompt: opts.onPrompt,
287
288
  });
@@ -371,6 +372,14 @@ export async function runSetup(opts) {
371
372
  const steps = [];
372
373
  let discoveredSignIn = false;
373
374
  const unit = await ensureInstalled(opts, steps);
375
+ if (opts.discoveryPins) {
376
+ const listed = await exchangeDesktopRequest(opts, { op: "spaces" });
377
+ const provider = listed.ok && !("event" in listed) && "spaces" in listed.result
378
+ ? listed.result.spaces.find(entry => entry.space === opts.space)?.idp : undefined;
379
+ if (provider !== undefined && normalizeIdpUrl(provider) !== normalizeIdpUrl(opts.discoveryPins.url)) {
380
+ throw new CommandFailure("refused", "USAGE_INVALID", "--idp does not match the space's pinned sign-in provider; no sign-in was started and nothing was registered", { native: { code: "IDP_MISMATCH" } });
381
+ }
382
+ }
374
383
  if (!opts.noManager) {
375
384
  let discovered = await exchangeDesktopRequest(opts, { op: "spaces", refresh: true });
376
385
  const hasSpace = () => discovered.ok && !("event" in discovered) && "spaces" in discovered.result && discovered.result.spaces.some((entry) => entry.space === opts.space);
@@ -0,0 +1,46 @@
1
+ /** launchd owns this one-shot process until the existing updater has exited. */
2
+ import { spawn } from "node:child_process";
3
+ import { closeSync, ftruncateSync, readFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { openPrivateAppend, writeSecretFileAtomic } from "@cotal-ai/core";
7
+ import { homeCotalDir, readUpdateSettings, UPDATE_HOUR_MS } from "@cotal-ai/workspace";
8
+ import { admitLaunchUpdate, launchUpdateResultPath, readLaunchUpdateResult } from "./update-launchd.js";
9
+ admitLaunchUpdate(process.argv[2] ?? "");
10
+ const attemptPath = join(homeCotalDir(), "update-attempt.json");
11
+ try {
12
+ if (!readUpdateSettings().auto || process.env.COTAL_NO_UPDATE_CHECK === "1") {
13
+ const attempt = JSON.parse(readFileSync(attemptPath, "utf8"));
14
+ writeSecretFileAtomic(attemptPath, `${JSON.stringify({ ...attempt, result: "automatic updates disabled before launchd handoff", next: Date.now() + UPDATE_HOUR_MS })}\n`);
15
+ }
16
+ else {
17
+ const log = openPrivateAppend(join(homeCotalDir(), "update-attempt.log"));
18
+ let code;
19
+ try {
20
+ ftruncateSync(log, 0);
21
+ code = await new Promise((resolve, reject) => {
22
+ const child = spawn(process.execPath, [fileURLToPath(new URL("../cotal.js", import.meta.url)), "update", "--self"], {
23
+ env: { ...process.env, COTAL_AUTO_UPDATE: "1", COTAL_NO_UPDATE_CHECK: "1" }, stdio: ["ignore", log, log],
24
+ });
25
+ child.once("error", reject);
26
+ child.once("close", resolve);
27
+ });
28
+ }
29
+ finally {
30
+ closeSync(log);
31
+ }
32
+ if (code !== 0)
33
+ throw new Error(`updater exited with ${code ?? "a signal"}; inspect update-attempt.log`);
34
+ }
35
+ }
36
+ catch (error) {
37
+ const attempt = JSON.parse(readFileSync(attemptPath, "utf8"));
38
+ writeSecretFileAtomic(attemptPath, `${JSON.stringify({ ...attempt, result: `launchd automatic update refused: ${error instanceof Error ? error.message : String(error)}. Run \`cotal update --self\``, next: Date.now() + UPDATE_HOUR_MS })}\n`);
39
+ process.exitCode = 1;
40
+ }
41
+ finally {
42
+ const result = readLaunchUpdateResult();
43
+ if (!result || result.pid !== process.pid)
44
+ throw new Error("automatic update runner lost its result receipt");
45
+ writeSecretFileAtomic(launchUpdateResultPath(), `${JSON.stringify({ ...result, done: true })}\n`);
46
+ }
@@ -0,0 +1,157 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ import { execFileSync } from "node:child_process";
3
+ import { rmSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { writeSecretFileAtomic } from "@cotal-ai/core";
7
+ import { assertSystemdSource, createSystemdSource } from "@cotal-ai/cli";
8
+ import { darwinLaunchdJob } from "@cotal-ai/seat";
9
+ import { homeCotalDir, readLocalRecordSource, UPDATE_HOUR_MS } from "@cotal-ai/workspace";
10
+ import { daemonStartedByOwnedService } from "./install.js";
11
+ import { daemonPaths } from "./endpoint.js";
12
+ import { processBirth } from "./lifetime.js";
13
+ import { xmlText } from "./install-darwin.js";
14
+ const receiptPath = () => join(homeCotalDir(), "update-launchd.json");
15
+ export const launchUpdateResultPath = () => join(homeCotalDir(), "update-launchd-result.json");
16
+ const run = (args) => execFileSync("/bin/launchctl", args, { encoding: "utf8", timeout: 20_000, stdio: ["ignore", "pipe", "pipe"] });
17
+ const domain = () => {
18
+ const uid = process.getuid?.();
19
+ if (uid === undefined || uid === 0)
20
+ throw new Error("automatic launchd updates require a signed-in non-root user");
21
+ return `gui/${uid}`;
22
+ };
23
+ /** A separate non-restarting job, never a child in the daemon's native stop boundary. */
24
+ export function renderUpdateLaunchAgent(label, argv, env) {
25
+ const str = (value) => `<string>${xmlText(value)}</string>`;
26
+ const keys = ["PATH", "HOME", "COTAL_HOME", "XDG_CONFIG_HOME", "TMPDIR", "npm_config_prefix", "npm_config_registry", "DO_NOT_TRACK", "COTAL_TELEMETRY", "COTAL_SKIP_CONNECTOR_SEED"];
27
+ const environment = keys.filter(key => env[key] !== undefined).map(key => `<key>${key}</key>${str(env[key])}`).join("");
28
+ const text = ['<?xml version="1.0" encoding="UTF-8"?>', '<plist version="1.0"><dict>',
29
+ `<key>Label</key>${str(label)}`, `<key>ProgramArguments</key><array>${argv.map(str).join("")}</array>`,
30
+ `<key>EnvironmentVariables</key><dict>${environment}</dict>`,
31
+ "<key>RunAtLoad</key><true/>", "<key>KeepAlive</key><false/>", "<key>Umask</key><integer>63</integer>", "</dict></plist>", ""].join("\n");
32
+ if (Buffer.byteLength(text) > 64 * 1024)
33
+ throw new Error("automatic update LaunchAgent exceeds its bounded source size");
34
+ return text;
35
+ }
36
+ function receipt() {
37
+ const source = readLocalRecordSource(receiptPath(), 64 * 1024, true);
38
+ if (!source)
39
+ return undefined;
40
+ const value = JSON.parse(source.toString("utf8"));
41
+ if (!/^ai\.cotal\.update\.[a-f0-9]{32}$/.test(value.label) || value.source !== join(homeCotalDir(), `${value.label}.plist`) || !/^[a-f0-9]{64}$/.test(value.sha256) || !Array.isArray(value.argv) || value.argv.some(arg => typeof arg !== "string") || !Number.isInteger(value.failures) || value.failures < 0)
42
+ throw new Error("automatic update launchd receipt is invalid");
43
+ assertSystemdSource(value.source, value.sha256, true);
44
+ return value;
45
+ }
46
+ export function readLaunchUpdateResult() {
47
+ const source = readLocalRecordSource(launchUpdateResultPath(), 4096, true);
48
+ if (!source)
49
+ return undefined;
50
+ const value = JSON.parse(source.toString("utf8"));
51
+ if (!Number.isSafeInteger(value.pid) || value.pid <= 1 || typeof value.start !== "string" || !value.start || typeof value.done !== "boolean")
52
+ throw new Error("automatic update launchd result is invalid");
53
+ return value;
54
+ }
55
+ /** Only the documented legacy list columns are parsed, never the non-API print output. */
56
+ export function launchUpdatePid(list, label) {
57
+ const rows = list.trim().split(/\r?\n/);
58
+ if (!/^PID\s+Status\s+Label$/.test(rows.shift() ?? ""))
59
+ throw new Error("launchd job list has no documented column header");
60
+ const matches = rows.filter(row => row.trim().split(/\s+/)[2] === label);
61
+ if (!matches.length)
62
+ return undefined;
63
+ const match = /^(\d+|-)\s+(-?\d+)\s+(\S+)$/.exec(matches[0].trim());
64
+ if (matches.length > 1 || !match || match[3] !== label)
65
+ throw new Error("launchd updater PID observation is ambiguous");
66
+ if (match[1] === "-")
67
+ return 0;
68
+ const pid = Number(match[1]);
69
+ if (!Number.isSafeInteger(pid) || pid <= 1)
70
+ throw new Error("launchd updater PID is invalid");
71
+ return pid;
72
+ }
73
+ /** Pure recovery decision shared by native observation and state regression cells. */
74
+ export function launchUpdateDisposition(jobPid, runnerAlive, done) {
75
+ if (jobPid !== undefined && jobPid > 0 || runnerAlive)
76
+ return "pending";
77
+ return done ? "completed" : "failed";
78
+ }
79
+ export function launchUpdateFailureCount(current, beforeHandoff) {
80
+ if (![current, beforeHandoff].every(value => Number.isSafeInteger(value) && value >= 0))
81
+ throw new Error("automatic update failure budget is invalid");
82
+ return Math.max(current, beforeHandoff + 1);
83
+ }
84
+ /** Retire only the unchanged, stopped updater job. Unknown custody always throws and stays fenced. */
85
+ export function cleanLaunchUpdate() {
86
+ const recorded = receipt();
87
+ if (!recorded) {
88
+ if (readLaunchUpdateResult())
89
+ throw new Error("automatic update result has no custody receipt");
90
+ return "absent";
91
+ }
92
+ const result = readLaunchUpdateResult();
93
+ const observed = darwinLaunchdJob(recorded.label);
94
+ if (observed.state === "unavailable")
95
+ throw new Error(`cannot inspect updater job: ${observed.reason}`);
96
+ if (observed.state === "loaded" && (observed.job.label !== recorded.label || observed.job.program !== recorded.argv[0] || JSON.stringify(observed.job.programArguments) !== JSON.stringify(recorded.argv)))
97
+ throw new Error("loaded updater job differs from its recorded source");
98
+ const pid = launchUpdatePid(run(["list"]), recorded.label);
99
+ if ((observed.state === "absent") !== (pid === undefined))
100
+ throw new Error("launchd updater observations disagree");
101
+ const disposition = launchUpdateDisposition(pid, result !== undefined && processBirth(result.pid) === result.start, result?.done === true);
102
+ if (disposition === "pending")
103
+ return disposition;
104
+ if (observed.state === "loaded") {
105
+ assertSystemdSource(recorded.source, recorded.sha256, true);
106
+ run(["bootout", `${domain()}/${recorded.label}`]);
107
+ if (launchUpdatePid(run(["list"]), recorded.label) !== undefined || darwinLaunchdJob(recorded.label).state !== "absent")
108
+ throw new Error("launchd updater removal is not yet confirmed");
109
+ }
110
+ if (result && processBirth(result.pid) === result.start)
111
+ throw new Error("updater runner is still present after native removal");
112
+ if (disposition === "failed") {
113
+ const attemptPath = join(homeCotalDir(), "update-attempt.json");
114
+ const source = readLocalRecordSource(attemptPath, 64 * 1024, true);
115
+ if (!source)
116
+ throw new Error("automatic update attempt record is missing");
117
+ const attempt = JSON.parse(source.toString("utf8"));
118
+ if (!Number.isInteger(attempt.failures) || attempt.failures < 0)
119
+ throw new Error("automatic update failure budget is invalid");
120
+ // The receipt captures the prior count. Repeating after a partial cleanup cannot count twice.
121
+ writeSecretFileAtomic(attemptPath, `${JSON.stringify({ ...attempt, failures: launchUpdateFailureCount(attempt.failures, recorded.failures), result: "launchd updater exited without confirming completion; retrying automatically", next: Date.now() + UPDATE_HOUR_MS })}\n`);
122
+ }
123
+ assertSystemdSource(recorded.source, recorded.sha256, true);
124
+ rmSync(launchUpdateResultPath(), { force: true });
125
+ rmSync(receiptPath());
126
+ rmSync(recorded.source);
127
+ return disposition;
128
+ }
129
+ /** A nonzero or uncertain bootstrap is never retried as a detached child. */
130
+ export function startLaunchUpdate(failures) {
131
+ if (process.platform !== "darwin")
132
+ throw new Error("launchd update handoff requires macOS");
133
+ if (daemonStartedByOwnedService(daemonPaths()).state !== "owned")
134
+ throw new Error("automatic update does not own the recorded launchd daemon");
135
+ if (cleanLaunchUpdate() === "pending")
136
+ throw new Error("previous launchd updater still has native custody");
137
+ const label = `ai.cotal.update.${randomBytes(16).toString("hex")}`;
138
+ const argv = [process.execPath, fileURLToPath(new URL("./update-launchd-runner.js", import.meta.url)), label];
139
+ const source = join(homeCotalDir(), `${label}.plist`);
140
+ const text = renderUpdateLaunchAgent(label, argv, process.env);
141
+ const sha256 = createHash("sha256").update(text).digest("hex");
142
+ createSystemdSource(source, text, sha256, true);
143
+ writeSecretFileAtomic(receiptPath(), `${JSON.stringify({ label, source, sha256, argv, failures })}\n`);
144
+ run(["bootstrap", domain(), source]);
145
+ }
146
+ /** The runner accepts only the freshly recorded launchd entry, not arbitrary command arguments. */
147
+ export function admitLaunchUpdate(label) {
148
+ const recorded = receipt();
149
+ if (process.platform !== "darwin" || process.ppid !== 1 || !recorded || label !== recorded.label || JSON.stringify(process.argv) !== JSON.stringify(recorded.argv))
150
+ throw new Error("automatic update runner does not match its launchd receipt");
151
+ if (readLaunchUpdateResult())
152
+ throw new Error("automatic update runner already started; refusing a second execution");
153
+ const start = processBirth(process.pid);
154
+ if (!start)
155
+ throw new Error("automatic update runner birth is unavailable");
156
+ writeSecretFileAtomic(launchUpdateResultPath(), `${JSON.stringify({ pid: process.pid, start, done: false })}\n`);
157
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cotal-ai",
3
- "version": "0.164.4",
3
+ "version": "0.164.6",
4
4
  "description": "Cotal — lateral agent coordination over NATS. Run `npx cotal-ai` for the CLI.",
5
5
  "license": "Apache-2.0",
6
6
  "keywords": [
@@ -33,28 +33,28 @@
33
33
  "node": ">=22.10"
34
34
  },
35
35
  "dependencies": {
36
- "@cotal-ai/auth": "0.164.4",
37
- "@cotal-ai/cli": "0.164.4",
38
- "@cotal-ai/connector-core": "0.164.4",
39
- "@cotal-ai/core": "0.164.4",
40
- "@cotal-ai/delivery": "0.164.4",
41
- "@cotal-ai/manager": "0.164.4",
42
- "@cotal-ai/registry": "0.164.4",
43
- "@cotal-ai/runtime": "0.164.4",
44
- "@cotal-ai/seat": "0.164.4",
45
- "@cotal-ai/workspace": "0.164.4",
36
+ "@cotal-ai/auth": "0.164.6",
37
+ "@cotal-ai/cli": "0.164.6",
38
+ "@cotal-ai/connector-core": "0.164.6",
39
+ "@cotal-ai/core": "0.164.6",
40
+ "@cotal-ai/delivery": "0.164.6",
41
+ "@cotal-ai/manager": "0.164.6",
42
+ "@cotal-ai/registry": "0.164.6",
43
+ "@cotal-ai/runtime": "0.164.6",
44
+ "@cotal-ai/seat": "0.164.6",
45
+ "@cotal-ai/workspace": "0.164.6",
46
46
  "jose": "^6.2.3"
47
47
  },
48
48
  "devDependencies": {
49
- "@cotal-ai/connector-claude-code": "0.164.4",
50
- "@cotal-ai/connector-codex": "0.164.4",
51
- "@cotal-ai/connector-hermes": "0.164.4",
52
- "@cotal-ai/connector-jcode": "0.164.4",
53
- "@cotal-ai/connector-opencode": "0.164.4",
54
- "@cotal-ai/linear": "0.164.4",
55
- "@cotal-ai/pi": "0.164.4",
49
+ "@cotal-ai/connector-claude-code": "0.164.6",
50
+ "@cotal-ai/connector-codex": "0.164.6",
51
+ "@cotal-ai/connector-hermes": "0.164.6",
52
+ "@cotal-ai/connector-jcode": "0.164.6",
53
+ "@cotal-ai/connector-opencode": "0.164.6",
54
+ "@cotal-ai/linear": "0.164.6",
55
+ "@cotal-ai/pi": "0.164.6",
56
56
  "@cotal-ai/smoke-kit": "0.0.0",
57
- "@cotal-ai/web": "0.164.4",
57
+ "@cotal-ai/web": "0.164.6",
58
58
  "@nats-io/jetstream": "^3.4.0",
59
59
  "@nats-io/transport-node": "^3.4.0",
60
60
  "typescript": "^5.9.3"
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "v": 1,
3
3
  "files": {
4
- "docs-bundle.bin": "94c9b042a03542444ea19bf81563170850f37a72ee11316abd9fa8999ce4971c",
5
- "docs-index.bin": "f1597fe06be43f88a4ac74209ebc952ef8e467437d3771b30b1e3177c20a669c"
4
+ "docs-bundle.bin": "0976e4aafea8722ea0face42823fac8d64939170ea04b894c0fb9c3e4c26d4ba",
5
+ "docs-index.bin": "bd9e046b180dd000f0f2147aae7658d91c5327bcb74cf7a17c5d539d645ba8c1"
6
6
  },
7
7
  "placements": {
8
8
  "claude": [