@zibby/core 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- import{AgentStrategy as ge,getSkill as fe}from"@zibby/agent-workflow";import{query as me}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as he}from"zod-to-json-schema";import{writeFileSync as I,mkdirSync as P,existsSync as V,readFileSync as ee}from"fs";import{homedir as te}from"os";import{join as E}from"path";import y from"chalk";var f={debug:0,info:1,warn:2,error:3,silent:4},v=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return f.debug;if(process.env.ZIBBY_VERBOSE==="true")return f.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in f?f[e]:f.info}_shouldLog(e){return f[e]>=this._level}_formatMessage(e,n,o={}){let s=new Date().toISOString(),u=`${this._getPrefix(e)} ${n}`;return Object.keys(o).length>0&&(u+=y.dim(` ${JSON.stringify(o)}`)),u}_getPrefix(e){return{debug:y.gray("[DEBUG]"),info:y.cyan("[INFO]"),warn:y.yellow("[WARN]"),error:y.red("\u274C [ERROR]")}[e]||""}debug(e,n){this._shouldLog("debug")&&console.log(this._formatMessage("debug",e,n))}info(e,n){this._shouldLog("info")&&console.log(this._formatMessage("info",e,n))}warn(e,n){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",e,n))}error(e,n){this._shouldLog("error")&&console.error(this._formatMessage("error",e,n))}setLevel(e){e in f&&(this._level=f[e])}getLevel(){return Object.keys(f).find(e=>f[e]===this._level)}},c=new v;import{timeline as D,Timeline as Ce,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as we}from"@zibby/agent-workflow";var $={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-2.5-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"};var R={auto:"claude-sonnet-4-6","sonnet-4.6":"claude-sonnet-4-6","sonnet-4-6":"claude-sonnet-4-6","opus-4.6":"claude-opus-4-6","opus-4-6":"claude-opus-4-6","sonnet-4.5":"claude-sonnet-4-5-20250929","sonnet-4-5":"claude-sonnet-4-5-20250929","opus-4.5":"claude-opus-4-20250514","opus-4-5":"claude-opus-4-20250514","claude-sonnet-4-6":"claude-sonnet-4-6","claude-opus-4-6":"claude-opus-4-6","claude-sonnet-4-5-20250929":"claude-sonnet-4-5-20250929","claude-opus-4-20250514":"claude-opus-4-20250514"};var Ne={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};function b(i){let e=`${i}_POOL`,n=process.env[e];if(!n||typeof n!="string")return{picked:null,count:0,dispose:()=>{}};let o=n.split(/[,\n]+/).map(u=>u.trim()).filter(Boolean);if(o.length===0)return{picked:null,count:0,dispose:()=>{}};let s=o[Math.floor(Math.random()*o.length)],r=process.env[i];return process.env[i]=s,c.debug(`[auth-pool] ${i}: picked 1 of ${o.length} from pool (***${s.slice(-4)})`),{picked:s,count:o.length,dispose(){r===void 0?delete process.env[i]:process.env[i]=r}}}import{execSync as De}from"node:child_process";import{existsSync as se,mkdirSync as Re}from"node:fs";import{join as z,resolve as ie}from"node:path";var ce="/workspace/repos",ae=".zibby/repos";function le(){return process.env.REPOS?ce:ie(process.cwd(),ae)}function ue(i){return String(i).replace(/\//g,"-")}function pe(){let i=process.env.REPOS;if(!i)return[];try{let e=JSON.parse(i);return Array.isArray(e)?e:[]}catch{return[]}}function de(i={}){let e=i.baseDir||le();return pe().map((o,s)=>{let r=z(e,ue(o.name));return{name:o.name,url:o.cloneUrl||o.url||null,branch:o.branch||null,provider:o.provider||"github",localPath:r,isCheckedOut:se(z(r,".git")),primary:s===0}})}function X(i={}){let e=de(i);if(e.length===0)return null;let n=["## Available repositories",""];for(let o of e){let s=o.isCheckedOut?"already checked out at":"will be checked out to",r=o.primary?" (primary)":"";n.push(`- \`${o.name}\`${r} \u2014 ${s} \`${o.localPath}\``)}return n.push(""),n.push(`To materialize a repo: call the \`git_checkout\` skill with the repo name (e.g. \`git_checkout({ url: "${e[0].name}" })\`). In code, \`import { ensureRepo } from "@zibby/core"\` and \`await ensureRepo()\` returns the local path (clones on first call, no-op after).`),n.join(`
2
- `)}var Q=class extends ge{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let n=!!process.env.ANTHROPIC_API_KEY||!!process.env.ANTHROPIC_API_KEY_POOL,o=!!process.env.CLAUDE_CODE_OAUTH_TOKEN||!!process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL,s=!!process.env.ANTHROPIC_AUTH_TOKEN||!!process.env.ANTHROPIC_AUTH_TOKEN_POOL,r=n||o||s;return r||c.debug("ClaudeAgentStrategy: no credentials. Set one of ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_AUTH_TOKEN (or a *_POOL variant for multi-token rotation)."),r}async invoke(e,n={}){let{model:o,workspace:s=process.cwd(),schema:r=null,images:u=[],skills:p=null,sessionPath:m=null,nodeName:w=null,timeout:x,config:U={},signal:A=null}=n,g=o;(!g||g==="auto")&&(c.debug(`Model is '${g||"undefined"}', using default: ${$.CLAUDE}`),g=$.CLAUDE);let S=R[g]||g;R[g]&&g!==S&&c.debug(`Mapped model: ${g} \u2192 ${S}`);let oe=[b("ANTHROPIC_API_KEY"),b("CLAUDE_CODE_OAUTH_TOKEN"),b("ANTHROPIC_AUTH_TOKEN")];try{c.debug(`Invoking Claude Agent SDK with model: ${S}, skills: ${JSON.stringify(p)}`);let _=process.env.CLAUDE_CODE_OAUTH_TOKEN,M=process.env.ANTHROPIC_API_KEY,K=process.env.ANTHROPIC_AUTH_TOKEN;process.env.CLAUDE_CODE_CREDENTIALS_JSON?Ee(process.env.CLAUDE_CODE_CREDENTIALS_JSON):_&&Oe(_,process.env.__ZIBBY_CLAUDE_PLAN);let k=process.env.__ZIBBY_CLAUDE_PLAN,J=k?k.charAt(0).toUpperCase()+k.slice(1):null,T;_?T=J?`Claude ${J} plan \xB7 ***${_.slice(-4)}`:`Subscription \xB7 ***${_.slice(-4)}`:M?T=`API key \xB7 ***${M.slice(-4)}`:K?T=`Bearer \xB7 ***${K.slice(-4)}`:T="NONE \u2014 request will fail";let h=(await import("chalk")).default,H=X(),B=H?`${H}
1
+ import{AgentStrategy as he,getSkill as _e}from"@zibby/agent-workflow";import{query as Oe}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as Ee}from"zod-to-json-schema";import{writeFileSync as R,mkdirSync as P,existsSync as te,readFileSync as oe}from"fs";import{homedir as re}from"os";import{join as E}from"path";import y from"chalk";var f={debug:0,info:1,warn:2,error:3,silent:4},v=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return f.debug;if(process.env.ZIBBY_VERBOSE==="true")return f.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in f?f[e]:f.info}_shouldLog(e){return f[e]>=this._level}_formatMessage(e,n,o={}){let s=new Date().toISOString(),u=`${this._getPrefix(e)} ${n}`;return Object.keys(o).length>0&&(u+=y.dim(` ${JSON.stringify(o)}`)),u}_getPrefix(e){return{debug:y.gray("[DEBUG]"),info:y.cyan("[INFO]"),warn:y.yellow("[WARN]"),error:y.red("\u274C [ERROR]")}[e]||""}debug(e,n){this._shouldLog("debug")&&console.log(this._formatMessage("debug",e,n))}info(e,n){this._shouldLog("info")&&console.log(this._formatMessage("info",e,n))}warn(e,n){this._shouldLog("warn")&&console.warn(this._formatMessage("warn",e,n))}error(e,n){this._shouldLog("error")&&console.error(this._formatMessage("error",e,n))}setLevel(e){e in f&&(this._level=f[e])}getLevel(){return Object.keys(f).find(e=>f[e]===this._level)}},c=new v;import{timeline as D,Timeline as Le,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as ke}from"@zibby/agent-workflow";var $={ASSISTANT:"gpt-5.4-nano-2026-03-17",CLAUDE:"claude-sonnet-4-6",CURSOR:"auto",CODEX:"o4-mini",GEMINI:"gemini-2.5-pro",OPENAI_POSTPROCESSING:"gpt-4o-mini"};var I={auto:"claude-sonnet-4-6","sonnet-4.6":"claude-sonnet-4-6","sonnet-4-6":"claude-sonnet-4-6","opus-4.6":"claude-opus-4-6","opus-4-6":"claude-opus-4-6","sonnet-4.5":"claude-sonnet-4-5-20250929","sonnet-4-5":"claude-sonnet-4-5-20250929","opus-4.5":"claude-opus-4-20250514","opus-4-5":"claude-opus-4-20250514","claude-sonnet-4-6":"claude-sonnet-4-6","claude-opus-4-6":"claude-opus-4-6","claude-sonnet-4-5-20250929":"claude-sonnet-4-5-20250929","claude-opus-4-20250514":"claude-opus-4-20250514"};var be={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};function k(i){let e=`${i}_POOL`,n=process.env[e];if(!n||typeof n!="string")return{picked:null,count:0,dispose:()=>{}};let o=n.split(/[,\n]+/).map(u=>u.trim()).filter(Boolean);if(o.length===0)return{picked:null,count:0,dispose:()=>{}};let s=o[Math.floor(Math.random()*o.length)],r=process.env[i];return process.env[i]=s,c.debug(`[auth-pool] ${i}: picked 1 of ${o.length} from pool (***${s.slice(-4)})`),{picked:s,count:o.length,dispose(){r===void 0?delete process.env[i]:process.env[i]=r}}}import{execSync as Re}from"node:child_process";import{existsSync as ae,mkdirSync as xe}from"node:fs";import{join as Q,resolve as le}from"node:path";var ue="/workspace/repos",pe=".zibby/repos";function de(){return process.env.REPOS?ue:le(process.cwd(),pe)}function ge(i){return String(i).replace(/\//g,"-")}function fe(){let i=process.env.REPOS;if(!i)return[];try{let e=JSON.parse(i);return Array.isArray(e)?e:[]}catch{return[]}}function me(i={}){let e=i.baseDir||de();return fe().map((o,s)=>{let r=Q(e,ge(o.name));return{name:o.name,url:o.cloneUrl||o.url||null,branch:o.branch||null,provider:o.provider||"github",localPath:r,isCheckedOut:ae(Q(r,".git")),primary:s===0}})}function V(i={}){let e=me(i);if(e.length===0)return null;let n=["## Available repositories",""];for(let o of e){let s=o.isCheckedOut?"already checked out at":"will be checked out to",r=o.primary?" (primary)":"";n.push(`- \`${o.name}\`${r} \u2014 ${s} \`${o.localPath}\``)}return n.push(""),n.push(`To materialize a repo: call the \`git_checkout\` skill with the repo name (e.g. \`git_checkout({ url: "${e[0].name}" })\`). In code, \`import { ensureRepo } from "@zibby/core"\` and \`await ensureRepo()\` returns the local path (clones on first call, no-op after).`),n.join(`
2
+ `)}var ee=class extends he{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let n=!!process.env.ANTHROPIC_API_KEY||!!process.env.ANTHROPIC_API_KEY_POOL,o=!!process.env.CLAUDE_CODE_OAUTH_TOKEN||!!process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL,s=!!process.env.ANTHROPIC_AUTH_TOKEN||!!process.env.ANTHROPIC_AUTH_TOKEN_POOL,r=n||o||s;return r||c.debug("ClaudeAgentStrategy: no credentials. Set one of ANTHROPIC_API_KEY / CLAUDE_CODE_OAUTH_TOKEN / ANTHROPIC_AUTH_TOKEN (or a *_POOL variant for multi-token rotation)."),r}async invoke(e,n={}){let{model:o,workspace:s=process.cwd(),schema:r=null,images:u=[],skills:p=null,sessionPath:m=null,nodeName:w=null,timeout:x,config:U={},signal:A=null,sessionId:M,resume:K,forkSession:ne}=n,g=o;(!g||g==="auto")&&(c.debug(`Model is '${g||"undefined"}', using default: ${$.CLAUDE}`),g=$.CLAUDE);let S=I[g]||g;I[g]&&g!==S&&c.debug(`Mapped model: ${g} \u2192 ${S}`);let se=[k("ANTHROPIC_API_KEY"),k("CLAUDE_CODE_OAUTH_TOKEN"),k("ANTHROPIC_AUTH_TOKEN")];try{c.debug(`Invoking Claude Agent SDK with model: ${S}, skills: ${JSON.stringify(p)}`);let _=process.env.CLAUDE_CODE_OAUTH_TOKEN,J=process.env.ANTHROPIC_API_KEY,H=process.env.ANTHROPIC_AUTH_TOKEN;process.env.CLAUDE_CODE_CREDENTIALS_JSON?Te(process.env.CLAUDE_CODE_CREDENTIALS_JSON):_&&Se(_,process.env.__ZIBBY_CLAUDE_PLAN);let b=process.env.__ZIBBY_CLAUDE_PLAN,B=b?b.charAt(0).toUpperCase()+b.slice(1):null,T;_?T=B?`Claude ${B} plan \xB7 ***${_.slice(-4)}`:`Subscription \xB7 ***${_.slice(-4)}`:J?T=`API key \xB7 ***${J.slice(-4)}`:H?T=`Bearer \xB7 ***${H.slice(-4)}`:T="NONE \u2014 request will fail";let h=(await import("chalk")).default,F=V(),G=F?`${F}
3
3
 
4
- ${e}`:e;console.log(""),console.log(` ${h.cyan("\u25C6")} ${h.bold(S)}`),console.log(` ${h.dim("Auth: ")}${T}`),console.log(` ${h.dim("Workdir: ")}${s}`),console.log(""),console.log(h.bold("Prompt sent to LLM:")),console.log(h.dim("\u2500".repeat(60))),console.log(h.dim(B)),console.log(h.dim("\u2500".repeat(60)));let{allowedTools:F,mcpServers:G}=this._resolveSkills(p,{sessionPath:m,workspace:s,nodeName:w});try{let d={cwd:s,allowedTools:F,settings:{permissions:{allow:["Bash(*)","Read(*)","Write(*)","Edit(*)","MultiEdit(*)","NotebookEdit(*)","Grep(*)","Glob(*)","WebFetch(*)","WebSearch(*)","Task(*)","TodoWrite(*)","Skill(*)"]}},model:S,...Object.keys(G).length>0&&{mcpServers:G}};if(r){let O=typeof r.parse=="function"?he(r,{target:"openApi3"}):r;d.outputFormat={type:"json_schema",schema:O},c.debug("Structured output enforced via SDK outputFormat")}c.debug(`Agent SDK options: ${JSON.stringify({cwd:d.cwd,toolCount:F.length,permissionMode:d.permissionMode,model:d.model,hasOutputFormat:!!d.outputFormat})}`);let N="",j=0,W=[];c.debug("Starting Claude Agent SDK query stream");let Y;try{Y=me({prompt:B,options:d})}catch(t){throw c.error(`Failed to initialize Claude Agent SDK: ${t.message}`),t}let Z=null,L=0,re=3;if(A?.aborted){let t=new Error("Aborted via signal");throw t.name="AbortError",t}try{for await(let t of Y){if(A?.aborted){let l=new Error("Aborted via signal");throw l.name="AbortError",l}if(W.push(t),t.type==="error"||t.error){let l=t.error?.message||t.error||t.message||"Unknown API error";try{c.error("SDK error event raw payload",{fullMessage:JSON.stringify(t,null,2)})}catch{}throw new Error(typeof l=="string"?l:JSON.stringify(l))}let O=JSON.stringify(t.message?.content||t.text||"").slice(0,200);if(O===Z){if(L++,L>=re){let l=(t.message?.content?.[0]?.text||t.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${L}x repeated): ${l}`)}}else Z=O,L=1;if(t.type==="assistant"||t.constructor?.name==="AssistantMessage"){let l=t.message?.content||t.content||[];for(let a of l)if(a.type==="thinking"&&a.thinking)console.log(`${a.thinking.substring(0,200)}${a.thinking.length>200?"...":""}`);else if(a.type==="text"&&a.text)N+=a.text,a.text.length<500?console.log(`${a.text}`):console.log(`${a.text.substring(0,200)}... (${a.text.length} chars)`);else if(a.type==="tool_use"){j++,a.name.includes("memory")?D.stepMemory(`Tool: ${a.name}`):D.stepTool(`Tool: ${a.name}`);let ne=JSON.stringify(a.input).substring(0,100);console.log(` Input: ${ne}${JSON.stringify(a.input).length>100?"...":""}`)}}else if(!(t.type==="user"&&t.tool_use_result)){if(t.type==="result"||t.constructor?.name==="ResultMessage"){let l=t.result||t.text||t.content||N;try{_e({message:t,sessionPath:m,nodeName:w,model:g,toolCallCount:j})}catch(a){c.debug(`usage.json write failed: ${a.message}`)}if(r){if(t.structured_output){c.debug("Using SDK native structured_output");let q=typeof r.parse=="function"?r.parse(t.structured_output):t.structured_output;return{raw:l,structured:q}}if(l){let a=this._extractJson(l,r);if(a)return{raw:l,structured:a}}c.warn(`Could not extract structured output \u2014 returning raw text (${(l||"").length} chars)`)}return l||""}}}if(c.warn(`Agent SDK ended without result. Collected ${W.length} messages`),N.length>0)return c.debug("Returning accumulated text from messages"),N;throw new Error("Claude Agent SDK query ended without result")}catch(t){let O={message:t?.message,name:t?.name,code:t?.code,cause:t?.cause?.message||t?.cause,stack:t?.stack?.split(`
4
+ ${e}`:e;console.log(""),console.log(` ${h.cyan("\u25C6")} ${h.bold(S)}`),console.log(` ${h.dim("Auth: ")}${T}`),console.log(` ${h.dim("Workdir: ")}${s}`),console.log(""),console.log(h.bold("Prompt sent to LLM:")),console.log(h.dim("\u2500".repeat(60))),console.log(h.dim(G)),console.log(h.dim("\u2500".repeat(60)));let{allowedTools:j,mcpServers:W}=this._resolveSkills(p,{sessionPath:m,workspace:s,nodeName:w});try{let d={cwd:s,allowedTools:j,settings:{permissions:{allow:["Bash(*)","Read(*)","Write(*)","Edit(*)","MultiEdit(*)","NotebookEdit(*)","Grep(*)","Glob(*)","WebFetch(*)","WebSearch(*)","Task(*)","TodoWrite(*)","Skill(*)"]}},model:S,...Object.keys(W).length>0&&{mcpServers:W},...M&&{sessionId:M},...K&&{resume:K},...ne&&{forkSession:!0}};if(r){let O=typeof r.parse=="function"?Ee(r,{target:"openApi3"}):r;d.outputFormat={type:"json_schema",schema:O},c.debug("Structured output enforced via SDK outputFormat")}c.debug(`Agent SDK options: ${JSON.stringify({cwd:d.cwd,toolCount:j.length,permissionMode:d.permissionMode,model:d.model,hasOutputFormat:!!d.outputFormat})}`);let N="",Y=0,Z=[];c.debug("Starting Claude Agent SDK query stream");let q;try{q=Oe({prompt:G,options:d})}catch(t){throw c.error(`Failed to initialize Claude Agent SDK: ${t.message}`),t}let z=null,L=0,ie=3;if(A?.aborted){let t=new Error("Aborted via signal");throw t.name="AbortError",t}try{for await(let t of q){if(A?.aborted){let l=new Error("Aborted via signal");throw l.name="AbortError",l}if(Z.push(t),t.type==="error"||t.error){let l=t.error?.message||t.error||t.message||"Unknown API error";try{c.error("SDK error event raw payload",{fullMessage:JSON.stringify(t,null,2)})}catch{}throw new Error(typeof l=="string"?l:JSON.stringify(l))}let O=JSON.stringify(t.message?.content||t.text||"").slice(0,200);if(O===z){if(L++,L>=ie){let l=(t.message?.content?.[0]?.text||t.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${L}x repeated): ${l}`)}}else z=O,L=1;if(t.type==="assistant"||t.constructor?.name==="AssistantMessage"){let l=t.message?.content||t.content||[];for(let a of l)if(a.type==="thinking"&&a.thinking)console.log(`${a.thinking.substring(0,200)}${a.thinking.length>200?"...":""}`);else if(a.type==="text"&&a.text)N+=a.text,a.text.length<500?console.log(`${a.text}`):console.log(`${a.text.substring(0,200)}... (${a.text.length} chars)`);else if(a.type==="tool_use"){Y++,a.name.includes("memory")?D.stepMemory(`Tool: ${a.name}`):D.stepTool(`Tool: ${a.name}`);let ce=JSON.stringify(a.input).substring(0,100);console.log(` Input: ${ce}${JSON.stringify(a.input).length>100?"...":""}`)}}else if(!(t.type==="user"&&t.tool_use_result)){if(t.type==="result"||t.constructor?.name==="ResultMessage"){let l=t.result||t.text||t.content||N;try{Ae({message:t,sessionPath:m,nodeName:w,model:g,toolCallCount:Y})}catch(a){c.debug(`usage.json write failed: ${a.message}`)}if(r){if(t.structured_output){c.debug("Using SDK native structured_output");let X=typeof r.parse=="function"?r.parse(t.structured_output):t.structured_output;return{raw:l,structured:X}}if(l){let a=this._extractJson(l,r);if(a)return{raw:l,structured:a}}c.warn(`Could not extract structured output \u2014 returning raw text (${(l||"").length} chars)`)}return l||""}}}if(c.warn(`Agent SDK ended without result. Collected ${Z.length} messages`),N.length>0)return c.debug("Returning accumulated text from messages"),N;throw new Error("Claude Agent SDK query ended without result")}catch(t){let O={message:t?.message,name:t?.name,code:t?.code,cause:t?.cause?.message||t?.cause,stack:t?.stack?.split(`
5
5
  `).slice(0,5).join(`
6
- `),stringified:(()=>{try{return JSON.stringify(t,Object.getOwnPropertyNames(Object(t)))}catch{return String(t)}})()};throw c.error(`Error during query stream: ${t?.message||t}`,O),t}}catch(d){throw c.error("Claude Agent SDK call failed",{message:d?.message,name:d?.name,code:d?.code,cause:d?.cause?.message||d?.cause}),d}}finally{for(let _ of oe)_.dispose()}}_resolveSkills(e,n){let o=["Read","Write","Edit","Bash","Grep","Glob"];if(e===null)return c.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return c.debug("Default IDE skills for code generation"),{allowedTools:[...o],mcpServers:{}};let s=[...o],r={};for(let u of e){let p=fe(u);if(!p){c.warn(`Unknown skill "${u}" \u2014 skipping`);continue}if(p.allowedTools&&s.push(...p.allowedTools),typeof p.resolve=="function"){let m=p.resolve(n);m&&(r[p.serverName]=m,c.debug(`MCP: ${p.serverName} \u2192 ${m.command} ${m.args[0]}`))}}return{allowedTools:s,mcpServers:r}}_extractJson(e,n){let o=[()=>{if(e.includes("===JSON_START===")){let s=e.indexOf("===JSON_START===")+16,r=e.indexOf("===JSON_END===");return e.substring(s,r).trim()}},()=>e.match(/```json\s*\n([\s\S]*?)\n```/)?.[1]?.trim(),()=>{if(!e.startsWith("{"))return e.match(/```\s*\n([\s\S]*?)\n```/)?.[1]?.trim()},()=>e.trim(),()=>{let s=e.indexOf("{"),r=e.lastIndexOf("}");if(s!==-1&&r>s)return e.substring(s,r+1)}];for(let s of o)try{let r=s();if(!r)continue;let u=JSON.parse(r);if(typeof u!="object"||u===null)continue;return typeof n.parse=="function"?n.parse(u):u}catch{}return null}};function _e({message:i,sessionPath:e,nodeName:n,model:o,toolCallCount:s}){if(!e||!n)return;let r=i?.usage||i?.message?.usage||{},u=C(r.input_tokens,r.inputTokens),p=C(r.output_tokens,r.outputTokens),m=C(r.cache_read_input_tokens,r.cacheReadInputTokens),w=C(r.cache_creation_input_tokens,r.cacheCreationInputTokens),x=C(i?.duration_ms,i?.durationMs),U={model:o||null,input_tokens:u,output_tokens:p,cache_read_tokens:m,cache_creation_tokens:w,tool_call_count:typeof s=="number"?s:null,duration_ms:x,captured_at:new Date().toISOString()},A=E(e,n);try{P(A,{recursive:!0})}catch{}I(E(A,"usage.json"),JSON.stringify(U,null,2),"utf-8")}function C(...i){for(let e of i){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()!==""&&!isNaN(Number(e)))return Number(e)}return null}function Oe(i,e){let n=E(te(),".claude"),o=E(n,".credentials.json"),s={claudeAiOauth:{accessToken:i,...e?{subscriptionType:String(e).toLowerCase()}:{}}};try{if(V(o)&&JSON.parse(ee(o,"utf-8"))?.claudeAiOauth?.accessToken===i)return;P(n,{recursive:!0}),I(o,JSON.stringify(s,null,2),"utf-8"),c.debug(`Wrote Claude Code OAuth credentials to ${o}`)}catch(r){c.warn(`Could not write ${o}: ${r.message} \u2014 Claude SDK may fail to authenticate.`)}}function Ee(i){let e=E(te(),".claude"),n=E(e,".credentials.json"),o;try{o=JSON.parse(i)}catch(s){c.warn(`CLAUDE_CODE_CREDENTIALS_JSON not valid JSON: ${s.message}`);return}if(!o?.claudeAiOauth?.accessToken){c.warn("CLAUDE_CODE_CREDENTIALS_JSON missing claudeAiOauth.accessToken \u2014 skipping write.");return}try{if(V(n)){let s=JSON.parse(ee(n,"utf-8"));if(s?.claudeAiOauth?.accessToken===o.claudeAiOauth.accessToken&&s?.claudeAiOauth?.expiresAt===o.claudeAiOauth.expiresAt)return}P(e,{recursive:!0}),I(n,JSON.stringify(o,null,2),"utf-8"),c.debug(`Wrote full Claude Code credentials blob to ${n}`)}catch(s){c.warn(`Could not write ${n}: ${s.message} \u2014 Claude SDK may fail to authenticate.`)}}export{Q as ClaudeAgentStrategy};
6
+ `),stringified:(()=>{try{return JSON.stringify(t,Object.getOwnPropertyNames(Object(t)))}catch{return String(t)}})()};throw c.error(`Error during query stream: ${t?.message||t}`,O),t}}catch(d){throw c.error("Claude Agent SDK call failed",{message:d?.message,name:d?.name,code:d?.code,cause:d?.cause?.message||d?.cause}),d}}finally{for(let _ of se)_.dispose()}}_resolveSkills(e,n){let o=["Read","Write","Edit","Bash","Grep","Glob"];if(e===null)return c.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return c.debug("Default IDE skills for code generation"),{allowedTools:[...o],mcpServers:{}};let s=[...o],r={};for(let u of e){let p=_e(u);if(!p){c.warn(`Unknown skill "${u}" \u2014 skipping`);continue}if(p.allowedTools&&s.push(...p.allowedTools),typeof p.resolve=="function"){let m=p.resolve(n);m&&(r[p.serverName]=m,c.debug(`MCP: ${p.serverName} \u2192 ${m.command} ${m.args[0]}`))}}return{allowedTools:s,mcpServers:r}}_extractJson(e,n){let o=[()=>{if(e.includes("===JSON_START===")){let s=e.indexOf("===JSON_START===")+16,r=e.indexOf("===JSON_END===");return e.substring(s,r).trim()}},()=>e.match(/```json\s*\n([\s\S]*?)\n```/)?.[1]?.trim(),()=>{if(!e.startsWith("{"))return e.match(/```\s*\n([\s\S]*?)\n```/)?.[1]?.trim()},()=>e.trim(),()=>{let s=e.indexOf("{"),r=e.lastIndexOf("}");if(s!==-1&&r>s)return e.substring(s,r+1)}];for(let s of o)try{let r=s();if(!r)continue;let u=JSON.parse(r);if(typeof u!="object"||u===null)continue;return typeof n.parse=="function"?n.parse(u):u}catch{}return null}};function Ae({message:i,sessionPath:e,nodeName:n,model:o,toolCallCount:s}){if(!e||!n)return;let r=i?.usage||i?.message?.usage||{},u=C(r.input_tokens,r.inputTokens),p=C(r.output_tokens,r.outputTokens),m=C(r.cache_read_input_tokens,r.cacheReadInputTokens),w=C(r.cache_creation_input_tokens,r.cacheCreationInputTokens),x=C(i?.duration_ms,i?.durationMs),U={model:o||null,input_tokens:u,output_tokens:p,cache_read_tokens:m,cache_creation_tokens:w,tool_call_count:typeof s=="number"?s:null,duration_ms:x,captured_at:new Date().toISOString()},A=E(e,n);try{P(A,{recursive:!0})}catch{}R(E(A,"usage.json"),JSON.stringify(U,null,2),"utf-8")}function C(...i){for(let e of i){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()!==""&&!isNaN(Number(e)))return Number(e)}return null}function Se(i,e){let n=E(re(),".claude"),o=E(n,".credentials.json"),s={claudeAiOauth:{accessToken:i,...e?{subscriptionType:String(e).toLowerCase()}:{}}};try{if(te(o)&&JSON.parse(oe(o,"utf-8"))?.claudeAiOauth?.accessToken===i)return;P(n,{recursive:!0}),R(o,JSON.stringify(s,null,2),"utf-8"),c.debug(`Wrote Claude Code OAuth credentials to ${o}`)}catch(r){c.warn(`Could not write ${o}: ${r.message} \u2014 Claude SDK may fail to authenticate.`)}}function Te(i){let e=E(re(),".claude"),n=E(e,".credentials.json"),o;try{o=JSON.parse(i)}catch(s){c.warn(`CLAUDE_CODE_CREDENTIALS_JSON not valid JSON: ${s.message}`);return}if(!o?.claudeAiOauth?.accessToken){c.warn("CLAUDE_CODE_CREDENTIALS_JSON missing claudeAiOauth.accessToken \u2014 skipping write.");return}try{if(te(n)){let s=JSON.parse(oe(n,"utf-8"));if(s?.claudeAiOauth?.accessToken===o.claudeAiOauth.accessToken&&s?.claudeAiOauth?.expiresAt===o.claudeAiOauth.expiresAt)return}P(e,{recursive:!0}),R(n,JSON.stringify(o,null,2),"utf-8"),c.debug(`Wrote full Claude Code credentials blob to ${n}`)}catch(s){c.warn(`Could not write ${n}: ${s.message} \u2014 Claude SDK may fail to authenticate.`)}}export{ee as ClaudeAgentStrategy};