@farero-ai/agent-runner 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +170 -2
- package/dist/index.d.ts +1417 -0
- package/dist/index.js +69 -0
- package/package.json +27 -4
package/dist/index.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
var yn=Object.defineProperty;var l=(s,e)=>yn(s,"name",{value:e,configurable:!0});import{accessSync as wn,constants as bn,readdirSync as vn,statSync as kn}from"node:fs";import{createRequire as Sn}from"node:module";import{homedir as rt}from"node:os";import C from"node:path";function le(s,e){return e?s==="claude"?{CLAUDE_CONFIG_DIR:e}:s==="codex"?{CODEX_HOME:e}:s==="opencode"?{XDG_DATA_HOME:e}:{}:{}}l(le,"homeEnvironment");var En=Sn(import.meta.url),tt={claude:"Claude Code",codex:"Codex"},xn=["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 Ae(s){try{return wn(s,bn.X_OK),kn(s).isFile()}catch{return!1}}l(Ae,"isExecutable");function _n(s){let e=C.join(s,".nvm","versions","node");try{return vn(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(_n,"nvmBins");function An(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=En.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(Ae)}l(An,"bundledClaude");function Tn(s,e){let t=rt(),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",..._n(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(Tn,"searchFolders");function nt(s,e,t){let n=e?.runtime;if(n?.source==="custom"){let o=n.customPath.trim();return o&&C.isAbsolute(o)&&Ae(o)?o:void 0}let r=process.platform==="win32"?`${s}.exe`:s,i=s==="claude"?An(r):void 0;return n?.source==="bundled"&&i?i:Tn(s,t).map(o=>C.join(o,r)).find(Ae)??i}l(nt,"findExecutable");function Te(s={}){let e=s.searchPaths??[];return{launch(t,n){let r=nt(t,n,e);return{command:r??t,args:[],resolved:r??null}},notInstalled(t,n){return new Error(n==="custom"?`${tt[t]} was not found at the selected path.`:`${tt[t]} is not installed on this computer. Install it, then try again.`)},environment({provider:t,workspaceEnv:n,accountHome:r,envKeys:i}){let o=nt(t,void 0,e),a={};for(let c of[...xn,...i??[]])process.env[c]!==void 0&&(a[c]=process.env[c]);return a.HOME??=rt(),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,...le(t,r)}},mcpStartupMs:s.mcpStartupMs??3e4,clientInfo:s.clientInfo??{name:"agent-runner",version:"0.1.0"}}}l(Te,"localHost");import{randomBytes as br,randomUUID as ve}from"node:crypto";import{mkdirSync as vr,readFileSync as kr,rmSync as Sr,writeFileSync as Er}from"node:fs";import xr from"node:path";import{forkSession as _r,query as Ar}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 Cn=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()}),Xs=P.object({version:P.literal(1),kind:P.enum(["fork","continue","reference"]),scope:P.enum(["chat","reply"]),sources:P.array(Cn).min(1)});var Rn=["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"],Ys=new Set(Rn.map(s=>s.toLowerCase().replace(/[_-]/g,"")));var Mn=1,Ji=`<farero-workflow-private version="${Mn}">`;var Qi=25*1024*1024;var Ce="Skill",st=["farero_host","farero","native"],Pn=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"]),Nn={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:Ce,todowrite:"TodoWrite",todoread:"TodoRead",question:"AskUserQuestion",askuserquestion:"AskUserQuestion",toolsearch:"ToolSearch",notebookedit:"NotebookEdit"};function it(s,e=""){let t=l((o,a)=>({name:o?`mcp__${o}__${a}`:`mcp__${a}`,label:a,server:o}),"mcp"),n=l(o=>st.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(Pn.has(o)?"farero_host":null,o):{name:s,label:s,server:null}}for(let o of st){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":Nn[r];return{name:i??s,label:i??s,server:null}}l(it,"toolIdentity");function Re(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(Re,"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 Ln=/^(?:\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&&Ln.test(s.trim())}l(W,"isLocalCommandNoise");function ot(s,e){return`Background task ${s}: ${e}`}l(ot,"backgroundTaskNotice");function at(s){return!!s&&s.includes("OpenCode is retrying the model request")}l(at,"isOpenCodeRetryNotice");var ct=String.raw`fb\.\d{1,2}\.\d{13}\.`,lt=String.raw`(?:\.(?:[A-Za-z0-9_-]{2}|[A-Za-z0-9_-]{8}))?`,Yi=new RegExp(`^${ct}\\d{1,32}${lt}$`),Zi=new RegExp(`^${ct}[A-Za-z0-9_-]{1,500}${lt}$`);var ut={artifacts:"CLAUDE_CODE_ARTIFACT",agentTeams:"CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS",taskTools:"CLAUDE_CODE_ENABLE_TODO_TOOLS"};var Oe={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 dt(s){return s==="bypassPermissions"}l(dt,"claudeCanDeclineSafetyChecks");var eo=720*60*60*1e3;var to=10*6e4;function Y(s){return e=>s[e]===!0}l(Y,"statusQuestion");var no=Y({disconnected:!1,connecting:!1,idle:!1,working:!0,waiting:!0,error:!1}),ro=Y({disconnected:!1,connecting:!0,idle:!1,working:!0,waiting:!0,error:!1}),so=Y({disconnected:!1,connecting:!0,idle:!1,working:!0,waiting:!1,error:!1}),io=Y({disconnected:!0,connecting:!1,idle:!0,working:!1,waiting:!1,error:!1}),oo=Y({disconnected:!1,connecting:!1,idle:!1,working:!1,waiting:!0,error:!0});var pt=["Edit","Write","MultiEdit","NotebookEdit"];function ue(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(ue,"mcpSignInBlocker");var Dn="request_mcp_sign_in";function qn(s,e=""){return it(s,e).name===`mcp__farero_host__${Dn}`}l(qn,"isMcpSignInTool");function de(s,e,t=""){if(!qn(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(de,"mcpSignInToolCall");var ft="claude.ai ";function K(s){return s.startsWith(ft)?s.slice(ft.length):s}l(K,"mcpServerLabel");function gt(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(gt,"matchMcpServer");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 $n}from"node:crypto";function ht(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=$n("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(ht,"providerMessageId");function pe(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(pe,"trackInteractions");var $=l(s=>s&&typeof s=="object"&&!Array.isArray(s)?s:null,"record");function Ie(s){return`mcp__${s.replace(/[^a-zA-Z0-9_-]/g,"_")}__`}l(Ie,"mcpServerToolPrefix");function Z(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(Z,"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 Un=l(s=>s&&typeof s=="object"&&!Array.isArray(s)?s:{},"obj"),mt={CLAUDE_CODE_MCP_APPS_HOST:"1"},Fn=2e3,jn=64;function Hn(s,e,t){let n=e.is_error===!0;if(t===1){let i=s.mcpMeta?{content:s.toolUseResult,...Un(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(Hn,"claudeToolResult");var fe=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=Hn(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>jn&&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<Fn?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:Z(c._meta),visibility:G(c._meta)}));r.set(o.name,a);for(let c of a){let u=`${Ie(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:`${Ie(e)}${t}`,arguments:n});return U(i.response)??{content:[]}}};function yt(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(yt,"claudeMcpServers");function wt(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(wt,"claudeSignInRemedy");var Bn=15*6e4,Wn={connected:"connected",failed:"failed","needs-auth":"needs-sign-in",pending:"connecting",disabled:"disabled"};function Me(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:Wn[s.status]??"unknown",signIn:n,...s.status==="failed"&&s.error?{error:s.error}:{}}}l(Me,"signInState");function bt(s,e){let t=new Map,n=l(o=>Date.now()-(t.get(o)??0)<Bn,"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=gt(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)),Me(c,r())},"state"),start:l(async o=>{let a=await i(o),c=s(),u=r(),d=Me(a,u);if(d.status==="connected")return{state:d};let p=ue(d);if(p||!u)throw new Error(p??"Claude Code offers no browser sign-in");let f=await u.call(c,a.name);return f?.callbackExpected&&t.set(a.name,Date.now()),{...f?.authUrl?{url:f.authUrl}:{},state:Me(await i(a.name),u)}},"start")}}l(bt,"claudeMcpSignIn");var vt=/^claude-([a-z]+)-(\d+(?:-\d{1,2})?)(?:-\d{8})?(?:\[\d+[mk]\])?$/i;function kt(s,e){let t=s.resolvedModel?.match(vt);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 p=d.resolvedModel?.match(vt);return d.value!==s.value&&p?.[1].toLowerCase()===n.toLowerCase()&&p[2]===r})?`${c} ${i} (default)`:`${c} ${i}`}l(kt,"claudeModelName");import{randomUUID as Go}from"node:crypto";import{appendFile as zn,mkdir as Xn,readdir as Jn,readFile as Xo,rm as Jo,stat as Qn,writeFile as Qo}from"node:fs/promises";import Yn from"node:os";import ee from"node:path";import{forkSession as Zn,getSessionMessages as er}from"@anthropic-ai/claude-agent-sdk";import{createReadStream as Kn}from"node:fs";var Vn=16*1024*1024,Gn=1e5;function St(s){try{let e=JSON.parse(s.toString("utf8"));return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}catch{return null}}l(St,"parseLine");async function Et(s,e={}){let t=e.maxRecords??Gn,n=[],r=[],i=[],o=0,a=0,c=0;for await(let u of Kn(s,{highWaterMark:64*1024})){let d=Buffer.isBuffer(u)?u:Buffer.from(u),p=0;for(;p<d.length;){let f=d.indexOf(10,p),g=f<0?d.length:f,w=d.subarray(p,g);if(a?a+=w.length:o+w.length>Vn?(a=o+w.length,i=[],o=0):w.length&&(i.push(w),o+=w.length),f<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=St(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,p=f+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=St(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(Et,"readJsonlObjects");function ge(s=process.env){return s.CLAUDE_CONFIG_DIR||ee.join(Yn.homedir(),".claude")}l(ge,"defaultClaudeHome");async function tr(s,e,t){let n=ee.join(s,"projects"),r;try{r=(await Jn(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=ee.join(n,o,`${e}.jsonl`);try{if((await Qn(a)).size>0)return a}catch{}}return null}l(tr,"sessionFile");function xt(s){return{async load(e){let t=e.subpath?null:await tr(s,e.sessionId,e.projectKey);if(!t)return null;let n=await Et(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=ee.join(s,"projects",e.projectKey);await Xn(n,{recursive:!0,mode:448}),await zn(ee.join(n,`${e.sessionId}.jsonl`),t.map(r=>`${JSON.stringify(r)}
|
|
2
|
+
`).join(""),{mode:384})}}}l(xt,"homeSessionStore");async function Pe(s,e,t){let n=typeof s=="string"?xt(s):s,r=await er(e,{dir:t,sessionStore:n});if(!r.length)throw new q("Claude",e);return r}l(Pe,"readClaudeSessionFrames");async function _t(s,e,t){return(await Zn(e,{dir:t,sessionStore:xt(s)})).sessionId}l(_t,"forkClaudeSession");import{readFileSync as or}from"node:fs";import Le from"node:path";var nr=/^\s*#\s*farero:\s*handoff\b/i,rr=[/^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)/],sr=/^(?:(?:[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 ir(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(sr,"")).filter(Boolean)}l(ir,"simpleCommands");function Ne(s){return nr.test(s.split(`
|
|
5
|
+
`,1)[0])?!0:ir(s).some(e=>rr.some(t=>t.test(e)))}l(Ne,"needsPerson");var ar=6e5;function cr(s){try{let e=JSON.parse(or(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(cr,"rules");function lr(s,e,t){let n=["/Library/Application Support/ClaudeCode/managed-settings.json",Le.join(e,"settings.json"),...t.flatMap(i=>[Le.join(i,".claude/settings.json"),Le.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=cr(i);return o===null||o.some(r)})}l(lr,"hasBashRule");function At(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"||!Ne(t.command))return{};if(lr(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:ar}}}:{}}]}]}l(At,"claudeTerminalHandoffHooks");var ur={now:Date.now,setTimeout:l((s,e)=>setTimeout(s,e).unref(),"setTimeout"),clearTimeout:l(s=>clearTimeout(s),"clearTimeout")},he=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??ur,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:Tt(r,.5),p95GapMs:Tt(r,.95),maxGapMs:r.at(-1)??0})}};function Tt(s,e){return s.length?s[Math.ceil(e*s.length)-1]:0}l(Tt,"rank");var Ct={'"':'"',"\\":"\\","/":"/",b:"\b",f:"\f",n:`
|
|
6
|
+
`,r:"\r",t:" "},dr=/^[0-9a-fA-F]{4}$/,Rt=l(s=>s===32||s===10||s===13||s===9,"isSpace"),pr=l(s=>s>=55296&&s<=56319,"isHighSurrogate"),me=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":Rt(r)&&(this.state="next");continue}Rt(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(!dr.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(Ct,d))o+=Ct[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&&pr(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 fr=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"]])]]),gr=/^\*\*\* (?:Add|Update|Delete) File: (.+?)\r?$/,De=class{constructor(e){this.roles=e}static{l(this,"EditDraft")}input=new me;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(gr)?.[1];e&&this.name(e),this.header=""}name(e){e&&!this.named.includes(e)&&this.named.push(e)}};function Ot(s){let e=fr.get(s);return e&&new De(e)}l(Ot,"editDraft");function qe(s){if(!s)return[];let e=s.split(`
|
|
11
|
+
`);return e.at(-1)===""&&e.pop(),e}l(qe,"lines");function hr(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 p=r.length-1;p>=0;p--)for(let f=i.length-1;f>=0;f--)c[p*a+f]=r[p]===i[f]?c[(p+1)*a+f+1]+1:Math.max(c[(p+1)*a+f],c[p*a+f+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(hr,"operations");function mr(s){let{old_string:e,new_string:t}=s;if(typeof e!="string"||typeof t!="string"||e===t)return;let n=hr(qe(e),qe(t)),r=[];for(let[d,p]of n.entries()){if(p.mark===" ")continue;let f=Math.max(0,d-3),g=Math.min(n.length,d+3+1),w=r.at(-1);w&&f<=w[1]?w[1]=g:r.push([f,g])}if(!r.length)return;let i=[],o=1,a=1,c=0;for(let[d,p]of r){for(;c<d;c++)n[c].mark!=="+"&&o++,n[c].mark!=="-"&&a++;let f=n.slice(d,p),g=f.filter(h=>h.mark!=="+").length,w=f.filter(h=>h.mark!=="-").length;i.push(`@@ -${g?o:o-1},${g} +${w?a:a-1},${w} @@`,...f.map(h=>h.mark+h.line))}return[...s.replace_all===!0?["Replaced every occurrence in the file."]:[],...i].join(`
|
|
12
|
+
`)}l(mr,"editPatch");function Mt(s){if(typeof s!="string")return;let e=qe(s);if(e.length)return[`@@ -0,0 +1,${e.length} @@`,...e.map(t=>`+${t}`)].join(`
|
|
13
|
+
`)}l(Mt,"addedPatch");function yr(s){return s.edit_mode==="delete"?void 0:Mt(s.new_source)}l(yr,"notebookPatch");var It={Edit:mr,Write:l(s=>Mt(s.content),"Write"),NotebookEdit:yr};function Pt(s,e){let t=Object.hasOwn(It,s)?It[s]:void 0;return t&&{patch:t(e),excerpt:s!=="Write"}}l(Pt,"callPatch");async function ye(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,p=>u({failed:p instanceof Error?p.message:String(p)})).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(ye,"verifyInjectedMcpServers");function we(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(we,"questionOptions");function be(s){let e=typeof s=="string"?s.trim():"";return e?{header:e}:{}}l(be,"questionHeader");function te(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(te,"questionPresentation");function Nt(s,e){return JSON.stringify(["request_user_input_async",s,e])}l(Nt,"codexAsyncQuestionId");function Lt(s){return`codex-async-question:${s}`}l(Lt,"codexAsyncQuestionInteractionId");var z=l(s=>typeof s=="string"?s:"","str");function wr(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(wr,"primaryToolInput");function Dt(s,e){return e||wr(s)||JSON.stringify(s)}l(Dt,"toolDetail");var _=l(s=>s&&typeof s=="object"&&!Array.isArray(s)?s:{},"obj"),y=l(s=>typeof s=="string"?s:"","str"),Tr={CLAUDE_CODE_EXPERIMENTAL_CODE_MODE:"1"};function Cr(s){let e={};for(let[t,n]of Object.entries(ut))s?.[t]&&(e[n]="1");return e}l(Cr,"claudeFeatureEnv");function Rr(s,e,t){if(!s)throw new Error("A Claude chat with MCP servers needs a private config directory");vr(s,{recursive:!0,mode:448});let n=xr.join(s,`${e}.${br(6).toString("hex")}.json`);return Er(n,JSON.stringify({mcpServers:t}),{mode:384}),n}l(Rr,"writeMcpConfig");var Or=l(s=>{let e=_(_(s).message).content;return Array.isArray(e)?e.flatMap(t=>_(t).type==="tool_result"?[y(_(t).tool_use_id)]:[]):[]},"answeredCalls");function qt({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(qt,"editCallRow");var $t="Claude\u2019s sign-in has ended. Sign in again to continue.",Ir=new Set(["[Request interrupted by user]","[Request interrupted by user for tool use]"]),$e=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})}}},ne=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 $e;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 he({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=pe(i=>e(this.replaying&&i.type==="entry"?{...i,history:!0}:i));this.emit=r.emit,this.liveInteractions=r.read,this.mcpApps=new fe(()=>this.client(),i=>this.emit(i)),n||(this.mcpSignIn=bt(()=>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??ve();let t=this.sandbox?{}:le("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??ge(),k=await Pe(v,e.threadId,e.cwd);this.answered=new Set(k.flatMap(Or)),this.replaying=!0;try{for(let x of k)this.message(x)}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?pt:[],...a?["AskUserQuestion"]:[]])],u=l(v=>c.some(k=>k.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"),p=e.agent.toolFree||e.agent.questionOnly?[]:["WebSearch","WebFetch"].filter(v=>!u(v)),f=[...new Set([...n?.allowedTools??[],...p.filter(v=>!(n?.allowedTools??[]).some(k=>k.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=yt(i,o),E=this.sandbox?this.sandbox.mcpConfigPath:h?Rr(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 R={persistSession:!e.catalogOnly,spawnClaudeCodeProcess:e.spawn?v=>{let k=this.sandbox?this.sandbox.spawn(e,v.args):e.spawn(v.command,v.args,v.cwd??e.cwd,{...v.env,...t});k.stderr.resume();let x=l(()=>{k.kill("SIGTERM")},"abort");return v.signal.addEventListener("abort",x,{once:!0}),k.once("close",()=>v.signal.removeEventListener("abort",x)),v.signal.aborted&&x(),k}:void 0,cwd:e.cwd,env:this.sandbox?{}:{...this.host.environment({provider:"claude",workspaceEnv:e.workspaceEnv,accountHome:e.account?.home,envKeys:n?.envKeys}),...mt,...Cr(n),...e.codeMode?Tr:{}},...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||f.length?{allowedTools:f}:{},...c.length?{disallowedTools:c}:{},...g?{hooks:{PreToolUse:At({prepare:l(v=>g.prepare(v),"prepare"),disallowedTools:c,configDir:e.account?.home??ge(),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,k,x)=>{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:k};let S=x;if(!(v==="AskUserQuestion"||v==="ExitPlanMode"||x.matchedAskRule!==void 0||S.requiresUserInteraction===!0||S.decisionReasonType==="rule"||S.decisionReasonType==="hook")&&dt(e.agent.plan?"plan":this.harnessMode)&&d()){let L=x.decisionReason?.trim();return{behavior:"deny",message:`Farero declined this request automatically. No person reviewed it.${L?` Reason: ${L}`:""}`}}let I=ve(),O=v==="AskUserQuestion",M=!O&&v!=="ExitPlanMode"&&!x.suppressAlwaysAllowRule&&x.suggestions?.length?x.suggestions.map(L=>({...L,destination:"session"})):void 0,J=x.agentID?{id:x.agentID,label:this.agentLabels.get(x.agentID)??"Subagent"}:void 0;return new Promise(L=>{this.requests.set(I,{tool:v,input:k,resolve:L,question:O,sessionRules:M});let et=l(()=>{this.requests.delete(I)&&(L({behavior:"deny",message:"Interaction cancelled"}),this.emit({type:"interaction-resolved",id:I}),this.publishActivity())},"cancel");if(x.signal.addEventListener("abort",et,{once:!0}),x.signal.aborted){et();return}this.emit({type:"interaction",interaction:{id:I,kind:O?"question":"approval",method:v,...J?{agent:J}:{},title:x.title??(O?"Question from Claude":`Claude requests ${v}`),body:O?"":x.decisionReason??JSON.stringify(k,null,2),decisions:O?void 0:M?["accept","acceptForSession","decline"]:["accept","decline"],...M?{decisionLabels:{acceptForSession:"Allow for this session"}}:{},questions:O&&Array.isArray(k.questions)?k.questions.map((ce,hn)=>{let _e=we(_(ce).options),mn=te(y(_(ce).question),_e.options,_e.optionDescriptions);return{id:String(hn),...be(_(ce).header),multiple:_(ce).multiSelect===!0,..._e,...mn}}):void 0,providerData:k}}),this.emit({type:"status",status:"waiting",turnId:this.turnId})})},"canUseTool")},T=Ar({prompt:this.stream,options:R});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??{}):ye(i,this.host.mcpStartupMs,k=>this.injectedMcpState(T,k))),!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=_(e),r=_(n.message),i=y(r.id)||y(n.uuid),o=y(n.timestamp)||new Date().toISOString();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}});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:$t,ts:o}});return}if(n.type==="user"&&!r.content.some(u=>_(u).type==="tool_result")){let u=r.content.map(d=>y(_(d).text)).filter(Boolean).join(`
|
|
14
|
+
`);if(!u.trim()||D(u)||W(u))return;if(n.isMeta===!0||n.isSynthetic===!0){let d=n.isMeta===!0?y(n.sourceToolUseID):this.skillCompanions.shift()??"";d&&this.emit({type:"entry",entry:{id:y(n.uuid)||`${d}:injected`,role:"tool",text:"",toolUseId:d,output:u,ts:o}});return}if(Ir.has(u)){this.emit({type:"entry",entry:{id:y(n.uuid),role:"system",text:"Stopped",ts:o}});return}this.emit({type:"entry",entry:{id:y(n.uuid),role:"user",text:u,ts:o}});return}n.type==="assistant"&&(this.skillCompanions.length=0);let a=0;if(n.type==="assistant"){let u=this.blockOffsets.get(i);u||(u={next:0,frames:new Map},this.blockOffsets.set(i,u));let d=y(n.uuid)||i,p=u.frames.get(d);p!==void 0?a=p:(a=u.next,u.frames.set(d,a),u.next+=r.content.length)}let c=r.content.filter(u=>_(u).type==="tool_result").length;for(let[u,d]of r.content.entries()){let p=_(d),f=p.type==="tool_use"?y(p.id):`${i}:${a+u}`,g=p.type==="thinking"?"thinking":p.type==="tool_use"||p.type==="tool_result"?"tool":n.type==="user"?"user":"assistant",w=_(p.input),h=p.type==="thinking"?y(p.thinking):y(p.text)||y(w.description)||y(p.name)||(p.type==="tool_result"?"":JSON.stringify(p)),E=p.type==="tool_result"?typeof p.content=="string"?p.content:JSON.stringify(p.content):void 0;if(D(h)||D(E))continue;p.type==="tool_use"&&y(p.name)===Ce&&this.skillCompanions.push(y(p.id));let R=p.type==="tool_result"?this.edits.get(y(p.tool_use_id)):void 0;R&&(this.edits.delete(y(p.tool_use_id)),this.answered.add(y(p.tool_use_id)),R.shown!=="plain"&&this.emit({type:"entry",entry:{...R.call,running:!1}}));let T=p.type==="tool_use"?this.mcpApps.call(y(p.id),y(p.name),w):void 0,v=p.type==="tool_use"?de(y(p.name),w):p.type==="tool_result"?wt(n.tool_result_meta,y(p.tool_use_id)):void 0,k={id:f,role:g,ts:o,text:h,...p.type==="tool_use"?{tool:y(p.name),toolUseId:y(p.id),running:!t,detail:Dt(w,Re(w)),...T?{app:T}:{}}:{},...p.type==="tool_result"?{toolUseId:y(p.tool_use_id),...R?.patch!==void 0&&p.is_error!==!0?{output:R.patch,diff:!0,...R.excerpt?{diffExcerpt:!0}:{}}:{output:E},error:p.is_error===!0}:{},...v?{mcpSignIn:v}:{},...typeof n.parent_tool_use_id=="string"?{parentToolUseId:n.parent_tool_use_id}:{}},x=p.type==="tool_use"?this.trackEdit(k,w,t):void 0,S=p.type==="tool_result"?this.mcpApps.result(k,n,p,c):void 0;p.type==="tool_use"&&this.writing.delete(f)&&this.drafts.settle(f),this.emit(S?{type:"entry",entry:{...k,app:S.app},appCall:S.appCall}:{type:"entry",entry:x?qt(x):k})}}trackEdit(e,t,n){let r=Pt(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:qt(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=_(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=_(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(_(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=_(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),p=y(a.name),f=a.type==="tool_use"&&d?Ot(p):void 0;if(!f)return;let g={id:d,role:"tool",ts:c,text:p,tool:p,toolUseId:d,output:"",draft:!0,...u};i.blocks.set(o,{entry:g,draft:f}),this.writing.set(d,n),this.drafts.update(g)}else if(t.type==="content_block_delta"){let a=i.blocks.get(o),c=_(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,p]=[u.text.length,u.paths.length];if(u.push(y(c.partial_json)),u.text.length===d&&u.paths.length===p)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??ge(),n=await Pe(t,this.threadId,this.options.cwd);if(this.closing)return;for(let r of n)r.type==="user"&&this.acknowledge(_(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=_(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(_).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)||ve(),role:"system",text:ot(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)||ve(),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(_(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?$t: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=ht("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:kr(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(_(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:kt(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?_t(e,this.threadId,this.options?.cwd):(await _r(this.threadId,{dir:this.options?.cwd})).sessionId}async close(){this.closing=!0,this.mcpConfigFile&&(Sr(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)}};function Ut(s){let e=s?.replace(/[-_]+/g," ").trim();return e?e[0].toUpperCase()+e.slice(1):"Subagent"}l(Ut,"codexAgentName");import{createHash as Mr}from"node:crypto";import{readFileSync as Pr,realpathSync as jt,statSync as Nr}from"node:fs";import Ht from"node:path";import Ue from"node:path";function Ft(s,e){let t=Ue.relative(s,e);return t!==""&&t!==".."&&!t.startsWith(`..${Ue.sep}`)&&!Ue.isAbsolute(t)}l(Ft,"pathInside");var Lr=new Set(["image/png","image/jpeg","image/webp","image/gif"]),Fe=10*1024*1024,Bt=l((s,e)=>`native_image_${Mr("sha256").update(s).update("\0").update(e).digest("hex")}`,"imageReference");function Wt(s,e){try{let t=jt(s),n=jt(Ht.resolve(s,e)),r={".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp",".gif":"image/gif"}[Ht.extname(n).toLowerCase()],i=Nr(n);if(!Ft(t,n)||!r||!i.isFile()||i.size>Fe)return[];let o=Pr(n);return[{reference:Bt(r,o),mediaType:r,data:o.toString("base64")}]}catch{return[]}}l(Wt,"nativeFileImage");function Dr(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(Dr,"sniffImageMediaType");function Kt(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(Fe/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>Fe||(n??=Dr(i),!n||!Lr.has(n))?null:{reference:Bt(n,i),mediaType:n,data:i.toString("base64")}}l(Kt,"nativeBase64Image");var X="codex_apps",Gt="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.",Vt=2e3,F=l(s=>s&&typeof s=="object"&&!Array.isArray(s)?s:{},"record");function qr(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(qr,"linkAccounts");async function zt(s,e){let t=performance.now()+Vt,r=(await s.request("mcpServerStatus/list",{threadId:e,serverName:X,detail:"toolsAndAuthOnly"},Vt)).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),p=F(d._codex_apps),f=d.connector_id;if(!(typeof f!="string"||p.requires_explicit_link_id!==!0||!G(d).includes("model")))for(let g of qr(u)){let w=i.get(f);w||(w=new Map,i.set(f,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,p)=>d.link_name.localeCompare(p.link_name)||d.link_id.localeCompare(p.link_id))}]}).sort((c,u)=>c.connection.localeCompare(u.connection))}l(zt,"readCodexAppConnections");var $r={connected:"connected",authenticationRequired:"needs-sign-in",starting:"connecting",notStarted:"connecting",failed:"failed",cancelled:"failed",disabled:"disabled"},Ur=1e4,re=l(s=>s&&typeof s=="object"&&!Array.isArray(s)?s:{},"record");function Fr(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.href:null}l(Fr,"chatgptUrl");function Xt(s){let e=$r[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(Xt,"serverState");function Jt(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(Jt,"appState");var ke=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=re(e.result),n=re(re(re(t._meta)._codex_apps).connector_auth_failure),r=n.connector_id,i=re(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:Fr(n.install_url),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(()=>{}),Jt(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),Xt(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"?Jt(t.app):Xt(t.status);if(n.status==="connected")return{state:n};let r=ue(n);if(r)throw new Error(r);if(t.kind==="app")return{url:t.app.installUrl??void 0,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),R=(await this.appList(t).catch(T=>{if(h)return this.apps?.list??[];throw T})).find(T=>T.id===i)??h;if(R)return{kind:"app",app:R};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 p=u.map(h=>({server:h.name,label:K(h.name),status:h})),f=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 p)(h.server.toLowerCase()===w||h.label.toLowerCase()===w)&&g.push({selector:`server:${h.server}`,target:{kind:"server",status:h.status}});for(let h of f)(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<Ur)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 jr}from"node:crypto";function Qt(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}"`,p={type:"command",command:d,timeout:5,async:!1},f={event_name:"pre_tool_use",hooks:[{async:!1,command:d,timeout:5,type:"command"}],matcher:s},g=`sha256:${jr("sha256").update(JSON.stringify(f)).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:[p]}],"hooks.state":{[h]:{enabled:!0,trusted_hash:g}}}}}l(Qt,"codexToolPolicy");function je(s){return Qt("^request_user_input(_async)?$",B,s)}l(je,"codexHelperQuestionPolicy");function He(s){return Qt("*","This side chat may only ask user questions.",s,!0)}l(He,"codexQuestionFormPolicy");async function Be(s,e,t=je()){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(Be,"verifyCodexHelperQuestionPolicy");import{spawn as Hr}from"node:child_process";var Br=64*1024*1024;function We(s){return Array.isArray(s)?`[${s.map(We).join(",")}]`:s&&typeof s=="object"?`{${Object.entries(s).map(([e,t])=>`${JSON.stringify(e)}=${We(t)}`).join(",")}}`:JSON.stringify(s)}l(We,"configValue");var se=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(([f,g])=>["--config",`${f}=${We(g)}`]),"--listen","stdio://"];this.child=o?o(e.command,d,t,a):Hr(e.command,d,{cwd:t,env:a,stdio:"pipe",windowsHide:!0}),this.closed=new Promise(f=>this.child.once("close",()=>f())),this.child.stdout.setEncoding("utf8"),this.child.stdout.on("data",f=>{if(this.buffer+=f,this.buffer.length>Br)return p(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){p(h instanceof Error?h:new Error("Invalid Codex frame"))}g=this.buffer.indexOf(`
|
|
17
|
+
`)}}),this.child.stderr.resume();let p=l(f=>{if(!this.ended){this.ended=!0;for(let g of this.pending.values())clearTimeout(g.timer),g.reject(f);this.pending.clear(),r(f),this.child.kill("SIGTERM")}},"fail");this.child.once("error",p),this.child.stdin.on("error",p),this.child.once("close",f=>p(new Error(`Codex driver disconnected (exit ${f??"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 Wr}from"node:crypto";import{existsSync as $c,readdirSync as Uc,readFileSync as Fc}from"node:fs";import Hc from"node:path";var Ge="farero_terminal",Kr="pre_tool_use",Ke=l(s=>`\${${s}}`,"field"),Vr={command:Ke("tool_input.command"),cwd:Ke("cwd"),permission_mode:Ke("permission_mode")},Gr=5;function Yt(s){return(s?.sandbox??"danger-full-access")==="danger-full-access"&&(s?.approvalPolicy??"never")==="never"}l(Yt,"codexHandsOff");function Ve(s){return Array.isArray(s)?s.map(Ve):!s||typeof s!="object"?s:Object.fromEntries(Object.entries(s).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>[e,Ve(t)]))}l(Ve,"sortedKeys");function Zt(s=process.platform,e=0){let t={type:"mcp_tool",server:Ge,tool:Kr,input:Vr,timeout:Gr},n={event_name:"pre_tool_use",hooks:[t],matcher:"Bash"},r=`sha256:${Wr("sha256").update(JSON.stringify(Ve(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(Zt,"codexTerminalHandoffHook");import{randomUUID as rs}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 zr(s,e,t){if(e.split(`
|
|
20
|
+
`).some(p=>p.startsWith("diff --git ")))return e;let n=(s||`file-${t+1}`).replace(/[\r\n]/g," "),r=l(p=>/[\s"\\]/.test(p)?`"${p.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`:p,"quotePath"),i=r(`a/${n}`),o=r(`b/${n}`),a=e.split(`
|
|
21
|
+
`),c=a.findIndex(p=>p.startsWith("@@ ")),u=c<0?a:a.slice(0,c),d=u.some(p=>p.startsWith("--- "))&&u.some(p=>p.startsWith("+++ "));return[`diff --git ${i} ${o}`,...d?[]:[`--- ${i}`,`+++ ${o}`],e].join(`
|
|
22
|
+
`)}l(zr,"fileChangePatch");var en={draft:!0,aborted:!0},tn=l(s=>Array.isArray(s)?s.map(e=>typeof e=="string"?e:m(b(e).text)).filter(Boolean).join(`
|
|
23
|
+
`):m(s),"reasoningText");function Xr(s,e){return"responseStreamDisconnected"in b(s.codexErrorInfo)?!0:/^reconnecting\.\.\.\s*\d+\s*\/\s*\d+/i.test(e.trim())}l(Xr,"isCodexReconnectNoise");function Jr(s){return/\bno (?:archived )?rollout found for (?:thread|conversation) id\b/i.test(s)}l(Jr,"isMissingRollout");function Qr(s,e){let t=e.approvedTools?.length?s.approvalHeaders?.(e.approvedTools):void 0;return t?{...e.headers,...t}:e.headers}l(Qr,"approvalHeaders");function on(s){if(!(!s.terminalHandoff||s.agent.questionOnly||s.agent.toolFree))return Yt(s.harness?.codex)?s.terminalHandoff.hookServer:void 0}l(on,"terminalHandoffServer");function Yr(s){if(!s)return{};if(s.agent.questionOnly)return He().config;let e=s.delegated?je().config:void 0;if(!on(s))return e??{};let t=Zt(process.platform,e?1:0);return{"hooks.PreToolUse":[...e?.["hooks.PreToolUse"]??[],...t["hooks.PreToolUse"]],"hooks.state":{...e?.["hooks.state"],...t["hooks.state"]}}}l(Yr,"codexHostHooks");function nn(s){return s?"priority":"default"}l(nn,"serviceTier");function rn(s){return s.effort==="ultracode"?{...s,effort:"ultra"}:s}l(rn,"codexAgentOptions");function Zr(s){if(!s.requiresOpenaiAuth)return null;let e=b(s.account).type;return e==="chatgpt"||e==="apiKey"?e:null}l(Zr,"codexLogin");var sn="Thread is not owned by this native session",es=500,Se=l(s=>`codex-agent:${s}:`,"subagentPrefix"),ts={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 ns(s){if(s.type!=="mcpToolCall"||typeof s.server!="string"||!s.server)return;let e=b(s.mcpAppUi).resourceUri??s.mcpAppResourceUri,t=Z({ui:{resourceUri:e}});return t?{server:s.server,resourceUri:t}:void 0}l(ns,"codexMcpApp");var ie=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=rs();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=pe(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 se({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 p=this.options?.harness?.codex,f=this.host.launch("codex",p);if(!f.resolved)throw this.host.notInstalled("codex",p?.runtime?.source??"bundled",f.unmet);let g=this.options?.account?.home;return new se(f,o,a,c,{spawn:this.options?.spawn,env:{...this.host.environment({provider:"codex",workspaceEnv:this.options?.workspaceEnv,accountHome:g,envKeys:p?.envKeys}),...g?{CODEX_SQLITE_HOME:g}:{}},codexHome:g,configOverrides:{...Yr(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 ke(()=>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:Z(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"?en:{})}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,...en})}}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?`${Se(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,p;if(i==="userMessage")c="user",u=Array.isArray(r.content)?r.content.map(S=>{let A=b(S);return A.type==="skill"?m(A.name)&&`$${m(A.name)}`:A.type==="mention"?m(A.name)&&`@${m(A.name)}`:m(A.text)}).filter(Boolean).join(`
|
|
24
|
+
`):u;else if(i==="agentMessage")c="assistant";else if(i==="reasoning")c="thinking",u=[tn(r.summary),tn(r.content)].filter(Boolean).join(`
|
|
25
|
+
`);else if(i==="commandExecution")u="Run command",d=Q(m(r.command))||void 0,p=m(r.aggregatedOutput);else if(i==="fileChange"){u="Edit files";let S=Array.isArray(r.changes)?r.changes.map(b):[];d=S.map(A=>m(A.path)).join(`
|
|
26
|
+
`),p=S.length>1?S.map((A,I)=>zr(m(A.path),m(A.diff),I)).join(`
|
|
27
|
+
`):S.map(A=>m(A.diff)).join(`
|
|
28
|
+
`)}else i==="imageGeneration"?(u="Generate image",d=m(r.revisedPrompt)||m(r.prompt)||void 0):i==="collabAgentToolCall"?(u=ts[m(r.tool)]??"Coordinate subagents",d=[(Array.isArray(r.receiverThreadIds)?r.receiverThreadIds.map(A=>this.subagentLabel(m(A))):[]).join(", "),m(r.prompt)].filter(Boolean).join(`
|
|
29
|
+
`)||void 0,p=Object.entries(b(r.agentsStates)).map(([A,I])=>{let O=b(I);return[`${this.subagentLabel(A)}: ${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&&(p=JSON.stringify(r.result,null,2)));let f=ns(r),g=i==="mcpToolCall"?(t?void 0:this.mcpSignIn?.observe(r))??de(`mcp__${m(r.server)}__${m(r.tool)}`,r.arguments):void 0,w=f&&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((S,A)=>{let I=b(S),O=m(I.title);return O.trim()?[{id:Nt(a,A),question:O,options:Array.isArray(I.options)?I.options.filter(M=>typeof M=="string"):void 0}]:[]}):[],R=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:p,diff:i==="fileChange",error:r.status==="failed",...f?{app:f}:{},...g?{mcpSignIn:g}:{},...R}:{}};this.entries.set(a,v);let k=t?this.subagents.get(t.threadId):void 0;k&&i==="agentMessage"&&u&&(k.lastMessage=u);let x=i==="imageView"&&this.options?Wt(this.options.cwd,m(r.path)):i==="imageGeneration"?(()=>{let S=Kt(r.result);return S?[S]:[]})():[];if(this.emit({type:"entry",entry:{...v},...x.length?{imageData:x}:{},...h?{appCall:h}:{}}),i==="agentMessage"&&!this.options?.delegated&&!t&&Array.isArray(r.questions)){let S=Lt(a),A=this.options?.stored?.questionDismissed?.(S),I={},O=E.flatMap(({id:M,question:J,options:L})=>A||this.options?.stored?.questionAnswered?.(S,M)?[]:(I[M]=J,[{id:M,...te(J,L)}]));O.length?this.emit({type:"interaction",interaction:{id:S,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:I}}}):this.liveInteractions().some(M=>M.id===S)&&this.emit({type:"interaction-resolved",id:S})}}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:Ut(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,sn);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<es)&&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,sn);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(`${Se(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:`${Se(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(Se(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&&Xr(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"],p=d.map((g,w)=>typeof g=="string"?g:`option:${w}`),f={accept:"Allow once",acceptForSession:"Allow for this session",decline:"Decline",cancel:"Cancel turn"};return d.forEach((g,w)=>{typeof g!="string"&&(f[`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:p,decisionLabels:c?void 0:f,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=we(b(g).options);return{id:m(b(g).id),...be(b(g).header),inputType:b(g).isSecret?"password":"text",...w,...te(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:rn(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(f){if(!e.catalogOnly)throw f;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 Be(t,e.cwd,this.sandbox?.questionPolicy()),e.agent.questionOnly&&await Be(t,e.cwd,this.sandbox?.questionPolicy(!0)??He());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(f=>[`features.${f}`,!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(([f,g])=>[f,{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(([f,g])=>[f,{url:g.url,http_headers:Qr(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:on(e);o&&(r.mcp_servers={...r.mcp_servers,[Ge]:{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:nn(e.agent.fast),config:r,developerInstructions:[e.instructions,this.host.codexInstructions,!this.sandbox&&!e.agent.questionOnly&&!e.agent.toolFree&&Gt].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(f=>{throw e.threadId&&f instanceof N&&Jr(f.message)?new q("Codex",e.threadId):f});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:Zr(n)});for(let f of d.thread.turns??[])for(let g of f.items??[])this.entry(g,void 0,f.status==="inProgress"?"history":"endedTurn");this.anchorOrphans(d.thread.id),await(this.sandbox?this.sandbox.verifyMcp(e.mcpServers??{}):ye(e.mcpServers,this.host.mcpStartupMs,(f,g)=>this.injectedMcpState(f,g)));let p=d.thread.turns?.find(f=>f.status==="inProgress");this.turnId=p?.id??null,this.emit({type:"status",status:p?"working":"idle",turnId:this.turnId,error:null}),this.hydrateSubagents().catch(f=>this.emit({type:"raw",method:"codex/subagent.history.failed",payload:{error:String(f)}}))}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 zt(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=rn(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:nn(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,p=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 p=="number"&&(!Number.isFinite(p)||d==="integer"&&!Number.isInteger(p)))throw new Error(`Enter a valid number for ${a}`);if(Array.isArray(b(c).enum)&&!b(c).enum.includes(p))throw new Error(`Choose a listed value for ${a}`);i[a]=p}}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 Qe}from"node:crypto";import{mkdirSync as dn}from"node:fs";import xe from"node:path";import{execFile as ss}from"node:child_process";import{homedir as is}from"node:os";var os={claude:"Claude Code",codex:"Codex"},as={claude:"claude auth login",codex:"codex login"},cs={claude:["auth","status"],codex:["login","status"]};function j(s,e,t){let n=os[s],r={ready:`${n} is signed in.`,missing:`${n} is not installed. Install it, then check again.`,"sign-in":`Run ${as[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 ls(s,e,t){return new Promise(n=>{ss(s,e,{cwd:is(),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(ls,"run");async function ze(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 ls(n.command,[...n.args,...cs[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(ze,"connectionStatus");import{closeSync as ds,mkdirSync as ps,openSync as fs}from"node:fs";import gs from"node:path";import{DatabaseSync as hs}from"node:sqlite";var an=1024*1024;function us(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(us,"utf8Prefix");function cn(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<=an)return s;let i=an,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]=us(u,i,n[a]),i-=Buffer.byteLength(o[c]??""))}return o}l(cn,"boundToolEntry");function Xe(s){return!at(s.text)&&!W(s.text)&&!D(s.text)&&!D(s.output)}l(Xe,"shownTranscriptRow");function Je(s){return!s.supersededBy&&Xe(s)&&(s.role!=="thinking"||!!s.text.trim())}l(Je,"listedTranscriptRow");function H(s){return s==="running"||s==="waiting"}l(H,"chatBusy");var ms={claude:"Claude Code",codex:"Codex"},ys=new Set(["ts","rowid","revision","queued"]),ln="id, provider, title, cwd, threadId, status, error, agent, interactions, createdAt, updatedAt, seq";function un(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(un,"chatOf");function Ee(s){return{...JSON.parse(s.entry),rowid:s.rowid,revision:s.revision,queued:!1}}l(Ee,"entryOf");function ws(s){return s.running===!0||s.draft===!0&&!s.aborted}l(ws,"openRow");function bs(s,e){let t=new Set([...Object.keys(s),...Object.keys(e)]);for(let n of t){if(ys.has(n))continue;let r=s[n],i=e[n];if(r!==i&&JSON.stringify(r)!==JSON.stringify(i))return!1}return!0}l(bs,"sameContent");var oe=class{static{l(this,"TranscriptStore")}database;listeners=new Set;constructor(e){ps(gs.dirname(e),{recursive:!0,mode:448}),ds(fs(e,"a",384)),this.database=new hs(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 ${ln} FROM chats ORDER BY updatedAt DESC, rowid DESC`).all().map(un)}chat(e){let t=this.database.prepare(`SELECT ${ln} FROM chats WHERE id = ?`).get(e);return t?un(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(Je),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))Je(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){Xe({...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=cn(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&&bs(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=ms[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(!ws(c))continue;let{rowid:u,revision:d,queued:p,...f}=c;this.database.prepare("UPDATE entries SET entry = ?, revision = ?, seq = ? WHERE rowid = ?").run(JSON.stringify({...f,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 vs=2e3,ks=10*6e4,Ye={claude:"Claude Code",codex:"Codex"};function pn(s){return Object.fromEntries(Object.entries(s??{}).filter(([,e])=>e!==void 0))}l(pn,"defined");function Ss(s){let e={source:"path",customPath:""};return{claude:{...Oe.claude,permissionMode:"default",runtime:e,...pn(s?.claude)},codex:{...Oe.codex,sandbox:"workspace-write",approvalPolicy:"on-request",runtime:e,...pn(s?.codex)}}}l(Ss,"harnessOf");function Es(s){return s instanceof Error?s.message:String(s)}l(Es,"messageOf");function ae(s){let e;return Promise.race([s.then(()=>{},()=>{}),new Promise(t=>{e=setTimeout(t,vs)})]).finally(()=>clearTimeout(e))}l(ae,"grace");var Ze=class s{constructor(e){this.options=e;let t=xe.resolve(e.directory);this.workspace=xe.join(t,"workspace"),this.mcpConfigDir=xe.join(t,"mcp"),dn(this.workspace,{recursive:!0,mode:448}),dn(this.mcpConfigDir,{recursive:!0,mode:448}),this.store=new oe(xe.join(t,"agent-runner.sqlite"));let n=e.host??Te();this.host=n,this.harness=Ss(e.harness),this.drivers={claude:l(r=>new ne(r,{host:n}),"claude"),codex:l(r=>new ie(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=Qe(),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 ${Ye[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 ae(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 ze(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=>ae(t.driver.close()))),this.store.close()}assertOpen(){if(this.closed)throw new Error("The agent runtime is closed.")}request(e){let t=Qe();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:Es(t),interactions:[]}),n&&(this.drop(e,n),ae(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-${Qe()}`,role:"system",text:`${Ye[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=Ye[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),ae(t.driver.close()))},ks),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 ae(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 xs,randomBytes as _s,timingSafeEqual as As}from"node:crypto";import Ts from"node:http";import{Server as Cs}from"@modelcontextprotocol/sdk/server/index.js";import{StreamableHTTPServerTransport as Rs}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{CallToolRequestSchema as Os,ListToolsRequestSchema as Is}from"@modelcontextprotocol/sdk/types.js";var fn="/mcp";function gn(s){return{isError:!0,content:[{type:"text",text:s}]}}l(gn,"failure");async function Ms({tools:s,call:e,name:t="tools"}){let n=_s(32),r=l(u=>`${Buffer.from(u).toString("base64url")}.${xs("sha256",n).update(u).digest("base64url")}`,"token"),i=l(u=>{let d=/^Bearer ([\w-]+)\.([\w-]+)$/.exec(u??"");if(!d)return;let p=Buffer.from(d[1],"base64url").toString(),f=Buffer.from(r(p)),g=Buffer.from(`${d[1]}.${d[2]}`);return f.length===g.length&&As(f,g)?p:void 0},"caller"),o=l(async(u,d)=>{if(new URL(u.url??"/","http://127.0.0.1").pathname!==fn){d.writeHead(404).end();return}let p=i(u.headers.authorization);if(!p){d.writeHead(401,{"content-type":"application/json"}).end('{"error":"unauthorized"}');return}if(u.method!=="POST"){d.writeHead(405,{allow:"POST"}).end();return}let f=new AbortController,g=new Cs({name:t,version:"1.0.0"},{capabilities:{tools:{}}});g.setRequestHandler(Is,async()=>({tools:[...s]})),g.setRequestHandler(Os,async(h,E)=>{let R=h.params.name;if(!s.some(T=>T.name===R))return gn(`Unknown tool ${R}`);try{return await e({chatId:p,name:R,args:h.params.arguments??{},signal:AbortSignal.any([E.signal,f.signal])})}catch(T){return gn(T instanceof Error?T.message:String(T))}});let w=new Rs({sessionIdGenerator:void 0,enableJsonResponse:!0});d.once("close",()=>{f.abort(),w.close(),g.close()}),await g.connect(w),await w.handleRequest(u,d)},"handle"),a=Ts.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}${fn}`,headers:l(u=>({Authorization:`Bearer ${r(u)}`}),"headers"),close:l(()=>new Promise(u=>{a.closeAllConnections(),a.close(()=>u())}),"close")}}l(Ms,"serveTools");export{Ze as AgentRuntime,ne as NativeClaudeDriver,ie as NativeCodexDriver,oe as TranscriptStore,H as chatBusy,ze as connectionStatus,Te as localHost,Ms as serveTools};
|
package/package.json
CHANGED
|
@@ -1,6 +1,29 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@farero-ai/agent-runner",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
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
|
+
}
|