@farero-ai/agent-runner 0.0.0-stage → 0.1.1

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/index.js ADDED
@@ -0,0 +1,69 @@
1
+ var vn=Object.defineProperty;var l=(s,e)=>vn(s,"name",{value:e,configurable:!0});import{accessSync as kn,constants as Sn,readdirSync as xn,statSync as En}from"node:fs";import{createRequire as _n}from"node:module";import{homedir as it}from"node:os";import C from"node:path";function ue(s,e){return e?s==="claude"?{CLAUDE_CONFIG_DIR:e}:s==="codex"?{CODEX_HOME:e}:s==="opencode"?{XDG_DATA_HOME:e}:{}:{}}l(ue,"homeEnvironment");var An=_n(import.meta.url),rt={claude:"Claude Code",codex:"Codex"},Tn=["HOME","USER","LOGNAME","SHELL","LANG","LC_ALL","LC_CTYPE","TERM","TMPDIR","TEMP","TMP","XDG_CONFIG_HOME","XDG_DATA_HOME","XDG_CACHE_HOME","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy","NODE_EXTRA_CA_CERTS","SSL_CERT_FILE","SystemRoot","ComSpec","PATHEXT","USERPROFILE","HOMEDRIVE","HOMEPATH","APPDATA","LOCALAPPDATA"];function Te(s){try{return kn(s,Sn.X_OK),En(s).isFile()}catch{return!1}}l(Te,"isExecutable");function Cn(s){let e=C.join(s,".nvm","versions","node");try{return xn(e).filter(t=>/^v\d+\.\d+\.\d+$/.test(t)).sort((t,n)=>n.localeCompare(t,"en",{numeric:!0})).map(t=>C.join(e,t,"bin"))}catch{return[]}}l(Cn,"nvmBins");function Rn(s){let e=`@anthropic-ai/claude-agent-sdk-${process.platform}-${process.arch}`,t=process.resourcesPath,n=t?[C.join(t,"app.asar.unpacked","node_modules",e,s)]:[];try{let r=An.resolve(`${e}/package.json`);n.push(C.join(C.dirname(r).replace(`${C.sep}app.asar${C.sep}`,`${C.sep}app.asar.unpacked${C.sep}`),s))}catch{}return n.find(Te)}l(Rn,"bundledClaude");function On(s,e){let t=it(),n=[...e,...(process.env.PATH??"").split(C.delimiter),C.join(t,".local","bin"),C.join(t,".volta","bin"),C.join(t,".bun","bin"),"/opt/homebrew/bin","/usr/local/bin",...Cn(t)];return process.platform==="darwin"&&s==="codex"&&n.push("/Applications/Codex.app/Contents/Resources",C.join(t,"Applications","Codex.app","Contents","Resources")),n.filter(r=>C.isAbsolute(r))}l(On,"searchFolders");function st(s,e,t){let n=e?.runtime;if(n?.source==="custom"){let o=n.customPath.trim();return o&&C.isAbsolute(o)&&Te(o)?o:void 0}let r=process.platform==="win32"?`${s}.exe`:s,i=s==="claude"?Rn(r):void 0;return n?.source==="bundled"&&i?i:On(s,t).map(o=>C.join(o,r)).find(Te)??i}l(st,"findExecutable");function Ce(s={}){let e=s.searchPaths??[];return{launch(t,n){let r=st(t,n,e);return{command:r??t,args:[],resolved:r??null}},notInstalled(t,n){return new Error(n==="custom"?`${rt[t]} was not found at the selected path.`:`${rt[t]} is not installed on this computer. Install it, then try again.`)},environment({provider:t,workspaceEnv:n,accountHome:r,envKeys:i}){let o=st(t,void 0,e),a={};for(let c of[...Tn,...i??[]])process.env[c]!==void 0&&(a[c]=process.env[c]);return a.HOME??=it(),a.PATH=[...new Set([o&&C.dirname(o),...(process.env.PATH??"").split(C.delimiter),...process.platform==="win32"?[]:["/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin"]].filter(c=>!!c))].join(C.delimiter),t==="claude"&&(a.DISABLE_AUTOUPDATER="1"),{...a,...n,...ue(t,r)}},mcpStartupMs:s.mcpStartupMs??3e4,clientInfo:s.clientInfo??{name:"agent-runner",version:"0.1.0"}}}l(Ce,"localHost");import{randomBytes as Sr,randomUUID as ke}from"node:crypto";import{mkdirSync as xr,readFileSync as Er,rmSync as _r,writeFileSync as Ar}from"node:fs";import Tr from"node:path";import{forkSession as Cr,query as Rr}from"@anthropic-ai/claude-agent-sdk";var B="For a step only the person can perform, such as using a passkey, call handoff_request. The person can answer in the helper or parent chat and Farero resumes the helper. For questions about the assignment, delegated helpers must not use AskUserQuestion or any equivalent user question tool. Continue independently using available evidence. For an ordinary delegation, when missing information blocks safe progress, use ask_delegation_question with your own session_id, a stable client_id, the question and optional choices, then yield without a final report. The parent answers through answer_delegation_question and Farero resumes this same assignment. Only the parent decides whether to ask the user for task information. A parent answer never grants approval authority or expands the authorized scope. If the assignment does not support parent questions, report the blocker and information needed to the parent in your final result.";import{z as P}from"zod";var In=P.object({sessionId:P.string().min(1),workspaceId:P.string().min(1),title:P.string(),through:P.number().int().positive().optional(),entryId:P.string().optional()}),Ys=P.object({version:P.literal(1),kind:P.enum(["fork","continue","reference"]),scope:P.enum(["chat","reply"]),sources:P.array(In).min(1)});var Mn=["AskUserQuestion","question","request_user_input","request_user_input_async","functions.request_user_input","functions.request_user_input_async","item/tool/requestUserInput","codex/request_user_input_async"],ti=new Set(Mn.map(s=>s.toLowerCase().replace(/[_-]/g,"")));var Ln=1,Zi=`<farero-workflow-private version="${Ln}">`;var eo=25*1024*1024;var Re="Skill",ot=["farero_host","farero","native"],Dn=new Set(["plugin_guide","plugin_prepare","plugin_run","plugin_status","workspace_overview","search_chats","read_chat","list_voice_calls","search_voice_calls","read_voice_call","list_workspaces","list_chats","list_roles","get_role","update_roles","update_workflows","delegate_task","cancel_delegation","ask_delegation_question","answer_delegation_question","list_delegations","workspace_diff","list_repos","plan_usage","create_workspace","create_chat","send_prompt","render_ui","create_tab","split","stop_turn","close_chat","rename_chat","list_models","set_default_model","set_agent_options","set_workspace_status","create_workspace_status","rename_workspace_status","delete_workspace_status","reorder_workspace_statuses","pin_workspace","set_workspace_webhooks","rename_workspace","dev_server","continue_workspace","archive_workspace","unarchive_workspace","dismiss_prompt","keep_awake","relay_logs","request_mcp_sign_in"]),qn={read:"Read",edit:"Edit",multiedit:"MultiEdit",write:"Write",grep:"Grep",glob:"Glob",ls:"LS",list:"LS",bash:"Bash",websearch:"WebSearch",webfetch:"WebFetch",agent:"Agent",task:"Agent",subagent:"Agent",skill:Re,todowrite:"TodoWrite",todoread:"TodoRead",question:"AskUserQuestion",askuserquestion:"AskUserQuestion",toolsearch:"ToolSearch",notebookedit:"NotebookEdit"};function at(s,e=""){let t=l((o,a)=>({name:o?`mcp__${o}__${a}`:`mcp__${a}`,label:a,server:o}),"mcp"),n=l(o=>ot.includes(o)?"farero_host":o,"host");if(s.startsWith("mcp__")){let o=s.slice(5).split("__");return o.length>1&&o.every(Boolean)?t(n(o.slice(0,-1).join("__")),o.at(-1)):{name:s,label:s,server:null}}if(s==="mcpToolCall"){let o=e&&e!==s?e:"";return o?t(Dn.has(o)?"farero_host":null,o):{name:s,label:s,server:null}}for(let o of ot){let a=s[o.length];if(s.startsWith(o)&&(a==="_"||a===".")&&s.length>o.length+1)return t("farero_host",s.slice(o.length+1))}let r=s.toLowerCase().replace(/[_-]/g,""),i=r.endsWith("spawnagent")?"Agent":qn[r];return{name:i??s,label:i??s,server:null}}l(at,"toolIdentity");function Oe(s){let e=typeof s.skill=="string"?s.skill.trim():"";if(!e)return;let t=typeof s.args=="string"?s.args.trim():"";return t?`${e} ${t}`:e}l(Oe,"skillLabel");function Q(s){let e=s;for(let t=0;t<3;t++){let n=/^(?:\S+\/)?(zsh|bash|sh|dash|ksh|fish)\s+-l?c\s+([\s\S]+)$/.exec(e.trim());if(!n)return e.trim()||s;let r=n[2].trim();if(r.length>=2){let i=r[0],o=r[r.length-1];(i==='"'&&o==='"'||i==="'"&&o==="'")&&(r=r.slice(1,-1).trim())}if(!r)return s;e=r}return e.trim()||s}l(Q,"unwrapShellCommand");function D(s){return!!s&&s.includes("<task-notification>")}l(D,"isTaskNotificationNoise");var $n=/^(?:\s*<(command-name|command-message|command-args|local-command-stdout|local-command-stderr|local-command-caveat)>[\s\S]*?<\/\1>\s*)+$/;function W(s){return!!s&&$n.test(s.trim())}l(W,"isLocalCommandNoise");function ct(s,e){return`Background task ${s}: ${e}`}l(ct,"backgroundTaskNotice");function lt(s){return!!s&&s.includes("OpenCode is retrying the model request")}l(lt,"isOpenCodeRetryNotice");var ut=String.raw`fb\.\d{1,2}\.\d{13}\.`,dt=String.raw`(?:\.(?:[A-Za-z0-9_-]{2}|[A-Za-z0-9_-]{8}))?`,to=new RegExp(`^${ut}\\d{1,32}${dt}$`),no=new RegExp(`^${ut}[A-Za-z0-9_-]{1,500}${dt}$`);var pt={artifacts:"CLAUDE_CODE_ARTIFACT",agentTeams:"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS",taskTools:"CLAUDE_CODE_ENABLE_TODO_TOOLS"};var Ie={version:1,claude:{permissionMode:"bypassPermissions",declineSafetyChecks:!1,settingSources:["user","project","local"],allowedTools:[],disallowedTools:[],additionalDirectories:[],maxTurns:null,skillListingBudgetFraction:null,skillListingMaxDescChars:null,artifacts:!1,agentTeams:!1,taskTools:!1,promptSuggestions:!1,thinkingSummaries:null,instructions:"",runtime:{source:"bundled",customPath:""},envKeys:[]},codex:{sandbox:"danger-full-access",approvalPolicy:"never",networkAccess:!1,webSearch:null,personality:null,instructions:"",runtime:{source:"bundled",customPath:""},envKeys:[]},opencode:{permission:"allow",permissions:{},share:null,instructions:"",runtime:{source:"bundled",customPath:""},envKeys:[]},cursor:{sandbox:!1,settingSources:["plugins"],instructions:"",envKeys:[]},antigravity:{permissionMode:null,runtime:{source:"path",customPath:""},envKeys:[]}};function ft(s){return s==="bypassPermissions"}l(ft,"claudeCanDeclineSafetyChecks");var ro=720*60*60*1e3;var so=10*6e4;function Y(s){return e=>s[e]===!0}l(Y,"statusQuestion");var io=Y({disconnected:!1,connecting:!1,idle:!1,working:!0,waiting:!0,error:!1}),oo=Y({disconnected:!1,connecting:!0,idle:!1,working:!0,waiting:!0,error:!1}),ao=Y({disconnected:!1,connecting:!0,idle:!1,working:!0,waiting:!1,error:!1}),co=Y({disconnected:!0,connecting:!1,idle:!0,working:!1,waiting:!1,error:!1}),lo=Y({disconnected:!1,connecting:!1,idle:!1,working:!1,waiting:!0,error:!0});var gt=["Edit","Write","MultiEdit","NotebookEdit"];function de(s){return s.status==="connected"?`${s.label} is connected. If its tools are not listed yet, they load on the next turn. A repository or resource permission error needs access granted to this connection; signing in again does not establish that access.`:s.status==="disabled"?`${s.label} is turned off in the provider configuration.`:s.signIn?s.signIn.available?void 0:s.signIn.reason:"This provider connection has not reported its browser sign-in capability."}l(de,"mcpSignInBlocker");var Un="request_mcp_sign_in";function Fn(s,e=""){return at(s,e).name===`mcp__farero_host__${Un}`}l(Fn,"isMcpSignInTool");function pe(s,e,t=""){if(!Fn(s,t))return;let n=typeof e=="object"&&e!==null?e.server:void 0;return typeof n=="string"&&n.trim()?{servers:[n.trim()]}:void 0}l(pe,"mcpSignInToolCall");var ht="claude.ai ";function K(s){return s.startsWith(ht)?s.slice(ht.length):s}l(K,"mcpServerLabel");function mt(s,e){let t=s.find(i=>i.server===e);if(t)return t;let n=e.trim().toLowerCase(),r=s.filter(i=>i.server.toLowerCase()===n||i.label.toLowerCase()===n);if(r.length>1)throw new Error(`${e} matches ${r.map(i=>i.server).join(", ")}`);return r[0]}l(mt,"matchMcpServer");var Z=l(s=>typeof s=="string"&&s.trim()?s.trim():void 0,"str");function yt(s,e){if(!e||typeof e!="object")return;let t=e;if(s==="Agent"||s==="Task")return Z(t.description)??Z(t.subagent_type)??"Subagent";if(!/(?:^|[_.:])spawn_?agent$/i.test(s))return;let n=Z(t.agent_path);return Me((n?n.split("/").filter(Boolean).at(-1):void 0)??Z(t.task_name)??Z(t.agent_nickname))}l(yt,"subagentLabel");function Me(s){let e=s?.replace(/[-_]+/g," ").trim();return e?e[0].toUpperCase()+e.slice(1):"Subagent"}l(Me,"codexAgentName");var N=class extends Error{static{l(this,"NativeRejectedError")}code;constructor(e,t){super(e),this.name="NativeRejectedError",this.code=t}};var V=class extends Error{static{l(this,"NativePendingDeliveryError")}constructor(e){super(e),this.name="NativePendingDeliveryError"}};var q=class extends Error{static{l(this,"NativeThreadMissingError")}threadId;constructor(e,t){super(`${e} has no saved conversation for thread ${t}`),this.name="NativeThreadMissingError",this.threadId=t}};import{createHash as jn}from"node:crypto";function wt(s,e){if(s==="codex"||s==="cursor"||s==="antigravity"||s==="claude"&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(e))return e;let t=jn("sha256").update(`native:${s}:${e}`).digest("hex");return s==="opencode"?`msg_${t.slice(0,26)}`:`${t.slice(0,8)}-${t.slice(8,12)}-8${t.slice(13,16)}-a${t.slice(17,20)}-${t.slice(20,32)}`}l(wt,"providerMessageId");function fe(s){let e=new Map;return{emit(t){t.type==="interaction"&&e.set(t.interaction.id,t.interaction),t.type==="interaction-resolved"&&e.delete(t.id),s(t)},read:l(()=>[...e.values()],"read")}}l(fe,"trackInteractions");var $=l(s=>s&&typeof s=="object"&&!Array.isArray(s)?s:null,"record");function Pe(s){return`mcp__${s.replace(/[^a-zA-Z0-9_-]/g,"_")}__`}l(Pe,"mcpServerToolPrefix");function ee(s){let e=$(s);if(!e)return null;let t=$(e.ui)?.resourceUri,n=typeof t=="string"?t:e["ui/resourceUri"];return typeof n=="string"&&n.startsWith("ui://")?n:null}l(ee,"mcpAppResourceUri");function G(s){let e=$($(s)?.ui)?.visibility;return Array.isArray(e)?e.filter(t=>t==="model"||t==="app"):["model","app"]}l(G,"mcpAppVisibility");function U(s,e=!1){let t=$(s);if(!t)return Array.isArray(s)?{content:s,...e?{isError:e}:{}}:null;let n=Array.isArray(t.content)?t.content:[],r=$(t.structuredContent)??void 0,i=$(t._meta)??void 0;return!n.length&&!r&&!i?null:{content:n,...r?{structuredContent:r}:{},...i?{_meta:i}:{},...e||t.isError===!0?{isError:!0}:{}}}l(U,"mcpAppToolResult");var Hn=l(s=>s&&typeof s=="object"&&!Array.isArray(s)?s:{},"obj"),bt={CLAUDE_CODE_MCP_APPS_HOST:"1"},Bn=2e3,Wn=64;function Kn(s,e,t){let n=e.is_error===!0;if(t===1){let i=s.mcpMeta?{content:s.toolUseResult,...Hn(s.mcpMeta)}:s.toolUseResult,o=U(s.tool_use_result??i,n);if(o)return o}let r=Array.isArray(e.content)?e.content:typeof e.content=="string"?[{type:"text",text:e.content}]:[];return U({content:r},n)}l(Kn,"claudeToolResult");var ge=class{constructor(e,t){this.client=e;this.emit=t}static{l(this,"ClaudeMcpApps")}views=new Map;listed=new Map;known=new Set;calls=new Map;waiting=new Map;refreshing=null;refreshedAt=0;started=!1;start(){this.started=!0,this.refresh(!0)}stop(){this.started=!1,this.waiting.clear()}call(e,t,n){if(t.startsWith("mcp__"))return this.calls.set(e,{tool:t,arguments:n}),this.known.has(t)||this.refresh(),this.views.get(t)}result(e,t,n,r){let i=typeof n.tool_use_id=="string"?n.tool_use_id:"",o=this.calls.get(i);if(!o)return;this.calls.delete(i);let a=Kn(t,n,r);if(!a)return;let c={arguments:o.arguments,result:a},u=this.views.get(o.tool);if(u)return{app:u,appCall:c};this.known.has(o.tool)||!a.structuredContent||(this.waiting.set(i,{tool:o.tool,entry:e,call:c}),this.waiting.size>Wn&&this.waiting.delete(this.waiting.keys().next().value),this.refresh())}refresh(e=!1){return this.started?this.refreshing?this.refreshing:!e&&Date.now()-this.refreshedAt<Bn?Promise.resolve():(this.refreshedAt=Date.now(),this.refreshing=(async()=>{try{let t=await this.client().mcpServerStatus(),n=new Map,r=new Map,i=new Set;for(let o of t){let a=(o.tools??[]).map(c=>({name:c.name,resourceUri:ee(c._meta),visibility:G(c._meta)}));r.set(o.name,a);for(let c of a){let u=`${Pe(o.name)}${c.name}`;i.add(u),c.resourceUri&&n.set(u,{server:o.name,resourceUri:c.resourceUri})}}this.views=n,this.listed=r,this.known=i}catch{return}finally{this.refreshing=null}for(let[t,n]of this.waiting){let r=this.views.get(n.tool);r&&this.emit({type:"entry",entry:{...n.entry,app:r},appCall:n.call}),(r||this.known.has(n.tool))&&this.waiting.delete(t)}})(),this.refreshing):Promise.resolve()}async readResource(e,t){return this.client().readMcpResource(e,t)}async tools(e){return await this.refresh(!0),this.listed.get(e)??[]}async refreshMetadata(){await this.refreshing,await this.refresh(!0)}async callTool(e,t,n){let r=this.client();if(typeof r.request!="function")throw new Error("This Claude Code version cannot call MCP tools for a view");let i=await r.request({subtype:"mcp_call",tool:`${Pe(e)}${t}`,arguments:n});return U(i.response)??{content:[]}}};function vt(s,e){if(!(!s&&!e))return{...Object.fromEntries(Object.entries(e??{}).map(([t,n])=>[t,{type:"stdio",command:n.command,args:n.args,env:n.env,timeout:n.toolTimeoutMs}])),...Object.fromEntries(Object.entries(s??{}).map(([t,n])=>[t,{type:"http",url:n.url,headers:n.headers}]))}}l(vt,"claudeMcpServers");function kt(s,e){if(Array.isArray(s))for(let t of s){if(typeof t!="object"||t===null||t.id!==e)continue;let n=t.remedy;if(n?.kind!=="mcp_needs_auth"||!Array.isArray(n.servers))return;let r=n.servers.filter(i=>typeof i=="string"&&!!i);return r.length?{servers:r}:void 0}}l(kt,"claudeSignInRemedy");var Vn=15*6e4,Gn={connected:"connected",failed:"failed","needs-auth":"needs-sign-in",pending:"connecting",disabled:"disabled"};function Ne(s,e){let t=s.source==="claudeai"||s.scope==="claudeai"||s.config?.type==="claudeai-proxy",n=typeof e!="function"?{available:!1,reason:"This Claude Code version cannot start an MCP sign-in."}:t||s.status==="needs-auth"?{available:!0}:{available:!1,reason:`Claude Code has not reported a browser sign-in requirement for ${s.name}. The provider must establish its authentication method first.`};return{server:s.name,label:K(s.name),kind:t?"connector":"server",status:Gn[s.status]??"unknown",signIn:n,...s.status==="failed"&&s.error?{error:s.error}:{}}}l(Ne,"signInState");function St(s,e){let t=new Map,n=l(o=>Date.now()-(t.get(o)??0)<Vn,"waiting"),r=l(()=>s().mcpAuthenticate,"authenticate"),i=l(async o=>{let a=(await s().mcpServerStatus()).filter(u=>!e().has(u.name)).map(u=>({server:u.name,label:K(u.name),status:u})),c=mt(a,o);if(!c)throw new Error(`Claude Code has no MCP server named ${o}`);return c.status},"find");return{state:l(async(o,a)=>{let c=await i(o);c.status==="connected"&&t.delete(c.name);let u=c.status==="needs-auth"||c.status==="failed";return a?.reconnect&&u&&!n(c.name)&&(await s().reconnectMcpServer(c.name).catch(()=>{}),c=await i(c.name)),Ne(c,r())},"state"),start:l(async o=>{let a=await i(o),c=s(),u=r(),d=Ne(a,u);if(d.status==="connected")return{state:d};let f=de(d);if(f||!u)throw new Error(f??"Claude Code offers no browser sign-in");let p=await u.call(c,a.name);return p?.callbackExpected&&t.set(a.name,Date.now()),{...p?.authUrl?{url:p.authUrl}:{},state:Ne(await i(a.name),u)}},"start")}}l(St,"claudeMcpSignIn");var xt=/^claude-([a-z]+)-(\d+(?:-\d{1,2})?)(?:-\d{8})?(?:\[\d+[mk]\])?$/i;function Et(s,e){let t=s.resolvedModel?.match(xt);if(!t)return s.displayName;let[,n,r]=t,i=r.replace("-","."),o=s.displayName.slice(0,n.length),a=s.displayName.slice(n.length);if(o.toLowerCase()===n.toLowerCase()&&/^(?:$|[\s(])/.test(a))return/^\s*\d/.test(a)?s.displayName:`${o} ${i}${a}`;let c=n[0].toUpperCase()+n.slice(1).toLowerCase();return s.value!=="default"?`${s.displayName.replace(/\s*\([^)]*\)$/,"")} (${c} ${i})`:e.some(d=>{let f=d.resolvedModel?.match(xt);return d.value!==s.value&&f?.[1].toLowerCase()===n.toLowerCase()&&f[2]===r})?`${c} ${i} (default)`:`${c} ${i}`}l(Et,"claudeModelName");import{randomUUID as oa}from"node:crypto";import{appendFile as Qn,mkdir as Yn,readdir as Zn,readFile as ca,rm as la,stat as er,writeFile as ua}from"node:fs/promises";import tr from"node:os";import te from"node:path";import{forkSession as nr,getSessionMessages as rr}from"@anthropic-ai/claude-agent-sdk";import{createReadStream as zn}from"node:fs";var Xn=16*1024*1024,Jn=1e5;function _t(s){try{let e=JSON.parse(s.toString("utf8"));return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}l(_t,"parseLine");async function At(s,e={}){let t=e.maxRecords??Jn,n=[],r=[],i=[],o=0,a=0,c=0;for await(let u of zn(s,{highWaterMark:64*1024})){let d=Buffer.isBuffer(u)?u:Buffer.from(u),f=0;for(;f<d.length;){let p=d.indexOf(10,f),g=p<0?d.length:p,w=d.subarray(f,g);if(a?a+=w.length:o+w.length>Xn?(a=o+w.length,i=[],o=0):w.length&&(i.push(w),o+=w.length),p<0)break;if(c++,a){if(n.length+r.length>=t)return{status:"limit"};r.push({line:c,byteLength:a})}else if(o){let h=i.length===1?i[0]:Buffer.concat(i,o);if(h.toString("utf8").trim()){if(n.length+r.length>=t)return{status:"limit"};let E=_t(h);if(E)n.push(E);else if(e.skipInvalid)r.push({line:c,byteLength:o});else return{status:"invalid"}}}i=[],o=0,a=0,f=p+1}}if(a){if(n.length+r.length>=t)return{status:"limit"};r.push({line:++c,byteLength:a})}if(o){let u=i.length===1?i[0]:Buffer.concat(i,o);if(u.toString("utf8").trim()){if(n.length+r.length>=t)return{status:"limit"};let d=_t(u);if(d)n.push(d);else if(e.skipInvalid)r.push({line:c+1,byteLength:o});else return{status:"invalid"}}}return{status:"ready",records:n,skipped:r}}l(At,"readJsonlObjects");function he(s=process.env){return s.CLAUDE_CONFIG_DIR||te.join(tr.homedir(),".claude")}l(he,"defaultClaudeHome");async function sr(s,e,t){let n=te.join(s,"projects"),r;try{r=(await Zn(n,{withFileTypes:!0})).filter(o=>o.isDirectory()).map(o=>o.name).sort()}catch{return null}let i=t&&r.includes(t)?[t]:[];for(let o of[...i,...r.filter(a=>a!==t)]){let a=te.join(n,o,`${e}.jsonl`);try{if((await er(a)).size>0)return a}catch{}}return null}l(sr,"sessionFile");function Tt(s){return{async load(e){let t=e.subpath?null:await sr(s,e.sessionId,e.projectKey);if(!t)return null;let n=await At(t,{skipInvalid:!0,maxRecords:Number.POSITIVE_INFINITY});return n.status!=="ready"?null:n.records.filter(r=>typeof r.type=="string")},async append(e,t){let n=te.join(s,"projects",e.projectKey);await Yn(n,{recursive:!0,mode:448}),await Qn(te.join(n,`${e.sessionId}.jsonl`),t.map(r=>`${JSON.stringify(r)}
2
+ `).join(""),{mode:384})}}}l(Tt,"homeSessionStore");async function Le(s,e,t){let n=typeof s=="string"?Tt(s):s,r=await rr(e,{dir:t,sessionStore:n});if(!r.length)throw new q("Claude",e);return r}l(Le,"readClaudeSessionFrames");async function Ct(s,e,t){return(await nr(e,{dir:t,sessionStore:Tt(s)})).sessionId}l(Ct,"forkClaudeSession");import{readFileSync as lr}from"node:fs";import qe from"node:path";var ir=/^\s*#\s*farero:\s*handoff\b/i,or=[/^gh\s+auth\s+(login|refresh)\b/,/^shopify\b.*\b(auth|login)\b/,/^(npm|pnpm)\s+(login|adduser)\b/,/^yarn\s+npm\s+login\b/,/^(firebase|vercel|netlify|heroku|railway|supabase|stripe|wrangler|sanity|eas|expo|doppler)\s+login\b/,/^(fly|flyctl|turso)\s+auth\s+login\b/,/^gcloud\s+(auth\s+(application-default\s+)?login|init)\b/,/^az\s+login\b/,/^aws\s+(sso\s+login|configure)\b/,/^doctl\s+auth\s+init\b/,/^docker\s+login\b(?!.*--password-stdin)/,/^(op\s+signin|vault\s+login)\b/,/^sudo\s+(?!(-[a-zA-Z]*[nS]|--non-interactive|--stdin)\b)/],ar=/^(?:(?:[A-Za-z_][A-Za-z0-9_]*=\S*|env|command|exec|time|npx(?:\s+-y|\s+--yes)?|bunx|(?:pnpm|yarn)\s+(?:dlx|exec))\s+)+/;function cr(s){let e=[],t=[],n="",r;for(let i=0;i<s.length;i++){let o=s[i];if(o==="\\"&&r!=="'")n+=s.slice(i,i+2),i++;else if(r)o===r&&(r=void 0),n+=o;else if(o==="'"||o==='"')r=o,n+=o;else if(o==="<"&&s[i+1]==="<"&&s[i+2]!=="<"){let a=/^<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\1/.exec(s.slice(i));a&&t.push(a[2]),n+=o}else if(o===`
3
+ `&&t.length){e.push(n),n="";let a=i+1;for(let c of t.splice(0))for(;;){let u=s.indexOf(`
4
+ `,a),d=s.slice(a,u<0?s.length:u);if(a=u<0?s.length:u+1,u<0||d.replace(/^\t+/,"")===c)break}i=a-1}else"\n;&|(`".includes(o)||o==="$"&&s[i+1]==="("?(e.push(n),n=""):n+=o}return e.push(n),e.map(i=>i.trim().replace(ar,"")).filter(Boolean)}l(cr,"simpleCommands");function De(s){return ir.test(s.split(`
5
+ `,1)[0])?!0:cr(s).some(e=>or.some(t=>t.test(e)))}l(De,"needsPerson");var ur=6e5;function dr(s){try{let e=JSON.parse(lr(s,"utf8"))?.permissions,t=e?.deny??[],n=e?.ask??[];if(!Array.isArray(t)||!Array.isArray(n))return null;let r=[...t,...n];return r.every(i=>typeof i=="string")?r:null}catch(e){return e.code==="ENOENT"?[]:null}}l(dr,"rules");function pr(s,e,t){let n=["/Library/Application Support/ClaudeCode/managed-settings.json",qe.join(e,"settings.json"),...t.flatMap(i=>[qe.join(i,".claude/settings.json"),qe.join(i,".claude/settings.local.json")])],r=l(i=>/^bash\b/i.test(i.trim()),"restrictsBash");return s.some(r)||n.some(i=>{let o=dr(i);return o===null||o.some(r)})}l(pr,"hasBashRule");function Rt(s){return[{matcher:"Bash",hooks:[async e=>{if(e.hook_event_name!=="PreToolUse"||e.permission_mode!=="bypassPermissions")return{};let t=e.tool_input&&typeof e.tool_input=="object"?e.tool_input:{};if(typeof t.command!="string"||!De(t.command))return{};if(pr(s.disallowedTools,s.configDir,[...new Set([s.cwd,e.cwd])]))return{};let n=await s.prepare(t.command).catch(r=>{console.warn("Terminal handoff unavailable; the command runs in the agent shell:",r)});return n?{hookSpecificOutput:{hookEventName:"PreToolUse",updatedInput:{...t,command:n,timeout:ur}}}:{}}]}]}l(Rt,"claudeTerminalHandoffHooks");var fr={now:Date.now,setTimeout:l((s,e)=>setTimeout(s,e).unref(),"setTimeout"),clearTimeout:l(s=>clearTimeout(s),"clearTimeout")},me=class{static{l(this,"DraftRows")}rows=new Map;ended=new Set;emit;interval;clock;cadence;closed=!1;constructor(e){this.emit=e.emit,this.interval=e.intervalMs??80,this.clock=e.clock??fr,this.cadence=process.env.FARERO_DRAFT_CADENCE==="1"?e.onCadence:void 0}update(e){if(this.closed||this.ended.has(e.id))return;let t=this.clock.now(),n=this.rows.get(e.id);if(n?(n.entry=e,n.pending=!0):(n={entry:e,pending:!0,emittedAt:Number.NEGATIVE_INFINITY,timer:void 0},this.cadence&&(n.times=[]),this.rows.set(e.id,n)),n.times?.push(t),n.timer!==void 0)return;let r=n.emittedAt+this.interval-t;r<=0?this.send(n):n.timer=this.schedule(n,r)}flush(e){for(let t of this.select(e))this.cancel(t),this.send(t)}settle(e){let t=this.rows.get(e);t&&(this.end(t),this.sample(t,"settled"))}abandon(e){for(let t of this.select(e))this.end(t),this.emit({...t.entry,draft:!0,aborted:!0}),this.sample(t,"abandoned")}dispose(){this.closed=!0;for(let e of this.rows.values())this.cancel(e);this.rows.clear()}select(e){if(e===void 0)return[...this.rows.values()];let t=this.rows.get(e);return t?[t]:[]}schedule(e,t){return this.clock.setTimeout(()=>{e.timer=void 0,this.rows.get(e.entry.id)===e&&this.send(e)},t)}cancel(e){e.timer!==void 0&&(this.clock.clearTimeout(e.timer),e.timer=void 0)}send(e){e.pending&&(e.pending=!1,e.emittedAt=this.clock.now(),this.emit(e.entry))}end(e){this.cancel(e),this.rows.delete(e.entry.id),this.ended.add(e.entry.id),this.ended.size>256&&this.ended.delete(this.ended.values().next().value)}sample(e,t){let n=e.times;if(!this.cadence||!n?.length)return;let r=n.slice(1).map((i,o)=>i-n[o]).sort((i,o)=>i-o);this.cadence({tool:e.entry.tool??"",outcome:t,updates:n.length,bytes:Buffer.byteLength(e.entry.output??""),first:n[0],last:n[n.length-1],medianGapMs:Ot(r,.5),p95GapMs:Ot(r,.95),maxGapMs:r.at(-1)??0})}};function Ot(s,e){return s.length?s[Math.ceil(e*s.length)-1]:0}l(Ot,"rank");var It={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
6
+ `,r:"\r",t:" "},gr=/^[0-9a-fA-F]{4}$/,Mt=l(s=>s===32||s===10||s===13||s===9,"isSpace"),hr=l(s=>s>=55296&&s<=56319,"isHighSurrogate"),ye=class{static{l(this,"PartialInput")}fields=new Map;state="start";key="";target=null;escaping=!1;hex=null;depth=0;quoted=!1;push(e){let t=[],n=0;for(;n<e.length&&this.state!=="done"&&this.state!=="failed";){if(this.state==="name"||this.state==="string"){n=this.readString(e,n,t);continue}if(this.state==="skip"){n=this.skip(e,n);continue}let r=e.charCodeAt(n++);if(this.state==="scalar"){r===44?this.state="key":r===125?this.state="done":Mt(r)&&(this.state="next");continue}Mt(r)||(this.state==="start"?this.state=r===123?"key":"failed":this.state==="key"?(this.key="",this.state=r===34?"name":r===125?"done":"failed"):this.state==="colon"?this.state=r===58?"value":"failed":this.state==="value"?this.value(r):this.state=r===44?"key":r===125?"done":"failed")}return t}field(e){let t=this.fields.get(e);return t&&{text:t.text,complete:t.complete}}get done(){return this.state==="done"}get failed(){return this.state==="failed"}value(e){if(e===34){if(this.fields.has(this.key)){this.quoted=!0,this.depth=0,this.state="skip";return}this.target={text:"",complete:!1,held:""},this.fields.set(this.key,this.target),this.state="string"}else e===123||e===91?(this.depth=1,this.quoted=!1,this.state="skip"):e===125||e===93||e===44||e===58?this.state="failed":this.state="scalar"}skip(e,t){let n=t;for(;n<e.length;){let r=e.charCodeAt(n++);if(this.quoted){if(this.escaping)this.escaping=!1;else if(r===92)this.escaping=!0;else if(r===34&&(this.quoted=!1,this.depth===0))return this.state="next",n}else if(r===34)this.quoted=!0;else if(r===123||r===91)this.depth++;else if((r===125||r===93)&&(this.depth--,this.depth===0))return this.state="next",n}return n}readString(e,t,n){let r=t,i=r,o="",a=!1,c=!1;for(;r<e.length;){if(this.hex!==null){for(;this.hex.length<4&&r<e.length;)this.hex+=e[r++];if(i=r,this.hex.length<4)break;if(!gr.test(this.hex)){c=!0;break}o+=String.fromCharCode(Number.parseInt(this.hex,16)),this.hex=null;continue}if(this.escaping){let d=e[r++];if(i=r,this.escaping=!1,d==="u")this.hex="";else if(Object.hasOwn(It,d))o+=It[d];else{c=!0;break}continue}let u=e.charCodeAt(r);if(u===34||u===92){if(o+=e.slice(i,r),r++,i=r,u===34){a=!0;break}this.escaping=!0;continue}r++}if(!a&&!c&&(o+=e.slice(i,r)),this.state==="name")this.key+=o,a&&(this.state="colon");else if(this.target){let u=this.target,d=u.held+o;u.held="",!a&&!c&&d&&hr(d.charCodeAt(d.length-1))&&(u.held=d.slice(-1),d=d.slice(0,-1)),u.text+=d,a&&(u.complete=!0,this.target=null,this.state="next"),(d||a)&&n.push({name:this.key,added:d,complete:a})}return c&&(this.state="failed"),r}};var mr=new Map([["Edit",new Map([["file_path","path"],["old_string","before"],["new_string","after"]])],["Write",new Map([["file_path","path"],["content","after"]])],["NotebookEdit",new Map([["notebook_path","path"],["new_source","after"]])],["edit",new Map([["path","path"],["filePath","path"],["oldString","before"],["newString","after"]])],["write",new Map([["path","path"],["filePath","path"],["content","after"]])],["patch",new Map([["patchText","patch"]])]]),yr=/^\*\*\* (?:Add|Update|Delete) File: (.+?)\r?$/,$e=class{constructor(e){this.roles=e}static{l(this,"EditDraft")}input=new ye;draft="";named=[];mark="";open=!1;header="";push(e){for(let t of this.input.push(e)){let n=this.roles.get(t.name);n==="path"?t.complete&&this.name(this.input.field(t.name)?.text??""):n==="patch"?(this.draft+=t.added,this.scan(t.added,t.complete)):n&&this.lines(n==="before"?"-":"+",t.added)}}get text(){return this.draft}get paths(){return this.named}lines(e,t){if(!t)return;let n="";e!==this.mark&&this.open&&(n=`
7
+ `,this.open=!1),this.mark=e;let r=0;for(;;){let i=t.indexOf(`
8
+ `,r),o=i<0?t.length:i;if((o>r||i>=0)&&(this.open||(n+=e),n+=t.slice(r,o),this.open=!0),i<0)break;n+=`
9
+ `,this.open=!1,r=i+1}this.draft+=n}scan(e,t){let n=0;for(;;){let r=e.indexOf(`
10
+ `,n),i=e.slice(n,r<0?e.length:r);if(this.header===""&&i&&i[0]!=="*"?this.header=null:this.header!==null&&(this.header+=i),r<0)break;this.endLine(),n=r+1}t&&this.endLine()}endLine(){let e=this.header?.match(yr)?.[1];e&&this.name(e),this.header=""}name(e){e&&!this.named.includes(e)&&this.named.push(e)}};function Pt(s){let e=mr.get(s);return e&&new $e(e)}l(Pt,"editDraft");function Ue(s){if(!s)return[];let e=s.split(`
11
+ `);return e.at(-1)===""&&e.pop(),e}l(Ue,"lines");function wr(s,e){let t=0;for(;t<s.length&&t<e.length&&s[t]===e[t];)t++;let n=0;for(;n<s.length-t&&n<e.length-t&&s[s.length-1-n]===e[e.length-1-n];)n++;let r=s.slice(t,s.length-n),i=e.slice(t,e.length-n),o=[],a=i.length+1;if((r.length+1)*a>1e6){for(let c of r)o.push({mark:"-",line:c});for(let c of i)o.push({mark:"+",line:c})}else{let c=new Uint16Array((r.length+1)*a);for(let f=r.length-1;f>=0;f--)for(let p=i.length-1;p>=0;p--)c[f*a+p]=r[f]===i[p]?c[(f+1)*a+p+1]+1:Math.max(c[(f+1)*a+p],c[f*a+p+1]);let u=0,d=0;for(;u<r.length||d<i.length;)u<r.length&&d<i.length&&r[u]===i[d]?(o.push({mark:" ",line:r[u]}),u++,d++):d===i.length||u<r.length&&c[(u+1)*a+d]>=c[u*a+d+1]?(o.push({mark:"-",line:r[u]}),u++):(o.push({mark:"+",line:i[d]}),d++)}return[...s.slice(0,t).map(c=>({mark:" ",line:c})),...o,...s.slice(s.length-n).map(c=>({mark:" ",line:c}))]}l(wr,"operations");function br(s){let{old_string:e,new_string:t}=s;if(typeof e!="string"||typeof t!="string"||e===t)return;let n=wr(Ue(e),Ue(t)),r=[];for(let[d,f]of n.entries()){if(f.mark===" ")continue;let p=Math.max(0,d-3),g=Math.min(n.length,d+3+1),w=r.at(-1);w&&p<=w[1]?w[1]=g:r.push([p,g])}if(!r.length)return;let i=[],o=1,a=1,c=0;for(let[d,f]of r){for(;c<d;c++)n[c].mark!=="+"&&o++,n[c].mark!=="-"&&a++;let p=n.slice(d,f),g=p.filter(h=>h.mark!=="+").length,w=p.filter(h=>h.mark!=="-").length;i.push(`@@ -${g?o:o-1},${g} +${w?a:a-1},${w} @@`,...p.map(h=>h.mark+h.line))}return[...s.replace_all===!0?["Replaced every occurrence in the file."]:[],...i].join(`
12
+ `)}l(br,"editPatch");function Lt(s){if(typeof s!="string")return;let e=Ue(s);if(e.length)return[`@@ -0,0 +1,${e.length} @@`,...e.map(t=>`+${t}`)].join(`
13
+ `)}l(Lt,"addedPatch");function vr(s){return s.edit_mode==="delete"?void 0:Lt(s.new_source)}l(vr,"notebookPatch");var Nt={Edit:br,Write:l(s=>Lt(s.content),"Write"),NotebookEdit:vr};function Dt(s,e){let t=Object.hasOwn(Nt,s)?Nt[s]:void 0;return t&&{patch:t(e),excerpt:s!=="Write"}}l(Dt,"callPatch");async function we(s,e,t){if(!s)return;let n=Date.now()+e;await Promise.all(Object.keys(s).map(async r=>{let i=`not connected after ${e/1e3} s`;for(let o=100;;o=Math.min(o*2,1e3)){let a=n-Date.now();if(a<=0)break;let c=await new Promise(u=>{let d=setTimeout(()=>u("pending"),a);t(r,a).then(u,f=>u({failed:f instanceof Error?f.message:String(f)})).finally(()=>clearTimeout(d))});if(c==="connected")return;if(c!=="pending"){i=c.failed;break}await new Promise(u=>setTimeout(u,Math.min(o,a)))}throw new Error(`MCP server ${r} is unavailable (${i}); refusing a thread without host tools`)}))}l(we,"verifyInjectedMcpServers");function be(s){if(!Array.isArray(s))return{};let e=[],t={},n={};for(let r of s){if(typeof r=="string"){e.push(r);continue}let i=r!==null&&typeof r=="object"?r:{},o=typeof i.label=="string"?i.label:"";e.push(o);let a=typeof i.description=="string"?i.description.trim():"";o&&a&&(t[o]=a);let c=typeof i.preview=="string"?i.preview.replace(/^(?:[ \t]*\n)+/,"").trimEnd():"";o&&c&&(n[o]=c)}return{options:e,...Object.keys(t).length?{optionDescriptions:t}:{},...Object.keys(n).length?{optionPreviews:n}:{}}}l(be,"questionOptions");function ve(s){let e=typeof s=="string"?s.trim():"";return e?{header:e}:{}}l(ve,"questionHeader");function ne(s,e,t){let n=/^\[(Decision|Information)\]\s+/.exec(s),r=n?n[1]==="Decision"?"decision":"information":void 0,i=n?s.slice(n[0].length):s;if(!e)return{question:i,...r?{purpose:r}:{}};let o=e.filter(c=>/(?:^|\s)\(\s*recommended\s*\)/i.test(c)),a=r!=="information"&&o.length===1;return{question:i,options:e,...t&&Object.keys(t).length?{optionDescriptions:t}:{},...r?{purpose:r}:{},...a?{recommendedOption:o[0]}:{}}}l(ne,"questionPresentation");function qt(s,e){return JSON.stringify(["request_user_input_async",s,e])}l(qt,"codexAsyncQuestionId");function $t(s){return`codex-async-question:${s}`}l($t,"codexAsyncQuestionInteractionId");var z=l(s=>typeof s=="string"?s:"","str");function kr(s){return Q(z(s.command))||z(s.file_path)||z(s.filePath)||z(s.pattern)||z(s.path)||z(s.url)||void 0}l(kr,"primaryToolInput");function Ut(s,e){return e||kr(s)||JSON.stringify(s)}l(Ut,"toolDetail");var A=l(s=>s&&typeof s=="object"&&!Array.isArray(s)?s:{},"obj"),y=l(s=>typeof s=="string"?s:"","str"),Or={CLAUDE_CODE_EXPERIMENTAL_CODE_MODE:"1"};function Ir(s){let e={};for(let[t,n]of Object.entries(pt))s?.[t]&&(e[n]="1");return e}l(Ir,"claudeFeatureEnv");function Mr(s,e,t){if(!s)throw new Error("A Claude chat with MCP servers needs a private config directory");xr(s,{recursive:!0,mode:448});let n=Tr.join(s,`${e}.${Sr(6).toString("hex")}.json`);return Ar(n,JSON.stringify({mcpServers:t}),{mode:384}),n}l(Mr,"writeMcpConfig");var Pr=l(s=>{let e=A(A(s).message).content;return Array.isArray(e)?e.flatMap(t=>A(t).type==="tool_result"?[y(A(t).tool_use_id)]:[]):[]},"answeredCalls");function Ft({call:s,patch:e,excerpt:t,shown:n}){return n==="plain"?s:{...s,...e===void 0?{}:{output:e,...t?{diffExcerpt:!0}:{}},diff:!0,draft:!0,...n==="aborted"?{aborted:!0,running:!1}:{}}}l(Ft,"editCallRow");var jt="Claude\u2019s sign-in has ended. Sign in again to continue.",Nr=new Set(["[Request interrupted by user]","[Request interrupted by user for tool use]"]),Fe=class{static{l(this,"InputStream")}values=[];wake=null;ended=!1;push(e){if(this.ended)throw new Error("Claude input is closed");this.values.push(e),this.wake?.()}close(){this.ended=!0,this.wake?.()}async*[Symbol.asyncIterator](){for(;!this.ended;){let e=this.values.shift();e?yield e:await new Promise(t=>{this.wake=t})}}},re=class{static{l(this,"NativeClaudeDriver")}backgroundTasks=new Map;provider="claude";capabilities={liveness:!0,steer:!0,fork:!0,approvals:!0,questions:!0,images:!0,plan:!0,fast:!0,efforts:["low","medium","high","xhigh","max"],replayIdentity:!0};emit;liveInteractions;options=null;mcpConfigFile;stream=new Fe;running=null;loop=null;threadId=null;closing=!1;turnId=null;unconsumed=new Set;stopping=!1;ownReply=!1;turnEnds=[];signedOut=!1;compactLimit;requests=new Map;agentLabels=new Map;harnessMode="bypassPermissions";replies=new Map;writing=new Map;drafts=new me({emit:l(e=>this.emit({type:"entry",entry:e}),"emit"),onCadence:l(e=>this.emit({type:"raw",method:"host/draft.cadence",payload:{provider:"claude",...e}}),"onCadence")});tasks=new Map;skillCompanions=[];edits=new Map;answered=new Set;replaying=!1;blockOffsets=new Map;receipts=new Map;receiptCheckTimer;receiptCheck;receiptCheckAttempts=0;mcpApps;mcpSignIn;host;sandbox;constructor(e,{host:t,sandbox:n}){this.host=t,this.sandbox=n,n&&(this.capabilities.fork=!1);let r=fe(i=>e(this.replaying&&i.type==="entry"?{...i,history:!0}:i));this.emit=r.emit,this.liveInteractions=r.read,this.mcpApps=new ge(()=>this.client(),i=>this.emit(i)),n||(this.mcpSignIn=St(()=>this.client(),()=>new Set(Object.keys(this.options?.mcpServers??{}))))}async connect(e){if(this.running)throw new Error("Claude driver is already connected");if(e.agent.effort&&!this.capabilities.efforts.includes(e.agent.effort))throw new Error("Unsupported Claude effort");this.sandbox&&await this.sandbox.prepare(e),this.options=e,this.closing=!1,this.compactLimit=void 0,this.threadId=e.threadId??ke();let t=this.sandbox?{}:ue("claude",e.account?.home);if(this.edits.clear(),this.answered=new Set,this.replies.clear(),this.tasks.clear(),e.threadId){let v=this.sandbox?.sessionStore??e.account?.home??he(),S=await Le(v,e.threadId,e.cwd);this.answered=new Set(S.flatMap(Pr)),this.replaying=!0;try{for(let _ of S)this.message(_)}finally{this.replaying=!1}}let n=e.harness?.claude;this.harnessMode=e.agent.questionOnly?"default":n?.permissionMode??"bypassPermissions";let r=e.agent.plan?"plan":this.harnessMode,i=e.agent.questionOnly?void 0:e.mcpServers,o=e.agent.questionOnly||this.sandbox?void 0:e.localMcpServers,a=e.delegated===!0,c=[...new Set([...n?.disallowedTools??[],...e.agent.readOnly?gt:[],...a?["AskUserQuestion"]:[]])],u=l(v=>c.some(S=>S.toLowerCase()===v.toLowerCase()),"isDisallowed"),d=l(()=>{try{return e.declineSafetyChecks?.()===!0}catch(v){return console.warn("Claude safety check setting unreadable; showing the request:",v),!1}},"declinesSafetyChecks"),f=e.agent.toolFree||e.agent.questionOnly?[]:["WebSearch","WebFetch"].filter(v=>!u(v)),p=[...new Set([...n?.allowedTools??[],...f.filter(v=>!(n?.allowedTools??[]).some(S=>S.toLowerCase()===v.toLowerCase()))])],g=e.terminalHandoff&&!this.sandbox&&!e.agent.questionOnly&&!e.agent.toolFree?e.terminalHandoff:void 0,w=this.sandbox?{resolved:"claude",unmet:void 0}:this.host.launch("claude",n);if(!w.resolved)throw this.host.notInstalled("claude",n?.runtime?.source??"bundled",w.unmet);let h=vt(i,o),E=this.sandbox?this.sandbox.mcpConfigPath:h?Mr(e.mcpConfigDir,this.threadId,h):void 0;if(h&&!E)throw new Error("Claude needs a private MCP config file for this chat; the host did not provide one");this.mcpConfigFile=this.sandbox?void 0:E;let I={persistSession:!e.catalogOnly,spawnClaudeCodeProcess:e.spawn?v=>{let S=this.sandbox?this.sandbox.spawn(e,v.args):e.spawn(v.command,v.args,v.cwd??e.cwd,{...v.env,...t});S.stderr.resume();let _=l(()=>{S.kill("SIGTERM")},"abort");return v.signal.addEventListener("abort",_,{once:!0}),S.once("close",()=>v.signal.removeEventListener("abort",_)),v.signal.aborted&&_(),S}:void 0,cwd:e.cwd,env:this.sandbox?{}:{...this.host.environment({provider:"claude",workspaceEnv:e.workspaceEnv,accountHome:e.account?.home,envKeys:n?.envKeys}),...bt,...Ir(n),...e.codeMode?Or:{}},...this.sandbox||n?.runtime?.source&&n.runtime.source!=="bundled"?{pathToClaudeCodeExecutable:w.resolved}:{},...e.threadId?{resume:e.threadId}:{sessionId:this.threadId},model:e.agent.model,effort:e.agent.effort,settings:{fastMode:e.agent.fast??!1,...typeof n?.skillListingBudgetFraction=="number"?{skillListingBudgetFraction:n.skillListingBudgetFraction}:{},...typeof n?.skillListingMaxDescChars=="number"?{skillListingMaxDescChars:n.skillListingMaxDescChars}:{},...typeof n?.thinkingSummaries=="boolean"?{showThinkingSummaries:n.thinkingSummaries}:{}},permissionMode:r,allowDangerouslySkipPermissions:this.harnessMode==="bypassPermissions",includePartialMessages:!0,...n?.promptSuggestions?{promptSuggestions:!0}:{},extraArgs:{"replay-user-messages":null,...E?{"mcp-config":E}:{}},settingSources:e.agent.questionOnly?[]:n?.settingSources??["user","project","local"],...e.agent.questionOnly?{tools:["AskUserQuestion"],allowedTools:[],strictMcpConfig:!0}:n?.allowedTools?.length||p.length?{allowedTools:p}:{},...c.length?{disallowedTools:c}:{},...g?{hooks:{PreToolUse:Rt({prepare:l(v=>g.prepare(v),"prepare"),disallowedTools:c,configDir:e.account?.home??he(),cwd:e.cwd})}}:{},...n?.additionalDirectories?.length?{additionalDirectories:[...n.additionalDirectories]}:{},...typeof n?.maxTurns=="number"?{maxTurns:n.maxTurns}:{},systemPrompt:{type:"preset",preset:"claude_code",...e.instructions?{append:e.instructions}:{}},canUseTool:l(async(v,S,_)=>{if(v==="AskUserQuestion"&&a)return{behavior:"deny",message:B};if(e.agent.toolFree)return{behavior:"deny",message:"Side questions are answer-only"};if(e.agent.questionOnly&&v!=="AskUserQuestion")return{behavior:"deny",message:"This side chat may only ask user questions."};if((v==="WebSearch"||v==="WebFetch")&&!u(v))return{behavior:"allow",updatedInput:S};let k=_;if(!(v==="AskUserQuestion"||v==="ExitPlanMode"||_.matchedAskRule!==void 0||k.requiresUserInteraction===!0||k.decisionReasonType==="rule"||k.decisionReasonType==="hook")&&ft(e.agent.plan?"plan":this.harnessMode)&&d()){let L=_.decisionReason?.trim();return{behavior:"deny",message:`Farero declined this request automatically. No person reviewed it.${L?` Reason: ${L}`:""}`}}let R=ke(),O=v==="AskUserQuestion",M=!O&&v!=="ExitPlanMode"&&!_.suppressAlwaysAllowRule&&_.suggestions?.length?_.suggestions.map(L=>({...L,destination:"session"})):void 0,J=_.agentID?{id:_.agentID,label:this.agentLabels.get(_.agentID)??"Subagent"}:void 0;return new Promise(L=>{this.requests.set(R,{tool:v,input:S,resolve:L,question:O,sessionRules:M});let nt=l(()=>{this.requests.delete(R)&&(L({behavior:"deny",message:"Interaction cancelled"}),this.emit({type:"interaction-resolved",id:R}),this.publishActivity())},"cancel");if(_.signal.addEventListener("abort",nt,{once:!0}),_.signal.aborted){nt();return}this.emit({type:"interaction",interaction:{id:R,kind:O?"question":"approval",method:v,...J?{agent:J}:{},title:_.title??(O?"Question from Claude":`Claude requests ${v}`),body:O?"":_.decisionReason??JSON.stringify(S,null,2),decisions:O?void 0:M?["accept","acceptForSession","decline"]:["accept","decline"],...M?{decisionLabels:{acceptForSession:"Allow for this session"}}:{},questions:O&&Array.isArray(S.questions)?S.questions.map((le,wn)=>{let Ae=be(A(le).options),bn=ne(y(A(le).question),Ae.options,Ae.optionDescriptions);return{id:String(wn),...ve(A(le).header),multiple:A(le).multiSelect===!0,...Ae,...bn}}):void 0,providerData:S}}),this.emit({type:"status",status:"waiting",turnId:this.turnId})})},"canUseTool")},T=Rr({prompt:this.stream,options:I});this.running=T,this.loop=this.consume(T);try{let v=await T.initializationResult();if(e.agent.fast&&v.fast_mode_state!=="on"&&v.fast_mode_state!=="cooldown")throw new Error(`Claude Fast mode is unavailable (${v.fast_mode_disabled_reason??"not confirmed by the runtime"}). Turn Fast off or retry after availability changes.`);e.agent.fast&&v.fast_mode_state==="cooldown"&&this.emit({type:"entry",entry:{id:`fast-cooldown-${this.threadId}`,role:"system",text:"Claude Fast mode is cooling down; this turn may use standard speed.",ts:new Date().toISOString()}}),e.catalogOnly||(this.emit({type:"thread",threadId:this.threadId}),this.readCompactLimit(T)),await(this.sandbox?this.sandbox.verifyMcp(i??{}):we(i,this.host.mcpStartupMs,S=>this.injectedMcpState(T,S))),!e.catalogOnly&&!this.sandbox&&this.mcpApps.start(),this.emit({type:"status",status:"idle",error:null})}catch(v){throw await this.close(),v}}message(e){let t=this.replaying,n=A(e),r=A(n.message),i=y(r.id)||y(n.uuid),o=y(n.timestamp)||new Date().toISOString(),a=typeof n.parent_tool_use_id=="string"?{parentToolUseId:n.parent_tool_use_id}:{};if(typeof r.content=="string"){if(D(r.content)||W(r.content))return;this.emit({type:"entry",entry:{id:i,role:n.type==="user"?"user":"assistant",text:r.content,ts:o,...a}});return}if(!Array.isArray(r.content))return;if(n.type==="assistant"&&n.error==="authentication_failed"){this.emit({type:"entry",entry:{id:`${i}:0`,role:"system",text:jt,ts:o}});return}if(n.type==="user"&&!r.content.some(d=>A(d).type==="tool_result")){let d=r.content.map(f=>y(A(f).text)).filter(Boolean).join(`
14
+ `);if(!d.trim()||D(d)||W(d))return;if(n.isMeta===!0||n.isSynthetic===!0){let f=n.isMeta===!0?y(n.sourceToolUseID):this.skillCompanions.shift()??"";f&&this.emit({type:"entry",entry:{id:y(n.uuid)||`${f}:injected`,role:"tool",text:"",toolUseId:f,output:d,ts:o,...a}});return}if(Nr.has(d)){this.emit({type:"entry",entry:{id:y(n.uuid),role:"system",text:"Stopped",ts:o,...a}});return}this.emit({type:"entry",entry:{id:y(n.uuid),role:"user",text:d,ts:o,...a}});return}n.type==="assistant"&&(this.skillCompanions.length=0);let c=0;if(n.type==="assistant"){let d=this.blockOffsets.get(i);d||(d={next:0,frames:new Map},this.blockOffsets.set(i,d));let f=y(n.uuid)||i,p=d.frames.get(f);p!==void 0?c=p:(c=d.next,d.frames.set(f,c),d.next+=r.content.length)}let u=r.content.filter(d=>A(d).type==="tool_result").length;for(let[d,f]of r.content.entries()){let p=A(f),g=p.type==="tool_use"?y(p.id):`${i}:${c+d}`,w=p.type==="thinking"?"thinking":p.type==="tool_use"||p.type==="tool_result"?"tool":n.type==="user"?"user":"assistant",h=A(p.input),E=p.type==="thinking"?y(p.thinking):y(p.text)||y(h.description)||y(p.name)||(p.type==="tool_result"?"":JSON.stringify(p)),I=p.type==="tool_result"?typeof p.content=="string"?p.content:JSON.stringify(p.content):void 0;if(D(E)||D(I))continue;p.type==="tool_use"&&y(p.name)===Re&&this.skillCompanions.push(y(p.id));let T=p.type==="tool_result"?this.edits.get(y(p.tool_use_id)):void 0;T&&(this.edits.delete(y(p.tool_use_id)),this.answered.add(y(p.tool_use_id)),T.shown!=="plain"&&this.emit({type:"entry",entry:{...T.call,running:!1}}));let v=p.type==="tool_use"?this.mcpApps.call(y(p.id),y(p.name),h):void 0,S=p.type==="tool_use"?yt(y(p.name),h):void 0,_=p.type==="tool_use"?pe(y(p.name),h):p.type==="tool_result"?kt(n.tool_result_meta,y(p.tool_use_id)):void 0,k={id:g,role:w,ts:o,text:E,...p.type==="tool_use"?{tool:y(p.name),toolUseId:y(p.id),running:!t,detail:Ut(h,Oe(h)),...S?{subagentLabel:S}:{},...v?{app:v}:{}}:{},...p.type==="tool_result"?{toolUseId:y(p.tool_use_id),...T?.patch!==void 0&&p.is_error!==!0?{output:T.patch,diff:!0,...T.excerpt?{diffExcerpt:!0}:{}}:{output:I},error:p.is_error===!0}:{},..._?{mcpSignIn:_}:{},...a},x=p.type==="tool_use"?this.trackEdit(k,h,t):void 0,R=p.type==="tool_result"?this.mcpApps.result(k,n,p,u):void 0;p.type==="tool_use"&&this.writing.delete(g)&&this.drafts.settle(g),this.emit(R?{type:"entry",entry:{...k,app:R.app},appCall:R.appCall}:{type:"entry",entry:x?Ft(x):k})}}trackEdit(e,t,n){let r=Dt(e.tool??"",t),i=e.toolUseId??"";if(!r||!i)return;let o=this.edits.get(i)?.shown??(this.answered.has(i)?"plain":n?"aborted":"draft"),a={call:e,...r,shown:o};return this.edits.set(i,a),a}endDrafts(e){for(let[t,n]of this.writing)e(n)&&(this.writing.delete(t),this.drafts.abandon(t));for(let t of this.edits.values())t.shown!=="draft"||!e(t.call.parentToolUseId)||(t.shown="aborted",this.emit({type:"entry",entry:Ft(t)}))}taskChain(e){let t=[],n=e?[...this.tasks.values()].find(r=>r.toolUseId===e):void 0;for(;n&&!t.includes(n);)t.push(n),n=n.parentTaskId?this.tasks.get(n.parentTaskId):void 0;return t}inBackground(e){return this.taskChain(e).some(t=>t.backgrounded)}trackTask(e){let t=y(e.task_id);if(!t)return;if(e.subtype==="task_started"){y(e.tool_use_id)&&this.tasks.set(t,{id:t,toolUseId:y(e.tool_use_id),backgrounded:e.is_backgrounded===!0,...y(e.parent_task_id)?{parentTaskId:y(e.parent_task_id)}:{}});return}let n=this.tasks.get(t);if(!n)return;let r=A(e.patch);e.subtype==="task_updated"&&typeof r.is_backgrounded=="boolean"&&(n.backgrounded=r.is_backgrounded),(e.subtype==="task_notification"||e.subtype==="task_updated"&&["completed","failed","killed"].includes(y(r.status)))&&(this.endDrafts(o=>this.taskChain(o).includes(n)),this.tasks.delete(t),this.replies.delete(n.toolUseId))}streamEvent(e){let t=A(e.event),n=y(e.parent_tool_use_id)||void 0,r=n??"";if(t.type==="message_start"){!this.turnId&&!n&&(this.ownReply=!0),this.emit({type:"status",status:"working",turnId:this.turnId});for(let a of this.replies.get(r)?.blocks.values()??[])a.draft&&this.writing.delete(a.entry.id)&&this.drafts.abandon(a.entry.id);this.replies.set(r,{messageId:y(A(t.message).id),blocks:new Map});return}let i=this.replies.get(r);if(!i)return;let o=Number(t.index);if(t.type==="content_block_start"){let a=A(t.content_block),c=new Date().toISOString(),u=n?{parentToolUseId:n}:{};if(a.type==="text"||a.type==="thinking"){i.blocks.set(o,{entry:{id:`${i.messageId}:${o}`,role:a.type==="thinking"?"thinking":"assistant",text:y(a.text)||y(a.thinking),ts:c,...u}});return}let d=y(a.id),f=y(a.name),p=a.type==="tool_use"&&d?Pt(f):void 0;if(!p)return;let g={id:d,role:"tool",ts:c,text:f,tool:f,toolUseId:d,output:"",draft:!0,...u};i.blocks.set(o,{entry:g,draft:p}),this.writing.set(d,n),this.drafts.update(g)}else if(t.type==="content_block_delta"){let a=i.blocks.get(o),c=A(t.delta);if(!a)return;if(!a.draft){a.entry.text+=y(c.text)||y(c.thinking),this.emit({type:"entry",entry:{...a.entry}});return}if(c.type!=="input_json_delta"||!this.writing.has(a.entry.id))return;let{draft:u}=a,[d,f]=[u.text.length,u.paths.length];if(u.push(y(c.partial_json)),u.text.length===d&&u.paths.length===f)return;a.entry={...a.entry,output:u.text,...u.paths.length?{detail:u.paths.join(`
15
+ `)}:{}},this.drafts.update(a.entry)}else if(t.type==="content_block_stop"){let a=i.blocks.get(o);a?.draft&&this.drafts.flush(a.entry.id)}}acknowledge(e){let t=[e.user_message_uuid,...Array.isArray(e.user_message_uuids)?e.user_message_uuids:[],...e.type==="user"?[e.uuid]:[]];for(let n of t){let r=this.receipts.get(y(n));r&&(this.receipts.delete(y(n)),this.emit({type:"entry",entry:{id:r.prompt.requestId,role:"user",text:r.prompt.text,ts:r.at}}),r.resolve())}this.receipts.size||(clearTimeout(this.receiptCheckTimer),this.receiptCheckTimer=void 0,this.receiptCheckAttempts=0)}checkPendingReceipts(){if(this.closing||!this.receipts.size||this.receiptCheckTimer||this.receiptCheck)return;let e=[0,1e3,5e3,3e4][this.receiptCheckAttempts];e!==void 0&&(this.receiptCheckTimer=setTimeout(()=>{this.receiptCheckTimer=void 0,this.receiptCheckAttempts++,this.receiptCheck=(async()=>{try{if(!this.options||!this.threadId)return;let t=this.sandbox?.sessionStore??this.options.account?.home??he(),n=await Le(t,this.threadId,this.options.cwd);if(this.closing)return;for(let r of n)r.type==="user"&&this.acknowledge(A(r))}catch{}finally{this.receiptCheck=void 0,this.checkPendingReceipts()}})()},e),this.receiptCheckTimer.unref?.())}failReceipts(e){clearTimeout(this.receiptCheckTimer),this.receiptCheckTimer=void 0;for(let t of this.receipts.values())t.reject(e);this.receipts.clear()}async readCompactLimit(e){try{let t=await e.getContextUsage({detail:"summary"}),n=t.isAutoCompactEnabled?t.autoCompactThreshold??null:null;if(this.closing||this.running!==e||n===this.compactLimit)return;this.compactLimit=n,this.emit({type:"raw",method:"claude/compact.limit",payload:{threshold:n}})}catch{}}async consume(e){try{for await(let t of e){if(this.closing)break;let n=t,r=A(n);if(this.acknowledge(r),n.type==="system"&&r.subtype==="task_started"&&typeof r.task_id=="string"&&this.agentLabels.set(r.task_id,y(r.description)||y(r.subagent_type)||"Subagent"),n.type==="system"&&this.trackTask(r),n.type==="system"&&r.subtype==="background_tasks_changed"&&Array.isArray(r.tasks)){let i=r.tasks.map(A).filter(o=>!o.ambient&&typeof o.task_id=="string").map(o=>({taskId:y(o.task_id),toolUseId:y(o.tool_use_id)||this.tasks.get(y(o.task_id))?.toolUseId||null,taskType:y(o.task_type),description:y(o.description),since:this.backgroundTasks.get(y(o.task_id))?.since??new Date().toISOString()}));this.backgroundTasks=new Map(i.map(o=>[o.taskId,o])),this.emit({type:"background-tasks",tasks:i})}if(n.type==="system"&&r.subtype==="task_notification"&&!r.ambient&&!r.skip_transcript&&this.emit({type:"entry",entry:{id:y(r.uuid)||ke(),role:"system",text:ct(y(r.status),y(r.summary)),ts:new Date().toISOString()}}),n.type==="system"&&r.subtype==="notification"&&typeof r.text=="string"&&this.emit({type:"entry",entry:{id:y(r.uuid)||ke(),role:"system",text:r.text,ts:new Date().toISOString()}}),n.type==="prompt_suggestion"&&typeof r.suggestion=="string"&&this.emit({type:"prompt-suggestion",suggestion:r.suggestion.trim()||null}),n.type==="assistant"&&n.error==="authentication_failed"&&!n.parent_tool_use_id&&(this.signedOut=!0),n.type==="assistant"||n.type==="user")this.message(n);else if(n.type==="stream_event")this.streamEvent(r);else if(n.type==="result"){this.endDrafts(a=>!this.inBackground(a)),this.ownReply=!1,this.receiptCheckAttempts=0,this.checkPendingReceipts();let i=[r.user_message_uuid,...Array.isArray(r.user_message_uuids)?r.user_message_uuids:[]].filter(Boolean);for(let a of i){let c=y(a);if(this.unconsumed.has(c)){for(let u of this.unconsumed)if(this.unconsumed.delete(u),u===c)break}}let o=!i.length&&!!y(A(r.origin).kind);if(!this.turnId||!i.length&&!o||this.stopping||!this.unconsumed.size){let a=["aborted_tools","aborted_streaming"].includes(y(r.terminal_reason))||this.stopping&&["interrupted","cancelled"].includes(y(r.terminal_reason)),c=this.signedOut&&n.is_error&&!a;this.turnId=null,this.unconsumed.clear(),this.stopping=!1,this.signedOut=!1,this.emit({type:"status",status:n.is_error&&!a?"error":"idle",turnId:null,error:c?jt:n.is_error&&!a?JSON.stringify(r.errors??r.result??n.subtype):null,...c?{signedOut:!0}:{}});for(let u of this.turnEnds.splice(0))u()}this.readCompactLimit(e)}n.type!=="stream_event"&&this.emit({type:"raw",method:`claude/${n.type}`,payload:n})}this.closing||this.emit({type:"status",status:"disconnected",turnId:null,error:"Claude process ended"})}catch(t){this.closing||this.emit({type:"status",status:"disconnected",turnId:null,error:String(t)})}finally{this.endDrafts(()=>!0),this.failReceipts(new Error("Claude disconnected before acknowledging the prompt"));for(let t of this.turnEnds.splice(0))t()}}client(){if(!this.running||this.closing)throw new Error("Connect to Claude first");return this.running}async injectedMcpState(e,t){let n=(await e.mcpServerStatus()).find(r=>r.name===t);return n?.status==="connected"?"connected":n?.status==="pending"?"pending":{failed:n?.error||n?.status||"Claude reported no status"}}async refreshTools(){let e=l(()=>!!this.turnId||this.requests.size>0||this.backgroundTasks.size>0||this.closing,"busy");if(!(e()||this.options?.agent.questionOnly||this.options?.agent.toolFree))try{let t=this.client(),n=await t.mcpServerStatus(),r=new Set(Object.keys(this.options?.mcpServers??{})),i=n.filter(a=>!r.has(a.name)&&["connected","failed"].includes(a.status)),o=[];for(let a of i){if(e())break;try{await t.reconnectMcpServer(a.name)}catch{o.push(a.name)}}o.length&&this.emit({type:"raw",method:"claude/mcp.refresh.failed",payload:{servers:o}}),await this.mcpApps.refreshMetadata()}catch{this.emit({type:"raw",method:"claude/mcp.refresh.failed",payload:{}})}}async send(e,t){return this.submit(e,!1,t)}async applyAgent(e){let t=this.options,n={};e.model!==t.agent.model&&(n.model=e.model??null),e.effort!==t.agent.effort&&(n.effortLevel=e.effort??null),!!e.fast!=!!t.agent.fast&&(n.fastMode=e.fast??!1),Object.keys(n).length&&(await this.client().applyFlagSettings(n),t.agent={...t.agent,model:e.model,effort:e.effort,fast:e.fast}),!!e.plan!=!!t.agent.plan&&(await this.client().setPermissionMode(e.plan?"plan":this.harnessMode),t.agent={...t.agent,plan:e.plan})}async submit(e,t,n){if(this.client(),n)try{await this.applyAgent(n)}catch(u){throw new N(`Claude settings could not be applied: ${String(u)}`,400)}!t&&this.sandbox&&await this.sandbox.beforeTurn();let r=wt("claude",e.requestId);(!t||!this.turnId)&&(this.turnId=e.requestId,this.unconsumed.clear()),this.unconsumed.add(r);let i=[{type:"text",text:e.text}];for(let u of e.attachments??[])u.mimeType&&["image/png","image/jpeg","image/webp","image/gif"].includes(u.mimeType)?i.push({type:"image",source:{type:"base64",media_type:u.mimeType,data:Er(u.path).toString("base64")}}):i.push({type:"text",text:`Read attached file: ${u.path}`});let o,a=!1,c=new Promise((u,d)=>{this.receipts.set(r,{prompt:e,at:new Date().toISOString(),resolve:u,reject:d}),o=setTimeout(()=>{a=!0,this.receiptCheckAttempts=0,this.checkPendingReceipts(),d(new V("Claude has not acknowledged the prompt; delivery is still unconfirmed"))},6e4)});this.emit({type:"status",status:"working",turnId:this.turnId,error:null});try{this.stream.push({type:"user",session_id:this.threadId,uuid:r,parent_tool_use_id:null,message:{role:"user",content:i},priority:"now"}),await c}catch(u){throw a||this.unconsumed.delete(r),u}finally{clearTimeout(o),a||this.receipts.delete(r)}}async steer(e,t){return this.submit(e,!0,t)}async stop(){this.stopping=!0;let e=this.resultDue?new Promise(t=>this.turnEnds.push(t)):void 0;try{await Promise.all([...this.backgroundTasks.keys()].map(r=>this.client().stopTask(r)));let t=await this.client().interrupt();if(!e||t?.still_queued?.some(r=>this.unconsumed.has(r)))return;let n;await Promise.race([e,new Promise(r=>{n=setTimeout(r,2e3)})]),clearTimeout(n)}catch(t){throw this.stopping=!1,t}}async answer(e,t){let n=this.requests.get(e);if(!n)throw new Error("This Claude interaction has closed");let r;if(n.question&&t.decision==="cancel")r={behavior:"deny",message:"Question cancelled by the user",interrupt:!0};else if(n.question&&t.decision==="decline")r={behavior:"deny",message:"Question declined by the user"};else if(n.question){let i=n.input.questions,o={};for(let[a,c]of i.entries()){let u=t.answers?.[String(a)]?.join(", ");if(!u?.trim())throw new Error("Answer every question");o[y(A(c).question)]=u}r={behavior:"allow",updatedInput:{...n.input,answers:o}}}else{if(!(n.sessionRules?["accept","acceptForSession","decline"]:["accept","decline"]).includes(t.decision??""))throw new Error("This decision is unavailable");r=t.decision==="decline"?{behavior:"deny",message:"Declined by the user"}:{behavior:"allow",updatedInput:n.input,...n.tool==="ExitPlanMode"?{updatedPermissions:[{type:"setMode",mode:this.harnessMode,destination:"session"}]}:t.decision==="acceptForSession"?{updatedPermissions:n.sessionRules}:{}}}this.requests.delete(e),n.resolve(r),n.tool==="ExitPlanMode"&&r.behavior==="allow"&&(this.options&&(this.options.agent={...this.options.agent,plan:!1}),this.emit({type:"settings",agent:{plan:!1}})),this.emit({type:"interaction-resolved",id:e}),this.publishActivity()}get resultDue(){return this.turnId!==null||this.ownReply}async activity(){return{interactions:this.liveInteractions(),running:this.resultDue,providerTurnId:this.turnId,blockedOn:[...this.requests.values()].some(e=>e.question)?"question":this.requests.size?"approval":null}}publishActivity(){this.emit({type:"status",status:this.requests.size?"waiting":this.resultDue?"working":"idle",turnId:this.turnId})}async models(){let e=await this.client().supportedModels();return e.map(t=>({id:t.value,name:Et(t,e),...t.description?.trim()?{description:t.description.trim()}:{},provider:"claude",default:t.value==="default",...t.resolvedModel?{resolvedModel:t.resolvedModel}:{},plan:!0,fast:!!t.supportsFastMode,efforts:t.supportedEffortLevels}))}async commands(){let e=this.client(),t=await e.supportedCommands(),n=this.options?.catalogOnly?await this.skillNames(e):void 0;return t.map(r=>({name:r.name,description:r.description,argumentHint:r.argumentHint,...r.aliases?.length?{aliases:r.aliases}:{},...n?{skill:n.has(r.name)}:{}}))}async skillNames(e){let t;try{let{skills:n}=await Promise.race([e.reloadSkills(),new Promise((r,i)=>{t=setTimeout(()=>i(new Error("Claude did not list its skills in time")),5e3)})]);return new Set(n.map(r=>r.name))}catch{return}finally{clearTimeout(t)}}async fork(){if(this.sandbox)throw new Error("Forking a sandbox Claude session in place is not supported");if(!this.threadId||this.turnId)throw new Error("Wait for Claude to finish before forking");let e=this.options?.account?.home;return e?Ct(e,this.threadId,this.options?.cwd):(await Cr(this.threadId,{dir:this.options?.cwd})).sessionId}async close(){this.closing=!0,this.mcpConfigFile&&(_r(this.mcpConfigFile,{force:!0}),this.mcpConfigFile=void 0),this.mcpApps.stop(),this.failReceipts(new Error("Native host closed before Claude acknowledged the prompt"));for(let e of this.requests.values())e.resolve({behavior:"deny",message:"Native host closed"});this.requests.clear(),await this.stopBackgroundTasks(),this.stream.close(),this.running?.close(),await this.loop,this.running=null}async stopBackgroundTasks(){let e=this.running,t=[...this.backgroundTasks.keys()];if(!e||!t.length)return;let n;await Promise.race([Promise.allSettled(t.map(async r=>{await e.stopTask(r),this.backgroundTasks.delete(r)&&this.emit({type:"background-tasks",tasks:[...this.backgroundTasks.values()],awaitsReply:!1})})),new Promise(r=>{n=setTimeout(r,2e3)})]),clearTimeout(n)}};import{createHash as Lr}from"node:crypto";import{readFileSync as Dr,realpathSync as Bt,statSync as qr}from"node:fs";import Wt from"node:path";import je from"node:path";function Ht(s,e){let t=je.relative(s,e);return t!==""&&t!==".."&&!t.startsWith(`..${je.sep}`)&&!je.isAbsolute(t)}l(Ht,"pathInside");var $r=new Set(["image/png","image/jpeg","image/webp","image/gif"]),He=10*1024*1024,Kt=l((s,e)=>`native_image_${Lr("sha256").update(s).update("\0").update(e).digest("hex")}`,"imageReference");function Vt(s,e){try{let t=Bt(s),n=Bt(Wt.resolve(s,e)),r={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif"}[Wt.extname(n).toLowerCase()],i=qr(n);if(!Ht(t,n)||!r||!i.isFile()||i.size>He)return[];let o=Dr(n);return[{reference:Kt(r,o),mediaType:r,data:o.toString("base64")}]}catch{return[]}}l(Vt,"nativeFileImage");function Ur(s){if(s.length>=4&&s[0]===137&&s[1]===80&&s[2]===78&&s[3]===71)return"image/png";if(s.length>=3&&s[0]===255&&s[1]===216&&s[2]===255)return"image/jpeg";if(s.length>=6){let e=s.subarray(0,6).toString();if(e==="GIF87a"||e==="GIF89a")return"image/gif"}return s.length>=12&&s.subarray(0,4).toString()==="RIFF"&&s.subarray(8,12).toString()==="WEBP"?"image/webp":null}l(Ur,"sniffImageMediaType");function Gt(s,e){if(typeof s!="string")return null;let t=s.trim(),n=typeof e=="string"?e:null,r=t.match(/^data:(image\/[a-z+.-]+);base64,([\s\S]*)$/i);if(r&&(n??=r[1],t=r[2].trim()),t.length>Math.ceil(He/3)*4||!/^[a-z0-9+/\r\n]*={0,2}$/i.test(t))return null;let i;try{i=Buffer.from(t,"base64")}catch{return null}return!i.length||i.length>He||(n??=Ur(i),!n||!$r.has(n))?null:{reference:Kt(n,i),mediaType:n,data:i.toString("base64")}}l(Gt,"nativeBase64Image");var X="codex_apps",Xt="Codex exposes ChatGPT app tools through codex_apps (mcp__codex_apps__*). Configured MCP servers have their own tool namespaces and credentials, even when they share an app's service label. Use the connection the task specifies. When it names a linked account, find the matching account in the ChatGPT app tool's current link_id choices and pass that exact link_id. Treat the connection inventory as a discovery aid and confirm the choice in the tool schema. If the intended connection or account is ambiguous, ask which to use. If the named account is unavailable, report the blocker.",zt=2e3,F=l(s=>s&&typeof s=="object"&&!Array.isArray(s)?s:{},"record");function Fr(s){let e=F(F(F(s.inputSchema).properties).link_id);if(typeof e.description!="string")return[];let t=e.description.search(/^[ \t]*\[/m);if(t<0)return[];let n;try{n=JSON.parse(e.description.slice(t))}catch{return[]}return Array.isArray(n)?n.flatMap(r=>{let{link_id:i,link_name:o}=F(r);return typeof i=="string"&&i.trim()&&typeof o=="string"&&o.trim()?[{link_id:i,link_name:o}]:[]}):[]}l(Fr,"linkAccounts");async function Jt(s,e){let t=performance.now()+zt,r=(await s.request("mcpServerStatus/list",{threadId:e,serverName:X,detail:"toolsAndAuthOnly"},zt)).data?.find(c=>c.name===X),i=new Map;for(let c of Object.values(r?.tools??{})){let u=F(c),d=F(u._meta),f=F(d._codex_apps),p=d.connector_id;if(!(typeof p!="string"||f.requires_explicit_link_id!==!0||!G(d).includes("model")))for(let g of Fr(u)){let w=i.get(p);w||(w=new Map,i.set(p,w)),w.set(JSON.stringify(g),g)}}let o=t-performance.now();if(!i.size||o<=0)return[];let{apps:a}=await s.request("app/installed",{threadId:e},o);return(a??[]).flatMap(c=>{let u=i.get(c.id);return!c.enabled||!c.callable||!u?[]:[{connection:`app:${c.id}`,name:c.runtimeName||c.id,accounts:[...u.values()].sort((d,f)=>d.link_name.localeCompare(f.link_name)||d.link_id.localeCompare(f.link_id))}]}).sort((c,u)=>c.connection.localeCompare(u.connection))}l(Jt,"readCodexAppConnections");var jr={connected:"connected",authenticationRequired:"needs-sign-in",starting:"connecting",notStarted:"connecting",failed:"failed",cancelled:"failed",disabled:"disabled"},Hr=1e4,se=l(s=>s&&typeof s=="object"&&!Array.isArray(s)?s:{},"record");function Zt(s){if(typeof s!="string"||!URL.canParse(s))return null;let e=new URL(s);return e.origin==="https://chatgpt.com"&&!e.username&&!e.password?e:null}l(Zt,"chatgptUrl");function Br(s){let e=Zt(s.installUrl);if(!e)return s.installUrl??void 0;let t=/^(?:\/plugins\/plugin_|\/apps\/[^/]+\/)(asdk_app_[\w-]+)\/?$/.exec(e.pathname)?.[1];return t!==s.id?s.installUrl??void 0:(e.pathname=`/settings/plugins-settings/plugin_${t}`,e.href)}l(Br,"appSignInUrl");function Qt(s){let e=jr[s.runtimeStatus??""]??(s.authStatus==="notLoggedIn"?"needs-sign-in":"unknown"),t=s.authStatus==="notLoggedIn"||s.authStatus==="oAuth",n=s.authStatus==="bearerToken"?`Codex uses a configured bearer token for ${s.name}. Browser sign-in cannot replace it. This Codex account needs a valid token with the required service permissions.`:s.authStatus==="unsupported"?`Codex reports no OAuth support for ${s.name}. Browser sign-in is unavailable; any required credentials must come from this server's provider configuration.`:s.authStatus===void 0?"This Codex version does not report MCP authentication capabilities. Browser sign-in requires a provider version that reports OAuth support.":`Codex has not established OAuth support for ${s.name}. Browser sign-in is unavailable until the provider can determine its authentication method.`;return{server:`server:${s.name}`,label:K(s.name),kind:"server",status:e,signIn:t?{available:!0}:{available:!1,reason:n},...e==="failed"&&s.toolsError?{error:s.toolsError}:{}}}l(Qt,"serverState");function Yt(s){return{server:`app:${s.id}`,label:s.name,kind:"app",status:s.isEnabled===!1?"disabled":s.isAccessible?"connected":"needs-sign-in",signIn:s.installUrl?{available:!0}:{available:!1,reason:`ChatGPT offers no page to connect ${s.name}. This app needs to be made available to the ChatGPT account.`}}}l(Yt,"appState");var Se=class{constructor(e,t){this.session=e;this.managed=t}static{l(this,"CodexMcpSignIn")}logins=new Map;appAuthFailures=new Map;apps;observe(e){if(e.type!=="mcpToolCall"||e.server!==X)return;let t=se(e.result),n=se(se(se(t._meta)._codex_apps).connector_auth_failure),r=n.connector_id,i=se(e.appContext).connectorId;if(n.is_auth_failure===!0&&typeof r=="string"&&r.trim()&&(typeof i!="string"||i===r))return this.appAuthFailures.set(r,{id:r,name:typeof n.connector_name=="string"?n.connector_name:r,installUrl:Zt(n.install_url)?.href??null,isAccessible:!1}),{servers:[`app:${r}`]};e.status==="completed"&&e.result&&t.isError!==!0&&n.is_auth_failure!==!0&&typeof i=="string"&&this.appAuthFailures.delete(i)}withAppAuthFailure(e){let t=this.appAuthFailures.get(e.id);return t?{...e,isAccessible:!1,installUrl:t.installUrl??e.installUrl}:e}completed(e){let t=typeof e.name=="string"?e.name:"",n=this.logins.get(t);this.logins.has(t)&&(n===void 0||e.loginId==null||e.loginId===n)&&this.logins.delete(t)}async state(e,t){let n=await this.find(e,t?.reconnect),{rpc:r,threadId:i}=this.session();if(n.kind==="app")return t?.reconnect&&await r.request("app/installed",{threadId:i,forceRefresh:!0}).catch(()=>{}),Yt(this.withAppAuthFailure(n.app));let o=n.status;return t?.reconnect&&!this.logins.has(o.name)&&(o.runtimeStatus==="authenticationRequired"||o.runtimeStatus==="failed")&&(await r.request("config/mcpServer/reload",void 0).catch(()=>{}),o=await this.server(o.name)??o),Qt(o)}async start(e){let t=await this.find(e,!0);t.kind==="app"&&(t.app=this.withAppAuthFailure(t.app));let n=t.kind==="app"?Yt(t.app):Qt(t.status);if(n.status==="connected")return{state:n};let r=de(n);if(r)throw new Error(r);if(t.kind==="app")return{url:Br(t.app),state:n};let{rpc:i,threadId:o}=this.session(),a=await i.request("mcpServer/oauth/login",{name:t.status.name,threadId:o});return this.logins.set(t.status.name,a.loginId),{url:a.authorizationUrl,state:n}}async server(e){let{rpc:t,threadId:n}=this.session();return(await t.request("mcpServerStatus/list",{threadId:n,serverName:e,detail:"toolsAndAuthOnly"})).data?.find(i=>i.name===e)}async find(e,t=!1){let n=/^(app|server):(.+)$/s.exec(e),r=n?.[1],i=n?.[2]??e;if(r==="app"){let h=this.appAuthFailures.get(i),I=(await this.appList(t).catch(T=>{if(h)return this.apps?.list??[];throw T})).find(T=>T.id===i)??h;if(I)return{kind:"app",app:I};throw new Error(`Codex has no ChatGPT app with id ${i}`)}let o=this.managed();if(r==="server"){if(o.has(i)||i===X)throw new Error(`${i} is provider-managed and has no independent sign-in`);let h=await this.server(i);if(h)return{kind:"server",status:h};throw new Error(`Codex has no MCP server named ${i}`)}let{rpc:a,threadId:c}=this.session(),u=[],d=null;do{let h=await a.request("mcpServerStatus/list",{threadId:c,cursor:d,detail:"toolsAndAuthOnly"});u.push(...(h.data??[]).filter(E=>!o.has(E.name)&&E.name!==X)),d=h.nextCursor??null}while(d);let f=u.map(h=>({server:h.name,label:K(h.name),status:h})),p=await this.appList(t).catch(()=>{throw new Error(`Codex could not list ChatGPT apps, so ${e} cannot be resolved safely. Use server:<configured-name> or app:<app-id> for the connection whose tools you need.`)}),g=[],w=i.trim().toLowerCase();for(let h of f)(h.server.toLowerCase()===w||h.label.toLowerCase()===w)&&g.push({selector:`server:${h.server}`,target:{kind:"server",status:h.status}});for(let h of p)(h.id.toLowerCase()===w||h.name.toLowerCase()===w)&&g.push({selector:`app:${h.id}`,target:{kind:"app",app:h}});if(g.length>1)throw new Error(`${e} matches multiple connections. Use the identity of the connection whose tools you need: ${g.map(h=>h.selector).join(", ")}`);if(g[0])return g[0].target;throw new Error(`Codex has no MCP server or ChatGPT app named ${e}`)}async appList(e){if(!e&&this.apps&&Date.now()-this.apps.at<Hr)return this.apps.list;let{rpc:t,threadId:n}=this.session(),r=[],i=null;do{let o=await t.request("app/list",{threadId:n,cursor:i,limit:200,...e?{forceRefetch:!0}:{}});r.push(...o.data??[]),i=o.nextCursor??null}while(i);return this.apps={at:Date.now(),list:r},r}};import{createHash as Wr}from"node:crypto";function en(s,e,t,n=!1){let r=Buffer.from(JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e}})).toString("base64"),i=!t&&process.platform==="win32",o=t??process.execPath,a=i?`"${o}"`:`'${o.replaceAll("'","'\\''")}'`,c=n?`let name;try{name=JSON.parse(require('node:fs').readFileSync(0,'utf8')).tool_name}catch{};process.stdout.write(name==='request_user_input'||name==='request_user_input_async'?'{}':Buffer.from('${r}','base64'))`:`process.stdout.write(Buffer.from('${r}','base64'))`,u=Buffer.from(c).toString("base64"),d=n?`${a} -e "eval(Buffer.from('${u}','base64').toString())"`:`${a} -e "${c}"`,f={type:"command",command:d,timeout:5,async:!1},p={event_name:"pre_tool_use",hooks:[{async:!1,command:d,timeout:5,type:"command"}],matcher:s},g=`sha256:${Wr("sha256").update(JSON.stringify(p)).digest("hex")}`,h=`${i?"C:\\<session-flags>\\config.toml":"/<session-flags>/config.toml"}:pre_tool_use:0:0`;return{command:d,hash:g,key:h,matcher:s,config:{"hooks.PreToolUse":[{matcher:s,hooks:[f]}],"hooks.state":{[h]:{enabled:!0,trusted_hash:g}}}}}l(en,"codexToolPolicy");function Be(s){return en("^request_user_input(_async)?$",B,s)}l(Be,"codexHelperQuestionPolicy");function We(s){return en("*","This side chat may only ask user questions.",s,!0)}l(We,"codexQuestionFormPolicy");async function Ke(s,e,t=Be()){let r=(await s.request("hooks/list",{cwds:[e]})).data?.flatMap(i=>i.hooks??[]).find(i=>i.key===t.key);if(!r||r.currentHash!==t.hash||r.command!==t.command||!r.enabled||r.trustStatus!=="trusted")throw new Error(t.matcher==="*"?"Codex cannot enforce the question-form tool policy: its required tool hook is unavailable or untrusted":"Codex cannot enforce the delegated helper question policy: its required tool hook is unavailable or untrusted")}l(Ke,"verifyCodexHelperQuestionPolicy");import{spawn as Kr}from"node:child_process";var Vr=64*1024*1024;function Ve(s){return Array.isArray(s)?`[${s.map(Ve).join(",")}]`:s&&typeof s=="object"?`{${Object.entries(s).map(([e,t])=>`${JSON.stringify(e)}=${Ve(t)}`).join(",")}}`:JSON.stringify(s)}l(Ve,"configValue");var ie=class{static{l(this,"CodexRpc")}child;pending=new Map;nextId=0;ended=!1;closed;buffer="";constructor(e,t,n,r,{timeoutMs:i=3e4,spawn:o,env:a,codexHome:c,configOverrides:u={}}){this.timeoutMs=i;let d=[...e.args,"app-server",...c?["--config",`sqlite_home=${JSON.stringify(c)}`]:[],...Object.entries(u).flatMap(([p,g])=>["--config",`${p}=${Ve(g)}`]),"--listen","stdio://"];this.child=o?o(e.command,d,t,a):Kr(e.command,d,{cwd:t,env:a,stdio:"pipe",windowsHide:!0}),this.closed=new Promise(p=>this.child.once("close",()=>p())),this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",p=>{if(this.buffer+=p,this.buffer.length>Vr)return f(new Error("Codex sent an oversized protocol frame"));let g=this.buffer.indexOf(`
16
+ `);for(;g!==-1&&!this.ended;){let w=this.buffer.slice(0,g).trim();if(this.buffer=this.buffer.slice(g+1),w)try{let h=JSON.parse(w);if(!h||typeof h!="object")throw new Error("Invalid Codex frame");if(h.method)n(h);else if(h.id!==void 0){let E=this.pending.get(h.id);E&&(clearTimeout(E.timer),this.pending.delete(h.id),h.error?E.reject(new N(h.error.message,h.error.code)):E.resolve(h.result))}}catch(h){f(h instanceof Error?h:new Error("Invalid Codex frame"))}g=this.buffer.indexOf(`
17
+ `)}}),this.child.stderr.resume();let f=l(p=>{if(!this.ended){this.ended=!0;for(let g of this.pending.values())clearTimeout(g.timer),g.reject(p);this.pending.clear(),r(p),this.child.kill("SIGTERM")}},"fail");this.child.once("error",f),this.child.stdin.on("error",f),this.child.once("close",p=>f(new Error(`Codex driver disconnected (exit ${p??"signal"})`)))}timeoutMs;request(e,t,n=this.timeoutMs){if(this.ended)return Promise.reject(new Error("Codex driver is disconnected"));let r=++this.nextId;return new Promise((i,o)=>{let a=setTimeout(()=>{this.pending.delete(r),o(new Error(`${e} timed out; delivery is uncertain. Disconnect and resume before sending again.`))},n);this.pending.set(r,{resolve:l(c=>i(c),"resolve"),reject:o,timer:a}),this.child.stdin.write(`${JSON.stringify({id:r,method:e,params:t})}
18
+ `)})}respond(e,t){this.write({id:e,result:t})}reject(e,t){this.write({id:e,error:{code:-32601,message:t}})}write(e){if(this.ended)throw new Error("Codex driver is disconnected");this.child.stdin.write(`${JSON.stringify(e)}
19
+ `)}notifyInitialized(){this.write({method:"initialized"})}async close(){this.child.stdin.end(),this.child.kill("SIGTERM");let e=setTimeout(()=>this.child.kill("SIGKILL"),2e3);try{await this.closed}finally{clearTimeout(e)}}};import{createHash as Gr}from"node:crypto";import{existsSync as Hc,readdirSync as Bc,readFileSync as Wc}from"node:fs";import Vc from"node:path";var Xe="farero_terminal",zr="pre_tool_use",Ge=l(s=>`\${${s}}`,"field"),Xr={command:Ge("tool_input.command"),cwd:Ge("cwd"),permission_mode:Ge("permission_mode")},Jr=5;function tn(s){return(s?.sandbox??"danger-full-access")==="danger-full-access"&&(s?.approvalPolicy??"never")==="never"}l(tn,"codexHandsOff");function ze(s){return Array.isArray(s)?s.map(ze):!s||typeof s!="object"?s:Object.fromEntries(Object.entries(s).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>[e,ze(t)]))}l(ze,"sortedKeys");function nn(s=process.platform,e=0){let t={type:"mcp_tool",server:Xe,tool:zr,input:Xr,timeout:Jr},n={event_name:"pre_tool_use",hooks:[t],matcher:"Bash"},r=`sha256:${Gr("sha256").update(JSON.stringify(ze(n))).digest("hex")}`;return{"hooks.PreToolUse":[{matcher:"Bash",hooks:[t]}],"hooks.state":{[`${s==="win32"?"C:\\<session-flags>\\config.toml":"/<session-flags>/config.toml"}:pre_tool_use:${e}:0`]:{enabled:!0,trusted_hash:r}}}}l(nn,"codexTerminalHandoffHook");import{randomUUID as os}from"node:crypto";var b=l(s=>s&&typeof s=="object"&&!Array.isArray(s)?s:{},"obj"),m=l(s=>typeof s=="string"?s:"","str");function Qr(s,e,t){if(e.split(`
20
+ `).some(f=>f.startsWith("diff --git ")))return e;let n=(s||`file-${t+1}`).replace(/[\r\n]/g," "),r=l(f=>/[\s"\\]/.test(f)?`"${f.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`:f,"quotePath"),i=r(`a/${n}`),o=r(`b/${n}`),a=e.split(`
21
+ `),c=a.findIndex(f=>f.startsWith("@@ ")),u=c<0?a:a.slice(0,c),d=u.some(f=>f.startsWith("--- "))&&u.some(f=>f.startsWith("+++ "));return[`diff --git ${i} ${o}`,...d?[]:[`--- ${i}`,`+++ ${o}`],e].join(`
22
+ `)}l(Qr,"fileChangePatch");var rn={draft:!0,aborted:!0},sn=l(s=>Array.isArray(s)?s.map(e=>typeof e=="string"?e:m(b(e).text)).filter(Boolean).join(`
23
+ `):m(s),"reasoningText");function Yr(s,e){return"responseStreamDisconnected"in b(s.codexErrorInfo)?!0:/^reconnecting\.\.\.\s*\d+\s*\/\s*\d+/i.test(e.trim())}l(Yr,"isCodexReconnectNoise");function Zr(s){return/\bno (?:archived )?rollout found for (?:thread|conversation) id\b/i.test(s)}l(Zr,"isMissingRollout");function es(s,e){let t=e.approvedTools?.length?s.approvalHeaders?.(e.approvedTools):void 0;return t?{...e.headers,...t}:e.headers}l(es,"approvalHeaders");function ln(s){if(!(!s.terminalHandoff||s.agent.questionOnly||s.agent.toolFree))return tn(s.harness?.codex)?s.terminalHandoff.hookServer:void 0}l(ln,"terminalHandoffServer");function ts(s){if(!s)return{};if(s.agent.questionOnly)return We().config;let e=s.delegated?Be().config:void 0;if(!ln(s))return e??{};let t=nn(process.platform,e?1:0);return{"hooks.PreToolUse":[...e?.["hooks.PreToolUse"]??[],...t["hooks.PreToolUse"]],"hooks.state":{...e?.["hooks.state"],...t["hooks.state"]}}}l(ts,"codexHostHooks");function on(s){return s?"priority":"default"}l(on,"serviceTier");function an(s){return s.effort==="ultracode"?{...s,effort:"ultra"}:s}l(an,"codexAgentOptions");function ns(s){if(!s.requiresOpenaiAuth)return null;let e=b(s.account).type;return e==="chatgpt"||e==="apiKey"?e:null}l(ns,"codexLogin");var cn="Thread is not owned by this native session",rs=500,xe=l(s=>`codex-agent:${s}:`,"subagentPrefix"),ss={spawnAgent:"Start subagent",sendInput:"Message subagent",sendMessage:"Message subagent",followupTask:"Give a subagent a task",resumeAgent:"Resume subagent",wait:"Wait for subagents",closeAgent:"Close subagent",interruptAgent:"Stop subagent",listAgents:"List subagents"};function is(s){if(s.type!=="mcpToolCall"||typeof s.server!="string"||!s.server)return;let e=b(s.mcpAppUi).resourceUri??s.mcpAppResourceUri,t=ee({ui:{resourceUri:e}});return t?{server:s.server,resourceUri:t}:void 0}l(is,"codexMcpApp");var oe=class{static{l(this,"NativeCodexDriver")}provider="codex";capabilities={liveness:!0,steer:!0,fork:!0,approvals:!0,questions:!0,images:!0,plan:!0,fast:!0,efforts:["none","minimal","low","medium","high","xhigh","max","ultra"]};emit;liveInteractions;factory;rpc=null;options=null;threadId=null;turnId=null;entries=new Map;unfinishedMessages=new Map;retryMessages=new Map;reconnecting=null;requests=new Map;connectionId=os();closing=!1;model="";subagents=new Map;foreign=new Set;pendingThreads=new Map;ownership=new Map;publishedSubagents="";appsRefreshUnsupported=!1;waitingEdits=new Map;host;sandbox;constructor(e,{host:t,rpc:n,sandbox:r}){this.host=t,this.sandbox=r;let i=fe(e);this.emit=o=>{o.type==="status"&&!o.retrying&&(this.reconnecting=null),i.emit(o)},this.liveInteractions=i.read,this.factory=n??((o,a,c)=>{let u=this.options,d=this.sandbox;if(d&&u)return new ie({command:"codex",args:[]},o,a,c,{spawn:l((w,h)=>d.spawn(u,h),"spawn"),env:{},configOverrides:u.delegated||u.agent.questionOnly?d.questionPolicy(u.agent.questionOnly).config:{}});let f=this.options?.harness?.codex,p=this.host.launch("codex",f);if(!p.resolved)throw this.host.notInstalled("codex",f?.runtime?.source??"bundled",p.unmet);let g=this.options?.account?.home;return new ie(p,o,a,c,{spawn:this.options?.spawn,env:{...this.host.environment({provider:"codex",workspaceEnv:this.options?.workspaceEnv,accountHome:g,envKeys:f?.envKeys}),...g?{CODEX_SQLITE_HOME:g}:{}},codexHome:g,configOverrides:{...ts(this.options),...this.options?.codeMode?{"features.code_mode":{enabled:!0}}:{},...Object.fromEntries(Object.entries(this.options?.toolEnvironment??{}).map(([w,h])=>[`shell_environment_policy.set.${w}`,h]))}})}),r||(this.mcpSignIn=new Se(()=>this.mcpRpc(),()=>new Set(Object.keys(this.options?.mcpServers??{}))))}mcpSignIn;mcpApps={readResource:l((e,t)=>this.mcpRpc().rpc.request("mcpServer/resource/read",{threadId:this.mcpRpc().threadId,server:e,uri:t}),"readResource"),tools:l(async e=>{let{rpc:t,threadId:n}=this.mcpRpc(),i=(await t.request("mcpServerStatus/list",{threadId:n,serverName:e,detail:"toolsAndAuthOnly"})).data.find(o=>o.name===e);return Object.entries(i?.tools??{}).map(([o,a])=>{let c=b(a)._meta;return{name:o,resourceUri:ee(c),visibility:G(c)}})},"tools"),callTool:l(async(e,t,n)=>{let{rpc:r,threadId:i}=this.mcpRpc(),o=await r.request("mcpServer/tool/call",{threadId:i,server:e,tool:t,arguments:n});return U(o)??{content:[]}},"callTool")};mcpRpc(){if(!this.rpc||!this.threadId)throw new Error("Connect the native Codex session first");return{rpc:this.rpc,threadId:this.threadId}}async injectedMcpState(e,t){let{rpc:n,threadId:r}=this.mcpRpc(),o=(await n.request("mcpServerStatus/list",{threadId:r,serverName:e,detail:"toolsAndAuthOnly"},t+15e3)).data?.find(a=>a.name===e);return o?.runtimeStatus==="connected"?"connected":o?.runtimeStatus==="starting"||o?.runtimeStatus==="notStarted"?"pending":{failed:o?.toolsError||o?.runtimeStatus||"Codex reported no status"}}editPhase(e,t,n,r){return t==="inProgress"&&!n?(this.waitingEdits.set(e,r?.threadId??this.threadId??""),{draft:!0}):(this.waitingEdits.delete(e),t==="declined"||t==="inProgress"?rn:{})}endDrafts(e){for(let[t,n]of this.waitingEdits){if(e!==void 0&&n!==e)continue;this.waitingEdits.delete(t);let r=this.entries.get(t);r&&this.put({...r,...rn})}}entry(e,t,n){let r=b(e),i=m(r.type),o=i==="userMessage"&&m(r.clientId)||m(r.id);if(!o||!i)return;let a=t?`${xe(t.threadId)}${o}`:o;if(i==="subAgentActivity"){this.agentActivity(r,a,t);return}if(this.options?.delegated&&i==="agentMessage"&&Array.isArray(r.questions)&&r.questions.length){this.emit({type:"raw",method:"codex/delegated.question.suppressed",payload:{id:a}});return}let c="tool",u=m(r.text),d,f;if(i==="userMessage")c="user",u=Array.isArray(r.content)?r.content.map(k=>{let x=b(k);return x.type==="skill"?m(x.name)&&`$${m(x.name)}`:x.type==="mention"?m(x.name)&&`@${m(x.name)}`:m(x.text)}).filter(Boolean).join(`
24
+ `):u;else if(i==="agentMessage")c="assistant";else if(i==="reasoning")c="thinking",u=[sn(r.summary),sn(r.content)].filter(Boolean).join(`
25
+ `);else if(i==="commandExecution")u="Run command",d=Q(m(r.command))||void 0,f=m(r.aggregatedOutput);else if(i==="fileChange"){u="Edit files";let k=Array.isArray(r.changes)?r.changes.map(b):[];d=k.map(x=>m(x.path)).join(`
26
+ `),f=k.length>1?k.map((x,R)=>Qr(m(x.path),m(x.diff),R)).join(`
27
+ `):k.map(x=>m(x.diff)).join(`
28
+ `)}else i==="imageGeneration"?(u="Generate image",d=m(r.revisedPrompt)||m(r.prompt)||void 0):i==="collabAgentToolCall"?(u=ss[m(r.tool)]??"Coordinate subagents",d=[(Array.isArray(r.receiverThreadIds)?r.receiverThreadIds.map(x=>this.subagentLabel(m(x))):[]).join(", "),m(r.prompt)].filter(Boolean).join(`
29
+ `)||void 0,f=Object.entries(b(r.agentsStates)).map(([x,R])=>{let O=b(R);return[`${this.subagentLabel(x)}: ${m(O.status)}`,m(O.message)].filter(Boolean).join(`
30
+ `)}).join(`
31
+
32
+ `)||void 0):i==="plan"?c="assistant":(u||=m(r.tool)||m(r.name)||i,d=JSON.stringify(r.arguments??r,null,2),r.result!==void 0&&(f=JSON.stringify(r.result,null,2)));let p=is(r),g=i==="mcpToolCall"?(t?void 0:this.mcpSignIn?.observe(r))??pe(`mcp__${m(r.server)}__${m(r.tool)}`,r.arguments):void 0,w=p&&r.result?U(r.result,r.status==="failed"):null,h=w?{arguments:b(r.arguments),result:w}:null,E=i==="agentMessage"&&Array.isArray(r.questions)?r.questions.flatMap((k,x)=>{let R=b(k),O=m(R.title);return O.trim()?[{id:qt(a,x),question:O,options:Array.isArray(R.options)?R.options.filter(M=>typeof M=="string"):void 0}]:[]}):[],I=i==="fileChange"?this.editPhase(a,r.status,n==="endedTurn",t):void 0,T=n==="history"?typeof r.status=="string"?r.status==="inProgress":void 0:n==="started",v={id:a,...this.entries.get(a)?.supersededBy?{supersededBy:this.entries.get(a).supersededBy}:{},role:c,text:u,ts:this.entries.get(a)?.ts??new Date().toISOString(),...t?{parentToolUseId:t.anchorId}:{},...E.length?{questionRequest:{questions:E}}:{},...c==="tool"?{tool:i==="commandExecution"?"Bash":i==="fileChange"?"Edit":i,toolUseId:a,running:T,detail:d,output:f,diff:i==="fileChange",error:r.status==="failed",...p?{app:p}:{},...g?{mcpSignIn:g}:{},...I}:{}};this.entries.set(a,v);let S=t?this.subagents.get(t.threadId):void 0;S&&i==="agentMessage"&&u&&(S.lastMessage=u);let _=i==="imageView"&&this.options?Vt(this.options.cwd,m(r.path)):i==="imageGeneration"?(()=>{let k=Gt(r.result);return k?[k]:[]})():[];if(this.emit({type:"entry",entry:{...v},..._.length?{imageData:_}:{},...h?{appCall:h}:{}}),i==="agentMessage"&&!this.options?.delegated&&!t&&Array.isArray(r.questions)){let k=$t(a),x=this.options?.stored?.questionDismissed?.(k),R={},O=E.flatMap(({id:M,question:J,options:L})=>x||this.options?.stored?.questionAnswered?.(k,M)?[]:(R[M]=J,[{id:M,...ne(J,L)}]));O.length?this.emit({type:"interaction",interaction:{id:k,kind:"question",blocking:!1,method:"codex/request_user_input_async",title:"Questions from Codex",body:"",questions:O,providerData:{kind:"codex-async-question",messageId:a,rawQuestionTitles:R}}}):this.liveInteractions().some(M=>M.id===k)&&this.emit({type:"interaction-resolved",id:k})}}completeMessage(e){let t=b(e),n=m(t.id);if(this.unfinishedMessages.delete(n),this.retryMessages.delete(n),t.type!=="agentMessage")return;let r=m(t.text);for(let[i,o]of this.retryMessages){let a=this.entries.get(i);if(!a||o!==m(t.phase)||!a.text||!r.startsWith(a.text))continue;let c={...a,supersededBy:n};this.entries.set(i,c),this.emit({type:"entry",entry:c}),this.retryMessages.delete(i),this.unfinishedMessages.delete(i)}this.retryMessages.clear(),this.unfinishedMessages.clear()}subagentOf(e){let t=m(e.params?.threadId);return t&&t!==this.threadId&&this.subagents.has(t)?t:void 0}async stopTurnOf(e){let t=this.subagentOf(e);if(!t)return this.stop();let n=this.subagents.get(t)?.turnId;n&&await this.client().request("turn/interrupt",{threadId:t,turnId:n})}subagentLabel(e){return this.subagents.get(e)?.label??"Subagent"}put(e){let t={...e,ts:this.entries.get(e.id)?.ts??e.ts};this.entries.set(e.id,t),this.emit({type:"entry",entry:{...t}})}agentActivity(e,t,n){let r=new Date().toISOString(),i=n?.threadId??this.threadId??"",o=m(e.agentThreadId),a=l(d=>this.put({id:t,role:"tool",tool:"subAgentActivity",text:"Subagent activity",supersededBy:d,ts:r}),"hide");if(!o||o===i||o===this.threadId){a(`codex-agent:${o||i}`);return}let c=this.subagents.get(o)??this.adopt(o,i,{path:m(e.agentPath),model:m(e.model)});m(e.model)&&(c.model=m(e.model)),m(e.reasoningEffort)&&(c.effort=m(e.reasoningEffort));let u=m(e.kind);u==="started"&&(!c.anchorId||c.anchorId===t)?(c.anchorId=t,this.putAnchor(c),this.flush(o)):u==="completed"||u==="interrupted"?this.put({id:t,role:"system",text:c.lastMessage,ts:r,...n?{parentToolUseId:n.anchorId}:{},backgroundResult:{kind:"subagent",description:c.label,state:u==="completed"?"succeeded":"interrupted",nativeID:o}}):a(c.anchorId??`codex-agent:${o}`)}adopt(e,t,n){let r={parentThreadId:t,label:Me(n.path?.split("/").filter(Boolean).at(-1)||n.nickname||n.role),model:n.model??"",effort:"",anchorId:null,turnId:null,since:null,failed:!1,lastMessage:"",total:null};return this.subagents.set(e,r),this.foreign.delete(e),r}putAnchor(e){if(!e.anchorId)return;let t=this.subagents.get(e.parentThreadId)?.anchorId;this.put({id:e.anchorId,role:"tool",tool:"Agent",text:e.label,detail:[e.model,e.effort].filter(Boolean).join(" \xB7 ")||void 0,toolUseId:e.anchorId,subagentLabel:e.label,ts:new Date().toISOString(),...t?{parentToolUseId:t}:{},...e.failed?{error:!0}:{}})}anchorOrphans(e){for(let[t,n]of this.subagents)n.anchorId||n.parentThreadId!==e||(n.anchorId=`codex-agent:${t}`,this.putAnchor(n),this.flush(t))}receiveForeign(e,t){if(this.foreign.has(e)){t.id!==void 0&&this.rpc?.reject(t.id,cn);return}let n=this.subagents.get(e);if(n&&(n.anchorId||t.id!==void 0)){this.receiveSubagent(e,n,t);return}let r=this.pendingThreads.get(e)??[];(t.id!==void 0||r.length<rs)&&r.push(t),this.pendingThreads.set(e,r),n||this.owns(e).catch(i=>this.emit({type:"raw",method:"codex/subagent.ownership.failed",payload:{threadId:e,error:String(i)}}))}owns(e,t=new Set){if(e===this.threadId||this.subagents.has(e))return Promise.resolve(!0);if(!this.rpc||this.foreign.has(e)||t.has(e))return Promise.resolve(!1);t.add(e);let n=this.ownership.get(e);if(n)return n;let r=this.rpc.request("thread/read",{threadId:e,includeTurns:!1}).then(i=>b(i.thread),()=>({})).then(async i=>{if(this.closing)return!1;if(this.subagents.has(e))return!0;let o=m(i.parentThreadId);if(!o||!await this.owns(o,t))return this.disown(e),!1;if(!this.subagents.has(e)){let a=b(b(b(i.source).subAgent).thread_spawn);this.adopt(e,o,{path:m(a.agent_path),nickname:m(i.agentNickname),role:m(i.agentRole),model:m(i.model)})}return this.flush(e),!0}).finally(()=>this.ownership.delete(e));return this.ownership.set(e,r),r}disown(e){this.foreign.add(e);for(let t of this.pendingThreads.get(e)??[])t.id!==void 0&&this.rpc?.reject(t.id,cn);this.pendingThreads.delete(e)}flush(e){let t=this.subagents.get(e),n=this.pendingThreads.get(e);if(!t||!n)return;let r=t.anchorId?[]:n.filter(i=>i.id===void 0);r.length?this.pendingThreads.set(e,r):this.pendingThreads.delete(e);for(let i of n)r.includes(i)||this.receiveSubagent(e,t,i)}receiveSubagent(e,t,n){let{method:r,id:i}=n;if(!r)return;let o=n.params??{};if(i!==void 0){this.request(n,r,i,{id:e,label:t.label});return}if(!t.anchorId)return;let a={threadId:e,anchorId:t.anchorId};if(r==="turn/started")t.turnId=m(b(o.turn).id)||null,t.since??=new Date().toISOString(),this.publishSubagents();else if(r==="turn/completed"){let c=b(o.turn);if(Array.isArray(c.items))for(let u of c.items)this.entry(u,a,"endedTurn");this.anchorOrphans(e),this.endDrafts(e),t.turnId=null,t.since=null,c.status==="failed"&&!t.failed&&(t.failed=!0,this.putAnchor(t));for(let[u,d]of this.requests)this.subagentOf(d)===e&&(this.requests.delete(u),this.emit({type:"interaction-resolved",id:u}));this.publishSubagents()}else if(r==="item/started"||r==="item/completed")this.entry(o.item,a,r==="item/started"?"started":"completed");else if(r==="serverRequest/resolved"){let c=`${this.connectionId}:${o.requestId}`;this.requests.delete(c),this.emit({type:"interaction-resolved",id:c})}else if(r.startsWith("item/")&&typeof o.delta=="string"){let c=this.entries.get(`${xe(e)}${m(o.itemId)}`);c&&(c.role==="tool"?c.output=(c.output??"")+o.delta:c.text+=o.delta,this.emit({type:"entry",entry:{...c}}))}else r==="thread/tokenUsage/updated"&&this.recordSubagentUsage(e,t,b(o.tokenUsage))}publishSubagents(){let e=[...this.subagents].flatMap(([n,r])=>r.turnId&&r.anchorId?[{taskId:`codex-agent:${n}`,toolUseId:r.anchorId,description:r.label,taskType:"codex_subagent",since:r.since??new Date().toISOString()}]:[]),t=e.map(n=>n.taskId).join(`
33
+ `);t!==this.publishedSubagents&&(this.publishedSubagents=t,this.emit({type:"background-tasks",tasks:e,awaitsReply:!1}))}recordSubagentUsage(e,t,n){let r=b(n.total),i=t.total;t.total=r;let o=l(d=>typeof d=="number"&&Number.isFinite(d)&&d>0?d:0,"count"),a=i&&o(r.totalTokens)>=o(i.totalTokens)?d=>Math.max(0,o(r[d])-o(i[d])):d=>o(b(n.last)[d]),c=a("inputTokens"),u=a("outputTokens");!c&&!u||this.emit({type:"raw",method:"usage/recorded",payload:{id:`${xe(e)}usage:${o(r.totalTokens)}`,provider:"codex",model:t.model||this.model,fast:this.options?.agent.fast===!0,tokens:{input:c,cached:a("cachedInputTokens"),output:u}}})}async hydrateSubagents(){let e=new Set,t=l(()=>[...this.subagents].flatMap(([n,r])=>r.anchorId&&!e.has(n)&&!this.options?.stored?.has(xe(n))?[{threadId:n,anchorId:r.anchorId}]:[]),"unread");for(let n=t();n.length&&!this.closing;n=t())for(let r of n){e.add(r.threadId);let i=null;for(let o=0;o<100&&!this.closing;o++){let a=await this.client().request("thread/turns/list",{threadId:r.threadId,cursor:i,limit:50,sortDirection:"asc",itemsView:"full"});for(let c of a.data??[])for(let u of c.items??[])this.entry(u,r,c.status==="inProgress"?"history":"endedTurn");if(i=a.nextCursor??null,!i)break}this.anchorOrphans(r.threadId)}}receive(e){if(this.closing)return;let{method:t,id:n}=e;if(!t)return;let r=e.params??{};if(t==="mcpServer/oauthLogin/completed"){this.mcpSignIn?.completed(r);return}let i=m(r.threadId);if(i&&this.threadId&&i!==this.threadId){this.receiveForeign(i,e);return}if(this.reconnecting!==null&&t.startsWith("item/")&&this.emit({type:"status",status:this.requests.size?"waiting":"working"}),n!==void 0){if(!this.request(e,t,n))return}else if(t==="turn/started")this.unfinishedMessages.clear(),this.retryMessages.clear(),this.turnId=m(b(r.turn).id),this.emit({type:"status",status:"working",turnId:this.turnId,error:null});else if(t==="turn/completed"){let o=b(r.turn);if(Array.isArray(o.items))for(let c of o.items)this.entry(c,void 0,"endedTurn");this.anchorOrphans(this.threadId??""),this.endDrafts(this.threadId??""),this.unfinishedMessages.clear(),this.retryMessages.clear(),this.turnId=null;for(let[c,u]of this.requests)this.subagentOf(u)||this.requests.delete(c);this.emit({type:"status",status:o.status==="failed"?"error":"idle",turnId:null,error:o.status==="failed"?m(b(o.error).message)||"Codex turn failed":null});let a=this.liveInteractions().filter(c=>c.agent);for(let c of a)this.emit({type:"interaction",interaction:c});a.length&&this.emit({type:"status",status:"waiting",turnId:null})}else if(t==="item/started"||t==="item/completed"){let o=b(r.item);this.entry(o,void 0,t==="item/started"?"started":"completed"),t==="item/completed"&&(!r.turnId||r.turnId===this.turnId)?this.completeMessage(o):o.type==="agentMessage"&&this.turnId&&(!r.turnId||r.turnId===this.turnId)&&this.unfinishedMessages.set(m(o.id),m(o.phase))}else if(t==="serverRequest/resolved"){let o=`${this.connectionId}:${r.requestId}`;this.requests.delete(o),this.emit({type:"interaction-resolved",id:o})}else if(t.startsWith("item/")&&typeof r.delta=="string"){let o=this.entries.get(m(r.itemId));o&&(o.role==="tool"?o.output=(o.output??"")+r.delta:o.text+=r.delta,this.emit({type:"entry",entry:{...o}}))}else if(t==="error"){let o=b(r.error),a=m(o.message)||"Codex error";if(this.turnId&&r.willRetry!==!1&&Yr(o,a)){for(let[c,u]of this.unfinishedMessages)this.retryMessages.set(c,u);this.reconnecting!==a&&(this.emit({type:"status",status:this.requests.size?"waiting":"working",retrying:a}),this.reconnecting=a)}else this.retryMessages.clear(),this.unfinishedMessages.clear(),this.emit({type:"status",status:"error",error:a})}typeof r.delta!="string"&&this.emit({type:"raw",method:t,payload:e})}request(e,t,n,r){let i=e.params??{},o=t==="mcpServer/elicitation/request",a=t==="item/permissions/requestApproval",c=t==="item/tool/requestUserInput"||o&&i.mode!=="url"&&Object.keys(b(b(i.requestedSchema).properties)).length>0;if(c&&this.options?.delegated)return this.rpc?.reject(n,B),!1;if(t==="item/tool/requestUserInput"&&(!Array.isArray(i.questions)||!i.questions.length||i.questions.some(g=>!m(b(g).id).trim()||!m(b(g).question).trim())))return this.rpc?.reject(n,"request_user_input requires at least one question with a nonempty id and question text."),!1;if(!c&&!o&&!a&&!["item/commandExecution/requestApproval","item/fileChange/requestApproval"].includes(t))return this.rpc?.reject(n,`Unsupported native interaction: ${t}`),this.emit({type:"raw",method:"host/unsupported-interaction",payload:{method:t}}),!1;let u=`${this.connectionId}:${n}`;this.requests.set(u,e);let d=Array.isArray(i.availableDecisions)?i.availableDecisions:a?["accept","acceptForSession","decline"]:["accept","decline"],f=d.map((g,w)=>typeof g=="string"?g:`option:${w}`),p={accept:"Allow once",acceptForSession:"Allow for this session",decline:"Decline",cancel:"Cancel turn"};return d.forEach((g,w)=>{typeof g!="string"&&(p[`option:${w}`]=Object.hasOwn(b(g),"acceptWithExecpolicyAmendment")?"Allow matching commands":`Apply network rule: ${JSON.stringify(g)}`)}),this.emit({type:"interaction",interaction:{id:u,kind:c?"question":"approval",method:t,...r?{agent:r}:{},title:o?`Request from ${m(i.serverName)}`:c?"Question from Codex":"Codex requests approval",body:o?m(i.message):c?"":[m(i.reason),m(i.command),i.additionalPermissions?JSON.stringify(i.additionalPermissions):"",i.command?"":JSON.stringify(i)].filter(Boolean).join(`
34
+ `),decisions:c?void 0:f,decisionLabels:c?void 0:p,url:o&&i.mode==="url"&&/^https?:\/\//.test(m(i.url))?m(i.url):void 0,questions:o&&c?Object.entries(b(b(i.requestedSchema).properties)).map(([g,w])=>{let h=b(w);return{id:g,question:m(h.title)||m(h.description)||g,required:Array.isArray(b(i.requestedSchema).required)&&b(i.requestedSchema).required.includes(g),inputType:["number","integer"].includes(m(h.type))?"number":"text",options:Array.isArray(h.enum)?h.enum.map(String):h.type==="boolean"?["true","false"]:void 0}}):Array.isArray(i.questions)?i.questions.map(g=>{let w=be(b(g).options);return{id:m(b(g).id),...ve(b(g).header),inputType:b(g).isSecret?"password":"text",...w,...ne(m(b(g).question),w.options,w.optionDescriptions)}}):void 0,providerData:i}}),this.emit({type:"status",status:"waiting",turnId:this.turnId}),!0}async connect(e){if(this.rpc)throw new Error("Codex driver is already connected");e={...e,agent:an(e.agent)},this.sandbox&&await this.sandbox.prepare(e),this.options=e,this.closing=!1,this.appsRefreshUnsupported=!1,this.threadId=e.threadId??null;let t=this.factory(e.cwd,n=>this.receive(n),n=>{this.closing||(this.endDrafts(),this.emit({type:"status",status:"disconnected",turnId:null,error:n.message}))});this.rpc=t;try{await t.request("initialize",{clientInfo:this.host.clientInfo,capabilities:{experimentalApi:!0}}),t.notifyInitialized();let n;try{n=await t.request("account/read",{refreshToken:!1})}catch(p){if(!e.catalogOnly)throw p;n=null}if(e.catalogOnly){if(n?.requiresOpenaiAuth&&!n.account)throw new Error("Sign in with codex login, then reconnect");return}if(!n)throw new Error("Could not read the Codex account");if(n.requiresOpenaiAuth&&!n.account)throw new Error("Sign in with codex login, then reconnect");e.delegated&&await Ke(t,e.cwd,this.sandbox?.questionPolicy()),e.agent.questionOnly&&await Ke(t,e.cwd,this.sandbox?.questionPolicy(!0)??We());let r={};e.delegated&&(r["features.default_mode_request_user_input"]=!1,r["tools.experimental_request_user_input.enabled"]=!1),e.agent.questionOnly&&(r["features.default_mode_request_user_input"]=!0,r["tools.experimental_request_user_input.enabled"]=!0,Object.assign(r,Object.fromEntries(["shell_tool","apply_patch_freeform","code_mode","apps","plugins","multi_agent","multi_agent_v2","browser_use","computer_use","image_generation"].map(p=>[`features.${p}`,!1])))),e.agent.effort&&(r.model_reasoning_effort=e.agent.effort);let i=e.agent.questionOnly||this.sandbox?void 0:e.localMcpServers;(e.mcpServers||i)&&(r.mcp_servers={...Object.fromEntries(Object.entries(i??{}).map(([p,g])=>[p,{command:g.command,args:g.args,...g.env?{env:g.env}:{},...g.toolTimeoutMs?{tool_timeout_sec:Math.ceil(g.toolTimeoutMs/1e3)}:{}}])),...Object.fromEntries(Object.entries(e.mcpServers??{}).map(([p,g])=>[p,{url:g.url,http_headers:es(this.host,g),startup_timeout_sec:this.host.mcpStartupMs/1e3,...g.approvedTools?.length?{tools:Object.fromEntries(g.approvedTools.map(w=>[w,{approval_mode:"approve"}]))}:{}}]))});let o=this.sandbox?void 0:ln(e);o&&(r.mcp_servers={...r.mcp_servers,[Xe]:{url:o.url,http_headers:o.headers,startup_timeout_sec:this.host.mcpStartupMs/1e3}});let a=e.harness?.codex,c=e.agent.plan||e.agent.readOnly?"read-only":a?.sandbox??"danger-full-access";c==="workspace-write"&&a?.networkAccess&&(r.sandbox_workspace_write={network_access:!0}),r.web_search=e.agent.toolFree||e.agent.questionOnly?"disabled":a?.webSearch??"live";let u={cwd:e.cwd,model:e.agent.model,sandbox:c,approvalPolicy:a?.approvalPolicy??"never",...a?.personality?{personality:a.personality}:{},serviceTier:on(e.agent.fast),config:r,developerInstructions:[e.instructions,this.host.codexInstructions,!this.sandbox&&!e.agent.questionOnly&&!e.agent.toolFree&&Xt].filter(Boolean).join(`
35
+
36
+ `)},d=await t.request(e.threadId?"thread/resume":"thread/start",e.threadId?{...u,threadId:e.threadId}:{...u,ephemeral:!1}).catch(p=>{throw e.threadId&&p instanceof N&&Zr(p.message)?new q("Codex",e.threadId):p});if(!d.thread?.id)throw new Error("Codex returned no thread ID");this.threadId=d.thread.id,this.model=d.model,this.emit({type:"settings",agent:{model:d.model,effort:d.reasoningEffort??e.agent.effort,fast:d.serviceTier==="priority",plan:e.agent.plan??!1}}),this.emit({type:"thread",threadId:d.thread.id}),this.emit({type:"codex-login",login:ns(n)});for(let p of d.thread.turns??[])for(let g of p.items??[])this.entry(g,void 0,p.status==="inProgress"?"history":"endedTurn");this.anchorOrphans(d.thread.id),await(this.sandbox?this.sandbox.verifyMcp(e.mcpServers??{}):we(e.mcpServers,this.host.mcpStartupMs,(p,g)=>this.injectedMcpState(p,g)));let f=d.thread.turns?.find(p=>p.status==="inProgress");this.turnId=f?.id??null,this.emit({type:"status",status:f?"working":"idle",turnId:this.turnId,error:null}),this.hydrateSubagents().catch(p=>this.emit({type:"raw",method:"codex/subagent.history.failed",payload:{error:String(p)}}))}catch(n){throw await this.close(),n}}client(){if(!this.rpc||!this.threadId)throw new Error("Connect the native Codex session first");return this.rpc}async skills(){if(!this.rpc)throw new Error("Initialize Codex before reading skills");let e=await this.rpc.request("skills/list",{cwds:[this.options?.cwd??""],forceReload:!1});return((e.data.find(n=>n.cwd===this.options?.cwd)??e.data[0])?.skills??[]).filter(n=>n.enabled).map(n=>({name:n.name,description:n.description,argumentHint:"[instructions]",path:n.path}))}async commands(){return(await this.skills()).map(e=>({...e,skill:!0,plugin:/[\\/]plugins[\\/]cache[\\/][^\\/]+[\\/]([^\\/]+)[\\/]/.exec(e.path)?.[1]??null}))}async input(e){let t=(e.attachments??[]).map(r=>r.mimeType?.startsWith("image/")?{type:"localImage",path:r.path}:{type:"mention",name:r.path.split("/").at(-1),path:r.path}),n=(await this.skills()).sort((r,i)=>i.name.length-r.name.length);for(let r of n){let i=r.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),o=new RegExp(`(^|\\s)/${i}(?=\\s|$)`,"i").exec(e.text);if(o){let a=o.index+o[1].length,c=e.text.slice(0,a).trimEnd(),u=e.text.slice(a+r.name.length+1).trimStart(),d=[c,u].filter(Boolean).join(" ");return[{type:"skill",name:r.name,path:r.path},...d?[{type:"text",text:d,text_elements:[]}]:[],...t]}}return[{type:"text",text:e.text,text_elements:[]},...t]}async refreshTools(){if(!(this.appsRefreshUnsupported||this.options?.agent.questionOnly||this.options?.agent.toolFree||this.turnId||this.requests.size||[...this.subagents.values()].some(e=>e.turnId)))try{await this.client().request("app/installed",{threadId:this.threadId,forceRefresh:!0})}catch(e){e instanceof N&&e.code===-32601&&(this.appsRefreshUnsupported=!0),this.emit({type:"raw",method:"codex/apps.refresh.failed",payload:{unsupported:this.appsRefreshUnsupported}})}}async appConnectionContext(e){if(this.sandbox||e.questionOnly||e.toolFree)return;let{rpc:t,threadId:n}=this.mcpRpc(),r=await Jt(t,n).catch(()=>[]);if(r.length)return{farero_chatgpt_apps:{kind:"untrusted",name:"chatgpt_app_connections",value:JSON.stringify(r)}}}async send(e,t=this.options?.agent??{}){t=an(t);let n=this.options?.harness?.codex,r=t.plan||t.readOnly?"read-only":n?.sandbox??"danger-full-access",i=r==="read-only"?{type:"readOnly"}:r==="workspace-write"?{type:"workspaceWrite",networkAccess:n?.networkAccess??!1}:{type:"dangerFullAccess"},o=this.client(),a=this.threadId,[c,u]=await Promise.all([this.input(e),this.appConnectionContext(t)]);await o.request("turn/start",{threadId:a,input:c,...u?{additionalContext:u}:{},clientUserMessageId:e.requestId,model:t.model,effort:t.effort,...!!t.plan!=!!this.options?.agent.plan?{sandboxPolicy:i}:{},collaborationMode:{mode:t.plan?"plan":"default",settings:{model:t.model??this.model,reasoning_effort:t.effort??null,developer_instructions:null}},serviceTier:on(t.fast)}),this.options&&(this.options.agent=t)}async steer(e,t){if(!this.turnId)throw new N("The turn already finished",409);await this.client().request("turn/steer",{threadId:this.threadId,expectedTurnId:this.turnId,input:await this.input(e),clientUserMessageId:e.requestId})}async stop(){this.turnId&&await this.client().request("turn/interrupt",{threadId:this.threadId,turnId:this.turnId}),await Promise.allSettled([...this.subagents].flatMap(([e,t])=>t.turnId?[this.client().request("turn/interrupt",{threadId:e,turnId:t.turnId})]:[]))}async answer(e,t){let n=this.requests.get(e);if(n?.id===void 0)throw new Error("This interaction has already closed");if(n.method==="item/permissions/requestApproval"){if(!["accept","acceptForSession","decline"].includes(t.decision??""))throw new Error("Choose a permission decision");let r=t.decision==="decline"?{}:Object.fromEntries(Object.entries(b(n.params?.permissions)).filter(([,i])=>i!==null));this.client().respond(n.id,{permissions:r,scope:t.decision==="acceptForSession"?"session":"turn"})}else if(n.method==="mcpServer/elicitation/request"){let r=t.decision??"accept";if(!["accept","decline","cancel"].includes(r))throw new Error("Choose an elicitation decision");let i=null;if(r==="accept"&&n.params?.mode!=="url"){i={};let o=b(n.params?.requestedSchema);for(let[a,c]of Object.entries(b(o.properties))){let u=t.answers?.[a]?.[0];if(!u){if(Array.isArray(o.required)&&o.required.includes(a))throw new Error(`Answer ${a}`);continue}let d=b(c).type,f=d==="boolean"?u==="true":d==="number"||d==="integer"?Number(u):u;if(d==="boolean"&&!["true","false"].includes(u))throw new Error(`Choose true or false for ${a}`);if(typeof f=="number"&&(!Number.isFinite(f)||d==="integer"&&!Number.isInteger(f)))throw new Error(`Enter a valid number for ${a}`);if(Array.isArray(b(c).enum)&&!b(c).enum.includes(f))throw new Error(`Choose a listed value for ${a}`);i[a]=f}}r==="cancel"&&await this.stopTurnOf(n),this.client().respond(n.id,{action:r,content:i,_meta:null})}else if(n.method==="item/tool/requestUserInput"){if(t.decision==="decline"){await this.stopTurnOf(n);return}let r=n.params?.questions;if(!Array.isArray(r))throw new Error("Unsupported question shape");let i={};for(let o of r){let a=m(b(o).id),c=t.answers?.[a];if(!c?.length||c.some(u=>!u.trim()))throw new Error("Answer every question");i[a]={answers:c}}this.client().respond(n.id,{answers:i})}else{let r=n.params?.availableDecisions,o=(Array.isArray(r)?r:["accept","decline"]).find((a,c)=>(typeof a=="string"?a:`option:${c}`)===t.decision);if(o===void 0)throw new Error("This decision is unavailable");this.client().respond(n.id,{decision:o})}this.requests.delete(e),this.emit({type:"interaction-resolved",id:e}),this.requests.size||this.emit({type:"status",status:this.turnId?"working":"idle",turnId:this.turnId})}async activity(){let{thread:e}=await this.client().request("thread/read",{threadId:this.threadId,includeTurns:!1});if(!["idle","active"].includes(e.status.type))throw new Error(`Codex activity unavailable: ${e.status.type}`);let t=e.status.activeFlags??[],n=this.liveInteractions();return{interactions:n,running:e.status.type==="active",providerTurnId:this.turnId,blockedOn:t.includes("waitingOnUserInput")?"question":t.includes("waitingOnApproval")?"approval":n.find(r=>r.agent)?.kind??null}}async models(){if(!this.rpc)throw new Error("Initialize Codex before reading models");return(await this.rpc.request("model/list",{})).data.map(t=>({id:t.model||t.id,name:t.displayName,...t.description?.trim()?{description:t.description.trim()}:{},provider:"codex",default:t.isDefault,fast:t.serviceTiers?.some(n=>n.id==="priority"),plan:!0,efforts:t.supportedReasoningEfforts.map(n=>n.reasoningEffort)}))}async fork(){if(this.turnId)throw new Error("Wait for the active turn before forking");let e=await this.client().request("thread/fork",{threadId:this.threadId,cwd:this.options?.cwd});if(!e.thread.id)throw new Error("Codex returned no fork ID");return e.thread.id}async close(){this.closing=!0,this.endDrafts(),await this.rpc?.close(),this.rpc=null,this.requests.clear(),this.turnId=null,this.publishedSubagents&&this.emit({type:"background-tasks",tasks:[],awaitsReply:!1}),this.publishedSubagents="",this.subagents.clear(),this.foreign.clear(),this.pendingThreads.clear(),this.ownership.clear()}};import{randomUUID as Ze}from"node:crypto";import{mkdirSync as gn}from"node:fs";import _e from"node:path";import{execFile as as}from"node:child_process";import{homedir as cs}from"node:os";var ls={claude:"Claude Code",codex:"Codex"},us={claude:"claude auth login",codex:"codex login"},ds={claude:["auth","status"],codex:["login","status"]};function j(s,e,t){let n=ls[s],r={ready:`${n} is signed in.`,missing:`${n} is not installed. Install it, then check again.`,"sign-in":`Run ${us[s]} in Terminal to sign in to ${n}, then check again.`,unavailable:`${n} did not answer. Update it, then check again.`}[e];return{state:e,message:r,...t?{method:t}:{}}}l(j,"status");function ps(s,e,t){return new Promise(n=>{as(s,e,{cwd:cs(),env:t,timeout:1e4,maxBuffer:256*1024,windowsHide:!0},(r,i,o)=>{let a=r?typeof r.code=="number"?r.code:null:0;n({code:a,output:`${i}
37
+ ${o}`,stdout:i})})})}l(ps,"run");async function Je(s,e,t){let n=s.launch(e,t);if(!n.resolved)return j(e,"missing");let r=s.environment({provider:e,envKeys:t?.envKeys}),i=await ps(n.command,[...n.args,...ds[e]],r);if(e==="claude"){let a;try{let c=JSON.parse(i.stdout);c&&typeof c=="object"&&!Array.isArray(c)&&(a=c)}catch{}return typeof a?.loggedIn!="boolean"?j(e,"unavailable"):a.loggedIn?j(e,"ready",typeof a.authMethod=="string"?a.authMethod:void 0):j(e,"sign-in")}let o=/logged in using\s+(.+)/i.exec(i.output);return i.code===0&&o?j(e,"ready",o[1].split(`
38
+ `)[0]?.trim()):i.code!==null&&i.code!==0?j(e,"sign-in"):j(e,"unavailable")}l(Je,"connectionStatus");import{closeSync as gs,mkdirSync as hs,openSync as ms}from"node:fs";import ys from"node:path";import{DatabaseSync as ws}from"node:sqlite";var un=1024*1024;function fs(s,e,t){if(t<=e)return s;let n=Buffer.from(s),r=e;for(;r>0&&r<n.length&&(n[r]&192)===128;)r--;return n.subarray(0,r).toString()}l(fs,"utf8Prefix");function dn(s,e){if(s.role!=="tool")return s;let t=["text","detail","output"],n=t.map(a=>Buffer.byteLength(s[a]??"")),r=n.reduce((a,c)=>a+c,0);if(r<=un)return s;let i=un,o={...s,outputTruncated:!0,outputOriginalBytes:e?.outputTruncated?e.outputOriginalBytes:r};for(let[a,c]of t.entries()){let u=s[c];u!==void 0&&(o[c]=fs(u,i,n[a]),i-=Buffer.byteLength(o[c]??""))}return o}l(dn,"boundToolEntry");function Qe(s){return!lt(s.text)&&!W(s.text)&&!D(s.text)&&!D(s.output)}l(Qe,"shownTranscriptRow");function Ye(s){return!s.supersededBy&&Qe(s)&&(s.role!=="thinking"||!!s.text.trim())}l(Ye,"listedTranscriptRow");function H(s){return s==="running"||s==="waiting"}l(H,"chatBusy");var bs={claude:"Claude Code",codex:"Codex"},vs=new Set(["ts","rowid","revision","queued"]),pn="id, provider, title, cwd, threadId, status, error, agent, interactions, createdAt, updatedAt, seq";function fn(s){return{id:s.id,provider:s.provider,title:s.title,cwd:s.cwd,threadId:s.threadId,status:s.status,error:s.error,agent:JSON.parse(s.agent),interactions:JSON.parse(s.interactions),createdAt:s.createdAt,updatedAt:s.updatedAt,revision:s.seq}}l(fn,"chatOf");function Ee(s){return{...JSON.parse(s.entry),rowid:s.rowid,revision:s.revision,queued:!1}}l(Ee,"entryOf");function ks(s){return s.running===!0||s.draft===!0&&!s.aborted}l(ks,"openRow");function Ss(s,e){let t=new Set([...Object.keys(s),...Object.keys(e)]);for(let n of t){if(vs.has(n))continue;let r=s[n],i=e[n];if(r!==i&&JSON.stringify(r)!==JSON.stringify(i))return!1}return!0}l(Ss,"sameContent");var ae=class{static{l(this,"TranscriptStore")}database;listeners=new Set;constructor(e){hs(ys.dirname(e),{recursive:!0,mode:448}),gs(ms(e,"a",384)),this.database=new ws(e);try{this.probe(),this.database.exec(`
39
+ PRAGMA journal_mode = WAL;
40
+ PRAGMA busy_timeout = 5000;
41
+ CREATE TABLE IF NOT EXISTS stamp (id INTEGER PRIMARY KEY CHECK (id = 1), value INTEGER NOT NULL) STRICT;
42
+ INSERT OR IGNORE INTO stamp (id, value) VALUES (1, 0);
43
+ CREATE TABLE IF NOT EXISTS chats (
44
+ id TEXT PRIMARY KEY,
45
+ provider TEXT NOT NULL,
46
+ title TEXT NOT NULL,
47
+ cwd TEXT NOT NULL,
48
+ threadId TEXT,
49
+ status TEXT NOT NULL CHECK (status IN ('idle', 'running', 'waiting', 'error')),
50
+ error TEXT,
51
+ agent TEXT NOT NULL,
52
+ interactions TEXT NOT NULL DEFAULT '[]',
53
+ createdAt TEXT NOT NULL,
54
+ updatedAt TEXT NOT NULL,
55
+ seq INTEGER NOT NULL
56
+ ) STRICT;
57
+ CREATE TABLE IF NOT EXISTS entries (
58
+ rowid INTEGER PRIMARY KEY,
59
+ id TEXT NOT NULL,
60
+ chatId TEXT NOT NULL REFERENCES chats(id),
61
+ entry TEXT NOT NULL,
62
+ revision INTEGER NOT NULL,
63
+ seq INTEGER NOT NULL,
64
+ UNIQUE (chatId, id)
65
+ ) STRICT;
66
+ CREATE INDEX IF NOT EXISTS entries_changes ON entries (chatId, seq);
67
+ `),this.interrupt()}catch(t){throw this.database.close(),t}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}list(){return this.database.prepare(`SELECT ${pn} FROM chats ORDER BY updatedAt DESC, rowid DESC`).all().map(fn)}chat(e){let t=this.database.prepare(`SELECT ${pn} FROM chats WHERE id = ?`).get(e);return t?fn(t):null}read(e){return this.reading(()=>{let t=this.chat(e);if(!t)return null;let n=this.database.prepare("SELECT rowid, entry, revision, seq FROM entries WHERE chatId = ? ORDER BY rowid").all(e);return{chat:t,entries:n.map(Ee).filter(Ye),revision:t.revision}})}changes(e,t){return this.reading(()=>{let n=this.chat(e);if(!n)return null;let r=this.database.prepare("SELECT rowid, entry, revision, seq FROM entries WHERE chatId = ? AND seq > ? ORDER BY seq, rowid").all(e,t),i=[],o=[];for(let a of r.map(Ee))Ye(a)?i.push(a):o.push(a.id);return{chat:n.revision>t?n:null,entries:i,removed:o,revision:n.revision}})}stored(e){return{after:l(()=>this.database.prepare(`SELECT MAX(json_extract(entry, '$.ts')) AS ts FROM entries
68
+ WHERE chatId = ? AND json_extract(entry, '$.role') IN ('assistant', 'thinking', 'tool')`).get(e)?.ts??void 0,"after"),has:l(t=>!!this.database.prepare("SELECT 1 FROM entries WHERE chatId = ? AND substr(id, 1, length(?)) = ? LIMIT 1").get(e,t,t),"has")}}create(e,t,n=new Date().toISOString()){return this.write(e.id,r=>(this.database.prepare(`INSERT INTO chats (id, provider, title, cwd, threadId, status, error, agent, interactions, createdAt, updatedAt, seq)
69
+ VALUES (?, ?, ?, ?, NULL, 'running', NULL, ?, '[]', ?, ?, ?)`).run(e.id,e.provider,e.title,e.cwd,JSON.stringify(e.agent),n,n,r),this.insertEntry(e.id,t,r),!0)),this.chat(e.id)}prompt(e,t){this.write(e,n=>(this.touch(e,{status:"running",error:null},n),this.insertEntry(e,t,n),!0))}update(e,t){this.write(e,n=>{let r=this.chat(e);return!r||!Object.keys(t).some(o=>JSON.stringify(r[o])!==JSON.stringify(t[o]))?!1:(this.touch(e,t,n),!0)})}record(e,t){Qe({...t,rowid:0,queued:!1})&&(t.role==="thinking"&&!t.text.trim()||this.write(e,n=>{let r=this.database.prepare("SELECT rowid, entry, revision, seq FROM entries WHERE chatId = ? AND id = ?").get(e,t.id),i=r?Ee(r):void 0,o=dn(t,i);return i?.supersededBy&&(o={...o,supersededBy:i.supersededBy}),i?.mcpSignIn&&!o.mcpSignIn&&(o={...o,mcpSignIn:i.mcpSignIn}),i?.app&&!o.app&&(o={...o,app:i.app}),i?.origin&&!o.origin&&(o={...o,origin:i.origin}),i&&r&&Ss(i,o)?!1:(i&&r?this.database.prepare("UPDATE entries SET entry = ?, revision = ?, seq = ? WHERE rowid = ?").run(JSON.stringify({...o,ts:i.ts}),r.revision+1,n,r.rowid):this.insertEntry(e,o,n),this.touch(e,{},n),!0)}))}close(){this.listeners.clear(),this.database.close()}interrupt(){let e=this.database.prepare("SELECT id, provider FROM chats WHERE status IN ('running', 'waiting')").all();for(let{id:t,provider:n}of e)this.write(t,r=>{let i=bs[n]??n;this.touch(t,{status:"error",error:`The ${i} reply was interrupted.`,interactions:[]},r);let o=this.database.prepare("SELECT rowid, entry, revision, seq FROM entries WHERE chatId = ?").all(t);for(let a of o){let c=Ee(a);if(!ks(c))continue;let{rowid:u,revision:d,queued:f,...p}=c;this.database.prepare("UPDATE entries SET entry = ?, revision = ?, seq = ? WHERE rowid = ?").run(JSON.stringify({...p,running:!1,aborted:!0}),a.revision+1,r,a.rowid)}return!0})}probe(){let e={chats:["provider","cwd","threadId","status","agent","interactions","seq"],entries:["chatId","entry","revision","seq"]};for(let[t,n]of Object.entries(e)){let r=this.database.prepare(`PRAGMA table_info(${t})`).all();if(r.length&&!n.every(i=>r.some(o=>o.name===i)))throw new Error("This transcript file was written by another store. Give the agent runtime a folder of its own.")}}insertEntry(e,t,n){this.database.prepare("INSERT INTO entries (id, chatId, entry, revision, seq) VALUES (?, ?, ?, 1, ?)").run(t.id,e,JSON.stringify(t),n)}touch(e,t,n){let r={updatedAt:new Date().toISOString(),seq:n};t.threadId!==void 0&&(r.threadId=t.threadId),t.status!==void 0&&(r.status=t.status),t.error!==void 0&&(r.error=t.error),t.agent!==void 0&&(r.agent=JSON.stringify(t.agent)),t.interactions!==void 0&&(r.interactions=JSON.stringify(t.interactions));let i=Object.keys(r).map(o=>`${o} = ?`);this.database.prepare(`UPDATE chats SET ${i.join(", ")} WHERE id = ?`).run(...Object.values(r),e)}write(e,t){this.database.exec("BEGIN IMMEDIATE");let n;try{let{value:r}=this.database.prepare("UPDATE stamp SET value = value + 1 WHERE id = 1 RETURNING value").get();t(r)&&(n=r),this.database.exec(n===void 0?"ROLLBACK":"COMMIT")}catch(r){throw this.database.exec("ROLLBACK"),r}if(n!==void 0)for(let r of[...this.listeners])try{r({chatId:e,revision:n})}catch{}}reading(e){this.database.exec("BEGIN");try{return e()}finally{this.database.exec("COMMIT")}}};var xs=2e3,Es=10*6e4,et={claude:"Claude Code",codex:"Codex"};function hn(s){return Object.fromEntries(Object.entries(s??{}).filter(([,e])=>e!==void 0))}l(hn,"defined");function _s(s){let e={source:"path",customPath:""};return{claude:{...Ie.claude,permissionMode:"default",runtime:e,...hn(s?.claude)},codex:{...Ie.codex,sandbox:"workspace-write",approvalPolicy:"on-request",runtime:e,...hn(s?.codex)}}}l(_s,"harnessOf");function As(s){return s instanceof Error?s.message:String(s)}l(As,"messageOf");function ce(s){let e;return Promise.race([s.then(()=>{},()=>{}),new Promise(t=>{e=setTimeout(t,xs)})]).finally(()=>clearTimeout(e))}l(ce,"grace");var tt=class s{constructor(e){this.options=e;let t=_e.resolve(e.directory);this.workspace=_e.join(t,"workspace"),this.mcpConfigDir=_e.join(t,"mcp"),gn(this.workspace,{recursive:!0,mode:448}),gn(this.mcpConfigDir,{recursive:!0,mode:448}),this.store=new ae(_e.join(t,"agent-runner.sqlite"));let n=e.host??Ce();this.host=n,this.harness=_s(e.harness),this.drivers={claude:l(r=>new re(r,{host:n}),"claude"),codex:l(r=>new oe(r,{host:n}),"codex"),...e.drivers}}static{l(this,"AgentRuntime")}store;host;harness;drivers;connections=new Map;stops=new Set;workspace;mcpConfigDir;closed=!1;static async open(e){return new s(e)}list(){return this.store.list()}read(e){let t=this.store.read(e);return t&&{...t,interactions:t.chat.interactions}}changes(e,t){return this.store.changes(e,t)}subscribe(e){return this.store.subscribe(e)}async start({provider:e,title:t,prompt:n,cwd:r,agent:i}){if(this.assertOpen(),!this.drivers[e])throw new Error(`This runtime has no driver for ${e}.`);let o=t.trim();if(!o)throw new Error("Enter a chat title.");if(!n.trim())throw new Error("Enter a prompt.");let a=Ze(),c=this.request(n),u=this.store.create({id:a,provider:e,title:o,cwd:r??this.workspace,agent:i??{}},c.entry);return this.turn(a,c.prompt),u}async send(e,t){this.assertOpen();let n=this.store.chat(e);if(!n)throw new Error("This chat could not be found.");if(H(n.status))throw new Error(`Wait for the current ${et[n.provider]??"agent"} reply to finish.`);if(!t.trim())throw new Error("Enter a prompt.");let r=this.request(t);this.store.prompt(e,r.entry),this.stops.delete(e),this.turn(e,r.prompt)}async stop(e){let t=this.store.chat(e);if(!t||!H(t.status))return;this.stops.add(e);let n=this.connections.get(e);if(!n){this.store.update(e,{status:"idle",interactions:[]});return}if(!n.turn)return;let r=!1;await ce(n.driver.stop().then(()=>{r=!0}));let i=this.store.chat(e);this.connections.get(e)===n&&i&&(!r||H(i.status)||n.backgroundTasks)&&await this.forceStop(e,n)}async answer(e,t,n){let r=this.connections.get(e);if(!r||!this.store.chat(e)?.interactions.some(i=>i.id===t))throw new Error("This request is no longer open.");await r.driver.answer(t,n)}connectionStatus(e){return Je(this.host,e,this.harness[e])}async close(){if(this.closed)return;this.closed=!0;let e=[...this.connections.values()];this.connections.clear();for(let t of e)this.release(t);this.store.interrupt(),await Promise.all(e.map(t=>ce(t.driver.close()))),this.store.close()}assertOpen(){if(this.closed)throw new Error("The agent runtime is closed.")}request(e){let t=Ze();return{prompt:{requestId:t,text:e,origin:"human"},entry:{id:t,role:"user",text:e,ts:new Date().toISOString(),origin:"human"}}}async turn(e,t){try{let n=await this.connect(e);if(this.stops.has(e)||this.connections.get(e)!==n){this.stops.delete(e),this.store.update(e,{status:"idle"});return}n.turn=t.requestId,await n.driver.send(t,this.store.chat(e)?.agent)}catch(n){if(n instanceof V)return;this.fail(e,n)}}fail(e,t){if(this.closed)return;let n=this.connections.get(e);this.store.update(e,{status:"error",error:As(t),interactions:[]}),n&&(this.drop(e,n),ce(n.driver.close()))}async connect(e){let t=this.connections.get(e);if(t)return clearTimeout(t.park),await t.ready,t;let n=this.store.chat(e);if(!n)throw new Error("This chat could not be found.");let r=this.drivers[n.provider];if(!r)throw new Error(`This runtime has no driver for ${n.provider}.`);let i={driver:this.driver(e,r,n,()=>i),ready:Promise.resolve(),connected:!1,turn:null,backgroundTasks:0,decisions:new Map};this.connections.set(e,i),i.ready=this.open(e,n,r,i);try{await i.ready}catch(o){throw this.connections.get(e)===i&&this.connections.delete(e),o}return i}driver(e,t,n,r){let i=t(o=>{let a=r();!this.closed&&this.connections.get(e)===a&&a.driver===i&&this.event(e,a,o)},n);return i}async open(e,t,n,r){let i=await this.options.connection?.(e)??{},o=l(a=>({cwd:t.cwd,...a?{threadId:a}:{},agent:t.agent,harness:this.harness,mcpConfigDir:this.mcpConfigDir,stored:this.store.stored(e),...i.mcpServers?{mcpServers:i.mcpServers}:{},...i.localMcpServers?{localMcpServers:i.localMcpServers}:{},...i.instructions?{instructions:i.instructions}:{},...i.toolEnvironment?{toolEnvironment:i.toolEnvironment}:{}}),"options");try{await r.driver.connect(o(t.threadId))}catch(a){if(!(a instanceof q)||!t.threadId)throw a;this.store.update(e,{threadId:null}),this.store.record(e,{id:`new-thread-${Ze()}`,role:"system",text:`${et[t.provider]??"The provider"} no longer has this conversation, so the reply starts a new one.`,ts:new Date().toISOString()}),r.driver=this.driver(e,n,t,()=>r),await r.driver.connect(o(null))}r.connected=!0}event(e,t,n){if(n.type==="thread")this.store.update(e,{threadId:n.threadId});else if(n.type==="settings"){let r=this.store.chat(e);r&&this.store.update(e,{agent:{...r.agent,...n.agent}})}else n.type==="entry"?this.store.record(e,n.entry):n.type==="interaction"?this.interaction(e,t,n.interaction):n.type==="interaction-resolved"?this.resolved(e,t,n.id):n.type==="background-tasks"?t.backgroundTasks=n.tasks.length:n.type==="status"&&t.connected&&this.status(e,t,n)}status(e,t,n){let r=this.store.chat(e);if(!r)return;let i=et[r.provider]??"The provider";switch(n.status){case"working":this.store.update(e,{status:"running",...n.error!==void 0?{error:n.error}:{}});return;case"waiting":this.store.update(e,{status:"waiting"});return;case"idle":this.settle(e,t,{status:"idle",...n.error!==void 0?{error:n.error}:{}});return;case"error":this.settle(e,t,{status:"error",error:n.error??`${i} could not finish the reply.`});return;case"disconnected":this.settle(e,t,H(r.status)?{status:"error",error:n.error??`${i} stopped during the reply.`}:{status:r.status}),this.drop(e,t);return;default:return}}settle(e,t,n){t.turn=null,this.stops.delete(e),this.release(t),this.store.update(e,{...n,interactions:[]}),t.park=setTimeout(()=>{let r=this.store.chat(e);this.connections.get(e)!==t||t.turn||t.backgroundTasks||r&&H(r.status)||(this.drop(e,t),ce(t.driver.close()))},Es),t.park.unref?.()}interaction(e,t,n){let r=this.store.chat(e);if(!r)return;let i=r.interactions.some(c=>c.id===n.id);this.store.update(e,{interactions:i?r.interactions.map(c=>c.id===n.id?n:c):[...r.interactions,n]});let o=this.options.decide;if(!o||t.decisions.has(n.id))return;let a=new AbortController;t.decisions.set(n.id,a),(async()=>{try{let c=await o(e,n,a.signal);c&&!a.signal.aborted&&this.connections.get(e)===t&&await t.driver.answer(n.id,c)}catch{}finally{t.decisions.get(n.id)===a&&t.decisions.delete(n.id)}})()}resolved(e,t,n){t.decisions.get(n)?.abort(),t.decisions.delete(n);let r=this.store.chat(e);r?.interactions.some(i=>i.id===n)&&this.store.update(e,{interactions:r.interactions.filter(i=>i.id!==n)})}async forceStop(e,t){this.drop(e,t),await ce(t.driver.close()),this.stops.delete(e),this.store.update(e,{status:"idle",error:null,interactions:[]})}drop(e,t){this.connections.get(e)===t&&this.connections.delete(e),this.release(t)}release(e){clearTimeout(e.park);for(let t of e.decisions.values())t.abort();e.decisions.clear()}};import{createHmac as Ts,randomBytes as Cs,timingSafeEqual as Rs}from"node:crypto";import Os from"node:http";import{Server as Is}from"@modelcontextprotocol/sdk/server/index.js";import{StreamableHTTPServerTransport as Ms}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as Ps,ListToolsRequestSchema as Ns}from"@modelcontextprotocol/sdk/types.js";var mn="/mcp";function yn(s){return{isError:!0,content:[{type:"text",text:s}]}}l(yn,"failure");async function Ls({tools:s,call:e,name:t="tools"}){let n=Cs(32),r=l(u=>`${Buffer.from(u).toString("base64url")}.${Ts("sha256",n).update(u).digest("base64url")}`,"token"),i=l(u=>{let d=/^Bearer ([\w-]+)\.([\w-]+)$/.exec(u??"");if(!d)return;let f=Buffer.from(d[1],"base64url").toString(),p=Buffer.from(r(f)),g=Buffer.from(`${d[1]}.${d[2]}`);return p.length===g.length&&Rs(p,g)?f:void 0},"caller"),o=l(async(u,d)=>{if(new URL(u.url??"/","http://127.0.0.1").pathname!==mn){d.writeHead(404).end();return}let f=i(u.headers.authorization);if(!f){d.writeHead(401,{"content-type":"application/json"}).end('{"error":"unauthorized"}');return}if(u.method!=="POST"){d.writeHead(405,{allow:"POST"}).end();return}let p=new AbortController,g=new Is({name:t,version:"1.0.0"},{capabilities:{tools:{}}});g.setRequestHandler(Ns,async()=>({tools:[...s]})),g.setRequestHandler(Ps,async(h,E)=>{let I=h.params.name;if(!s.some(T=>T.name===I))return yn(`Unknown tool ${I}`);try{return await e({chatId:f,name:I,args:h.params.arguments??{},signal:AbortSignal.any([E.signal,p.signal])})}catch(T){return yn(T instanceof Error?T.message:String(T))}});let w=new Ms({sessionIdGenerator:void 0,enableJsonResponse:!0});d.once("close",()=>{p.abort(),w.close(),g.close()}),await g.connect(w),await w.handleRequest(u,d)},"handle"),a=Os.createServer((u,d)=>{o(u,d).catch(()=>{d.headersSent||d.writeHead(500),d.end()})});await new Promise((u,d)=>{a.once("error",d),a.listen(0,"127.0.0.1",()=>{a.off("error",d),u()})});let{port:c}=a.address();return{url:`http://127.0.0.1:${c}${mn}`,headers:l(u=>({Authorization:`Bearer ${r(u)}`}),"headers"),close:l(()=>new Promise(u=>{a.closeAllConnections(),a.close(()=>u())}),"close")}}l(Ls,"serveTools");export{tt as AgentRuntime,re as NativeClaudeDriver,oe as NativeCodexDriver,ae as TranscriptStore,H as chatBusy,Je as connectionStatus,Ce as localHost,Ls as serveTools};
package/package.json CHANGED
@@ -1,6 +1,29 @@
1
1
  {
2
2
  "name": "@farero-ai/agent-runner",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "type": "module",
5
+ "license": "MIT",
6
+ "description": "Claude Code and Codex drivers with a local transcript store, for desktop apps.",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/farero-ai/farero.git",
10
+ "directory": "packages/agent-runner"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js"
16
+ }
17
+ },
18
+ "files": [
19
+ "dist"
20
+ ],
21
+ "engines": {
22
+ "node": ">=22.13"
23
+ },
24
+ "dependencies": {
25
+ "@anthropic-ai/claude-agent-sdk": "0.3.321",
26
+ "@modelcontextprotocol/sdk": "1.32.2",
27
+ "zod": "4.6.7"
28
+ }
29
+ }