@zibby/core 0.1.21 → 0.1.23

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 (167) hide show
  1. package/dist/agents/base.js +17 -0
  2. package/dist/backend-client.js +1 -0
  3. package/dist/constants/tool-names.js +1 -0
  4. package/dist/constants/zibby-scratch.js +1 -0
  5. package/dist/constants.js +1 -0
  6. package/dist/enrichment/base.js +1 -0
  7. package/dist/enrichment/enrichers/accessibility-enricher.js +1 -0
  8. package/dist/enrichment/enrichers/dom-enricher.js +1 -0
  9. package/dist/enrichment/enrichers/page-state-enricher.js +1 -0
  10. package/dist/enrichment/enrichers/position-enricher.js +1 -0
  11. package/dist/enrichment/index.js +1 -0
  12. package/dist/enrichment/mcp-integration.js +1 -0
  13. package/dist/enrichment/mcp-ref-enricher.js +1 -0
  14. package/dist/enrichment/pipeline.js +3 -0
  15. package/dist/enrichment/trace-text-enricher.js +1 -0
  16. package/dist/framework/agents/assistant-strategy.js +5 -0
  17. package/dist/framework/agents/base.js +1 -0
  18. package/dist/framework/agents/claude-strategy.js +4 -0
  19. package/dist/framework/agents/codex-strategy.js +4 -0
  20. package/dist/framework/agents/cursor-strategy.js +32 -0
  21. package/dist/framework/agents/gemini-strategy.js +11 -0
  22. package/dist/framework/agents/index.js +13 -0
  23. package/dist/framework/agents/middleware/assistant-round-pipeline.js +3 -0
  24. package/dist/framework/agents/providers/base.js +1 -0
  25. package/dist/framework/agents/providers/index.js +1 -0
  26. package/dist/framework/agents/providers/openai-transport.js +2 -0
  27. package/dist/framework/agents/providers/openai.js +1 -0
  28. package/dist/framework/agents/providers/transport-base.js +1 -0
  29. package/dist/framework/agents/utils/auth-resolver.js +1 -0
  30. package/dist/framework/agents/utils/cursor-output-formatter.js +1 -0
  31. package/dist/framework/agents/utils/openai-proxy-formatter.js +9 -0
  32. package/dist/framework/agents/utils/payload-budget.js +3 -0
  33. package/dist/framework/agents/utils/structured-output-formatter.js +21 -0
  34. package/dist/framework/code-generator.js +10 -0
  35. package/dist/framework/constants.js +1 -0
  36. package/dist/framework/context-loader.js +5 -0
  37. package/dist/framework/function-bridge.js +2 -0
  38. package/dist/framework/function-skill-registry.js +1 -0
  39. package/dist/framework/graph-compiler.js +1 -0
  40. package/dist/framework/graph.js +5 -0
  41. package/dist/framework/index.js +1 -0
  42. package/dist/framework/mcp-client.js +2 -0
  43. package/dist/framework/node-registry.js +9 -0
  44. package/dist/framework/node.js +5 -0
  45. package/dist/framework/output-parser.js +3 -0
  46. package/dist/framework/skill-registry.js +1 -0
  47. package/dist/framework/state-utils.js +1 -0
  48. package/dist/framework/state.js +1 -0
  49. package/dist/framework/tool-resolver.js +1 -0
  50. package/dist/index.js +8 -0
  51. package/dist/runtime/generation/base.js +1 -0
  52. package/dist/runtime/generation/index.js +3 -0
  53. package/dist/runtime/generation/mcp-ref-strategy.js +41 -0
  54. package/dist/runtime/generation/stable-id-strategy.js +16 -0
  55. package/dist/runtime/stable-id-runtime.js +1 -0
  56. package/dist/runtime/verification/base.js +1 -0
  57. package/dist/runtime/verification/index.js +3 -0
  58. package/dist/runtime/verification/playwright-json-strategy.js +1 -0
  59. package/dist/runtime/zibby-runtime.js +1 -0
  60. package/dist/sync/index.js +1 -0
  61. package/dist/sync/uploader.js +1 -0
  62. package/dist/tools/run-playwright-test.js +5 -0
  63. package/dist/utils/adf-converter.js +7 -0
  64. package/dist/utils/ast-utils.js +1 -0
  65. package/dist/utils/ci-setup.js +5 -0
  66. package/dist/utils/cursor-mcp-isolated-home.js +1 -0
  67. package/dist/utils/cursor-utils.js +18 -0
  68. package/dist/utils/live-frame-discovery.js +1 -0
  69. package/dist/utils/logger.js +1 -0
  70. package/dist/utils/mcp-config-writer.js +10 -0
  71. package/dist/utils/mission-control-from-run-states.js +1 -0
  72. package/dist/utils/node-schema-parser.js +1 -0
  73. package/dist/utils/parallel-config.js +1 -0
  74. package/dist/utils/post-process-events.js +1 -0
  75. package/dist/utils/result-handler.js +1 -0
  76. package/{src → dist}/utils/ripple-effect.js +3 -12
  77. package/dist/utils/run-capacity-coordinator.js +1 -0
  78. package/dist/utils/run-capacity-queue.js +2 -0
  79. package/dist/utils/run-index-merge.js +1 -0
  80. package/dist/utils/run-index-post-cli.js +1 -0
  81. package/dist/utils/run-registry.js +3 -0
  82. package/dist/utils/run-state-session.js +2 -0
  83. package/dist/utils/selector-generator.js +4 -0
  84. package/dist/utils/session-state-constants.js +1 -0
  85. package/dist/utils/session-state-live-runs.js +1 -0
  86. package/dist/utils/streaming-parser.js +4 -0
  87. package/dist/utils/test-post-processor.js +18 -0
  88. package/dist/utils/timeline.js +14 -0
  89. package/dist/utils/trace-parser.js +2 -0
  90. package/dist/utils/video-organizer.js +3 -0
  91. package/package.json +49 -35
  92. package/templates/browser-test-automation/README.md +29 -7
  93. package/templates/browser-test-automation/chat.mjs +36 -0
  94. package/templates/browser-test-automation/graph.mjs +5 -9
  95. package/templates/browser-test-automation/nodes/execute-live.mjs +30 -58
  96. package/templates/browser-test-automation/nodes/generate-script.mjs +32 -12
  97. package/templates/browser-test-automation/nodes/utils.mjs +153 -10
  98. package/templates/browser-test-automation/pipeline-ids.js +12 -0
  99. package/templates/browser-test-automation/result-handler.mjs +78 -2
  100. package/templates/browser-test-automation/run-index.mjs +418 -0
  101. package/scripts/export-default-workflows.js +0 -51
  102. package/scripts/patch-cursor-mcp.js +0 -174
  103. package/scripts/setup-ci.sh +0 -115
  104. package/scripts/setup-official-playwright-mcp.sh +0 -226
  105. package/scripts/test-with-video.sh +0 -49
  106. package/src/agents/base.js +0 -361
  107. package/src/constants.js +0 -47
  108. package/src/enrichment/base.js +0 -49
  109. package/src/enrichment/enrichers/accessibility-enricher.js +0 -197
  110. package/src/enrichment/enrichers/dom-enricher.js +0 -171
  111. package/src/enrichment/enrichers/page-state-enricher.js +0 -129
  112. package/src/enrichment/enrichers/position-enricher.js +0 -67
  113. package/src/enrichment/index.js +0 -96
  114. package/src/enrichment/mcp-integration.js +0 -149
  115. package/src/enrichment/mcp-ref-enricher.js +0 -78
  116. package/src/enrichment/pipeline.js +0 -192
  117. package/src/enrichment/trace-text-enricher.js +0 -115
  118. package/src/framework/AGENTS.md +0 -98
  119. package/src/framework/agents/base.js +0 -72
  120. package/src/framework/agents/claude-strategy.js +0 -278
  121. package/src/framework/agents/cursor-strategy.js +0 -544
  122. package/src/framework/agents/index.js +0 -105
  123. package/src/framework/agents/utils/cursor-output-formatter.js +0 -67
  124. package/src/framework/agents/utils/openai-proxy-formatter.js +0 -249
  125. package/src/framework/code-generator.js +0 -301
  126. package/src/framework/constants.js +0 -33
  127. package/src/framework/context-loader.js +0 -101
  128. package/src/framework/function-bridge.js +0 -78
  129. package/src/framework/function-skill-registry.js +0 -20
  130. package/src/framework/graph-compiler.js +0 -342
  131. package/src/framework/graph.js +0 -610
  132. package/src/framework/index.js +0 -28
  133. package/src/framework/node-registry.js +0 -163
  134. package/src/framework/node.js +0 -259
  135. package/src/framework/output-parser.js +0 -71
  136. package/src/framework/skill-registry.js +0 -55
  137. package/src/framework/state-utils.js +0 -52
  138. package/src/framework/state.js +0 -67
  139. package/src/framework/tool-resolver.js +0 -65
  140. package/src/index.js +0 -345
  141. package/src/runtime/generation/base.js +0 -46
  142. package/src/runtime/generation/index.js +0 -70
  143. package/src/runtime/generation/mcp-ref-strategy.js +0 -197
  144. package/src/runtime/generation/stable-id-strategy.js +0 -170
  145. package/src/runtime/stable-id-runtime.js +0 -248
  146. package/src/runtime/verification/base.js +0 -44
  147. package/src/runtime/verification/index.js +0 -67
  148. package/src/runtime/verification/playwright-json-strategy.js +0 -119
  149. package/src/runtime/zibby-runtime.js +0 -299
  150. package/src/sync/index.js +0 -2
  151. package/src/sync/uploader.js +0 -29
  152. package/src/tools/run-playwright-test.js +0 -158
  153. package/src/utils/adf-converter.js +0 -68
  154. package/src/utils/ast-utils.js +0 -37
  155. package/src/utils/ci-setup.js +0 -124
  156. package/src/utils/cursor-utils.js +0 -71
  157. package/src/utils/logger.js +0 -144
  158. package/src/utils/mcp-config-writer.js +0 -115
  159. package/src/utils/node-schema-parser.js +0 -522
  160. package/src/utils/post-process-events.js +0 -55
  161. package/src/utils/result-handler.js +0 -102
  162. package/src/utils/selector-generator.js +0 -239
  163. package/src/utils/streaming-parser.js +0 -387
  164. package/src/utils/test-post-processor.js +0 -211
  165. package/src/utils/timeline.js +0 -217
  166. package/src/utils/trace-parser.js +0 -325
  167. package/src/utils/video-organizer.js +0 -91
