cotal-ai 0.164.5 → 0.164.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/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/install-darwin.js +2 -9
  5. package/dist/daemon/install-identity.js +50 -0
  6. package/dist/daemon/install-native-run.js +22 -0
  7. package/dist/daemon/install-receipt.js +24 -0
  8. package/dist/daemon/install-win32.js +3 -3
  9. package/dist/daemon/install-xml.js +10 -0
  10. package/dist/daemon/install.js +25 -89
  11. package/dist/daemon/login.js +1 -0
  12. package/dist/daemon/ownership-win32.js +40 -0
  13. package/dist/daemon/protocol.js +24 -2
  14. package/dist/daemon/server.js +1 -0
  15. package/dist/daemon/setup.js +10 -1
  16. package/dist/daemon/update-launchd-runner.js +46 -0
  17. package/dist/daemon/update-launchd.js +157 -0
  18. package/package.json +19 -19
  19. package/seeded-connectors/_shared/docs-bundle.bin +0 -0
  20. package/seeded-connectors/_shared/docs-index.bin +0 -0
  21. package/seeded-connectors/_shared/placements.json +2 -2
  22. package/seeded-connectors/claude/dist/index.js +1 -1
  23. package/seeded-connectors/claude/dist/mcp.cjs +2 -2
  24. package/seeded-connectors/claude/package.json +1 -1
  25. package/seeded-connectors/codex/dist/host.js +2 -2
  26. package/seeded-connectors/codex/dist/index.js +1 -1
  27. package/seeded-connectors/codex/dist/personal.js +2 -2
  28. package/seeded-connectors/codex/package.json +1 -1
  29. package/seeded-connectors/hermes/dist/index.js +1 -1
  30. package/seeded-connectors/hermes/dist/launch.js +2 -2
  31. package/seeded-connectors/hermes/package.json +1 -1
  32. package/seeded-connectors/hermes/plugin/cotal/_sidecar/standalone.cjs +2 -2
  33. package/seeded-connectors/jcode/dist/host.js +2 -2
  34. package/seeded-connectors/jcode/dist/index.js +2 -2
  35. package/seeded-connectors/jcode/dist/mcp.js +1 -1
  36. package/seeded-connectors/jcode/package.json +1 -1
  37. package/seeded-connectors/opencode/dist/index.js +1 -1
  38. package/seeded-connectors/opencode/dist/plugin/index.js +2 -2
  39. package/seeded-connectors/opencode/package.json +1 -1
  40. package/seeded-connectors/pi/dist/index.js +2 -2
  41. package/seeded-connectors/pi/dist/standalone.js +2 -2
  42. package/seeded-connectors/pi/package.json +1 -1
  43. package/seeded-connectors/web/package.json +1 -1
