@zibby/core 0.3.1 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +100 -103
- package/dist/package.json +1 -1
- package/dist/register-built-in-strategies.js +50 -53
- package/dist/strategies/claude-strategy.js +1 -4
- package/dist/strategies/index.js +56 -59
- package/dist/templates/browser-test-automation/graph.mjs +3 -3
- package/dist/templates/browser-test-automation/nodes/execute-live.mjs +32 -0
- package/package.json +1 -1
- package/templates/browser-test-automation/graph.mjs +3 -3
- package/templates/browser-test-automation/nodes/execute-live.mjs +32 -0
- package/dist/templates/code-implementation/graph.js +0 -35
- package/dist/templates/code-implementation/index.js +0 -7
- package/dist/templates/code-implementation/state.js +0 -14
- package/templates/code-implementation/graph.js +0 -35
- package/templates/code-implementation/index.js +0 -7
- package/templates/code-implementation/state.js +0 -14
|
@@ -1,4 +1 @@
|
|
|
1
|
-
import{AgentStrategy as
|
|
2
|
-
\u25C6 Model: ${m}${U}
|
|
3
|
-
`);let O=(await import("chalk")).default;console.log(`
|
|
4
|
-
${O.bold("Prompt sent to LLM:")}`),console.log(O.dim("\u2500".repeat(60))),console.log(O.dim(e)),console.log(O.dim("\u2500".repeat(60)));let{allowedTools:N,mcpServers:D}=this._resolveSkills(f,{sessionPath:R,workspace:r,nodeName:$});try{let d={cwd:r,allowedTools:N,permissionMode:"bypassPermissions",model:m,...Object.keys(D).length>0&&{mcpServers:D}};if(o){let S=typeof o.parse=="function"?Y(o,{target:"openApi3"}):o;d.outputFormat={type:"json_schema",schema:S},i.debug("Structured output enforced via SDK outputFormat")}i.debug(`Agent SDK options: ${JSON.stringify({cwd:d.cwd,toolCount:N.length,permissionMode:d.permissionMode,model:d.model,hasOutputFormat:!!d.outputFormat})}`);let E="",K=0,I=[];i.debug("Starting Claude Agent SDK query stream");let P;try{P=B({prompt:e,options:d})}catch(t){throw i.error(`Failed to initialize Claude Agent SDK: ${t.message}`),t}let M=null,A=0,H=3;if(C?.aborted){let t=new Error("Aborted via signal");throw t.name="AbortError",t}try{for await(let t of P){if(C?.aborted){let u=new Error("Aborted via signal");throw u.name="AbortError",u}if(I.push(t),t.type==="error"||t.error){let u=t.error?.message||t.error||t.message||"Unknown API error";throw new Error(typeof u=="string"?u:JSON.stringify(u))}let S=JSON.stringify(t.message?.content||t.text||"").slice(0,200);if(S===M){if(A++,A>=H){let u=(t.message?.content?.[0]?.text||t.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${A}x repeated): ${u}`)}}else M=S,A=1;if(t.type==="assistant"||t.constructor?.name==="AssistantMessage"){let u=t.message?.content||t.content||[];for(let s of u)if(s.type==="thinking"&&s.thinking)console.log(`${s.thinking.substring(0,200)}${s.thinking.length>200?"...":""}`);else if(s.type==="text"&&s.text)E+=s.text,s.text.length<500?console.log(`${s.text}`):console.log(`${s.text.substring(0,200)}... (${s.text.length} chars)`);else if(s.type==="tool_use"){K++,s.name.includes("memory")?y.stepMemory(`Tool: ${s.name}`):y.stepTool(`Tool: ${s.name}`);let G=JSON.stringify(s.input).substring(0,100);console.log(` Input: ${G}${JSON.stringify(s.input).length>100?"...":""}`)}}else if(!(t.type==="user"&&t.tool_use_result)){if(t.type==="result"||t.constructor?.name==="ResultMessage"){let u=t.result||t.text||t.content||E;if(o){if(t.structured_output){i.debug("Using SDK native structured_output");let x=typeof o.parse=="function"?o.parse(t.structured_output):t.structured_output;return{raw:u,structured:x}}if(u){let s=this._extractJson(u,o);if(s)return{raw:u,structured:s}}i.warn(`Could not extract structured output \u2014 returning raw text (${(u||"").length} chars)`)}return u||""}}}if(i.warn(`Agent SDK ended without result. Collected ${I.length} messages`),E.length>0)return i.debug("Returning accumulated text from messages"),E;throw new Error("Claude Agent SDK query ended without result")}catch(t){throw i.error(`Error during query stream: ${t.message}`),t}}catch(d){throw i.error("Claude Agent SDK call failed",{error:d.message}),d}}finally{for(let h of b)h.dispose()}}_resolveSkills(e,n){if(e===null)return i.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return i.debug("Default IDE skills for code generation"),{allowedTools:["Read","Write","Bash","Grep","Glob"],mcpServers:{}};let c=[],r={};for(let o of e){let l=F(o);if(!l){i.warn(`Unknown skill "${o}" \u2014 skipping`);continue}if(l.allowedTools&&c.push(...l.allowedTools),typeof l.resolve=="function"){let f=l.resolve(n);f&&(r[l.serverName]=f,i.debug(`MCP: ${l.serverName} \u2192 ${f.command} ${f.args[0]}`))}}return{allowedTools:c,mcpServers:r}}_extractJson(e,n){let c=[()=>{if(e.includes("===JSON_START===")){let r=e.indexOf("===JSON_START===")+16,o=e.indexOf("===JSON_END===");return e.substring(r,o).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 r=e.indexOf("{"),o=e.lastIndexOf("}");if(r!==-1&&o>r)return e.substring(r,o+1)}];for(let r of c)try{let o=r();if(!o)continue;let l=JSON.parse(o);if(typeof l!="object"||l===null)continue;return typeof n.parse=="function"?n.parse(l):l}catch{}return null}};export{k as ClaudeAgentStrategy};
|
|
1
|
+
import{AgentStrategy as Q,getSkill as V}from"@zibby/agent-workflow";import{query as ee}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as te}from"zod-to-json-schema";import{writeFileSync as Z,mkdirSync as q,existsSync as oe,readFileSync as ne}from"fs";import{homedir as re}from"os";import{join as v}from"path";import E from"chalk";var g={debug:0,info:1,warn:2,error:3,silent:4},D=class{constructor(){this._level=this._getLogLevel()}_getLogLevel(){if(process.env.ZIBBY_DEBUG==="true")return g.debug;if(process.env.ZIBBY_VERBOSE==="true")return g.info;let e=process.env.LOG_LEVEL?.toLowerCase();return e&&e in g?g[e]:g.info}_shouldLog(e){return g[e]>=this._level}_formatMessage(e,n,s={}){let r=new Date().toISOString(),c=`${this._getPrefix(e)} ${n}`;return Object.keys(s).length>0&&(c+=E.dim(` ${JSON.stringify(s)}`)),c}_getPrefix(e){return{debug:E.gray("[DEBUG]"),info:E.cyan("[INFO]"),warn:E.yellow("[WARN]"),error:E.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 g&&(this._level=g[e])}getLevel(){return Object.keys(g).find(e=>g[e]===this._level)}},i=new D;import{timeline as I,Timeline as pe,WORKFLOW_GRAPH_LOG_MARKER_PREFIX as de}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 P={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 ge={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:18e4};function N(u){let e=`${u}_POOL`,n=process.env[e];if(!n||typeof n!="string")return{picked:null,count:0,dispose:()=>{}};let s=n.split(/[,\n]+/).map(c=>c.trim()).filter(Boolean);if(s.length===0)return{picked:null,count:0,dispose:()=>{}};let r=s[Math.floor(Math.random()*s.length)],t=process.env[u];return process.env[u]=r,i.debug(`[auth-pool] ${u}: picked 1 of ${s.length} from pool (***${r.slice(-4)})`),{picked:r,count:s.length,dispose(){t===void 0?delete process.env[u]:process.env[u]=t}}}var Y=class extends Q{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(e){let n=!!process.env.ANTHROPIC_API_KEY||!!process.env.ANTHROPIC_API_KEY_POOL,s=!!process.env.CLAUDE_CODE_OAUTH_TOKEN||!!process.env.CLAUDE_CODE_OAUTH_TOKEN_POOL,r=!!process.env.ANTHROPIC_AUTH_TOKEN||!!process.env.ANTHROPIC_AUTH_TOKEN_POOL,t=n||s||r;return t||i.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)."),t}async invoke(e,n={}){let{model:s,workspace:r=process.cwd(),schema:t=null,images:c=[],skills:p=null,sessionPath:T=null,nodeName:y=null,timeout:b,config:x={},signal:h=null}=n,d=s;(!d||d==="auto")&&(i.debug(`Model is '${d||"undefined"}', using default: ${$.CLAUDE}`),d=$.CLAUDE);let O=P[d]||d;P[d]&&d!==O&&i.debug(`Mapped model: ${d} \u2192 ${O}`);let W=[N("ANTHROPIC_API_KEY"),N("CLAUDE_CODE_OAUTH_TOKEN"),N("ANTHROPIC_AUTH_TOKEN")];try{i.debug(`Invoking Claude Agent SDK with model: ${O}, skills: ${JSON.stringify(p)}`);let _=process.env.CLAUDE_CODE_OAUTH_TOKEN,M=process.env.ANTHROPIC_API_KEY,R=process.env.ANTHROPIC_AUTH_TOKEN;_&&ie(_,process.env.__ZIBBY_CLAUDE_PLAN);let k=process.env.__ZIBBY_CLAUDE_PLAN,U=k?k.charAt(0).toUpperCase()+k.slice(1):null,A;_?A=U?`Claude ${U} plan \xB7 ***${_.slice(-4)}`:`Subscription \xB7 ***${_.slice(-4)}`:M?A=`API key \xB7 ***${M.slice(-4)}`:R?A=`Bearer \xB7 ***${R.slice(-4)}`:A="NONE \u2014 request will fail";let m=(await import("chalk")).default;console.log(""),console.log(` ${m.cyan("\u25C6")} ${m.bold(O)}`),console.log(` ${m.dim("Auth: ")}${A}`),console.log(` ${m.dim("Workdir: ")}${r}`),console.log(""),console.log(m.bold("Prompt sent to LLM:")),console.log(m.dim("\u2500".repeat(60))),console.log(m.dim(e)),console.log(m.dim("\u2500".repeat(60)));let{allowedTools:K,mcpServers:H}=this._resolveSkills(p,{sessionPath:T,workspace:r,nodeName:y});try{let f={cwd:r,allowedTools:K,permissionMode:"bypassPermissions",model:O,...Object.keys(H).length>0&&{mcpServers:H}};if(t){let L=typeof t.parse=="function"?te(t,{target:"openApi3"}):t;f.outputFormat={type:"json_schema",schema:L},i.debug("Structured output enforced via SDK outputFormat")}i.debug(`Agent SDK options: ${JSON.stringify({cwd:f.cwd,toolCount:K.length,permissionMode:f.permissionMode,model:f.model,hasOutputFormat:!!f.outputFormat})}`);let w="",J=0,F=[];i.debug("Starting Claude Agent SDK query stream");let B;try{B=ee({prompt:e,options:f})}catch(o){throw i.error(`Failed to initialize Claude Agent SDK: ${o.message}`),o}let G=null,C=0,X=3;if(h?.aborted){let o=new Error("Aborted via signal");throw o.name="AbortError",o}try{for await(let o of B){if(h?.aborted){let a=new Error("Aborted via signal");throw a.name="AbortError",a}if(F.push(o),o.type==="error"||o.error){let a=o.error?.message||o.error||o.message||"Unknown API error";throw new Error(typeof a=="string"?a:JSON.stringify(a))}let L=JSON.stringify(o.message?.content||o.text||"").slice(0,200);if(L===G){if(C++,C>=X){let a=(o.message?.content?.[0]?.text||o.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${C}x repeated): ${a}`)}}else G=L,C=1;if(o.type==="assistant"||o.constructor?.name==="AssistantMessage"){let a=o.message?.content||o.content||[];for(let l of a)if(l.type==="thinking"&&l.thinking)console.log(`${l.thinking.substring(0,200)}${l.thinking.length>200?"...":""}`);else if(l.type==="text"&&l.text)w+=l.text,l.text.length<500?console.log(`${l.text}`):console.log(`${l.text.substring(0,200)}... (${l.text.length} chars)`);else if(l.type==="tool_use"){J++,l.name.includes("memory")?I.stepMemory(`Tool: ${l.name}`):I.stepTool(`Tool: ${l.name}`);let z=JSON.stringify(l.input).substring(0,100);console.log(` Input: ${z}${JSON.stringify(l.input).length>100?"...":""}`)}}else if(!(o.type==="user"&&o.tool_use_result)){if(o.type==="result"||o.constructor?.name==="ResultMessage"){let a=o.result||o.text||o.content||w;try{se({message:o,sessionPath:T,nodeName:y,model:d,toolCallCount:J})}catch(l){i.debug(`usage.json write failed: ${l.message}`)}if(t){if(o.structured_output){i.debug("Using SDK native structured_output");let j=typeof t.parse=="function"?t.parse(o.structured_output):o.structured_output;return{raw:a,structured:j}}if(a){let l=this._extractJson(a,t);if(l)return{raw:a,structured:l}}i.warn(`Could not extract structured output \u2014 returning raw text (${(a||"").length} chars)`)}return a||""}}}if(i.warn(`Agent SDK ended without result. Collected ${F.length} messages`),w.length>0)return i.debug("Returning accumulated text from messages"),w;throw new Error("Claude Agent SDK query ended without result")}catch(o){throw i.error(`Error during query stream: ${o.message}`),o}}catch(f){throw i.error("Claude Agent SDK call failed",{error:f.message}),f}}finally{for(let _ of W)_.dispose()}}_resolveSkills(e,n){if(e===null)return i.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(e)||e.length===0)return i.debug("Default IDE skills for code generation"),{allowedTools:["Read","Write","Bash","Grep","Glob"],mcpServers:{}};let s=[],r={};for(let t of e){let c=V(t);if(!c){i.warn(`Unknown skill "${t}" \u2014 skipping`);continue}if(c.allowedTools&&s.push(...c.allowedTools),typeof c.resolve=="function"){let p=c.resolve(n);p&&(r[c.serverName]=p,i.debug(`MCP: ${c.serverName} \u2192 ${p.command} ${p.args[0]}`))}}return{allowedTools:s,mcpServers:r}}_extractJson(e,n){let s=[()=>{if(e.includes("===JSON_START===")){let r=e.indexOf("===JSON_START===")+16,t=e.indexOf("===JSON_END===");return e.substring(r,t).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 r=e.indexOf("{"),t=e.lastIndexOf("}");if(r!==-1&&t>r)return e.substring(r,t+1)}];for(let r of s)try{let t=r();if(!t)continue;let c=JSON.parse(t);if(typeof c!="object"||c===null)continue;return typeof n.parse=="function"?n.parse(c):c}catch{}return null}};function se({message:u,sessionPath:e,nodeName:n,model:s,toolCallCount:r}){if(!e||!n)return;let t=u?.usage||u?.message?.usage||{},c=S(t.input_tokens,t.inputTokens),p=S(t.output_tokens,t.outputTokens),T=S(t.cache_read_input_tokens,t.cacheReadInputTokens),y=S(t.cache_creation_input_tokens,t.cacheCreationInputTokens),b=S(u?.duration_ms,u?.durationMs),x={model:s||null,input_tokens:c,output_tokens:p,cache_read_tokens:T,cache_creation_tokens:y,tool_call_count:typeof r=="number"?r:null,duration_ms:b,captured_at:new Date().toISOString()},h=v(e,n);try{q(h,{recursive:!0})}catch{}Z(v(h,"usage.json"),JSON.stringify(x,null,2),"utf-8")}function S(...u){for(let e of u){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()!==""&&!isNaN(Number(e)))return Number(e)}return null}function ie(u,e){let n=v(re(),".claude"),s=v(n,".credentials.json"),r={claudeAiOauth:{accessToken:u,...e?{subscriptionType:String(e).toLowerCase()}:{}}};try{if(oe(s)&&JSON.parse(ne(s,"utf-8"))?.claudeAiOauth?.accessToken===u)return;q(n,{recursive:!0}),Z(s,JSON.stringify(r,null,2),"utf-8"),i.debug(`Wrote Claude Code OAuth credentials to ${s}`)}catch(t){i.warn(`Could not write ${s}: ${t.message} \u2014 Claude SDK may fail to authenticate.`)}}export{Y as ClaudeAgentStrategy};
|