@cotal-ai/connector-claude-code 0.171.4 → 0.172.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/README.md CHANGED
@@ -15,7 +15,7 @@ See [docs/connect-claude.mdx](../../docs/connect-claude.mdx) for the integration
15
15
  Claude Code documents every hook event and its matchers in its
16
16
  [hooks reference](https://code.claude.com/docs/en/hooks). This README does not copy that list.
17
17
 
18
- The plugin registers the nine hooks below in [`hooks/hooks.json`](hooks/hooks.json). Each runs
18
+ The plugin registers the eleven hooks below in [`hooks/hooks.json`](hooks/hooks.json). Each runs
19
19
  `dist/hook.cjs`, which relays the event to the session's connector over its authenticated control
20
20
  socket. A Cotal session, one that Cotal launched, carries a mesh identity in its environment. A
21
21
  plain session, such as a `claude` you started yourself, carries none until it connects. Its command
@@ -30,9 +30,11 @@ hosted connection checks in the `PreToolUse` and `PostToolUse` rows. The presenc
30
30
  | `SessionStart` | all | Surfaces the channel briefing and waiting messages, sets `idle` when no turn is open, resets attention to `open`, and records the session's model when none is pinned. On `startup`, `resume` or `fork` it also records the session's directory. |
31
31
  | `UserPromptSubmit` | all | Sets `working` and surfaces waiting messages and run turns. |
32
32
  | `PreToolUse` | all | Records the pending tool so a permission wait can name it. In a Cotal session, it denies a Cotal tool from any server other than the local one. In a plain session, it denies a hosted `connection_id` that it recorded as opened by a different session. |
33
+ | `PermissionRequest` | all | In a Cotal session on a signed-in space, opens the tool permission on the agent endpoint and hands Claude a remote allow or deny, while Claude's own dialog stays open. `AskUserQuestion` and `ExitPlanMode` stay with the dialog. On Windows the hook answers with no decision. See [tool permissions](https://docs.cotal.ai/docs/claude-connector-reference/#tool-permissions). |
33
34
  | `PostToolUse` | `^mcp__.+__cotal_(connect\|disconnect)$` | Plain sessions only: records or forgets which session opened a hosted connection. |
34
- | `PostToolBatch` | all | Sets `working` again when the main agent's batch resolves after a prompt left the seat `waiting`. A subagent's batch changes nothing. |
35
+ | `PostToolBatch` | all | Reports the calls its scope ran to that scope's tool permissions. Sets `working` again when the main agent's batch resolves after a prompt left the seat `waiting`. A subagent's batch leaves the status as it is. |
35
36
  | `Notification` | `permission_prompt\|agent_needs_input\|elicitation_dialog` | Sets `waiting`. `permission_prompt` adds condition `approval`, and `agent_needs_input` adds `input`. |
36
- | `Stop` | all | Ends the turn: closes the run on the event plane, sets `idle`, and asks for a wake turn when held messages are waiting. |
37
+ | `SubagentStop` | all | Ends that subagent's turn for its tool permissions. |
38
+ | `Stop` | all | Ends the turn: ends the main agent's turn for its tool permissions, closes the run on the event plane, sets `idle`, and asks for a wake turn when held messages are waiting. |
37
39
  | `StopFailure` | all | Same as `Stop`, but closes the run with `RUN_ERROR` and sets a condition mapped from the error type. |
38
- | `SessionEnd` | all | Sets `offline`. |
40
+ | `SessionEnd` | all | Closes every tool permission and sets `offline`. |
@@ -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,GAAG,SAAS,CAAC;IAAC,EAAE,EAAE,MAAM,CAAA;CAAE;AAEnH,UAAU,cAAc;IACtB,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,UA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AAC,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,UAAU,OAAQ,SAAQ,WAAW;IACnC,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;AA2ED,wBAAgB,aAAa,CAAC,CAAC,EAAE,cAAc,GAAG,OAAO,CAoQxD"}
@@ -9,6 +9,8 @@ export interface DesktopEntry {
9
9
  /** The Desktop chat server in the config at `path`: the current name, or an older entry of ours still
10
10
  * stored under `cotal`. */
11
11
  export declare function readDesktopEntry(path: string): unknown;
12
+ /** Compare the exact entry writeDesktopEntry would leave, including an owned legacy entry. */
13
+ export declare function desktopEntryCurrent(path: string, entry: DesktopEntry): boolean;
12
14
  /** Whether Desktop's config has a server named `cotal`. That is also the Claude Code plugin's server
13
15
  * name, so a Code session in Desktop runs this one instead of the plugin. */
14
16
  export declare function desktopNameClash(path: string): boolean;
@@ -21,5 +23,5 @@ export declare function desktopRunning(platform?: NodeJS.Platform): boolean;
21
23
  /** Write `entry` as the `cotal-desktop` server in the config at `path`. An older entry of ours named
22
24
  * `cotal` moves with it. Returns what changed, or that nothing was written because Claude Desktop
23
25
  * is running. */
24
- export declare function writeDesktopEntry(path: string, entry: DesktopEntry, running?: () => boolean): "added" | "updated" | "current" | "not added" | "not updated";
26
+ export declare function writeDesktopEntry(path: string, entry: DesktopEntry, running?: () => boolean): "added" | "updated" | "current" | "not added" | "not updated" | "read-only";
25
27
  //# sourceMappingURL=desktop-config.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"desktop-config.d.ts","sourceRoot":"","sources":["../src/desktop-config.ts"],"names":[],"mappings":"AAmBA;iCACiC;AACjC,wBAAgB,iBAAiB,CAAC,QAAQ,GAAE,MAAM,CAAC,QAA2B,EAAE,GAAG,GAAE,MAAM,CAAC,UAAwB,EAAE,IAAI,GAAE,MAAkB,GAAG,MAAM,GAAG,SAAS,CAIlK;AAED,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC9B;AA2BD;4BAC4B;AAC5B,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAGtD;AAED;8EAC8E;AAC9E,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEtD;AAED;;;;yEAIyE;AACzE,wBAAgB,cAAc,CAAC,QAAQ,GAAE,MAAM,CAAC,QAA2B,GAAG,OAAO,CAKpF;AAED;;kBAEkB;AAClB,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,YAAY,EAAE,OAAO,GAAE,MAAM,OAAwB,GAAG,OAAO,GAAG,SAAS,GAAG,SAAS,GAAG,WAAW,GAAG,aAAa,CAc3K"}
1
+ {"version":3,"file":"desktop-config.d.ts","sourceRoot":"","sources":["../src/desktop-config.ts"],"names":[],"mappings":"AAoBA;iCACiC;AACjC,wBAAgB,iBAAiB,CAAC,QAAQ,GAAE,MAAM,CAAC,QAA2B,EAAE,GAAG,GAAE,MAAM,CAAC,UAAwB,EAAE,IAAI,GAAE,MAAkB,GAAG,MAAM,GAAG,SAAS,CAIlK;AAED,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,EAAE,CAAC;IACf,GAAG,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;CAC9B;AA2BD;4BAC4B;AAC5B,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAGtD;AAED,8FAA8F;AAC9F,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,YAAY,GAAG,OAAO,CAG9E;AAED;8EAC8E;AAC9E,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAEtD;AAED;;;;yEAIyE;AACzE,wBAAgB,cAAc,CAAC,QAAQ,GAAE,MAAM,CAAC,QAA2B,GAAG,OAAO,CAKpF;AAED;;kBAEkB;AAClB,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,YAAY,EAAE,OAAO,GAAE,MAAM,OAAwB,GAAG,OAAO,GAAG,SAAS,GAAG,SAAS,GAAG,WAAW,GAAG,aAAa,GAAG,WAAW,CAwBzL"}
Binary file
Binary file
@@ -1 +1 @@
1
- {"version":3,"file":"extension.d.ts","sourceRoot":"","sources":["../src/extension.ts"],"names":[],"mappings":"AAKA,OAAO,EAAwE,KAAK,SAAS,EAA8E,MAAM,gBAAgB,CAAC;AAWlM;;;;;;;;;4FAS4F;AAC5F,eAAO,MAAM,oBAAoB,8/DA4EvB,CAAC;AAkJX;;;;;GAKG;AACH,eAAO,MAAM,eAAe,EAAE,SA8P7B,CAAC"}
1
+ {"version":3,"file":"extension.d.ts","sourceRoot":"","sources":["../src/extension.ts"],"names":[],"mappings":"AAKA,OAAO,EAAwE,KAAK,SAAS,EAA8E,MAAM,gBAAgB,CAAC;AAWlM;;;;;;;;;4FAS4F;AAC5F,eAAO,MAAM,oBAAoB,8/DA4EvB,CAAC;AAkJX;;;;;GAKG;AACH,eAAO,MAAM,eAAe,EAAE,SAiQ7B,CAAC"}
package/dist/hook.cjs CHANGED
@@ -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
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
- `));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));
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,opts={}){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;let held=false;try{held=opts.holds?.(event)===true}catch{}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;if(held)clearTimeout(timer)}})}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
+ `));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 isPermissionRequest=event=>event?.hook_event_name==="PermissionRequest";var windowsPermission=event=>process.platform==="win32"&&isPermissionRequest(event)?{}:void 0;var owner=connectionOwner(process.env.CLAUDE_PLUGIN_DATA);void runHookRelay((event,session)=>windowsPermission(event,session)??otherCotalPath(event,session)??owner(event,session),async(event,session)=>{if(!session.managed)await observePersonalHook(event)},{holds:isPermissionRequest}).catch(()=>process.exit(0));
package/dist/hooks.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type MeshAgent, type InboxItem, type HookEvent, type HookHandle } from "@cotal-ai/connector-core";
1
+ import { type MeshAgent, type InboxItem, type HookEvent } from "@cotal-ai/connector-core";
2
2
  import type { AguiEmitterHolder } from "@cotal-ai/connector-core";
