cotal-ai 0.171.2 → 0.171.3

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 (40) hide show
  1. package/dist/cotal-program.js +33 -1
  2. package/dist/cotal.js +2 -1
  3. package/dist/daemon/command.js +14 -4
  4. package/dist/daemon/connect.js +2 -3
  5. package/dist/daemon/guidance.js +12 -1
  6. package/dist/daemon/server.js +30 -2
  7. package/dist/daemon/setup.js +4 -1
  8. package/dist/daemon/update-entry.js +9 -2
  9. package/dist/mcp-host.js +6 -2
  10. package/dist/run.js +0 -7
  11. package/package.json +20 -19
  12. package/seeded-connectors/_shared/docs-bundle.bin +0 -0
  13. package/seeded-connectors/_shared/docs-index.bin +0 -0
  14. package/seeded-connectors/_shared/placements.json +2 -2
  15. package/seeded-connectors/claude/dist/hook.cjs +2 -2
  16. package/seeded-connectors/claude/dist/index.js +1 -1
  17. package/seeded-connectors/claude/dist/mcp.cjs +14 -14
  18. package/seeded-connectors/claude/package.json +1 -1
  19. package/seeded-connectors/codex/dist/host.js +10 -10
  20. package/seeded-connectors/codex/dist/index.js +1 -1
  21. package/seeded-connectors/codex/dist/personal.js +9 -9
  22. package/seeded-connectors/codex/package.json +1 -1
  23. package/seeded-connectors/hermes/dist/index.js +1 -1
  24. package/seeded-connectors/hermes/dist/launch.js +6 -6
  25. package/seeded-connectors/hermes/package.json +1 -1
  26. package/seeded-connectors/hermes/plugin/cotal/_sidecar/standalone.cjs +10 -10
  27. package/seeded-connectors/jcode/dist/host.js +9 -9
  28. package/seeded-connectors/jcode/dist/index.js +1 -1
  29. package/seeded-connectors/jcode/dist/mcp.js +3 -3
  30. package/seeded-connectors/jcode/package.json +1 -1
  31. package/seeded-connectors/opencode/dist/index.js +1 -1
  32. package/seeded-connectors/opencode/dist/launch.d.ts.map +1 -1
  33. package/seeded-connectors/opencode/dist/launch.js +1 -1
  34. package/seeded-connectors/opencode/dist/plugin/index.js +11 -11
  35. package/seeded-connectors/opencode/dist/serve.js +1 -1
  36. package/seeded-connectors/opencode/package.json +1 -1
  37. package/seeded-connectors/pi/dist/index.js +3 -3
  38. package/seeded-connectors/pi/dist/standalone.js +9 -9
  39. package/seeded-connectors/pi/package.json +1 -1
  40. package/seeded-connectors/web/package.json +1 -1
@@ -1,7 +1,32 @@
1
1
  #!/usr/bin/env node
2
2
  /** The generation-local Node preflight and CLI entry. Reached through the built-ins bootstrap. */
3
+ import { dirname, isAbsolute } from "node:path";
3
4
  import { setFlagsFromString } from "node:v8";
4
5
  import { ensureSupportedNode } from "./cotal.js";
6
+ // The updater probes this form. Leave usage and invalid-home diagnostics to the dispatcher.
7
+ async function runVersionFlag() {
8
+ if (process.argv.length !== 3 || (process.argv[2] !== "--version" && process.argv[2] !== "-V"))
9
+ return false;
10
+ const { c, cotalHomeProblem, stderrLine } = await import("@cotal-ai/workspace");
11
+ const home = process.env.COTAL_HOME;
12
+ if ((home && !isAbsolute(home)) || cotalHomeProblem())
13
+ return false;
14
+ const { completeFileWrites, stdoutError } = await import("@cotal-ai/cli/dispatch");
15
+ const { cliVersion, printVersion, readExtensionVersions } = await import("@cotal-ai/cli/version");
16
+ (await import("./update-notice.js")).installUpdateNotice(process.argv.slice(2), cliVersion());
17
+ const inventory = readExtensionVersions();
18
+ if (inventory.unreadable !== undefined) {
19
+ stderrLine("✗ ", inventory.unreadable, c.red);
20
+ process.exitCode = 1;
21
+ }
22
+ else {
23
+ process.stdout.on("error", stdoutError);
24
+ completeFileWrites();
25
+ await (await import("./startup-interrupt.js")).releaseStartupInterrupt();
26
+ printVersion(inventory.versions);
27
+ }
28
+ return true;
29
+ }
5
30
  ensureSupportedNode();
6
31
  setFlagsFromString("--no-maglev");
7
32
  setFlagsFromString("--no-concurrent-sparkplug");
@@ -18,5 +43,12 @@ else if (!bearerDone) {
18
43
  const commandWord = process.argv.slice(2).find((word) => !word.startsWith("-"));
19
44
  if (!commandWord?.startsWith("__"))
20
45
  (await import("./startup-interrupt.js")).holdStartupInterrupt();
21
- await import("./run.js");
46
+ const { executionIdentity } = await import("@cotal-ai/workspace");
47
+ const identity = executionIdentity();
48
+ if (identity && identity.logicalEntry === identity.loadedEntry) {
49
+ const { retireSupersededExecutionDescriptor } = await import("./execution-transaction.js");
50
+ retireSupersededExecutionDescriptor(dirname(dirname(identity.logicalEntry)));
51
+ }
52
+ if (!(await runVersionFlag()))
53
+ await import("./run.js");
22
54
  }
