@automagik/genie 4.260429.13 → 4.260429.14

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/genie.js CHANGED
@@ -139,7 +139,7 @@ Your role adapts based on workspace maturity:
139
139
  SELECT name FROM _genie_migrations ORDER BY name
140
140
  `,appliedSet=new Set(applied.map((r)=>r.name)),pending=files.filter((f)=>!appliedSet.has(f.name)),results=[];for(let migration of pending)await sql.begin(async(tx)=>{await tx.unsafe(migration.sql),await tx.unsafe("INSERT INTO _genie_migrations (name) VALUES ($1)",[migration.name])}),results.push({name:migration.name,applied_at:new Date().toISOString()});return results}async function getMigrationStatus(sql){await ensureMigrationsTable(sql);let files=await loadMigrationFiles(),applied=await sql`
141
141
  SELECT name, applied_at FROM _genie_migrations ORDER BY name
142
- `,appliedMap=new Map(applied.map((r)=>[r.name,r.applied_at.toISOString()])),appliedRecords=[],pendingRecords=[];for(let file of files){let appliedAt=appliedMap.get(file.name);if(appliedAt)appliedRecords.push({name:file.name,applied_at:appliedAt});else pendingRecords.push({name:file.name,applied_at:null})}return{applied:appliedRecords,pending:pendingRecords}}var init_db_migrations=()=>{};import{readFile,unlink,writeFile}from"fs/promises";function lockPath(filePath){return`${filePath}.lock`}function isPidAlive(pid){try{return process.kill(pid,0),!0}catch{return!1}}async function acquireLock(path){let lock=lockPath(path),deadline=Date.now()+LOCK_TIMEOUT_MS;while(Date.now()<deadline)try{await writeFile(lock,String(process.pid),{flag:"wx"});return}catch{try{let content=await readFile(lock,"utf-8"),holderPid=Number.parseInt(content.trim(),10);if(!Number.isNaN(holderPid)&&!isPidAlive(holderPid)){try{await unlink(lock)}catch{}continue}}catch{continue}let jitter=Math.floor(Math.random()*LOCK_POLL_MS);await new Promise((r)=>setTimeout(r,LOCK_POLL_MS+jitter))}console.warn(`[lockfile] Force-acquiring stale lock: ${lock}`),await writeFile(lock,String(process.pid))}async function releaseLock(path){try{await unlink(lockPath(path))}catch{}}var LOCK_TIMEOUT_MS=5000,LOCK_POLL_MS=50;var init_lockfile=()=>{};function isBlockingEvent(event){return BLOCKING_EVENTS.has(event)}var DISPATCHED_EVENT_MATCHERS,DISPATCHED_EVENTS,BLOCKING_EVENTS;var init_types2=__esm(()=>{DISPATCHED_EVENT_MATCHERS={PreToolUse:"*",PostToolUse:"SendMessage"},DISPATCHED_EVENTS=Object.keys(DISPATCHED_EVENT_MATCHERS),BLOCKING_EVENTS=new Set(["PreToolUse","UserPromptSubmit","TeammateIdle","TaskCompleted","PermissionRequest"])});var exports_inject={};__export(exports_inject,{isTeamHooked:()=>isTeamHooked,injectTeamHooks:()=>injectTeamHooks,buildDispatchCommand:()=>buildDispatchCommand});import{existsSync as existsSync6}from"fs";import{mkdir,readFile as readFile2,writeFile as writeFile2}from"fs/promises";import{homedir as homedir5}from"os";import{join as join8}from"path";import{fileURLToPath}from"url";function escapeShellArg(arg){return`'${arg.replace(/'/g,"'\\''")}'`}function compiledBinaryCandidates(){let candidates=[];if(process.env.GENIE_HOOK_BIN)candidates.push(process.env.GENIE_HOOK_BIN);let home=process.env.GENIE_HOME??join8(homedir5(),".genie");candidates.push(join8(home,"bin","genie-hook"));try{let repoBin=fileURLToPath(new URL("../../dist/genie-hook",import.meta.url));candidates.push(repoBin)}catch{}return candidates}function buildDispatchCommand(){for(let candidate of compiledBinaryCandidates())if(existsSync6(candidate))return escapeShellArg(candidate);let entrypoint=fileURLToPath(new URL("../genie.ts",import.meta.url));if(!existsSync6(entrypoint))return"genie hook dispatch";let bun=process.execPath||"bun";return`${escapeShellArg(bun)} run ${escapeShellArg(entrypoint)} hook dispatch`}function isGenieDispatchCommand(command){return typeof command==="string"&&/(?:^|\s)hook\s+dispatch(?:\s|$)/.test(command)}function claudeConfigDir(){return process.env.CLAUDE_CONFIG_DIR??join8(homedir5(),".claude")}function teamSettingsPath(teamName){let sanitized=teamName.replace(/[^a-zA-Z0-9]/g,"-").toLowerCase();return join8(claudeConfigDir(),"teams",sanitized,"settings.json")}function buildHooksConfig(){let hooks={},dispatchCommand=buildDispatchCommand();for(let[event,matcher]of Object.entries(DISPATCHED_EVENT_MATCHERS))hooks[event]=[{matcher,hooks:[{type:"command",command:dispatchCommand,timeout:DISPATCH_TIMEOUT}]}];return hooks}async function readSettings(settingsPath){if(!existsSync6(settingsPath))return{};try{return JSON.parse(await readFile2(settingsPath,"utf-8"))}catch{return{}}}function allEventsAlreadyInjected(existingHooks,hooksConfig){return DISPATCHED_EVENTS.every((event)=>{let existing=existingHooks[event],desiredCommand=hooksConfig[event][0].hooks[0].command,desiredMatcher=hooksConfig[event][0].matcher;return existing?.some((m)=>m.matcher===desiredMatcher&&m.hooks?.some((h)=>h.command===desiredCommand))})}function hasNoObsoleteGenieEntries(existingHooks){return Object.keys(existingHooks).every((event)=>{if(DISPATCHED_EVENTS.includes(event))return!0;return!existingHooks[event]?.some((m)=>m.hooks?.some((h)=>isGenieDispatchCommand(h.command)))})}function pruneObsoleteGenieEntries(mergedHooks){for(let event of Object.keys(mergedHooks)){if(DISPATCHED_EVENTS.includes(event))continue;let cleaned=(mergedHooks[event]??[]).map((matcher)=>({...matcher,hooks:matcher.hooks?.filter((hook)=>!isGenieDispatchCommand(hook.command))})).filter((matcher)=>(matcher.hooks?.length??0)>0);if(cleaned.length===0)delete mergedHooks[event];else mergedHooks[event]=cleaned}}function refreshMatcherEntries(entries,genieEntry){return entries.map((matcher)=>{let hasGenieHook=matcher.hooks?.some((h)=>isGenieDispatchCommand(h.command));return{...matcher,matcher:hasGenieHook?genieEntry.matcher:matcher.matcher,hooks:matcher.hooks?.map((hook)=>isGenieDispatchCommand(hook.command)?{...hook,command:genieEntry.hooks[0].command,timeout:DISPATCH_TIMEOUT}:hook)}})}function upsertGenieEntry(mergedHooks,event,genieEntry){let existingEntries=refreshMatcherEntries(mergedHooks[event]??[],genieEntry),alreadyPresent=existingEntries.some((m)=>m.hooks?.some((h)=>isGenieDispatchCommand(h.command)));mergedHooks[event]=alreadyPresent?existingEntries:[...existingEntries,genieEntry]}async function injectIntoFile(settingsPath){let settings=await readSettings(settingsPath),hooksConfig=buildHooksConfig(),existingHooks=settings.hooks;if(existingHooks&&allEventsAlreadyInjected(existingHooks,hooksConfig)&&hasNoObsoleteGenieEntries(existingHooks))return!1;let mergedHooks=existingHooks?{...existingHooks}:{};pruneObsoleteGenieEntries(mergedHooks);for(let event of DISPATCHED_EVENTS)upsertGenieEntry(mergedHooks,event,hooksConfig[event][0]);settings.hooks=mergedHooks;let dir=join8(settingsPath,"..");return await mkdir(dir,{recursive:!0}),await writeFile2(settingsPath,JSON.stringify(settings,null,2)),!0}async function injectTeamHooks(teamName){let path=teamSettingsPath(teamName);return injectIntoFile(path)}async function isTeamHooked(teamName){let path=teamSettingsPath(teamName);if(!existsSync6(path))return!1;try{let content=await readFile2(path,"utf-8"),hooks=JSON.parse(content).hooks;if(!hooks)return!1;return DISPATCHED_EVENTS.every((event)=>{return hooks[event]?.some((m)=>m.hooks?.some((h)=>isGenieDispatchCommand(h.command)))})}catch{return!1}}var DISPATCH_TIMEOUT=15;var init_inject=__esm(()=>{init_types2()});var exports_js_yaml={};__export(exports_js_yaml,{types:()=>types2,safeLoadAll:()=>safeLoadAll,safeLoad:()=>safeLoad,safeDump:()=>safeDump,loadAll:()=>loadAll,load:()=>load,dump:()=>dump,default:()=>jsYaml,YAMLException:()=>YAMLException,Type:()=>Type,Schema:()=>Schema,JSON_SCHEMA:()=>JSON_SCHEMA,FAILSAFE_SCHEMA:()=>FAILSAFE_SCHEMA,DEFAULT_SCHEMA:()=>DEFAULT_SCHEMA,CORE_SCHEMA:()=>CORE_SCHEMA});function isNothing(subject){return typeof subject>"u"||subject===null}function isObject(subject){return typeof subject==="object"&&subject!==null}function toArray(sequence){if(Array.isArray(sequence))return sequence;else if(isNothing(sequence))return[];return[sequence]}function extend(target,source){var index,length,key,sourceKeys;if(source){sourceKeys=Object.keys(source);for(index=0,length=sourceKeys.length;index<length;index+=1)key=sourceKeys[index],target[key]=source[key]}return target}function repeat(string,count){var result2="",cycle;for(cycle=0;cycle<count;cycle+=1)result2+=string;return result2}function isNegativeZero(number){return number===0&&Number.NEGATIVE_INFINITY===1/number}function formatError(exception,compact){var where="",message=exception.reason||"(unknown reason)";if(!exception.mark)return message;if(exception.mark.name)where+='in "'+exception.mark.name+'" ';if(where+="("+(exception.mark.line+1)+":"+(exception.mark.column+1)+")",!compact&&exception.mark.snippet)where+=`
142
+ `,appliedMap=new Map(applied.map((r)=>[r.name,r.applied_at.toISOString()])),appliedRecords=[],pendingRecords=[];for(let file of files){let appliedAt=appliedMap.get(file.name);if(appliedAt)appliedRecords.push({name:file.name,applied_at:appliedAt});else pendingRecords.push({name:file.name,applied_at:null})}return{applied:appliedRecords,pending:pendingRecords}}var init_db_migrations=()=>{};import{readFile,unlink,writeFile}from"fs/promises";function lockPath(filePath){return`${filePath}.lock`}function isPidAlive(pid){try{return process.kill(pid,0),!0}catch{return!1}}async function acquireLock(path){let lock=lockPath(path),deadline=Date.now()+LOCK_TIMEOUT_MS;while(Date.now()<deadline)try{await writeFile(lock,String(process.pid),{flag:"wx"});return}catch{try{let content=await readFile(lock,"utf-8"),holderPid=Number.parseInt(content.trim(),10);if(!Number.isNaN(holderPid)&&!isPidAlive(holderPid)){try{await unlink(lock)}catch{}continue}}catch{continue}let jitter=Math.floor(Math.random()*LOCK_POLL_MS);await new Promise((r)=>setTimeout(r,LOCK_POLL_MS+jitter))}console.warn(`[lockfile] Force-acquiring stale lock: ${lock}`),await writeFile(lock,String(process.pid))}async function releaseLock(path){try{await unlink(lockPath(path))}catch{}}var LOCK_TIMEOUT_MS=5000,LOCK_POLL_MS=50;var init_lockfile=()=>{};var exports_types={};__export(exports_types,{isBlockingEvent:()=>isBlockingEvent,DISPATCHED_EVENT_MATCHERS:()=>DISPATCHED_EVENT_MATCHERS,DISPATCHED_EVENTS:()=>DISPATCHED_EVENTS,CODEX_DISPATCHED_EVENT_MATCHERS:()=>CODEX_DISPATCHED_EVENT_MATCHERS});function isBlockingEvent(event){return BLOCKING_EVENTS.has(event)}var DISPATCHED_EVENT_MATCHERS,CODEX_DISPATCHED_EVENT_MATCHERS,DISPATCHED_EVENTS,BLOCKING_EVENTS;var init_types2=__esm(()=>{DISPATCHED_EVENT_MATCHERS={PreToolUse:"*",PostToolUse:"SendMessage"},CODEX_DISPATCHED_EVENT_MATCHERS={PreToolUse:"*",PostToolUse:"SendMessage",UserPromptSubmit:"*",Stop:"*"},DISPATCHED_EVENTS=Object.keys(DISPATCHED_EVENT_MATCHERS),BLOCKING_EVENTS=new Set(["PreToolUse","UserPromptSubmit","TeammateIdle","TaskCompleted","PermissionRequest"])});var exports_inject={};__export(exports_inject,{isTeamHooked:()=>isTeamHooked,injectTeamHooks:()=>injectTeamHooks,buildDispatchCommand:()=>buildDispatchCommand});import{existsSync as existsSync6}from"fs";import{mkdir,readFile as readFile2,writeFile as writeFile2}from"fs/promises";import{homedir as homedir5}from"os";import{join as join8}from"path";import{fileURLToPath}from"url";function escapeShellArg(arg){return`'${arg.replace(/'/g,"'\\''")}'`}function compiledBinaryCandidates(){let candidates=[];if(process.env.GENIE_HOOK_BIN)candidates.push(process.env.GENIE_HOOK_BIN);let home=process.env.GENIE_HOME??join8(homedir5(),".genie");candidates.push(join8(home,"bin","genie-hook"));try{let repoBin=fileURLToPath(new URL("../../dist/genie-hook",import.meta.url));candidates.push(repoBin)}catch{}return candidates}function buildDispatchCommand(){for(let candidate of compiledBinaryCandidates())if(existsSync6(candidate))return escapeShellArg(candidate);let entrypoint=fileURLToPath(new URL("../genie.ts",import.meta.url));if(!existsSync6(entrypoint))return"genie hook dispatch";let bun=process.execPath||"bun";return`${escapeShellArg(bun)} run ${escapeShellArg(entrypoint)} hook dispatch`}function isGenieDispatchCommand(command){return typeof command==="string"&&/(?:^|\s)hook\s+dispatch(?:\s|$)/.test(command)}function claudeConfigDir(){return process.env.CLAUDE_CONFIG_DIR??join8(homedir5(),".claude")}function teamSettingsPath(teamName){let sanitized=teamName.replace(/[^a-zA-Z0-9]/g,"-").toLowerCase();return join8(claudeConfigDir(),"teams",sanitized,"settings.json")}function buildHooksConfig(){let hooks={},dispatchCommand=buildDispatchCommand();for(let[event,matcher]of Object.entries(DISPATCHED_EVENT_MATCHERS))hooks[event]=[{matcher,hooks:[{type:"command",command:dispatchCommand,timeout:DISPATCH_TIMEOUT}]}];return hooks}async function readSettings(settingsPath){if(!existsSync6(settingsPath))return{};try{return JSON.parse(await readFile2(settingsPath,"utf-8"))}catch{return{}}}function allEventsAlreadyInjected(existingHooks,hooksConfig){return DISPATCHED_EVENTS.every((event)=>{let existing=existingHooks[event],desiredCommand=hooksConfig[event][0].hooks[0].command,desiredMatcher=hooksConfig[event][0].matcher;return existing?.some((m)=>m.matcher===desiredMatcher&&m.hooks?.some((h)=>h.command===desiredCommand))})}function hasNoObsoleteGenieEntries(existingHooks){return Object.keys(existingHooks).every((event)=>{if(DISPATCHED_EVENTS.includes(event))return!0;return!existingHooks[event]?.some((m)=>m.hooks?.some((h)=>isGenieDispatchCommand(h.command)))})}function pruneObsoleteGenieEntries(mergedHooks){for(let event of Object.keys(mergedHooks)){if(DISPATCHED_EVENTS.includes(event))continue;let cleaned=(mergedHooks[event]??[]).map((matcher)=>({...matcher,hooks:matcher.hooks?.filter((hook)=>!isGenieDispatchCommand(hook.command))})).filter((matcher)=>(matcher.hooks?.length??0)>0);if(cleaned.length===0)delete mergedHooks[event];else mergedHooks[event]=cleaned}}function refreshMatcherEntries(entries,genieEntry){return entries.map((matcher)=>{let hasGenieHook=matcher.hooks?.some((h)=>isGenieDispatchCommand(h.command));return{...matcher,matcher:hasGenieHook?genieEntry.matcher:matcher.matcher,hooks:matcher.hooks?.map((hook)=>isGenieDispatchCommand(hook.command)?{...hook,command:genieEntry.hooks[0].command,timeout:DISPATCH_TIMEOUT}:hook)}})}function upsertGenieEntry(mergedHooks,event,genieEntry){let existingEntries=refreshMatcherEntries(mergedHooks[event]??[],genieEntry),alreadyPresent=existingEntries.some((m)=>m.hooks?.some((h)=>isGenieDispatchCommand(h.command)));mergedHooks[event]=alreadyPresent?existingEntries:[...existingEntries,genieEntry]}async function injectIntoFile(settingsPath){let settings=await readSettings(settingsPath),hooksConfig=buildHooksConfig(),existingHooks=settings.hooks;if(existingHooks&&allEventsAlreadyInjected(existingHooks,hooksConfig)&&hasNoObsoleteGenieEntries(existingHooks))return!1;let mergedHooks=existingHooks?{...existingHooks}:{};pruneObsoleteGenieEntries(mergedHooks);for(let event of DISPATCHED_EVENTS)upsertGenieEntry(mergedHooks,event,hooksConfig[event][0]);settings.hooks=mergedHooks;let dir=join8(settingsPath,"..");return await mkdir(dir,{recursive:!0}),await writeFile2(settingsPath,JSON.stringify(settings,null,2)),!0}async function injectTeamHooks(teamName){let path=teamSettingsPath(teamName);return injectIntoFile(path)}async function isTeamHooked(teamName){let path=teamSettingsPath(teamName);if(!existsSync6(path))return!1;try{let content=await readFile2(path,"utf-8"),hooks=JSON.parse(content).hooks;if(!hooks)return!1;return DISPATCHED_EVENTS.every((event)=>{return hooks[event]?.some((m)=>m.hooks?.some((h)=>isGenieDispatchCommand(h.command)))})}catch{return!1}}var DISPATCH_TIMEOUT=15;var init_inject=__esm(()=>{init_types2()});var exports_js_yaml={};__export(exports_js_yaml,{types:()=>types2,safeLoadAll:()=>safeLoadAll,safeLoad:()=>safeLoad,safeDump:()=>safeDump,loadAll:()=>loadAll,load:()=>load,dump:()=>dump,default:()=>jsYaml,YAMLException:()=>YAMLException,Type:()=>Type,Schema:()=>Schema,JSON_SCHEMA:()=>JSON_SCHEMA,FAILSAFE_SCHEMA:()=>FAILSAFE_SCHEMA,DEFAULT_SCHEMA:()=>DEFAULT_SCHEMA,CORE_SCHEMA:()=>CORE_SCHEMA});function isNothing(subject){return typeof subject>"u"||subject===null}function isObject(subject){return typeof subject==="object"&&subject!==null}function toArray(sequence){if(Array.isArray(sequence))return sequence;else if(isNothing(sequence))return[];return[sequence]}function extend(target,source){var index,length,key,sourceKeys;if(source){sourceKeys=Object.keys(source);for(index=0,length=sourceKeys.length;index<length;index+=1)key=sourceKeys[index],target[key]=source[key]}return target}function repeat(string,count){var result2="",cycle;for(cycle=0;cycle<count;cycle+=1)result2+=string;return result2}function isNegativeZero(number){return number===0&&Number.NEGATIVE_INFINITY===1/number}function formatError(exception,compact){var where="",message=exception.reason||"(unknown reason)";if(!exception.mark)return message;if(exception.mark.name)where+='in "'+exception.mark.name+'" ';if(where+="("+(exception.mark.line+1)+":"+(exception.mark.column+1)+")",!compact&&exception.mark.snippet)where+=`
143
143
 
