claude-ws 0.4.6 → 0.4.7

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.
Files changed (35) hide show
  1. package/.next/BUILD_ID +1 -1
  2. package/.next/build-manifest.json +3 -3
  3. package/.next/fallback-build-manifest.json +3 -3
  4. package/.next/server/app/_global-error.html +1 -1
  5. package/.next/server/app/_global-error.rsc +1 -1
  6. package/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
  7. package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  8. package/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  9. package/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  10. package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  11. package/.next/server/app/_not-found.html +1 -1
  12. package/.next/server/app/_not-found.rsc +1 -1
  13. package/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  14. package/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  15. package/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
  16. package/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  17. package/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  18. package/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  19. package/.next/server/app/api/attempts/[id]/alive/route.js +3 -3
  20. package/.next/server/app/api/attempts/[id]/pending-question/route.js +3 -3
  21. package/.next/server/app/api/questions/answer/route.js +3 -3
  22. package/.next/server/app/api/questions/route.js +3 -3
  23. package/.next/server/app/api/tasks/[id]/pending-question/route.js +3 -3
  24. package/.next/server/chunks/src_lib_agent-manager_ts_0o7~e5j._.js +15 -15
  25. package/.next/server/chunks/src_lib_agent-manager_ts_0o7~e5j._.js.map +1 -1
  26. package/.next/server/middleware/middleware-manifest.json +1 -1
  27. package/.next/server/middleware-build-manifest.js +3 -3
  28. package/.next/server/middleware-manifest.json +1 -1
  29. package/.next/server/pages/404.html +1 -1
  30. package/.next/server/pages/500.html +1 -1
  31. package/package.json +1 -1
  32. package/src/lib/providers/claude-sdk-provider.ts +8 -0
  33. /package/.next/static/{5G902DD-80Ibj1L3h4Q-7 → khPpgbybSehHp7yKzNvzK}/_buildManifest.js +0 -0
  34. /package/.next/static/{5G902DD-80Ibj1L3h4Q-7 → khPpgbybSehHp7yKzNvzK}/_clientMiddlewareManifest.js +0 -0
  35. /package/.next/static/{5G902DD-80Ibj1L3h4Q-7 → khPpgbybSehHp7yKzNvzK}/_ssgManifest.js +0 -0
