cotal-ai 0.161.1 → 0.163.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/daemon/account.js +1 -2
- package/dist/daemon/command.js +47 -11
- package/dist/daemon/login.js +4 -3
- package/dist/daemon/manager.js +1 -1
- package/dist/daemon/setup.js +12 -1
- package/package.json +19 -19
- package/seeded-connectors/_shared/docs-bundle.bin +0 -0
- package/seeded-connectors/_shared/docs-index.bin +0 -0
- package/seeded-connectors/_shared/placements.json +2 -2
- package/seeded-connectors/claude/dist/app-host.d.ts +1 -1
- package/seeded-connectors/claude/dist/app-host.d.ts.map +1 -1
- package/seeded-connectors/claude/dist/approval-notice.d.ts.map +1 -1
- package/seeded-connectors/claude/dist/hook.cjs +3 -3
- package/seeded-connectors/claude/dist/index.js +1 -1
- package/seeded-connectors/claude/dist/mcp.cjs +9 -9
- package/seeded-connectors/claude/dist/mcp.d.ts.map +1 -1
- package/seeded-connectors/claude/dist/monitor.cjs +4 -4
- package/seeded-connectors/claude/dist/seat.cjs +1 -1
- package/seeded-connectors/claude/hooks/native-wake.js +2 -1
- package/seeded-connectors/claude/package.json +1 -1
- package/seeded-connectors/codex/dist/host.js +18 -18
- package/seeded-connectors/codex/dist/index.js +1 -1
- package/seeded-connectors/codex/dist/personal-host.d.ts +1 -1
- package/seeded-connectors/codex/dist/personal-host.d.ts.map +1 -1
- package/seeded-connectors/codex/dist/personal.d.ts.map +1 -1
- package/seeded-connectors/codex/dist/personal.js +7 -7
- package/seeded-connectors/codex/package.json +2 -2
- package/seeded-connectors/hermes/dist/index.js +1 -1
- package/seeded-connectors/hermes/dist/launch.js +15 -15
- package/seeded-connectors/hermes/package.json +1 -1
- package/seeded-connectors/hermes/plugin/cotal/_sidecar/standalone.cjs +6 -6
- package/seeded-connectors/jcode/dist/host.js +26 -26
- package/seeded-connectors/jcode/dist/index.js +1 -1
- package/seeded-connectors/jcode/dist/mcp.js +2 -2
- package/seeded-connectors/jcode/package.json +1 -1
- package/seeded-connectors/opencode/dist/index.js +1 -1
- package/seeded-connectors/opencode/dist/plugin/index.js +6 -6
- package/seeded-connectors/opencode/package.json +1 -1
- package/seeded-connectors/pi/dist/extension.d.ts.map +1 -1
- package/seeded-connectors/pi/dist/index.js +5 -5
- package/seeded-connectors/pi/dist/standalone.js +15 -15
- package/seeded-connectors/pi/package.json +1 -1
- package/seeded-connectors/web/package.json +1 -1
package/dist/daemon/account.js
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { measureComputerVitals } from "@cotal-ai/manager";
|
|
2
1
|
import { defaultComputerName, readComputerName, saveComputerName } from "./computer-name.js";
|
|
3
2
|
import { findMesh } from "@cotal-ai/workspace";
|
|
4
3
|
import { loadIdpSession, requestAccountMachine, signedInMachineAccounts, withIdpSessionDir } from "@cotal-ai/auth";
|
|
@@ -10,7 +9,7 @@ export function createAccountComputer(home, version, reconciler) {
|
|
|
10
9
|
let vitals;
|
|
11
10
|
let vitalsError;
|
|
12
11
|
let sampling;
|
|
13
|
-
const sample = () => sampling ??= measureComputerVitals().then(value => { vitals = value; vitalsError = undefined; }).catch(() => { vitalsError = "Computer vitals could not be measured; no new sample was sent."; }).finally(() => { sampling = undefined; });
|
|
12
|
+
const sample = () => sampling ??= import("@cotal-ai/manager").then(({ measureComputerVitals }) => measureComputerVitals()).then(value => { vitals = value; vitalsError = undefined; }).catch(() => { vitalsError = "Computer vitals could not be measured; no new sample was sent."; }).finally(() => { sampling = undefined; });
|
|
14
13
|
let name;
|
|
15
14
|
let nameWarning;
|
|
16
15
|
try {
|
package/dist/daemon/command.js
CHANGED
|
@@ -25,8 +25,9 @@ import { readFileSync, realpathSync } from "node:fs";
|
|
|
25
25
|
import { dirname, isAbsolute, join } from "node:path";
|
|
26
26
|
import { fileURLToPath } from "node:url";
|
|
27
27
|
import { registry } from "@cotal-ai/core";
|
|
28
|
-
import { CommandFailure, codeSpan, homeCotalDir, readUpdateRecovery, jsonFlag, plainFlag, presentationOf, recordOperationContext, renderReport, writeResult } from "@cotal-ai/workspace";
|
|
29
|
-
import {
|
|
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";
|
|
30
31
|
import { EndpointRefusal, defaultPeerUid, defaultPeerPid, checkDir, daemonPaths, daemonPathsFor } from "./endpoint.js";
|
|
31
32
|
import { serveDaemon } from "./server.js";
|
|
32
33
|
import { loginFromCli } from "./cli-login.js";
|
|
@@ -43,6 +44,8 @@ import { nativeDaemonLog } from "./native-log.js";
|
|
|
43
44
|
export const daemonFlags = [
|
|
44
45
|
jsonFlag,
|
|
45
46
|
plainFlag,
|
|
47
|
+
{ name: "cloud", type: "boolean", description: "sign in to Cotal Cloud" },
|
|
48
|
+
{ name: "no-browser", type: "boolean", description: "print approval instructions without opening a browser" },
|
|
46
49
|
{ name: "idp", type: "string", value: "<auth base URL>", description: "the provider's auth base URL, e.g. <origin>/api/auth" },
|
|
47
50
|
{ name: "client-id", type: "string", value: "<id>", description: "the OAuth device-flow client id" },
|
|
48
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." },
|
|
@@ -176,11 +179,20 @@ async function status(args) {
|
|
|
176
179
|
async function login(args) {
|
|
177
180
|
const presentation = presentationOf(args.values);
|
|
178
181
|
const values = args.values;
|
|
179
|
-
if (
|
|
180
|
-
|
|
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
|
+
if (chosen === undefined)
|
|
192
|
+
return;
|
|
181
193
|
let idp;
|
|
182
194
|
try {
|
|
183
|
-
idp = normalizeIdpUrl(
|
|
195
|
+
idp = normalizeIdpUrl(chosen);
|
|
184
196
|
}
|
|
185
197
|
catch {
|
|
186
198
|
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");
|
|
@@ -199,6 +211,7 @@ async function login(args) {
|
|
|
199
211
|
{ kind: "fields", rows: [["Provider", idp], ["Open", p.verificationUriComplete], ["Or open", p.verificationUri], ["Approval code", p.userCode], ["Expires", p.expiresAt]] },
|
|
200
212
|
{ kind: "lines", lines: [{ text: "Waiting for the provider's approval. The daemon keeps the session. Ctrl-C cancels this sign-in on this machine. Do not share the approval link or code.", tone: "hint" }] },
|
|
201
213
|
] }] }, presentation === "plain" ? "plain" : "rich", process.stderr)}\n`);
|
|
214
|
+
openLoginBrowser(p.verificationUriComplete, args.values);
|
|
202
215
|
},
|
|
203
216
|
});
|
|
204
217
|
}
|
|
@@ -224,7 +237,9 @@ async function login(args) {
|
|
|
224
237
|
throw new CommandFailure("refused", "PERMISSION_DENIED", `${r.message}; no session was saved`, native);
|
|
225
238
|
throw new CommandFailure("failed", "OPERATION_FAILED", `${r.message}; a session may have been saved before the failure, so sign in again`, native);
|
|
226
239
|
}
|
|
227
|
-
|
|
240
|
+
// The switch is done; a credential file it could not delete leaves the run partial.
|
|
241
|
+
const partial = r.credentialsKept?.length ? keptCatalogCredentials(r.credentialsKept) : undefined;
|
|
242
|
+
writeResult(presentation, { command: "daemon login", target: { idp }, result: { attempt: reply.attempt, ...r }, ...(partial ? { partial } : {}) }, () => ({ sections: [
|
|
228
243
|
{ title: "Signed in", blocks: [{ kind: "fields", rows: [["Account", r.label || r.sub], ["Subject", r.sub], ["Provider", r.idp]] }, { kind: "lines", lines: [...(r.previousSub ? [`Replaced account: ${r.previousSub}`] : []), { text: "The daemon holds this session in the machine's Cotal home. No session token is printed. Each space's grants decide access separately.", tone: "hint" }] }] },
|
|
229
244
|
] }));
|
|
230
245
|
}
|
|
@@ -409,10 +424,14 @@ async function setupUnderClosure(args) {
|
|
|
409
424
|
throw new CommandFailure("refused", "USAGE_INVALID", "--no-manager and --wait require --space <s>");
|
|
410
425
|
if (space && !SPACE_PATTERN.test(space))
|
|
411
426
|
throw new CommandFailure("refused", "USAGE_INVALID", "space must be 1-64 characters of [A-Za-z0-9_-]", { native: { code: "BAD_FIELD" } });
|
|
427
|
+
if (args.values.cloud && values.idp !== undefined)
|
|
428
|
+
throw new CommandFailure("refused", "USAGE_INVALID", "--cloud and --idp cannot be combined");
|
|
412
429
|
let idp;
|
|
430
|
+
if (args.values.cloud === true)
|
|
431
|
+
idp = await chooseAccount(args, "login");
|
|
413
432
|
if (values.idp !== undefined) {
|
|
414
433
|
try {
|
|
415
|
-
idp = normalizeIdpUrl(values.idp);
|
|
434
|
+
idp = normalizeIdpUrl(cloudAuthUrl(values.idp));
|
|
416
435
|
}
|
|
417
436
|
catch {
|
|
418
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");
|
|
@@ -426,6 +445,22 @@ async function setupUnderClosure(args) {
|
|
|
426
445
|
if (values.wait !== undefined && values["no-manager"] !== true)
|
|
427
446
|
throw new CommandFailure("refused", "USAGE_INVALID", "--wait requires --no-manager; Manager setup never waits for machine approval");
|
|
428
447
|
const { paths, home } = resolveTarget(args);
|
|
448
|
+
let newSignIn = values.idp !== undefined || args.values.cloud === true;
|
|
449
|
+
if (!space && !idp) {
|
|
450
|
+
let installed = true;
|
|
451
|
+
try {
|
|
452
|
+
planUninstall(paths, home);
|
|
453
|
+
}
|
|
454
|
+
catch {
|
|
455
|
+
installed = false;
|
|
456
|
+
}
|
|
457
|
+
if (!installed) {
|
|
458
|
+
idp = await chooseAccount(args, "login");
|
|
459
|
+
if (idp === undefined)
|
|
460
|
+
return;
|
|
461
|
+
newSignIn = true;
|
|
462
|
+
}
|
|
463
|
+
}
|
|
429
464
|
const plain = presentation === "plain";
|
|
430
465
|
// Progress goes to stderr so a --json caller still reads one document on stdout.
|
|
431
466
|
const report = (line) => { process.stderr.write(`${line}\n`); };
|
|
@@ -453,9 +488,9 @@ async function setupUnderClosure(args) {
|
|
|
453
488
|
throw new CommandFailure("refused", "USAGE_INVALID", `The daemon is signed in to several providers (${providers.join(", ")}); pass --idp <url> to choose one`);
|
|
454
489
|
idp = providers[0];
|
|
455
490
|
}
|
|
456
|
-
const r = await runAccountSetup({ paths, daemonHome: home, peerUid, peerPid, report, version: binVersion(), idp: idp, existingSignInOnly:
|
|
491
|
+
const r = await runAccountSetup({ paths, daemonHome: home, peerUid, peerPid, report, version: binVersion(), idp: idp, existingSignInOnly: !newSignIn,
|
|
457
492
|
...(values["client-id"] !== undefined ? { clientId: values["client-id"] } : {}),
|
|
458
|
-
onPrompt: p => { process.stderr.write(`Approve this machine\nOpen: ${p.verificationUriComplete}\nApproval code: ${p.userCode}\n`); }, });
|
|
493
|
+
onPrompt: p => { process.stderr.write(`Approve this machine\nOpen: ${p.verificationUriComplete}\nApproval code: ${p.userCode}\n`); openLoginBrowser(p.verificationUriComplete, args.values); }, });
|
|
459
494
|
writeResult(presentation, { command: "daemon setup", target: { idp: idp }, result: r }, () => ({ sections: [
|
|
460
495
|
{ title: "Connected to your account", blocks: [{ kind: "fields", rows: [["Account", r.label || "Signed in"], ["Computer", r.computer]] },
|
|
461
496
|
{ kind: "lines", lines: [r.spaces.length ? `Spaces using this computer: ${r.spaces.join(", ")}` : "Turn on the spaces that can use this computer in the dashboard."] }] },
|
|
@@ -473,6 +508,7 @@ async function setupUnderClosure(args) {
|
|
|
473
508
|
{ kind: "fields", rows: [["Provider", idp], ["Open", p.verificationUriComplete], ["Or open", p.verificationUri], ["Approval code", p.userCode], ["Expires", p.expiresAt]] },
|
|
474
509
|
{ kind: "lines", lines: [{ text: "Open that link on any device with a browser. This machine needs none. Do not share the approval link or code.", tone: "hint" }] },
|
|
475
510
|
] }] }, plain ? "plain" : "rich", process.stderr)}\n`);
|
|
511
|
+
openLoginBrowser(p.verificationUriComplete, args.values);
|
|
476
512
|
},
|
|
477
513
|
});
|
|
478
514
|
}
|
|
@@ -675,12 +711,12 @@ const daemonCommand = {
|
|
|
675
711
|
{ name: "spaces", usage: "cotal daemon spaces [--refresh] [--daemon-home <dir>] [--json|--plain]", examples: [{ command: "cotal daemon spaces", note: "list registered spaces" }, { command: "cotal daemon spaces --refresh", note: "refresh catalogs before listing spaces" }], summary: "list registered spaces; optionally refresh catalogs using the daemon-held sign-in", flagNames: ["refresh", "daemon-home", "json", "plain"], outputs: ["json", "plain"], prepareMeshTarget: false },
|
|
676
712
|
{ name: "start", usage: "cotal daemon start [--daemon-home <dir>] [--json|--plain]", examples: [{ command: "cotal daemon start", note: "start the recorded daemon service" }], summary: "start the unchanged, recorded daemon service without restarting a running instance", flagNames: ["daemon-home", "json", "plain"], outputs: ["json", "plain"], prepareMeshTarget: false },
|
|
677
713
|
{ name: "desktop", usage: "cotal daemon desktop [--daemon-home <dir>]", examples: [{ command: "cotal daemon desktop < request.json", note: "serve one desktop request from a file" }], summary: "serve one bounded JSON request from the desktop app on stdin; credentials remain in the daemon", flagNames: ["daemon-home"], prepareMeshTarget: false },
|
|
678
|
-
{ name: "setup", usage: "cotal daemon setup [--idp <url>] [--space <s>] [--client-id <id>] [--no-manager [--wait <seconds>]] [--daemon-home <dir>] [--json|--plain]", summary: "connect this computer to an account, or rerun using its sole signed-in provider; with --space, host its Manager (--no-manager and --wait require --space)", examples: [{ command: "cotal daemon setup", note: "refresh apps using the sole signed-in provider" }, { command: "cotal daemon setup --idp <url>", note: "connect your account, then enable spaces in the dashboard" }, { command: "cotal daemon setup --space <space> --no-manager --wait 0", note: "report machine-service approval without hosting a Manager" }], flagNames: ["space", "idp", "client-id", "wait", "no-manager", "daemon-home", "json", "plain"], outputs: ["json", "plain"], prepareMeshTarget: false },
|
|
714
|
+
{ name: "setup", usage: "cotal daemon setup [--cloud | --idp <url>] [--no-browser] [--space <s>] [--client-id <id>] [--no-manager [--wait <seconds>]] [--daemon-home <dir>] [--json|--plain]", summary: "connect this computer to an account, or rerun using its sole signed-in provider; with --space, host its Manager (--no-manager and --wait require --space)", examples: [{ command: "cotal daemon setup", note: "refresh apps using the sole signed-in provider" }, { command: "cotal daemon setup --idp <url>", note: "connect your account, then enable spaces in the dashboard" }, { command: "cotal daemon setup --space <space> --no-manager --wait 0", note: "report machine-service approval without hosting a Manager" }], flagNames: ["space", "cloud", "no-browser", "idp", "client-id", "wait", "no-manager", "daemon-home", "json", "plain"], outputs: ["json", "plain"], prepareMeshTarget: false },
|
|
679
715
|
{ name: "status", usage: "cotal daemon status [--space <s>] [--daemon-home <dir>] [--json|--plain]", summary: "ask the running daemon for its status and hosted Managers over the local endpoint", examples: [{ command: "cotal daemon status", note: "ask the running daemon for its status" }, { command: "cotal daemon status --json", note: "the same as one JSON document" }], flagNames: ["space", "daemon-home", "json", "plain"], outputs: ["json", "plain"], reads: true, prepareMeshTarget: false },
|
|
680
716
|
{ name: "serve", usage: "cotal daemon serve [--daemon-home <dir>] [--json|--plain]", summary: "run the daemon in the foreground and serve its local endpoint (refusals honor --json)", examples: [{ command: "cotal daemon serve", note: "run the machine daemon in this terminal" }], flagNames: ["daemon-home", "json", "plain"], outputs: ["json", "plain"], prepareMeshTarget: false },
|
|
681
717
|
{ name: "install", usage: "cotal daemon install [--daemon-home <dir>] [--dry-run] [--json|--plain]", summary: "install the daemon as this platform's user service; Linux also enables linger", examples: [{ command: "cotal daemon install", note: "run it as a persistent user service" }, { command: "cotal daemon install --dry-run", note: "show the unit it would write" }], flagNames: ["daemon-home", "dry-run", "json", "plain"], outputs: ["json", "plain"], prepareMeshTarget: false },
|
|
682
718
|
{ name: "uninstall", usage: "cotal daemon uninstall [--daemon-home <dir>] [--yes|--dry-run] [--json|--plain]", summary: "stop the daemon's user service, disable autostart and remove its unit", examples: [{ command: "cotal daemon uninstall", note: "remove its login unit" }], flagNames: ["daemon-home", "yes", "dry-run", "json", "plain"], outputs: ["json", "plain"], prepareMeshTarget: false },
|
|
683
|
-
{ name: "login", usage: "cotal daemon login --idp <auth base URL> [--client-id <id>] [--daemon-home <dir>] [--json|--plain]", summary: "sign the running daemon in to a provider with device approval; the daemon keeps the session", examples: [{ command: "cotal daemon login --idp <url>", note: "sign the daemon in with device approval" }], flagNames: ["idp", "client-id", "daemon-home", "json", "plain"], outputs: ["json", "plain"], prepareMeshTarget: false },
|
|
719
|
+
{ name: "login", usage: "cotal daemon login [--cloud | --idp <auth base URL>] [--no-browser] [--client-id <id>] [--daemon-home <dir>] [--json|--plain]", summary: "sign the running daemon in to a provider with device approval; the daemon keeps the session", examples: [{ command: "cotal daemon login --idp <url>", note: "sign the daemon in with device approval" }], flagNames: ["cloud", "no-browser", "idp", "client-id", "daemon-home", "json", "plain"], outputs: ["json", "plain"], prepareMeshTarget: false },
|
|
684
720
|
{ name: "connect-check", usage: "cotal daemon connect-check --space <s> [--daemon-home <dir>] [--json|--plain]", summary: "ask the running daemon whether it could register with a space as its own service; registers nothing", examples: [{ command: "cotal daemon connect-check --space <space>", note: "check whether it could register" }], flagNames: ["space", "daemon-home", "json", "plain"], outputs: ["json", "plain"], reads: true, prepareMeshTarget: false },
|
|
685
721
|
{ name: "register", usage: "cotal daemon register --space <s> [--daemon-home <dir>] [--json|--plain]", summary: "ask the running daemon to request its own service registration with a space; the space owner must approve it, and it does not connect", examples: [{ command: "cotal daemon register --space <space>", note: "ask a space to approve it as a service" }], flagNames: ["space", "daemon-home", "json", "plain"], outputs: ["json", "plain"], prepareMeshTarget: false },
|
|
686
722
|
{ name: "service-connect", usage: "cotal daemon service-connect --space <s> [--daemon-home <dir>] [--json|--plain]", summary: "connect the running daemon to a space as its own approved service; succeeds only when the broker accepts the connection and the space accepts it as ready", examples: [{ command: "cotal daemon service-connect --space <space>", note: "connect it to a space" }], flagNames: ["space", "daemon-home", "json", "plain"], outputs: ["json", "plain"], prepareMeshTarget: false },
|
package/dist/daemon/login.js
CHANGED
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
import { randomBytes } from "node:crypto";
|
|
19
19
|
import { resolve } from "node:path";
|
|
20
20
|
import { deleteIdpSpaceCatalog, establishIdpSession, IdpDeviceAuthorizationRefusedError, IdpLoginCancelled, IdpUnreachableError } from "@cotal-ai/auth";
|
|
21
|
-
import { homeCotalDir, isCommandFailure,
|
|
21
|
+
import { homeCotalDir, isCommandFailure, removeCatalogAccount } from "@cotal-ai/workspace";
|
|
22
22
|
/** The client id stock `cotal login` presents by default. */
|
|
23
23
|
export const DEFAULT_CLIENT_ID = "cotal-cli";
|
|
24
24
|
/** How many finished attempt ids are remembered, so a late cancel still gets a truthful answer. */
|
|
@@ -55,13 +55,14 @@ export function createLoginCoordinator(opts) {
|
|
|
55
55
|
expiresAt: new Date(Date.now() + p.expiresInSec * 1000).toISOString(),
|
|
56
56
|
}),
|
|
57
57
|
});
|
|
58
|
+
let credentialsKept = [];
|
|
58
59
|
if (r.previousSub) {
|
|
59
60
|
const owner = deleteIdpSpaceCatalog(opts.sessionDir, req.idp, r.previousSub);
|
|
60
61
|
// A separate daemon owns its catalog cache, not the shared registry or its credentials.
|
|
61
62
|
if (resolve(opts.sessionDir) === resolve(homeCotalDir()))
|
|
62
|
-
|
|
63
|
+
({ credentialsKept } = removeCatalogAccount(owner));
|
|
63
64
|
}
|
|
64
|
-
return { outcome: "signed-in", idp: req.idp, sub: r.sub, ...(r.label ? { label: r.label } : {}), ...(r.previousSub ? { previousSub: r.previousSub } : {}) };
|
|
65
|
+
return { outcome: "signed-in", idp: req.idp, sub: r.sub, ...(r.label ? { label: r.label } : {}), ...(r.previousSub ? { previousSub: r.previousSub } : {}), ...(credentialsKept.length ? { credentialsKept } : {}) };
|
|
65
66
|
}
|
|
66
67
|
catch (e) {
|
|
67
68
|
if (e instanceof IdpLoginCancelled)
|
package/dist/daemon/manager.js
CHANGED
|
@@ -4,7 +4,6 @@ import { spawn } from "node:child_process";
|
|
|
4
4
|
import { appendFileSync, chmodSync, existsSync, lstatSync, readFileSync, readdirSync, renameSync, rmSync, statSync } from "node:fs";
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
import { assertLifecycleToken, mkSecretDir, parseRemoteEndpointDeregisterResult, registry, writeSecretFileAtomic } from "@cotal-ai/core";
|
|
7
|
-
import { remoteManagerClient } from "@cotal-ai/manager";
|
|
8
7
|
import { daemonArgv } from "@cotal-ai/cli/self-exec";
|
|
9
8
|
import { writeDefaultPersonaForLaunch } from "@cotal-ai/cli/default-persona";
|
|
10
9
|
import { loadIdpSession, retainManagerAuthorityRoute, withIdpSessionDir } from "@cotal-ai/auth";
|
|
@@ -830,6 +829,7 @@ export function createHostedManagers(home = homeCotalDir(), version = installedG
|
|
|
830
829
|
if (held.view.registrationCleanup === "unknown")
|
|
831
830
|
incomplete("Manager registration removal is unconfirmed; no automatic request was repeated");
|
|
832
831
|
try {
|
|
832
|
+
const { remoteManagerClient } = await import("@cotal-ai/manager");
|
|
833
833
|
instanceId = remoteManagerClient.loadRemoteManagerInstanceId(daemonManagerRoot(space, home), space) ?? instanceId;
|
|
834
834
|
}
|
|
835
835
|
catch {
|
package/dist/daemon/setup.js
CHANGED
|
@@ -14,7 +14,7 @@ import { ensureHostedManager, hostingPrerequisite } from "./hosting.js";
|
|
|
14
14
|
* It composes the existing commands and adds no new authority. Pausing, renaming and disconnecting
|
|
15
15
|
* stay separate commands; this one does not absorb them.
|
|
16
16
|
*/
|
|
17
|
-
import { codeSpan, CommandFailure, resolveOnPath } from "@cotal-ai/workspace";
|
|
17
|
+
import { codeSpan, CommandFailure, keptCatalogCredentials, resolveOnPath } from "@cotal-ai/workspace";
|
|
18
18
|
import { normalizeIdpUrl } from "@cotal-ai/auth";
|
|
19
19
|
import { EndpointRefusal } from "./endpoint.js";
|
|
20
20
|
import { loginFromCli } from "./cli-login.js";
|
|
@@ -183,6 +183,14 @@ async function refreshApplications(opts, steps) {
|
|
|
183
183
|
await waitForDaemon(opts, 60);
|
|
184
184
|
return true;
|
|
185
185
|
}
|
|
186
|
+
/** A sign-in that replaced an account but could not delete some of that account's discovered-space
|
|
187
|
+
* credential files stops setup as partial. The session is already switched, so a rerun continues. */
|
|
188
|
+
function credentialsRemoved(r) {
|
|
189
|
+
if (r.outcome !== "signed-in" || !r.credentialsKept?.length)
|
|
190
|
+
return;
|
|
191
|
+
const { message, remedy } = keptCatalogCredentials(r.credentialsKept);
|
|
192
|
+
throw new CommandFailure("partial", "OPERATION_PARTIAL", message, { remedy: `${remedy}, then run this setup again` });
|
|
193
|
+
}
|
|
186
194
|
/** Connect this computer to an account without changing any space intent. */
|
|
187
195
|
export async function runAccountSetup(opts) {
|
|
188
196
|
const steps = [];
|
|
@@ -203,6 +211,7 @@ export async function runAccountSetup(opts) {
|
|
|
203
211
|
throw new CommandFailure("refused", "AUTH_REQUIRED", signed.message, { native: { code: signed.code } });
|
|
204
212
|
if (signed.result.outcome === "failed")
|
|
205
213
|
throw new CommandFailure("refused", "AUTH_REQUIRED", signed.result.message);
|
|
214
|
+
credentialsRemoved(signed.result);
|
|
206
215
|
steps.push({ step: "sign-in", outcome: "signed-in", detail: `signed in as ${signed.result.label || signed.result.sub}` });
|
|
207
216
|
}
|
|
208
217
|
else
|
|
@@ -289,6 +298,7 @@ async function ensureSignedIn(opts, steps) {
|
|
|
289
298
|
throw new CommandFailure("refused", "PERMISSION_DENIED", `${r.message}; no session was saved and nothing was registered`, native);
|
|
290
299
|
throw new CommandFailure("failed", "OPERATION_FAILED", `${r.message}; a session may have been saved before the failure, so run this again`, native);
|
|
291
300
|
}
|
|
301
|
+
credentialsRemoved(r);
|
|
292
302
|
steps.push({ step: "sign-in", outcome: "signed-in", detail: `signed in as ${r.label || r.sub}` });
|
|
293
303
|
opts.report(`sign-in: signed in as ${r.label || r.sub}`, steps.at(-1));
|
|
294
304
|
}
|
|
@@ -376,6 +386,7 @@ export async function runSetup(opts) {
|
|
|
376
386
|
throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", failed.message, { native: { code: failed.reason.toUpperCase() }, remedy: failed.remedy });
|
|
377
387
|
throw new CommandFailure("refused", failed.reason === "unreachable" || failed.reason === "authorization-refused" ? "DEPENDENCY_UNAVAILABLE" : "PERMISSION_DENIED", failed.message, { native: { code: failed.reason.toUpperCase().replaceAll("-", "_") }, remedy: `run ${codeSpan(daemonCommandCopy("login", opts.daemonHome, [["--idp", opts.idp]]))}` });
|
|
378
388
|
}
|
|
389
|
+
credentialsRemoved(signed.result);
|
|
379
390
|
steps.push({ step: "sign-in", outcome: "signed-in", detail: `signed in as ${signed.result.label || signed.result.sub}` });
|
|
380
391
|
opts.report(`sign-in: signed in as ${signed.result.label || signed.result.sub}`, steps.at(-1));
|
|
381
392
|
discoveredSignIn = true;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cotal-ai",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.163.0",
|
|
4
4
|
"description": "Cotal — lateral agent coordination over NATS. Run `npx cotal-ai` for the CLI.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"keywords": [
|
|
@@ -33,28 +33,28 @@
|
|
|
33
33
|
"node": ">=22.10"
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
|
-
"@cotal-ai/auth": "0.
|
|
37
|
-
"@cotal-ai/cli": "0.
|
|
38
|
-
"@cotal-ai/connector-core": "0.
|
|
39
|
-
"@cotal-ai/core": "0.
|
|
40
|
-
"@cotal-ai/delivery": "0.
|
|
41
|
-
"@cotal-ai/manager": "0.
|
|
42
|
-
"@cotal-ai/registry": "0.
|
|
43
|
-
"@cotal-ai/runtime": "0.
|
|
44
|
-
"@cotal-ai/seat": "0.
|
|
45
|
-
"@cotal-ai/workspace": "0.
|
|
36
|
+
"@cotal-ai/auth": "0.163.0",
|
|
37
|
+
"@cotal-ai/cli": "0.163.0",
|
|
38
|
+
"@cotal-ai/connector-core": "0.163.0",
|
|
39
|
+
"@cotal-ai/core": "0.163.0",
|
|
40
|
+
"@cotal-ai/delivery": "0.163.0",
|
|
41
|
+
"@cotal-ai/manager": "0.163.0",
|
|
42
|
+
"@cotal-ai/registry": "0.163.0",
|
|
43
|
+
"@cotal-ai/runtime": "0.163.0",
|
|
44
|
+
"@cotal-ai/seat": "0.163.0",
|
|
45
|
+
"@cotal-ai/workspace": "0.163.0",
|
|
46
46
|
"jose": "^6.2.3"
|
|
47
47
|
},
|
|
48
48
|
"devDependencies": {
|
|
49
|
-
"@cotal-ai/connector-claude-code": "0.
|
|
50
|
-
"@cotal-ai/connector-codex": "0.
|
|
51
|
-
"@cotal-ai/connector-hermes": "0.
|
|
52
|
-
"@cotal-ai/connector-jcode": "0.
|
|
53
|
-
"@cotal-ai/connector-opencode": "0.
|
|
54
|
-
"@cotal-ai/linear": "0.
|
|
55
|
-
"@cotal-ai/pi": "0.
|
|
49
|
+
"@cotal-ai/connector-claude-code": "0.163.0",
|
|
50
|
+
"@cotal-ai/connector-codex": "0.163.0",
|
|
51
|
+
"@cotal-ai/connector-hermes": "0.163.0",
|
|
52
|
+
"@cotal-ai/connector-jcode": "0.163.0",
|
|
53
|
+
"@cotal-ai/connector-opencode": "0.163.0",
|
|
54
|
+
"@cotal-ai/linear": "0.163.0",
|
|
55
|
+
"@cotal-ai/pi": "0.163.0",
|
|
56
56
|
"@cotal-ai/smoke-kit": "0.0.0",
|
|
57
|
-
"@cotal-ai/web": "0.
|
|
57
|
+
"@cotal-ai/web": "0.163.0",
|
|
58
58
|
"@nats-io/jetstream": "^3.4.0",
|
|
59
59
|
"@nats-io/transport-node": "^3.4.0",
|
|
60
60
|
"typescript": "^5.9.3"
|
|
Binary file
|
|
Binary file
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"v": 1,
|
|
3
3
|
"files": {
|
|
4
|
-
"docs-bundle.bin": "
|
|
5
|
-
"docs-index.bin": "
|
|
4
|
+
"docs-bundle.bin": "5e1e5ce542cc1e9df966a26e3a4ea77ff0187763cef4c3244714f434bbf91853",
|
|
5
|
+
"docs-index.bin": "8a4915b2760d979f691a55f0ab692729f1a454441a3ad47dacc5afb279d063db"
|
|
6
6
|
},
|
|
7
7
|
"placements": {
|
|
8
8
|
"claude": [
|
|
@@ -9,7 +9,7 @@ declare const WATCH: {
|
|
|
9
9
|
* conversation already holds; an approved request is finished with `cotal_connect` and that id. */
|
|
10
10
|
export interface ApprovalNotice {
|
|
11
11
|
name: string;
|
|
12
|
-
status: "approved" | "denied" | "expired";
|
|
12
|
+
status: "approved" | "denied" | "expired" | "refused";
|
|
13
13
|
id: string;
|
|
14
14
|
}
|
|
15
15
|
export interface AppHostOptions {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"app-host.d.ts","sourceRoot":"","sources":["../src/app-host.ts"],"names":[],"mappings":"AAKA,OAAO,EAAyF,KAAK,iBAAiB,EAAE,KAAK,WAAW,EAAkB,KAAK,4BAA4B,EAAE,MAAM,0BAA0B,CAAC;AAQ9N;mGACmG;AACnG,QAAA,MAAM,KAAK;;;CAAsC,CAAC;AAElD;oGACoG;AACpG,MAAM,WAAW,cAAc;IAAG,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,UAAU,GAAG,QAAQ,GAAG,SAAS,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE;
|
|
1
|
+
{"version":3,"file":"app-host.d.ts","sourceRoot":"","sources":["../src/app-host.ts"],"names":[],"mappings":"AAKA,OAAO,EAAyF,KAAK,iBAAiB,EAAE,KAAK,WAAW,EAAkB,KAAK,4BAA4B,EAAE,MAAM,0BAA0B,CAAC;AAQ9N;mGACmG;AACnG,QAAA,MAAM,KAAK;;;CAAsC,CAAC;AAElD;oGACoG;AACpG,MAAM,WAAW,cAAc;IAAG,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,UAAU,GAAG,QAAQ,GAAG,SAAS,GAAG,SAAS,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE;AAEnH,MAAM,WAAW,cAAc;IAC7B,KAAK,EAAE,MAAM,SAAS,MAAM,EAAE,CAAC;IAC/B,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC,UAAU,CAAC;IACvB,0FAA0F;IAC1F,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,cAAc,KAAK,OAAO,CAAC;IAC9D,+EAA+E;IAC/E,WAAW,CAAC,EAAE,CAAC,UAAU,EAAE,iBAAiB,KAAK,OAAO,CAAC,4BAA4B,CAAC,CAAC;IACvF,oFAAoF;IACpF,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;IACxE,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACtB;AAED,MAAM,WAAW,OAAQ,SAAQ,WAAW;IAC1C,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1B,WAAW,CAAC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3D,UAAU,CAAC,EAAE,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;CAC5C;AAyDD,wBAAgB,aAAa,CAAC,CAAC,EAAE,cAAc,GAAG,OAAO,CAkQxD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"approval-notice.d.ts","sourceRoot":"","sources":["../src/approval-notice.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAEpD,eAAO,MAAM,WAAW,QAAmB,CAAC;AAG5C,mGAAmG;AACnG,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,cAAc,GAAG,SAAS,CAQxE;AAED,6FAA6F;AAC7F,wBAAgB,aAAa,CAAC,CAAC,EAAE,cAAc,GAAG,MAAM,
|
|
1
|
+
{"version":3,"file":"approval-notice.d.ts","sourceRoot":"","sources":["../src/approval-notice.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,eAAe,CAAC;AAEpD,eAAO,MAAM,WAAW,QAAmB,CAAC;AAG5C,mGAAmG;AACnG,wBAAgB,aAAa,CAAC,KAAK,EAAE,OAAO,GAAG,cAAc,GAAG,SAAS,CAQxE;AAED,6FAA6F;AAC7F,wBAAgB,aAAa,CAAC,CAAC,EAAE,cAAc,GAAG,MAAM,CAYvD"}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var import_node_net=require("node:net");var import_node_fs2=require("node:fs");var import_node_fs=require("node:fs");var import_node_child_process=require("node:child_process");var import_node_path=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_path.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_fs.closeSync)(openPrivate(path,import_node_fs.constants.O_RDONLY));else(0,import_node_fs.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"),[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_fs.openSync)(path,flags,384);try{(0,import_node_fs.fchmodSync)(fd2,384)}catch(e){(0,import_node_fs.closeSync)(fd2);throw e}return fd2}let fd;try{fd=(0,import_node_fs.openSync)(path,flags|import_node_fs.constants.O_NOFOLLOW|import_node_fs.constants.O_NONBLOCK,384)}catch(e){if(e.code==="ELOOP")throw notPrivate(path,"is a symlink");throw e}try{const info=(0,import_node_fs.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_fs.fchmodSync)(fd,384);return fd}catch(e){(0,import_node_fs.closeSync)(fd);throw e}}function writeSecretFile(path,data){writePrivate(path,data,false)}function writeBytes(path,data,exclusive){const fd=openPrivate(path,import_node_fs.constants.O_WRONLY|import_node_fs.constants.O_CREAT|(exclusive?import_node_fs.constants.O_EXCL:0));try{try{(0,import_node_fs.ftruncateSync)(fd);(0,import_node_fs.writeFileSync)(fd,data)}finally{(0,import_node_fs.closeSync)(fd)}}catch(e){if(exclusive){try{(0,import_node_fs.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_fs.unlinkSync)(path)}catch{}throw e}}function writeSecretFileAtomic(path,data){const tmp=`${path}.${process.pid}.${Date.now()}.tmp`;try{writeSecretFile(tmp,data);(0,import_node_fs.renameSync)(tmp,path)}catch(e){try{(0,import_node_fs.unlinkSync)(tmp)}catch{}throw e}}function mkSecretDir(path){(0,import_node_fs.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_fs2.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_fs2.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`);material[key]=v};str("servers");str("creds");str("token");str("controlToken");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.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_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){const path=env.COTAL_CONTROL_SOCKET?.trim();const token=readMaterial(env)?.controlToken??env.COTAL_CONTROL_TOKEN?.trim();if(path&&token)return{path,token};if(!path&&!token)return void 0;if(path)throw new Error("COTAL config: COTAL_CONTROL_SOCKET is set but no control token could be resolved - neither the launch material nor COTAL_CONTROL_TOKEN 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 token 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 hasIdentity(env=process.env){return Boolean(env.COTAL_NAME?.trim()||env.COTAL_LINK?.trim()||env.COTAL_AGENT_FILE?.trim())}var HANDOFF_RECEIPT='{"handoff":"ok"}\n';var MAX_FRAME_BYTES=1<<20;var TIMEOUT_MS=2e3;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}
|
|
2
|
-
`)}catch{}}function readStdin(){return new Promise(
|
|
3
|
-
`));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)
|
|
1
|
+
"use strict";var import_node_net=require("node:net");var import_node_fs2=require("node:fs");var import_node_fs=require("node:fs");var import_node_child_process=require("node:child_process");var import_node_path=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_path.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_fs.closeSync)(openPrivate(path,import_node_fs.constants.O_RDONLY));else(0,import_node_fs.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_path.toNamespacedPath)((0,import_node_path.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_fs.openSync)(path,flags,384);try{(0,import_node_fs.fchmodSync)(fd2,384)}catch(e){(0,import_node_fs.closeSync)(fd2);throw e}return fd2}let fd;try{fd=(0,import_node_fs.openSync)(path,flags|import_node_fs.constants.O_NOFOLLOW|import_node_fs.constants.O_NONBLOCK,384)}catch(e){if(e.code==="ELOOP")throw notPrivate(path,"is a symlink");throw e}try{const info=(0,import_node_fs.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_fs.fchmodSync)(fd,384);return fd}catch(e){(0,import_node_fs.closeSync)(fd);throw e}}function writeSecretFile(path,data){writePrivate(path,data,false)}function writeBytes(path,data,exclusive){const fd=openPrivate(path,import_node_fs.constants.O_WRONLY|import_node_fs.constants.O_CREAT|(exclusive?import_node_fs.constants.O_EXCL:0));try{try{(0,import_node_fs.ftruncateSync)(fd);(0,import_node_fs.writeFileSync)(fd,data)}finally{(0,import_node_fs.closeSync)(fd)}}catch(e){if(exclusive){try{(0,import_node_fs.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_fs.unlinkSync)(path)}catch{}throw e}}function writeSecretFileAtomic(path,data){const tmp=`${path}.${process.pid}.${Date.now()}.tmp`;try{writeSecretFile(tmp,data);(0,import_node_fs.renameSync)(tmp,path)}catch(e){try{(0,import_node_fs.unlinkSync)(tmp)}catch{}throw e}}function mkSecretDir(path){(0,import_node_fs.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_fs2.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_fs2.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`);material[key]=v};str("servers");str("creds");str("token");str("controlToken");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.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_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){const path=env.COTAL_CONTROL_SOCKET?.trim();const token=readMaterial(env)?.controlToken??env.COTAL_CONTROL_TOKEN?.trim();if(path&&token)return{path,token};if(!path&&!token)return void 0;if(path)throw new Error("COTAL config: COTAL_CONTROL_SOCKET is set but no control token could be resolved - neither the launch material nor COTAL_CONTROL_TOKEN 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 token 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 hasIdentity(env=process.env){return Boolean(env.COTAL_NAME?.trim()||env.COTAL_LINK?.trim()||env.COTAL_AGENT_FILE?.trim())}var HANDOFF_RECEIPT='{"handoff":"ok"}\n';var MAX_FRAME_BYTES=1<<20;var TIMEOUT_MS=2e3;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}
|
|
2
|
+
`)}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, 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{path,token}=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,candidate)=>{if(!settle())return;done(out,then=>{try{candidate.write(HANDOFF_RECEIPT,()=>{drop(candidate);then()})}catch{then()}})};const timer=setTimeout(()=>finish(""),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 candidate=(0,import_node_net.connect)(path);sock=candidate;let connected=false;let reply="";candidate.setEncoding("utf8");candidate.on("connect",()=>{if(settled||sock!==candidate)return;connected=true;try{candidate.write(JSON.stringify({token,event,handoff:true})+"\n")}catch{finish("")}});candidate.on("data",d=>{if(settled||sock!==candidate)return;reply+=d;const nl=reply.indexOf("\n");if(nl>=0)finishWithReceipt(reply.slice(0,nl),candidate)});candidate.on("error",error=>{if(settled||sock!==candidate)return;if(!connected&&startupCritical&&isRetryableConnectError(error)){drop(candidate);retryLater();return}finish("")});candidate.on("end",()=>{if(settled||sock!==candidate)return;finish(reply)})};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_fs3=require("node:fs");var import_node_path2=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_path2.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_fs3.readFileSync)((0,import_node_path2.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_fs3.mkdirSync)(dir,{recursive:true,mode:448});(0,import_node_fs3.writeFileSync)((0,import_node_path2.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_fs3.rmSync)((0,import_node_path2.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_fs5=require("node:fs");var import_node_net2=require("node:net");var import_node_os2=require("node:os");var import_node_path4=require("node:path");var import_node_fs4=require("node:fs");var import_node_os=require("node:os");var import_node_path3=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_path3.join)((0,import_node_os.tmpdir)(),`cotal-claude-wake-${uid}`);(0,import_node_fs4.mkdirSync)(dir,{recursive:true,mode:448});const st=(0,import_node_fs4.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_path3.join)(dir,entryName(claudePid,serverPid))}function wakeSockets(claudePid){const dir=wakeDir();return(0,import_node_fs4.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_path4.join)((0,import_node_os2.tmpdir)(),`cotal-claude-native-${process.getuid?.()??"local"}`);const st=(0,import_node_fs5.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_path4.join)(root,`${session}.json`)}function readRecord(file){const st=(0,import_node_fs5.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_fs5.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_path4.isAbsolute)(path)&&(0,import_node_path4.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})}
|
|
3
|
+
`));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_fs5.unlinkSync)(file);if(target)(0,import_node_fs5.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));
|