@@ -0,0 +1,17 @@
1
+ import{spawn as k}from"child_process";import{mkdirSync as C,existsSync as P,writeFileSync as v}from"fs";import{join as $}from"path";import{ContextLoader as N}from"../framework/context-loader.js";import{StreamingParser as O}from"../utils/streaming-parser.js";import{findCursorAgentPath as D}from"../utils/cursor-utils.js";import{DEFAULT_OUTPUT_BASE as E,SESSIONS_DIR as G,SESSION_INFO_FILE as L}from"../framework/constants.js";import{WorkflowGraph as _}from"../framework/graph.js";class x{constructor(t={}){this.config=t,this.adapter=null,this.paths=t.paths||{specs:"test-specs",generated:"tests"},this.agentCommand=t.agentCommand||"cursor-agent",this.buildArgs=t.buildArgs||((s,e=!0)=>{const o=["-p",s,"--approve-mcps","--force"];return e&&(o.push("--output-format","stream-json"),o.push("--stream-partial-output")),o})}static extractJsonFromStream(t){return O.extractResult(t)}async initialize(t){this.adapter=t,t&&!t.isConnected()&&await t.connect()}buildGraph(){throw new Error("buildGraph() must be implemented by subclass")}async onComplete(t){}async run(t,s={}){const e=this.buildGraph(),o=typeof t=="object"&&!Array.isArray(t)?{input:t,...t,...s}:{input:t,...s};return await e.run(this,o)}async executeNode(t,s){const{prompt:e,outputSchema:o,model:l}=t,n=typeof e=="function"?e(s):e;console.log(`
2
+ \u{1F4DD} Prompt:
3
+ ${n}
4
+ `);const r=await this.executePrompt(n,s.cwd,3e5,l);console.log(`
5
+ \u{1F4E4} Raw Output:
6
+ ${r}
7
+ `);let a=null;if(o)try{if(a=x.extractJsonFromStream(r),!a)throw new Error("No valid result JSON found in output");console.log(`
8
+ \u2705 Parsed Output:
9
+ ${JSON.stringify(a,null,2)}
10
+ `)}catch(i){console.warn(`\u26A0\uFE0F Failed to parse output as JSON: ${i.message}`)}return{success:!0,output:a,raw:r}}async cleanup(){this.adapter&&this.adapter.isConnected()&&await this.adapter.disconnect()}async executePrompt(t,s=process.cwd(),e=3e5,o=null,l=!0){let n=this.agentCommand;if(n==="cursor-agent"){const r=await D();r&&(n=r)}return new Promise((r,a)=>{let i="";const I=this.buildArgs(t,l);o&&I.push("--model",o);const T={...process.env},c=k(n,I,{cwd:s,env:T,stdio:["inherit","pipe","inherit"],shell:!1,detached:!1}),m=setTimeout(()=>{console.log(`
11
+ \u23F1\uFE0F Timeout reached (${e/1e3}s) - killing agent...`),c.kill("SIGTERM"),setTimeout(()=>{c.killed||(console.log("\u26A0\uFE0F Forcing kill (SIGKILL)..."),c.kill("SIGKILL"))},2e3),a(new Error(`Agent timed out after ${e/1e3}s. The agent may be stuck or waiting for user input.`))},e);let f=0,S=Date.now();const h=setInterval(()=>{if(i.length>f)f=i.length,S=Date.now();else{const u=Date.now()-S;u>1e4&&console.log(`\u23F3 AI agent is thinking... (${Math.floor(u/1e3)}s, ${i.length} bytes so far)`)}},1e4),y=()=>{clearTimeout(m),clearInterval(h),c&&!c.killed&&(c.kill("SIGTERM"),setTimeout(()=>{c.killed||c.kill("SIGKILL")},2e3))},g=()=>{console.log(`
12
+
13
+ \u{1F6D1} Interrupted by user (Ctrl+C)`),y(),a(new Error("Interrupted by user"))};process.on("SIGINT",g);const p=new O;c.stdout.on("data",u=>{const d=u.toString();i+=d;const w=p.processChunk(d);w&&(process.stdout.write(w,"utf8",()=>{process.stdout.isTTY&&process.stdout._flush&&process.stdout._flush()}),S=Date.now(),f+=w.length)}),c.on("close",u=>{process.off("SIGINT",g),clearTimeout(m),clearInterval(h);const d=p.flush();d&&process.stdout.write(d),i=p.getRawText();const w=p.getResult();u===0?r({raw:i,extracted:w}):a(new Error(`Agent exited with code ${u}`))}),c.on("error",u=>{process.off("SIGINT",g),clearTimeout(m),clearInterval(h),a(new Error(`Failed to spawn agent: ${u.message}`))})})}async runSingleNode(t,s,e){const o=s[t];if(!o)throw new Error(`Unknown node: ${t}. Available nodes: ${Object.keys(s).join(", ")}`);const{cwd:l}=e;if(!l)throw new Error("cwd is required for single node execution");let n=e.sessionPath,r=e.sessionTimestamp;const a=e.config||{};if(!n){const g=process.env.CI_JOB_ID||process.env.GITHUB_RUN_ID||process.env.CIRCLE_WORKFLOW_ID||process.env.BUILD_ID||Date.now().toString(),p=a.paths?.sessionPrefix,u=p?`${p}_${g}`:g;r=r||Date.now();const d=a.paths?.output||E;n=$(l,d,G,u),P(n)||C(n,{recursive:!0})}const i=a.paths?.output||E,I=$(l,i,L);C($(l,i),{recursive:!0}),v(I,JSON.stringify({sessionPath:n,sessionTimestamp:r||n.split("/").pop(),currentNode:t,createdAt:new Date().toISOString()}),"utf-8"),console.log(`
14
+ ${"=".repeat(80)}`),console.log(`\u{1F3AF} SINGLE NODE EXECUTION: ${t}`),console.log(`\u{1F4C1} Session: ${n.split("/").pop()}${e.sessionPath?" (reusing)":""}`),console.log(`${"=".repeat(80)}
15
+ `);const T=await N.loadContext(e.specPath||"",l,e.contextConfig||{}),{Node:c}=await import("../framework/node.js"),{WorkflowState:m}=await import("../framework/state.js"),f=new m({...e,sessionPath:n,sessionTimestamp:r,context:T}),h=await new c(o).execute(this,f);return console.log(`
16
+ ${"=".repeat(80)}`),console.log(`\u2705 Node ${t} completed`),console.log(`${"=".repeat(80)}
17
+ `),{success:!0,output:h.output,outputPath:e.outputPath,state:h}}calculateOutputPath(t){const{specs:s,generated:e}=this.paths;if(!t)return`${e}/generated-test.spec.js`;const o=t.replace(new RegExp(`^${s}/`),"").replace(/\.[^.]+$/,".spec.js");return`${e}/${o}`.replace(/\/+/g,"/")}}function W(b,t={}){const s=new x(t);return s.buildGraph=function(){const e=new _;return b(e),e},t.onComplete&&(s.onComplete=t.onComplete),s}export{x as WorkflowAgent,W as workflow};
@@ -0,0 +1 @@
1
+ import{existsSync as f,readFileSync as u}from"fs";import{homedir as l}from"os";import{join as h}from"path";const o=new Map;function w(){if(process.env.ZIBBY_USER_TOKEN)return process.env.ZIBBY_USER_TOKEN;try{const t=h(l(),".zibby","config.json");return f(t)&&JSON.parse(u(t,"utf-8")).sessionToken||null}catch{return null}}function k(){return process.env.ZIBBY_ACCOUNT_API_URL?process.env.ZIBBY_ACCOUNT_API_URL.replace(/\/$/,""):(process.env.ZIBBY_ENV||"prod")==="local"?"http://localhost:3001":process.env.ZIBBY_PROD_ACCOUNT_API_URL||"https://account-api-prod.zibby.app"}async function y(t){const s=Date.now(),r=o.get(t);if(r&&r.expiresAt>s)return r.data;const i=w();if(!i)throw new Error("No session token. Run `zibby login` first.");const c=`${k()}/integrations/token/${t}`,n=await fetch(c,{method:"GET",headers:{Authorization:`Bearer ${i}`}});if(!n.ok){const p=await n.text().catch(()=>"");throw n.status===404?new Error(`${t} is not connected. Connect it at https://studio.zibby.app/integrations`):n.status===401||n.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Failed to resolve ${t} token (${n.status}): ${p}`)}const e=await n.json();if(!e||typeof e!="object")throw new Error(`Invalid response from ${t} token endpoint: expected object, got ${typeof e}`);if(t==="jira"){if(!e.token||typeof e.token!="string")throw new Error(`Invalid jira token response: token is ${typeof e.token}, expected string`);if(!e.cloudId)throw new Error("Invalid jira token response: missing cloudId")}else if(t==="github"&&(!e.token||typeof e.token!="string"))throw new Error(`Invalid github token response: token is ${typeof e.token}, expected string`);const a=((e.expiresInSec||3e3)-120)*1e3;return o.set(t,{data:e,expiresAt:s+a}),e}function b(t){t?o.delete(t):o.clear()}export{b as clearTokenCache,y as resolveIntegrationToken};
@@ -0,0 +1 @@
1
+ const _={READ_FILE:"read_file",WRITE_FILE:"write_file",LIST_DIRECTORY:"list_directory",RUN_COMMAND:"run_command",OPEN_URL:"open_url",WAIT:"wait"},t={LIST_PROJECTS:"jira_list_projects",SEARCH:"jira_search",GET_ISSUE:"jira_get_issue",CREATE_ISSUE:"jira_create_issue",LIST_SPRINTS:"jira_list_sprints",GET_SPRINT_ISSUES:"jira_get_sprint_issues",GET_COMMENTS:"jira_get_comments",ADD_COMMENT:"jira_add_comment",EDIT_ISSUE:"jira_edit_issue",TRANSITION_ISSUE:"jira_transition_issue"},e={GET_USER:"github_get_user",LIST_ORGS:"github_list_orgs",LIST_REPOS:"github_list_repos",CLONE:"github_clone",SEARCH_REPOS:"github_search_repos",SEARCH_ISSUES:"github_search_issues",SEARCH_CODE:"github_search_code",GET_PR:"github_get_pr",GET_PR_DIFF:"github_get_pr_diff",LIST_PR_FILES:"github_list_pr_files",LIST_PR_COMMENTS:"github_list_pr_comments",LIST_COMMITS:"github_list_commits",GET_COMMIT:"github_get_commit",GET_FILE:"github_get_file",CREATE_ISSUE:"github_create_issue"},s={LIST_CHANNELS:"slack_list_channels",POST_MESSAGE:"slack_post_message",REPLY_TO_THREAD:"slack_reply_to_thread",ADD_REACTION:"slack_add_reaction",GET_CHANNEL_HISTORY:"slack_get_channel_history",GET_THREAD_REPLIES:"slack_get_thread_replies",GET_USERS:"slack_get_users",GET_USER_PROFILE:"slack_get_user_profile"},S={GENERATE:"run_generate",TEST:"run_test",STATUS:"run_status",CANCEL:"run_cancel",WAIT:"run_wait",ARTIFACTS:"run_artifacts",LIST_SPECS:"list_specs"},E={GET_TEST_HISTORY:"memory_get_test_history",GET_SELECTORS:"memory_get_selectors",GET_PAGE_MODEL:"memory_get_page_model",GET_NAVIGATION:"memory_get_navigation",SAVE_INSIGHT:"memory_save_insight"},T={STORE:"memory_store",RECALL:"memory_recall",BRIEF:"memory_brief",END_SESSION:"memory_end_session",TASK_LOG:"task_log",TASK_HISTORY:"task_history"},i={INSTALL:"install_skill",UNINSTALL:"uninstall_skill",LIST_AVAILABLE:"list_available_skills"},r={..._,...t,...e,...s,...S,...E,...T,...i};export{r as ALL_TOOLS,T as CHAT_MEMORY_TOOLS,_ as CORE_TOOLS,e as GITHUB_TOOLS,t as JIRA_TOOLS,E as MEMORY_TOOLS,S as RUNNER_TOOLS,i as SKILL_TOOLS,s as SLACK_TOOLS};
@@ -0,0 +1 @@
1
+ import{resolve as c}from"path";const t=".zibby/scratch/specs";function o(r){return c(String(r||process.cwd()),t)}export{t as ZIBBY_SCRATCH_SPECS_REL,o as zibbyScratchSpecsDir};
@@ -0,0 +1 @@
1
+ const o={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"},n={ASSISTANT:"assistant",CLAUDE:"claude",CURSOR:"cursor",CODEX:"codex",GEMINI:"gemini"},e={DEBUG:"debug",INFO:"info",WARN:"warn",ERROR:"error",SILENT:"silent"},t={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"},s={auto:"o4-mini","o4-mini":"o4-mini",o3:"o3","o3-mini":"o3-mini","codex-mini":"codex-mini-latest","gpt-4o":"gpt-4o","gpt-4o-mini":"gpt-4o-mini","gpt-5.2-codex":"gpt-5.2-codex","gpt-5.2":"gpt-5.2","gpt-5.3":"gpt-5.3","gpt-5.4":"gpt-5.4"},i={auto:"gemini-2.5-pro","gemini-2.5-pro":"gemini-2.5-pro","gemini-2.5-flash":"gemini-2.5-flash"},p={CURSOR_AGENT_DEFAULT:1200*1e3,OPENAI_REQUEST:3e4};export{n as AGENT_TYPES,t as CLAUDE_MODEL_MAP,s as CODEX_MODEL_MAP,o as DEFAULT_MODELS,i as GEMINI_MODEL_MAP,e as LOG_LEVELS,p as TIMEOUTS};
@@ -0,0 +1 @@
1
+ class t{constructor(e={}){this.config=e,this.enabled=e.enabled!==!1,this.priority=e.priority||50}getName(){throw new Error("EventEnricher.getName() must be implemented")}canEnrich(e){return this.enabled}async enrich(e,r){throw new Error("EventEnricher.enrich() must be implemented")}handleError(e,r){return console.warn(`[${this.getName()}] Enrichment failed for event ${r.type}:`,e.message),null}}var i=t;export{t as EventEnricher,i as default};
@@ -0,0 +1 @@
1
+ import{EventEnricher as o}from"../base.js";import s from"crypto";class u extends o{getName(){return"AccessibilityEnricher"}getPriority(){return 100}canEnrich(t){return!this.enabled||!t.element||!t.event?!1:["click","fill","type","selectOption","hover"].includes(t.event.type)}async enrich(t,r){try{const{page:e,element:i}=r,n=await e.accessibility.snapshot(),a=await this.findAxNode(i,n);if(!a)return null;const l=await this.getAxContext(a,n),h=this.hashAxSubtree(a),c=this.hashAxPath(l.path);return{accessibility:{role:a.role,name:a.name||"",level:l.level,parent:l.parent,siblings:l.siblings,axTreeHash:h,axPathHash:c}}}catch(e){return this.handleError(e,t)}}async findAxNode(t,r){const e=await t.evaluate(i=>({role:i.getAttribute("role")||i.tagName.toLowerCase(),name:i.getAttribute("aria-label")||i.textContent?.trim()||"",tagName:i.tagName.toLowerCase()}));return this.searchAxTree(r,e)}searchAxTree(t,r){if(!t)return null;if(t.role===r.role&&(t.name||"").includes(r.name.substring(0,20)))return t;if(t.children)for(const e of t.children){const i=this.searchAxTree(e,r);if(i)return i}return null}getAxContext(t,r){const e={level:0,parent:null,siblings:[],path:[]},i=this.findParent(t,r);return i&&(e.parent={role:i.role,name:i.name},e.siblings=(i.children||[]).filter(n=>n!==t).map(n=>({role:n.role,name:n.name})).slice(0,3)),e.level=this.calculateLevel(t,r),e.path=this.buildPath(t,r),e}findParent(t,r,e=r){if(!e||!e.children)return null;if(e.children.includes(t))return e;for(const i of e.children){const n=this.findParent(t,r,i);if(n)return n}return null}calculateLevel(t,r,e=r,i=0){if(e===t)return i;if(e.children)for(const n of e.children){const a=this.calculateLevel(t,r,n,i+1);if(a>=0)return a}return-1}buildPath(t,r,e=r,i=[]){if(e===t)return[...i,{role:e.role,name:e.name}];if(e.children)for(const n of e.children){const a=this.buildPath(t,r,n,[...i,{role:e.role,name:e.name}]);if(a)return a}return null}hashAxSubtree(t){const r=JSON.stringify({role:t.role,name:t.name,children:(t.children||[]).map(e=>({role:e.role,name:e.name}))});return s.createHash("md5").update(r).digest("hex").substring(0,12)}hashAxPath(t){const r=t.map(e=>`${e.role}:${e.name}`).join("/");return s.createHash("md5").update(r).digest("hex").substring(0,12)}}var x=u;export{u as AccessibilityEnricher,x as default};
@@ -0,0 +1 @@
1
+ import{EventEnricher as v}from"../base.js";class E extends v{getName(){return"DOMEnricher"}getPriority(){return 85}canEnrich(e){return!this.enabled||!e.element||!e.event?!1:["click","fill","type","selectOption","hover"].includes(e.event.type)}async enrich(e,a){try{const{element:s}=a,r=await s.evaluate(i=>{const f=o=>{const c=[];let t=o;for(;t&&t!==document.body;){let p=t.tagName.toLowerCase();const n=t.parentElement;if(n){const u=Array.from(n.children).filter(h=>h.tagName===t.tagName);if(u.length>1){const h=u.indexOf(t)+1;p+=`:nth-child(${h})`}}c.unshift(p),t=t.parentElement}return`body > ${c.join(" > ")}`},g=o=>{const c=[];let t=o;for(;t&&t!==document.body;){let p=1,n=t.previousSibling;for(;n;)n.nodeType===1&&n.tagName===t.tagName&&p++,n=n.previousSibling;const u=t.tagName.toLowerCase();c.unshift(`${u}[${p}]`),t=t.parentElement}return`/html/body/${c.join("/")}`},b={};for(const o of i.attributes)b[o.name]=o.value;const l=window.getComputedStyle(i),y={display:l.display,visibility:l.visibility,opacity:l.opacity,pointerEvents:l.pointerEvents};let m=0,d=i.parentElement;for(;d;)m++,d=d.parentElement;return{path:f(i),xpath:g(i),depth:m,parent:i.parentElement?i.parentElement.tagName.toLowerCase():null,tagName:i.tagName.toLowerCase(),attributes:b,state:{visible:l.display!=="none"&&l.visibility!=="hidden",enabled:!i.disabled,focused:document.activeElement===i,...y}}});return{dom:{path:r.path,xpath:r.xpath,depth:r.depth,parent:r.parent,selector:this.buildSmartSelector(r)},attributes:r.attributes,state:r.state}}catch(s){return this.handleError(s,e)}}buildSmartSelector(e){let a=e.tagName;if(e.attributes.id)return`#${e.attributes.id}`;if(e.attributes["data-test-id"])return`[data-test-id="${e.attributes["data-test-id"]}"]`;if(e.attributes.class){const s=e.attributes.class.split(" ").filter(r=>r&&!r.match(/^(active|focus|hover|disabled)/));s.length>0&&(a+=`.${s.slice(0,2).join(".")}`)}return e.parent&&(a=`${e.parent} > ${a}`),a}}var $=E;export{E as DOMEnricher,$ as default};
@@ -0,0 +1 @@
1
+ import{EventEnricher as c}from"../base.js";class o extends c{constructor(e={}){super(e),this.pendingRequests=new Set,this.setupNetworkTracking=!1}getName(){return"PageStateEnricher"}getPriority(){return 95}canEnrich(e){return this.enabled&&e.page}async setupTracking(e){this.setupNetworkTracking||(e.on("request",t=>{["document","xhr","fetch"].includes(t.resourceType())&&this.pendingRequests.add(t.url())}),e.on("requestfinished",t=>{this.pendingRequests.delete(t.url())}),e.on("requestfailed",t=>{this.pendingRequests.delete(t.url())}),this.setupNetworkTracking=!0)}async enrich(e,t){try{const{page:r}=t;await this.setupTracking(r);const n=await r.evaluate(()=>({readyState:document.readyState,domContentLoaded:document.readyState!=="loading",loadComplete:document.readyState==="complete",url:document.location.href})),s=await this.checkDOMStability(r);return{page:{networkIdle:this.pendingRequests.size===0,pendingRequests:this.pendingRequests.size,domStable:s,...n}}}catch(r){return this.handleError(r,e)}}async checkDOMStability(e,t=500){try{return await e.evaluate(n=>new Promise(s=>{let i,u=0;const a=new MutationObserver(()=>{u++,clearTimeout(i),i=setTimeout(()=>{a.disconnect(),s(u===0)},n)});a.observe(document.body,{childList:!0,subtree:!0,attributes:!0}),i=setTimeout(()=>{a.disconnect(),s(!0)},n)}),t)}catch{return!1}}reset(){this.pendingRequests.clear(),this.setupNetworkTracking=!1}}var h=o;export{o as PageStateEnricher,h as default};
@@ -0,0 +1 @@
1
+ import{EventEnricher as h}from"../base.js";class s extends h{getName(){return"PositionEnricher"}getPriority(){return 90}canEnrich(r){return!this.enabled||!r.element||!r.event?!1:["click","fill","type","selectOption","hover"].includes(r.event.type)}async enrich(r,i){try{const{page:n,element:o}=i,e=await o.boundingBox();if(!e)return null;const t=await n.evaluate(()=>({scrollX:window.scrollX,scrollY:window.scrollY,width:window.innerWidth,height:window.innerHeight})),l=e.y>=t.scrollY&&e.y+e.height<=t.scrollY+t.height&&e.x>=0&&e.x+e.width<=t.width;return{position:{boundingBox:e,viewport:t,inViewport:l,centerPoint:{x:Math.round(e.x+e.width/2),y:Math.round(e.y+e.height/2)}}}}catch(n){return this.handleError(n,r)}}}var d=s;export{s as PositionEnricher,d as default};
@@ -0,0 +1 @@
1
+ import{EventEnricher as D}from"./base.js";import{EnrichmentPipeline as A}from"./pipeline.js";import{PositionEnricher as R}from"./enrichers/position-enricher.js";import{AccessibilityEnricher as v}from"./enrichers/accessibility-enricher.js";import{PageStateEnricher as j}from"./enrichers/page-state-enricher.js";import{DOMEnricher as q}from"./enrichers/dom-enricher.js";import{MCPRefEnricher as B}from"./mcp-ref-enricher.js";import{TraceTextEnricher as G}from"./trace-text-enricher.js";import{EnrichmentPipeline as i}from"./pipeline.js";import{PositionEnricher as s}from"./enrichers/position-enricher.js";import{AccessibilityEnricher as n}from"./enrichers/accessibility-enricher.js";import{PageStateEnricher as o}from"./enrichers/page-state-enricher.js";import{DOMEnricher as a}from"./enrichers/dom-enricher.js";import{MCPRefEnricher as m}from"./mcp-ref-enricher.js";import{TraceTextEnricher as l}from"./trace-text-enricher.js";function b(e={}){const r=new i(e);return e.enableMCPRef!==!1&&r.register(new m(e)),e.enableTraceText!==!1&&r.register(new l(e)),e.enableAccessibility!==!1&&r.register(new n(e)),e.enablePageState!==!1&&r.register(new o(e)),e.enablePosition!==!1&&r.register(new s(e)),e.enableDOM!==!1&&r.register(new a(e)),r}function u(e={}){const r=new i(e);return r.register(new n(e)),r.register(new o(e)),r}function M(e,r={}){const t=new i(r);for(const p of e)t.register(p);return t}export{v as AccessibilityEnricher,q as DOMEnricher,A as EnrichmentPipeline,D as EventEnricher,B as MCPRefEnricher,j as PageStateEnricher,R as PositionEnricher,G as TraceTextEnricher,M as createCustomPipeline,b as createDefaultPipeline,u as createMinimalPipeline};
@@ -0,0 +1 @@
1
+ import{createDefaultPipeline as l,createMinimalPipeline as p}from"./index.js";import{readFileSync as u,writeFileSync as s}from"fs";import{join as o}from"path";async function m(r,e={}){const n=o(r,"events.json"),c=o(r,"trace.zip");try{const t=JSON.parse(u(n,"utf-8")),i=t.map(h=>({...h,_enrichmentNote:"Full enrichment requires live Playwright access. Use EnrichmentPipeline during test execution."})),a=`${n}.backup`;return s(a,JSON.stringify(t,null,2)),s(n,JSON.stringify(i,null,2)),{enrichedCount:i.length,skippedCount:0,errors:[]}}catch(t){return console.error("[EnrichmentIntegration] Failed to enrich events:",t.message),{enrichedCount:0,skippedCount:0,errors:[t.message]}}}class v{constructor(e={}){this.pipeline=e.minimal?p(e):l(e),this.events=[],this.config=e}async recordEvent(e,n,c){const t={id:this.events.length,type:e,timestamp:new Date().toISOString(),data:n},i=await this.pipeline.enrich(t,{...c,event:t});return this.events.push(i),i}saveEvents(e){s(e,JSON.stringify(this.events,null,2)),console.log(`[LiveEnrichment] Saved ${this.events.length} enriched events to ${e}`),this.pipeline.logStatus()}getStats(){return this.pipeline.getStats()}}var y={enrichRecordedEvents:m,LiveEnrichmentRecorder:v};export{v as LiveEnrichmentRecorder,y as default,m as enrichRecordedEvents};
@@ -0,0 +1 @@
1
+ import{EventEnricher as u}from"./base.js";class p extends u{constructor(r={}){super(r),this.priority=200}getName(){return"MCPRef"}getPriority(){return this.priority}async enrich(r,n){const i=r.data?.params?.ref,a=r.data?.params?.element;if(!i&&!a)return null;let l=null,o=null,c=null;if(n?.element)try{const e=await n.element.evaluate(t=>({text:t.textContent?.trim()||"",innerText:t.innerText?.trim()||"",value:t.value||"",label:t.getAttribute("aria-label")||t.getAttribute("label")||"",role:t.getAttribute("role")||t.tagName.toLowerCase(),placeholder:t.getAttribute("placeholder")||"",title:t.getAttribute("title")||""}));l=e.text||e.innerText||e.value||e.placeholder,o=e.role,c=e.label||e.title,console.log(`[MCPRefEnricher] \u2705 Captured actual text: "${l}" (AI said: "${a}")`)}catch(e){console.log(`[MCPRefEnricher] \u26A0\uFE0F Could not extract actual text: ${e.message}`)}return{mcpRef:i,mcpElement:a,actualText:l,actualRole:o,actualLabel:c,recordedSelector:l||a}}}export{p as MCPRefEnricher};
@@ -0,0 +1,3 @@
1
+ class l{constructor(e={}){this.enrichers=[],this.config=e,this.stats={totalEvents:0,enrichedEvents:0,skippedEvents:0,errors:{}}}register(e){return this.enrichers.push(e),this.enrichers.sort((t,s)=>s.getPriority()-t.getPriority()),this}unregister(e){return this.enrichers=this.enrichers.filter(t=>t.getName()!==e),this}get(e){return this.enrichers.find(t=>t.getName()===e)}setEnabled(e,t){const s=this.get(e);return s&&(s.enabled=t),this}async enrich(e,t){this.stats.totalEvents++;const s={...e},n=[],i=[],h=[];for(const r of this.enrichers)try{if(!r.canEnrich(t)){i.push(r.getName());continue}const o=Date.now(),c=await r.enrich(e,t),a=Date.now()-o;c?(Object.assign(s,c),n.push({name:r.getName(),duration:a})):i.push(r.getName())}catch(o){console.warn(`[EnrichmentPipeline] ${r.getName()} failed:`,o.message),h.push(r.getName()),this.stats.errors[r.getName()]=(this.stats.errors[r.getName()]||0)+1}return s._enrichment={version:"1.0",timestamp:new Date().toISOString(),enrichers:{run:n,skipped:i,failed:h}},n.length>0?this.stats.enrichedEvents++:this.stats.skippedEvents++,s}async enrichBatch(e,t){const s=[];for(const n of e){const i=await this.enrich(n,t);s.push(i)}return s}getStats(){return{...this.stats,enrichers:this.enrichers.map(e=>({name:e.getName(),enabled:e.enabled,priority:e.getPriority(),errors:this.stats.errors[e.getName()]||0}))}}resetStats(){this.stats={totalEvents:0,enrichedEvents:0,skippedEvents:0,errors:{}}}logStatus(){console.log(`
2
+ \u{1F4CA} Enrichment Pipeline Status:`),console.log(` Total events: ${this.stats.totalEvents}`),console.log(` Enriched: ${this.stats.enrichedEvents}`),console.log(` Skipped: ${this.stats.skippedEvents}`),console.log(`
3
+ Registered enrichers (${this.enrichers.length}):`);for(const e of this.enrichers){const t=e.enabled?"\u2713":"\u2717",s=this.stats.errors[e.getName()]||0,n=s>0?` (${s} errors)`:"";console.log(` ${t} ${e.getName()} (priority: ${e.getPriority()})${n}`)}console.log()}}var p=l;export{l as EnrichmentPipeline,p as default};
@@ -0,0 +1 @@
1
+ import{EventEnricher as s}from"./base.js";import{TraceParser as u}from"../utils/trace-parser.js";import{existsSync as h}from"fs";import{join as l}from"path";class d extends s{constructor(t={}){super(t),this.priority=190,this.traceData=null}getName(){return"TraceText"}getPriority(){return this.priority}async loadTrace(t){if(this.traceData)return;const c=l(t,"traces"),a=l(t,"trace.zip");if(h(a))try{this.traceData=await u.parseTraceZip(a),console.log(`[TraceTextEnricher] \u2705 Loaded trace with ${this.traceData.length} actions`)}catch(r){console.log(`[TraceTextEnricher] \u26A0\uFE0F Failed to parse trace: ${r.message}`)}}async enrich(t,c){const a=t.data?.params?.ref,r=t.id;if(a===void 0&&r===void 0||(!this.traceData&&c.sessionPath&&await this.loadTrace(c.sessionPath),!this.traceData))return null;const e=this.traceData[r];if(!e)return console.log(`[TraceTextEnricher] \u26A0\uFE0F No trace action for event ${r}`),null;const n=e.actualText||this._extractTextFromSelector(e.selector),i=e.actualRole,o=e.actualAriaLabel;return n||i||o?(console.log(`[TraceTextEnricher] \u2705 Event ${r}: text="${n}", role="${i}", label="${o}"`),{traceActualText:n,traceActualRole:i,traceActualAriaLabel:o,traceSelector:e.selector,traceStrategies:e.strategies}):null}_extractTextFromSelector(t){if(!t)return null;const c=t.match(/internal:label="([^"]+)"/);if(c)return c[1];const a=t.match(/internal:text="([^"]+)"/);if(a)return a[1];const r=t.match(/getByText\(['"]([^'"]+)['"]\)/);if(r)return r[1];const e=t.match(/name:\s*['"]([^'"]+)['"]/);return e?e[1]:null}}export{d as TraceTextEnricher};
@@ -0,0 +1,5 @@
1
+ import{AgentStrategy as I}from"./base.js";import{logger as E}from"../../utils/logger.js";import{DEFAULT_MODELS as N}from"../../constants.js";import{OpenAICompletionProvider as O,OpenAIToolProvider as _}from"./providers/index.js";import{McpClientManager as M}from"../mcp-client.js";import{getSkill as T}from"../skill-registry.js";import{resolveAssistantAuth as A}from"./utils/auth-resolver.js";import{runAssistantRound as B}from"./middleware/assistant-round-pipeline.js";const L=N.ASSISTANT,j=15,w="get_skill_context";function h(i){!i||typeof i!="object"||(i.type==="object"&&i.properties&&(i.required=Object.keys(i.properties),i.additionalProperties=!1,Object.values(i.properties).forEach(h)),i.type==="array"&&i.items&&h(i.items),i.anyOf&&i.anyOf.forEach(h),i.oneOf&&i.oneOf.forEach(h),i.allOf&&i.allOf.forEach(h))}const v={maxBytes:49e3,systemMaxChars:12e3},y=()=>process.env.ZIBBY_VERBOSE==="true"||process.env.ZIBBY_DEBUG==="true",R=i=>Buffer.byteLength(JSON.stringify(i),"utf8");function b(i){return Array.isArray(i)?new Set(i.map(e=>String(e||"").trim()).filter(Boolean)):new Set}function D(i){return Array.isArray(i)?i.map(e=>String(e||"").trim()).filter(Boolean):[]}class K extends I{#e;#t;#o=new M;constructor(e=null){super("assistant","Zibby Assistant",200),e&&typeof e=="object"&&(e.toolProvider||e.completionProvider)?(this.#e=e.toolProvider||new _,this.#t=e.completionProvider||new O):(this.#e=e||new _,this.#t=new O)}canHandle(e){return A().ok}async invoke(e,t={}){const n=t.model&&t.model!=="auto"?t.model:L,s=A();if(!s.ok)throw s.reason==="missing_session_token"?new Error("Login required. Run `zibby login` to authenticate."):s.reason==="missing_openai_api_key"?new Error("Missing OPENAI_API_KEY for BYOK mode."):s.reason==="missing_openai_proxy_url"?new Error("Missing OPENAI_PROXY_URL for local mode."):new Error(`Assistant auth unavailable (${s.reason}).`);const o=t.messages||[{role:"user",content:e}],c=s.baseUrl,r=y();if(r?await this.#g(o,n,c,s.tokenPreview||"none"):E.debug(`[Assistant] ${c} | model: ${n} | messages: ${o.length}`),t.schema)return this.#c(n,o,s,t);const a=t.activeSkills||[],l=this.#f(t),m=this.#u(a,l),d=this.#d(m),g=this.#m(t),p={...t,payloadCompaction:g},$={activeSkills:m,options:p,executionRegistry:d,capabilityPolicy:l},P=!!t.stream,S={model:n,messages:[...o],stream:!1};this.#n(S,m,l);for(let x=0;x<j;x++){if(t.signal?.aborted)throw new Error("Aborted");const k=await B({body:S,auth:s,options:p,streaming:P,toolContext:$,activeSkills:m,round:x,verbose:r,dependencies:{fetchCompletion:this.#r.bind(this),fetchStreamingCompletion:this.#a.bind(this),onFallbackLog:(f,u)=>{y()&&console.log(`413 fallback: messages ${f.messages.length} -> ${u.messages.length}, bytes=${R(u)}`)},hasToolCalls:f=>this.#e.hasToolCalls(f),getTextContent:f=>this.#e.getTextContent(f),parseToolCalls:f=>this.#e.parseToolCalls(f),buildAssistantMessage:f=>this.#e.buildAssistantMessage(f),buildToolResultMessage:(f,u)=>this.#e.buildToolResultMessage(f,u),executeTool:(f,u)=>this.#l(f,u),onToolCallLog:async f=>{const u=(await import("chalk")).default;console.log(u.dim(` ${f.map(C=>`${C.name}(${JSON.stringify(C.args).slice(0,80)})`).join(", ")}`))},injectTools:(f,u)=>this.#n(f,u,l)},config:{maxToolResultChars:t.maxToolResultChars||3e3}});if(k.done)return k.text;S.messages=k.body.messages,k.body.tools?S.tools=k.body.tools:delete S.tools}return"I hit my tool-calling limit for this turn. Please try again."}async cleanup(){await this.#o.stopAll()}#n(e,t,n=null){const s=this.#i(t,n),o=this.#e.formatTools(s);this.#e.injectToolsIntoBody(e,o)}#i(e,t=null){const n=[],s=new Set;for(const o of e){const c=T(o);if(c?.tools?.length)for(const r of c.tools)this.#s(r.name,t)&&(s.has(r.name)||(s.add(r.name),n.push({name:r.name,description:r.description,parameters:r.parameters||r.input_schema||{type:"object",properties:{}}})))}return!t?.disableSkillContextTool&&this.#s(w,t)&&n.push({name:w,description:"Fetch full prompt guidance/instructions for one installed skill on demand. Use this before making complex tool decisions if guidance is needed.",parameters:{type:"object",properties:{skillId:{type:"string",description:"Installed skill id to inspect (e.g. jira, github, runner, chat-memory)"}},required:["skillId"]}}),n}async#l(e,t){const{activeSkills:n,options:s,executionRegistry:o,capabilityPolicy:c}=t;if(!this.#s(e.name,c))return`Tool "${e.name}" blocked by policy`;if(e.name===w){const l=String(e.args?.skillId||"").trim();if(!l)return JSON.stringify({error:"skillId is required"});if(!n.includes(l))return JSON.stringify({error:`Skill "${l}" is not active`,activeSkills:n});const m=T(l);if(!m)return JSON.stringify({error:`Skill "${l}" not found`});const d=typeof m.promptFragment=="function"?m.promptFragment():m.promptFragment||"",g=(m.tools||[]).map($=>$.name),p=JSON.stringify({skillId:l,description:m.description||"",toolNames:g,promptFragment:d||""});return y()&&(console.log(`
2
+ \u{1F4D6} get_skill_context("${l}") \u2192 ${p.length} chars (fragment: ${d.length} chars)`),console.log(` tools: [${g.join(", ")}]`),console.log(` fragment preview: ${d.slice(0,200).replace(/\n/g,"\\n")}\u2026
3
+ `)),p}const r=o?.get(e.name)||null;if(!r)return`Unknown tool: ${e.name}`;const a=T(r.skillId);if(!a)return`Skill "${r.skillId}" not found for tool "${e.name}"`;if(r.mode==="handler")try{return a.handleToolCall(e.name,e.args,t)}catch(l){return`Error in ${e.name}: ${l.message}`}if(r.mode==="mcp")try{if(!this.#o.isRunning(a.serverName)){const m=a.resolve(s);if(!m)return`Skill "${r.skillId}" is not available (cannot start server)`;await this.#o.ensureServer(a.serverName,m)}const l=await this.#o.callTool(a.serverName,e.name,e.args);return l.text||(l.isError?"Tool call failed":"Done")}catch(l){return`MCP error (${a.serverName}): ${l.message}`}return`Skill "${r.skillId}" owns tool "${e.name}" but has no execution mode`}async#a(e,t,n){return this.#t.fetchStreamingCompletion(e,t,{...n,onBudget:({beforeBytes:s,meta:o})=>{y()&&console.log(`payload bytes (stream) before=${s} after=${o.bytes} trimmed=${o.trimmed} messages=${o.messageCount}`)}})}async#r(e,t,n){return this.#t.fetchCompletion(e,t,{...n,onBudget:({beforeBytes:s,meta:o})=>{y()&&console.log(`payload bytes before=${s} after=${o.bytes} trimmed=${o.trimmed} messages=${o.messageCount}`)}})}async#c(e,t,n,s){const{zodToJsonSchema:o}=await import("zod-to-json-schema"),c=typeof s.schema?.parse=="function",r=c?o(s.schema):s.schema;delete r.$schema,h(r);const a={model:e,messages:t,stream:!1,response_format:{type:"json_schema",json_schema:{name:"extract",schema:r,strict:!0}}},l=await this.#r(a,n,s),m=this.#e.getTextContent(l),d=JSON.parse(m),g=c?s.schema.parse(d):d;return{raw:m,structured:g}}#m(e={}){const t=e?.config?.agent?.assistant?.payloadCompaction||{};return{maxBytes:Number(t.maxBytes||e.maxPayloadBytes||v.maxBytes),systemMaxChars:Number(t.systemMaxChars||v.systemMaxChars)}}#f(e={}){const t=e?.config?.agent?.assistant?.toolPolicy||{};return{allowTools:b(t.allowTools||e.allowTools),denyTools:b(t.denyTools||e.denyTools),denyPrefixes:D(t.denyPrefixes||e.denyToolPrefixes),includeSkills:b(t.includeSkills||e.includeSkills),excludeSkills:b(t.excludeSkills||e.excludeSkills),disableSkillContextTool:!!(t.disableSkillContextTool||e.disableSkillContextTool)}}#u(e,t){const n=t?.includeSkills||new Set,s=t?.excludeSkills||new Set;return n.size===0&&s.size===0?e:e.filter(o=>!(n.size>0&&!n.has(o)||s.has(o)))}#s(e,t){const n=String(e||"").trim();if(!n)return!1;const s=t?.allowTools;if(s&&s.size>0&&!s.has(n))return!1;const o=t?.denyTools;return!(o&&o.has(n)||(t?.denyPrefixes||[]).some(r=>n.startsWith(r)))}#d(e){const t=new Map,n=[];for(const s of e){const o=T(s);if(!o?.tools?.length)continue;const c=typeof o.handleToolCall=="function"?"handler":o.serverName&&typeof o.resolve=="function"?"mcp":null;if(c)for(const r of o.tools){const a=String(r?.name||"").trim();if(a){if(t.has(a)){n.push({tool:a,winner:t.get(a).skillId,skipped:s});continue}t.set(a,{skillId:s,mode:c})}}}if(n.length>0&&y()){const s=n.slice(0,5).map(o=>`${o.tool}:${o.winner}>${o.skipped}`).join(", ");console.log(`tool registry collisions: ${s}${n.length>5?" ...":""}`)}return t}async#g(e,t,n,s){console.log(`
4
+ \u25C6 Model: ${t} | proxy: ${n} | token: ${s||"none"}
5
+ `);const o=(await import("chalk")).default;console.log(o.bold("Prompt sent to LLM:")),console.log(o.dim("\u2500".repeat(60)));let c=!1;for(const r of e)if(r.role==="system")console.log(o.dim(`[System] ${r.content||""}`));else{c||(console.log(o.dim("\u2500\u2500\u2500 chat history \u2500\u2500\u2500")),c=!0);const a=r.role==="user"?"Human":"AI",l=r.content?.length>200?`${r.content.slice(0,200)}...`:r.content||"";console.log(o.dim(`[${a}] ${l}`))}console.log(o.dim("\u2500".repeat(60)))}}export{K as AssistantStrategy};
@@ -0,0 +1 @@
1
+ class n{constructor(t,e,r=0){this.name=t,this.description=e,this.priority=r}async invoke(t,e={}){throw new Error("AgentStrategy.invoke() must be implemented by subclass")}canHandle(t){throw new Error("AgentStrategy.canHandle() must be implemented by subclass")}getName(){return this.name}getDescription(){return this.description}getPriority(){return this.priority}}var s=n;export{n as AgentStrategy,s as default};
@@ -0,0 +1,4 @@
1
+ import{AgentStrategy as I}from"./base.js";import{query as P}from"@anthropic-ai/claude-agent-sdk";import{zodToJsonSchema as J}from"zod-to-json-schema";import{logger as r}from"../../utils/logger.js";import{timeline as b}from"../../utils/timeline.js";import{DEFAULT_MODELS as M,CLAUDE_MODEL_MAP as O}from"../../constants.js";import{getSkill as K}from"../skill-registry.js";class z extends I{constructor(){super("claude","Claude (Anthropic API)",50)}canHandle(o){const u=!!process.env.ANTHROPIC_API_KEY;return u||r.debug("ClaudeAgentStrategy: ANTHROPIC_API_KEY not set"),u}async invoke(o,u={}){const{model:g,workspace:n=process.cwd(),schema:s=null,images:l=[],skills:d=null,sessionPath:C=null,nodeName:v=null,timeout:R,config:q={}}=u;let a=g;(!a||a==="auto")&&(r.debug(`Model is '${a||"undefined"}', using default: ${M.CLAUDE}`),a=M.CLAUDE);const m=O[a]||a;O[a]&&a!==m&&r.debug(`Mapped model: ${a} \u2192 ${m}`),r.debug(`Invoking Claude Agent SDK with model: ${m}, skills: ${JSON.stringify(d)}`);const S=process.env.ANTHROPIC_API_KEY,E=S?` | key: ***${S.slice(-4)}`:" | key: not set";console.log(`
2
+ \u25C6 Model: ${m}${E}
3
+ `);const f=(await import("chalk")).default;console.log(`
4
+ ${f.bold("Prompt sent to LLM:")}`),console.log(f.dim("\u2500".repeat(60))),console.log(f.dim(o)),console.log(f.dim("\u2500".repeat(60)));const{allowedTools:w,mcpServers:A}=this._resolveSkills(d,{sessionPath:C,workspace:n,nodeName:v});try{const c={cwd:n,allowedTools:w,permissionMode:"bypassPermissions",model:m,...Object.keys(A).length>0&&{mcpServers:A}};if(s){const y=typeof s.parse=="function"?J(s,{target:"openApi3"}):s;c.outputFormat={type:"json_schema",schema:y},r.debug("Structured output enforced via SDK outputFormat")}r.debug(`Agent SDK options: ${JSON.stringify({cwd:c.cwd,toolCount:w.length,permissionMode:c.permissionMode,model:c.model,hasOutputFormat:!!c.outputFormat})}`);let p="",N=0;const _=[];r.debug("Starting Claude Agent SDK query stream");let $;try{$=P({prompt:o,options:c})}catch(e){throw r.error(`Failed to initialize Claude Agent SDK: ${e.message}`),e}let k=null,h=0;const x=3;try{for await(const e of $){if(_.push(e),e.type==="error"||e.error){const i=e.error?.message||e.error||e.message||"Unknown API error";throw new Error(typeof i=="string"?i:JSON.stringify(i))}const y=JSON.stringify(e.message?.content||e.text||"").slice(0,200);if(y===k){if(h++,h>=x){const i=(e.message?.content?.[0]?.text||e.text||"unknown").slice(0,100);throw new Error(`API stuck in loop (${h}x repeated): ${i}`)}}else k=y,h=1;if(e.type==="assistant"||e.constructor?.name==="AssistantMessage"){const i=e.message?.content||e.content||[];for(const t of i)if(t.type==="thinking"&&t.thinking)console.log(`${t.thinking.substring(0,200)}${t.thinking.length>200?"...":""}`);else if(t.type==="text"&&t.text)p+=t.text,t.text.length<500?console.log(`${t.text}`):console.log(`${t.text.substring(0,200)}... (${t.text.length} chars)`);else if(t.type==="tool_use"){N++,t.name.includes("memory")?b.stepMemory(`Tool: ${t.name}`):b.stepTool(`Tool: ${t.name}`);const D=JSON.stringify(t.input).substring(0,100);console.log(` Input: ${D}${JSON.stringify(t.input).length>100?"...":""}`)}}else if(!(e.type==="user"&&e.tool_use_result)){if(e.type==="result"||e.constructor?.name==="ResultMessage"){const i=e.result||e.text||e.content||p;if(s){if(e.structured_output){r.debug("Using SDK native structured_output");const T=typeof s.parse=="function"?s.parse(e.structured_output):e.structured_output;return{raw:i,structured:T}}if(i){const t=this._extractJson(i,s);if(t)return{raw:i,structured:t}}r.warn(`Could not extract structured output \u2014 returning raw text (${(i||"").length} chars)`)}return i||""}}}if(r.warn(`Agent SDK ended without result. Collected ${_.length} messages`),p.length>0)return r.debug("Returning accumulated text from messages"),p;throw new Error("Claude Agent SDK query ended without result")}catch(e){throw r.error(`Error during query stream: ${e.message}`),e}}catch(c){throw r.error("Claude Agent SDK call failed",{error:c.message}),c}}_resolveSkills(o,u){if(o===null)return r.debug("No skills \u2014 pure LLM mode"),{allowedTools:[],mcpServers:{}};if(!Array.isArray(o)||o.length===0)return r.debug("Default IDE skills for code generation"),{allowedTools:["Read","Write","Bash","Grep","Glob"],mcpServers:{}};const g=[],n={};for(const s of o){const l=K(s);if(!l){r.warn(`Unknown skill "${s}" \u2014 skipping`);continue}if(l.allowedTools&&g.push(...l.allowedTools),typeof l.resolve=="function"){const d=l.resolve(u);d&&(n[l.serverName]=d,r.debug(`MCP: ${l.serverName} \u2192 ${d.command} ${d.args[0]}`))}}return{allowedTools:g,mcpServers:n}}_extractJson(o,u){const g=[()=>{if(o.includes("===JSON_START===")){const n=o.indexOf("===JSON_START===")+16,s=o.indexOf("===JSON_END===");return o.substring(n,s).trim()}},()=>o.match(/```json\s*\n([\s\S]*?)\n```/)?.[1]?.trim(),()=>{if(!o.startsWith("{"))return o.match(/```\s*\n([\s\S]*?)\n```/)?.[1]?.trim()},()=>o.trim(),()=>{const n=o.indexOf("{"),s=o.lastIndexOf("}");if(n!==-1&&s>n)return o.substring(n,s+1)}];for(const n of g)try{const s=n();if(!s)continue;const l=JSON.parse(s);if(typeof l!="object"||l===null)continue;return typeof u.parse=="function"?u.parse(l):l}catch{}return null}}export{z as ClaudeAgentStrategy};
@@ -0,0 +1,4 @@
1
+ import{AgentStrategy as K}from"./base.js";import{execSync as M}from"child_process";import{zodToJsonSchema as N}from"zod-to-json-schema";import{logger as e}from"../../utils/logger.js";import{timeline as k}from"../../utils/timeline.js";import{DEFAULT_MODELS as A,CODEX_MODEL_MAP as w}from"../../constants.js";import{getSkill as T}from"../skill-registry.js";class R extends K{constructor(){super("codex","Codex (OpenAI)",75)}canHandle(i){if(!!!(process.env.OPENAI_API_KEY||process.env.CODEX_API_KEY))return e.debug("CodexAgentStrategy: OPENAI_API_KEY or CODEX_API_KEY not set"),!1;try{return M("codex --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return e.warn("[Codex] codex CLI not found. Install: npm install -g @openai/codex"),!1}}async invoke(i,p={}){const{model:f,workspace:a=process.cwd(),schema:o=null,skills:t=null,sessionPath:v=null,nodeName:d=null,timeout:X,config:j={}}=p,{Codex:I}=await import("@openai/codex-sdk");let s=f;(!s||s==="auto")&&(e.debug(`Model is '${s||"undefined"}', using default: ${A.CODEX}`),s=A.CODEX);const x=w[s]||s;w[s]&&s!==x&&e.debug(`Mapped model: ${s} \u2192 ${x}`),e.debug(`Invoking Codex SDK with model: ${x}, skills: ${JSON.stringify(t)}`);const h=process.env.CODEX_API_KEY||process.env.OPENAI_API_KEY;h&&!process.env.CODEX_API_KEY&&(process.env.CODEX_API_KEY=h);const b=h?` | key: ***${h.slice(-4)}`:" | key: not set";console.log(`
2
+ \u25C6 Model: ${x}${b}
3
+ `);const C=(await import("chalk")).default;console.log(`
4
+ ${C.bold("Prompt sent to LLM:")}`),console.log(C.dim("\u2500".repeat(60))),console.log(C.dim(i)),console.log(C.dim("\u2500".repeat(60)));const _=this._resolveSkillsToMcp(t,{sessionPath:v,workspace:a,nodeName:d}),y={};Object.keys(_).length>0&&(y.mcp_servers=_,e.debug(`[Codex] MCP servers: ${Object.keys(_).join(", ")}`));const P=new I({...Object.keys(y).length>0&&{config:y}}).startThread({workingDirectory:a,skipGitRepoCheck:!0,approvalPolicy:"never",sandboxMode:"danger-full-access",networkAccessEnabled:!0}),S=o&&typeof o.parse=="function",O={};if(o)try{const r=S?N(o,{target:"openAi"}):o;O.outputSchema=r,e.debug("Structured output via SDK outputSchema")}catch(r){e.warn(`[Codex] Schema conversion failed, will extract from text: ${r.message}`)}try{const{events:r}=await P.runStreamed(i,O);let g=0,n="";for await(const l of r){const u=l.type;if(u==="item.completed"){const c=l.item,m=c?.type;if(m==="mcp_tool_call"){g++;const $=`${c.server}/${c.tool}`;if(k.stepTool(`Tool: ${$}`),c.arguments){const E=JSON.stringify(c.arguments),D=E.length>100?`${E.substring(0,100)}...`:E;console.log(` Input: ${D}`)}}else if(m==="tool_call"||m==="function_call"||m==="command_execution"){g++;const $=c.name||c.tool||c.command||"unknown";k.stepTool(`Tool: ${$}`)}else m==="agent_message"&&(n=c.text||"",n.length<500?console.log(n):console.log(`${n.substring(0,200)}... (${n.length} chars)`))}else u==="turn.completed"?e.debug(`[Codex] Turn completed. Usage: ${JSON.stringify(l.usage||{})}`):e.debug(`[Codex] Event: ${u} ${JSON.stringify(l).slice(0,300)}`)}if(e.debug(`[Codex] Last agent message (${n.length} chars): ${n.slice(0,500)}`),o){if(!n)throw new Error("Codex agent returned no response");const l=JSON.parse(n),u=S?o.parse(l):l;return e.debug("\u2705 [Codex] Structured output validated"),{raw:n,structured:u}}return n||""}catch(r){const g=r.message||String(r);throw e.error(`\u274C [Codex] SDK call failed: ${g}`),g.includes("exited with code")&&(e.error("\u{1F4A1} [Codex] Verify: codex --version && echo $OPENAI_API_KEY"),e.error("\u{1F4A1} [Codex] If codex is missing: npm install -g @openai/codex")),r}}_resolveSkillsToMcp(i,p={}){if(!Array.isArray(i)||i.length===0)return{};const f={};for(const a of i){const o=T(a);if(!o){e.warn(`[Codex] Unknown skill "${a}" \u2014 skipping`);continue}if(typeof o.resolve!="function")continue;const t=o.resolve(p);if(!t)continue;const v=o.serverName||a,d={command:t.command};t.args?.length&&(d.args=t.args),t.env&&Object.keys(t.env).length>0&&(d.env=t.env),f[v]=d,e.debug(`[Codex] MCP: ${v} \u2192 ${t.command} ${(t.args||[]).join(" ")}`)}return f}}export{R as CodexAgentStrategy};
@@ -0,0 +1,32 @@
1
+ import{AgentStrategy as Y}from"./base.js";import{spawn as q,execSync as N}from"child_process";import{writeFileSync as j,readFileSync as J,mkdirSync as z,existsSync as H,accessSync as B,constants as W,unlinkSync as V}from"fs";import{join as C,resolve as X}from"path";import{homedir as D}from"os";import{logger as t}from"../../utils/logger.js";import{DEFAULT_MODELS as Q,TIMEOUTS as ee}from"../../constants.js";import{DEFAULT_OUTPUT_BASE as te,SESSION_INFO_FILE as re,STUDIO_STOP_REQUEST_FILE as oe}from"../constants.js";import{getAllSkills as ne,getSkill as Z}from"../skill-registry.js";import{StreamingParser as se}from"../../utils/streaming-parser.js";import{StructuredOutputFormatter as ie}from"./utils/structured-output-formatter.js";import{formatWithOpenAIProxy as le}from"./utils/openai-proxy-formatter.js";import{timeline as G}from"../../utils/timeline.js";import{shouldUseIsolatedCursorMcpHome as ae,createIsolatedCursorAgentHome as ue,removeIsolatedCursorAgentHome as ce}from"../../utils/cursor-mcp-isolated-home.js";class Ee extends Y{constructor(){super("cursor","Cursor (CLI)",100)}canHandle(s){const l=[C(D(),".local","bin","cursor-agent"),C(D(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"];for(const r of l)try{if(r.startsWith("/")){B(r,W.X_OK);const f=N(`"${r}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(f&&f.length>0)return t.debug(`[Cursor] Found agent at: ${r} (version: ${f.trim().slice(0,50)})`),!0}else{const f=N(`which ${r}`,{encoding:"utf-8",timeout:2e3,stdio:"pipe"}).trim();if(!f)continue;const a=N(`${r} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});if(a&&a.length>0)return t.debug(`[Cursor] Found '${r}' in PATH at ${f} (version: ${a.trim().slice(0,50)})`),!0}}catch{continue}return t.warn("[Cursor] \u274C Cursor Agent CLI not found or not working. Run: agent --version"),!1}async invoke(s,l={}){const{workspace:r=process.cwd(),print:f=!1,schema:a=null,skills:b=null,sessionPath:u=null,nodeName:g=null,timeout:m=ee.CURSOR_AGENT_DEFAULT,config:h={}}=l,$=h?.agent?.strictMode||!1,v=l.model??h?.agent?.cursor?.model??Q.CURSOR;t.debug(`[Cursor] Invoking (model: ${v}, timeout: ${m/1e3}s, skills: ${JSON.stringify(b)})`);const E=(this._setupMcpConfig(u,r,h,b,g)||{}).isolatedMcpHome??null,S=[C(D(),".local","bin","cursor-agent"),C(D(),".cursor","bin","cursor-agent"),"/usr/local/bin/cursor-agent","/usr/local/bin/agent","/Applications/Cursor.app/Contents/Resources/app/bin/cursor","agent","cursor-agent"];let n=null;for(const c of S)try{if(c.startsWith("/"))B(c,W.X_OK),N(`"${c}" --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"});else{if(!N(`which ${c}`,{encoding:"utf-8",timeout:2e3}).trim())throw new Error("not in PATH");N(`${c} --version 2>&1`,{encoding:"utf-8",timeout:3e3,stdio:"pipe"})}n=c,t.debug(`[Agent] Using binary: ${c}`);break}catch(w){t.debug(`[Agent] Binary '${c}' check failed: ${w.message}`);continue}if(!n)throw new Error(`Cursor Agent CLI not found or not working.
2
+
3
+ Checked paths:
4
+ ${S.map(c=>` - ${c}`).join(`
5
+ `)}
6
+
7
+ Install cursor-agent:
8
+ curl https://cursor.com/install -fsS | bash
9
+
10
+ Then add to PATH:
11
+ echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc
12
+
13
+ Test with: agent --version`);let y=null;if(a){const c=`zibby-result-${Date.now()}.json`;y=C(r,".zibby","tmp",c);const w=C(r,".zibby","tmp");H(w)||z(w,{recursive:!0});const T=ie.generateFileOutputInstructions(a,y);s=`${s}
14
+
15
+ ${T}`}const P=process.env.CURSOR_API_KEY,x=P?` | key: ***${P.slice(-4)}`:" | key: not set";console.log(`
16
+ \u25C6 Model: ${v||"auto"}${x}
17
+ `);const M=(await import("chalk")).default;console.log(`
18
+ ${M.bold("Prompt sent to LLM:")}`),console.log(M.dim("\u2500".repeat(60))),console.log(M.dim(s)),console.log(M.dim("\u2500".repeat(60)));const L=["--print","--force","--approve-mcps","--output-format","stream-json","--stream-partial-output","--model",v||"auto"];if(process.env.CURSOR_API_KEY&&L.push("--api-key",process.env.CURSOR_API_KEY),L.push(s),t.debug(`[Agent] Prompt: ${s.length} chars, model: ${v||"auto"}`),t.debug(`[Agent] Workspace: ${r}`),process.env.LOG_LEVEL==="debug"||process.env.ZIBBY_LOG_CURSOR_CLI==="1")try{console.log(`\u{1F527} Cursor CLI --model ${v||"auto"} (from .zibby.config.js agent.cursor.model)
19
+ `)}catch{}let _,o=null;try{const c=u||(process.env.ZIBBY_SESSION_PATH?String(process.env.ZIBBY_SESSION_PATH).trim():null);_=await this._spawnWithStreaming(n,L,r,m,null,c,E)}catch(c){o=c}const A=_?.stdout||"";if(a){const c=typeof a.parse=="function";let w=null;const T=!!(y&&H(y));if(y&&t.info(`[Agent] Result file: ${T?"present":"missing"} at ${y}`),T)try{const e=J(y,"utf-8").trim();w=JSON.parse(e),t.info(`[Agent] Parsed JSON from result file OK (${e.length} chars) \u2192 object ready for validation`),o&&t.debug("[Agent] Agent exited non-zero but result file was written \u2014 recovering")}catch(e){t.warn(`\u26A0\uFE0F [Agent] Result file exists on disk but is not valid JSON: ${e.message}`)}else if(o)t.warn(`[Agent] Result file missing at ${y} (agent process error \u2014 may still recover if strictMode repairs)`);else throw t.error(`\u274C [Agent] Result file was never created at ${y}`),new Error(`Agent did not write required result file at ${y}`);if(w&&c)try{const e=a.parse(w);return t.info("\u2705 [Agent] Zod validation passed for structured result file"),$&&t.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:A,structured:e}}catch(e){t.warn(`\u26A0\uFE0F [Agent] JSON parsed but Zod rejected it (wrong types/shape): ${e.message?.slice(0,400)}`)}else{if(w)return t.info("\u2705 [Agent] File-based output extracted (no Zod parse fn) \u2014 accepting as structured"),$&&t.debug("[Agent] strictMode enabled but not needed \u2014 agent wrote valid file"),{raw:A,structured:w};T&&t.error("\u274C [Agent] Result file exists but produced no in-memory JSON (parse failed earlier)")}if($&&!o){const e=_.parsedText,d=w?JSON.stringify(w):e;t.info(`[Agent] strictMode: calling OpenAI proxy to fix structured output (${d.length} chars in)`);const i=await le(d,a);if(c){const p=a.parse(i.structured);return t.info("\u2705 [Agent] Proxy output passed Zod validation"),{raw:A,structured:p}}return{raw:A,...i}}if(o)throw o;const k=T?w==null?"file existed but JSON.parse failed \u2014 see WARN log above":c?"JSON was valid but Zod validation failed \u2014 see WARN log above":"no structured object after read (unexpected)":"file never appeared (agent may not have run Write tool to the path above)";throw t.error(`\u274C [Agent] No validated structured output: ${k}`),t.error("\u{1F4A1} Tip: Set strictMode=true in .zibby.config.js for OpenAI proxy fallback"),new Error(`Agent did not produce a valid result file at ${y}. Enable strictMode for proxy fallback.`)}if(o)throw o;return this._extractFinalResult(A)||_?.parsedText||A}_extractFinalResult(s){if(!s)return null;const l=s.split(`
20
+ `);let r=null;for(const f of l){const a=f.trim();if(a)try{const b=JSON.parse(a);if(b.type==="assistant"&&b.message?.content){const u=b.message.content;if(Array.isArray(u)){const g=u.filter(m=>m.type==="text"&&m.text).map(m=>m.text).join("");g&&(r=g)}else typeof u=="string"&&u&&(r=u)}}catch{}}return r?.trim()||null}_setupMcpConfig(s,l,r,f=null,a=null){const b=r?.headless,u=C(D(),".cursor"),g=C(u,"mcp.json");let m={};if(H(g))try{m=JSON.parse(J(g,"utf-8"))}catch{}const h=m.mcpServers||{},$=r?.paths?.output||te,v=C(l||process.cwd(),$,re),I=Array.isArray(f)?f.map(n=>Z(n)).filter(Boolean):[...ne()].map(([,n])=>n),E=new Set;for(const n of I)typeof n.resolve=="function"&&(E.has(n.serverName)||(E.add(n.serverName),this._ensureSkillConfigured(h,n,s,v,a,b)));if(s){const n=Z("browser");n&&typeof n.resolve=="function"&&!E.has(n.serverName)&&this._ensureSkillConfigured(h,n,s,v,"execute_live",b)}if(Object.keys(h).length===0)return t.debug("[MCP] No MCP servers configured - agent will run without tool access"),{isolatedMcpHome:null};const S=`${JSON.stringify({mcpServers:h},null,2)}
21
+ `;if(ae(s)){const n=ue(l||process.cwd()),y=C(n,".cursor","mcp.json");return j(y,S,"utf8"),t.debug(`[MCP] Isolated cursor-agent HOME (session-scoped mcp.json): ${n} | servers: ${Object.keys(h).join(", ")}`),{isolatedMcpHome:n}}return H(u)||z(u,{recursive:!0}),j(g,S,"utf8"),t.debug(`[MCP] Global ~/.cursor/mcp.json | servers: ${Object.keys(h).join(", ")}`),{isolatedMcpHome:null}}_ensureSkillConfigured(s,l,r,f,a=null,b){const u=l.cursorKey||l.serverName,g=s[u]?u:s[l.serverName]?l.serverName:null;if(g&&r){const h=typeof l.resolve=="function"?l.resolve({sessionPath:r,nodeName:a,headless:b}):null;h?.args?s[g].args=h.args:s[g].args=(s[g].args||[]).map(I=>I.startsWith("--output-dir=")?`--output-dir=${r}`:I);const $=h?.env||{},v=l.sessionEnvKey?{[l.sessionEnvKey]:f}:{};s[g].env={...s[g].env||{},...$,...v},t.debug(`[MCP] Updated ${g} session \u2192 ${r}`);return}if(g)return;const m=l.resolve({sessionPath:r,nodeName:a,headless:b});m&&(s[u]={...m,...l.sessionEnvKey&&{env:{...m.env||{},[l.sessionEnvKey]:f}}},t.debug(`[MCP] Configured ${u}`))}_spawnWithStreaming(s,l,r,f,a=null,b=null,u=null){return new Promise((g,m)=>{const h=Date.now();let $="",v="",I=Date.now(),E=0,S=!1,n=null,y=!1,P=!1,x=null;if(b)try{x=C(X(String(b)),oe)}catch{x=null}let M=!1;const L=()=>{M||(M=!0,ce(u))},_={...process.env};u&&(_.HOME=u,process.platform==="win32"&&(_.USERPROFILE=u),t.debug(`[Agent] cursor-agent HOME=${u} (isolated MCP config)`));const o=q(s,l,{cwd:r,shell:!1,stdio:["pipe","pipe","pipe"],env:_});t.debug(`[Agent] PID: ${o.pid}`),o.stdin.on("error",e=>{e.code!=="EPIPE"&&t.warn(`[Agent] stdin error: ${e.message}`)}),o.stdout.on("error",e=>{e.code!=="EPIPE"&&t.warn(`[Agent] stdout error: ${e.message}`)}),o.stderr.on("error",e=>{e.code!=="EPIPE"&&t.warn(`[Agent] stderr error: ${e.message}`)}),a?(o.stdin.write(a,e=>{e&&e.code!=="EPIPE"&&t.warn(`[Agent] Failed to write to stdin: ${e.message}`),o.stdin.end()}),t.debug(`[Agent] Prompt also piped to stdin (${a.length} chars)`)):o.stdin.end();let A=null;x&&(A=setInterval(()=>{if(!(S||P))try{if(H(x)){S=!0,n="studio-stop";try{V(x)}catch{}t.warn("\u{1F6D1} Studio stop requested \u2014 terminating Cursor agent (and MCP browser session)"),o.kill("SIGTERM"),setTimeout(()=>{o.killed||o.kill("SIGKILL")},2e3)}}catch{}},600));const F=new Set,c=new Date(h).toISOString().replace(/\.\d+Z$/,""),w=setInterval(()=>{const e=Math.round((Date.now()-h)/1e3),d=Math.round((Date.now()-I)/1e3),i=[];try{const R=Math.ceil(e/60)+1,O=N(`find "${r}" -type f -mmin -${R} -not -path '*/node_modules/*' -not -path '*/.git/*' -not -path '*/target/*' 2>/dev/null | head -20`,{encoding:"utf-8",timeout:5e3}).trim();if(O)for(const U of O.split(`
22
+ `)){const K=U.replace(`${r}/`,"");F.has(K)||(F.add(K),i.push(K))}}catch{}let p="";i.length>0&&(p=` | \u{1F4C1} new: ${i.map(O=>O.split("/").pop()).join(", ")}`),F.size>0&&(p+=` | \u{1F4E6} total: ${F.size} files`),t.debug(`\u{1F493} [Agent] Running for ${e}s | ${E} lines output${p}`),E===0&&e>=30&&F.size===0&&(e<35&&t.warn(`\u26A0\uFE0F [Agent] No output after ${e}s \u2014 agent may be stuck. Check your CURSOR_API_KEY.`),e>=60&&(S=!0,n=n||"stall",t.error(`\u274C [Agent] No response after ${e}s \u2014 killing. Verify CURSOR_API_KEY is valid and agent CLI works: agent --version`),o.kill("SIGTERM"),setTimeout(()=>{o.killed||o.kill("SIGKILL")},3e3)))},3e4),T=setTimeout(()=>{S=!0,n=n||"timeout";const e=Math.round((Date.now()-h)/1e3);t.error(`\u23F1\uFE0F [Agent] Timeout after ${e}s \u2014 killing process (PID: ${o.pid})`),$.trim()&&t.warn(`\u{1F4E4} [Agent] Partial output (${$.length} chars) before timeout:
23
+ ${$.slice(-2e3)}`),o.kill("SIGTERM"),setTimeout(()=>{o.killed||o.kill("SIGKILL")},5e3)},f),k=new se;k.onToolCall=(e,d)=>{let i=e,p=d;if(e==="mcpToolCall"&&d?.name)i=d.name.replace(/^mcp_+[^_]+_+/,""),i.includes("-")&&i.split("-")[0]===i.split("-")[1]&&(i=i.split("-")[0]),p=d.args??d.input??d;else{if(e==="readToolCall"||e==="editToolCall"||e==="writeToolCall")return;(e.startsWith("mcp__")||e.includes("ToolCall"))&&(i=e.replace(/^mcp_+[^_]+_+/,"").replace(/ToolCall$/,""))}if(i.includes("memory")?G.stepMemory(`Tool: ${i}`):G.stepTool(`Tool: ${i}`),p!=null&&typeof p=="object"&&Object.keys(p).length>0&&!P){const O=JSON.stringify(p),U=O.length>100?`${O.substring(0,100)}...`:O;console.log(` Input: ${U}`)}},o.stdout.on("data",e=>{const d=e.toString();$+=d,I=Date.now(),y||(y=!0);const i=k.processChunk(d);i&&!P&&process.stdout.write(i);const p=d.split(`
24
+ `).filter(R=>R.trim());E+=p.length}),o.stderr.on("data",e=>{const d=e.toString();v+=d,I=Date.now(),y||(y=!0);const i=d.split(`
25
+ `).filter(p=>p.trim());for(const p of i)t.warn(`\u26A0\uFE0F [Agent stderr] ${p}`)}),o.on("close",(e,d)=>{P=!0,L(),clearTimeout(T),clearInterval(w),A&&clearInterval(A),k.flush();const i=Math.round((Date.now()-h)/1e3);if(t.debug(`[Agent] Exited: code=${e}, signal=${d}, elapsed=${i}s, output=${$.length} chars`),S){if(n==="studio-stop"){m(new Error("Stopped from Zibby Studio"));return}m(new Error(`Cursor Agent timed out after ${i}s (limit: ${f/1e3}s). ${E} lines produced. Last output ${Math.round((Date.now()-I)/1e3)}s ago. ${$.trim()?`
26
+ Partial output (last 500 chars):
27
+ ${$.slice(-500)}`:"No output captured."}`));return}if(e!==0){m(new Error(`Cursor Agent failed: exit code ${e}, signal ${d}. ${v.trim()?`
28
+ Stderr: ${v.slice(-1e3)}`:""}${$.trim()?`
29
+ Stdout (last 500 chars): ${$.slice(-500)}`:""}`));return}const p=k.getResult(),R=p?JSON.stringify(p,null,2):k.getRawText()||$||"";g({stdout:$||v||"",parsedText:R})}),o.on("error",e=>{L(),clearTimeout(T),clearInterval(w),A&&clearInterval(A),m(new Error(`Cursor Agent spawn error: ${e.message}
30
+ Binary: ${s}
31
+ This usually means the binary is not in PATH. Try:
32
+ echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc && source ~/.zshrc`))})})}}export{Ee as CursorAgentStrategy};
@@ -0,0 +1,11 @@
1
+ import{AgentStrategy as Y}from"./base.js";import{execSync as F,spawn as z}from"child_process";import{zodToJsonSchema as H}from"zod-to-json-schema";import{existsSync as C,mkdirSync as K,readFileSync as L,rmSync as q,writeFileSync as R}from"fs";import{join as G}from"path";import{logger as i}from"../../utils/logger.js";import{DEFAULT_MODELS as U,GEMINI_MODEL_MAP as W}from"../../constants.js";import{getSkill as Z}from"../skill-registry.js";import{StructuredOutputFormatter as B}from"./utils/structured-output-formatter.js";import{StreamingParser as Q}from"../../utils/streaming-parser.js";function V(g){if(!g)return null;const e=String(g),a=e.match(/```(?:json)?\s*([\s\S]*?)```/i);if(a?.[1])try{return JSON.parse(a[1].trim())}catch{}const l=e.indexOf("{");if(l<0)return null;let n=0,t=!1,r=!1,o=-1;for(let c=l;c<e.length;c++){const u=e[c];if(t){r?r=!1:u==="\\"?r=!0:u==='"'&&(t=!1);continue}if(u==='"'){t=!0;continue}if(u==="{"){n===0&&(o=c),n+=1;continue}if(u==="}"){if(n===0)continue;if(n-=1,n===0&&o>=0){const m=e.slice(o,c+1);try{return JSON.parse(m)}catch{o=-1}}}}return null}function X(g){const e=String(g||"").trim();if(!e)return null;try{return JSON.parse(e)}catch{return V(e)}}function ee(g){try{const e=JSON.parse(g);if(typeof e=="string")return e;if(typeof e?.response=="string")return e.response;if(typeof e?.text=="string")return e.text;if(typeof e?.output=="string")return e.output;if(Array.isArray(e?.candidates)&&e.candidates.length>0){const a=e.candidates[0];if(typeof a?.content=="string")return a.content;if(Array.isArray(a?.content?.parts)){const l=a.content.parts.map(n=>typeof n?.text=="string"?n.text:"").join("");if(l.trim())return l}}}catch{}return g}class me extends Y{constructor(){super("gemini","Gemini (Google)",70)}canHandle(e){if(!!!(process.env.GEMINI_API_KEY||process.env.GOOGLE_API_KEY))return i.debug("GeminiAgentStrategy: GEMINI_API_KEY or GOOGLE_API_KEY not set"),!1;try{return F("gemini --version",{encoding:"utf-8",timeout:5e3,stdio:"pipe"}),!0}catch{return i.warn("[Gemini] gemini CLI not found. Install: npm install -g @google/gemini-cli"),!1}}async invoke(e,a={}){const{model:l,workspace:n=process.cwd(),schema:t=null,skills:r=null,sessionPath:o=null,nodeName:c=null,timeout:u=600*1e3}=a;let m=l;(!m||m==="auto")&&(m=U.GEMINI);const _=W[m]||m,A=String(process.env.GEMINI_API_KEY||"").trim(),J=String(process.env.GOOGLE_API_KEY||"").trim(),N=this._resolveSkillsToMcp(r,{sessionPath:o,workspace:n,nodeName:c}),T=Object.keys(N).length>0;let I=e;const b=t&&typeof t.parse=="function";let O=null;if(t){let s;try{const p=b?H(t,{target:"openAi"}):t;s=JSON.stringify(p,null,2)}catch{s="{}"}if(T){I+=`
2
+
3
+ Write valid JSON that matches this schema:
4
+ ${s}`;const p=`zibby-result-${Date.now()}.json`,d=G(n,".zibby","tmp");O=G(d,p),K(d,{recursive:!0}),I+=B.generateFileOutputInstructions(t,O)}else I+=`
5
+
6
+ Return ONLY valid JSON (no markdown, no commentary) that matches this schema:
7
+ ${s}`}const M=this._createGeminiConfigDir(n,N),y=["--output-format","json"];_&&_!=="auto"&&y.push("--model",_);const $=Object.keys(N);if($.length>0){y.push("--approval-mode","yolo");for(const s of $)y.push("--allowed-mcp-server-names",s);i.info(`[Gemini] Enabling MCP servers: ${$.join(", ")}`)}else r&&r.length>0&&i.warn(`[Gemini] Skills requested but no MCP servers configured: ${r.join(", ")}`);y.push("-p",I);const E={...process.env,GEMINI_CLI_HOME:M};A?(E.GEMINI_API_KEY=A,delete E.GOOGLE_API_KEY):J&&(E.GOOGLE_API_KEY=J,delete E.GEMINI_API_KEY),i.debug(`[Gemini] Command: gemini ${y.slice(0,8).join(" ")}... (${y.length} total args)`),i.debug(`[Gemini] Config home: ${M}`),i.debug(`[Gemini] GEMINI_CLI_HOME env: ${E.GEMINI_CLI_HOME}`);let P="",w=null;try{P=await new Promise((p,d)=>{const v=z("gemini",y,{cwd:n,env:E,stdio:["ignore","pipe","pipe"]});let x="",j="";const k=setTimeout(()=>{try{v.kill("SIGTERM")}catch{}},u);v.stdout.on("data",h=>{x+=h.toString()}),v.stderr.on("data",h=>{j+=h.toString()}),v.on("error",h=>{clearTimeout(k),d(h)}),v.on("close",h=>{if(clearTimeout(k),h===0)return p(x.trim());d(new Error(`gemini failed with code ${h}: ${(j||x).trim()}`))})})}catch(s){w=s}finally{try{q(M,{recursive:!0,force:!0})}catch{}}const f=ee(P).trim();if(!t){if(w)throw w;return f}if(O){const s=C(O);if(i.info(`[Gemini] Result file: ${s?"present":"missing"} at ${O}`),s)try{const p=L(O,"utf-8").trim(),d=JSON.parse(p),v=b?t.parse(d):d;return i.info("[Gemini] Structured output recovered from result file"),{raw:f,structured:v}}catch(p){i.warn(`[Gemini] Result file parse/validation failed: ${p.message}`)}else w||i.warn("[Gemini] Result file missing; falling back to stream-parsed JSON")}let S=null;if(t){const s=new Q;s.zodSchema=t,s.processChunk(f),s.flush(),S=s.getResult()}if(i.info(`[Gemini] Raw stdout length: ${P.length} chars`),i.info(`[Gemini] Extracted text length: ${f.length} chars`),i.info(`[Gemini] StreamParser result: ${S?"extracted":"null"}`),S||(f.length<2e3?i.info(`[Gemini] Raw text preview:
8
+ ${f}`):i.info(`[Gemini] Raw text preview (first 1000 chars):
9
+ ${f.slice(0,1e3)}`),S=X(f)),!S)throw w||(i.error("[Gemini] Failed to extract valid JSON from output"),new Error("Gemini did not return valid JSON for structured output"));const D=b?t.parse(S):S;return{raw:f,structured:D}}_resolveSkillsToMcp(e,a={}){if(!Array.isArray(e)||e.length===0)return{};const l={};for(const n of e){const t=Z(n);if(!t||typeof t.resolve!="function")continue;const r=t.resolve(a);if(!r)continue;const o=t.cursorKey||t.serverName||n,c={command:r.command};r.args?.length&&(c.args=r.args),r.env&&Object.keys(r.env).length>0&&(c.env=r.env),r.cwd&&(c.cwd=r.cwd),l[o]=c}return l}_createGeminiConfigDir(e,a){const l=`${Date.now()}-${Math.random().toString(16).slice(2,10)}`,n=G(e||process.cwd(),".zibby","tmp",`gemini-home-${l}`),t=G(n,".gemini");K(t,{recursive:!0});const r=G(t,"settings.json");let o={};const c=G(process.env.HOME||"",".gemini","settings.json");if(C(c))try{o=JSON.parse(L(c,"utf-8"))}catch{o={}}const u={...o,mcpServers:{...o.mcpServers&&typeof o.mcpServers=="object"?o.mcpServers:{},...a||{}}};R(r,`${JSON.stringify(u,null,2)}
10
+ `,"utf-8");const m=G(e||process.cwd(),".zibby","tmp","gemini-settings-debug.json");try{R(m,`${JSON.stringify(u,null,2)}
11
+ `,"utf-8")}catch{}return i.debug(`[Gemini] Created isolated config with ${Object.keys(u.mcpServers||{}).length} MCP servers`),i.debug(`[Gemini] MCP servers: ${JSON.stringify(Object.keys(u.mcpServers||{}),null,2)}`),n}}export{me as GeminiAgentStrategy};
@@ -0,0 +1,13 @@
1
+ import{CursorAgentStrategy as u}from"./cursor-strategy.js";import{ClaudeAgentStrategy as f}from"./claude-strategy.js";import{CodexAgentStrategy as E}from"./codex-strategy.js";import{GeminiAgentStrategy as A}from"./gemini-strategy.js";import{AssistantStrategy as I}from"./assistant-strategy.js";import{logger as i}from"../../utils/logger.js";const h=[new I,new u,new f,new E,new A];function T(r={}){const{state:t={},preferredAgent:e=null}=r,n=e||t.agentType||process.env.AGENT_TYPE;if(!n)throw new Error("No agent specified. Set agent.claude, agent.cursor, agent.codex, or agent.gemini in .zibby.config.js");i.debug(`Agent selection: requested=${n}`);const o=h.find(a=>a.getName()===n);if(!o)throw new Error(`Unknown agent '${n}'. Available: ${h.map(a=>a.getName()).join(", ")}`);if(i.debug(`Checking if ${n} can handle this environment...`),!o.canHandle(r)){const s={assistant:"Run `zibby login` to authenticate",claude:"Set ANTHROPIC_API_KEY in .env",cursor:"Install cursor-agent CLI or set CURSOR_API_KEY",codex:"Install codex CLI (npm i -g @openai/codex) and set OPENAI_API_KEY in .env",gemini:"Install gemini CLI (npm i -g @google/gemini-cli) and set GEMINI_API_KEY in .env"}[n]||"Check your environment configuration";throw new Error(`Agent '${n}' is not available. ${s}`)}return i.debug(`Using agent: ${o.getName()}`),o}async function _(r,t={},e={}){try{await import("@zibby/skills")}catch{}const n=T(t),o=t.state?.config||e.config||{},a=o.models||{},s=e.nodeName&&a[e.nodeName]||null,p=a.default||null,N=n.name,w=o.agent?.[N]?.model||null,y=s||p||w||e.model||null,l={...e,model:y,workspace:t.state?.workspace||e.workspace,schema:e.schema||t.schema,images:e.images||t.images||[],skills:e.skills||t.skills||[],config:o},c=l.skills||[];if(c.length>0&&!e.skipPromptFragments){const{getSkill:S}=await import("../skill-registry.js"),d=c.map(C=>{const g=S(C)?.promptFragment;return typeof g=="function"?g():g}).filter(Boolean);d.length>0&&(r+=`
2
+
3
+ ${d.join(`
4
+
5
+ `)}`)}const m=t.state?._currentNodeConfig?.extraPromptInstructions?.trim();return m&&(r+=`
6
+
7
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
8
+ \u26A0\uFE0F PRIORITY OVERRIDE \u2014 THE FOLLOWING INSTRUCTIONS TAKE PRECEDENCE OVER ALL PREVIOUS CONTENT
9
+ \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
10
+
11
+ ${m}
12
+ `),i.debug(`Prompt length: ${r.length} chars`),process.env.STAGE!=="prod"&&i.debug(`Full prompt:
13
+ ${r}`),n.invoke(r,l)}import{AgentStrategy as L}from"./base.js";export{L as AgentStrategy,I as AssistantStrategy,f as ClaudeAgentStrategy,E as CodexAgentStrategy,u as CursorAgentStrategy,A as GeminiAgentStrategy,T as getAgentStrategy,_ as invokeAgent};
@@ -0,0 +1,3 @@
1
+ function m(t,l){const o=String(t??"");return o.length<=l?o:`${o.slice(0,Math.max(0,l-30))}
2
+
3
+ [tool result truncated for size]`}function J(t,l){if(typeof t=="string")return m(t,l);try{return m(JSON.stringify(t),l)}catch{return m(String(t),l)}}function p(t){const l=new Set;for(const e of t)if(e.role==="assistant"&&Array.isArray(e.tool_calls))for(const n of e.tool_calls)l.add(n.id);const o=t.filter(e=>e.role==="tool"?l.has(e.tool_call_id):!0),s=new Set;for(const e of o)e.role==="tool"&&s.add(e.tool_call_id);return o.map(e=>{if(e.role!=="assistant"||!Array.isArray(e.tool_calls)||e.tool_calls.every(u=>s.has(u.id)))return e;const{tool_calls:f,...r}=e;return{...r,content:r.content||""}})}function N(t){const l=Array.isArray(t?.messages)?t.messages:[],o=l.find(n=>n.role==="system");let s=l.slice(-4).map(n=>({...n,content:m(n.content,n.role==="tool"?1200:2500)}));s=p(s);const e={...t,messages:[o,...s].filter(Boolean)};return delete e.tools,e}async function O({body:t,streaming:l,auth:o,options:s,fetchCompletion:e,fetchStreamingCompletion:n,onFallbackLog:f}){try{return l?await n(t,o,s):await e(t,o,s)}catch(r){const u=String(r?.message||r||"");if(!/proxy error 413|payload too large/i.test(u))throw r;const i=N(t);return typeof f=="function"&&f(t,i),{data:l?await n(i,o,s):await e(i,o,s),fallback:i}}}async function P({body:t,auth:l,options:o,streaming:s,toolContext:e,activeSkills:n,round:f,verbose:r,dependencies:u,config:i={}}){const h=i.maxToolResultChars||3e3,{fetchCompletion:x,fetchStreamingCompletion:w,onFallbackLog:R,hasToolCalls:k,getTextContent:C,parseToolCalls:S,buildAssistantMessage:z,buildToolResultMessage:B,executeTool:M,onToolCallLog:_,injectTools:F}=u;Array.isArray(t?.messages)&&(t.messages=p(t.messages));const g=await O({body:t,streaming:s,auth:l,options:o,fetchCompletion:x,fetchStreamingCompletion:w,onFallbackLog:R}),d=g?.data||g;if(!k(d))return{done:!0,text:C(d),body:g?.fallback||t};const c=S(d),y=g?.fallback||t;y.messages.push(z(d)),r&&typeof _=="function"&&_(c);const T=await Promise.all(c.map((a,A)=>(typeof o.onToolCall=="function"&&o.onToolCall(a.name,a.args,{round:f,index:A,total:c.length}),M(a,e))));for(let a=0;a<c.length;a++){const I=c[a].name==="get_skill_context"?typeof T[a]=="string"?T[a]:JSON.stringify(T[a]):J(T[a],h);y.messages.push(B(c[a].id,I))}return typeof o.onToolCall=="function"&&o.onToolCall(null),F(y,n),{done:!1,body:y}}export{P as runAssistantRound};
@@ -0,0 +1 @@
1
+ class s{formatTools(e){throw new Error("formatTools() must be implemented")}hasToolCalls(e){throw new Error("hasToolCalls() must be implemented")}parseToolCalls(e){throw new Error("parseToolCalls() must be implemented")}getTextContent(e){throw new Error("getTextContent() must be implemented")}buildAssistantMessage(e){throw new Error("buildAssistantMessage() must be implemented")}buildToolResultMessage(e,o){throw new Error("buildToolResultMessage() must be implemented")}injectToolsIntoBody(e,o){throw new Error("injectToolsIntoBody() must be implemented")}}export{s as ToolCallProvider};
@@ -0,0 +1 @@
1
+ import{ToolCallProvider as e}from"./base.js";import{OpenAIToolProvider as t}from"./openai.js";import{CompletionTransportProvider as l}from"./transport-base.js";import{OpenAICompletionProvider as n}from"./openai-transport.js";export{l as CompletionTransportProvider,n as OpenAICompletionProvider,t as OpenAIToolProvider,e as ToolCallProvider};
@@ -0,0 +1,2 @@
1
+ import{CompletionTransportProvider as T}from"./transport-base.js";import{applyPayloadBudget as P}from"../utils/payload-budget.js";const O=B=>Buffer.byteLength(JSON.stringify(B),"utf8");class N extends T{async fetchCompletion(n,e,t={}){const d=O(n),{body:f,meta:m}=P(n,t.payloadCompaction);t.onBudget?.({streaming:!1,beforeBytes:d,meta:m});const g=this.#t(t),h=`${e.baseUrl}${t.chatCompletionsPath||"/v1/chat/completions"}`,o=await fetch(h,{method:"POST",headers:e.headers,body:JSON.stringify(f),signal:g});if(!o.ok){const s=await o.text();throw o.status===401||o.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${o.status}: ${s}`)}return o.json()}async fetchStreamingCompletion(n,e,t={}){const d={...n,stream:!0},f=O(d),{body:m,meta:g}=P(d,t.payloadCompaction);t.onBudget?.({streaming:!0,beforeBytes:f,meta:g});const h=this.#t(t),o=`${e.baseUrl}${t.chatCompletionsPath||"/v1/chat/completions"}`,s=await fetch(o,{method:"POST",headers:e.headers,body:JSON.stringify(m),signal:h});if(!s.ok){const l=await s.text();throw s.status===401||s.status===403?new Error("Session expired. Run `zibby login` to re-authenticate."):new Error(`Proxy error ${s.status}: ${l}`)}const $=s.body.getReader(),k=new TextDecoder;let y="",p="";const c=new Map;for(;;){const{done:l,value:a}=await $.read();if(l)break;y+=k.decode(a,{stream:!0});const u=y.split(`
2
+ `);y=u.pop();for(const S of u){if(!S.startsWith("data: "))continue;const x=S.slice(6).trim();if(x==="[DONE]")continue;let C;try{C=JSON.parse(x)}catch{continue}const i=C.choices?.[0]?.delta;if(i&&(i.content&&(p+=i.content,t.onToken&&t.onToken(i.content)),i.tool_calls))for(const r of i.tool_calls){const b=r.index??0;c.has(b)||c.set(b,{id:"",name:"",args:""});const w=c.get(b);r.id&&(w.id=r.id),r.function?.name&&(w.name=r.function.name),r.function?.arguments!=null&&(w.args+=r.function.arguments)}}}if(c.size>0){const l=[...c.entries()].sort(([a],[u])=>a-u).map(([,a])=>({id:a.id,type:"function",function:{name:a.name,arguments:a.args}}));return{choices:[{message:{role:"assistant",content:p||null,tool_calls:l}}]}}return{choices:[{message:{role:"assistant",content:p}}]}}#t(n={}){const e=[n.signal,n.timeout?AbortSignal.timeout(n.timeout):null].filter(Boolean);return e.length>1?AbortSignal.any(e):e[0]||void 0}}export{N as OpenAICompletionProvider};
@@ -0,0 +1 @@
1
+ import{ToolCallProvider as t}from"./base.js";class r extends t{formatTools(o){return o.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:e.parameters||e.input_schema||{type:"object",properties:{}}}}))}hasToolCalls(o){const e=o.choices?.[0]?.message;return!!(e?.tool_calls&&e.tool_calls.length>0)}parseToolCalls(o){return(o.choices?.[0]?.message?.tool_calls||[]).map(s=>({id:s.id,name:s.function.name,args:JSON.parse(s.function.arguments||"{}")}))}getTextContent(o){return o.choices?.[0]?.message?.content||""}buildAssistantMessage(o){return o.choices?.[0]?.message}buildToolResultMessage(o,e){return{role:"tool",tool_call_id:o,content:typeof e=="string"?e:JSON.stringify(e)}}injectToolsIntoBody(o,e){return e.length>0&&(o.tools=e),o}}export{r as OpenAIToolProvider};
@@ -0,0 +1 @@
1
+ class r{async fetchCompletion(e,o,t={}){throw new Error("fetchCompletion() must be implemented")}async fetchStreamingCompletion(e,o,t={}){throw new Error("fetchStreamingCompletion() must be implemented")}}export{r as CompletionTransportProvider};
@@ -0,0 +1 @@
1
+ import{existsSync as l,readFileSync as f}from"fs";import{join as u}from"path";import{homedir as _}from"os";function A(){try{const o=u(_(),".zibby","config.json");return l(o)?JSON.parse(f(o,"utf-8")):{}}catch{return{}}}function t(o){return String(o||"").replace(/\/v1\/?$/,"")}function y(o,r){const s=process.env.OPENAI_PROXY_URL;if(s)return t(s);if(o==="session")return r.proxyUrl?t(r.proxyUrl):`${(process.env.ZIBBY_API_URL||"https://api-prod.zibby.app").replace(/\/$/,"")}/openai-proxy`;if(o==="byok"){const n=process.env.OPENAI_BASE_URL;return t(n||"https://api.openai.com")}return t(s||"")}function m(){const o=A(),r=process.env.ZIBBY_USER_TOKEN||o.sessionToken||null,s=process.env.OPENAI_API_KEY||null,n=(process.env.ASSISTANT_AUTH_MODE||"").trim().toLowerCase(),c=process.env.OPENAI_PROXY_NO_AUTH==="true",p=process.env.OPENAI_PROXY_URL;let e="session";n==="byok"||n==="local"||n==="session"?e=n:r?e="session":s?e="byok":p&&c&&(e="local");const a=y(e,o),i={"Content-Type":"application/json"};if(e==="session"){if(!r)return{ok:!1,mode:e,reason:"missing_session_token"};i.Authorization=`Bearer ${r}`}else if(e==="byok"){if(!s)return{ok:!1,mode:e,reason:"missing_openai_api_key"};i.Authorization=`Bearer ${s}`}else if(e==="local"){if(!a)return{ok:!1,mode:e,reason:"missing_openai_proxy_url"};!c&&s&&(i.Authorization=`Bearer ${s}`)}return a?{ok:!0,mode:e,baseUrl:a,headers:i,tokenPreview:i.Authorization?`***${i.Authorization.slice(-4)}`:"none"}:{ok:!1,mode:e,reason:"missing_base_url"}}export{m as resolveAssistantAuth};
@@ -0,0 +1 @@
1
+ import{StructuredOutputFormatter as t}from"./structured-output-formatter.js";class e extends t{}export{e as CursorOutputFormatter};
@@ -0,0 +1,9 @@
1
+ import g from"axios";import{homedir as m}from"os";import{join as I}from"path";import{existsSync as _,readFileSync as P}from"fs";import{toJSONSchema as b}from"zod";import{logger as t}from"../../../utils/logger.js";import{DEFAULT_MODELS as d,TIMEOUTS as A}from"../../../constants.js";function S(){if(process.env.OPENAI_PROXY_TOKEN)return t.debug("[Auth] Using OPENAI_PROXY_TOKEN (ECS execution)"),process.env.OPENAI_PROXY_TOKEN;if(process.env.ZIBBY_USER_TOKEN)return t.debug("[Auth] Using ZIBBY_USER_TOKEN (CI/CD PAT)"),process.env.ZIBBY_USER_TOKEN;try{const e=I(m(),".zibby","config.json");if(_(e)){const n=JSON.parse(P(e,"utf-8"));if(n.sessionToken)return t.debug("[Auth] Using session token from zibby login"),n.sessionToken}}catch(e){t.debug(`[Auth] Could not read zibby login session: ${e.message}`)}return null}function N(){return process.env.OPENAI_PROXY_URL?process.env.OPENAI_PROXY_URL.replace(/\/v1\/?$/,""):"https://api-prod.zibby.app/openai-proxy"}function a(e){if(!(typeof e!="object"||e===null)){if(Object.keys(e).length===0){e.type="object",e.additionalProperties=!0;return}if(e.type||(e.properties?e.type="object":e.items&&(e.type="array")),e.type==="object")if(e.properties){for(const[n,o]of Object.entries(e.properties))o.type==="object"&&o.additionalProperties&&o.additionalProperties!==!1&&(!o.properties||Object.keys(o.properties).length===0)&&(e.properties[n]={type:["object","null"]});e.additionalProperties=!1,e.required=Object.keys(e.properties),Object.values(e.properties).forEach(a)}else"additionalProperties"in e||(e.additionalProperties=!0);e.type==="array"&&e.items&&a(e.items),e.anyOf&&e.anyOf.forEach(a),e.oneOf&&e.oneOf.forEach(a),e.allOf&&e.allOf.forEach(a)}}async function v(e,n){t.info("\u{1F527} [OpenAI Proxy] Formatting structured output...");const o=S();if(!o)throw new Error("Authentication required for structured output processing.\n Local development: Run `zibby login`\n CI/CD: Set ZIBBY_USER_TOKEN environment variable (Personal Access Token from UI settings)");const u=N();t.info(`\u{1F517} Using OpenAI proxy: ${u}`);const i=b(n);let s=i;if(i.$ref&&i.definitions){const r=i.$ref.split("/").pop();s=i.definitions[r]||i,t.debug(`Extracted schema from $ref: ${r}`)}delete s.$schema,a(s);const c=4e5;let l=e;e.length>c&&(t.warn(`\u26A0\uFE0F [OpenAI Proxy] Raw text (${e.length} chars) exceeds limit, keeping last ${c} chars`),l=`... [truncated early content] ...
2
+ ${e.slice(-c)}`);const O=`Extract and format the following information into structured JSON matching the schema.
3
+
4
+ RAW CONTENT:
5
+ ${l}
6
+
7
+ Extract all relevant information and format it according to the schema. If any required fields are missing, do your best to infer them from the content.`,y={model:d.OPENAI_POSTPROCESSING,messages:[{role:"user",content:O}],response_format:{type:"json_schema",json_schema:{name:"extract",schema:s,strict:!0}}};t.info(`\u{1F4E4} Sending to OpenAI proxy: model=${d.OPENAI_POSTPROCESSING}, schema keys=${Object.keys(s.properties||{}).join(", ")}`),t.debug(` Schema size: ${JSON.stringify(s).length} chars`),t.debug(` Prompt size: ${O.length} chars`);try{const r={"Content-Type":"application/json"};process.env.OPENAI_PROXY_TOKEN?(r["x-proxy-token"]=o,r["x-execution-id"]=process.env.EXECUTION_ID||""):(r.Authorization=`Bearer ${o}`,r["x-api-key"]=process.env.ZIBBY_API_KEY||"",r["x-execution-id"]=process.env.EXECUTION_ID||"");const p=(await g.post(u,y,{headers:r,timeout:A.OPENAI_REQUEST})).data?.choices?.[0]?.message?.content;if(!p)throw new Error("OpenAI proxy returned empty response");const E=JSON.parse(p);return t.info("\u2705 Successfully formatted with OpenAI proxy"),{structured:E,raw:e}}catch(r){if(r.response){const f=r.response.status,p=r.response.data;throw t.error(`\u274C OpenAI proxy request failed: ${f}`),t.error(` Status: ${f}`),t.error(` Response: ${JSON.stringify(p,null,2)}`),f===401||f===403?new Error(`Authentication failed for OpenAI proxy.
8
+ Run \`zibby login\` or set ZIBBY_USER_TOKEN environment variable.
9
+ Response: ${JSON.stringify(p)}`,{cause:r}):new Error(`Failed to format Cursor output: ${p?.error?.message||"Unknown error"}`,{cause:r})}throw t.error(`\u274C OpenAI proxy request failed: ${r.message}`),new Error(`Failed to format output: ${r.message}`,{cause:r})}}export{v as formatWithOpenAIProxy};
@@ -0,0 +1,3 @@
1
+ const y=49e3,A=12e3;function i(s){return Buffer.byteLength(JSON.stringify(s),"utf8")}function c(s,t){const o=String(s||"");if(o.length<=t)return o;const n=Math.max(0,t-28);return`${o.slice(0,n)}
2
+
3
+ [truncated for size budget]`}function f(s,t=0){if(!s||typeof s!="object"||t>8)return s;if(Array.isArray(s))return s.map(n=>f(n,t+1));const o={};for(const[n,e]of Object.entries(s))n==="description"||n==="title"||n==="examples"||n==="default"||(o[n]=f(e,t+1));return o}function _(s=[]){return s.map(t=>({...t,function:{...t.function,description:c(t.function?.description||"",180),parameters:f(t.function?.parameters||{type:"object",properties:{}})}}))}function g(s){const t=new Set;for(const e of s)if(e.role==="assistant"&&Array.isArray(e.tool_calls))for(const r of e.tool_calls)t.add(r.id);const o=s.filter(e=>e.role==="tool"?t.has(e.tool_call_id):!0),n=new Set;for(const e of o)e.role==="tool"&&n.add(e.tool_call_id);return o.map(e=>{if(e.role!=="assistant"||!Array.isArray(e.tool_calls)||e.tool_calls.every(a=>n.has(a.id)))return e;const{tool_calls:u,...l}=e;return{...l,content:l.content||""}})}function p(s,t={}){const o=t.maxBytes||49e3,n=t.systemMaxChars||12e3,e={...s,messages:Array.isArray(s.messages)?[...s.messages]:[],tools:Array.isArray(s.tools)?_(s.tools):s.tools};e.messages.length>0&&e.messages[0]?.role==="system"&&(e.messages[0]={...e.messages[0],content:c(e.messages[0].content,n)});let r=!1;for(;i(e)>o&&e.messages.length>2;)e.messages.splice(1,1),r=!0;if(r&&(e.messages=g(e.messages)),i(e)>o&&e.messages.length>0&&(e.messages[0]={...e.messages[0],content:c(e.messages[0].content,6e3)},r=!0),i(e)>o){const u=e.messages.find(a=>a.role==="system")||e.messages[0],l=e.messages.slice(-2);e.messages=g([u,...l].filter(Boolean).map((a,m)=>({...a,content:c(a.content,m===0?4e3:8e3)}))),r=!0}return{body:e,meta:{bytes:i(e),trimmed:r,maxBytes:o,messageCount:e.messages.length}}}export{p as applyPayloadBudget};
@@ -0,0 +1,21 @@
1
+ import{zodToJsonSchema as o}from"zod-to-json-schema";class s{static generateFileOutputInstructions(t,r){let e;typeof t?.parse=="function"?e=o(t,{target:"openApi3"}):e=t;const i=this._buildExample(e);return`
2
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
3
+ \u{1F6A8} MANDATORY: WRITE RESULT TO FILE \u{1F6A8}
4
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
5
+ You MUST write your final result as pure JSON to this EXACT file path:
6
+
7
+ ${r}
8
+
9
+ Use your file writing tool (WriteFile or ApplyPatch) to create this file.
10
+ DO NOT just output JSON to stdout. The file MUST exist when you finish.
11
+ DO NOT skip this step. The workflow WILL FAIL if the file is missing.
12
+
13
+ Required JSON structure:
14
+ ${JSON.stringify(i,null,2)}
15
+
16
+ JSON types (strict \u2014 validators reject wrong types):
17
+ - Use bare JSON numbers for numeric fields (e.g. 3000). Do NOT quote them as strings (wrong: "3000").
18
+ - Use true/false without quotes for booleans.
19
+ - Use unquoted null where a field may be null.
20
+
21
+ Rules: valid JSON only, no markdown wrapping, no extra text in the file.`}static _buildExample(t){if(!t)return{};const r=t.type;if(r==="object"&&t.properties){const e={};for(const[i,n]of Object.entries(t.properties))e[i]=this._buildExample(n);return e}if(r==="array"&&t.items)return[this._buildExample(t.items)];if(r==="string")return"<string>";if(r==="number"||r==="integer")return 0;if(r==="boolean")return!1;if(t.description)return`<${t.description}>`;if(t.nullable||t.oneOf||t.anyOf){const e=t.oneOf?.find(i=>i.type!=="null")||t.anyOf?.find(i=>i.type!=="null");return e?this._buildExample(e):null}return"<value>"}}export{s as StructuredOutputFormatter};
@@ -0,0 +1,10 @@
1
+ import{NODE_DEFAULT_TOOLS as $}from"./tool-resolver.js";import{getNodeTemplate as T}from"./node-registry.js";function I(n,s={}){const{nodes:e,edges:t,nodeConfigs:r={}}=n,c=new Set,o=[],d=new Map;for(const p of e){const l=p.data?.nodeType||p.type;d.set(p.id,l),l==="decision"?c.add(p.id):o.push({id:p.id,nodeType:l,label:p.data?.label||p.id})}const i=o.some(p=>{const l=r[p.id]||{};return!l.customCode&&!l.executeCode}),{toolsPerNode:a,toolIdsByVar:f}=_(o,r),{simpleEdges:h,conditionalEdges:y}=v(t,c),w=x(o,t,c),u=[],g=s.workflowType||"workflow";return u.push(b(s)),u.push(k(g,{usesRegisteredNodes:i})),u.push(j(f)),u.push(N(g)),u.push(C(o,r)),u.push(E(o,w,h,y,a,g)),u.filter(Boolean).join(`
2
+ `)}function D(n){const s={};for(const[e,t]of Object.entries(n)){const{tools:r,...c}=t;Object.keys(c).length>0&&(s[e]=c)}return s}function b(n){const s=n.workflowType||"workflow";return["// Generated by Zibby Visual Workflow Editor",`// ${n.projectId?`Project: ${n.projectId} | `:""}Type: ${s} | Version: ${n.version??0}`,`// Downloaded: ${new Date().toISOString()}`,"//",`// Upload back: zibby workflow upload --project <id> --type ${s}`,""].join(`
3
+ `)}function k(n,{usesRegisteredNodes:s=!0}={}){const e=["import '@zibby/skills';","import { WorkflowGraph } from '@zibby/core/framework/graph.js';","import { invokeAgent } from '@zibby/core';","import { getResolvedToolDefinitions } from '@zibby/core/framework/tool-resolver.js';"];return s&&e.push("import '@zibby/core/templates/register-nodes.js';"),e.push("import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs';","import { join, dirname } from 'path';","import { fileURLToPath } from 'url';",""),e.join(`
4
+ `)}function j(n){if(n.size===0)return"";const s=["// \u2500\u2500 Tool Bindings \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","// Each call resolves skill IDs \u2192 full schemas + MCP server configs","// from the skill registry (populated by @zibby/skills import above)."];for(const[e,t]of n){const r=t.join(", ");s.push(`const ${e} = getResolvedToolDefinitions(${JSON.stringify(t)}); // ${r}`)}return s.push(""),s.join(`
5
+ `)}function N(n){return["// \u2500\u2500 Node Configs (extra instructions, runtime settings) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","const __filename = fileURLToPath(import.meta.url);","const __dirname = dirname(__filename);",`const configPath = join(__dirname, 'workflow-${n}.config.json');`,"const nodeConfigs = existsSync(configPath)"," ? JSON.parse(readFileSync(configPath, 'utf-8'))"," : {};",""].join(`
6
+ `)}function C(n,s){const e=["// \u2500\u2500 Node Implementations \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500","// Each node's execute function is inlined below.","// Edit any function to customize behavior. The upload command detects","// changes via // @custom markers and persists them to the cloud.",""];for(const t of n){const r=m(t.id),c=s[t.id]?.customCode;if(c)e.push(`// @custom \u2014 modified from default "${t.nodeType}" template`),e.push(`const ${r}_execute = ${c};`);else{const o=T(t.nodeType);o?(e.push(`// Default "${t.nodeType}" implementation`),e.push(`const ${r}_execute = ${o};`)):(e.push(`// No template available for "${t.nodeType}" \u2014 using passthrough`),e.push(`const ${r}_execute = async (state) => ({ success: true, output: {}, raw: null });`))}e.push("")}return e.join(`
7
+ `)}function E(n,s,e,t,r,c="workflow"){const o=[];o.push("// \u2500\u2500 Graph Builder \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),o.push("export function buildGraph(options = {}) {"),o.push(" const graph = new WorkflowGraph(options);"),o.push(""),o.push(" // Nodes");for(const i of n){const a=m(i.id);o.push(` graph.addNode('${i.id}', { name: '${i.id}', execute: ${a}_execute });`),o.push(` graph.setNodeType('${i.id}', '${i.nodeType}');`)}o.push(""),o.push(" // Entry point"),o.push(` graph.setEntryPoint('${s}');`),o.push(""),(e.length>0||t.length>0)&&o.push(" // Edges");for(const i of e)o.push(` graph.addEdge('${i.source}', '${i.target}');`);for(const i of t){const a=i.code.split(`
8
+ `).map((f,h)=>h===0?f:` ${f}`).join(`
9
+ `);o.push(` graph.addConditionalEdges('${i.source}', ${a});`)}const d=[];for(const i of n){const a=r.get(i.id);a&&d.push(` '${i.id}': ${a},`)}if(d.length>0){o.push(""),o.push(" graph.resolvedToolsMap = {");for(const i of d)o.push(` ${i}`);o.push(" };")}return o.push(""),o.push(" return graph;"),o.push("}"),o.push(""),o.push("// \u2500\u2500 Exports \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"),o.push("export { nodeConfigs };"),o.push(""),o.join(`
10
+ `)}function _(n,s){const e=new Map,t=new Map;for(const r of n){const c=s[r.id]?.tools;let o;if(Array.isArray(c)&&c.length>0)o=[...c].sort();else{const d=$[r.nodeType];d&&d.length>0&&(o=[...d].sort())}if(o){const d=`${o.map(i=>i.replace(/[^a-zA-Z0-9]/g,"")).join("And")}Tools`;e.set(r.id,d),t.has(d)||t.set(d,o)}}return{toolsPerNode:e,toolIdsByVar:t}}function v(n,s){const e=[],t=[],r=new Map,c=new Set;for(const o of n){const d=o.source;r.has(d)||r.set(d,[]),r.get(d).push(o)}for(const o of n)if(!s.has(o.source))if(s.has(o.target)){if(c.has(o.target))continue;c.add(o.target);const i=(r.get(o.target)||[]).find(a=>a.data?.conditionalCode||a.conditionalCode);if(i){const a=i.data?.conditionalCode||i.conditionalCode;t.push({source:o.source,code:a})}}else e.push({source:o.source,target:o.target});return{simpleEdges:e,conditionalEdges:t}}function x(n,s,e){const t=new Set;for(const c of s)e.has(c.target)||t.add(c.target);const r=n.find(c=>!t.has(c.id));return r?r.id:n[0]?.id}function m(n){return n.replace(/[^a-zA-Z0-9]/g,"_")}export{D as generateNodeConfigsJson,I as generateWorkflowCode};
@@ -0,0 +1 @@
1
+ const o=".zibby/output",t="sessions",s=".session-info.json",_=".zibby-studio-stop",I="result.json",E="raw_stream_output.txt",e="events.json",r={BROWSER:"browser",JIRA:"jira",GITHUB:"github",SLACK:"slack",MEMORY:"memory",CHAT_MEMORY:"chat-memory",RUNNER:"runner",SKILL_INSTALLER:"skill-installer",CORE_TOOLS:"core-tools"},S=["CI_JOB_ID","GITHUB_RUN_ID","CIRCLE_WORKFLOW_ID","BUILD_ID"];export{S as CI_ENV_VARS,o as DEFAULT_OUTPUT_BASE,e as EVENTS_FILE,E as RAW_OUTPUT_FILE,I as RESULT_FILE,t as SESSIONS_DIR,s as SESSION_INFO_FILE,r as SKILLS,_ as STUDIO_STOP_REQUEST_FILE};
@@ -0,0 +1,5 @@
1
+ import{existsSync as f,readFileSync as u}from"fs";import{join as d,dirname as m}from"path";class x{static async loadContext(e,r,a={}){const t={},s=a.filenames||["CONTEXT.md","AGENTS.md"];if(e){const i=m(d(r,e));for(const o of s){const c=await this.findAndMergeContextFiles(o,i,r);if(c){const l=o.replace(/\.[^.]+$/,"").toLowerCase();t[l]=c}}}const n=a.discovery||{};for(const[i,o]of Object.entries(n))try{const c=d(r,o);if(f(c)){const l=await this.loadFile(c);t[i]=l}}catch(c){console.warn(`\u26A0\uFE0F Could not load context '${i}' from '${o}': ${c.message}`)}return t}static async findAndMergeContextFiles(e,r,a){const t=[];let s=r;for(;s.startsWith(a);){const n=d(s,e);if(f(n))try{const o=await this.loadFile(n);t.unshift(o)}catch(o){console.warn(`\u26A0\uFE0F Could not load ${e} from ${n}: ${o.message}`)}const i=m(s);if(i===s)break;s=i}return t.length===0?null:t.every(n=>typeof n=="string")?t.join(`
2
+
3
+ ---
4
+
5
+ `):t.every(n=>typeof n=="object")?Object.assign({},...t):t[t.length-1]}static async loadFile(e){const r=u(e,"utf-8");if(e.endsWith(".json"))return JSON.parse(r);if(e.endsWith(".js")||e.endsWith(".mjs")){const{pathToFileURL:a}=await import("url"),t=await import(a(e).href);return t.default||t}return r}}export{x as ContextLoader};
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ import{McpServer as p}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as d}from"@modelcontextprotocol/sdk/server/stdio.js";import{z as o}from"zod";const[a,s]=process.argv.slice(2);(!a||!s)&&(console.error("Usage: node function-bridge.js <modulePath> <skillId>"),process.exit(1)),await import(a);const{getHandlers:f}=await import("./function-skill-registry.js"),c=f(s);c||(console.error(`No handlers registered for skill "${s}". Did the module call functionSkill()?`),process.exit(1));const{handlers:u,tools:m}=c;function b(e){if(!e||e.type!=="object")return o.object({});const n={};for(const[i,r]of Object.entries(e.properties||{})){let t;switch(r.type){case"number":case"integer":t=o.number();break;case"boolean":t=o.boolean();break;case"array":t=o.array(o.any());break;default:t=o.string();break}r.description&&(t=t.describe(r.description)),e.required?.includes(i)||(t=t.optional()),n[i]=t}return o.object(n)}const l=new p({name:`zibby-fn-${s}`,version:"1.0.0"},{capabilities:{tools:{}}});for(const e of m){const n=b(e.input_schema);l.registerTool(e.name,{title:e.name,description:e.description||"",inputSchema:n},async i=>{try{const r=await u[e.name](i);return{content:[{type:"text",text:typeof r=="string"?r:JSON.stringify(r,null,2)}]}}catch(r){return{content:[{type:"text",text:`Error: ${r.message}`}],isError:!0}}})}const y=new d;await l.connect(y);
@@ -0,0 +1 @@
1
+ const t=new Map;function s(e,n,r){t.set(e,{handlers:n,tools:r})}function o(e){return t.get(e)||null}export{o as getHandlers,s as registerHandlers};
@@ -0,0 +1 @@
1
+ import{WorkflowGraph as b}from"./graph.js";import{getNodeImpl as A,hasNode as x}from"./node-registry.js";import{resolveNodeTools as k}from"./tool-resolver.js";import{logger as w}from"../utils/logger.js";function M(t,o={}){const{nodes:d,edges:i,nodeConfigs:c={}}=t;if(!Array.isArray(d)||d.length===0)throw new f("Graph must have at least one node");if(!Array.isArray(i))throw new f("Graph edges must be an array");const s=new b(o);o.stateSchema&&s.setStateSchema(o.stateSchema);const r=new Set,e=new Map,u={};for(const n of d){const g=$(n);e.set(n.id,{...n,resolvedType:g}),g==="decision"&&r.add(n.id)}for(const[n,g]of e){if(r.has(n))continue;const p=g.resolvedType,a=c[n]||{},C=a.tools,m=k(p,C);m&&(u[n]=m);const y={};a.prompt&&(y.prompt=a.prompt);const v=x(p);if(w.debug(`[compiler] Node "${n}" type="${p}" registered=${v} hasCustomCode=${!!a.customCode} hasExecuteCode=${!!a.executeCode}`),a.customCode&&!v)w.debug("[compiler] \u2192 using customCode (unregistered node)"),s.addNode(n,N(n,a.customCode,a),y),s.setNodeType(n,p);else if(v){w.debug("[compiler] \u2192 using registered implementation");const T=A(p);T.factory?s.addNode(n,T.create(n,{...a,resolvedTools:m}),y):s.addNode(n,T,y),s.setNodeType(n,p)}else if(a.executeCode)w.debug("[compiler] \u2192 using executeCode (fallback)"),s.addNode(n,N(n,a.executeCode,a),y),s.setNodeType(n,p);else throw new f(`Unknown node type "${p}" for node "${n}". Did you forget to register it?`)}s.resolvedToolsMap=u;const h=new Set;for(const n of i)r.has(n.target)||h.add(n.target);const l=d.find(n=>!r.has(n.id)&&!h.has(n.id));if(!l)throw new f("Could not determine entry point: no node without incoming edges found");s.setEntryPoint(l.id);const S=E(i,"source");for(const n of i){const g=r.has(n.source),p=r.has(n.target);if(!g)if(p){const a=n.target,C=S.get(a)||[];if(C.length===0)throw new f(`Decision node "${a}" has no outgoing edges`);const m=G(a,C,r);s.addConditionalEdges(n.source,m)}else s.addEdge(n.source,n.target)}return s}function q(t){const o=[];if(!t||typeof t!="object")return{valid:!1,errors:["Config must be a non-null object"]};if((!Array.isArray(t.nodes)||t.nodes.length===0)&&o.push("Graph must have at least one node"),Array.isArray(t.edges)||o.push("Graph edges must be an array"),o.length>0)return{valid:!1,errors:o};const d=t.nodeConfigs||{};for(const e of t.nodes){const u=$(e);if(u==="decision"||x(u))continue;const h=d[e.id]||{};h.customCode||h.executeCode||o.push(`Unknown node type "${u}" for node "${e.id}". Register it or provide customCode/executeCode.`)}const i=new Set(t.nodes.map(e=>e.id));for(const e of t.edges)i.has(e.source)||o.push(`Edge references unknown source node "${e.source}"`),i.has(e.target)||o.push(`Edge references unknown target node "${e.target}"`);const c=new Set(t.nodes.filter(e=>$(e)==="decision").map(e=>e.id)),s=new Set;for(const e of t.edges)c.has(e.target)||s.add(e.target);const r=t.nodes.filter(e=>!c.has(e.id)&&!s.has(e.id));r.length===0?o.push("No entry point found (every node has incoming edges)"):r.length>1&&o.push(`Multiple entry points found: ${r.map(e=>e.id).join(", ")}. Graph must have exactly one.`);for(const e of c){const u=t.edges.filter(l=>l.source===e);u.length===0&&o.push(`Decision node "${e}" has no outgoing edges`),u.some(l=>l.data?.conditionalCode||l.conditionalCode)||o.push(`Decision node "${e}" outgoing edges have no conditionalCode`)}return{valid:o.length===0,errors:o}}function R(t){return!t||!Array.isArray(t.nodes)?[]:t.nodes.filter(o=>$(o)!=="decision").map(o=>o.id)}function $(t){const o=t.data?.nodeType||t.data?.type||t.type;return o==="workflowNode"||o==="custom"||o==="default"?t.id:o}function E(t,o){const d=new Map;for(const i of t){const c=i[o];d.has(c)||d.set(c,[]),d.get(c).push(i)}return d}function G(t,o,d){const i=o.find(e=>e.data?.conditionalCode||e.conditionalCode);if(!i)throw new f(`Decision node "${t}" has no conditionalCode on its outgoing edges`);const c=i.data?.conditionalCode||i.conditionalCode,s=new Set(o.map(e=>e.target).filter(e=>!d.has(e)));let r;try{const u=new Function(`return (${c})`)();r=h=>{const l=u(h);return s.has(l)||w.warn(`Conditional route from "${t}" returned "${l}" which is not a valid target. Valid: ${[...s].join(", ")}`),l}}catch(e){throw new f(`Failed to compile conditionalCode for decision "${t}": ${e.message}`)}return r}function N(t,o,d={}){let i;try{i=new Function("invokeAgent","require","console",`return (${o})`)}catch(r){throw new f(`Failed to compile customCode for node "${t}": ${r.message}`)}const c=i(async(...r)=>{const{invokeAgent:e}=await import("./agents/index.js");return e(...r)},typeof require<"u"?require:void 0,console);let s=null;return d.outputSchema&&(s=d.outputSchema.jsonSchema||d.outputSchema),{name:t,_isCustomCode:!0,outputSchema:s,execute:async r=>{try{const e=await c(r);return typeof e=="object"&&"success"in e?e:{success:!0,output:e,raw:null}}catch(e){return{success:!1,error:e.message,raw:null}}}}}class f extends Error{constructor(o){super(o),this.name="CompilationError"}}export{f as CompilationError,M as compileGraph,R as extractSteps,q as validateGraphConfig};
@@ -0,0 +1,5 @@
1
+ import{WorkflowState as X}from"./state.js";import{Node as U,ConditionalNode as ee}from"./node.js";import{ContextLoader as te}from"./context-loader.js";import{mkdirSync as L,existsSync as C,writeFileSync as W,unlinkSync as oe}from"fs";import{join as I,resolve as z}from"path";import{config as se}from"dotenv";import{zodToJsonSchema as G}from"zod-to-json-schema";import ne from"handlebars";import{invokeAgent as re}from"./agents/index.js";import{DEFAULT_OUTPUT_BASE as x,SESSIONS_DIR as ie,SESSION_INFO_FILE as H,CI_ENV_VARS as ce,STUDIO_STOP_REQUEST_FILE as ae}from"./constants.js";import{timeline as S}from"../utils/timeline.js";function de({traceFrom:f,sessionId:e,sessionPath:t,idSource:s,mkdirFresh:o}){if(process.env.ZIBBY_SESSION_LOG==="0"||process.env.ZIBBY_SESSION_LOG==="false")return;const n=typeof process.ppid=="number"?process.ppid:"n/a",r=`[zibby:session] from=${f} pid=${process.pid} ppid=${n} sessionId=${e} source=${s} mkdir=${o?"yes":"no"} path=${t}`;if(console.log(r),(process.env.ZIBBY_TRACE_SESSION==="1"||process.env.ZIBBY_TRACE_SESSION==="true")&&process.env.ZIBBY_SESSION_LOG!=="0"&&process.env.ZIBBY_SESSION_LOG!=="false"){const i=(new Error("session trace").stack||"").split(`
2
+ `).slice(2,14).join(`
3
+ `);console.log(`[zibby:session] stack (${f}):
4
+ ${i}`)}}function pe(){return process.env.ZIBBY_RUN_SOURCE==="studio"||process.env.ZIBBY_KEEP_SESSION_ENV==="1"||process.env.ZIBBY_KEEP_SESSION_ENV==="true"}function le(){if(process.env.ZIBBY_RUN_SOURCE!=="studio")return;const f=process.env.ZIBBY_SESSION_PATH;if(!(f==null||String(f).trim()===""))try{return z(String(f).trim())}catch{return String(f).trim()}}function fe(){pe()||(delete process.env.ZIBBY_SESSION_PATH,delete process.env.ZIBBY_SESSION_ID)}function ue({sessionPath:f,sessionId:e}){f&&typeof f=="string"&&(process.env.ZIBBY_SESSION_PATH=f),e!=null&&String(e).trim()!==""&&(process.env.ZIBBY_SESSION_ID=String(e).trim())}function he(f={}){const e=ce.map(n=>process.env[n]).find(Boolean),t=Math.random().toString(36).slice(2,6),s=e||`${Date.now()}_${t}`,o=f.paths?.sessionPrefix;return o?`${o}_${s}`:s}function me({cwd:f=process.cwd(),config:e={},initialState:t={},traceFrom:s="resolveWorkflowSession"}={}){let o=t.sessionPath,n=t.sessionTimestamp,r="initialState.sessionPath";if(!o&&process.env.ZIBBY_SESSION_PATH)try{const i=z(String(process.env.ZIBBY_SESSION_PATH));i&&(o=i,r="ZIBBY_SESSION_PATH")}catch{}let c;if(o)c=String(o).split(/[/\\]/).filter(Boolean).pop(),n==null&&(n=Date.now());else{const i=process.env.ZIBBY_SESSION_ID&&String(process.env.ZIBBY_SESSION_ID).trim();if(i)c=i,r="ZIBBY_SESSION_ID";else{const g=e.sessionId!=null?String(e.sessionId).trim():"";g&&g!=="last"?(c=g,r="config.sessionId"):(c=he(e),r="generated")}n=n??Date.now();const u=e.paths?.output||x;o=I(f,u,ie,c)}const l=!C(o);return l&&L(o,{recursive:!0}),de({traceFrom:s,sessionId:c,sessionPath:o,idSource:r,mkdirFresh:l}),ue({sessionPath:o,sessionId:c}),{sessionPath:o,sessionId:c,sessionTimestamp:n}}class Te{constructor(e={}){this.nodes=new Map,this.edges=new Map,this.entryPoint=null,this.middleware=Array.isArray(e.middleware)?[...e.middleware]:[],e.nodeMiddleware&&this.middleware.push(e.nodeMiddleware),this.nodeTypeMap=new Map,this.conditionalCodeMap=new Map,this.stateSchema=e.stateSchema||null,this.nodePrompts=new Map,this.nodeOptions=new Map}setStateSchema(e){return this.stateSchema=e,this}getStateSchema(){return this.stateSchema}addNode(e,t,s={}){const o=t instanceof U?t:new U(t);return o.name=e,this.nodes.set(e,o),s.prompt&&this.nodePrompts.set(e,s.prompt),Object.keys(s).length>0&&this.nodeOptions.set(e,s),this}addConditionalNode(e,t){const s=new ee({...t,name:e});return this.nodes.set(e,s),this}addEdge(e,t){return this.edges.set(e,t),this}setNodeType(e,t){return this.nodeTypeMap.set(e,t),this}addConditionalEdges(e,t,{labels:s}={}){return this.edges.set(e,{conditional:!0,routes:t,labels:s}),typeof t=="function"&&this.conditionalCodeMap.set(e,t.toString()),this}setEntryPoint(e){return this.entryPoint=e,this}use(e){return typeof e=="function"&&this.middleware.push(e),this}_composeMiddleware(e,t,s,o,n){let r=s;for(let c=e.length-1;c>=0;c--){const l=e[c],i=r;r=()=>l(t,i,o,n)}return r()}serialize(){const e=[],t={};for(const[n,r]of this.nodes){const c=this.nodeTypeMap.get(n)||n;e.push({id:n,type:c,data:{nodeType:c,label:n}});const l=r._isCustomCode||!1,i={};l&&typeof r.execute=="function"&&(i.customCode=r.execute.toString());const u=this.nodePrompts.get(n);if(u&&(i.prompt=u),typeof r.customExecute=="function"&&(i.executeCode=r.customExecute.toString()),r.outputSchema)try{if(typeof r.outputSchema._def<"u"){const v=G(r.outputSchema,{target:"openApi3"}),d=this._flattenJsonSchemaToVariables(v);i.outputSchema={jsonSchema:v,variables:d}}else i.outputSchema={schema:r.outputSchema}}catch(E){console.warn(`Failed to convert schema for ${n}:`,E.message)}const g=(this.resolvedToolsMap||{})[n];g?.toolIds&&(i.tools=g.toolIds),Object.keys(i).length>0&&(t[n]=i)}const s=[];for(const[n,r]of this.edges)if(typeof r=="string")s.push({source:n,target:r});else if(r.conditional){const c=this.conditionalCodeMap.get(n)||r.routes.toString(),l=this._inferConditionalTargets(r.routes),i=r.labels||{};for(const u of l){const g={source:n,target:u,data:{conditionalCode:c}};i[u]&&(g.label=i[u]),s.push(g)}}let o=null;if(this.stateSchema)try{o=G(this.stateSchema,{target:"openApi3"})}catch{o=this.stateSchema}return{nodes:e,edges:s,nodeConfigs:t,stateSchema:o}}_inferConditionalTargets(e){const t=e.toString(),s=new Set,o=/return\s+['"]([^'"]+)['"]/g;let n;for(;(n=o.exec(t))!==null;)s.add(n[1]);return[...s]}_flattenJsonSchemaToVariables(e,t=""){let s=e;if(e.$ref&&e.definitions){const o=e.$ref.replace("#/definitions/","");s=e.definitions[o]||e}return this._flattenSchema(s,t)}_flattenSchema(e,t=""){if(!e||typeof e!="object")return[];const s=[],o=e.properties||{},n=e.required||[];for(const[r,c]of Object.entries(o)){const l=t?`${t}.${r}`:r,i=!n.includes(r);if(s.push({path:l,type:c.type||"unknown",label:c.description||this._formatLabel(r),optional:i}),c.type==="object"&&c.properties){const u=this._flattenSchema(c,l);s.push(...u)}if(c.type==="array"&&c.items?.type==="object"&&c.items.properties){const u=this._flattenSchema(c.items,`${l}[]`);s.push(...u)}}return s}_formatLabel(e){return e.replace(/([A-Z])/g," $1").replace(/^./,t=>t.toUpperCase()).trim()}_summarizeNodeOutput(e,t){if(!t||typeof t!="object")return[];const s=[];t.success!==void 0&&s.push(`Result: ${t.success?"passed":"failed"}`);for(const[o,n]of Object.entries(t))if(!(o==="success"||o==="raw"||o==="nextNode")){if(typeof n=="string"&&n.length<=80)s.push(`${o}: ${n}`);else if(Array.isArray(n)){const r=n.length,c=n.filter(i=>i?.passed===!0).length;if(n.some(i=>i?.passed!==void 0)){const i=r-c;s.push(`${o}: ${c}/${r} passed${i?`, ${i} failed`:""}`)}else s.push(`${o}: ${r} items`)}if(s.length>=4)break}return s}async run(e,t={}){if(!this.entryPoint)throw new Error("No entry point set for graph");const s=t.cwd||process.cwd();se({path:I(s,".env")});let o=t.config||{};if(!o||Object.keys(o).length===0)try{const p=I(s,".zibby.config.js");C(p)&&(o=(await import(p)).default||{})}catch{}process.env.EXECUTION_ID&&!o.agent?.strictMode&&(o.agent={...o.agent,strictMode:!0});let n=t.agentType;if(!n){const p=o?.agent;p?.provider?n=p.provider:p?.claude?n="claude":p?.cursor?n="cursor":n=process.env.AGENT_TYPE||"cursor"}const r=t.contextConfig||e?.config?.contextConfig||e?.config?.context||o?.context||{};if(this.stateSchema){const p=this.stateSchema.safeParse(t);if(!p.success){const m=p.error.issues.map(w=>`${w.path.join(".")}: ${w.message}`);throw console.error("\u274C Initial state validation failed:"),m.forEach(w=>console.error(` - ${w}`)),new Error(`State validation failed: ${m.join(", ")}`)}S.step("State validated against schema")}const c=le(),l=t.sessionPath||c;l||fe();const{sessionPath:i,sessionTimestamp:u,sessionId:g}=me({cwd:s,config:o,traceFrom:"WorkflowGraph.run",initialState:{sessionPath:l,sessionTimestamp:t.sessionTimestamp}});S.step(`Session ${g}`);const E=await te.loadContext(t.specPath||"",s,r);Object.keys(E).length>0&&S.step(`Context loaded: ${Object.keys(E).join(", ")}`);let v=t.outputPath;!v&&t.specPath&&(e?.calculateOutputPath?v=e.calculateOutputPath(t.specPath):console.warn(`\u26A0\uFE0F outputPath not resolved (specPath=${t.specPath})`));const d=new X({...t,config:o,agentType:n,outputPath:v,sessionPath:i,sessionTimestamp:u,context:E,resolvedTools:this.resolvedToolsMap||{}}),A=new Map;try{await import("@zibby/skills")}catch{}const{getSkill:V}=await import("./skill-registry.js"),M=new Set;for(const[,p]of this.nodes)for(const m of p.config?.skills||[])M.add(m);for(const p of M){const m=V(p);if(typeof m?.middleware=="function")try{const w=await m.middleware();typeof w=="function"&&A.set(p,w)}catch{}}let a=this.entryPoint;const O=[];for(;a&&a!=="END";){const p=I(i,ae);if(C(p)){console.warn(`
5
+ \u{1F6D1} Studio stop requested \u2014 ending workflow.`);try{oe(p)}catch{}if(e&&typeof e.cleanup=="function")try{await e.cleanup()}catch{}return S.step("Workflow stopped by Studio"),{success:!0,state:d.getAll(),executionLog:O,stoppedByStudio:!0}}const m=this.nodes.get(a);if(!m)throw new Error(`Node '${a}' not found in graph`);const w=JSON.stringify({sessionPath:i,sessionTimestamp:u,currentNode:a,createdAt:new Date().toISOString(),config:d.get("config")}),J=I(i,H);W(J,w,"utf-8");const D=d.get("config")?.paths?.output||x,q=I(s,D,H);L(I(s,D),{recursive:!0});try{W(q,w,"utf-8")}catch{}const Y=t.onPipelineProgress;if(typeof Y=="function")try{Y({cwd:s,sessionPath:i,sessionId:g,outputBase:d.get("config")?.paths?.output||x,currentNode:a})}catch{}const K=(this.resolvedToolsMap||{})[a]||null;d.set("_currentNodeTools",K);const Q=d.get("nodeConfigs")||{};d.set("_currentNodeConfig",Q[a]||{}),S.nodeStart(a);const R=Date.now(),T=this.nodePrompts.get(a),j={state:d,invokeAgent:async(P={},_={})=>{let h=_.prompt||"";if(T)try{h=ne.compile(T,{noEscape:!0})(P)}catch(y){throw console.error(`\u274C Template rendering failed for node '${a}':`,y.message),new Error(`Template rendering failed: ${y.message}`,{cause:y})}else if(!h)throw new Error(`No prompt template configured for node '${a}' and no prompt provided in options`);const B={state:d.getAll(),images:_.images||[]},b={model:_.model||d.get("model"),workspace:d.get("workspace"),schema:_.schema,..._};return re(h,B,b)},agent:e,nodeId:a,promptTemplate:T,getPromptTemplate:()=>T,...d.getAll()};try{const P=(m.config?.skills||[]).map($=>A.get($)).filter(Boolean),_=[...this.middleware,...P];let h;_.length>0?h=await this._composeMiddleware(_,a,async()=>m.execute(j,d),d.getAll(),d):h=await m.execute(j,d);const B=Date.now()-R;if(O.push({node:a,success:h.success,duration:B,timestamp:new Date().toISOString()}),!h.success){if(String(h.error||"").includes("Stopped from Zibby Studio")){if(S.step("Workflow stopped by Studio"),d.set("stoppedByStudio",!0),e&&typeof e.cleanup=="function")try{await e.cleanup()}catch{}return{success:!0,state:d.getAll(),executionLog:O,stoppedByStudio:!0}}d.append("errors",{node:a,error:h.error});const N=m.config?.retries||0,F=`${a}_retries`,k=d.getAll()[F]||0;if(k<N){S.stepInfo(`Retrying (attempt ${k+1}/${N})`),d.update({[F]:k+1,[`${a}_raw`]:h.raw});continue}throw S.nodeFailed(a,h.error,{duration:B}),new Error(`Node '${a}' failed after ${k} attempts: ${h.error}`)}d.update({[a]:h.output});const b=this._summarizeNodeOutput(a,h.output);S.nodeComplete(a,{duration:B,details:b});const y=this.edges.get(a);if(!y)a="END";else if(y.conditional){const $=d.getAll(),N=y.routes($);S.route(a,N),a=N}else a=y}catch(P){throw S.isInsideNode&&S.nodeFailed(a,P.message,{duration:Date.now()-R}),d.set("failed",!0),d.set("failedAt",a),P}}S.graphComplete();const Z={success:!0,state:d.getAll(),executionLog:O};return e&&typeof e.onComplete=="function"&&await e.onComplete(Z),Z}}export{Te as WorkflowGraph,fe as clearInheritedSessionEnvForFreshRun,he as generateWorkflowSessionId,le as readStudioPinnedSessionPathFromEnv,me as resolveWorkflowSession,pe as shouldTrustInheritedSessionEnv,ue as syncProcessEnvToSession};
@@ -0,0 +1 @@
1
+ import{WorkflowGraph as t}from"./graph.js";import{Node as l,ConditionalNode as a}from"./node.js";import{WorkflowState as p}from"./state.js";import{OutputParser as s,SchemaTypes as f}from"./output-parser.js";import{compileGraph as m,validateGraphConfig as d,extractSteps as S,CompilationError as x}from"./graph-compiler.js";import{registerNode as k,getNodeImpl as A,hasNode as C,listNodeTypes as h,getNodeTemplate as T}from"./node-registry.js";import{resolveNodeTools as u,getResolvedToolDefinitions as v,NODE_DEFAULT_TOOLS as O}from"./tool-resolver.js";import{registerSkill as w,getSkill as D,hasSkill as E,getAllSkills as G,listSkillIds as W}from"./skill-registry.js";import{generateWorkflowCode as L,generateNodeConfigsJson as _}from"./code-generator.js";import{hasAgentCall as J}from"../utils/ast-utils.js";import{invokeAgent as R,getAgentStrategy as U,CursorAgentStrategy as b,ClaudeAgentStrategy as j,AgentStrategy as q}from"./agents/index.js";export{q as AgentStrategy,j as ClaudeAgentStrategy,x as CompilationError,a as ConditionalNode,b as CursorAgentStrategy,O as NODE_DEFAULT_TOOLS,l as Node,s as OutputParser,f as SchemaTypes,t as WorkflowGraph,p as WorkflowState,m as compileGraph,S as extractSteps,_ as generateNodeConfigsJson,L as generateWorkflowCode,U as getAgentStrategy,G as getAllSkills,A as getNodeImpl,T as getNodeTemplate,v as getResolvedToolDefinitions,D as getSkill,J as hasAgentCall,C as hasNode,E as hasSkill,R as invokeAgent,h as listNodeTypes,W as listSkillIds,k as registerNode,w as registerSkill,u as resolveNodeTools,d as validateGraphConfig};
@@ -0,0 +1,2 @@
1
+ import{Client as l}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as p}from"@modelcontextprotocol/sdk/client/stdio.js";import{logger as c}from"../utils/logger.js";class ${#t=new Map;async ensureServer(t,n){if(this.#t.has(t))return this.#t.get(t);const{command:s,args:i=[],env:r={}}=n;c.debug(`[MCP] Starting ${t}: ${s} ${i.join(" ")}`);const o=new p({command:s,args:i,env:{...process.env,...r}}),e=new l({name:`zibby-chat-${t}`,version:"1.0.0"},{capabilities:{}});await e.connect(o);const a={client:e,transport:o,serverConfig:n};return this.#t.set(t,a),a}async callTool(t,n,s={}){const i=this.#t.get(t);if(!i)throw new Error(`MCP server "${t}" not running`);c.debug(`[MCP] ${t}.${n}(${JSON.stringify(s).slice(0,200)})`);const r=await i.client.callTool({name:n,arguments:s});return{text:r.content?.filter(e=>e.type==="text").map(e=>e.text).join(`
2
+ `)||"",isError:r.isError||!1}}isRunning(t){return this.#t.has(t)}async stopServer(t){const n=this.#t.get(t);if(n){try{await n.client.close()}catch(s){c.debug(`[MCP] Error closing ${t}: ${s.message}`)}this.#t.delete(t)}}async stopAll(){const t=[...this.#t.keys()];await Promise.allSettled(t.map(n=>this.stopServer(n)))}}export{$ as McpClientManager};
@@ -0,0 +1,9 @@
1
+ const s=new Map;function p(t,e){s.set(t,e)}function m(t){return s.get(t)}function x(t){return s.has(t)}function h(){return Array.from(s.keys())}function S(t){const e=s.get(t);return e?e.factory&&typeof e.create=="function"?e.create.toString():typeof e.execute=="function"?e.execute.toString():typeof e=="function"?e.toString():null:null}p("ai_agent",{name:"ai_agent",factory:!0,create:(t,e={})=>({name:t,execute:async r=>{const{invokeAgent:n}=await import("./agents/index.js"),c=e.extraPromptInstructions||"Execute the task based on the current state.",i=y(c,r),o=await n(i,{cwd:r.workspace||process.cwd(),model:r.model,tools:e.resolvedTools||null});return{success:!0,output:{raw:o,nodeId:t},raw:typeof o=="string"?o:o.raw}}})});function g(t){const e=/@([\w.]+)/g,r=new Set;let n;for(;(n=e.exec(t))!==null;)r.add(n[1]);return Array.from(r)}function d(t,e){const r=e.split(".");let n=t;for(const c of r){if(n==null)return;n=n[c]}return n}function w(t){return t==null?"[not available]":typeof t=="string"?t:typeof t=="object"?t.raw&&typeof t.raw=="string"?t.raw:JSON.stringify(t,null,2):String(t)}function y(t,e){const r=g(t);if(r.length===0)return t;const n=[],c=new Set;for(const i of r){const o=i.split(".")[0];if(c.has(o))continue;const f=d(e,i);if(f!==void 0){const u=w(f),a=i.replace(/_/g," ").replace(/\b\w/g,l=>l.toUpperCase());n.push(`## ${a}
2
+ ${u}`),i.includes(".")||c.add(o)}}return n.length===0?t:`${t}
3
+
4
+ ---
5
+ # Referenced Context
6
+
7
+ ${n.join(`
8
+
9
+ `)}`}export{m as getNodeImpl,S as getNodeTemplate,x as hasNode,h as listNodeTypes,p as registerNode};
@@ -0,0 +1,5 @@
1
+ import{OutputParser as _}from"./output-parser.js";import{writeFileSync as f,readFileSync as N,existsSync as C,mkdirSync as b}from"fs";import{join as d,dirname as v}from"path";import h from"chalk";import{invokeAgent as A}from"./agents/index.js";import{logger as u}from"../utils/logger.js";import{timeline as I}from"../utils/timeline.js";import{SESSION_INFO_FILE as $}from"./constants.js";class P{constructor(e){if(this.config=e,this.name=e.name,this.prompt=e.prompt,this.outputSchema=e.outputSchema,!this.outputSchema&&!e._isCustomCode)throw new Error(`Node '${this.name}' must define outputSchema (Zod schema). This defines the contract for what the node returns to state.`);this.isZodSchema=this.outputSchema&&typeof this.outputSchema._def<"u",this.parser=e.outputSchema&&!this.isZodSchema?new _(e.outputSchema):null,this.retries=e.retries||0,this.onComplete=e.onComplete,this.customExecute=e.execute}async execute(e,o){const a=()=>o&&typeof o.getAll=="function"?o.getAll():e,S=t=>o&&typeof o.get=="function"?o.get(t):e?.[t];if(typeof this.customExecute=="function"){u.info("\u26A1 Using custom execute method (skipping LLM)");try{const t=await this.customExecute(e);return typeof t=="object"&&t!==null&&t.success===!1?{success:!1,error:t.error||"Node execution failed",raw:t.raw||null}:this.isZodSchema?(u.debug("Validating return value against outputSchema..."),{success:!0,output:this.outputSchema.parse(t),raw:null}):{success:!0,output:t,raw:null}}catch(t){return u.error(`\u274C Node '${this.name}' execution failed: ${t.message}`),t.name==="ZodError"&&u.error(`Schema validation errors: ${JSON.stringify(t.errors,null,2)}`),{success:!1,error:t.message,raw:null}}}let m=typeof this.prompt=="function"?this.prompt(a()):this.prompt;const g=S("_skillHints");g&&(m=`${g}
2
+
3
+ ${m}`);const w=a(),O=w.cwd||process.cwd(),p=w.sessionPath;try{if(p){const t=d(p,$);if(C(t)){const c=JSON.parse(N(t,"utf-8"));c.currentNode=this.name,f(t,JSON.stringify(c,null,2),"utf-8")}const i=d(p,"..",$);if(C(i))try{const c=JSON.parse(N(i,"utf-8"));c.currentNode=this.name,f(i,JSON.stringify(c,null,2),"utf-8")}catch{}}}catch(t){u.debug(`Could not update session info: ${t.message}`)}let y=null;for(let t=0;t<=this.retries;t++)try{u.debug(`Node.execute attempt ${t} for '${this.name}'`);const i=a(),c=i.config||{},J={state:i},k={workspace:O,schema:this.isZodSchema?this.outputSchema:null,skills:this.config.skills||[],sessionPath:p,config:c,nodeName:this.name,timeout:this.config?.timeout||3e5},n=await A(m,J,k);let r,l;if(typeof n=="string"?(r=n,l=null):n.structured?(r=n.raw||JSON.stringify(n.structured,null,2),l=n.structured):(r=n.raw||JSON.stringify(n,null,2),l=n.extracted||null),p)try{const s=d(p,this.name,"raw_stream_output.txt");b(v(s),{recursive:!0}),f(s,typeof r=="string"?r:JSON.stringify(r),"utf-8")}catch(s){u.debug(`Could not save raw output: ${s.message}`)}if(this.isZodSchema&&l){console.log(`
4
+ \u{1F50D} ${h.cyan("Validated output:")} ${h.white(JSON.stringify(l,null,2))}`);let s=l;if(typeof this.onComplete=="function")try{s=await this.onComplete(a(),l)}catch(E){u.warn(`onComplete hook failed: ${E.message}`)}return{success:!0,output:s,raw:r}}if(typeof this.onComplete=="function")try{return{success:!0,output:await this.onComplete(a(),{raw:r}),raw:r}}catch(s){throw new Error(`onComplete failed: ${s.message}`,{cause:s})}if(this.parser){const s=this.parser.parse(r);return console.log(`
5
+ \u{1F50D} ${h.cyan("Parsed output:")} ${h.white(JSON.stringify(s,null,2))}`),I.step("Output parsed"),{success:!0,output:s,raw:r}}return{success:!0,output:r,raw:r}}catch(i){y=i,t<this.retries&&u.info(`Node '${this.name}' failed, retrying (${t+1}/${this.retries})...`)}return{success:!1,error:y.message,raw:null}}}class M extends P{constructor(e){super({...e,_isCustomCode:!0}),this.condition=e.condition}async execute(e,o){const a=o&&typeof o.getAll=="function"?o.getAll():e;return{success:!0,output:{nextNode:this.condition(a)},raw:null}}}export{M as ConditionalNode,P as Node};
@@ -0,0 +1,3 @@
1
+ class a{constructor(e){this.schema=e}parse(e){const i=e.match(/```json\s*([\s\S]*?)\s*```/);if(i)return this.validate(JSON.parse(i[1]));const r=e.match(/\{[\s\S]*\}/);return r?this.validate(JSON.parse(r[0])):this.validate({result:e.trim()})}validate(e){const i=[];for(const[r,s]of Object.entries(this.schema)){if(s.required&&!(r in e)&&i.push(`Missing required field: ${r}`),r in e&&s.type){const n=typeof e[r];n!==s.type&&i.push(`Field '${r}' expected ${s.type}, got ${n}`)}if(s.validate&&r in e){const n=s.validate(e[r]);n&&i.push(`Field '${r}': ${n}`)}}if(i.length>0)throw new Error(`Output validation failed:
2
+ ${i.join(`
3
+ `)}`);return e}}const o={string:(t=!0)=>({type:"string",required:t}),number:(t=!0)=>({type:"number",required:t}),boolean:(t=!0)=>({type:"boolean",required:t}),array:(t=!0)=>({type:"object",required:t,validate:e=>Array.isArray(e)?null:"must be an array"}),enum:(t,e=!0)=>({type:"string",required:e,validate:i=>t.includes(i)?null:`must be one of: ${t.join(", ")}`})};export{a as OutputParser,o as SchemaTypes};
@@ -0,0 +1 @@
1
+ const e=new Map;function r(t){if(!t||typeof t.id!="string")throw new Error("Skill definition must include a string id");e.set(t.id,Object.freeze({...t}))}function n(t){return e.get(t)||null}function i(t){return e.has(t)}function o(){return new Map(e)}function l(){return Array.from(e.keys())}export{o as getAllSkills,n as getSkill,i as hasSkill,l as listSkillIds,r as registerSkill};
@@ -0,0 +1 @@
1
+ import{zodToJsonSchema as p}from"zod-to-json-schema";function a(e){return e?p(e,{target:"openApi3"}):null}function f(e,n=""){const t=p(e);return s(t,n)}function s(e,n=""){const t=[];if(e.type==="object"&&e.properties)for(const[r,o]of Object.entries(e.properties)){const i=n?`${n}.${r}`:r,c=e.required?.includes(r)??!1;t.push({name:r,path:i,type:o.type||"unknown",description:o.description,optional:!c}),o.type==="object"&&o.properties&&t.push(...s(o,i))}return t}export{a as getJsonSchema,f as schemaToVariables};
@@ -0,0 +1 @@
1
+ const i=new Set(["__proto__","constructor","prototype"]);function a(r){if(i.has(r))throw new Error(`Invalid state key: "${r}"`)}class h{constructor(t={}){this._state=Object.create(null),Object.assign(this._state,{messages:[],errors:[],artifacts:{},metadata:{},...t}),this._history=[]}get(t){return this._state[t]}set(t,s){a(t),this._history.push({...this._state}),this._state[t]=s}update(t){const s=Object.getOwnPropertyNames(t);for(const e of s)a(e);this._history.push({...this._state});for(const e of s)this._state[e]=t[e]}append(t,s){a(t),this._history.push({...this._state}),Array.isArray(this._state[t])||(this._state[t]=[]),this._state[t].push(s)}getAll(){return{...this._state}}rollback(){this._history.length>0&&(this._state=this._history.pop())}}export{h as WorkflowState};