@@ -2,7 +2,7 @@ module.exports=[707272,e=>{"use strict";var t=e.i(427699),s=e.i(924868),n=e.i(81
2
2
  ## BACKGROUND SERVERS - CRITICAL
3
3
  - Unless specified otherwise, create files/folders ONLY within the project's path and organize files/folders using the PARA method, also create docs, plans, reports, executions if needed
4
4
  - Respond in the same language as the user's prompt, except for CLAUDE.md requirements.
5
- `.trim(),o={fix:`
5
+ `.trim(),r={fix:`
6
6
  ## MODE: BUG FIX
7
7
  Find root cause FIRST. Grep→Read→Trace→Fix→Test`,feature:`
8
8
  ## MODE: FEATURE
@@ -15,21 +15,21 @@ Preserve behavior. Read→Grep usages→Small edits→Test EACH`,question:`
15
15
  Cite file:line. Grep/Glob→Read→Answer with references`,setup:`
16
16
  ## MODE: SETUP
17
17
  Follow official docs. Read configs→Check package.json→Verify`,server:`
18
- ## MODE: SERVER`};var r=e.i(955931);e.i(723643);var a=e.i(368770),l=t,u=e.i(81850);let c=(0,a.createLogger)("SDKAdapter");function d(e){return"object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type}function p(e){let t={output:{type:e.type}};switch(e.type){case"system":if(t.output={type:"system",subtype:e.subtype,session_id:e.session_id},"init"===e.subtype&&e.session_id&&(t.sessionId=e.session_id),"init"===e.subtype&&e.mcp_servers)for(let t of e.mcp_servers)"connected"===t.status?c.info({name:t.name},`MCP connected: ${t.name}`):"failed"===t.status&&c.error({name:t.name,error:t.error},`MCP failed: ${t.name}`);break;case"assistant":{t.output={type:"assistant",message:{role:"assistant",content:e.message.content}};let s=function(e){for(let t of e)if("tool_use"===t.type&&"AskUserQuestion"===t.name)return{toolUseId:t.id||"",questions:t.input?.questions||[]}}(e.message.content);s&&(t.askUserQuestion=s);let n=function(e){for(let t of e)if("tool_use"===t.type&&"Bash"===t.name){let e=t.input;if(e?.run_in_background===!0&&e?.command)return c.info({commandPreview:e.command.substring(0,50)},"Background shell detected via run_in_background=true"),{toolUseId:t.id||"",command:e.command,description:e.description}}for(let t of e)if("text"===t.type&&t.text){let e=t.text.match(/```background-shell\n([\s\S]+?)\n```/);if(e){let t=e[1].trim();if(t)return{toolUseId:`bg-shell-${Date.now()}`,command:t,description:"Background shell from markdown block"}}}}(e.message.content);n&&(t.backgroundShell=n);break}case"user":t.output={type:"user",message:{role:"user",content:e.message.content}},e.uuid&&(t.checkpointUuid=e.uuid);break;case"result":t.output={type:"result",subtype:e.subtype,session_id:e.session_id,is_error:e.is_error},e.session_id&&(t.sessionId=e.session_id);break;case"stream_event":{let s=e.event;"content_block_delta"===s.type&&s.delta&&("text_delta"===s.delta.type&&s.delta.text?t.output={type:"content_block_delta",index:s.index,delta:{type:"text_delta",text:s.delta.text}}:"thinking_delta"===s.delta.type&&s.delta.thinking&&(t.output={type:"content_block_delta",index:s.index,delta:{type:"thinking_delta",thinking:s.delta.thinking}})),"message_delta"===s.type&&s.usage&&(t.usageEvent={input_tokens:s.usage.input_tokens||0,output_tokens:s.usage.output_tokens||0,cache_read_input_tokens:s.usage.cache_read_input_tokens||0,cache_creation_input_tokens:s.usage.cache_creation_input_tokens||0}),"message_start"===s.type&&s.message?.usage&&(t.usageEvent={input_tokens:s.message.usage.input_tokens||0,output_tokens:s.message.usage.output_tokens||0,cache_read_input_tokens:s.message.usage.cache_read_input_tokens||0,cache_creation_input_tokens:s.message.usage.cache_creation_input_tokens||0});break}default:t.output={type:e.type}}return t}var g=e.i(522734),m=e.i(446786);let h=(0,a.createLogger)("SDKProvider:MCP"),f={"claude-opus-4-6":"opus","claude-sonnet-4-5-20250929":"sonnet","claude-haiku-4-5-20251001":"haiku","claude-3-5-sonnet-20241022":"sonnet"},k=[/npm\s+run\s+(dev|start|serve)/i,/yarn\s+(dev|start|serve)/i,/pnpm\s+(dev|start|serve)/i,/npx\s+(directus|strapi|next|vite|nuxt)/i,/nohup\s+/i];var _=e.i(768770);let v=(0,a.createLogger)("SDKProvider:QueryBuilder"),y=["CLAUDECODE","CLAUDE_CODE_ENTRYPOINT","CK_"],w=(0,a.createLogger)("SDKProvider");class I{attemptId;controller;providerId;sessionId;outputFormat;queryRef;constructor(e,t,s){this.attemptId=e,this.controller=t,this.providerId="claude-sdk",this.outputFormat=s}cancel(){if(this.queryRef)try{this.queryRef.close()}catch{this.controller.abort()}else this.controller.abort()}}class T extends l.EventEmitter{id="claude-sdk";sessions=new Map;pendingQuestions=new Map;pendingQuestionData=new Map;resolveModel(e){return f[e]||e}async start(e){let{attemptId:t,projectPath:s,prompt:n,sessionOptions:i,maxTurns:o,model:r,systemPromptAppend:a,outputFormat:l}=e,u=new I(t,new AbortController,l);return this.sessions.set(t,u),this.runQuery(u,s,n,i,o,r,a),u}makeCanUseTool(e){var t,s,n;return t=()=>this.pendingQuestions.has(e),s=(t,s)=>{this.pendingQuestionData.set(e,{toolUseId:t,questions:s,timestamp:Date.now()}),this.emit("question",{attemptId:e,toolUseId:t,questions:s})},n=t=>new Promise(s=>{this.pendingQuestions.set(e,{toolUseId:t,resolve:s})}).then(t=>(this.pendingQuestions.delete(e),this.pendingQuestionData.delete(e),t)),async(i,o)=>{if(v.debug({toolName:i,attemptId:e},"canUseTool called"),"AskUserQuestion"===i){if(t())return{behavior:"deny",message:"Duplicate question"};let e=`ask-${Date.now()}`;s(e,o.questions||[]);let i=await n(e);return i&&0!==Object.keys(i.answers).length?{behavior:"allow",updatedInput:i}:{behavior:"deny",message:"User cancelled"}}if("Bash"===i){let e=o.command;if(e&&k.some(t=>t.test(e))&&!e.includes('echo "BGPID:$!"')&&/>\s*\/tmp\/[^\s]+\.log\s*$/.test(e)){let t=e.trim()+' 2>&1 & echo "BGPID:$!"';return v.debug({fixedCommand:t},"Fixed BGPID pattern"),{behavior:"allow",updatedInput:{...o,command:t}}}}return{behavior:"allow",updatedInput:o}}}async runQuery(e,t,s,i,o,r,a){let{attemptId:l,controller:c}=e;try{var f;let a=function(e){let t=(0,n.join)((0,m.homedir)(),".claude.json"),s=(0,n.join)(e,".mcp.json"),i=null;if((0,g.existsSync)(t))try{let s=(0,g.readFileSync)(t,"utf-8"),n=JSON.parse(s);if(n.mcpServers&&"object"==typeof n.mcpServers&&Object.keys(n.mcpServers).length>0&&(i=n.mcpServers,h.info({servers:Object.keys(i||{}),path:t},"Loaded global MCP config")),n.projects&&n.projects[e]?.mcpServers){let t=n.projects[e].mcpServers;Object.keys(t).length>0&&(i={...i||{},...t},h.info({servers:Object.keys(t),projectPath:e},"Loaded CLI project MCP config"))}}catch(e){h.warn({err:e,path:t},"Failed to parse config file")}let o=function(e){if(!(0,g.existsSync)(e))return null;try{let t=(0,g.readFileSync)(e,"utf-8"),s=JSON.parse(t);return!s.mcpServers&&Object.keys(s).some(e=>{let t=s[e];return t&&"object"==typeof t&&("command"in t||"url"in t||"type"in t)})&&(s={mcpServers:s}),s.mcpServers||null}catch(t){return h.warn({err:t,path:e},"Failed to parse config file"),null}}(s);o&&h.info({servers:Object.keys(o),path:s},"Loaded project MCP config");let r={...i||{},...o||{}};if(0===Object.keys(r).length)return h.info("No MCP servers found in user or project config"),null;for(let[,e]of Object.entries(r)){if("env"in e&&e.env){for(let[t,s]of Object.entries(e.env))if("string"==typeof s&&s.startsWith("${")&&s.endsWith("}")){let n=s.slice(2,-1);e.env[t]=process.env[n]||""}}if("headers"in e&&e.headers)for(let[t,s]of Object.entries(e.headers))"string"==typeof s&&s.includes("${")&&(e.headers[t]=s.replace(/\$\{([^}]+)\}/g,(e,t)=>process.env[t]||""))}return h.info({servers:Object.keys(r)},"Merged MCP servers"),{mcpServers:r}}(t),k=a?.mcpServers?(f=a.mcpServers,Object.keys(f).map(e=>`mcp__${e}__*`)):[],I=r?this.resolveModel(r):"opus",T=function(e){let{projectPath:t,model:s,sessionOptions:i,maxTurns:o,mcpServers:r,mcpToolWildcards:a,controller:l,canUseToolCallback:u}=e,c=_.checkpointManager.getCheckpointingOptions(),d={executable:process.execPath,cwd:t,model:s,permissionMode:"bypassPermissions",...r?{mcpServers:r}:{},allowedTools:["Skill","Task","Read","Write","Edit","NotebookEdit","Bash","Grep","Glob","WebFetch","WebSearch","TodoWrite","AskUserQuestion",...a],...i?.resume?{resume:i.resume}:{},...i?.resumeSessionAt?{resumeSessionAt:i.resumeSessionAt}:{},...c,...o?{maxTurns:o}:{},abortController:l,canUseTool:u,env:function(e){let t={};for(let[e,s]of Object.entries(process.env))y.some(t=>e.startsWith(t))||(t[e]=s);t.ANTHROPIC_MODEL=e;let s=(0,n.resolve)(process.env.DATA_DIR||"./data","claude-sdk-isolated-config");try{(0,g.mkdirSync)(s,{recursive:!0})}catch{}return t.CLAUDE_CONFIG_DIR=s,t}(s)};return v.debug({model:s,cwd:t,mcpCount:a.length},"Query options built"),d}({projectPath:t,model:I,sessionOptions:i,maxTurns:o,mcpServers:a?.mcpServers,mcpToolWildcards:k,controller:c,canUseToolCallback:this.makeCanUseTool(l)});w.info({endpoint:process.env.ANTHROPIC_BASE_URL||"https://api.anthropic.com",prompt:s.substring(0,200)+(s.length>200?"...":""),model:T.model,cwd:T.cwd},"SDK Query starting");let C=(0,u.query)({prompt:s,options:T});for await(let t of(e.queryRef=C,C)){if(c.signal.aborted)break;try{if(!d(t))continue;let s=p(t);s.sessionId&&(e.sessionId=s.sessionId),this.emit("message",{attemptId:l,output:s.output,sessionId:s.sessionId,checkpointUuid:s.checkpointUuid,backgroundShell:s.backgroundShell,resultMessage:"result"===t.type?t:void 0,usageEvent:s.usageEvent,rawMessage:t})}catch(t){let e=t instanceof Error?t.message:"Unknown message error";w.error({err:t,message:e},"Message processing error"),e.includes("Unexpected end of JSON")||this.emit("stderr",{attemptId:l,content:`Warning: ${e}`})}}this.cleanupPendingQuestions(l),this.sessions.delete(l),this.emit("complete",{attemptId:l,sessionId:e.sessionId})}catch(g){let n=g instanceof Error?g.message:"Unknown error",u=g instanceof Error?g.name:"UnknownError",d=!!i?.resume;if(w.error({err:g,message:n,attemptId:l},"SDK Error - Query failed"),d&&!c.signal.aborted)return w.warn({attemptId:l},"Resume failed, retrying without resume"),this.sessions.set(l,e),this.runQuery(e,t,s,void 0,o,r,a);let p=n.toLowerCase().includes("prompt is too long")||n.toLowerCase().includes("request too large");this.cleanupPendingQuestions(l),this.sessions.delete(l),this.emit("error",{attemptId:l,error:n,errorName:u,isPromptTooLong:p,wasResuming:d})}}answerQuestion(e,t,s,n){let i=this.pendingQuestions.get(e);return!!i&&(t&&i.toolUseId!==t?(w.warn({attemptId:e,expected:i.toolUseId,received:t},"Rejecting stale answer"),!1):(i.resolve({questions:s,answers:n}),this.pendingQuestions.delete(e),this.pendingQuestionData.delete(e),this.emit("questionResolved",{attemptId:e}),!0))}cancelQuestion(e){let t=this.pendingQuestions.get(e);return!!t&&(t.resolve(null),this.pendingQuestions.delete(e),this.pendingQuestionData.delete(e),this.emit("questionResolved",{attemptId:e}),!0)}hasPendingQuestion(e){return this.pendingQuestions.has(e)}getPendingQuestionData(e){return this.pendingQuestionData.get(e)||null}cancelSession(e){let t=this.sessions.get(e);return!!t&&(this.cleanupPendingQuestions(e),t.cancel(),this.sessions.delete(e),!0)}cleanupPendingQuestions(e){let t=this.pendingQuestions.get(e);t&&(t.resolve(null),this.pendingQuestions.delete(e),this.pendingQuestionData.delete(e))}on(e,t){return super.on(e,t)}emit(e,t){return super.emit(e,t)}}var C=t,b=e.i(18973);class x{attemptId;providerId;sessionId;outputFormat;child;activeBackgroundAgents;backgroundWaitTimer;waitingForUserAnswer;pendingQuestion;constructor(e,t,s){this.attemptId=e,this.providerId="claude-cli",this.activeBackgroundAgents=0,this.backgroundWaitTimer=null,this.waitingForUserAnswer=!1,this.pendingQuestion=null,this.child=t,this.outputFormat=s}setPendingQuestion(e){this.pendingQuestion=e}getPendingQuestion(){return this.pendingQuestion}writeToolResult(e,t){if(!this.child.stdin||this.child.stdin.destroyed)return!1;let s=JSON.stringify({type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:e,content:t}]}});return this.child.stdin.write(s+"\n")}writeUserMessage(e){if(!this.child.stdin||this.child.stdin.destroyed)return!1;let t=JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:e}]}});return this.child.stdin.write(t+"\n")}cancel(){this.backgroundWaitTimer&&(clearInterval(this.backgroundWaitTimer),this.backgroundWaitTimer=null),this.child&&!this.child.killed&&(this.child.kill("SIGTERM"),setTimeout(()=>{this.child&&!this.child.killed&&this.child.kill("SIGKILL")},3e3))}}var A=e.i(233405);let S=(0,a.createLogger)("CLIProvider:Spawner"),U=(0,a.createLogger)("CLIProvider:Parser"),E=(0,a.createLogger)("CLIProvider");class P extends C.EventEmitter{id="claude-cli";sessions=new Map;resolveModel(e){return e}async start(e){let t,{attemptId:s,projectPath:n,prompt:i,sessionOptions:o,maxTurns:r,model:a,systemPromptAppend:l,outputFormat:u}=e,c=(0,b.findClaudePath)();if(!c){let e="Claude CLI not found. Set CLAUDE_PATH in your .env file.";throw this.emit("error",{attemptId:s,error:e,errorName:"CLINotFound"}),Error(e)}let d=function(e){let{claudePath:t,projectPath:s,model:n,sessionResume:i,maxTurns:o,systemPromptAppend:r,attemptId:a}=e,l=["--input-format","stream-json","--output-format","stream-json","--verbose","--permission-mode","bypassPermissions"];n&&l.push("--model",n),i&&l.push("--resume",i),o&&l.push("--max-turns",String(o)),r&&l.push("--append-system-prompt",r),S.info({claudePath:t,argsCount:l.length,attemptId:a},"Spawning CLI process");let{ANTHROPIC_AUTH_TOKEN:u,ANTHROPIC_BASE_URL:c,...d}=process.env;return(0,A.spawn)(t,l,{cwd:s,stdio:["pipe","pipe","pipe"],env:{...d,FORCE_COLOR:"0",NO_COLOR:"1",TERM:"dumb",PATH:`${process.env.PATH}:/opt/homebrew/bin:/usr/local/bin`}})}({claudePath:c,projectPath:n,model:a,attemptId:s,sessionResume:o?.resume,maxTurns:r,systemPromptAppend:l}),p=new x(s,d,u);this.sessions.set(s,p),t=JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:i}]}}),d.stdin?.write(t+"\n");let g="";return d.stdout?.on("data",e=>{let t=(g+=e.toString()).split("\n");for(let e of(g=t.pop()||"",t))e.trim()&&this.processLine(p,e)}),d.stderr?.on("data",e=>{let t=e.toString();E.debug({attemptId:s,content:t.substring(0,200)},"stderr received"),this.emit("stderr",{attemptId:s,content:t})}),d.on("error",e=>{E.error({attemptId:s,err:e},"Process error"),this.sessions.delete(s),this.emit("error",{attemptId:s,error:e.message,errorName:e.name})}),d.on("exit",e=>{E.info({attemptId:s,code:e},"Process exited"),g.trim()&&this.processLine(p,g),this.sessions.delete(s),this.emit("complete",{attemptId:s,sessionId:p.sessionId})}),p}processLine(e,t){let{attemptId:s}=e,n=function(e,t){let s,n;try{s=JSON.parse(e)}catch{return U.trace({line:e.substring(0,100)},"Non-JSON line"),null}let{attemptId:i}=t;if(U.debug({type:s?.type,attemptId:i},"CLI message received"),!d(s))return U.debug({type:s?.type},"Invalid message skipped"),null;let o=p(s);o.askUserQuestion&&(n=o.askUserQuestion);let r=!1;if("user"===s.type&&t.getPendingQuestion()){let e=s.message?.content||[],n=t.getPendingQuestion();for(let t of e)if("tool_result"===t.type&&t.tool_use_id&&n&&t.tool_use_id===n.toolUseId){U.info({attemptId:i,toolUseId:t.tool_use_id},"CLI auto-handled AskUserQuestion, clearing pending (answer will use auto-retry flow)"),r=!0;break}}let a="result"===s.type;return{messagePayload:{output:o.output,sessionId:o.sessionId,checkpointUuid:o.checkpointUuid,backgroundShell:o.backgroundShell,resultMessage:a?s:void 0,rawMessage:s},askUserQuestion:n,cliAutoHandledQuestion:r,isResultMessage:a}}(t,e);if(!n)return;if(n.messagePayload.sessionId&&(e.sessionId=n.messagePayload.sessionId),n.askUserQuestion){let{toolUseId:t,questions:i}=n.askUserQuestion;e.setPendingQuestion({toolUseId:t,questions:i,timestamp:Date.now()}),e.waitingForUserAnswer=!0,this.emit("question",{attemptId:s,toolUseId:t,questions:i})}if(n.cliAutoHandledQuestion){e.setPendingQuestion(null);let t=n.messagePayload.output,s=t?.message;if(s?.content)for(let e of s.content)"tool_result"===e.type&&e.is_error&&delete e.is_error}this.emit("message",{attemptId:s,...n.messagePayload});let i=n.messagePayload.rawMessage;if("system"===i.type&&"task_started"===i.subtype&&(e.activeBackgroundAgents=(e.activeBackgroundAgents||0)+1,E.info({attemptId:s,active:e.activeBackgroundAgents},"Background agent started")),"system"===i.type&&"task_notification"===i.subtype&&(e.activeBackgroundAgents=Math.max(0,(e.activeBackgroundAgents||0)-1),E.info({attemptId:s,active:e.activeBackgroundAgents},"Background agent notification received")),n.isResultMessage){if(e.waitingForUserAnswer)return void E.info({attemptId:s},"Result received but waiting for user answer — keeping stdin open");let t=e.activeBackgroundAgents||0;if(t>0){E.info({attemptId:s,activeAgents:t},"Result received but background agents still active, delaying stdin close");let n=0;e.backgroundWaitTimer=setInterval(()=>{n+=2e3;let t=e.activeBackgroundAgents||0;(t<=0||n>=6e4)&&(e.backgroundWaitTimer&&(clearInterval(e.backgroundWaitTimer),e.backgroundWaitTimer=null),E.info({attemptId:s,waited:n,remaining:t},"Closing stdin (background agents done or timeout)"),e.child.stdin?.end())},2e3)}else E.info({attemptId:s},"Result message received, closing stdin"),e.child.stdin?.end()}}answerQuestion(e,t,s,n){let i=this.sessions.get(e);if(!i)return E.warn({attemptId:e},"answerQuestion: session not found"),!1;let o=Object.entries(n).map(([e,t])=>`Q: ${e}
19
- A: ${t}`).join("\n\n"),r=`The user answered the previous question:
20
- ${o}
18
+ ## MODE: SERVER`};var o=e.i(955931);e.i(723643);var a=e.i(368770),l=t,u=e.i(522734),c=e.i(81850);let d=(0,a.createLogger)("SDKAdapter");function p(e){return"object"==typeof e&&null!==e&&"type"in e&&"string"==typeof e.type}function g(e){let t={output:{type:e.type}};switch(e.type){case"system":if(t.output={type:"system",subtype:e.subtype,session_id:e.session_id},"init"===e.subtype&&e.session_id&&(t.sessionId=e.session_id),"init"===e.subtype&&e.mcp_servers)for(let t of e.mcp_servers)"connected"===t.status?d.info({name:t.name},`MCP connected: ${t.name}`):"failed"===t.status&&d.error({name:t.name,error:t.error},`MCP failed: ${t.name}`);break;case"assistant":{t.output={type:"assistant",message:{role:"assistant",content:e.message.content}};let s=function(e){for(let t of e)if("tool_use"===t.type&&"AskUserQuestion"===t.name)return{toolUseId:t.id||"",questions:t.input?.questions||[]}}(e.message.content);s&&(t.askUserQuestion=s);let n=function(e){for(let t of e)if("tool_use"===t.type&&"Bash"===t.name){let e=t.input;if(e?.run_in_background===!0&&e?.command)return d.info({commandPreview:e.command.substring(0,50)},"Background shell detected via run_in_background=true"),{toolUseId:t.id||"",command:e.command,description:e.description}}for(let t of e)if("text"===t.type&&t.text){let e=t.text.match(/```background-shell\n([\s\S]+?)\n```/);if(e){let t=e[1].trim();if(t)return{toolUseId:`bg-shell-${Date.now()}`,command:t,description:"Background shell from markdown block"}}}}(e.message.content);n&&(t.backgroundShell=n);break}case"user":t.output={type:"user",message:{role:"user",content:e.message.content}},e.uuid&&(t.checkpointUuid=e.uuid);break;case"result":t.output={type:"result",subtype:e.subtype,session_id:e.session_id,is_error:e.is_error},e.session_id&&(t.sessionId=e.session_id);break;case"stream_event":{let s=e.event;"content_block_delta"===s.type&&s.delta&&("text_delta"===s.delta.type&&s.delta.text?t.output={type:"content_block_delta",index:s.index,delta:{type:"text_delta",text:s.delta.text}}:"thinking_delta"===s.delta.type&&s.delta.thinking&&(t.output={type:"content_block_delta",index:s.index,delta:{type:"thinking_delta",thinking:s.delta.thinking}})),"message_delta"===s.type&&s.usage&&(t.usageEvent={input_tokens:s.usage.input_tokens||0,output_tokens:s.usage.output_tokens||0,cache_read_input_tokens:s.usage.cache_read_input_tokens||0,cache_creation_input_tokens:s.usage.cache_creation_input_tokens||0}),"message_start"===s.type&&s.message?.usage&&(t.usageEvent={input_tokens:s.message.usage.input_tokens||0,output_tokens:s.message.usage.output_tokens||0,cache_read_input_tokens:s.message.usage.cache_read_input_tokens||0,cache_creation_input_tokens:s.message.usage.cache_creation_input_tokens||0});break}default:t.output={type:e.type}}return t}var m=e.i(446786);let h=(0,a.createLogger)("SDKProvider:MCP"),f={"claude-opus-4-6":"opus","claude-sonnet-4-5-20250929":"sonnet","claude-haiku-4-5-20251001":"haiku","claude-3-5-sonnet-20241022":"sonnet"},k=[/npm\s+run\s+(dev|start|serve)/i,/yarn\s+(dev|start|serve)/i,/pnpm\s+(dev|start|serve)/i,/npx\s+(directus|strapi|next|vite|nuxt)/i,/nohup\s+/i];var _=e.i(768770);let v=(0,a.createLogger)("SDKProvider:QueryBuilder"),y=["CLAUDECODE","CLAUDE_CODE_ENTRYPOINT","CK_"],w=(0,a.createLogger)("SDKProvider");class I{attemptId;controller;providerId;sessionId;outputFormat;queryRef;constructor(e,t,s){this.attemptId=e,this.controller=t,this.providerId="claude-sdk",this.outputFormat=s}cancel(){if(this.queryRef)try{this.queryRef.close()}catch{this.controller.abort()}else this.controller.abort()}}class T extends l.EventEmitter{id="claude-sdk";sessions=new Map;pendingQuestions=new Map;pendingQuestionData=new Map;resolveModel(e){return f[e]||e}async start(e){let{attemptId:t,projectPath:s,prompt:n,sessionOptions:i,maxTurns:r,model:o,systemPromptAppend:a,outputFormat:l}=e,u=new I(t,new AbortController,l);return this.sessions.set(t,u),this.runQuery(u,s,n,i,r,o,a),u}makeCanUseTool(e){var t,s,n;return t=()=>this.pendingQuestions.has(e),s=(t,s)=>{this.pendingQuestionData.set(e,{toolUseId:t,questions:s,timestamp:Date.now()}),this.emit("question",{attemptId:e,toolUseId:t,questions:s})},n=t=>new Promise(s=>{this.pendingQuestions.set(e,{toolUseId:t,resolve:s})}).then(t=>(this.pendingQuestions.delete(e),this.pendingQuestionData.delete(e),t)),async(i,r)=>{if(v.debug({toolName:i,attemptId:e},"canUseTool called"),"AskUserQuestion"===i){if(t())return{behavior:"deny",message:"Duplicate question"};let e=`ask-${Date.now()}`;s(e,r.questions||[]);let i=await n(e);return i&&0!==Object.keys(i.answers).length?{behavior:"allow",updatedInput:i}:{behavior:"deny",message:"User cancelled"}}if("Bash"===i){let e=r.command;if(e&&k.some(t=>t.test(e))&&!e.includes('echo "BGPID:$!"')&&/>\s*\/tmp\/[^\s]+\.log\s*$/.test(e)){let t=e.trim()+' 2>&1 & echo "BGPID:$!"';return v.debug({fixedCommand:t},"Fixed BGPID pattern"),{behavior:"allow",updatedInput:{...r,command:t}}}}return{behavior:"allow",updatedInput:r}}}async runQuery(e,t,s,i,r,o,a){let{attemptId:l,controller:d}=e;try{var f;(0,u.existsSync)(t)||(w.warn({projectPath:t,attemptId:l},"Project path missing, creating directory"),(0,u.mkdirSync)(t,{recursive:!0}));let a=function(e){let t=(0,n.join)((0,m.homedir)(),".claude.json"),s=(0,n.join)(e,".mcp.json"),i=null;if((0,u.existsSync)(t))try{let s=(0,u.readFileSync)(t,"utf-8"),n=JSON.parse(s);if(n.mcpServers&&"object"==typeof n.mcpServers&&Object.keys(n.mcpServers).length>0&&(i=n.mcpServers,h.info({servers:Object.keys(i||{}),path:t},"Loaded global MCP config")),n.projects&&n.projects[e]?.mcpServers){let t=n.projects[e].mcpServers;Object.keys(t).length>0&&(i={...i||{},...t},h.info({servers:Object.keys(t),projectPath:e},"Loaded CLI project MCP config"))}}catch(e){h.warn({err:e,path:t},"Failed to parse config file")}let r=function(e){if(!(0,u.existsSync)(e))return null;try{let t=(0,u.readFileSync)(e,"utf-8"),s=JSON.parse(t);return!s.mcpServers&&Object.keys(s).some(e=>{let t=s[e];return t&&"object"==typeof t&&("command"in t||"url"in t||"type"in t)})&&(s={mcpServers:s}),s.mcpServers||null}catch(t){return h.warn({err:t,path:e},"Failed to parse config file"),null}}(s);r&&h.info({servers:Object.keys(r),path:s},"Loaded project MCP config");let o={...i||{},...r||{}};if(0===Object.keys(o).length)return h.info("No MCP servers found in user or project config"),null;for(let[,e]of Object.entries(o)){if("env"in e&&e.env){for(let[t,s]of Object.entries(e.env))if("string"==typeof s&&s.startsWith("${")&&s.endsWith("}")){let n=s.slice(2,-1);e.env[t]=process.env[n]||""}}if("headers"in e&&e.headers)for(let[t,s]of Object.entries(e.headers))"string"==typeof s&&s.includes("${")&&(e.headers[t]=s.replace(/\$\{([^}]+)\}/g,(e,t)=>process.env[t]||""))}return h.info({servers:Object.keys(o)},"Merged MCP servers"),{mcpServers:o}}(t),k=a?.mcpServers?(f=a.mcpServers,Object.keys(f).map(e=>`mcp__${e}__*`)):[],I=o?this.resolveModel(o):"opus",T=function(e){let{projectPath:t,model:s,sessionOptions:i,maxTurns:r,mcpServers:o,mcpToolWildcards:a,controller:l,canUseToolCallback:c}=e,d=_.checkpointManager.getCheckpointingOptions(),p={executable:process.execPath,cwd:t,model:s,permissionMode:"bypassPermissions",...o?{mcpServers:o}:{},allowedTools:["Skill","Task","Read","Write","Edit","NotebookEdit","Bash","Grep","Glob","WebFetch","WebSearch","TodoWrite","AskUserQuestion",...a],...i?.resume?{resume:i.resume}:{},...i?.resumeSessionAt?{resumeSessionAt:i.resumeSessionAt}:{},...d,...r?{maxTurns:r}:{},abortController:l,canUseTool:c,env:function(e){let t={};for(let[e,s]of Object.entries(process.env))y.some(t=>e.startsWith(t))||(t[e]=s);t.ANTHROPIC_MODEL=e;let s=(0,n.resolve)(process.env.DATA_DIR||"./data","claude-sdk-isolated-config");try{(0,u.mkdirSync)(s,{recursive:!0})}catch{}return t.CLAUDE_CONFIG_DIR=s,t}(s)};return v.debug({model:s,cwd:t,mcpCount:a.length},"Query options built"),p}({projectPath:t,model:I,sessionOptions:i,maxTurns:r,mcpServers:a?.mcpServers,mcpToolWildcards:k,controller:d,canUseToolCallback:this.makeCanUseTool(l)});w.info({endpoint:process.env.ANTHROPIC_BASE_URL||"https://api.anthropic.com",prompt:s.substring(0,200)+(s.length>200?"...":""),model:T.model,cwd:T.cwd},"SDK Query starting");let C=(0,c.query)({prompt:s,options:T});for await(let t of(e.queryRef=C,C)){if(d.signal.aborted)break;try{if(!p(t))continue;let s=g(t);s.sessionId&&(e.sessionId=s.sessionId),this.emit("message",{attemptId:l,output:s.output,sessionId:s.sessionId,checkpointUuid:s.checkpointUuid,backgroundShell:s.backgroundShell,resultMessage:"result"===t.type?t:void 0,usageEvent:s.usageEvent,rawMessage:t})}catch(t){let e=t instanceof Error?t.message:"Unknown message error";w.error({err:t,message:e},"Message processing error"),e.includes("Unexpected end of JSON")||this.emit("stderr",{attemptId:l,content:`Warning: ${e}`})}}this.cleanupPendingQuestions(l),this.sessions.delete(l),this.emit("complete",{attemptId:l,sessionId:e.sessionId})}catch(g){let n=g instanceof Error?g.message:"Unknown error",u=g instanceof Error?g.name:"UnknownError",c=!!i?.resume;if(w.error({err:g,message:n,attemptId:l},"SDK Error - Query failed"),c&&!d.signal.aborted)return w.warn({attemptId:l},"Resume failed, retrying without resume"),this.sessions.set(l,e),this.runQuery(e,t,s,void 0,r,o,a);let p=n.toLowerCase().includes("prompt is too long")||n.toLowerCase().includes("request too large");this.cleanupPendingQuestions(l),this.sessions.delete(l),this.emit("error",{attemptId:l,error:n,errorName:u,isPromptTooLong:p,wasResuming:c})}}answerQuestion(e,t,s,n){let i=this.pendingQuestions.get(e);return!!i&&(t&&i.toolUseId!==t?(w.warn({attemptId:e,expected:i.toolUseId,received:t},"Rejecting stale answer"),!1):(i.resolve({questions:s,answers:n}),this.pendingQuestions.delete(e),this.pendingQuestionData.delete(e),this.emit("questionResolved",{attemptId:e}),!0))}cancelQuestion(e){let t=this.pendingQuestions.get(e);return!!t&&(t.resolve(null),this.pendingQuestions.delete(e),this.pendingQuestionData.delete(e),this.emit("questionResolved",{attemptId:e}),!0)}hasPendingQuestion(e){return this.pendingQuestions.has(e)}getPendingQuestionData(e){return this.pendingQuestionData.get(e)||null}cancelSession(e){let t=this.sessions.get(e);return!!t&&(this.cleanupPendingQuestions(e),t.cancel(),this.sessions.delete(e),!0)}cleanupPendingQuestions(e){let t=this.pendingQuestions.get(e);t&&(t.resolve(null),this.pendingQuestions.delete(e),this.pendingQuestionData.delete(e))}on(e,t){return super.on(e,t)}emit(e,t){return super.emit(e,t)}}var C=t,b=e.i(18973);class x{attemptId;providerId;sessionId;outputFormat;child;activeBackgroundAgents;backgroundWaitTimer;waitingForUserAnswer;pendingQuestion;constructor(e,t,s){this.attemptId=e,this.providerId="claude-cli",this.activeBackgroundAgents=0,this.backgroundWaitTimer=null,this.waitingForUserAnswer=!1,this.pendingQuestion=null,this.child=t,this.outputFormat=s}setPendingQuestion(e){this.pendingQuestion=e}getPendingQuestion(){return this.pendingQuestion}writeToolResult(e,t){if(!this.child.stdin||this.child.stdin.destroyed)return!1;let s=JSON.stringify({type:"user",message:{role:"user",content:[{type:"tool_result",tool_use_id:e,content:t}]}});return this.child.stdin.write(s+"\n")}writeUserMessage(e){if(!this.child.stdin||this.child.stdin.destroyed)return!1;let t=JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:e}]}});return this.child.stdin.write(t+"\n")}cancel(){this.backgroundWaitTimer&&(clearInterval(this.backgroundWaitTimer),this.backgroundWaitTimer=null),this.child&&!this.child.killed&&(this.child.kill("SIGTERM"),setTimeout(()=>{this.child&&!this.child.killed&&this.child.kill("SIGKILL")},3e3))}}var S=e.i(233405);let A=(0,a.createLogger)("CLIProvider:Spawner"),U=(0,a.createLogger)("CLIProvider:Parser"),P=(0,a.createLogger)("CLIProvider");class E extends C.EventEmitter{id="claude-cli";sessions=new Map;resolveModel(e){return e}async start(e){let t,{attemptId:s,projectPath:n,prompt:i,sessionOptions:r,maxTurns:o,model:a,systemPromptAppend:l,outputFormat:u}=e,c=(0,b.findClaudePath)();if(!c){let e="Claude CLI not found. Set CLAUDE_PATH in your .env file.";throw this.emit("error",{attemptId:s,error:e,errorName:"CLINotFound"}),Error(e)}let d=function(e){let{claudePath:t,projectPath:s,model:n,sessionResume:i,maxTurns:r,systemPromptAppend:o,attemptId:a}=e,l=["--input-format","stream-json","--output-format","stream-json","--verbose","--permission-mode","bypassPermissions"];n&&l.push("--model",n),i&&l.push("--resume",i),r&&l.push("--max-turns",String(r)),o&&l.push("--append-system-prompt",o),A.info({claudePath:t,argsCount:l.length,attemptId:a},"Spawning CLI process");let{ANTHROPIC_AUTH_TOKEN:u,ANTHROPIC_BASE_URL:c,...d}=process.env;return(0,S.spawn)(t,l,{cwd:s,stdio:["pipe","pipe","pipe"],env:{...d,FORCE_COLOR:"0",NO_COLOR:"1",TERM:"dumb",PATH:`${process.env.PATH}:/opt/homebrew/bin:/usr/local/bin`}})}({claudePath:c,projectPath:n,model:a,attemptId:s,sessionResume:r?.resume,maxTurns:o,systemPromptAppend:l}),p=new x(s,d,u);this.sessions.set(s,p),t=JSON.stringify({type:"user",message:{role:"user",content:[{type:"text",text:i}]}}),d.stdin?.write(t+"\n");let g="";return d.stdout?.on("data",e=>{let t=(g+=e.toString()).split("\n");for(let e of(g=t.pop()||"",t))e.trim()&&this.processLine(p,e)}),d.stderr?.on("data",e=>{let t=e.toString();P.debug({attemptId:s,content:t.substring(0,200)},"stderr received"),this.emit("stderr",{attemptId:s,content:t})}),d.on("error",e=>{P.error({attemptId:s,err:e},"Process error"),this.sessions.delete(s),this.emit("error",{attemptId:s,error:e.message,errorName:e.name})}),d.on("exit",e=>{P.info({attemptId:s,code:e},"Process exited"),g.trim()&&this.processLine(p,g),this.sessions.delete(s),this.emit("complete",{attemptId:s,sessionId:p.sessionId})}),p}processLine(e,t){let{attemptId:s}=e,n=function(e,t){let s,n;try{s=JSON.parse(e)}catch{return U.trace({line:e.substring(0,100)},"Non-JSON line"),null}let{attemptId:i}=t;if(U.debug({type:s?.type,attemptId:i},"CLI message received"),!p(s))return U.debug({type:s?.type},"Invalid message skipped"),null;let r=g(s);r.askUserQuestion&&(n=r.askUserQuestion);let o=!1;if("user"===s.type&&t.getPendingQuestion()){let e=s.message?.content||[],n=t.getPendingQuestion();for(let t of e)if("tool_result"===t.type&&t.tool_use_id&&n&&t.tool_use_id===n.toolUseId){U.info({attemptId:i,toolUseId:t.tool_use_id},"CLI auto-handled AskUserQuestion, clearing pending (answer will use auto-retry flow)"),o=!0;break}}let a="result"===s.type;return{messagePayload:{output:r.output,sessionId:r.sessionId,checkpointUuid:r.checkpointUuid,backgroundShell:r.backgroundShell,resultMessage:a?s:void 0,rawMessage:s},askUserQuestion:n,cliAutoHandledQuestion:o,isResultMessage:a}}(t,e);if(!n)return;if(n.messagePayload.sessionId&&(e.sessionId=n.messagePayload.sessionId),n.askUserQuestion){let{toolUseId:t,questions:i}=n.askUserQuestion;e.setPendingQuestion({toolUseId:t,questions:i,timestamp:Date.now()}),e.waitingForUserAnswer=!0,this.emit("question",{attemptId:s,toolUseId:t,questions:i})}if(n.cliAutoHandledQuestion){e.setPendingQuestion(null);let t=n.messagePayload.output,s=t?.message;if(s?.content)for(let e of s.content)"tool_result"===e.type&&e.is_error&&delete e.is_error}this.emit("message",{attemptId:s,...n.messagePayload});let i=n.messagePayload.rawMessage;if("system"===i.type&&"task_started"===i.subtype&&(e.activeBackgroundAgents=(e.activeBackgroundAgents||0)+1,P.info({attemptId:s,active:e.activeBackgroundAgents},"Background agent started")),"system"===i.type&&"task_notification"===i.subtype&&(e.activeBackgroundAgents=Math.max(0,(e.activeBackgroundAgents||0)-1),P.info({attemptId:s,active:e.activeBackgroundAgents},"Background agent notification received")),n.isResultMessage){if(e.waitingForUserAnswer)return void P.info({attemptId:s},"Result received but waiting for user answer — keeping stdin open");let t=e.activeBackgroundAgents||0;if(t>0){P.info({attemptId:s,activeAgents:t},"Result received but background agents still active, delaying stdin close");let n=0;e.backgroundWaitTimer=setInterval(()=>{n+=2e3;let t=e.activeBackgroundAgents||0;(t<=0||n>=6e4)&&(e.backgroundWaitTimer&&(clearInterval(e.backgroundWaitTimer),e.backgroundWaitTimer=null),P.info({attemptId:s,waited:n,remaining:t},"Closing stdin (background agents done or timeout)"),e.child.stdin?.end())},2e3)}else P.info({attemptId:s},"Result message received, closing stdin"),e.child.stdin?.end()}}answerQuestion(e,t,s,n){let i=this.sessions.get(e);if(!i)return P.warn({attemptId:e},"answerQuestion: session not found"),!1;let r=Object.entries(n).map(([e,t])=>`Q: ${e}
19
+ A: ${t}`).join("\n\n"),o=`The user answered the previous question:
20
+ ${r}
21
21
 
22
- Please continue based on these answers.`,a=i.writeUserMessage(r);return a?(E.info({attemptId:e},"Answer sent to CLI as follow-up message via stdin"),i.waitingForUserAnswer=!1,i.setPendingQuestion(null),this.emit("questionResolved",{attemptId:e})):E.error({attemptId:e},"Failed to write answer to CLI stdin (process may have exited)"),a}cancelQuestion(e){let t=this.sessions.get(e);if(!t)return!1;let s=t.getPendingQuestion();if(!s)return!1;let n=t.writeToolResult(s.toolUseId,"User cancelled");return n&&(t.setPendingQuestion(null),this.emit("questionResolved",{attemptId:e})),n}hasPendingQuestion(e){return!!this.sessions.get(e)?.getPendingQuestion()}getPendingQuestionData(e){return this.sessions.get(e)?.getPendingQuestion()||null}cancelSession(e){let t=this.sessions.get(e);return!!t&&(t.cancel(),this.sessions.delete(e),!0)}on(e,t){return super.on(e,t)}emit(e,t){return super.emit(e,t)}}let O=new Map;function M(e){if(!O.has(e))switch(e){case"claude-sdk":O.set(e,new T);break;case"claude-cli":O.set(e,new P);break;default:throw Error(`Unknown provider: ${e}`)}return O.get(e)}let R=(0,a.createLogger)("AgentOutputHandler");var D=e.i(408970),L=t;function Q(e,t,s){var n;let i=e+t,o=i/s,r=100*o,{status:a,score:l}=(n=o)<.6?{status:"HEALTHY",score:1}:n<.75?{status:"WARNING",score:.8}:n<.9?{status:"CRITICAL",score:.5}:{status:"EMERGENCY",score:.2},u=s>=1e6?Math.floor(.33*s):Math.floor(.75*s);return{status:a,score:l,utilization:o,utilizationPercent:r,totalTokens:i,limit:s,remaining:s-i,shouldCompact:i>=u,compactThreshold:u}}let N=(0,a.createLogger)("UsageContextTokenCalculator"),$=(0,a.createLogger)("UsageTracker");class B extends L.EventEmitter{sessions=new Map;accountInfo;constructor(){super()}initSession(e){if(!this.sessions.has(e)){let t={totalInputTokens:0,totalOutputTokens:0,totalCacheCreationTokens:0,totalCacheReadTokens:0,totalTokens:0,totalCostUSD:0,numTurns:0,durationMs:0,durationApiMs:0,contextUsed:0,contextLimit:2e5,contextPercentage:0,baselineContext:0,modelUsage:{},startedAt:Date.now(),lastUpdatedAt:Date.now()};this.sessions.set(e,t)}return this.sessions.get(e)}trackResult(e,t){let s=this.initSession(e);if("session_id"in t&&(s.sessionId=t.session_id),"usage"in t){var n,i;let e,o,r,a,l,u,c,d,p=t.usage;s.totalInputTokens+=p.input_tokens,s.totalOutputTokens+=p.output_tokens,s.totalCacheCreationTokens+=p.cache_creation_input_tokens||0,s.totalCacheReadTokens+=p.cache_read_input_tokens||0,s.totalTokens=s.totalInputTokens+s.totalOutputTokens;let{contextUsed:g,contextPercentage:m,baselineContext:h,contextHealth:f}=(n=s.contextLimit,i=0===s.numTurns,e=p.input_tokens||0,o=p.cache_read_input_tokens||0,r=p.cache_creation_input_tokens||0,a=p.output_tokens||0,l=0,i&&o>0&&(l=o,N.info(`First turn baseline (cached): ${o} tokens`)),c=(u=e+o+r+a)/n*100,d=Q(e+o+r,a,n),N.debug({contextUsed:u,contextLimit:n,contextPercentage:c.toFixed(1),healthStatus:d.status,inputTokens:e,cacheRead:o,cacheCreation:r,outputTokens:a,totalInput:e+o+r},"Context updated (includes cache_read)"),{contextUsed:u,contextPercentage:c,baselineContext:l,contextHealth:d});s.contextUsed=g,s.contextPercentage=m,h>0&&(s.baselineContext=h),s.contextHealth=f}if("total_cost_usd"in t&&(s.totalCostUSD+=t.total_cost_usd),"num_turns"in t&&(s.numTurns+=t.num_turns||0),"duration_ms"in t&&(s.durationMs+=t.duration_ms||0),"duration_api_ms"in t&&(s.durationApiMs+=t.duration_api_ms||0),"success"===t.subtype&&"modelUsage"in t&&t.modelUsage)for(let[e,n]of Object.entries(t.modelUsage)){s.modelUsage[e]||(s.modelUsage[e]={inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,costUSD:0,contextWindow:n.contextWindow||2e5});let t=s.modelUsage[e];t.inputTokens+=n.inputTokens||0,t.outputTokens+=n.outputTokens||0,t.cacheReadInputTokens+=n.cacheReadInputTokens||0,t.cacheCreationInputTokens+=n.cacheCreationInputTokens||0,t.costUSD+=n.costUSD||0,n.contextWindow&&n.contextWindow>0&&(s.contextLimit=n.contextWindow)}s.lastUpdatedAt=Date.now(),this.emit("usage-update",{attemptId:e,usage:s})}trackUsageEvent(e,t){let s=this.initSession(e),n=(t.input_tokens||0)+(t.cache_read_input_tokens||0)+(t.cache_creation_input_tokens||0),i=t.output_tokens||0;0===s.baselineContext&&n>0&&(s.baselineContext=n,$.info({attemptId:e,baseline:n},"Context baseline set from first usage event")),n>0&&(s.contextUsed=n+i,s.contextPercentage=s.contextUsed/s.contextLimit*100,s.contextHealth=Q(n,i,s.contextLimit),$.debug({attemptId:e,contextUsed:s.contextUsed,contextLimit:s.contextLimit,contextPct:s.contextPercentage.toFixed(1),input:t.input_tokens,cacheRead:t.cache_read_input_tokens,cacheCreate:t.cache_creation_input_tokens,output:i},"Context updated from stream usage event")),s.lastUpdatedAt=Date.now(),this.emit("usage-update",{attemptId:e,usage:s})}getUsage(e){return this.sessions.get(e)}clearSession(e){this.sessions.delete(e)}getAllSessions(){return this.sessions}setAccountInfo(e){this.accountInfo=e}getAccountInfo(){return this.accountInfo}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}}let j=new B;var F=e.i(224361);let W=(0,a.createLogger)("GitStatsCollector"),G=(0,F.promisify)(A.exec);async function q(e){try{let{stdout:t}=await G("git diff --numstat HEAD",{cwd:e});if(!t.trim())return{additions:0,deletions:0,filesChanged:0,capturedAt:Date.now()};return function(e){let t=e.trim().split("\n").filter(Boolean),s=0,n=0,i=0;for(let e of t){let t=e.split(" ");if(t.length<3)continue;let[o,r]=t;"-"!==o&&(s+=parseInt(o,10)||0),"-"!==r&&(n+=parseInt(r,10)||0),i++}return{additions:s,deletions:n,filesChanged:i,capturedAt:Date.now()}}(t)}catch(e){return W.error({error:e},"[GitStats] Failed to collect git stats:"),null}}class H{cache=new Map;set(e,t){this.cache.set(e,t)}get(e){return this.cache.get(e)}clear(e){this.cache.delete(e)}getAll(){return this.cache}}let Y=new H;var J=e.i(414688);class K{store=new Map;set(e,t){this.store.set(e,t)}get(e){return this.store.get(e)||null}clear(e){this.store.delete(e)}}process.env.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="1",process.env.CLAUDE_CODE_ENABLE_TASKS="true";let V=(0,a.createLogger)("AgentManager");class z extends t.EventEmitter{agents=new Map;pendingBashCommands=new Map;persistentQuestionStore=new K;constructor(){super(),process.on("exit",()=>this.cancelAll())}buildWiringContext(){return{getSessionId:e=>this.agents.get(e)?.session.sessionId,setSessionId:(e,t)=>{let s=this.agents.get(e);s&&(s.session.sessionId=t)},deleteAgent:e=>this.agents.delete(e),emit:(e,t)=>this.emit(e,t),pendingBashCommands:this.pendingBashCommands}}async start(t){var a;let l,u,c,d,p,g,m,h,{attemptId:f,projectPath:k,prompt:v,sessionOptions:y,filePaths:w,outputFormat:I,outputSchema:T,maxTurns:C,model:b,provider:x}=t;if(this.agents.has(f))return;let A=v,S=[];w&&w.length>0&&S.push(...w);let U=/@([\w.\/\\-]+(?:#L\d+(?:-\d+)?)?)/g,E=[];for(;null!==(l=U.exec(v));){let e=l[1],t=e.indexOf("#"),s=t>=0?e.substring(0,t):e,n=t>=0?e.substring(t+1):void 0;(s.includes(".")||s.includes("/"))&&E.push({fullMatch:l[0],filePath:s,lineRange:n})}let P=[],O=new Set;for(let e of S){let t=(0,n.isAbsolute)(e)?e:(0,n.resolve)(k,e);if(!O.has(t)){O.add(t);try{let n=await (0,s.readFile)(t,"utf-8");P.push(`<file path="${e}">
22
+ Please continue based on these answers.`,a=i.writeUserMessage(o);return a?(P.info({attemptId:e},"Answer sent to CLI as follow-up message via stdin"),i.waitingForUserAnswer=!1,i.setPendingQuestion(null),this.emit("questionResolved",{attemptId:e})):P.error({attemptId:e},"Failed to write answer to CLI stdin (process may have exited)"),a}cancelQuestion(e){let t=this.sessions.get(e);if(!t)return!1;let s=t.getPendingQuestion();if(!s)return!1;let n=t.writeToolResult(s.toolUseId,"User cancelled");return n&&(t.setPendingQuestion(null),this.emit("questionResolved",{attemptId:e})),n}hasPendingQuestion(e){return!!this.sessions.get(e)?.getPendingQuestion()}getPendingQuestionData(e){return this.sessions.get(e)?.getPendingQuestion()||null}cancelSession(e){let t=this.sessions.get(e);return!!t&&(t.cancel(),this.sessions.delete(e),!0)}on(e,t){return super.on(e,t)}emit(e,t){return super.emit(e,t)}}let O=new Map;function M(e){if(!O.has(e))switch(e){case"claude-sdk":O.set(e,new T);break;case"claude-cli":O.set(e,new E);break;default:throw Error(`Unknown provider: ${e}`)}return O.get(e)}let R=(0,a.createLogger)("AgentOutputHandler");var D=e.i(408970),L=t;function Q(e,t,s){var n;let i=e+t,r=i/s,o=100*r,{status:a,score:l}=(n=r)<.6?{status:"HEALTHY",score:1}:n<.75?{status:"WARNING",score:.8}:n<.9?{status:"CRITICAL",score:.5}:{status:"EMERGENCY",score:.2},u=s>=1e6?Math.floor(.33*s):Math.floor(.75*s);return{status:a,score:l,utilization:r,utilizationPercent:o,totalTokens:i,limit:s,remaining:s-i,shouldCompact:i>=u,compactThreshold:u}}let N=(0,a.createLogger)("UsageContextTokenCalculator"),$=(0,a.createLogger)("UsageTracker");class B extends L.EventEmitter{sessions=new Map;accountInfo;constructor(){super()}initSession(e){if(!this.sessions.has(e)){let t={totalInputTokens:0,totalOutputTokens:0,totalCacheCreationTokens:0,totalCacheReadTokens:0,totalTokens:0,totalCostUSD:0,numTurns:0,durationMs:0,durationApiMs:0,contextUsed:0,contextLimit:2e5,contextPercentage:0,baselineContext:0,modelUsage:{},startedAt:Date.now(),lastUpdatedAt:Date.now()};this.sessions.set(e,t)}return this.sessions.get(e)}trackResult(e,t){let s=this.initSession(e);if("session_id"in t&&(s.sessionId=t.session_id),"usage"in t){var n,i;let e,r,o,a,l,u,c,d,p=t.usage;s.totalInputTokens+=p.input_tokens,s.totalOutputTokens+=p.output_tokens,s.totalCacheCreationTokens+=p.cache_creation_input_tokens||0,s.totalCacheReadTokens+=p.cache_read_input_tokens||0,s.totalTokens=s.totalInputTokens+s.totalOutputTokens;let{contextUsed:g,contextPercentage:m,baselineContext:h,contextHealth:f}=(n=s.contextLimit,i=0===s.numTurns,e=p.input_tokens||0,r=p.cache_read_input_tokens||0,o=p.cache_creation_input_tokens||0,a=p.output_tokens||0,l=0,i&&r>0&&(l=r,N.info(`First turn baseline (cached): ${r} tokens`)),c=(u=e+r+o+a)/n*100,d=Q(e+r+o,a,n),N.debug({contextUsed:u,contextLimit:n,contextPercentage:c.toFixed(1),healthStatus:d.status,inputTokens:e,cacheRead:r,cacheCreation:o,outputTokens:a,totalInput:e+r+o},"Context updated (includes cache_read)"),{contextUsed:u,contextPercentage:c,baselineContext:l,contextHealth:d});s.contextUsed=g,s.contextPercentage=m,h>0&&(s.baselineContext=h),s.contextHealth=f}if("total_cost_usd"in t&&(s.totalCostUSD+=t.total_cost_usd),"num_turns"in t&&(s.numTurns+=t.num_turns||0),"duration_ms"in t&&(s.durationMs+=t.duration_ms||0),"duration_api_ms"in t&&(s.durationApiMs+=t.duration_api_ms||0),"success"===t.subtype&&"modelUsage"in t&&t.modelUsage)for(let[e,n]of Object.entries(t.modelUsage)){s.modelUsage[e]||(s.modelUsage[e]={inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,costUSD:0,contextWindow:n.contextWindow||2e5});let t=s.modelUsage[e];t.inputTokens+=n.inputTokens||0,t.outputTokens+=n.outputTokens||0,t.cacheReadInputTokens+=n.cacheReadInputTokens||0,t.cacheCreationInputTokens+=n.cacheCreationInputTokens||0,t.costUSD+=n.costUSD||0,n.contextWindow&&n.contextWindow>0&&(s.contextLimit=n.contextWindow)}s.lastUpdatedAt=Date.now(),this.emit("usage-update",{attemptId:e,usage:s})}trackUsageEvent(e,t){let s=this.initSession(e),n=(t.input_tokens||0)+(t.cache_read_input_tokens||0)+(t.cache_creation_input_tokens||0),i=t.output_tokens||0;0===s.baselineContext&&n>0&&(s.baselineContext=n,$.info({attemptId:e,baseline:n},"Context baseline set from first usage event")),n>0&&(s.contextUsed=n+i,s.contextPercentage=s.contextUsed/s.contextLimit*100,s.contextHealth=Q(n,i,s.contextLimit),$.debug({attemptId:e,contextUsed:s.contextUsed,contextLimit:s.contextLimit,contextPct:s.contextPercentage.toFixed(1),input:t.input_tokens,cacheRead:t.cache_read_input_tokens,cacheCreate:t.cache_creation_input_tokens,output:i},"Context updated from stream usage event")),s.lastUpdatedAt=Date.now(),this.emit("usage-update",{attemptId:e,usage:s})}getUsage(e){return this.sessions.get(e)}clearSession(e){this.sessions.delete(e)}getAllSessions(){return this.sessions}setAccountInfo(e){this.accountInfo=e}getAccountInfo(){return this.accountInfo}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}}let j=new B;var F=e.i(224361);let W=(0,a.createLogger)("GitStatsCollector"),G=(0,F.promisify)(S.exec);async function q(e){try{let{stdout:t}=await G("git diff --numstat HEAD",{cwd:e});if(!t.trim())return{additions:0,deletions:0,filesChanged:0,capturedAt:Date.now()};return function(e){let t=e.trim().split("\n").filter(Boolean),s=0,n=0,i=0;for(let e of t){let t=e.split(" ");if(t.length<3)continue;let[r,o]=t;"-"!==r&&(s+=parseInt(r,10)||0),"-"!==o&&(n+=parseInt(o,10)||0),i++}return{additions:s,deletions:n,filesChanged:i,capturedAt:Date.now()}}(t)}catch(e){return W.error({error:e},"[GitStats] Failed to collect git stats:"),null}}class H{cache=new Map;set(e,t){this.cache.set(e,t)}get(e){return this.cache.get(e)}clear(e){this.cache.delete(e)}getAll(){return this.cache}}let Y=new H;var J=e.i(414688);class K{store=new Map;set(e,t){this.store.set(e,t)}get(e){return this.store.get(e)||null}clear(e){this.store.delete(e)}}process.env.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING="1",process.env.CLAUDE_CODE_ENABLE_TASKS="true";let V=(0,a.createLogger)("AgentManager");class z extends t.EventEmitter{agents=new Map;pendingBashCommands=new Map;persistentQuestionStore=new K;constructor(){super(),process.on("exit",()=>this.cancelAll())}buildWiringContext(){return{getSessionId:e=>this.agents.get(e)?.session.sessionId,setSessionId:(e,t)=>{let s=this.agents.get(e);s&&(s.session.sessionId=t)},deleteAgent:e=>this.agents.delete(e),emit:(e,t)=>this.emit(e,t),pendingBashCommands:this.pendingBashCommands}}async start(t){var a;let l,u,c,d,p,g,m,h,{attemptId:f,projectPath:k,prompt:v,sessionOptions:y,filePaths:w,outputFormat:I,outputSchema:T,maxTurns:C,model:b,provider:x}=t;if(this.agents.has(f))return;let S=v,A=[];w&&w.length>0&&A.push(...w);let U=/@([\w.\/\\-]+(?:#L\d+(?:-\d+)?)?)/g,P=[];for(;null!==(l=U.exec(v));){let e=l[1],t=e.indexOf("#"),s=t>=0?e.substring(0,t):e,n=t>=0?e.substring(t+1):void 0;(s.includes(".")||s.includes("/"))&&P.push({fullMatch:l[0],filePath:s,lineRange:n})}let E=[],O=new Set;for(let e of A){let t=(0,n.isAbsolute)(e)?e:(0,n.resolve)(k,e);if(!O.has(t)){O.add(t);try{let n=await (0,s.readFile)(t,"utf-8");E.push(`<file path="${e}">
23
23
  ${n}
24
- </file>`)}catch(s){V.warn({path:t},"Could not read attached file, falling back to @reference"),P.push(`@${e}`)}}}for(let e of E){let t=(0,n.isAbsolute)(e.filePath)?e.filePath:(0,n.resolve)(k,e.filePath);if(!O.has(t)){O.add(t);try{let n=await (0,s.readFile)(t,"utf-8");if(e.lineRange){let t=n.split("\n"),s=e.lineRange.match(/^L(\d+)(?:-(\d+))?$/);if(s){let i=Math.max(1,parseInt(s[1]))-1,o=s[2]?parseInt(s[2]):i+1;n=t.slice(i,o).join("\n"),P.push(`<file path="${e.filePath}" lines="${e.lineRange}">
24
+ </file>`)}catch(s){V.warn({path:t},"Could not read attached file, falling back to @reference"),E.push(`@${e}`)}}}for(let e of P){let t=(0,n.isAbsolute)(e.filePath)?e.filePath:(0,n.resolve)(k,e.filePath);if(!O.has(t)){O.add(t);try{let n=await (0,s.readFile)(t,"utf-8");if(e.lineRange){let t=n.split("\n"),s=e.lineRange.match(/^L(\d+)(?:-(\d+))?$/);if(s){let i=Math.max(1,parseInt(s[1]))-1,r=s[2]?parseInt(s[2]):i+1;n=t.slice(i,r).join("\n"),E.push(`<file path="${e.filePath}" lines="${e.lineRange}">
25
25
  ${n}
26
- </file>`)}else P.push(`<file path="${e.filePath}">
26
+ </file>`)}else E.push(`<file path="${e.filePath}">
27
27
  ${n}
28
- </file>`)}else P.push(`<file path="${e.filePath}">
28
+ </file>`)}else E.push(`<file path="${e.filePath}">
29
29
  ${n}
30
- </file>`)}catch{V.debug({path:t},"Could not read mentioned file, keeping @reference")}}}if(P.length>0){let e=v;for(let t of E){let s=(0,n.isAbsolute)(t.filePath)?t.filePath:(0,n.resolve)(k,t.filePath);O.has(s)&&(e=e.replace(t.fullMatch,"").trim())}A=`${P.join("\n\n")}
30
+ </file>`)}catch{V.debug({path:t},"Could not read mentioned file, keeping @reference")}}}if(E.length>0){let e=v;for(let t of P){let s=(0,n.isAbsolute)(t.filePath)?t.filePath:(0,n.resolve)(k,t.filePath);O.has(s)&&(e=e.replace(t.fullMatch,"").trim())}S=`${E.join("\n\n")}
31
31
 
32
- ${e}`}let L=function(e={}){var t,s,n;let r,a;if("string"==typeof e)return i;let{prompt:l,outputFormat:u,outputSchema:c,attemptId:d,outputFilePath:p}=e,g=i;return u&&d&&(g+="\n"+(t=u,s=c,n=d,a=p||`data/tmp/${n}`,s?`## OUTPUT FORMAT: ${t.toUpperCase()}
32
+ ${e}`}let L=function(e={}){var t,s,n;let o,a;if("string"==typeof e)return i;let{prompt:l,outputFormat:u,outputSchema:c,attemptId:d,outputFilePath:p}=e,g=i;return u&&d&&(g+="\n"+(t=u,s=c,n=d,a=p||`data/tmp/${n}`,s?`## OUTPUT FORMAT: ${t.toUpperCase()}
33
33
  You MUST save your work results to a ${t.toUpperCase()} file at \`${a}.${t}\`.
34
34
 
35
35
  Format specification:
@@ -48,9 +48,9 @@ CRITICAL: Your task is INCOMPLETE until you:
48
48
  1. Write your generated results to the file using the Write tool
49
49
  2. Read back the file to verify it is valid ${t.toUpperCase()}
50
50
 
51
- The file MUST contain your actual work output - not empty, not placeholders.`)),l&&(r=l.toLowerCase(),/run.*(start|dev|server)|start.*(directus|strapi|server)|npm run (dev|start)|npx.*(start|dev)/.test(r))&&o.server&&(g+="\n"+o.server),g}({prompt:v,projectPath:k});L&&(A+=`
51
+ The file MUST contain your actual work output - not empty, not placeholders.`)),l&&(o=l.toLowerCase(),/run.*(start|dev|server)|start.*(directus|strapi|server)|npm run (dev|start)|npx.*(start|dev)/.test(o))&&r.server&&(g+="\n"+r.server),g}({prompt:v,projectPath:k});L&&(S+=`
52
52
 
53
- ${L}`),I&&(A+=(u=process.env.DATA_DIR||process.cwd(),c=(0,n.resolve)(u,"tmp",f||"unknown"),d=function(e){switch(e.toLowerCase()){case"json":return`Example: Write:
53
+ ${L}`),I&&(S+=(u=process.env.DATA_DIR||process.cwd(),c=(0,n.resolve)(u,"tmp",f||"unknown"),d=function(e){switch(e.toLowerCase()){case"json":return`Example: Write:
54
54
  ["Max", "Bella", "Charlie"]
55
55
 
56
56
  NOT:
@@ -126,11 +126,11 @@ ${d}
126
126
  Your task is INCOMPLETE until:
127
127
  1. File exists with valid content
128
128
  2. You have Read it back to verify
129
- ========================`));let Q=b?.trim()||function(){for(let e of[process.env.ANTHROPIC_MODEL,process.env.ANTHROPIC_DEFAULT_OPUS_MODEL,process.env.ANTHROPIC_DEFAULT_SONNET_MODEL,process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL]){let t=e?.trim();if(t)return t}return"claude-opus-4-6"}(),N=(0,r.modelIdToDisplayName)(Q),$=N!==Q?`You are powered by the model named ${N}. The exact model ID is ${Q}.`:`You are powered by the model ${Q}.`,B=`Your current working directory is ${k}. All file operations should use paths relative to or within this directory.`,F=x?M(x):M("cli"===process.env.CLAUDE_PROVIDER?"claude-cli":"claude-sdk");a=this.buildWiringContext(),g=[],m=()=>{for(let{event:e,fn:t}of g)F.removeListener(e,t)},(h=(e,t)=>{g.push({event:e,fn:t}),F.on(e,t)})("message",async e=>{e.attemptId===f&&(e.sessionId&&(a.setSessionId(f,e.sessionId),await D.sessionManager.saveSession(f,e.sessionId)),e.checkpointUuid&&_.checkpointManager.captureCheckpointUuid(f,e.checkpointUuid),e.rawMessage&&function(e,t,s){if("assistant"===s.type&&s.message?.content)for(let n of s.message.content){if("tool_use"===n.type&&("Task"===n.name||"Agent"===n.name)&&n.id){let e=n.input;J.workflowTracker.trackSubagentStart(t,n.id,e?.subagent_type||e?.model||"agent",s.parent_tool_use_id||null,{teamName:e?.team_name,name:e?.name,prompt:e?.prompt||e?.description})}if("tool_use"===n.type&&"TeamCreate"===n.name&&n.id){let e=n.input;e?.team_name&&J.workflowTracker.trackTeamCreate(t,e.team_name)}if("tool_use"===n.type&&"SendMessage"===n.name&&n.id){let e=n.input;if(e){let s,n=J.workflowTracker.getWorkflow(t);if(n){let e=n.activeNodes.map(e=>n.nodes.get(e)).filter(Boolean).sort((e,t)=>(t.startedAt||0)-(e.startedAt||0));s=e[0]?.name||e[0]?.type}let i="string"==typeof e.message?e.message:e.content||"";J.workflowTracker.trackMessage(t,{...e,content:i,fromAgent:s,isBroadcast:"*"===e.to})}}if("tool_use"===n.type&&"TaskCreate"===n.name&&n.id){let e=n.input;e&&J.workflowTracker.trackTaskCreate(t,n.id,e)}if("tool_use"===n.type&&"TaskUpdate"===n.name&&n.id){let e=n.input;e&&J.workflowTracker.trackTaskUpdate(t,e)}if("tool_use"===n.type&&"Bash"===n.name&&n.id){let s=n.input,i=n.id;s?.command&&(e.pendingBashCommands.set(i,{command:s.command,attemptId:t}),setTimeout(()=>e.pendingBashCommands.delete(i),3e5))}}if("user"===s.type&&s.message?.content){for(let n of s.message.content)if("tool_result"===n.type&&n.tool_use_id){let s="";"string"==typeof n.content?s=n.content:Array.isArray(n.content)&&(s=n.content.filter(e=>e&&"object"==typeof e&&"text"in e).map(e=>e.text||"").join(""));{let e=J.workflowTracker.getWorkflow(t);if(e&&e.tasks.some(e=>e.id===n.tool_use_id)&&s)try{let e=JSON.parse(s);e.taskId&&J.workflowTracker.registerTaskId(t,n.tool_use_id,String(e.taskId))}catch{let e=s.match(/Task\s*#(\d+)/i)||s.match(/taskId["\s:]+(\d+)/);e&&J.workflowTracker.registerTaskId(t,n.tool_use_id,e[1])}}let i=s,o=s.indexOf("agentId:"),r=s.indexOf("<usage>");if(o>0||r>0){let e=Math.min(o>0?o:1/0,r>0?r:1/0);i=s.slice(0,e).trim()}let a=i.indexOf("|");a>0&&i.includes("Spawned successfully")?i=i.slice(a+1).trim():i.startsWith("Spawned successfully")&&(i=""),J.workflowTracker.trackSubagentEnd(t,n.tool_use_id,!n.is_error,n.is_error?s:void 0,i||s);let l="";"string"==typeof n.content?l=n.content:Array.isArray(n.content)&&(l=n.content.filter(e=>e&&"object"==typeof e&&"text"in e).map(e=>e.text||"").join(""));let u=l.match(/BGPID:(\d+)/),c=l.match(/BGPID:\s*$/m)||"BGPID:"===l.trim();if(u&&n.tool_use_id){let s=parseInt(u[1],10),i=e.pendingBashCommands.get(n.tool_use_id),o=i?.command||`Background process (PID: ${s})`,r=o.match(/>\s*([^\s]+\.log)/);e.emit("trackedProcess",{attemptId:t,pid:s,command:o,logFile:r?.[1]}),e.pendingBashCommands.delete(n.tool_use_id)}else if(c&&n.tool_use_id){let s=e.pendingBashCommands.get(n.tool_use_id);if(s?.command&&function(e){return[/npm\s+run\s+(dev|start|serve)/i,/yarn\s+(dev|start|serve)/i,/pnpm\s+(dev|start|serve)/i,/npx\s+(directus|strapi|next|vite|nuxt)/i,/nohup\s+/i].some(t=>t.test(e))}(s.command)){let i=s.command.match(/nohup\s+(.+?)\s*>\s*\/tmp\//);i&&e.emit("backgroundShell",{attemptId:t,shell:{toolUseId:n.tool_use_id,command:i[1].trim(),description:"Auto-spawned from empty BGPID",originalCommand:s.command}})}e.pendingBashCommands.delete(n.tool_use_id)}}}}(a,f,e.rawMessage),e.resultMessage&&j.trackResult(f,e.resultMessage),e.usageEvent&&j.trackUsageEvent(f,e.usageEvent),e.backgroundShell&&a.emit("backgroundShell",{attemptId:f,shell:e.backgroundShell}),"result"===e.output.type&&I||(I&&(e.output.outputFormat=I),a.emit("json",{attemptId:f,data:e.output})))}),h("question",e=>{e.attemptId===f&&a.emit("question",e)}),h("questionResolved",e=>{e.attemptId===f&&a.emit("questionResolved",e)}),h("complete",async t=>{if(t.attemptId===f){if(I&&function(t,s,i){try{let o=e.r(522734),r=process.env.DATA_DIR||process.cwd(),a=(0,n.resolve)(r,"tmp",`${s}.${i}`);if(o.existsSync(a)){let e=o.readFileSync(a,"utf-8");t.emit("json",{attemptId:s,data:{type:"result",subtype:"success",is_error:!1,content:e,outputFormat:i}})}else t.emit("stderr",{attemptId:s,content:`Error: Expected output file not found: ${a}`})}catch(e){R.error({err:e},"Failed to read output file")}}(a,f,I),k)try{let e=await q(k);e&&Y.set(f,e)}catch{}a.deleteAgent(f),a.emit("exit",{attemptId:f,code:0}),m()}}),h("error",e=>{e.attemptId===f&&(a.emit("stderr",{attemptId:f,content:`${e.errorName}: ${e.error}`}),e.isPromptTooLong&&a.emit("promptTooLong",{attemptId:f}),a.deleteAgent(f),a.emit("exit",{attemptId:f,code:1}),m())}),h("stderr",e=>{e.attemptId===f&&a.emit("stderr",e)});try{let e=await F.start({attemptId:f,projectPath:k,prompt:A,model:Q,sessionOptions:y,maxTurns:C,systemPromptAppend:`${$}
130
- ${B}`,outputFormat:I,outputSchema:T}),t={attemptId:f,session:e,provider:F,startedAt:Date.now(),outputFormat:I};this.agents.set(f,t)}catch(t){let e=t instanceof Error?t.message:"Unknown error";V.error({attemptId:f,err:t},"Failed to start provider"),this.emit("stderr",{attemptId:f,content:e}),this.emit("exit",{attemptId:f,code:1})}}answerQuestion(e,t,s,n){let i=this.agents.get(e);return!!i&&i.provider.answerQuestion(e,t,s,n)}cancelQuestion(e){let t=this.agents.get(e);return!!t&&t.provider.cancelQuestion(e)}hasPendingQuestion(e){let t=this.agents.get(e);return!!t&&t.provider.hasPendingQuestion(e)}getPendingQuestionData(e){let t=this.agents.get(e);return t?t.provider.getPendingQuestionData(e):null}getAllPendingQuestions(){let e=[];for(let[t,s]of this.agents){let n=s.provider.getPendingQuestionData(t);n&&e.push({attemptId:t,...n})}return e}setPersistentQuestion(e,t){this.persistentQuestionStore.set(e,t)}getPersistentQuestion(e){return this.persistentQuestionStore.get(e)}clearPersistentQuestion(e){this.persistentQuestionStore.clear(e)}async sendInput(e,t){let s=this.agents.get(e);return!s||!s.session.sessionId,!1}async compact(e){let{attemptId:t,projectPath:s,conversationSummary:n,model:i,provider:o}=e,r=n?`You are continuing a previous conversation that reached the context limit. Here is a summary of the previous context:
129
+ ========================`));let Q=b?.trim()||function(){for(let e of[process.env.ANTHROPIC_MODEL,process.env.ANTHROPIC_DEFAULT_OPUS_MODEL,process.env.ANTHROPIC_DEFAULT_SONNET_MODEL,process.env.ANTHROPIC_DEFAULT_HAIKU_MODEL]){let t=e?.trim();if(t)return t}return"claude-opus-4-6"}(),N=(0,o.modelIdToDisplayName)(Q),$=N!==Q?`You are powered by the model named ${N}. The exact model ID is ${Q}.`:`You are powered by the model ${Q}.`,B=`Your current working directory is ${k}. All file operations should use paths relative to or within this directory.`,F=x?M(x):M("cli"===process.env.CLAUDE_PROVIDER?"claude-cli":"claude-sdk");a=this.buildWiringContext(),g=[],m=()=>{for(let{event:e,fn:t}of g)F.removeListener(e,t)},(h=(e,t)=>{g.push({event:e,fn:t}),F.on(e,t)})("message",async e=>{e.attemptId===f&&(e.sessionId&&(a.setSessionId(f,e.sessionId),await D.sessionManager.saveSession(f,e.sessionId)),e.checkpointUuid&&_.checkpointManager.captureCheckpointUuid(f,e.checkpointUuid),e.rawMessage&&function(e,t,s){if("assistant"===s.type&&s.message?.content)for(let n of s.message.content){if("tool_use"===n.type&&("Task"===n.name||"Agent"===n.name)&&n.id){let e=n.input;J.workflowTracker.trackSubagentStart(t,n.id,e?.subagent_type||e?.model||"agent",s.parent_tool_use_id||null,{teamName:e?.team_name,name:e?.name,prompt:e?.prompt||e?.description})}if("tool_use"===n.type&&"TeamCreate"===n.name&&n.id){let e=n.input;e?.team_name&&J.workflowTracker.trackTeamCreate(t,e.team_name)}if("tool_use"===n.type&&"SendMessage"===n.name&&n.id){let e=n.input;if(e){let s,n=J.workflowTracker.getWorkflow(t);if(n){let e=n.activeNodes.map(e=>n.nodes.get(e)).filter(Boolean).sort((e,t)=>(t.startedAt||0)-(e.startedAt||0));s=e[0]?.name||e[0]?.type}let i="string"==typeof e.message?e.message:e.content||"";J.workflowTracker.trackMessage(t,{...e,content:i,fromAgent:s,isBroadcast:"*"===e.to})}}if("tool_use"===n.type&&"TaskCreate"===n.name&&n.id){let e=n.input;e&&J.workflowTracker.trackTaskCreate(t,n.id,e)}if("tool_use"===n.type&&"TaskUpdate"===n.name&&n.id){let e=n.input;e&&J.workflowTracker.trackTaskUpdate(t,e)}if("tool_use"===n.type&&"Bash"===n.name&&n.id){let s=n.input,i=n.id;s?.command&&(e.pendingBashCommands.set(i,{command:s.command,attemptId:t}),setTimeout(()=>e.pendingBashCommands.delete(i),3e5))}}if("user"===s.type&&s.message?.content){for(let n of s.message.content)if("tool_result"===n.type&&n.tool_use_id){let s="";"string"==typeof n.content?s=n.content:Array.isArray(n.content)&&(s=n.content.filter(e=>e&&"object"==typeof e&&"text"in e).map(e=>e.text||"").join(""));{let e=J.workflowTracker.getWorkflow(t);if(e&&e.tasks.some(e=>e.id===n.tool_use_id)&&s)try{let e=JSON.parse(s);e.taskId&&J.workflowTracker.registerTaskId(t,n.tool_use_id,String(e.taskId))}catch{let e=s.match(/Task\s*#(\d+)/i)||s.match(/taskId["\s:]+(\d+)/);e&&J.workflowTracker.registerTaskId(t,n.tool_use_id,e[1])}}let i=s,r=s.indexOf("agentId:"),o=s.indexOf("<usage>");if(r>0||o>0){let e=Math.min(r>0?r:1/0,o>0?o:1/0);i=s.slice(0,e).trim()}let a=i.indexOf("|");a>0&&i.includes("Spawned successfully")?i=i.slice(a+1).trim():i.startsWith("Spawned successfully")&&(i=""),J.workflowTracker.trackSubagentEnd(t,n.tool_use_id,!n.is_error,n.is_error?s:void 0,i||s);let l="";"string"==typeof n.content?l=n.content:Array.isArray(n.content)&&(l=n.content.filter(e=>e&&"object"==typeof e&&"text"in e).map(e=>e.text||"").join(""));let u=l.match(/BGPID:(\d+)/),c=l.match(/BGPID:\s*$/m)||"BGPID:"===l.trim();if(u&&n.tool_use_id){let s=parseInt(u[1],10),i=e.pendingBashCommands.get(n.tool_use_id),r=i?.command||`Background process (PID: ${s})`,o=r.match(/>\s*([^\s]+\.log)/);e.emit("trackedProcess",{attemptId:t,pid:s,command:r,logFile:o?.[1]}),e.pendingBashCommands.delete(n.tool_use_id)}else if(c&&n.tool_use_id){let s=e.pendingBashCommands.get(n.tool_use_id);if(s?.command&&function(e){return[/npm\s+run\s+(dev|start|serve)/i,/yarn\s+(dev|start|serve)/i,/pnpm\s+(dev|start|serve)/i,/npx\s+(directus|strapi|next|vite|nuxt)/i,/nohup\s+/i].some(t=>t.test(e))}(s.command)){let i=s.command.match(/nohup\s+(.+?)\s*>\s*\/tmp\//);i&&e.emit("backgroundShell",{attemptId:t,shell:{toolUseId:n.tool_use_id,command:i[1].trim(),description:"Auto-spawned from empty BGPID",originalCommand:s.command}})}e.pendingBashCommands.delete(n.tool_use_id)}}}}(a,f,e.rawMessage),e.resultMessage&&j.trackResult(f,e.resultMessage),e.usageEvent&&j.trackUsageEvent(f,e.usageEvent),e.backgroundShell&&a.emit("backgroundShell",{attemptId:f,shell:e.backgroundShell}),"result"===e.output.type&&I||(I&&(e.output.outputFormat=I),a.emit("json",{attemptId:f,data:e.output})))}),h("question",e=>{e.attemptId===f&&a.emit("question",e)}),h("questionResolved",e=>{e.attemptId===f&&a.emit("questionResolved",e)}),h("complete",async t=>{if(t.attemptId===f){if(I&&function(t,s,i){try{let r=e.r(522734),o=process.env.DATA_DIR||process.cwd(),a=(0,n.resolve)(o,"tmp",`${s}.${i}`);if(r.existsSync(a)){let e=r.readFileSync(a,"utf-8");t.emit("json",{attemptId:s,data:{type:"result",subtype:"success",is_error:!1,content:e,outputFormat:i}})}else t.emit("stderr",{attemptId:s,content:`Error: Expected output file not found: ${a}`})}catch(e){R.error({err:e},"Failed to read output file")}}(a,f,I),k)try{let e=await q(k);e&&Y.set(f,e)}catch{}a.deleteAgent(f),a.emit("exit",{attemptId:f,code:0}),m()}}),h("error",e=>{e.attemptId===f&&(a.emit("stderr",{attemptId:f,content:`${e.errorName}: ${e.error}`}),e.isPromptTooLong&&a.emit("promptTooLong",{attemptId:f}),a.deleteAgent(f),a.emit("exit",{attemptId:f,code:1}),m())}),h("stderr",e=>{e.attemptId===f&&a.emit("stderr",e)});try{let e=await F.start({attemptId:f,projectPath:k,prompt:S,model:Q,sessionOptions:y,maxTurns:C,systemPromptAppend:`${$}
130
+ ${B}`,outputFormat:I,outputSchema:T}),t={attemptId:f,session:e,provider:F,startedAt:Date.now(),outputFormat:I};this.agents.set(f,t)}catch(t){let e=t instanceof Error?t.message:"Unknown error";V.error({attemptId:f,err:t},"Failed to start provider"),this.emit("stderr",{attemptId:f,content:e}),this.emit("exit",{attemptId:f,code:1})}}answerQuestion(e,t,s,n){let i=this.agents.get(e);return!!i&&i.provider.answerQuestion(e,t,s,n)}cancelQuestion(e){let t=this.agents.get(e);return!!t&&t.provider.cancelQuestion(e)}hasPendingQuestion(e){let t=this.agents.get(e);return!!t&&t.provider.hasPendingQuestion(e)}getPendingQuestionData(e){let t=this.agents.get(e);return t?t.provider.getPendingQuestionData(e):null}getAllPendingQuestions(){let e=[];for(let[t,s]of this.agents){let n=s.provider.getPendingQuestionData(t);n&&e.push({attemptId:t,...n})}return e}setPersistentQuestion(e,t){this.persistentQuestionStore.set(e,t)}getPersistentQuestion(e){return this.persistentQuestionStore.get(e)}clearPersistentQuestion(e){this.persistentQuestionStore.clear(e)}async sendInput(e,t){let s=this.agents.get(e);return!s||!s.session.sessionId,!1}async compact(e){let{attemptId:t,projectPath:s,conversationSummary:n,model:i,provider:r}=e,o=n?`You are continuing a previous conversation that reached the context limit. Here is a summary of the previous context:
131
131
 
132
132
  ${n}
133
133
 
134
- Please acknowledge this context briefly and let the user know you're ready to continue.`:"A previous conversation reached the context limit. Please let the user know you are ready to continue with a fresh context.";await this.start({attemptId:t,projectPath:s,prompt:r,maxTurns:1,model:i,provider:o})}cancel(e){let t=this.agents.get(e);return!!t&&(t.session.cancel(),this.agents.delete(e),!0)}cancelAll(){for(let[,e]of this.agents)e.session.cancel();this.agents.clear()}isRunning(e){return this.agents.has(e)}get runningCount(){return this.agents.size}getRunningAttempts(){return Array.from(this.agents.keys())}getSessionId(e){return this.agents.get(e)?.session.sessionId}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}}let X="__claude_agent_manager__",Z=globalThis[X]??new z;globalThis[X]||(globalThis[X]=Z),e.s(["agentManager",0,Z],707272)}];
134
+ Please acknowledge this context briefly and let the user know you're ready to continue.`:"A previous conversation reached the context limit. Please let the user know you are ready to continue with a fresh context.";await this.start({attemptId:t,projectPath:s,prompt:o,maxTurns:1,model:i,provider:r})}cancel(e){let t=this.agents.get(e);return!!t&&(t.session.cancel(),this.agents.delete(e),!0)}cancelAll(){for(let[,e]of this.agents)e.session.cancel();this.agents.clear()}isRunning(e){return this.agents.has(e)}get runningCount(){return this.agents.size}getRunningAttempts(){return Array.from(this.agents.keys())}getSessionId(e){return this.agents.get(e)?.session.sessionId}on(e,t){return super.on(e,t)}emit(e,...t){return super.emit(e,...t)}}let X="__claude_agent_manager__",Z=globalThis[X]??new z;globalThis[X]||(globalThis[X]=Z),e.s(["agentManager",0,Z],707272)}];
135
135
 
136
136
  //# sourceMappingURL=src_lib_agent-manager_ts_0o7~e5j._.js.map