package/dist/cotal.js CHANGED
@@ -172,7 +172,8 @@ export function executionInventory(root) {
172
172
  export function executionLaunchBinding(root, entry) {
173
173
  const logical = resolve(entry), physical = realpathSync.native(logical);
174
174
  const canonicalRoot = realpathSync.native(root);
175
- if (physical !== join(canonicalRoot, "dist", "cotal.js"))
175
+ // npm's postinstall can repoint the saved entry to this package's wrapper.
176
+ if (physical !== join(canonicalRoot, "dist", "cotal.js") && physical !== join(canonicalRoot, "dist", "cotal-npm"))
176
177
  throw new Error("execution launch route does not resolve to this bootstrap");
177
178
  let path = join(canonicalRoot, "package.json");
178
179
  for (let current = dirname(logical); current !== dirname(current); current = dirname(current)) {
@@ -36,7 +36,7 @@ import { connectCheckViaDaemon, managerViaDaemon, queryDaemon, registerViaDaemon
36
36
  import { admitWindowsNativeDaemon, applyInstall, applyUninstall, observeDaemonOwnedService, planInstall, planUninstall, repairMissingInstalledProgram, startInstalled } from "./install.js";
37
37
  import { exchangeDesktopRequest, runDesktopBridge } from "./desktop.js";
38
38
  import { runAccountSetup, runSetup } from "./setup.js";
39
- import { daemonCommandCopy } from "./guidance.js";
39
+ import { daemonCommandCopy, daemonServiceRequirement } from "./guidance.js";
40
40
  import { forgetHostedManagerIntents } from "./manager.js";
41
41
  import { automaticUpdates } from "./auto-update.js";
42
42
  import { watchDaemonGeneration } from "./generation.js";
@@ -119,7 +119,7 @@ function resolveTarget(args, recoverMissingHome = false) {
119
119
  }
120
120
  const REFUSAL = {
121
121
  UNSUPPORTED_PLATFORM: { code: "UNSUPPORTED" },
122
- NO_RUNTIME_DIR: { code: "TARGET_UNAVAILABLE", remedy: "run as the intended operating-system user with its private runtime directory available" },
122
+ NO_RUNTIME_DIR: { code: "TARGET_UNAVAILABLE", remedy: "Use a private runtime directory provisioned by systemd-logind or pam_rundir, or create one owned by your user with mode 0700 and set XDG_RUNTIME_DIR to it" },
123
123
  NOT_RUNNING: { code: "TARGET_UNAVAILABLE", remedy: "start it with `cotal daemon serve`" },
124
124
  ALREADY_RUNNING: { code: "CONFLICT", remedy: "run `cotal daemon status` for the same daemon home; inspect the conflicting endpoint with your operating system before changing it. No foreign endpoint was removed" },
125
125
  DIR_NOT_DIRECTORY: { code: "PERMISSION_DENIED", remedy: "inspect the path; nothing was changed" },
@@ -399,6 +399,11 @@ async function serviceCommand(args, op) {
399
399
  async function unitCommand(args, op) {
400
400
  const presentation = presentationOf(args.values);
401
401
  const values = args.values;
402
+ if (op === "install" && (values["daemon-home"] === undefined || isAbsolute(values["daemon-home"]))) {
403
+ const requirement = daemonServiceRequirement(values["daemon-home"]);
404
+ if (requirement)
405
+ throw requirement;
406
+ }
402
407
  const { paths, home } = resolveTarget(args, true);
403
408
  if (op === "install") {
404
409
  const dry = values["dry-run"] === true;
@@ -450,8 +455,6 @@ async function setupCommand(args) {
450
455
  throw new CommandFailure("refused", "USAGE_INVALID", "space must be 1-64 characters of [A-Za-z0-9_-]", { native: { code: "BAD_FIELD" } });
451
456
  if (args.values.cloud && values.idp !== undefined)
452
457
  throw new CommandFailure("refused", "USAGE_INVALID", "--cloud and --idp cannot be combined");
453
- let choice = values.idp !== undefined || args.values.cloud === true ? await daemonAccountChoice(args) : undefined;
454
- let idp = choice?.url;
455
458
  if (values["client-id"] !== undefined && !values["client-id"].trim())
456
459
  throw new CommandFailure("refused", "USAGE_INVALID", "--client-id cannot be empty");
457
460
  const waitSeconds = values.wait === undefined ? 900 : Number(values.wait);
@@ -459,6 +462,13 @@ async function setupCommand(args) {
459
462
  throw new CommandFailure("refused", "USAGE_INVALID", "--wait takes whole seconds from 0 to 86400");
460
463
  if (values.wait !== undefined && values["no-manager"] !== true)
461
464
  throw new CommandFailure("refused", "USAGE_INVALID", "--wait requires --no-manager; Manager setup never waits for machine approval");
465
+ if (values["daemon-home"] === undefined || isAbsolute(values["daemon-home"])) {
466
+ const requirement = daemonServiceRequirement(values["daemon-home"]);
467
+ if (requirement)
468
+ throw requirement;
469
+ }
470
+ let choice = values.idp !== undefined || args.values.cloud === true ? await daemonAccountChoice(args) : undefined;
471
+ let idp = choice?.url;
462
472
  const { paths, home } = resolveTarget(args);
463
473
  let newSignIn = values.idp !== undefined || args.values.cloud === true;
464
474
  if (!space && !idp) {
@@ -21,7 +21,7 @@ import { base64url, decodeJwt, decodeProtectedHeader } from "jose";
21
21
  import { assertLifecycleToken, isAccountNkey, mintLifecycleUid, resolveAuthProvider } from "@cotal-ai/core";
22
22
  import { claimIdentityRecord, codeSpan, findMesh, homeCotalDir, spaceSegment, userAuthStateDir, workspaceSecretStore } from "@cotal-ai/workspace";
23
23
  import { fetchIdpJwt, IdpSessionRejectedError, IdpUnreachableError, loadIdpSession } from "@cotal-ai/auth";
24
- import { daemonCommandCopy } from "./guidance.js";
24
+ import { daemonCommandCopy, NON_USER_AUTH_MESSAGE, NON_USER_AUTH_REMEDY } from "./guidance.js";
25
25
  /** The service name the daemon proposes for itself. Single-label names are reserved for reference
26
26
  * endpoints and a third-party name must be reverse-DNS, so this is the reverse-DNS of cotal.ai.
27
27
  * Binding it still needs the space operator's `name-bind`; the daemon never claims it. */
@@ -65,7 +65,6 @@ export function readDaemonServiceIdentity(space, home) {
65
65
  /** The fixed sentence per failure. Nothing from the remote side is quoted. */
66
66
  const SENTENCE = {
67
67
  "not-registered": "this space is not registered on this machine; add it with `cotal meshes add`",
68
- "not-user-auth": "this space does not use user sign-in, so the daemon cannot connect to it as its own service",
69
68
  "not-signed-in": "this machine is not signed in to the space's provider",
70
69
  "unsupported-by-space": "the space's auth service does not host service endpoints, so the daemon cannot register with it",
71
70
  unreachable: "the space's auth service could not be reached",
@@ -80,7 +79,7 @@ export async function connectCheck(space, home = homeCotalDir(), signal) {
80
79
  return { outcome: "not-registered", space, message: SENTENCE["not-registered"] };
81
80
  const ua = entry.mode === "user" ? entry.userAuth : undefined;
82
81
  if (!ua)
83
- return { outcome: "not-user-auth", space, message: SENTENCE["not-user-auth"] };
82
+ return { outcome: "not-user-auth", space, message: NON_USER_AUTH_MESSAGE, remedy: NON_USER_AUTH_REMEDY };
84
83
  let session;
85
84
  try {
86
85
  session = loadIdpSession(home, ua.idp.url);
@@ -1,4 +1,15 @@
1
- import { homeCotalDir, shellPath } from "@cotal-ai/workspace";
1
+ import { existsSync } from "node:fs";
2
+ import { codeSpan, CommandFailure, homeCotalDir, resolveOnPath, shellPath } from "@cotal-ai/workspace";
3
+ /** An unavailable systemd installation is different from an unreachable systemd user manager. */
4
+ export function daemonServiceRequirement(home) {
5
+ if (process.platform !== "linux" || (existsSync("/run/systemd/system") && resolveOnPath("systemctl")))
6
+ return undefined;
7
+ return new CommandFailure("refused", "UNSUPPORTED", "The Linux background service requires systemd. This environment does not provide both a running systemd and systemctl on PATH.", {
8
+ remedy: `Manage an existing systemd service from an environment with systemd and systemctl on PATH as the same user. If no daemon is installed or running, run ${codeSpan(daemonCommandCopy("serve", home))} under your own supervisor. Use \`cotal update --self\` for manual updates.`,
9
+ });
10
+ }
11
+ export const NON_USER_AUTH_MESSAGE = "this space does not use user sign-in. The machine service hosts Managers only for user-auth participant spaces";
12
+ export const NON_USER_AUTH_REMEDY = "run `cotal up` in the folder that hosts the local space. Its stack runs the Manager";
2
13
  /** A copyable command for this daemon. Tuples keep option values distinct from boolean flags;
3
14
  * leading-hyphen values need `=` even when shell-quoted. Windows copy targets PowerShell. */
4
15
  export function daemonCommandCopy(op, home, args = []) {
@@ -26,7 +26,8 @@ import { encode, parseRequest } from "./protocol.js";
26
26
  import { createLoginCoordinator } from "./login.js";
27
27
  import { connectCheck } from "./connect.js";
28
28
  import { createServiceConnections } from "./service.js";
29
- import { findMesh, homeCotalDir, isCommandFailure, readUpdateSettings, setUpdateSetting } from "@cotal-ai/workspace";
29
+ import { findMesh, homeCotalDir, isCommandFailure, isMeshRegistryError, meshFile, readMeshRegistry, readUpdateSettings, setUpdateSetting } from "@cotal-ai/workspace";
30
+ import { NON_USER_AUTH_MESSAGE, NON_USER_AUTH_REMEDY } from "./guidance.js";
30
31
  import { desktopSpaces } from "./desktop-state.js";
31
32
  import { idpTimeoutMs, signOutIdpSession, withIdpSessionDir } from "@cotal-ai/auth";
32
33
  import { createHostedManagers, HostedManagerRefusal } from "./manager.js";
@@ -414,7 +415,34 @@ async function serveLocked(opts, uid, lock) {
414
415
  counters.serviceAnswered++;
415
416
  if (req.op === "service-connect" && result.state === "not-registered")
416
417
  return result;
417
- return { ...result, manager: req.op === "service-status" ? await managers.refresh(req.space) : managers.status(req.space) };
418
+ const manager = req.op === "service-status" ? await managers.refresh(req.space) : managers.status(req.space);
419
+ // Read guidance only for these replies, after disconnect has finished removing records.
420
+ if (!manager.registrationCleanup && ((req.op === "service-status" && (result.state === "not-requested" || result.state === "unsupported")) ||
421
+ (req.op === "service-disconnect" && result.state === "disconnected"))) {
422
+ let damaged = false;
423
+ try {
424
+ const { entries, unusable } = readMeshRegistry();
425
+ // Keep pre-hex registrations visible without mistaking a damaged canonical record for a legacy one.
426
+ damaged = unusable.some(error => error.file === meshFile(req.space));
427
+ if (!damaged && entries.some(entry => entry.space === req.space && entry.mode !== "user")) {
428
+ if (req.op === "service-status")
429
+ return { space: req.space, state: "unsupported", message: NON_USER_AUTH_MESSAGE, remedy: NON_USER_AUTH_REMEDY };
430
+ return { ...result, manager: { ...manager, next: NON_USER_AUTH_REMEDY } };
431
+ }
432
+ }
433
+ catch (error) {
434
+ if (!isMeshRegistryError(error))
435
+ throw error;
436
+ damaged = true;
437
+ }
438
+ if (damaged) {
439
+ const remedy = "run `cotal daemon spaces` to identify unreadable records, then restore the mesh registry";
440
+ if (req.op === "service-status")
441
+ return { space: req.space, state: "unavailable", message: "the mesh registry could not be read for this space", remedy };
442
+ return { ...result, manager: { ...manager, next: remedy } };
443
+ }
444
+ }
445
+ return { ...result, manager };
418
446
  });
419
447
  return;
420
448
  }
@@ -23,7 +23,7 @@ import { exchangeDesktopRequest } from "./desktop.js";
23
23
  import { applyInstall, installedDaemonIdentity, planUninstall, planInstalledPathRefresh, startInstalled, restartInstalled } from "./install.js";
24
24
  import { fromRegister } from "./service.js";
25
25
  import { DAEMON_PROTOCOL_VERSION } from "./endpoint.js";
26
- import { daemonCommandCopy } from "./guidance.js";
26
+ import { daemonCommandCopy, NON_USER_AUTH_MESSAGE, NON_USER_AUTH_REMEDY } from "./guidance.js";
27
27
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
28
28
  /** Wait for the daemon to answer its endpoint after a start, so the steps below reach a live one. */
29
29
  async function waitForDaemon(opts, seconds) {
@@ -261,6 +261,9 @@ async function ensureSignedIn(opts, steps) {
261
261
  const check = await connectCheckViaDaemon({ paths: opts.paths, peerUid: opts.peerUid, peerPid: opts.peerPid, space: opts.space });
262
262
  if (!check.ok)
263
263
  throw new CommandFailure("refused", "USAGE_INVALID", `the daemon refused the connection check: ${check.code} ${check.message}`, { native: { code: check.code } });
264
+ if (check.result.outcome === "not-user-auth") {
265
+ throw new CommandFailure("refused", "UNSUPPORTED", NON_USER_AUTH_MESSAGE, { remedy: NON_USER_AUTH_REMEDY, native: { code: "NOT_USER_AUTH" } });
266
+ }
264
267
  if (check.result.outcome === "credential-expired") {
265
268
  throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", check.result.message, { native: { code: "CREDENTIAL_EXPIRED" } });
266
269
  }
@@ -23,6 +23,7 @@ import { reportRunningManagers } from "@cotal-ai/cli/update";
23
23
  import { adoptAutomaticUpdateChild } from "./update-scope.js";
24
24
  import { captureWindowsGeneration, closeWindowsGeneration, windowsGenerationLifecycle } from "./update-generation-win32.js";
25
25
  import { observeUpdateDaemon, sameUpdateDaemon } from "./update-lifetime.js";
26
+ import { daemonServiceRequirement } from "./guidance.js";
26
27
  /** A reconcile child of a parent that said it waits after the child and prints the line. A parent
27
28
  * from before that marker never waits there, so its child keeps the line. */
28
29
  export function currentParentWaits(env, parentPid, journaled) {
@@ -378,6 +379,10 @@ const composed = { ...command, async run(args) {
378
379
  currentPackages = updateRuntime.isCurrent?.() === true;
379
380
  return currentPackages;
380
381
  }, async automaticUpdateAdvice() {
382
+ const systemdAdvice = () => {
383
+ const requirement = daemonServiceRequirement();
384
+ return requirement && `${requirement.message} ${requirement.remedy}`;
385
+ };
381
386
  try {
382
387
  const reply = await queryDaemon({ paths: daemonPaths() });
383
388
  if (!reply.ok)
@@ -386,14 +391,16 @@ const composed = { ...command, async run(args) {
386
391
  throw new Error("machine daemon returned no update schedule; run `cotal daemon status` to inspect it");
387
392
  if (reply.result.update.automatic && typeof reply.result.update.nextAttempt === "string")
388
393
  return undefined;
389
- return "The daemon is not scheduling automatic installation. Run `cotal daemon status` to inspect it. If no daemon service is installed, run `cotal daemon install`.";
394
+ const inactive = "The daemon is not scheduling automatic installation. Run `cotal daemon status` to inspect it.";
395
+ const unsupported = systemdAdvice();
396
+ return `${inactive} ${unsupported ?? "If no daemon service is installed, run `cotal daemon install`."}`;
390
397
  }
391
398
  catch (error) {
392
399
  if (error instanceof EndpointRefusal && error.code === "PEER_NOT_LOCK_OWNER") {
393
400
  return `Could not check the automatic update schedule: ${error.message}.`;
394
401
  }
395
402
  if (error instanceof EndpointRefusal && ["NOT_RUNNING", "NO_RUNTIME_DIR"].includes(error.code)) {
396
- return "No daemon service is running the automatic update schedule. Run `cotal daemon install`, then inspect `cotal daemon status`.";
403
+ return systemdAdvice() ?? "No daemon service is running the automatic update schedule. Run `cotal daemon install`, then inspect `cotal daemon status`.";
397
404
  }
398
405
  throw error;
399
406
  }
package/dist/mcp-host.js CHANGED
@@ -3,6 +3,7 @@ import { execFile } from "node:child_process";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { configFromEnv, MeshAgent, NameTaken, } from "@cotal-ai/connector-core";
5
5
  import { resolveTargetOrThrow } from "@cotal-ai/workspace";
6
+ import { retireLocalAppIdentity } from "@cotal-ai/cli/app-identity";
6
7
  import { selfArgv } from "@cotal-ai/cli/self-exec";
7
8
  /** The host never invents a native conversation for a signed-in space. Static identities use the
8
9
  * terminal-seat contract: the credential and generation last to its horizon, without renewal. */
@@ -34,9 +35,12 @@ export function createMcpHost(space) {
34
35
  // A failed retirement remains owned, but may never route another tool to a stopped agent.
35
36
  held.stopped = true;
36
37
  await held.connection?.agent.stop();
37
- const result = await plumbing(["retire", "--dir", held.dir]);
38
- if (!result.ok)
38
+ try {
39
+ await retireLocalAppIdentity(held.dir);
40
+ }
41
+ catch {
39
42
  throw new Error("identity cleanup is unfinished; call cotal_disconnect again to retry it");
43
+ }
40
44
  held = undefined;
41
45
  };
42
46
  const open = async (name, selection) => {
package/dist/run.js CHANGED
@@ -60,13 +60,6 @@ registry.provide({ provides: commands("mcp"), load: importing("mcp") });
60
60
  // The dispatch module reads the command word as `runCli` will, and loads no command. A word a
61
61
  // provider declares imports that provider's surfaces; any other word imports them all.
62
62
  const { commandWord, completeFileWrites, runCli, stdoutError } = await import("@cotal-ai/cli/dispatch");
63
- const { executionIdentity } = await import("@cotal-ai/workspace");
64
- const identity = executionIdentity();
65
- if (identity && identity.logicalEntry === identity.loadedEntry) {
66
- const { retireSupersededExecutionDescriptor } = await import("./execution-transaction.js");
67
- const { dirname } = await import("node:path");
68
- retireSupersededExecutionDescriptor(dirname(dirname(identity.logicalEntry)));
69
- }
70
63
  const argv = process.argv.slice(2);
71
64
  const { readFileSync } = await import("node:fs");
72
65
  const currentVersion = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cotal-ai",
3
- "version": "0.171.2",
3
+ "version": "0.171.3",
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": [
@@ -37,28 +37,29 @@
37
37
  "node": ">=22.10"
38
38
  },
39
39
  "dependencies": {
40
- "@cotal-ai/auth": "0.171.2",
41
- "@cotal-ai/cli": "0.171.2",
42
- "@cotal-ai/connector-core": "0.171.2",
43
- "@cotal-ai/core": "0.171.2",
44
- "@cotal-ai/delivery": "0.171.2",
45
- "@cotal-ai/manager": "0.171.2",
46
- "@cotal-ai/registry": "0.171.2",
47
- "@cotal-ai/runtime": "0.171.2",
48
- "@cotal-ai/seat": "0.171.2",
49
- "@cotal-ai/workspace": "0.171.2",
40
+ "@cotal-ai/auth": "0.171.3",
41
+ "@cotal-ai/cli": "0.171.3",
42
+ "@cotal-ai/connector-core": "0.171.3",
43
+ "@cotal-ai/core": "0.171.3",
44
+ "@cotal-ai/delivery": "0.171.3",
45
+ "@cotal-ai/manager": "0.171.3",
46
+ "@cotal-ai/registry": "0.171.3",
47
+ "@cotal-ai/runtime": "0.171.3",
48
+ "@cotal-ai/seat": "0.171.3",
49
+ "@cotal-ai/workspace": "0.171.3",
50
50
  "jose": "^6.2.3"
51
51
  },
52
52
  "devDependencies": {
53
- "@cotal-ai/connector-claude-code": "0.171.2",
54
- "@cotal-ai/connector-codex": "0.171.2",
55
- "@cotal-ai/connector-hermes": "0.171.2",
56
- "@cotal-ai/connector-jcode": "0.171.2",
57
- "@cotal-ai/connector-opencode": "0.171.2",
58
- "@cotal-ai/linear": "0.171.2",
59
- "@cotal-ai/pi": "0.171.2",
53
+ "@cotal-ai/connector-claude-code": "0.171.3",
54
+ "@cotal-ai/connector-codex": "0.171.3",
55
+ "@cotal-ai/connector-hermes": "0.171.3",
56
+ "@cotal-ai/connector-jcode": "0.171.3",
57
+ "@cotal-ai/connector-opencode": "0.171.3",
58
+ "@cotal-ai/linear": "0.171.3",
59
+ "@cotal-ai/pi": "0.171.3",
60
60
  "@cotal-ai/smoke-kit": "0.0.0",
61
- "@cotal-ai/web": "0.171.2",
61
+ "@cotal-ai/web": "0.171.3",
62
+ "@modelcontextprotocol/sdk": "1.29.0",
62
63
  "@nats-io/jetstream": "3.4.0",
63
64
  "@nats-io/transport-node": "3.4.0",
64
65
  "typescript": "^5.9.3"
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "v": 1,
3
3
  "files": {
4
- "docs-bundle.bin": "8b31508a1ab9c88cb75d116b79ac79f925aa4bfedceb6c1e99c2f40ba4d773c7",
5
- "docs-index.bin": "976f0244a5463566d7f255ca14fb57bd8bebb9f1f4ba0ba1d7555c7efd91cdd6"
4
+ "docs-bundle.bin": "1b60c67007ec5e34be7b1fc27a95e4c43e557238ea9fc79d19209b2cbc8e49fa",
5
+ "docs-index.bin": "41aa74ee5a6e1b6ddee60f95a70b331eacec5346f3aab5aedb33ab3ba7783e96"
6
6
  },
7
7
  "placements": {
8
8
  "claude": [
@@ -1,4 +1,4 @@
1
1
  "use strict";var import_node_net=require("node:net");var import_node_crypto=require("node:crypto");var import_node_fs=require("node:fs");var import_node_path=require("node:path");var CONTROL_PROTOCOL_VERSION=1;var CONTROL_CLIENT_PROOF_DEADLINE_MS=1e3;var MAX_HANDSHAKE_LINE_BYTES=1024;var MAX_CONTROL_REQUEST_BYTES=1<<20;var BASE64URL_43=/^[A-Za-z0-9_-]{43}$/;var MAC_CHARS=43;var MAC_PREFIX_BYTES=MAC_CHARS+1;var NEWLINE=10;var SPACE=32;var utf8=new TextDecoder("utf-8",{fatal:true});function assertControlVersion(version,where){if(version===CONTROL_PROTOCOL_VERSION)return;throw new Error(`${where} carries control protocol version ${JSON.stringify(version)}, and this build speaks only version ${CONTROL_PROTOCOL_VERSION}. A launcher and connector from different releases refuse each other instead of falling back; upgrade both to the same release.`)}function assertReplyCap(opts){const cap=opts?.maxReplyBytes;if(typeof cap!=="number"||!Number.isSafeInteger(cap)||cap<0)throw new Error(`maxReplyBytes must be a finite, non-negative whole number of bytes, not ${typeof cap==="number"?cap:typeof cap}`)}function assertControlEndpoint(endpoint){assertControlVersion(endpoint.version,"the control endpoint");if(typeof endpoint.token!=="string"||!endpoint.token)throw new Error("the control endpoint has no key")}function transcriptMac(token,role,nc,ns,body){const mac=(0,import_node_crypto.createHmac)("sha256",Buffer.from(token,"utf8"));mac.update(`cotal-control/${CONTROL_PROTOCOL_VERSION}\0${role}\0${nc}\0${ns}`,"utf8");if(body!==void 0)mac.update("\0","utf8").update(body);return mac.digest("base64url")}function macMatches(presented,expected){if(typeof presented!=="string"||!BASE64URL_43.test(presented))return false;return(0,import_node_crypto.timingSafeEqual)(Buffer.from(presented,"ascii"),Buffer.from(expected,"ascii"))}function openSealed(line,expected){if(line.length<MAC_PREFIX_BYTES||line[MAC_CHARS]!==SPACE)return void 0;const body=line.subarray(MAC_PREFIX_BYTES);if(!macMatches(line.subarray(0,MAC_CHARS).toString("latin1"),expected(body)))return void 0;try{return utf8.decode(body)}catch{return void 0}}function parseHandshake(line){try{const value=JSON.parse(utf8.decode(line));return value&&typeof value==="object"&&!Array.isArray(value)?value:void 0}catch{return void 0}}function lineReader(cap,onLine,oversize){let buf=Buffer.alloc(0);let stopped=false;return chunk=>{if(stopped)return;buf=buf.length?Buffer.concat([buf,chunk]):chunk;for(;;){const limit=cap();const nl=buf.indexOf(NEWLINE);const length=nl<0?buf.length:nl;if(length>limit){stopped=true;return oversize()}if(nl<0)return;const line=buf.subarray(0,nl);buf=buf.subarray(nl+1);if(!onLine(line)){stopped=true;return}}}}var nonce=()=>(0,import_node_crypto.randomBytes)(32).toString("base64url");function socketDir(path){return process.platform==="win32"?void 0:(0,import_node_path.dirname)(path)}function assertPrivateDir(dir){const st=(0,import_node_fs.lstatSync)(dir);const uid=process.getuid();const problem=st.isSymbolicLink()?"is a symbolic link, not a directory":!st.isDirectory()?"is not a directory":st.uid!==uid?`is owned by uid ${st.uid}, not by this user (uid ${uid})`:(st.mode&63)!==0?`has mode ${(st.mode&4095).toString(8)}, which lets group or others in`:void 0;if(problem)throw new Error(`control socket directory ${dir} ${problem}, so it is not a private directory of this user. Remove it if you did not create it, or point TMPDIR at a directory only you can write, and relaunch.`)}function checkControlSocketDir(path){if(path.startsWith("\0"))return{ok:false,absent:false,reason:"the path is in the Linux abstract namespace, which any local user can bind"};const dir=socketDir(path);if(!dir)return{ok:true};try{assertPrivateDir(dir);return{ok:true}}catch(e){const code=e.code;return{ok:false,absent:code==="ENOENT",reason:e.message}}}function clientExchange(sock,endpoint,request,done2,opts){assertReplyCap(opts);assertControlEndpoint(endpoint);const nc=nonce();let ns;let requestSent=false;let settled=false;const finish=result=>{if(settled)return;settled=true;clearTimeout(proof);sock.off("data",onData);sock.off("end",onEnd);sock.off("close",onEnd);if(!result.ok)sock.destroy();done2(result)};const refuse=reason=>(finish({ok:false,reason,requestSent}),false);const proof=setTimeout(()=>refuse("the server did not prove it holds the key in time"),opts.proofDeadlineMs??CONTROL_CLIENT_PROOF_DEADLINE_MS);proof.unref?.();const onEnd=()=>void refuse("the connection closed before a proven reply");const onLine=line=>{if(ns===void 0){const challenge=parseHandshake(line);if(!challenge)return refuse("the server's challenge is not JSON");if(challenge.v!==CONTROL_PROTOCOL_VERSION)return refuse(`the server speaks control protocol ${JSON.stringify(challenge.v)}, not ${CONTROL_PROTOCOL_VERSION}`);if(typeof challenge.nonce!=="string"||!BASE64URL_43.test(challenge.nonce))return refuse("the server's nonce is malformed");if(!macMatches(challenge.mac,transcriptMac(endpoint.token,"server",nc,challenge.nonce)))return refuse("the server did not prove it holds the key");ns=challenge.nonce;clearTimeout(proof);const body=Buffer.from(JSON.stringify(request),"utf8");try{requestSent=true;sock.write(Buffer.concat([Buffer.from(`${transcriptMac(endpoint.token,"client",nc,ns,body)} `,"ascii"),body,Buffer.from("\n")]))}catch{return refuse("the connection closed before the request was sent")}opts.onRequestSent?.();return true}const proven=ns;const reply=openSealed(line,body=>transcriptMac(endpoint.token,"reply",nc,proven,body));if(reply===void 0)return refuse("the reply's MAC does not verify");const receipt=`${transcriptMac(endpoint.token,"receipt",nc,proven,line.subarray(MAC_PREFIX_BYTES))}
2
- `;finish({ok:true,reply,receipt});return false};const onData=lineReader(()=>ns===void 0?MAX_HANDSHAKE_LINE_BYTES:MAC_PREFIX_BYTES+opts.maxReplyBytes,onLine,()=>void refuse(ns===void 0?"the server's challenge is oversized":"the reply is oversized"));sock.on("data",onData);sock.on("end",onEnd);sock.on("close",onEnd);try{sock.write(JSON.stringify({v:CONTROL_PROTOCOL_VERSION,nonce:nc})+"\n")}catch{refuse("the connection closed before the hello was sent")}}var import_node_fs3=require("node:fs");var import_node_fs2=require("node:fs");var import_node_child_process=require("node:child_process");var import_node_path2=require("node:path");var isWin=process.platform==="win32";function sys32(exe){const root=process.env.SystemRoot||process.env.windir||"C:\\Windows";return(0,import_node_path2.join)(root,"System32",exe)}var cachedSid;function ownerSid(){if(cachedSid)return cachedSid;const out=(0,import_node_child_process.execFileSync)(sys32("whoami.exe"),["/user","/fo","csv","/nh"],{encoding:"utf8"});const sid=out.trim().split(",").pop()?.replace(/^"|"$/g,"").trim();if(!sid||!/^S-1-/.test(sid))throw new Error(`could not determine the current user's SID from \`whoami\` (got: ${out.trim()})`);cachedSid=sid;return sid}var BROAD_SIDS=["S-1-1-0","S-1-5-11","S-1-5-32-545"];function hardenPrivate(path,kind){if(!isWin){if(kind==="file")(0,import_node_fs2.closeSync)(openPrivate(path,import_node_fs2.constants.O_RDONLY));else(0,import_node_fs2.chmodSync)(path,448);return}const perm=kind==="dir"?"(OI)(CI)(F)":"(F)";const removeBroad=BROAD_SIDS.flatMap(sid=>["/remove:g",`*${sid}`]);const grant=sid=>["/grant:r",`*${sid}:${perm}`];try{(0,import_node_child_process.execFileSync)(sys32("icacls.exe"),[(0,import_node_path2.toNamespacedPath)((0,import_node_path2.resolve)(path)),"/inheritance:r",...removeBroad,...grant(ownerSid()),...grant("S-1-5-18"),...grant("S-1-5-32-544")],{stdio:["ignore","ignore","pipe"]})}catch(e){throw new Error(`failed to harden ${kind} "${path}" to private via icacls: ${e.message.trim()}. Cotal will not leave a secret with a permissive ACL - ensure the path is on an NTFS volume and %SystemRoot%\\System32\\icacls.exe is available.`)}}function notPrivate(path,why){const refused=new Error(`refusing to write "${path}": it ${why}; it was left unchanged`);refused.code="EPERM";return refused}function openPrivate(path,flags){if(isWin){const fd2=(0,import_node_fs2.openSync)(path,flags,384);try{(0,import_node_fs2.fchmodSync)(fd2,384)}catch(e){(0,import_node_fs2.closeSync)(fd2);throw e}return fd2}let fd;try{fd=(0,import_node_fs2.openSync)(path,flags|import_node_fs2.constants.O_NOFOLLOW|import_node_fs2.constants.O_NONBLOCK,384)}catch(e){if(e.code==="ELOOP")throw notPrivate(path,"is a symlink");throw e}try{const info=(0,import_node_fs2.fstatSync)(fd);if(!info.isFile())throw notPrivate(path,"is not a regular file");if(info.uid!==process.getuid())throw notPrivate(path,`is owned by uid ${info.uid}, not this user`);(0,import_node_fs2.fchmodSync)(fd,384);return fd}catch(e){(0,import_node_fs2.closeSync)(fd);throw e}}function writeSecretFile(path,data){writePrivate(path,data,false)}function writeBytes(path,data,exclusive){const fd=openPrivate(path,import_node_fs2.constants.O_WRONLY|import_node_fs2.constants.O_CREAT|(exclusive?import_node_fs2.constants.O_EXCL:0));try{try{(0,import_node_fs2.ftruncateSync)(fd);(0,import_node_fs2.writeFileSync)(fd,data)}finally{(0,import_node_fs2.closeSync)(fd)}}catch(e){if(exclusive){try{(0,import_node_fs2.unlinkSync)(path)}catch{}}throw e}}function writePrivate(path,data,exclusive){writeBytes(path,data,exclusive);if(!isWin)return;try{hardenPrivate(path,"file")}catch(e){try{(0,import_node_fs2.unlinkSync)(path)}catch{}throw e}}function writeSecretFileAtomic(path,data){const tmp=`${path}.${process.pid}.${Date.now()}.tmp`;try{writeSecretFile(tmp,data);(0,import_node_fs2.renameSync)(tmp,path)}catch(e){try{(0,import_node_fs2.unlinkSync)(tmp)}catch{}throw e}}function mkSecretDir(path){(0,import_node_fs2.mkdirSync)(path,{recursive:true,mode:448});hardenPrivate(path,"dir")}var LAUNCH_MATERIAL_ENV="COTAL_LAUNCH_MATERIAL";function readLaunchMaterial(path){let raw;try{if(process.platform!=="win32"){const mode=(0,import_node_fs3.statSync)(path).mode&511;if(mode&63)throw new Error(`is readable beyond its owner (mode ${mode.toString(8)}) - refusing to read connection material out of a file other local users can open`)}raw=(0,import_node_fs3.readFileSync)(path,"utf8")}catch(e){throw new Error(`launch material: cannot read ${path} (${e instanceof Error?e.message:String(e)})`)}let parsed;try{parsed=JSON.parse(raw)}catch{throw new Error(`launch material: ${path} is not valid JSON`)}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))throw new Error(`launch material: ${path} must contain a JSON object`);return validate(parsed,path)}function validate(raw,path){const material={};const str=key=>{const v=raw[key];if(v===void 0)return;if(typeof v!=="string"||!v.trim())throw new Error(`launch material: ${path} has a ${key} that is not a non-empty string`);if(key==="controlKey"&&v!==v.trim())throw new Error(`launch material: ${path} has a controlKey with whitespace around it`);material[key]=v};str("servers");str("creds");str("token");str("controlKey");if(raw.controlToken!==void 0)throw new Error(`launch material: ${path} carries controlToken, the control key field of a release before the control exchange. This build reads controlKey and refuses the old field; launch with a launcher from the same release.`);if(raw.controlVersion!==void 0){assertControlVersion(raw.controlVersion,`launch material ${path}`);material.controlVersion=raw.controlVersion}if(material.controlKey===void 0!==(material.controlVersion===void 0))throw new Error(`launch material: ${path} has ${material.controlKey===void 0?"a controlVersion without a controlKey":"a controlKey without a controlVersion"}. The control key and its protocol version travel together; a launcher and connector from different releases refuse each other.`);if(raw.eventsRequired!==void 0){if(raw.eventsRequired!==true)throw new Error(`launch material: ${path} has eventsRequired that is not exactly true`);material.eventsRequired=true}if(raw.eventPayloadsWithheld!==void 0){if(raw.eventPayloadsWithheld!==true)throw new Error(`launch material: ${path} has eventPayloadsWithheld that is not true`);material.eventPayloadsWithheld=true}if(raw.userAuth!==void 0){const u=raw.userAuth;if(typeof u!=="object"||u===null||Array.isArray(u))throw new Error(`launch material: ${path} has a userAuth that is not an object`);const{owner:owner2,actor,sentinelCredsPath,bearerCmd}=u;const named={owner:owner2,actor,sentinelCredsPath};for(const[k,v]of Object.entries(named))if(typeof v!=="string"||!v.trim())throw new Error(`launch material: ${path} has a userAuth.${k} that is not a non-empty string`);if(!Array.isArray(bearerCmd)||bearerCmd.length===0||!bearerCmd.every(a=>typeof a==="string"&&a))throw new Error(`launch material: ${path} has a userAuth.bearerCmd that is not a non-empty array of strings`);material.userAuth={owner:owner2,actor,sentinelCredsPath,bearerCmd}}if(Object.keys(material).length===0)throw new Error(`launch material: ${path} carries nothing this reader recognises. A launch that references material and supplies none is a broken launcher, not an open-mode launch, so it is refused rather than defaulted.`);return material}var DIRECT_MATERIAL_VARS=["COTAL_CREDS","COTAL_SERVERS","COTAL_TOKEN","COTAL_OWNER","COTAL_ACTOR","COTAL_SENTINEL_CREDS","COTAL_BEARER_CMD","COTAL_EVENTS_REQUIRED","COTAL_CONTROL_KEY","COTAL_CONTROL_VERSION","COTAL_CONTROL_TOKEN","COTAL_LINK"];function readMaterial(env){const path=env[LAUNCH_MATERIAL_ENV]?.trim();if(!path)return void 0;const direct=DIRECT_MATERIAL_VARS.filter(k=>env[k]?.trim());if(direct.length)throw new Error(`COTAL config: this launch carries connection material BOTH as ${LAUNCH_MATERIAL_ENV} and as ${direct.join(", ")}. One launch carries one identity plane - drop the direct variables, or drop the material file.`);return readLaunchMaterial(path)}function controlFromEnv(env=process.env){if(env.COTAL_CONTROL_TOKEN?.trim())throw new Error("COTAL config: COTAL_CONTROL_TOKEN is the control key variable of a release before the control exchange. Set COTAL_CONTROL_KEY and COTAL_CONTROL_VERSION instead; this build refuses the old name rather than guess which protocol it meant.");const path=env.COTAL_CONTROL_SOCKET?.trim();const material=readMaterial(env);const token=material?material.controlKey:directControlKey(env);if(path&&token){const direct=env.COTAL_CONTROL_VERSION;const version=material?material.controlVersion:direct?.trim()?/^(0|[1-9][0-9]*)$/.test(direct)?Number(direct):direct:void 0;assertControlVersion(version,material?"this launch's material":"COTAL_CONTROL_VERSION");return{path,token,version}}if(!path&&!token)return void 0;if(path)throw new Error("COTAL config: COTAL_CONTROL_SOCKET is set but no control key could be resolved - neither the launch material nor COTAL_CONTROL_KEY carries one. Half a pair is not a control endpoint, so this launch is refused rather than started without the control plane it was configured to have.");throw new Error("COTAL config: a control key was supplied but COTAL_CONTROL_SOCKET is unset, so there is no socket to authenticate against. Half a pair is not a control endpoint, so this launch is refused rather than started without the control plane it was configured to have.")}function directControlKey(env){const key=env.COTAL_CONTROL_KEY;if(!key?.trim()){if(env.COTAL_CONTROL_VERSION?.trim())throw new Error("COTAL config: COTAL_CONTROL_VERSION is set without COTAL_CONTROL_KEY. The version travels with the key; set both or neither.");return void 0}if(key!==key.trim())throw new Error("COTAL config: COTAL_CONTROL_KEY has whitespace around it. A key is used as given, never trimmed; remove the whitespace.");return key}function hasIdentity(env=process.env){return Boolean(env.COTAL_NAME?.trim()||env.COTAL_LINK?.trim()||env.COTAL_AGENT_FILE?.trim())}var TIMEOUT_MS=2e3;var MAX_HOOK_REPLY_BYTES=1<<20;var MAY_HAVE_BEEN_HANDLED="this session's control endpoint proved it holds the session's key and was sent the event, but no proven reply came back, so the event may have been handled. No reply was used.";var CONNECT_RETRY_INITIAL_MS=25;var CONNECT_RETRY_MAX_MS=250;var isRetryableConnectError=error=>{const code=error instanceof Error?error.code:void 0;return["ENOENT","ECONNREFUSED","ECONNRESET","EPIPE","EAGAIN","EBUSY"].includes(code??"")};var isSessionStart=event=>event!==null&&typeof event==="object"&&event.hook_event_name==="SessionStart";var warned=false;function warnOnce(message){if(warned)return;warned=true;try{process.stderr.write(`[cotal-connector] ${message}
3
- `)}catch{}}function readStdin(){return new Promise(resolve2=>{if(process.stdin.isTTY)return resolve2("");let d="";process.stdin.setEncoding("utf8");process.stdin.on("data",c=>d+=c);process.stdin.on("end",()=>resolve2(d));process.stdin.on("error",()=>resolve2(d))})}function done(out,confirm){const exit=()=>process.exit(0);const t=out.trim();if(!t)return exit();process.stdout.on("error",()=>exit());process.stdout.write(t+"\n",err=>{if(err||!confirm)return exit();confirm(exit)});setTimeout(exit,1e3)}async function runHookRelay(answer,observe){const managed=hasIdentity();if(!managed&&!answer&&!observe)return done("");const raw=(await readStdin()).trim()||"{}";let event={};try{event=JSON.parse(raw)}catch{}let local;try{local=answer?.(event,{managed})}catch{}if(local)return done(JSON.stringify(local));try{await observe?.(event,{managed})}catch{}if(!managed)return done("");let control;try{control=controlFromEnv()}catch{warnOnce("this session's control endpoint could not be resolved: the launch material is missing, unreadable, readable beyond its owner, malformed, from another release, or contradicted by direct COTAL_ variables. Lifecycle relays are disabled for this session, so presence will not advance and queued peer messages will not be injected. Check COTAL_LAUNCH_MATERIAL and COTAL_CONTROL_SOCKET.");return done("")}if(!control)return done("");const endpoint=control;const startupCritical=isSessionStart(event);let sock;let settled=false;let retryDelayMs=CONNECT_RETRY_INITIAL_MS;const drop=(candidate=sock)=>{try{candidate?.destroy()}catch{}};const settle=()=>{if(settled)return false;settled=true;clearTimeout(timer);return true};const finish=out=>{if(!settle())return;drop();done(out)};const finishWithReceipt=(out,receipt,candidate)=>{if(!settle())return;done(out,then=>{try{candidate.write(receipt,()=>{drop(candidate);then()})}catch{then()}})};let requestSent=false;const unanswered=()=>{if(settled)return;if(requestSent)warnOnce(MAY_HAVE_BEEN_HANDLED);finish("")};const timer=setTimeout(unanswered,TIMEOUT_MS);const retryLater=()=>{const wait=retryDelayMs;retryDelayMs=Math.min(retryDelayMs*2,CONNECT_RETRY_MAX_MS);setTimeout(dial,wait)};const dial=()=>{if(settled)return;const dir=checkControlSocketDir(endpoint.path);if(!dir.ok){if(dir.absent&&startupCritical)return retryLater();if(!dir.absent)warnOnce("this session's control socket is not in a directory private to this user, so the hook connected to nothing. Lifecycle relays are disabled until the connector is relaunched.");return finish("")}const candidate=(0,import_node_net.connect)(endpoint.path);sock=candidate;let connected=false;candidate.on("connect",()=>{if(settled||sock!==candidate)return;connected=true;try{clientExchange(candidate,endpoint,{event,handoff:true},result=>{if(settled||sock!==candidate)return;if(result.ok)return finishWithReceipt(result.reply,result.receipt,candidate);if(result.requestSent)return unanswered();warnOnce("this session's control endpoint did not prove it holds the session's key, so nothing was relayed and no reply was used. A connector from another release looks the same as a stand-in.");finish("")},{maxReplyBytes:MAX_HOOK_REPLY_BYTES,onRequestSent:()=>requestSent=true})}catch{finish("")}});candidate.on("error",error=>{if(settled||sock!==candidate)return;if(!connected&&startupCritical&&isRetryableConnectError(error)){drop(candidate);retryLater();return}unanswered()})};dial()}var LOCAL_SERVERS=new Set(["cotal","plugin_cotal_cotal"]);var COTAL_TOOL=/^mcp__(.+)__(cotal_[a-z0-9]+(?:_[a-z0-9]+)*)$/;function hostedCotalTool(toolName){const m=typeof toolName==="string"?COTAL_TOOL.exec(toolName):null;return m&&!LOCAL_SERVERS.has(m[1])?m[2]:void 0}var ONE_PATH_REASON="This session is already on a Cotal mesh through its local Cotal plugin, and a session uses one Cotal path. Use the local cotal_* tools (mcp__cotal__...). To use the hosted Cotal connector, start a Claude Code session that Cotal did not launch.";var otherCotalPath=(event,session)=>{if(!session.managed)return void 0;const ev=event;if(ev?.hook_event_name!=="PreToolUse"||hostedCotalTool(ev.tool_name)===void 0)return void 0;return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:ONE_PATH_REASON}}};var import_node_fs4=require("node:fs");var import_node_path3=require("node:path");var CONNECTED=/^connection_id: (\S+)$/m;var SAFE_ID=/^[A-Za-z0-9_-]{1,128}$/;var FORKED_REASON="This connection_id was opened by another Claude Code session. This session is a fork or a copy of that one, so it needs its own connection: call cotal_connect, then use the connection_id it returns.";function connectedId(response){const blocks=Array.isArray(response)?response:[];for(const b of blocks){const text=b?.text;const id=typeof text==="string"?CONNECTED.exec(text)?.[1]:void 0;if(id!==void 0)return SAFE_ID.test(id)?id:void 0}return void 0}function connectionOwner(dataDir){const dir=dataDir?(0,import_node_path3.join)(dataDir,"hosted-connections"):void 0;return(event,session)=>{if(session.managed||!dir)return void 0;const ev=event;const tool=hostedCotalTool(ev?.tool_name);const sessionId=ev?.session_id;if(tool===void 0||typeof sessionId!=="string"||!sessionId)return void 0;const given=ev?.tool_input?.connection_id;const id=typeof given==="string"&&SAFE_ID.test(given)?given:void 0;const owner2=()=>{try{return(0,import_node_fs4.readFileSync)((0,import_node_path3.join)(dir,id),"utf8")}catch{return void 0}};if(ev?.hook_event_name==="PostToolUse"&&tool==="cotal_connect"){const opened=connectedId(ev.tool_response);if(opened===void 0)return void 0;(0,import_node_fs4.mkdirSync)(dir,{recursive:true,mode:448});(0,import_node_fs4.writeFileSync)((0,import_node_path3.join)(dir,opened),sessionId,{mode:384});return void 0}if(id===void 0)return void 0;if(ev?.hook_event_name==="PostToolUse"&&tool==="cotal_disconnect"){if(owner2()===sessionId)(0,import_node_fs4.rmSync)((0,import_node_path3.join)(dir,id),{force:true});return void 0}if(ev?.hook_event_name!=="PreToolUse")return void 0;const recorded=owner2();if(recorded===void 0||recorded===sessionId)return void 0;return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:FORKED_REASON}}}}var import_node_fs6=require("node:fs");var import_node_net2=require("node:net");var import_node_os2=require("node:os");var import_node_path5=require("node:path");var import_node_fs5=require("node:fs");var import_node_os=require("node:os");var import_node_path4=require("node:path");var WAKE_ID=/^[A-Za-z0-9_-]{1,128}$/;var WIN_PIPES="\\\\.\\pipe\\";var WIN_PREFIX="cotal-claude-wake-";function wakeDir(){if(process.platform==="win32")return WIN_PIPES;const uid=process.getuid();const dir=(0,import_node_path4.join)((0,import_node_os.tmpdir)(),`cotal-claude-wake-${uid}`);(0,import_node_fs5.mkdirSync)(dir,{recursive:true,mode:448});const st=(0,import_node_fs5.lstatSync)(dir);if(!st.isDirectory()||st.uid!==uid||(st.mode&63)!==0)throw new Error(`${dir} is not a private directory of this user's`);return dir}var entryName=(claudePid,serverPid)=>process.platform==="win32"?`${WIN_PREFIX}${claudePid}-${serverPid}`:`${claudePid}-${serverPid}.sock`;var ENTRY=process.platform==="win32"?new RegExp(`^${WIN_PREFIX}(\\d+)-(\\d+)$`):/^(\d+)-(\d+)\.sock$/;function alive(pid){try{process.kill(pid,0);return true}catch(e){return e.code==="EPERM"}}function wakeSocketPath(claudePid,serverPid=process.pid){const dir=wakeDir();return process.platform==="win32"?`${dir}${entryName(claudePid,serverPid)}`:(0,import_node_path4.join)(dir,entryName(claudePid,serverPid))}function wakeSockets(claudePid){const dir=wakeDir();return(0,import_node_fs5.readdirSync)(dir).flatMap(name=>{const m=ENTRY.exec(name);return m?.[1]===String(claudePid)&&alive(Number(m[2]))?[wakeSocketPath(claudePid,Number(m[2]))]:[]})}function nativeSocketPath(feed){return`${feed}.native`}function stateFile(session){if(!WAKE_ID.test(session))throw new Error("invalid native session identity");const root=(0,import_node_path5.join)((0,import_node_os2.tmpdir)(),`cotal-claude-native-${process.getuid?.()??"local"}`);const st=(0,import_node_fs6.lstatSync)(root,{throwIfNoEntry:false});if(st&&(!st.isDirectory()||process.getuid&&st.uid!==process.getuid()))throw new Error("native session state is not this user's private directory");mkSecretDir(root);return(0,import_node_path5.join)(root,`${session}.json`)}function readRecord(file){const st=(0,import_node_fs6.lstatSync)(file,{throwIfNoEntry:false});if(!st)return void 0;if(!st.isFile()||st.size>16384||process.getuid&&(st.uid!==process.getuid()||(st.mode&63)!==0))throw new Error("native session state is not an owner-private bounded regular file");const value=JSON.parse((0,import_node_fs6.readFileSync)(file,"utf8"));if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("invalid native session state");return value}function transcriptMatches(session,path){return typeof path==="string"&&(0,import_node_path5.isAbsolute)(path)&&(0,import_node_path5.basename)(path)===`${session}.jsonl`}async function forward(event,hostPid){const paths=wakeSockets(hostPid);if(!paths.length)throw new Error("no local native lifecycle server");await Promise.all(paths.map(path=>new Promise((resolve2,reject)=>{const socket=(0,import_node_net2.createConnection)(nativeSocketPath(path));let reply="";socket.setEncoding("utf8");socket.setTimeout(2e3,()=>socket.destroy(new Error("native lifecycle relay timed out")));socket.on("connect",()=>socket.write(`${JSON.stringify({op:"native",event})}
2
+ `;finish({ok:true,reply,receipt});return false};const onData=lineReader(()=>ns===void 0?MAX_HANDSHAKE_LINE_BYTES:MAC_PREFIX_BYTES+opts.maxReplyBytes,onLine,()=>void refuse(ns===void 0?"the server's challenge is oversized":"the reply is oversized"));sock.on("data",onData);sock.on("end",onEnd);sock.on("close",onEnd);try{sock.write(JSON.stringify({v:CONTROL_PROTOCOL_VERSION,nonce:nc})+"\n")}catch{refuse("the connection closed before the hello was sent")}}var import_node_fs3=require("node:fs");var import_node_fs2=require("node:fs");var import_node_child_process=require("node:child_process");var import_node_path2=require("node:path");var isWin=process.platform==="win32";function sys32(exe){const root=process.env.SystemRoot||process.env.windir||"C:\\Windows";return(0,import_node_path2.join)(root,"System32",exe)}var cachedSid;function ownerSid(){if(cachedSid)return cachedSid;const out=(0,import_node_child_process.execFileSync)(sys32("whoami.exe"),["/user","/fo","csv","/nh"],{encoding:"utf8"});const sid=out.trim().split(",").pop()?.replace(/^"|"$/g,"").trim();if(!sid||!/^S-1-/.test(sid))throw new Error(`could not determine the current user's SID from \`whoami\` (got: ${out.trim()})`);cachedSid=sid;return sid}var BROAD_SIDS=["S-1-1-0","S-1-5-11","S-1-5-32-545"];function hardenPrivate(path,kind){if(!isWin){if(kind==="file")(0,import_node_fs2.closeSync)(openPrivate(path,import_node_fs2.constants.O_RDONLY));else(0,import_node_fs2.chmodSync)(path,448);return}const perm=kind==="dir"?"(OI)(CI)(F)":"(F)";const removeBroad=BROAD_SIDS.flatMap(sid=>["/remove:g",`*${sid}`]);const grant=sid=>["/grant:r",`*${sid}:${perm}`];try{(0,import_node_child_process.execFileSync)(sys32("icacls.exe"),[(0,import_node_path2.toNamespacedPath)((0,import_node_path2.resolve)(path)),"/inheritance:r",...removeBroad,...grant(ownerSid()),...grant("S-1-5-18"),...grant("S-1-5-32-544")],{stdio:["ignore","ignore","pipe"]})}catch(e){throw new Error(`failed to harden ${kind} "${path}" to private via icacls: ${e.message.trim()}. Cotal will not leave a secret with a permissive ACL - ensure the path is on an NTFS volume and %SystemRoot%\\System32\\icacls.exe is available.`)}}function notPrivate(path,why){const refused=new Error(`refusing to write "${path}": it ${why}; it was left unchanged`);refused.code="EPERM";return refused}function openPrivate(path,flags){if(isWin){const fd2=(0,import_node_fs2.openSync)(path,flags,384);try{(0,import_node_fs2.fchmodSync)(fd2,384)}catch(e){(0,import_node_fs2.closeSync)(fd2);throw e}return fd2}let fd;try{fd=(0,import_node_fs2.openSync)(path,flags|import_node_fs2.constants.O_NOFOLLOW|import_node_fs2.constants.O_NONBLOCK,384)}catch(e){if(e.code==="ELOOP")throw notPrivate(path,"is a symlink");throw e}try{const info=(0,import_node_fs2.fstatSync)(fd);if(!info.isFile())throw notPrivate(path,"is not a regular file");if(info.uid!==process.getuid())throw notPrivate(path,`is owned by uid ${info.uid}, not this user`);(0,import_node_fs2.fchmodSync)(fd,384);return fd}catch(e){(0,import_node_fs2.closeSync)(fd);throw e}}function writeSecretFile(path,data){writePrivate(path,data,false)}function writeBytes(path,data,exclusive){const fd=openPrivate(path,import_node_fs2.constants.O_WRONLY|import_node_fs2.constants.O_CREAT|(exclusive?import_node_fs2.constants.O_EXCL:0));try{try{(0,import_node_fs2.ftruncateSync)(fd);(0,import_node_fs2.writeFileSync)(fd,data)}finally{(0,import_node_fs2.closeSync)(fd)}}catch(e){if(exclusive){try{(0,import_node_fs2.unlinkSync)(path)}catch{}}throw e}}function writePrivate(path,data,exclusive){writeBytes(path,data,exclusive);if(!isWin)return;try{hardenPrivate(path,"file")}catch(e){try{(0,import_node_fs2.unlinkSync)(path)}catch{}throw e}}function writeSecretFileAtomic(path,data){const tmp=`${path}.${process.pid}.${Date.now()}.tmp`;try{writeSecretFile(tmp,data);(0,import_node_fs2.renameSync)(tmp,path)}catch(e){try{(0,import_node_fs2.unlinkSync)(tmp)}catch{}throw e}}function mkSecretDir(path){(0,import_node_fs2.mkdirSync)(path,{recursive:true,mode:448});hardenPrivate(path,"dir")}var LAUNCH_MATERIAL_ENV="COTAL_LAUNCH_MATERIAL";function readLaunchMaterial(path){let raw;try{if(process.platform!=="win32"){const mode=(0,import_node_fs3.statSync)(path).mode&511;if(mode&63)throw new Error(`is readable beyond its owner (mode ${mode.toString(8)}) - refusing to read connection material out of a file other local users can open`)}raw=(0,import_node_fs3.readFileSync)(path,"utf8")}catch(e){throw new Error(`launch material: cannot read ${path} (${e instanceof Error?e.message:String(e)})`)}let parsed;try{parsed=JSON.parse(raw)}catch{throw new Error(`launch material: ${path} is not valid JSON`)}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))throw new Error(`launch material: ${path} must contain a JSON object`);return validate(parsed,path)}function validate(raw,path){const material={};const str=key=>{const v=raw[key];if(v===void 0)return;if(typeof v!=="string"||!v.trim())throw new Error(`launch material: ${path} has a ${key} that is not a non-empty string`);if(key==="controlKey"&&v!==v.trim())throw new Error(`launch material: ${path} has a controlKey with whitespace around it`);material[key]=v};str("servers");str("creds");str("token");str("controlKey");if(raw.controlToken!==void 0)throw new Error(`launch material: ${path} carries controlToken, the control key field of a release before the control exchange. This build reads controlKey and refuses the old field; launch with a launcher from the same release.`);if(raw.controlVersion!==void 0){assertControlVersion(raw.controlVersion,`launch material ${path}`);material.controlVersion=raw.controlVersion}if(material.controlKey===void 0!==(material.controlVersion===void 0))throw new Error(`launch material: ${path} has ${material.controlKey===void 0?"a controlVersion without a controlKey":"a controlKey without a controlVersion"}. The control key and its protocol version travel together; a launcher and connector from different releases refuse each other.`);if(raw.eventsRequired!==void 0){if(raw.eventsRequired!==true)throw new Error(`launch material: ${path} has eventsRequired that is not exactly true`);material.eventsRequired=true}if(raw.eventPayloadsWithheld!==void 0){if(raw.eventPayloadsWithheld!==true)throw new Error(`launch material: ${path} has eventPayloadsWithheld that is not true`);material.eventPayloadsWithheld=true}if(raw.userAuth!==void 0){const u=raw.userAuth;if(typeof u!=="object"||u===null||Array.isArray(u))throw new Error(`launch material: ${path} has a userAuth that is not an object`);const{owner:owner2,actor,sentinelCredsPath,bearerCmd}=u;const named={owner:owner2,actor,sentinelCredsPath};for(const[k,v]of Object.entries(named))if(typeof v!=="string"||!v.trim())throw new Error(`launch material: ${path} has a userAuth.${k} that is not a non-empty string`);if(!Array.isArray(bearerCmd)||bearerCmd.length===0||!bearerCmd.every(a=>typeof a==="string"&&a))throw new Error(`launch material: ${path} has a userAuth.bearerCmd that is not a non-empty array of strings`);material.userAuth={owner:owner2,actor,sentinelCredsPath,bearerCmd}}if(Object.keys(material).length===0)throw new Error(`launch material: ${path} carries nothing this reader recognises. A launch that references material and supplies none is a broken launcher, not an open-mode launch, so it is refused rather than defaulted.`);return material}var DIRECT_MATERIAL_VARS=["COTAL_CREDS","COTAL_SERVERS","COTAL_TOKEN","COTAL_OWNER","COTAL_ACTOR","COTAL_SENTINEL_CREDS","COTAL_BEARER_CMD","COTAL_EVENTS_REQUIRED","COTAL_CONTROL_KEY","COTAL_CONTROL_VERSION","COTAL_CONTROL_TOKEN","COTAL_LINK"];function readMaterial(env){const path=env[LAUNCH_MATERIAL_ENV]?.trim();if(!path)return void 0;const direct=DIRECT_MATERIAL_VARS.filter(k=>env[k]?.trim());if(direct.length)throw new Error(`COTAL config: this launch carries connection material BOTH as ${LAUNCH_MATERIAL_ENV} and as ${direct.join(", ")}. One launch carries one identity plane - drop the direct variables, or drop the material file.`);return readLaunchMaterial(path)}function controlFromEnv(env=process.env){if(env.COTAL_CONTROL_TOKEN?.trim())throw new Error("COTAL config: COTAL_CONTROL_TOKEN is the control key variable of a release before the control exchange. Set COTAL_CONTROL_KEY and COTAL_CONTROL_VERSION instead; this build refuses the old name rather than guess which protocol it meant.");const path=env.COTAL_CONTROL_SOCKET?.trim();const material=readMaterial(env);const token=material?material.controlKey:directControlKey(env);if(path&&token){const direct=env.COTAL_CONTROL_VERSION;const version=material?material.controlVersion:direct?.trim()?/^(0|[1-9][0-9]*)$/.test(direct)?Number(direct):direct:void 0;assertControlVersion(version,material?"this launch's material":"COTAL_CONTROL_VERSION");return{path,token,version}}if(!path&&!token)return void 0;if(path)throw new Error("COTAL config: COTAL_CONTROL_SOCKET is set but no control key could be resolved - neither the launch material nor COTAL_CONTROL_KEY carries one. Half a pair is not a control endpoint, so this launch is refused rather than started without the control plane it was configured to have.");throw new Error("COTAL config: a control key was supplied but COTAL_CONTROL_SOCKET is unset, so there is no socket to authenticate against. Half a pair is not a control endpoint, so this launch is refused rather than started without the control plane it was configured to have.")}function directControlKey(env){const key=env.COTAL_CONTROL_KEY;if(!key?.trim()){if(env.COTAL_CONTROL_VERSION?.trim())throw new Error("COTAL config: COTAL_CONTROL_VERSION is set without COTAL_CONTROL_KEY. The version travels with the key; set both or neither.");return void 0}if(key!==key.trim())throw new Error("COTAL config: COTAL_CONTROL_KEY has whitespace around it. A key is used as given, never trimmed; remove the whitespace.");return key}function hasIdentity(env=process.env){return Boolean(env.COTAL_NAME?.trim()||env.COTAL_LINK?.trim()||env.COTAL_AGENT_FILE?.trim())}var TIMEOUT_MS=2e3;var MAX_HOOK_REPLY_BYTES=1<<20;var MAY_HAVE_BEEN_HANDLED="this session's control endpoint proved it holds the session's key and was sent the event, but no proven reply came back, so the event may have been handled. No reply was used.";var CONNECT_RETRY_INITIAL_MS=25;var CONNECT_RETRY_MAX_MS=250;var LAUNCH_CONNECT_MS=3e4;var LAUNCH_SOURCES=new Set(["startup","resume","fork"]);var isRetryableConnectError=error=>{const code=error instanceof Error?error.code:void 0;return["ENOENT","ECONNREFUSED","ECONNRESET","EPIPE","EAGAIN","EBUSY"].includes(code??"")};var isSessionStart=event=>event!==null&&typeof event==="object"&&event.hook_event_name==="SessionStart";var warned=false;function warnOnce(message){if(warned)return;warned=true;try{process.stderr.write(`[cotal-connector] ${message}
3
+ `)}catch{}}function readStdin(){return new Promise(resolve2=>{if(process.stdin.isTTY)return resolve2("");let d="";process.stdin.setEncoding("utf8");process.stdin.on("data",c=>d+=c);process.stdin.on("end",()=>resolve2(d));process.stdin.on("error",()=>resolve2(d))})}function done(out,confirm){const exit=()=>process.exit(0);const t=out.trim();if(!t)return exit();process.stdout.on("error",()=>exit());process.stdout.write(t+"\n",err=>{if(err||!confirm)return exit();confirm(exit)});setTimeout(exit,1e3)}async function runHookRelay(answer,observe){const managed=hasIdentity();if(!managed&&!answer&&!observe)return done("");const raw=(await readStdin()).trim()||"{}";let event={};try{event=JSON.parse(raw)}catch{}let local;try{local=answer?.(event,{managed})}catch{}if(local)return done(JSON.stringify(local));try{await observe?.(event,{managed})}catch{}if(!managed)return done("");let control;try{control=controlFromEnv()}catch{warnOnce("this session's control endpoint could not be resolved: the launch material is missing, unreadable, readable beyond its owner, malformed, from another release, or contradicted by direct COTAL_ variables. Lifecycle relays are disabled for this session, so presence will not advance and queued peer messages will not be injected. Check COTAL_LAUNCH_MATERIAL and COTAL_CONTROL_SOCKET.");return done("")}if(!control)return done("");const endpoint=control;const startupCritical=isSessionStart(event);const launch=startupCritical&&LAUNCH_SOURCES.has(event.source);let sock;let settled=false;let retryDelayMs=CONNECT_RETRY_INITIAL_MS;const drop=(candidate=sock)=>{try{candidate?.destroy()}catch{}};const settle=()=>{if(settled)return false;settled=true;clearTimeout(timer);return true};const finish=out=>{if(!settle())return;drop();done(out)};const finishWithReceipt=(out,receipt,candidate)=>{if(!settle())return;done(out,then=>{try{candidate.write(receipt,()=>{drop(candidate);then()})}catch{then()}})};let requestSent=false;const unanswered=()=>{if(settled)return;if(requestSent)warnOnce(MAY_HAVE_BEEN_HANDLED);finish("")};let timer=setTimeout(unanswered,launch?LAUNCH_CONNECT_MS:TIMEOUT_MS);const retryLater=()=>{const wait=retryDelayMs;retryDelayMs=Math.min(retryDelayMs*2,CONNECT_RETRY_MAX_MS);setTimeout(dial,wait)};const dial=()=>{if(settled)return;const dir=checkControlSocketDir(endpoint.path);if(!dir.ok){if(dir.absent&&startupCritical)return retryLater();if(!dir.absent)warnOnce("this session's control socket is not in a directory private to this user, so the hook connected to nothing. Lifecycle relays are disabled until the connector is relaunched.");return finish("")}const candidate=(0,import_node_net.connect)(endpoint.path);sock=candidate;let connected=false;candidate.on("connect",()=>{if(settled||sock!==candidate)return;connected=true;if(launch){clearTimeout(timer);timer=setTimeout(unanswered,TIMEOUT_MS)}try{clientExchange(candidate,endpoint,{event,handoff:true},result=>{if(settled||sock!==candidate)return;if(result.ok)return finishWithReceipt(result.reply,result.receipt,candidate);if(result.requestSent)return unanswered();warnOnce("this session's control endpoint did not prove it holds the session's key, so nothing was relayed and no reply was used. A connector from another release looks the same as a stand-in.");finish("")},{maxReplyBytes:MAX_HOOK_REPLY_BYTES,onRequestSent:()=>requestSent=true})}catch{finish("")}});candidate.on("error",error=>{if(settled||sock!==candidate)return;if(!connected&&startupCritical&&isRetryableConnectError(error)){drop(candidate);retryLater();return}unanswered()})};dial()}var LOCAL_SERVERS=new Set(["cotal","plugin_cotal_cotal"]);var COTAL_TOOL=/^mcp__(.+)__(cotal_[a-z0-9]+(?:_[a-z0-9]+)*)$/;function hostedCotalTool(toolName){const m=typeof toolName==="string"?COTAL_TOOL.exec(toolName):null;return m&&!LOCAL_SERVERS.has(m[1])?m[2]:void 0}var ONE_PATH_REASON="This session is already on a Cotal mesh through its local Cotal plugin, and a session uses one Cotal path. Use the local cotal_* tools (mcp__cotal__...). To use the hosted Cotal connector, start a Claude Code session that Cotal did not launch.";var otherCotalPath=(event,session)=>{if(!session.managed)return void 0;const ev=event;if(ev?.hook_event_name!=="PreToolUse"||hostedCotalTool(ev.tool_name)===void 0)return void 0;return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:ONE_PATH_REASON}}};var import_node_fs4=require("node:fs");var import_node_path3=require("node:path");var CONNECTED=/^connection_id: (\S+)$/m;var SAFE_ID=/^[A-Za-z0-9_-]{1,128}$/;var FORKED_REASON="This connection_id was opened by another Claude Code session. This session is a fork or a copy of that one, so it needs its own connection: call cotal_connect, then use the connection_id it returns.";function connectedId(response){const blocks=Array.isArray(response)?response:[];for(const b of blocks){const text=b?.text;const id=typeof text==="string"?CONNECTED.exec(text)?.[1]:void 0;if(id!==void 0)return SAFE_ID.test(id)?id:void 0}return void 0}function connectionOwner(dataDir){const dir=dataDir?(0,import_node_path3.join)(dataDir,"hosted-connections"):void 0;return(event,session)=>{if(session.managed||!dir)return void 0;const ev=event;const tool=hostedCotalTool(ev?.tool_name);const sessionId=ev?.session_id;if(tool===void 0||typeof sessionId!=="string"||!sessionId)return void 0;const given=ev?.tool_input?.connection_id;const id=typeof given==="string"&&SAFE_ID.test(given)?given:void 0;const owner2=()=>{try{return(0,import_node_fs4.readFileSync)((0,import_node_path3.join)(dir,id),"utf8")}catch{return void 0}};if(ev?.hook_event_name==="PostToolUse"&&tool==="cotal_connect"){const opened=connectedId(ev.tool_response);if(opened===void 0)return void 0;(0,import_node_fs4.mkdirSync)(dir,{recursive:true,mode:448});(0,import_node_fs4.writeFileSync)((0,import_node_path3.join)(dir,opened),sessionId,{mode:384});return void 0}if(id===void 0)return void 0;if(ev?.hook_event_name==="PostToolUse"&&tool==="cotal_disconnect"){if(owner2()===sessionId)(0,import_node_fs4.rmSync)((0,import_node_path3.join)(dir,id),{force:true});return void 0}if(ev?.hook_event_name!=="PreToolUse")return void 0;const recorded=owner2();if(recorded===void 0||recorded===sessionId)return void 0;return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:FORKED_REASON}}}}var import_node_fs6=require("node:fs");var import_node_net2=require("node:net");var import_node_os2=require("node:os");var import_node_path5=require("node:path");var import_node_fs5=require("node:fs");var import_node_os=require("node:os");var import_node_path4=require("node:path");var WAKE_ID=/^[A-Za-z0-9_-]{1,128}$/;var WIN_PIPES="\\\\.\\pipe\\";var WIN_PREFIX="cotal-claude-wake-";function wakeDir(){if(process.platform==="win32")return WIN_PIPES;const uid=process.getuid();const dir=(0,import_node_path4.join)((0,import_node_os.tmpdir)(),`cotal-claude-wake-${uid}`);(0,import_node_fs5.mkdirSync)(dir,{recursive:true,mode:448});const st=(0,import_node_fs5.lstatSync)(dir);if(!st.isDirectory()||st.uid!==uid||(st.mode&63)!==0)throw new Error(`${dir} is not a private directory of this user's`);return dir}var entryName=(claudePid,serverPid)=>process.platform==="win32"?`${WIN_PREFIX}${claudePid}-${serverPid}`:`${claudePid}-${serverPid}.sock`;var ENTRY=process.platform==="win32"?new RegExp(`^${WIN_PREFIX}(\\d+)-(\\d+)$`):/^(\d+)-(\d+)\.sock$/;function alive(pid){try{process.kill(pid,0);return true}catch(e){return e.code==="EPERM"}}function wakeSocketPath(claudePid,serverPid=process.pid){const dir=wakeDir();return process.platform==="win32"?`${dir}${entryName(claudePid,serverPid)}`:(0,import_node_path4.join)(dir,entryName(claudePid,serverPid))}function wakeSockets(claudePid){const dir=wakeDir();return(0,import_node_fs5.readdirSync)(dir).flatMap(name=>{const m=ENTRY.exec(name);return m?.[1]===String(claudePid)&&alive(Number(m[2]))?[wakeSocketPath(claudePid,Number(m[2]))]:[]})}function nativeSocketPath(feed){return`${feed}.native`}function stateFile(session){if(!WAKE_ID.test(session))throw new Error("invalid native session identity");const root=(0,import_node_path5.join)((0,import_node_os2.tmpdir)(),`cotal-claude-native-${process.getuid?.()??"local"}`);const st=(0,import_node_fs6.lstatSync)(root,{throwIfNoEntry:false});if(st&&(!st.isDirectory()||process.getuid&&st.uid!==process.getuid()))throw new Error("native session state is not this user's private directory");mkSecretDir(root);return(0,import_node_path5.join)(root,`${session}.json`)}function readRecord(file){const st=(0,import_node_fs6.lstatSync)(file,{throwIfNoEntry:false});if(!st)return void 0;if(!st.isFile()||st.size>16384||process.getuid&&(st.uid!==process.getuid()||(st.mode&63)!==0))throw new Error("native session state is not an owner-private bounded regular file");const value=JSON.parse((0,import_node_fs6.readFileSync)(file,"utf8"));if(!value||typeof value!=="object"||Array.isArray(value))throw new Error("invalid native session state");return value}function transcriptMatches(session,path){return typeof path==="string"&&(0,import_node_path5.isAbsolute)(path)&&(0,import_node_path5.basename)(path)===`${session}.jsonl`}async function forward(event,hostPid){const paths=wakeSockets(hostPid);if(!paths.length)throw new Error("no local native lifecycle server");await Promise.all(paths.map(path=>new Promise((resolve2,reject)=>{const socket=(0,import_node_net2.createConnection)(nativeSocketPath(path));let reply="";socket.setEncoding("utf8");socket.setTimeout(2e3,()=>socket.destroy(new Error("native lifecycle relay timed out")));socket.on("connect",()=>socket.write(`${JSON.stringify({op:"native",event})}
4
4
  `));socket.on("data",data=>{reply+=data;if(reply.length>128)socket.destroy()});socket.on("error",reject);socket.on("close",()=>{try{if(JSON.parse(reply).ok===true)resolve2();else reject(new Error("native lifecycle binding refused"))}catch{reject(new Error("native lifecycle binding was not confirmed"))}})})))}async function observePersonalHook(value){if(!value||typeof value!=="object")return;const event=value;if(event.agent_id!==void 0||typeof event.session_id!=="string"||!WAKE_ID.test(event.session_id)||!transcriptMatches(event.session_id,event.transcript_path)||typeof event.hook_event_name!=="string")return;if(!["SessionStart","UserPromptSubmit","PreToolUse","PostToolBatch","Notification","Stop","StopFailure","SessionEnd"].includes(event.hook_event_name))return;const file=stateFile(event.session_id);const previous=readRecord(file);if(previous&&previous.transcript_path!==event.transcript_path)throw new Error("native command hook changed its session transcript");const safe={};for(const key of["hook_event_name","session_id","transcript_path","cwd","source","notification_type","error","model"])if(typeof event[key]==="string"&&event[key].length<=4096)safe[key]=event[key];if(JSON.stringify(safe).length>8192)throw new Error("native command-hook metadata is too large");writeSecretFileAtomic(file,JSON.stringify(safe));const target=readRecord(`${file}.host`);if(target){if(!Number.isInteger(target.hostPid)||target.hostPid<=0)throw new Error("invalid native lifecycle host");await forward(safe,target.hostPid)}if(event.hook_event_name==="SessionEnd"){(0,import_node_fs6.unlinkSync)(file);if(target)(0,import_node_fs6.unlinkSync)(`${file}.host`)}}var owner=connectionOwner(process.env.CLAUDE_PLUGIN_DATA);void runHookRelay((event,session)=>otherCotalPath(event,session)??owner(event,session),async(event,session)=>{if(!session.managed)await observePersonalHook(event)}).catch(()=>process.exit(0));