@@ -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: [
@@ -34,15 +34,8 @@ export function launchAgentLabel(daemonHome) {
34
34
  return "ai.cotal.daemon";
35
35
  return `ai.cotal.daemon.${createHash("sha256").update(daemonHome).digest("hex").slice(0, 16)}`;
36
36
  }
37
- /** XML character data: bounded, without controls or code points XML cannot carry, and escaped. */
38
- export function xmlText(value) {
39
- if (!value || value.length > 4096 || /[\u0000-\u001f\u007f]/u.test(value) || [...value].some((scalar) => {
40
- const cp = scalar.codePointAt(0);
41
- return cp >= 0xd800 && cp <= 0xdfff || cp === 0xfffe || cp === 0xffff;
42
- }))
43
- throw new CommandFailure("refused", "USAGE_INVALID", "the daemon job needs bounded XML text without control or invalid Unicode characters; no job bytes were prepared");
44
- return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
45
- }
37
+ import { xmlText } from "./install-xml.js";
38
+ export { xmlText } from "./install-xml.js";
46
39
  /** The plist this install writes. launchd execs `ProgramArguments` directly, with no shell. */
47
40
  export function renderLaunchAgent(input) {
48
41
  if ([input.argv[0] ?? "", input.workingDirectory, input.logPath].some((path) => !isAbsolute(path)))
@@ -0,0 +1,50 @@
1
+ import { readFileSync, realpathSync } from "node:fs";
2
+ import { CommandFailure } from "@cotal-ai/workspace/local-observation";
3
+ /** Whether the verified source carries the installer-owned native launch marker. */
4
+ export function recordedSourceMarked(receipt, mechanism) {
5
+ const source = readFileSync(receipt.unitPath).toString(mechanism === "scheduled-task" ? "utf16le" : "utf8");
6
+ return mechanism === "systemd-user" ? source.includes("Environment=COTAL_DAEMON_NATIVE_SERVICE=1")
7
+ : mechanism === "launchd-agent" ? source.includes("<key>COTAL_DAEMON_NATIVE_SERVICE</key><string>1</string>")
8
+ : source.includes("daemon-native.js") || (source.includes("cotal-desktop.exe</Command>") && source.includes("<Arguments>--daemon"));
9
+ }
10
+ /** Compare the verified source's executable and entry with the caller's immutable launch coordinates. */
11
+ export function recordedSourceIdentity(receipt, mechanism, expected) {
12
+ const bytes = readFileSync(receipt.unitPath);
13
+ const decode = (value) => value.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&quot;", '"').replaceAll("&apos;", "'").replaceAll("&amp;", "&");
14
+ let argv;
15
+ if (mechanism === "systemd-user") {
16
+ const line = /^ExecStart=(.*)$/m.exec(bytes.toString("utf8"))?.[1];
17
+ if (!line)
18
+ throw new CommandFailure("refused", "CONFLICT", "the recorded daemon unit has no readable executable and entry");
19
+ argv = [...line.matchAll(/"((?:\\.|[^"\\])*)"|([^\s"]+)/g)].map(match => (match[1] ?? match[2]).replace(/\\([\\"])/g, "$1").replaceAll("%%", "%").replaceAll("$$", "$"));
20
+ }
21
+ else if (mechanism === "launchd-agent") {
22
+ const array = /<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(bytes.toString("utf8"))?.[1] ?? "";
23
+ argv = [...array.matchAll(/<string>([^<]*)<\/string>/g)].map(match => decode(match[1]));
24
+ }
25
+ else {
26
+ const text = bytes.subarray(2).toString("utf16le");
27
+ const executable = decode(/<Command>([^<]*)<\/Command>/.exec(text)?.[1] ?? "");
28
+ const args = decode(/<Arguments>([^<]*)<\/Arguments>/.exec(text)?.[1] ?? "");
29
+ argv = [executable, ...[...args.matchAll(/"([^"]*)"|(\S+)/g)].map(match => match[1] ?? match[2])];
30
+ }
31
+ const coordinate = (args) => {
32
+ const daemon = args.indexOf("daemon");
33
+ const entry = daemon >= 2 ? args[daemon - 1] : args[0];
34
+ return { executable: args[0], entry };
35
+ };
36
+ const installed = coordinate(argv), current = coordinate(typeof expected === "function" ? expected() : expected);
37
+ if (mechanism === "launchd-agent")
38
+ installed.entry = argv[argv.indexOf("daemon") - 2].replace(/daemon-cwd\.js$/, "cotal.js");
39
+ if (mechanism === "scheduled-task")
40
+ installed.entry = installed.entry.replace(/daemon-native\.js$/, "cotal.js");
41
+ if (!installed.executable || !installed.entry)
42
+ throw new CommandFailure("refused", "CONFLICT", "the recorded daemon installation could not be identified");
43
+ const canonical = (path) => { try {
44
+ return realpathSync(path);
45
+ }
46
+ catch {
47
+ return path;
48
+ } };
49
+ return { same: canonical(installed.executable) === canonical(current.executable) && canonical(installed.entry) === canonical(current.entry), installed: `${installed.executable} ${installed.entry}`, current: `${current.executable} ${current.entry}` };
50
+ }
@@ -0,0 +1,22 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { basename } from "node:path";
3
+ import { CommandFailure } from "@cotal-ai/workspace/local-observation";
4
+ /** Runs one native tool by absolute path with the existing bounds, never through a shell. */
5
+ export function nativeRun(file, args, env) {
6
+ const started = Date.now();
7
+ const result = spawnSync(file, args, { encoding: "utf8", timeout: 30_000, maxBuffer: 256 * 1024, stdio: ["ignore", "pipe", "pipe"], windowsHide: true, ...(env ? { env } : {}) });
8
+ if (result.error || result.signal) {
9
+ const elapsedMs = Date.now() - started;
10
+ const code = result.error?.code;
11
+ const reason = code === "ETIMEDOUT" ? "timed out after 30 s"
12
+ : code === "ENOBUFS" ? "exceeded its 256 KiB output limit"
13
+ : code ? `could not start or complete (${code})`
14
+ : `exited by signal ${result.signal}`;
15
+ throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", `${basename(file)} ${reason} (elapsed ${elapsedMs} ms); no further native step was taken`, {
16
+ native: { code: code ?? result.signal ?? "NATIVE_TOOL_FAILED", detail: { elapsedMs, timeoutMs: 30_000, signal: result.signal } },
17
+ });
18
+ }
19
+ const stdout = typeof result.stdout === "string" ? result.stdout : "";
20
+ const stderr = typeof result.stderr === "string" ? result.stderr : "";
21
+ return { status: result.status, stdout, detail: (stderr.trim() || stdout.trim()).replace(/[\u0000-\u001f\u007f]+/gu, " ").slice(0, 300) };
22
+ }
@@ -0,0 +1,24 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ /** Where the receipt lives: beside the lifetime lock, in this daemon's own state directory. */
4
+ export function unitReceiptFile(paths) {
5
+ return join(paths.state, "service-unit.json");
6
+ }
7
+ /** Read the existing installer receipt shape without loading installation commands. */
8
+ export function readReceipt(paths) {
9
+ let o;
10
+ try {
11
+ o = JSON.parse(readFileSync(unitReceiptFile(paths), "utf8"));
12
+ }
13
+ catch {
14
+ return undefined;
15
+ }
16
+ if (!o || typeof o !== "object")
17
+ return undefined;
18
+ const r = o;
19
+ if (r.v !== 1 || typeof r.unit !== "string" || typeof r.unitPath !== "string" || typeof r.unitSha256 !== "string" || typeof r.installedAt !== "string")
20
+ return undefined;
21
+ if (r.mechanism !== undefined && r.mechanism !== "systemd-user" && r.mechanism !== "launchd-agent" && r.mechanism !== "scheduled-task")
22
+ return undefined;
23
+ return { v: 1, ...(r.mechanism !== undefined ? { mechanism: r.mechanism } : {}), unit: r.unit, unitPath: r.unitPath, unitSha256: r.unitSha256, installedAt: r.installedAt, ...(typeof r.daemonHome === "string" ? { daemonHome: r.daemonHome } : {}) };
24
+ }
@@ -26,9 +26,9 @@ import { createHash } from "node:crypto";
26
26
  import { lstatSync, rmSync } from "node:fs";
27
27
  import { homedir, userInfo } from "node:os";
28
28
  import { basename, join, win32 } from "node:path";
29
- import { writeSecretFileCreateOnly } from "@cotal-ai/core";
30
- import { CommandFailure, readLocalRecordSource } from "@cotal-ai/workspace";
31
- import { xmlText } from "./install-darwin.js";
29
+ import { writeSecretFileCreateOnly } from "@cotal-ai/core/secret-fs";
30
+ import { CommandFailure, readLocalRecordSource } from "@cotal-ai/workspace/local-observation";
31
+ import { xmlText } from "./install-xml.js";
32
32
  /** A System32 tool, resolved from the Windows directory and never from `PATH`. */
33
33
  function system32(...segments) {
34
34
  return join(process.env.SystemRoot || process.env.windir || "C:\\Windows", "System32", ...segments);
@@ -0,0 +1,10 @@
1
+ import { CommandFailure } from "@cotal-ai/workspace/local-observation";
2
+ /** XML character data: bounded, without controls or code points XML cannot carry, and escaped. */
3
+ export function xmlText(value) {
4
+ if (!value || value.length > 4096 || /[\u0000-\u001f\u007f]/u.test(value) || [...value].some((scalar) => {
5
+ const cp = scalar.codePointAt(0);
6
+ return cp >= 0xd800 && cp <= 0xdfff || cp === 0xfffe || cp === 0xffff;
7
+ }))
8
+ throw new CommandFailure("refused", "USAGE_INVALID", "the daemon job needs bounded XML text without control or invalid Unicode characters; no job bytes were prepared");
9
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
10
+ }
@@ -31,8 +31,11 @@
31
31
  */
32
32
  import { spawnSync } from "node:child_process";
33
33
  import { createHash } from "node:crypto";
34
- import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, rmSync } from "node:fs";
35
- import { basename, delimiter, dirname, isAbsolute, join, posix } from "node:path";
34
+ import { existsSync, lstatSync, mkdirSync, readFileSync, rmSync } from "node:fs";
35
+ import { delimiter, dirname, isAbsolute, join, posix } from "node:path";
36
+ import { recordedSourceIdentity, recordedSourceMarked } from "./install-identity.js";
37
+ import { nativeRun } from "./install-native-run.js";
38
+ import { checkWindowsRecordedUnit } from "./ownership-win32.js";
36
39
  import { Worker } from "node:worker_threads";
37
40
  import { setTimeout as delay } from "node:timers/promises";
38
41
  import { randomUUID } from "node:crypto";
@@ -49,10 +52,8 @@ import { scheduledTaskName, scheduledTaskService } from "./install-win32.js";
49
52
  import { daemonCommandCopy } from "./guidance.js";
50
53
  import { recoverPausedTask } from "./restart-recovery.js";
51
54
  import { removeAllServiceRecords } from "./service-records.js";
52
- /** Where the receipt lives: beside the lifetime lock, in this daemon's own state directory. */
53
- export function unitReceiptFile(paths) {
54
- return join(paths.state, "service-unit.json");
55
- }
55
+ import { readReceipt, unitReceiptFile } from "./install-receipt.js";
56
+ export { unitReceiptFile } from "./install-receipt.js";
56
57
  /** `cotal-daemon.service`, or `cotal-daemon-<16 hex>.service` for an explicit daemon home, derived
57
58
  * the same way its socket directory is so the two always agree. */
58
59
  export function daemonUnitName(daemonHome) {
@@ -60,23 +61,6 @@ export function daemonUnitName(daemonHome) {
60
61
  return "cotal-daemon.service";
61
62
  return `cotal-daemon-${createHash("sha256").update(daemonHome).digest("hex").slice(0, 16)}.service`;
62
63
  }
63
- function readReceipt(paths) {
64
- let o;
65
- try {
66
- o = JSON.parse(readFileSync(unitReceiptFile(paths), "utf8"));
67
- }
68
- catch {
69
- return undefined;
70
- }
71
- if (!o || typeof o !== "object")
72
- return undefined;
73
- const r = o;
74
- if (r.v !== 1 || typeof r.unit !== "string" || typeof r.unitPath !== "string" || typeof r.unitSha256 !== "string" || typeof r.installedAt !== "string")
75
- return undefined;
76
- if (r.mechanism !== undefined && r.mechanism !== "systemd-user" && r.mechanism !== "launchd-agent" && r.mechanism !== "scheduled-task")
77
- return undefined;
78
- return { v: 1, ...(r.mechanism !== undefined ? { mechanism: r.mechanism } : {}), unit: r.unit, unitPath: r.unitPath, unitSha256: r.unitSha256, installedAt: r.installedAt, ...(typeof r.daemonHome === "string" ? { daemonHome: r.daemonHome } : {}) };
79
- }
80
64
  function writeReceipt(paths, receipt) {
81
65
  writeSecretFile(unitReceiptFile(paths), `${JSON.stringify(receipt)}\n`);
82
66
  }
@@ -166,24 +150,6 @@ export function assertScheduledEntry(entry) {
166
150
  if (!file)
167
151
  throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", `the scheduled task entry is missing or is not a file: ${entry}; no task was prepared`, { remedy: "repair or reinstall this Cotal installation before running \`cotal daemon install\` again" });
168
152
  }
169
- function nativeRun(file, args, env) {
170
- const started = Date.now();
171
- const result = spawnSync(file, args, { encoding: "utf8", timeout: 30_000, maxBuffer: 256 * 1024, stdio: ["ignore", "pipe", "pipe"], windowsHide: true, ...(env ? { env } : {}) });
172
- if (result.error || result.signal) {
173
- const elapsedMs = Date.now() - started;
174
- const code = result.error?.code;
175
- const reason = code === "ETIMEDOUT" ? "timed out after 30 s"
176
- : code === "ENOBUFS" ? "exceeded its 256 KiB output limit"
177
- : code ? `could not start or complete (${code})`
178
- : `exited by signal ${result.signal}`;
179
- throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", `${basename(file)} ${reason} (elapsed ${elapsedMs} ms); no further native step was taken`, {
180
- native: { code: code ?? result.signal ?? "NATIVE_TOOL_FAILED", detail: { elapsedMs, timeoutMs: 30_000, signal: result.signal } },
181
- });
182
- }
183
- const stdout = typeof result.stdout === "string" ? result.stdout : "";
184
- const stderr = typeof result.stderr === "string" ? result.stderr : "";
185
- return { status: result.status, stdout, detail: (stderr.trim() || stdout.trim()).replace(/[\u0000-\u001f\u007f]+/gu, " ").slice(0, 300) };
186
- }
187
153
  /** This OS's per-user supervisor, or `undefined` on Linux, whose systemd route is below. */
188
154
  function nativeService() {
189
155
  if (process.platform === "linux")
@@ -303,14 +269,16 @@ function recordedUnit(paths, daemonHome) {
303
269
  const mechanism = receipt.mechanism ?? "systemd-user";
304
270
  if (mechanism !== (service ? service.mechanism : "systemd-user"))
305
271
  throw new CommandFailure("refused", "CONFLICT", `the recorded unit ${receipt.unit} is a ${mechanism} unit, which this OS does not run; nothing was removed`);
272
+ if (process.platform === "win32") {
273
+ checkWindowsRecordedUnit(paths, receipt, service);
274
+ return { receipt, plan: { mechanism, unit: receipt.unit, unitPath: receipt.unitPath, installedAt: receipt.installedAt }, service };
275
+ }
306
276
  try {
307
277
  lstatSync(receipt.unitPath);
308
278
  }
309
279
  catch {
310
280
  throw new CommandFailure("refused", "TARGET_NOT_FOUND", `the recorded unit file ${receipt.unitPath} is gone; nothing was removed. Delete ${unitReceiptFile(paths)} by hand to forget it`);
311
281
  }
312
- if (mechanism === "scheduled-task" && receipt.unitPath !== join(paths.state, "service-task.xml"))
313
- throw new CommandFailure("refused", "CONFLICT", "the scheduled-task receipt names a definition outside this daemon state; nothing was changed");
314
282
  if (service)
315
283
  service.check(receipt);
316
284
  else {
@@ -402,46 +370,7 @@ export function installedDaemonIdentity(paths, daemonHome) {
402
370
  return recordedDaemonIdentity(recordedUnit(paths, daemonHome));
403
371
  }
404
372
  function recordedDaemonIdentity({ receipt, plan }) {
405
- const bytes = readFileSync(receipt.unitPath);
406
- const decode = (value) => value.replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&quot;", '"').replaceAll("&apos;", "'").replaceAll("&amp;", "&");
407
- let argv;
408
- if (plan.mechanism === "systemd-user") {
409
- const line = /^ExecStart=(.*)$/m.exec(bytes.toString("utf8"))?.[1];
410
- if (!line)
411
- throw new CommandFailure("refused", "CONFLICT", "the recorded daemon unit has no readable executable and entry");
412
- argv = [...line.matchAll(/"((?:\\.|[^"\\])*)"|([^\s"]+)/g)].map(match => (match[1] ?? match[2]).replace(/\\([\\"])/g, "$1").replaceAll("%%", "%").replaceAll("$$", "$"));
413
- }
414
- else if (plan.mechanism === "launchd-agent") {
415
- const array = /<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/.exec(bytes.toString("utf8"))?.[1] ?? "";
416
- argv = [...array.matchAll(/<string>([^<]*)<\/string>/g)].map(match => decode(match[1]));
417
- }
418
- else {
419
- const text = bytes.subarray(2).toString("utf16le");
420
- const executable = decode(/<Command>([^<]*)<\/Command>/.exec(text)?.[1] ?? "");
421
- const args = decode(/<Arguments>([^<]*)<\/Arguments>/.exec(text)?.[1] ?? "");
422
- argv = [executable, ...[...args.matchAll(/"([^"]*)"|(\S+)/g)].map(match => match[1] ?? match[2])];
423
- }
424
- const expected = daemonServeArgv(receipt.daemonHome);
425
- const coordinate = (args) => {
426
- const daemon = args.indexOf("daemon");
427
- const entry = daemon >= 2 ? args[daemon - 1] : args[0];
428
- return { executable: args[0], entry };
429
- };
430
- const installed = coordinate(argv), current = coordinate(expected);
431
- // launchd pins the adjacent cwd bootstrap instead of cotal.js itself.
432
- if (plan.mechanism === "launchd-agent")
433
- installed.entry = argv[argv.indexOf("daemon") - 2].replace(/daemon-cwd\.js$/, "cotal.js");
434
- if (plan.mechanism === "scheduled-task")
435
- installed.entry = installed.entry.replace(/daemon-native\.js$/, "cotal.js");
436
- if (!installed.executable || !installed.entry)
437
- throw new CommandFailure("refused", "CONFLICT", "the recorded daemon installation could not be identified");
438
- const canonical = (path) => { try {
439
- return realpathSync(path);
440
- }
441
- catch {
442
- return path;
443
- } };
444
- return { same: canonical(installed.executable) === canonical(current.executable) && canonical(installed.entry) === canonical(current.entry), installed: `${installed.executable} ${installed.entry}`, current: `${current.executable} ${current.entry}` };
373
+ return recordedSourceIdentity(receipt, plan.mechanism, () => daemonServeArgv(receipt.daemonHome));
445
374
  }
446
375
  /** A native launch marker is trusted only with this installation's verified recorded source. */
447
376
  export function daemonStartedByOwnedService(paths, daemonHome) {
@@ -452,10 +381,7 @@ export function daemonStartedByOwnedService(paths, daemonHome) {
452
381
  if (!recordedDaemonIdentity(recorded).same)
453
382
  return { state: "not-owned", reason: "identity-differs" };
454
383
  const { receipt, plan } = recorded;
455
- const source = readFileSync(receipt.unitPath).toString(plan.mechanism === "scheduled-task" ? "utf16le" : "utf8");
456
- const marked = plan.mechanism === "systemd-user" ? source.includes("Environment=COTAL_DAEMON_NATIVE_SERVICE=1")
457
- : plan.mechanism === "launchd-agent" ? source.includes("<key>COTAL_DAEMON_NATIVE_SERVICE</key><string>1</string>")
458
- : source.includes("daemon-native.js") || (source.includes("cotal-desktop.exe</Command>") && source.includes("<Arguments>--daemon"));
384
+ const marked = recordedSourceMarked(receipt, plan.mechanism);
459
385
  return marked ? { state: "owned", reason: "verified" } : { state: "not-owned", reason: "source-marker-absent" };
460
386
  }
461
387
  catch {
@@ -484,12 +410,22 @@ export function observeDaemonOwnedService(paths, daemonHome, signal) {
484
410
  return new Promise(resolve => {
485
411
  // Reuse the installer's exact source, identity and native-job checks. The worker's
486
412
  // default argv names this helper, so explicitly preserve the daemon's launch vector.
413
+ let expected;
414
+ if (process.platform === "win32") {
415
+ try {
416
+ expected = daemonServeArgv(daemonHome);
417
+ }
418
+ catch {
419
+ resolve({ state: "unknown", reason: "observation-failed" });
420
+ return;
421
+ }
422
+ }
487
423
  const worker = new Worker(`
488
424
  const { parentPort, workerData } = require('node:worker_threads');
489
425
  process.argv = workerData.argv;
490
426
  process.execArgv = workerData.execArgv;
491
- import(workerData.module).then(m => parentPort.postMessage(m.daemonStartedByOwnedService(workerData.paths, workerData.home))).catch(() => parentPort.postMessage({ state: 'unknown', reason: 'worker-failed' }));
492
- `, { eval: true, workerData: { module: import.meta.url, paths, home: daemonHome, argv: process.argv, execArgv: process.execArgv }, stdout: true, stderr: true });
427
+ import(workerData.module).then(m => parentPort.postMessage(workerData.expected ? m.observeWindowsOwnedService(workerData.paths, workerData.expected) : m.daemonStartedByOwnedService(workerData.paths, workerData.home))).catch(() => parentPort.postMessage({ state: 'unknown', reason: 'worker-failed' }));
428
+ `, { eval: true, workerData: { module: expected ? new URL("./ownership-win32.js", import.meta.url).href : import.meta.url, expected, paths, home: daemonHome, argv: process.argv, execArgv: process.execArgv }, stdout: true, stderr: true });
493
429
  worker.stdout.resume();
494
430
  worker.stderr.resume();
495
431
  let settled = false;
@@ -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, {
@@ -0,0 +1,40 @@
1
+ import { lstatSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { CommandFailure } from "@cotal-ai/workspace/local-observation";
4
+ import { scheduledTaskService } from "./install-win32.js";
5
+ import { nativeRun } from "./install-native-run.js";
6
+ import { recordedSourceIdentity, recordedSourceMarked } from "./install-identity.js";
7
+ import { readReceipt, unitReceiptFile } from "./install-receipt.js";
8
+ /** The Windows receipt and registered job checks shared by installer and observer. */
9
+ export function checkWindowsRecordedUnit(paths, receipt, service) {
10
+ const mechanism = receipt.mechanism ?? "systemd-user";
11
+ if (mechanism !== "scheduled-task")
12
+ throw new CommandFailure("refused", "CONFLICT", `the recorded unit ${receipt.unit} is a ${mechanism} unit, which this OS does not run; nothing was removed`);
13
+ try {
14
+ lstatSync(receipt.unitPath);
15
+ }
16
+ catch {
17
+ throw new CommandFailure("refused", "TARGET_NOT_FOUND", `the recorded unit file ${receipt.unitPath} is gone; nothing was removed. Delete ${unitReceiptFile(paths)} by hand to forget it`);
18
+ }
19
+ if (receipt.unitPath !== join(paths.state, "service-task.xml"))
20
+ throw new CommandFailure("refused", "CONFLICT", "the scheduled-task receipt names a definition outside this daemon state; nothing was changed");
21
+ service.check(receipt);
22
+ }
23
+ /** Fresh Windows provenance through the installer's exact receipt, source, task and identity checks. */
24
+ export function observeWindowsOwnedService(paths, expected) {
25
+ if (process.env.COTAL_DAEMON_NATIVE_SERVICE !== "1")
26
+ return { state: "not-owned", reason: "marker-absent" };
27
+ try {
28
+ const receipt = readReceipt(paths);
29
+ if (!receipt)
30
+ throw new CommandFailure("refused", "TARGET_NOT_FOUND", "this daemon has no installed unit recorded by `cotal daemon install`; nothing was removed");
31
+ checkWindowsRecordedUnit(paths, receipt, scheduledTaskService(nativeRun));
32
+ if (!recordedSourceIdentity(receipt, "scheduled-task", expected).same)
33
+ return { state: "not-owned", reason: "identity-differs" };
34
+ const marked = recordedSourceMarked(receipt, "scheduled-task");
35
+ return marked ? { state: "owned", reason: "verified" } : { state: "not-owned", reason: "source-marker-absent" };
36
+ }
37
+ catch {
38
+ return { state: "unknown", reason: "observation-failed" };
39
+ }
40
+ }
@@ -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`;