144
144
  `+exception.mark.snippet;return message+" "+where}function YAMLException$1(reason,mark){if(Error.call(this),this.name="YAMLException",this.reason=reason,this.mark=mark,this.message=formatError(this,!1),Error.captureStackTrace)Error.captureStackTrace(this,this.constructor);else this.stack=Error().stack||""}function getLine(buffer,lineStart,lineEnd,position,maxLineLength){var head="",tail="",maxHalfLength=Math.floor(maxLineLength/2)-1;if(position-lineStart>maxHalfLength)head=" ... ",lineStart=position-maxHalfLength+head.length;if(lineEnd-position>maxHalfLength)tail=" ...",lineEnd=position+maxHalfLength-tail.length;return{str:head+buffer.slice(lineStart,lineEnd).replace(/\t/g,"\u2192")+tail,pos:position-lineStart+head.length}}function padStart(string,max){return common.repeat(" ",max-string.length)+string}function makeSnippet(mark,options){if(options=Object.create(options||null),!mark.buffer)return null;if(!options.maxLength)options.maxLength=79;if(typeof options.indent!=="number")options.indent=1;if(typeof options.linesBefore!=="number")options.linesBefore=3;if(typeof options.linesAfter!=="number")options.linesAfter=2;var re=/\r?\n|\r|\0/g,lineStarts=[0],lineEnds=[],match,foundLineNo=-1;while(match=re.exec(mark.buffer))if(lineEnds.push(match.index),lineStarts.push(match.index+match[0].length),mark.position<=match.index&&foundLineNo<0)foundLineNo=lineStarts.length-2;if(foundLineNo<0)foundLineNo=lineStarts.length-1;var result2="",i,line,lineNoLength=Math.min(mark.line+options.linesAfter,lineEnds.length).toString().length,maxLineLength=options.maxLength-(options.indent+lineNoLength+3);for(i=1;i<=options.linesBefore;i++){if(foundLineNo-i<0)break;line=getLine(mark.buffer,lineStarts[foundLineNo-i],lineEnds[foundLineNo-i],mark.position-(lineStarts[foundLineNo]-lineStarts[foundLineNo-i]),maxLineLength),result2=common.repeat(" ",options.indent)+padStart((mark.line-i+1).toString(),lineNoLength)+" | "+line.str+`
