Something went wrong. Try again.
[READ-ONLY] Mirror of https://github.com/Aquaticat/Monochromatic. TypeScript and Rust monorepo: Claude Code and Pi coding-agent plugins, a m
Something went wrong. Try again.
123456789#!/usr/bin/env nodeimport{access,chmod,mkdir,readFile,readdir,rename,symlink,unlink,writeFile}from"node:fs/promises";import{join,resolve}from"node:path";import{constants}from"node:fs";import{text}from"node:stream/consumers";function spawnResultsDir(env=process.env){return join(env.HOME??`/tmp`,`.claude`,`spawn-results`)}function byPidDir(env=process.env){return join(spawnResultsDir(env),`.by-pid`)}function spawnsDir(env=process.env){return join(spawnResultsDir(env),`spawns`)}spawnResultsDir();const BY_PID_DIR=byPidDir(),SPAWNS_DIR=spawnsDir(),NO_WARNING=Symbol(`claude-spawn/cli-setup-ok`);async function handleSessionStart({sessionId,transcriptPath,hookDir}){await mkdir(BY_PID_DIR,{recursive:!0});let mapping={sessionId,transcriptPath};await writeFile(join(BY_PID_DIR,String(process.ppid)),JSON.stringify(mapping));let spawnId=process.env.CLAUDE_SPAWN_ID;if(spawnId!==void 0){let jsonPath=join(SPAWNS_DIR,`${spawnId}.json`);try{let raw=await readFile(jsonPath,`utf8`),state=JSON.parse(raw);if(state.sessionId===``){let updated={...state,sessionId,transcriptPath};await writeFile(jsonPath,JSON.stringify(updated))}}catch{}}let cliWarning=await autoSetupCli(hookDir);return cliWarning===NO_WARNING?JSON.stringify({}):cliWarning}async function isExecutablePath(path){try{return await access(path,constants.X_OK),!0}catch{return!1}}async function cliIsOnPath(){let pathDirs=(process.env.PATH??``).split(`:`);return(await Promise.all(pathDirs.map(function(dir){return isExecutablePath(join(dir,`spawn-claude`))}))).includes(!0)}async function autoSetupCli(hookDir){if(await cliIsOnPath())return NO_WARNING;let cliSource=join(resolve(hookDir,`..`,`..`),`src`,`cli.ts`),localBin=join(process.env.HOME??`/tmp`,`.local`,`bin`),symlinkPath=join(localBin,`spawn-claude`);try{await mkdir(localBin,{recursive:!0}),await chmod(cliSource,493);try{await unlink(symlinkPath)}catch{}return await symlink(cliSource,symlinkPath),(process.env.PATH??``).split(`:`).includes(localBin)?NO_WARNING:[`[claude-spawn] Symlinked spawn-claude to ~/.local/bin/spawn-claude,`,`but ~/.local/bin is not on PATH. Add it to your shell profile:`,` export PATH="$HOME/.local/bin:$PATH"`].join(``)}catch(error){return[`[claude-spawn] Could not auto-setup spawn-claude CLI.`,`Symlink target: ${cliSource}`,`Symlink path: ${symlinkPath}`,`Setup error: ${String(error)}`,`Create the symlink manually or add the plugin directory to PATH.`].join(``)}}function formatSpawnResult(state){return[`Spawned Claude session completed (spawnId: ${state.spawnId}):`,`Session ID: ${state.sessionId}`,`Transcript: ${state.transcriptPath}`,state.lastMessage.length>0?`Last assistant message:\n${state.lastMessage}`:`No assistant message was produced.`].join(``)}const NOTHING_TO_REPORT=Symbol(`claude-spawn/nothing-to-report`);async function readSpawnsDir(){try{return await readdir(SPAWNS_DIR)}catch{return NOTHING_TO_REPORT}}function hasReport(result){return result!==NOTHING_TO_REPORT}async function readCompletedChild({filename,parentSessionId,consume}){if(!filename.endsWith(`.json`))return NOTHING_TO_REPORT;let filePath=join(SPAWNS_DIR,filename),reportedPath=join(SPAWNS_DIR,`${filename.slice(0,-5)}.reported`);try{let raw=await readFile(filePath,`utf8`),state=JSON.parse(raw);if(state.parentSessionId!==parentSessionId||state.status!==`stopped`)return NOTHING_TO_REPORT;if(consume)try{await rename(filePath,reportedPath)}catch{return NOTHING_TO_REPORT}return formatSpawnResult(state)}catch{return NOTHING_TO_REPORT}}async function checkCompletedChildren({parentSessionId,consume}){let entries=await readSpawnsDir();if(entries===NOTHING_TO_REPORT)return NOTHING_TO_REPORT;let results=(await Promise.all(entries.map(function(filename){return readCompletedChild({filename,parentSessionId,consume})}))).filter(function(result){return hasReport(result)});return results.length===0?NOTHING_TO_REPORT:results.join(`
---
`)}const HOOK_DIR=import.meta.dirname;async function updateChildOnStop({sessionId,lastMessage}){let spawnId=process.env.CLAUDE_SPAWN_ID;if(spawnId===void 0)return;let filePath=join(SPAWNS_DIR,`${spawnId}.json`);try{let existing=await readFile(filePath,`utf8`),state=JSON.parse(existing);if(state.sessionId===sessionId){let updated={...state,lastMessage,status:`stopped`};await writeFile(filePath,JSON.stringify(updated))}}catch{}}async function stopResponse(event){if(!event.stop_hook_active){let context=await checkCompletedChildren({parentSessionId:event.session_id,consume:!0});if(context!==NOTHING_TO_REPORT)return{kind:`json`,payload:{decision:`block`,reason:context}}}return{kind:`json`,payload:{}}}async function additionalContextResponse(event){let context=await checkCompletedChildren({parentSessionId:event.session_id,consume:!0});return context===NOTHING_TO_REPORT?{kind:`json`,payload:{}}:{kind:`json`,payload:{hookSpecificOutput:{hookEventName:event.hook_event_name,additionalContext:context}}}}async function claudeSpawnHandler(event){return event.hook_event_name===`SessionStart`?{kind:`raw`,text:await handleSessionStart({sessionId:event.session_id,transcriptPath:event.transcript_path,hookDir:HOOK_DIR})}:event.hook_event_name===`Stop`?(event.last_assistant_message!==void 0&&await updateChildOnStop({sessionId:event.session_id,lastMessage:event.last_assistant_message}),stopResponse(event)):event.hook_event_name===`SessionEnd`?{kind:`json`,payload:{}}:additionalContextResponse(event)}function claudeSpawnParser(raw){return JSON.parse(raw)}function claudeSpawnWriter(output){return output.kind===`raw`?output.text:JSON.stringify(output.payload)}const NO_STDOUT=Symbol(`claude-code-plugin-runtime/hook-intentionally-emits-no-stdout-bytes`);async function runHookPlugin({parser,handler,writer}){let serialized=writer(await handler(parser(await text(process.stdin))));serialized!==NO_STDOUT&&process.stdout.write(serialized)}await runHookPlugin({parser:claudeSpawnParser,handler:claudeSpawnHandler,writer:claudeSpawnWriter});export{};