3
3
  import type { ClaudeEntry } from "./agui-map.js";
4
4
  interface ClaudeHandleDeps {
@@ -25,7 +25,8 @@ export interface ClaudeHooks {
25
25
  /** Adopt a native transcript when a personal connection starts mid-session. No synthetic
26
26
  * lifecycle event is needed, and the source decides the pre-connection privacy boundary. */
27
27
  adoptTranscript(path: string, source: unknown): void;
28
- handle: HookHandle;
28
+ /** A control-server handler that never reads the hook's connection. */
29
+ handle: (agent: MeshAgent, ev: HookEvent) => Promise<Record<string, unknown>>;
29
30
  /** Pass as {@link ControlServerOpts.onReply}. */
30
31
  onReply: (ev: HookEvent, delivered: boolean, handoff?: boolean) => void;
31
32
  /** Receipt for an empty inbox after a confirmed hook handoff. Contains no peer content. */
@@ -1 +1 @@
1
- {"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AAiBA,OAAO,EAOL,KAAK,SAAS,EACd,KAAK,SAAS,EACd,KAAK,SAAS,EACd,KAAK,UAAU,EAChB,MAAM,0BAA0B,CAAC;AAClC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAClE,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAiJjD,UAAU,gBAAgB;IACxB,mGAAmG;IACnG,GAAG,CAAC,EAAE,MAAM,CAAC,UAAU,CAAC;IACxB,+FAA+F;IAC/F,MAAM,CAAC,EAAE,MAAM,iBAAiB,CAAC,WAAW,EAAE,OAAO,CAAC,GAAG,SAAS,CAAC;IACnE,iFAAiF;IACjF,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,SAAS,SAAS,EAAE,KAAK,IAAI,CAAC;IACjD,sFAAsF;IACtF,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,qGAAqG;IACrG,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB;;6FAEyF;IACzF,WAAW,CAAC,EAAE,MAAM,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;CACjD;AASD,eAAO,MAAM,kBAAkB,OAAQ,CAAC;AAGxC;;+DAE+D;AAC/D,MAAM,WAAW,WAAW;IAC1B;gGAC4F;IAC5F,eAAe,CAAC,IAAI,EAA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