145
145
  `+result2}line=getLine(mark.buffer,lineStarts[foundLineNo],lineEnds[foundLineNo],mark.position,maxLineLength),result2+=common.repeat(" ",options.indent)+padStart((mark.line+1).toString(),lineNoLength)+" | "+line.str+`
@@ -177,7 +177,7 @@ ${prompt}`}function extractPromptPreamble(input){let match=input.match(PREAMBLE_
177
177
 
178
178
  ${content}`;if(params.extraArgs){let fileIdx=params.extraArgs.indexOf("--append-system-prompt-file");if(fileIdx!==-1&&params.extraArgs[fileIdx+1])content=`${content}
179
179
 
180
- ${readFileSync6(params.extraArgs[fileIdx+1],"utf-8")}`,params.extraArgs.splice(fileIdx,2)}writeFileSync6(promptFile,content);let flag=params.promptMode==="system"?"--system-prompt-file":"--append-system-prompt-file";parts.push(flag,escapeShellArg2(promptFile))}else if(params.systemPromptFile){let flag=params.promptMode==="system"?"--system-prompt-file":"--append-system-prompt-file";parts.push(flag,escapeShellArg2(params.systemPromptFile))}}function appendOtelEnv(env,params){if(!params.otelPort||process.env.OTEL_EXPORTER_OTLP_ENDPOINT)return;if(env.CLAUDE_CODE_ENABLE_TELEMETRY="1",env.OTEL_LOGS_EXPORTER="otlp",env.OTEL_METRICS_EXPORTER="otlp",env.OTEL_EXPORTER_OTLP_PROTOCOL="http/json",env.OTEL_EXPORTER_OTLP_ENDPOINT=`http://127.0.0.1:${params.otelPort}`,env.OTEL_LOG_TOOL_DETAILS="1",params.otelLogPrompts!==!1)env.OTEL_LOG_USER_PROMPTS="1";let resourceParts=[];if(params.role)resourceParts.push(`agent.name=${params.role}`);if(params.team)resourceParts.push(`team.name=${params.team}`);if(params.otelWishSlug)resourceParts.push(`wish.slug=${params.otelWishSlug}`);if(params.role)resourceParts.push(`agent.role=${params.role}`);if(resourceParts.length>0)env.OTEL_RESOURCE_ATTRIBUTES=resourceParts.join(",")}function appendTraceContext(parts,env,params){let ctx=getAmbient();if(params.initialPrompt){let prompt=ctx?injectPromptPreamble(params.initialPrompt,ctx):params.initialPrompt;parts.push(escapeShellArg2(prompt))}if(ctx)env[TRACE_ENV_VAR]=mintToken(ctx),env[TRACE_ID_ENV_VAR]=ctx.trace_id}function buildClaudeGenieEnv(params){let env={};if(env.GENIE_WORKER="1",params.role)env.GENIE_AGENT_NAME=params.role;if(params.team)env.GENIE_TEAM=params.team;if(params.executorId)env.GENIE_EXECUTOR_ID=params.executorId;if(params.agentId)env.GENIE_AGENT_ID=params.agentId;return env}function appendSessionFlags(parts,params){if(params.resume)parts.push("--resume",escapeShellArg2(params.resume));else if(params.sessionId)parts.push("--session-id",escapeShellArg2(params.sessionId));let claudeAgentFlag=params.agentTemplate??params.role;if(claudeAgentFlag)parts.push("--agent",escapeShellArg2(claudeAgentFlag));if(params.model)parts.push("--model",escapeShellArg2(params.model));if(params.name)parts.push("--name",escapeShellArg2(params.name))}function buildSettingsObject(params){let settingsObj={};if(!params.skipHooks){let hookEntry={type:"command",command:buildDispatchCommand(),timeout:15};settingsObj.hooks={PreToolUse:[{matcher:"*",hooks:[hookEntry]}],PostToolUse:[{matcher:"*",hooks:[hookEntry]}],UserPromptSubmit:[{hooks:[hookEntry]}],Stop:[{hooks:[hookEntry]}]}}if(params.permissions){let perms={};if(params.permissions.allow?.length)perms.allow=params.permissions.allow;if(params.permissions.deny?.length)perms.deny=params.permissions.deny;if(Object.keys(perms).length>0)settingsObj.permissions=perms}return settingsObj}function warnIfAllowRulesAreBypassed(params){if(!params.permissions?.allow?.length)return;if(params.nativeTeam?.permissionMode!=="bypassPermissions")return;let agentName=params.nativeTeam.agentName??params.role??params.name??"unknown";process.stderr.write(`Warning: agent ${agentName} declares permissions.allow but permissionMode is bypassPermissions \u2014 allow rules are advisory under bypass (deny still enforced).
180
+ ${readFileSync6(params.extraArgs[fileIdx+1],"utf-8")}`,params.extraArgs.splice(fileIdx,2)}writeFileSync6(promptFile,content);let flag=params.promptMode==="system"?"--system-prompt-file":"--append-system-prompt-file";parts.push(flag,escapeShellArg2(promptFile))}else if(params.systemPromptFile){let flag=params.promptMode==="system"?"--system-prompt-file":"--append-system-prompt-file";parts.push(flag,escapeShellArg2(params.systemPromptFile))}}function appendOtelEnv(env,params){if(!params.otelPort||process.env.OTEL_EXPORTER_OTLP_ENDPOINT)return;if(env.CLAUDE_CODE_ENABLE_TELEMETRY="1",env.OTEL_LOGS_EXPORTER="otlp",env.OTEL_METRICS_EXPORTER="otlp",env.OTEL_EXPORTER_OTLP_PROTOCOL="http/json",env.OTEL_EXPORTER_OTLP_ENDPOINT=`http://127.0.0.1:${params.otelPort}`,env.OTEL_LOG_TOOL_DETAILS="1",params.otelLogPrompts!==!1)env.OTEL_LOG_USER_PROMPTS="1";let resourceParts=[];if(params.role)resourceParts.push(`agent.name=${params.role}`);if(params.team)resourceParts.push(`team.name=${params.team}`);if(params.otelWishSlug)resourceParts.push(`wish.slug=${params.otelWishSlug}`);if(params.role)resourceParts.push(`agent.role=${params.role}`);if(resourceParts.length>0)env.OTEL_RESOURCE_ATTRIBUTES=resourceParts.join(",")}function appendTraceContext(parts,env,params){let ctx=getAmbient();if(params.initialPrompt){let prompt=ctx?injectPromptPreamble(params.initialPrompt,ctx):params.initialPrompt;parts.push(escapeShellArg2(prompt))}if(ctx)env[TRACE_ENV_VAR]=mintToken(ctx),env[TRACE_ID_ENV_VAR]=ctx.trace_id}function buildClaudeGenieEnv(params){let env={};if(env.GENIE_WORKER="1",params.role)env.GENIE_AGENT_NAME=params.role;if(params.team)env.GENIE_TEAM=params.team;if(params.executorId)env.GENIE_EXECUTOR_ID=params.executorId;if(params.agentId)env.GENIE_AGENT_ID=params.agentId;return env}function appendSessionFlags(parts,params){if(params.resume)parts.push("--resume",escapeShellArg2(params.resume));else if(params.sessionId)parts.push("--session-id",escapeShellArg2(params.sessionId));let claudeAgentFlag=params.agentTemplate??params.role;if(claudeAgentFlag)parts.push("--agent",escapeShellArg2(claudeAgentFlag));if(params.model)parts.push("--model",escapeShellArg2(params.model));if(params.name)parts.push("--name",escapeShellArg2(params.name))}function buildSettingsObject(params){let settingsObj={};if(!params.skipHooks){let hookEntry={type:"command",command:buildDispatchCommand(),timeout:15},{DISPATCHED_EVENT_MATCHERS:DISPATCHED_EVENT_MATCHERS2}=(init_types2(),__toCommonJS(exports_types)),hooks={};for(let[event,matcher]of Object.entries(DISPATCHED_EVENT_MATCHERS2))hooks[event]=[{matcher,hooks:[hookEntry]}];settingsObj.hooks=hooks}if(params.permissions){let perms={};if(params.permissions.allow?.length)perms.allow=params.permissions.allow;if(params.permissions.deny?.length)perms.deny=params.permissions.deny;if(Object.keys(perms).length>0)settingsObj.permissions=perms}return settingsObj}function warnIfAllowRulesAreBypassed(params){if(!params.permissions?.allow?.length)return;if(params.nativeTeam?.permissionMode!=="bypassPermissions")return;let agentName=params.nativeTeam.agentName??params.role??params.name??"unknown";process.stderr.write(`Warning: agent ${agentName} declares permissions.allow but permissionMode is bypassPermissions \u2014 allow rules are advisory under bypass (deny still enforced).
181
181
  `)}function appendDisallowedAndExtraArgs(parts,params){if(params.disallowedTools?.length)for(let tool of params.disallowedTools)parts.push("--disallowedTools",escapeShellArg2(tool));if(params.extraArgs)for(let arg of params.extraArgs)parts.push(escapeShellArg2(arg))}function assertClaudeBuiltinHasIdentity(params){let templateName=params.agentTemplate??params.role;if(!templateName)return;if(params.resume)return;if(!resolveBuiltinAgentPath(templateName))return;if(params.systemPromptFile||params.systemPrompt)return;throw Error(`Refusing to launch built-in agent "${templateName}" without AGENTS.md identity. Resolve systemPromptFile or systemPrompt before building the Claude command.`)}function buildClaudeCommand(params){assertClaudeBuiltinHasIdentity(params),preflightCheck("claude");let parts=[resolveShellBinary("claude")??"claude","--permission-mode",escapeShellArg2("auto")],env=buildClaudeGenieEnv(params);if(appendOtelEnv(env,params),params.nativeTeam?.enabled)appendNativeTeamFlags(parts,env,params.nativeTeam,params);appendSessionFlags(parts,params),appendSystemPromptFlags(parts,params),warnIfAllowRulesAreBypassed(params);let settingsObj=buildSettingsObject(params);if(Object.keys(settingsObj).length>0)parts.push("--settings",escapeShellArg2(JSON.stringify(settingsObj)));return appendDisallowedAndExtraArgs(parts,params),appendTraceContext(parts,env,params),{command:parts.join(" "),provider:"claude",env:Object.keys(env).length>0?env:void 0,meta:{role:params.role,skill:params.skill}}}function buildCodexAutoPrompt(params){let promptParts=[`Genie worker. Team: ${params.team}.`];if(params.role)promptParts.push(`Role: ${params.role}.`);if(params.skill)promptParts.push(`Execute the ${params.skill} skill instructions.`);return promptParts.join(" ")}function sanitizeCodexPromptFileStem(stem){return stem.replace(/[^a-zA-Z0-9._-]/g,"-")||Date.now().toString(36)}function splitCodexExtraArgs(extraArgs){let forwarded=[],promptFiles=[],args=extraArgs??[];for(let i2=0;i2<args.length;i2++){let arg=args[i2],equalsFlag=[...CODEX_PROMPT_FILE_FLAGS].find((flag)=>arg.startsWith(`${flag}=`));if(equalsFlag){let path=arg.slice(equalsFlag.length+1);if(!path)throw Error(`Missing path for ${equalsFlag}`);promptFiles.push(path);continue}if(CODEX_PROMPT_FILE_FLAGS.has(arg)){let path=args[i2+1];if(!path)throw Error(`Missing path after ${arg}`);promptFiles.push(path),i2++;continue}forwarded.push(arg)}return{forwarded,promptFiles}}function buildCodexMergedPrompt(params,extraPromptFiles){let{readFileSync:readFileSync6}=__require("fs"),sections=[];if(params.systemPromptFile!==void 0)sections.push(readFileSync6(params.systemPromptFile,"utf-8"));if(params.systemPrompt!==void 0)sections.push(params.systemPrompt);for(let promptFile of extraPromptFiles)sections.push(readFileSync6(promptFile,"utf-8"));if(params.initialPrompt!==void 0)sections.push(params.initialPrompt);return sections.length>0?sections.join(`
182
182
 
183
183
  `):null}function writeCodexPromptFile(params,content){let{mkdirSync:mkdirSync5,writeFileSync:writeFileSync6}=__require("fs"),{join:join10}=__require("path");mkdirSync5(CODEX_PROMPT_DIR,{recursive:!0});let stem=sanitizeCodexPromptFileStem(params.executorId??Date.now().toString(36)),promptFile=join10(CODEX_PROMPT_DIR,`${stem}.txt`);return writeFileSync6(promptFile,content,"utf-8"),promptFile}function buildCodexCommand(params){preflightCheck("codex");let parts=["codex"],env={};if(params.executorId)env.GENIE_EXECUTOR_ID=params.executorId;if(params.agentId)env.GENIE_AGENT_ID=params.agentId;if(params.role)env.GENIE_AGENT_NAME=params.role;else if(params.name)env.GENIE_AGENT_NAME=params.name;if(params.team)env.GENIE_TEAM=params.team;let{forwarded:extraArgs,promptFiles:extraPromptFiles}=splitCodexExtraArgs(params.extraArgs);parts.push("--yolo"),parts.push("--no-alt-screen");let codexModel=sanitizeModelForProvider("codex",params.model);if(codexModel)parts.push("--model",escapeShellArg2(codexModel));for(let arg of extraArgs)parts.push(escapeShellArg2(arg));let mergedPrompt=buildCodexMergedPrompt(params,extraPromptFiles);if(mergedPrompt!==null){let promptFile=writeCodexPromptFile(params,mergedPrompt);parts.push(`"$(cat ${escapeShellArg2(promptFile)})"`)}else parts.push(escapeShellArg2(buildCodexAutoPrompt(params)));return{command:parts.join(" "),provider:"codex",env:Object.keys(env).length>0?env:void 0,meta:{role:params.role,skill:params.skill}}}function buildLaunchCommand(params){let validated=validateSpawnParams(params);switch(validated.provider){case"claude":return buildClaudeCommand(validated);case"codex":return buildCodexCommand(validated);case"claude-sdk":return{command:"claude-sdk-in-process",provider:"claude-sdk",meta:{role:validated.role,skill:validated.skill}};default:throw Error(`Unknown provider "${validated.provider}". Valid providers: claude, codex, claude-sdk`)}}var CLAUDE_TEAM_COLORS,spawnParamsSchema,CODEX_PROMPT_DIR="/tmp/genie-codex-prompts",CODEX_PROMPT_FILE_FLAGS;var init_provider_adapters=__esm(()=>{init_zod();init_inject();init_builtin_agents();init_provider_models();init_trace_context();CLAUDE_TEAM_COLORS=["red","blue","green","yellow","purple","orange","pink","cyan"],spawnParamsSchema=exports_external.object({provider:exports_external.enum(["claude","codex","claude-sdk","app-pty"]),team:exports_external.string().min(1,"Team name is required"),role:exports_external.string().optional(),agentTemplate:exports_external.string().optional(),skill:exports_external.string().optional(),agentId:exports_external.string().optional(),executorId:exports_external.string().uuid().optional(),extraArgs:exports_external.array(exports_external.string()).optional(),nativeTeam:exports_external.object({enabled:exports_external.boolean(),parentSessionId:exports_external.string().optional(),color:exports_external.string().optional(),agentType:exports_external.string().optional(),planModeRequired:exports_external.boolean().optional(),permissionMode:exports_external.string().optional(),agentName:exports_external.string().optional()}).optional(),sessionId:exports_external.string().uuid().optional(),resume:exports_external.string().optional(),systemPromptFile:exports_external.string().optional(),systemPrompt:exports_external.string().optional(),promptMode:exports_external.enum(["system","append"]).optional(),model:exports_external.string().optional(),initialPrompt:exports_external.string().optional(),name:exports_external.string().optional(),permissions:exports_external.object({allow:exports_external.array(exports_external.string()).optional(),deny:exports_external.array(exports_external.string()).optional()}).optional(),disallowedTools:exports_external.array(exports_external.string()).optional(),otelPort:exports_external.number().optional(),otelLogPrompts:exports_external.boolean().optional(),otelWishSlug:exports_external.string().optional(),newWindow:exports_external.boolean().optional(),windowTarget:exports_external.string().optional()});CODEX_PROMPT_FILE_FLAGS=new Set(["--append-system-prompt-file","--system-prompt-file"])});var exports_audit={};__export(exports_audit,{recordAuditEvent:()=>recordAuditEvent,queryToolUsageDetail:()=>queryToolUsageDetail,queryToolUsage:()=>queryToolUsage,queryTimeline:()=>queryTimeline,querySummary:()=>querySummary,queryErrorPatterns:()=>queryErrorPatterns,queryCostBreakdown:()=>queryCostBreakdown,queryAuditEvents:()=>queryAuditEvents,getActor:()=>getActor,generateTraceId:()=>generateTraceId,followAuditEvents:()=>followAuditEvents});async function recordAuditEvent(entityType,entityId,eventType,actor,details){try{if(!await isAvailable())return;let sql=await getConnection();await sql`
@@ -1749,7 +1749,7 @@ ${gitStatus}`:"","","Pick up where you left off. Read the wish file for full con
1749
1749
  --- Error ---
1750
1750
  ${Array.isArray(error2.errors)&&error2.errors.length>0?error2.errors.join("; "):error2.subtype}\x1B[0m
1751
1751
  `}function formatSystem(msg){let rec=msg;if(rec.subtype==="status"&&rec.status)return`[status] ${rec.status}
1752
- `;return null}var exports_codex_inject={};__export(exports_codex_inject,{injectCodexHooks:()=>injectCodexHooks,codexHooksInjected:()=>codexHooksInjected,CODEX_DISPATCHED_EVENTS:()=>CODEX_DISPATCHED_EVENTS});import{existsSync as existsSync36}from"fs";import{mkdir as mkdir6,readFile as readFile10,writeFile as writeFile7}from"fs/promises";import{homedir as homedir29}from"os";import{join as join43}from"path";function codexHomeDir(){return process.env.CODEX_HOME??join43(homedir29(),".codex")}function codexConfigPath(){return join43(codexHomeDir(),"config.toml")}function escapeTomlString(value){return`"${value.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function buildCodexHookFragment(){let cmd=buildDispatchCommand(),lines=[];lines.push("# === GENIE HOOK BRIDGE BEGIN ==="),lines.push("# Auto-injected by `genie spawn ... --provider codex`. Do not edit by hand."),lines.push("# Removing this block disables codex \u2192 genie hook event delivery."),lines.push("[hooks]"),lines.push("feature_enabled = true"),lines.push("");for(let event of CODEX_DISPATCHED_EVENTS)lines.push(`[[hooks.${event}]]`),lines.push('matcher = "*"'),lines.push(""),lines.push(`[[hooks.${event}.hooks]]`),lines.push('type = "command"'),lines.push(`command = ${escapeTomlString(cmd)}`),lines.push(`timeout = ${DISPATCH_TIMEOUT2}`),lines.push("");return lines.push("# === GENIE HOOK BRIDGE END ==="),lines.join(`
1752
+ `;return null}var exports_codex_inject={};__export(exports_codex_inject,{injectCodexHooks:()=>injectCodexHooks,codexHooksInjected:()=>codexHooksInjected,CODEX_DISPATCHED_EVENTS:()=>CODEX_DISPATCHED_EVENTS});import{existsSync as existsSync36}from"fs";import{mkdir as mkdir6,readFile as readFile10,writeFile as writeFile7}from"fs/promises";import{homedir as homedir29}from"os";import{join as join43}from"path";function codexHomeDir(){return process.env.CODEX_HOME??join43(homedir29(),".codex")}function codexConfigPath(){return join43(codexHomeDir(),"config.toml")}function escapeTomlString(value){return`"${value.replace(/\\/g,"\\\\").replace(/"/g,"\\\"")}"`}function buildCodexHookFragment(){let cmd=buildDispatchCommand(),lines=[];lines.push("# === GENIE HOOK BRIDGE BEGIN ==="),lines.push("# Auto-injected by `genie spawn ... --provider codex`. Do not edit by hand."),lines.push("# Removing this block disables codex \u2192 genie hook event delivery."),lines.push("[hooks]"),lines.push("feature_enabled = true"),lines.push("");for(let[event,matcher]of Object.entries(CODEX_DISPATCHED_EVENT_MATCHERS))lines.push(`[[hooks.${event}]]`),lines.push(`matcher = ${escapeTomlString(matcher)}`),lines.push(""),lines.push(`[[hooks.${event}.hooks]]`),lines.push('type = "command"'),lines.push(`command = ${escapeTomlString(cmd)}`),lines.push(`timeout = ${DISPATCH_TIMEOUT2}`),lines.push("");return lines.push("# === GENIE HOOK BRIDGE END ==="),lines.join(`
1753
1753
  `)}function stripExistingBlock(content){let beginIdx=content.indexOf(BEGIN_MARKER),endIdx=content.indexOf(END_MARKER);if(beginIdx===-1||endIdx===-1||endIdx<beginIdx)return{trimmed:content,existed:!1};let before=content.slice(0,beginIdx).replace(/\s+$/,""),after=content.slice(endIdx+END_MARKER.length).replace(/^\s+/,"");return{trimmed:before&&after?`${before}
1754
1754
 
1755
1755
  ${after}
@@ -1758,7 +1758,7 @@ ${after}
1758
1758
 
1759
1759
  ${desired}
1760
1760
  `:`${desired}
1761
- `;if(existing.trim()===candidate.trim())return!1;return await mkdir6(codexHomeDir(),{recursive:!0}),await writeFile7(path3,candidate),!0}async function codexHooksInjected(){let path3=codexConfigPath();if(!existsSync36(path3))return!1;try{let content=await readFile10(path3,"utf-8");return content.includes(BEGIN_MARKER)&&content.includes(END_MARKER)}catch{return!1}}var DISPATCH_TIMEOUT2=15,CODEX_DISPATCHED_EVENTS,BEGIN_MARKER="# === GENIE HOOK BRIDGE BEGIN ===",END_MARKER="# === GENIE HOOK BRIDGE END ===";var init_codex_inject=__esm(()=>{init_inject();CODEX_DISPATCHED_EVENTS=["PreToolUse","PostToolUse","UserPromptSubmit","SessionStart","Stop","PermissionRequest"]});var exports_idle_timeout={};__export(exports_idle_timeout,{suspendWorker:()=>suspendWorker,getIdleTimeoutMs:()=>getIdleTimeoutMs,checkIdleWorkers:()=>checkIdleWorkers,WATCHDOG_POLL_INTERVAL_MS:()=>WATCHDOG_POLL_INTERVAL_MS});function getIdleTimeoutMs(){let env=process.env.GENIE_IDLE_TIMEOUT_MS;if(env!==void 0){if(env==="")return DEFAULT_IDLE_TIMEOUT_MS;let parsed=Number(env);if(!Number.isNaN(parsed)&&parsed>=0)return parsed}return DEFAULT_IDLE_TIMEOUT_MS}async function suspendWorker(executorId,deps=defaultDeps3){let executor=(await deps.listExecutors()).find((e)=>e.id===executorId);if(!executor)return!1;if(executor.state==="terminated")return!0;if(executor.tmuxPaneId)try{await deps.executeTmux(`kill-pane -t '${executor.tmuxPaneId}'`)}catch{}return await deps.terminateExecutor(executorId),!0}async function checkIdleWorkers(deps=defaultDeps3){let timeoutMs=getIdleTimeoutMs();if(timeoutMs===0)return[];let executors=await deps.listExecutors(),suspended=[];for(let e of executors){if(e.state!=="idle")continue;if(Date.now()-new Date(e.updatedAt).getTime()<timeoutMs)continue;if(e.tmuxPaneId){if(!await deps.isPaneAlive(e.tmuxPaneId)){await deps.terminateExecutor(e.id),suspended.push(e.id);continue}}if(await suspendWorker(e.id,deps))suspended.push(e.id)}return suspended}var defaultDeps3,DEFAULT_IDLE_TIMEOUT_MS=1800000,WATCHDOG_POLL_INTERVAL_MS=60000;var init_idle_timeout=__esm(()=>{init_executor_registry();init_tmux();defaultDeps3={listExecutors:()=>listExecutors(),terminateExecutor,updateExecutorState,executeTmux:executeTmux2,isPaneAlive}});var exports_agents={};__export(exports_agents,{tryAutoRegisterAgent:()=>tryAutoRegisterAgent,resolveTeamName:()=>resolveTeamName3,resolveSpawnIdentity:()=>resolveSpawnIdentity,resolveAgentWorkingDir:()=>resolveAgentWorkingDir,resolveAgentForSpawn:()=>resolveAgentForSpawn,rejectDuplicateRole:()=>rejectDuplicateRole,recoverSurgery:()=>recoverSurgery,pickParallelShortId:()=>pickParallelShortId,handleWorkerStop:()=>handleWorkerStop,handleWorkerSpawn:()=>handleWorkerSpawn,handleWorkerResume:()=>handleWorkerResume,handleWorkerRecover:()=>handleWorkerRecover,handleWorkerKill:()=>handleWorkerKill,handleLsCommand:()=>handleLsCommand,findDeadResumable:()=>findDeadResumable,buildWorkerStatusMap:()=>buildWorkerStatusMap,buildResumeContext:()=>buildResumeContext,buildInitialSplitWindowCommand:()=>buildInitialSplitWindowCommand,buildFullResumeParams:()=>buildFullResumeParams,buildDirectoryPermissionSpawnParams:()=>buildDirectoryPermissionSpawnParams,_spawnAutoSyncDeps:()=>_spawnAutoSyncDeps,RecoverAgentNotFoundError:()=>RecoverAgentNotFoundError,OwnerSpawnCollisionError:()=>OwnerSpawnCollisionError});import{existsSync as existsSync37,readFileSync as readFileSync23}from"fs";import{isAbsolute,join as join44,relative,resolve as resolvePath}from"path";async function isPaneAliveOrDead(paneId){try{return await isPaneAlive(paneId)}catch(err){let message=err instanceof Error?err.message:String(err);if(err instanceof TmuxUnreachableError||message.includes("no server running")||message.includes("server exited")||message.includes("error connecting"))return!1;throw err}}async function resolveTeamLeaderName(teamNameOrDefault){return resolveLeaderName(teamNameOrDefault)}function isRelayAlive(pidFile){let{readFileSync:readFileSync24,existsSync:existsSync38}=__require("fs");if(!existsSync38(pidFile))return!1;try{let pid=Number.parseInt(readFileSync24(pidFile,"utf-8").trim());if(pid>0)return process.kill(pid,0),!0}catch{}return!1}async function ensureOtelRelay(team){let{writeFileSync:writeFileSync14,mkdirSync:mkdirSync15}=__require("fs"),{join:join45}=__require("path"),{homedir:homedir30}=__require("os"),relayDir=join45(homedir30(),".genie","relay");mkdirSync15(relayDir,{recursive:!0});let pidFile=join45(relayDir,"otel-relay.pid"),scriptFile=join45(relayDir,"otel-relay.mjs");if(isRelayAlive(pidFile))return!0;let inboxDir=join45(process.env.CLAUDE_CONFIG_DIR??join45(homedir30(),".claude"),"teams",team,"inboxes"),leaderInboxName=sanitizeTeamName(await resolveTeamLeaderName(team)),escapedRelayDir=relayDir.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),escapedInboxDir=inboxDir.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),escapedPidFile=pidFile.replace(/\\/g,"\\\\").replace(/'/g,"\\'");try{writeFileSync14(scriptFile,`import { createServer } from 'http';
1761
+ `;if(existing.trim()===candidate.trim())return!1;return await mkdir6(codexHomeDir(),{recursive:!0}),await writeFile7(path3,candidate),!0}async function codexHooksInjected(){let path3=codexConfigPath();if(!existsSync36(path3))return!1;try{let content=await readFile10(path3,"utf-8");return content.includes(BEGIN_MARKER)&&content.includes(END_MARKER)}catch{return!1}}var DISPATCH_TIMEOUT2=15,CODEX_DISPATCHED_EVENTS,BEGIN_MARKER="# === GENIE HOOK BRIDGE BEGIN ===",END_MARKER="# === GENIE HOOK BRIDGE END ===";var init_codex_inject=__esm(()=>{init_inject();init_types2();CODEX_DISPATCHED_EVENTS=Object.keys(CODEX_DISPATCHED_EVENT_MATCHERS)});var exports_idle_timeout={};__export(exports_idle_timeout,{suspendWorker:()=>suspendWorker,getIdleTimeoutMs:()=>getIdleTimeoutMs,checkIdleWorkers:()=>checkIdleWorkers,WATCHDOG_POLL_INTERVAL_MS:()=>WATCHDOG_POLL_INTERVAL_MS});function getIdleTimeoutMs(){let env=process.env.GENIE_IDLE_TIMEOUT_MS;if(env!==void 0){if(env==="")return DEFAULT_IDLE_TIMEOUT_MS;let parsed=Number(env);if(!Number.isNaN(parsed)&&parsed>=0)return parsed}return DEFAULT_IDLE_TIMEOUT_MS}async function suspendWorker(executorId,deps=defaultDeps3){let executor=(await deps.listExecutors()).find((e)=>e.id===executorId);if(!executor)return!1;if(executor.state==="terminated")return!0;if(executor.tmuxPaneId)try{await deps.executeTmux(`kill-pane -t '${executor.tmuxPaneId}'`)}catch{}return await deps.terminateExecutor(executorId),!0}async function checkIdleWorkers(deps=defaultDeps3){let timeoutMs=getIdleTimeoutMs();if(timeoutMs===0)return[];let executors=await deps.listExecutors(),suspended=[];for(let e of executors){if(e.state!=="idle")continue;if(Date.now()-new Date(e.updatedAt).getTime()<timeoutMs)continue;if(e.tmuxPaneId){if(!await deps.isPaneAlive(e.tmuxPaneId)){await deps.terminateExecutor(e.id),suspended.push(e.id);continue}}if(await suspendWorker(e.id,deps))suspended.push(e.id)}return suspended}var defaultDeps3,DEFAULT_IDLE_TIMEOUT_MS=1800000,WATCHDOG_POLL_INTERVAL_MS=60000;var init_idle_timeout=__esm(()=>{init_executor_registry();init_tmux();defaultDeps3={listExecutors:()=>listExecutors(),terminateExecutor,updateExecutorState,executeTmux:executeTmux2,isPaneAlive}});var exports_agents={};__export(exports_agents,{tryAutoRegisterAgent:()=>tryAutoRegisterAgent,resolveTeamName:()=>resolveTeamName3,resolveSpawnIdentity:()=>resolveSpawnIdentity,resolveAgentWorkingDir:()=>resolveAgentWorkingDir,resolveAgentForSpawn:()=>resolveAgentForSpawn,rejectDuplicateRole:()=>rejectDuplicateRole,recoverSurgery:()=>recoverSurgery,pickParallelShortId:()=>pickParallelShortId,handleWorkerStop:()=>handleWorkerStop,handleWorkerSpawn:()=>handleWorkerSpawn,handleWorkerResume:()=>handleWorkerResume,handleWorkerRecover:()=>handleWorkerRecover,handleWorkerKill:()=>handleWorkerKill,handleLsCommand:()=>handleLsCommand,findDeadResumable:()=>findDeadResumable,buildWorkerStatusMap:()=>buildWorkerStatusMap,buildResumeContext:()=>buildResumeContext,buildInitialSplitWindowCommand:()=>buildInitialSplitWindowCommand,buildFullResumeParams:()=>buildFullResumeParams,buildDirectoryPermissionSpawnParams:()=>buildDirectoryPermissionSpawnParams,_spawnAutoSyncDeps:()=>_spawnAutoSyncDeps,RecoverAgentNotFoundError:()=>RecoverAgentNotFoundError,OwnerSpawnCollisionError:()=>OwnerSpawnCollisionError});import{existsSync as existsSync37,readFileSync as readFileSync23}from"fs";import{isAbsolute,join as join44,relative,resolve as resolvePath}from"path";async function isPaneAliveOrDead(paneId){try{return await isPaneAlive(paneId)}catch(err){let message=err instanceof Error?err.message:String(err);if(err instanceof TmuxUnreachableError||message.includes("no server running")||message.includes("server exited")||message.includes("error connecting"))return!1;throw err}}async function resolveTeamLeaderName(teamNameOrDefault){return resolveLeaderName(teamNameOrDefault)}function isRelayAlive(pidFile){let{readFileSync:readFileSync24,existsSync:existsSync38}=__require("fs");if(!existsSync38(pidFile))return!1;try{let pid=Number.parseInt(readFileSync24(pidFile,"utf-8").trim());if(pid>0)return process.kill(pid,0),!0}catch{}return!1}async function ensureOtelRelay(team){let{writeFileSync:writeFileSync14,mkdirSync:mkdirSync15}=__require("fs"),{join:join45}=__require("path"),{homedir:homedir30}=__require("os"),relayDir=join45(homedir30(),".genie","relay");mkdirSync15(relayDir,{recursive:!0});let pidFile=join45(relayDir,"otel-relay.pid"),scriptFile=join45(relayDir,"otel-relay.mjs");if(isRelayAlive(pidFile))return!0;let inboxDir=join45(process.env.CLAUDE_CONFIG_DIR??join45(homedir30(),".claude"),"teams",team,"inboxes"),leaderInboxName=sanitizeTeamName(await resolveTeamLeaderName(team)),escapedRelayDir=relayDir.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),escapedInboxDir=inboxDir.replace(/\\/g,"\\\\").replace(/'/g,"\\'"),escapedPidFile=pidFile.replace(/\\/g,"\\\\").replace(/'/g,"\\'");try{writeFileSync14(scriptFile,`import { createServer } from 'http';
1762
1762
  import { execSync } from 'child_process';
1763
1763
  import { readFileSync, writeFileSync, mkdirSync, readdirSync, unlinkSync, statSync } from 'fs';
1764
1764
  import { createHash } from 'crypto';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@automagik/genie",
3
- "version": "4.260429.13",
3
+ "version": "4.260429.14",
4
4
  "description": "Collaborative terminal toolkit for human + AI workflows. NOTE: the npm distribution is being soft-deprecated — the canonical install is `curl -fsSL https://get.automagik.dev/genie | bash` (cosign + SLSA verified). See https://automagik.dev/genie/security/distribution-sovereignty",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "genie",
3
- "version": "4.260429.13",
3
+ "version": "4.260429.14",
4
4
  "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /work, validate with /review, and ship as one team.",
5
5
  "author": {
6
6
  "name": "Namastex Labs"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "genie-plugin",
3
- "version": "4.260429.13",
3
+ "version": "4.260429.14",
4
4
  "private": true,
5
5
  "description": "Runtime dependencies for genie bundled CLIs",
6
6
  "type": "module",