@crewx/sdk 0.8.3 → 0.8.4-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/conversation/types.d.ts +1 -1
  2. package/dist/esm/index.js +46 -59
  3. package/dist/esm/plugins/index.js +3 -3
  4. package/dist/esm/repository/index.js +8 -8
  5. package/dist/facade/Crewx.d.ts +1 -0
  6. package/dist/index.d.ts +5 -4
  7. package/dist/index.js +46 -59
  8. package/dist/plugins/index.js +3 -3
  9. package/dist/provider/acp/adapter.d.ts +43 -0
  10. package/dist/provider/acp/adapters/claude.d.ts +2 -0
  11. package/dist/provider/acp/adapters/codex.d.ts +2 -0
  12. package/dist/provider/acp/adapters/copilot.d.ts +2 -0
  13. package/dist/provider/acp/adapters/gemini.d.ts +2 -0
  14. package/dist/provider/acp/adapters/index.d.ts +7 -0
  15. package/dist/provider/acp/adapters/opencode.d.ts +2 -0
  16. package/dist/provider/acp/connection.d.ts +40 -0
  17. package/dist/provider/acp/index.d.ts +9 -0
  18. package/dist/provider/acp/register.d.ts +2 -0
  19. package/dist/provider/acp/runtime.d.ts +16 -0
  20. package/dist/provider/acp/types.d.ts +24 -0
  21. package/dist/provider/bridge.d.ts +6 -1
  22. package/dist/provider/{adapter.types.d.ts → cli/adapter.types.d.ts} +2 -2
  23. package/dist/provider/{adapters → cli/adapters}/agent-call.util.d.ts +1 -1
  24. package/dist/provider/{adapters → cli/adapters}/index.d.ts +1 -1
  25. package/dist/provider/cli/adapters/tool-input.util.d.ts +1 -0
  26. package/dist/provider/cli/index.d.ts +3 -0
  27. package/dist/repository/index.js +8 -8
  28. package/dist/repository/workspace.repository.d.ts +4 -0
  29. package/dist/types/index.d.ts +2 -0
  30. package/dist/types/task-log.types.d.ts +1 -1
  31. package/dist/utils/workspace.d.ts +2 -0
  32. package/package.json +22 -1
  33. /package/dist/provider/{adapters → cli/adapters}/claude.d.ts +0 -0
  34. /package/dist/provider/{adapters → cli/adapters}/codex.d.ts +0 -0
  35. /package/dist/provider/{adapters → cli/adapters}/copilot.d.ts +0 -0
  36. /package/dist/provider/{adapters → cli/adapters}/gemini.d.ts +0 -0
  37. /package/dist/provider/{adapters → cli/adapters}/opencode.d.ts +0 -0
package/dist/esm/index.js CHANGED
@@ -1,71 +1,58 @@
1
- import*as ne from'path';import ne__default,{join,resolve,dirname,isAbsolute,basename}from'path';import {fileURLToPath}from'url';import {existsSync,readFileSync,readdirSync,appendFileSync,mkdirSync,writeFileSync,statSync}from'fs';import {spawn,execFileSync}from'child_process';import {load}from'js-yaml';import {z}from'zod';import {createRequire}from'module';import*as _e from'handlebars';import _e__default from'handlebars';import {readFile,access}from'fs/promises';import {createHash,randomBytes}from'crypto';import {EventEmitter}from'events';import {AsyncLocalStorage}from'async_hooks';import {McpServer}from'@modelcontextprotocol/sdk/server/mcp.js';import {WebStandardStreamableHTTPServerTransport}from'@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';import La,{homedir}from'os';import {sql,eq,or,isNull,desc,and,asc,inArray}from'drizzle-orm';import {sqliteTable,text,integer,real,index,unique}from'drizzle-orm/sqlite-core';import {performance}from'perf_hooks';var fr=Object.defineProperty;var Ri=Object.getOwnPropertyDescriptor;var Ci=Object.getOwnPropertyNames;var Ti=Object.prototype.hasOwnProperty;var J=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var ee=(r,e)=>()=>(r&&(e=r(r=0)),e);var $e=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),hr=(r,e)=>{for(var t in e)fr(r,t,{get:e[t],enumerable:true});},Pi=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ci(e))!Ti.call(r,o)&&o!==t&&fr(r,o,{get:()=>e[o],enumerable:!(n=Ri(e,o))||n.enumerable});return r};var Pn=r=>Pi(fr({},"__esModule",{value:true}),r);var An,Si,P,A,g=ee(()=>{An=()=>fileURLToPath(import.meta.url),Si=()=>ne__default.dirname(An()),P=Si(),A=An();});function Ht(r){return typeof r!="string"?void 0:r.trim()||void 0}function qt(r){return Ht(r)?.toLowerCase()??""}function it(r){try{return statSync(r).isFile()}catch{return false}}function On(r,e){if(r.includes("/")||r.includes("\\")||ne__default.isAbsolute(r))return r;let n=(e.PATH??e.Path??process.env.PATH??process.env.Path??"").split(";").map(a=>a.trim()).filter(Boolean),o=ne__default.extname(r).length>0,s=e.PATHEXT??e.Pathext??process.env.PATHEXT??process.env.Pathext??".EXE;.CMD;.BAT;.COM",i=o?[""]:s.split(";").map(a=>a.trim()).filter(Boolean).map(a=>a.startsWith(".")?a:`.${a}`);for(let a of n)for(let l of i){let u=qt(l),d=l.toUpperCase();for(let c of [l,u,d]){let p=ne__default.join(a,`${r}${c}`);if(it(p))return p}}return r}function Fi(r){if(!it(r))return null;try{let e=readFileSync(r,"utf8"),t=[];for(let o of e.matchAll(/"([^"\r\n]*)"/g)){let a=(o[1]??"").match(/%~?dp0%?\s*[\\/]*(.*)$/i)?.[1]?.trim();if(!a)continue;let l=a.replace(/[\\/]+/g,ne__default.sep).replace(/^[\\/]+/,""),u=ne__default.resolve(ne__default.dirname(r),l);it(u)&&t.push(u);}return t.find(o=>{let s=qt(ne__default.basename(o));return s!=="node.exe"&&s!=="node"})??null}catch{return null}}function Ui(r,e){if(typeof e=="string")return Ht(e)||null;if(!e||typeof e!="object")return null;if(r){let t=e[r],n=typeof t=="string"?Ht(t):void 0;if(n)return n}for(let t of Object.values(e)){let n=typeof t=="string"?Ht(t):void 0;if(n)return n}return null}function Bi(r,e){if(!e)return null;let t=ne__default.dirname(r),n=[ne__default.resolve(t,"..",e),ne__default.resolve(t,"node_modules",e)];for(let o of n){let s=ne__default.join(o,"package.json");if(it(s))try{let i=JSON.parse(readFileSync(s,"utf8")),a=Ui(e,i.bin);if(!a)continue;let l=ne__default.resolve(o,a);if(it(l))return l}catch{}}return null}function Wi(r){let e=r.platform??process.platform,t=r.env??process.env,n=r.execPath??process.execPath;if(e!=="win32")return {command:r.command,leadingArgv:[],resolution:"direct"};let o=On(r.command,t),s=qt(ne__default.extname(o));if(s===".js"||s===".cjs"||s===".mjs")return {command:n,leadingArgv:[o],resolution:"node-entrypoint",windowsHide:true};if(s===".cmd"||s===".bat"){let i=Fi(o)??Bi(o,r.packageName);return i?qt(ne__default.extname(i))===".exe"?{command:i,leadingArgv:[],resolution:"exe-entrypoint",windowsHide:true}:{command:n,leadingArgv:[i],resolution:"node-entrypoint",windowsHide:true}:{command:o,leadingArgv:[],resolution:"unresolved-wrapper"}}return {command:o,leadingArgv:[],resolution:"direct"}}function Ji(r){if(r.candidate.resolution!=="unresolved-wrapper")return {command:r.candidate.command,leadingArgv:r.candidate.leadingArgv,resolution:r.candidate.resolution,windowsHide:r.candidate.windowsHide};if(r.allowShellFallback===true)return {command:r.candidate.command,leadingArgv:[],resolution:"shell-fallback",shell:true};throw new Error(`${ne__default.basename(r.candidate.command)} wrapper resolved, but no executable/Node entrypoint could be resolved without shell execution.`)}function at(r){let e=Wi(r);return Ji({candidate:e,allowShellFallback:r.allowShellFallback})}function lt(r,e){return {command:r.command,argv:[...r.leadingArgv,...e],resolution:r.resolution,shell:r.shell,windowsHide:r.windowsHide}}var Lt=ee(()=>{g();});function Vi(r){if(r.type!=="usage"||!("input_tokens"in r))return null;let e=Number(r.input_tokens??0),t=Number(r.output_tokens??0),o="cache_read_input_tokens"in r?Number(r.cache_read_input_tokens):void 0,s="cached_input_tokens"in r?Number(r.cached_input_tokens):void 0,i=o!==void 0?o:s??0;return {inputTokens:o!==void 0?e+o:e,outputTokens:t,cachedInputTokens:i}}function Ki(r){let e=r.usage;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(!("input_tokens"in t))return null;let n=Number(t.input_tokens??0),o=Number(t.output_tokens??0),i="cache_read_input_tokens"in t?Number(t.cache_read_input_tokens):void 0,a="cached_input_tokens"in t?Number(t.cached_input_tokens):void 0,l=i!==void 0?i:a??0;return {inputTokens:i!==void 0?n+i:n,outputTokens:o,cachedInputTokens:l}}function Gi(r){if(r.type!=="step_finish")return null;let t=r.part?.tokens;if(!t)return null;let n=Number(t.input??0),o=Number(t.output??0),s=t.cache,i=s?Number(s.read??0):0;return {inputTokens:n+i,outputTokens:o,cachedInputTokens:i}}function ge(r){if(!r||!r.trim())return;let e=null;for(let t of r.split(`
2
- `))if(t.trim())try{let n=JSON.parse(t),o=Vi(n)??Ki(n)??Gi(n);o&&(e=o);}catch{}return e??void 0}var Le=ee(()=>{g();});var ut,vr=ee(()=>{g();ut=class extends Error{name="RateLimitError";constructor(e){super(e);}};});function me(r){return /crewx\s+(x|execute)\s/.test(r)}function fe(r,e){let t=e.match(/@(\S+)/);return {timestamp:r,type:"agent_call",targetAgent:t?.[1]?.replace(/["']/g,""),toolInput:e}}var Ze=ee(()=>{g();});function Xi(r,e){let t=e.type;if(t==="text"){let n=String(e.text||"");return n?{timestamp:r,type:"text",content:n}:null}if(t==="tool_use"){let n=String(e.name||""),o=e.id,s=e.input,i=s?.command?String(s.command):JSON.stringify(s||{});return n==="Bash"&&me(i)?fe(r,i):{timestamp:r,type:"tool_use",toolUseId:o,toolName:n,toolInput:i}}if(t==="tool_result"){let n=!!e.is_error,o=e.tool_use_id,s=e.output??e.content??"",i;return typeof s=="string"?i=s:Array.isArray(s)?i=s.filter(a=>a.type==="text"&&typeof a.text=="string").map(a=>a.text).join(`
3
- `):i=JSON.stringify(s),{timestamp:r,type:"tool_result",toolUseId:o,resultPreview:i,isError:n}}return null}var Ft,_r=ee(()=>{g();vr();Ze();Ft={command:"claude",buildArgs(r,e,t){if(e.additionalArgs!==void 0){let o=[...e.additionalArgs],s=o.indexOf("-p");return s!==-1?(o.splice(s+1,0,r),e.model&&o.push("--model",e.model),{args:o}):(e.model&&o.push("--model",e.model),{args:o,stdinMessage:r})}let n=["-p",r,"--output-format","stream-json","--verbose"];return e.model&&n.push("--model",e.model),{args:n}},extractText(r){let e=r.split(`
4
- `).filter(o=>o.trim()),t=[],n=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant"&&Array.isArray(s.message?.content))for(let i of s.message.content)i.type==="text"&&typeof i.text=="string"&&i.text.trim()&&t.push(i.text.trim());s.type==="result"&&typeof s.result=="string"&&(n=s.result);}catch{}return t.length>0?t.join(`
1
+ import*as W from'path';import W__default,{join,resolve,dirname,isAbsolute,basename}from'path';import {fileURLToPath}from'url';import {existsSync,readFileSync,readdirSync,appendFileSync,mkdirSync,writeFileSync,statSync}from'fs';import {spawn,execFileSync}from'child_process';import {ndJsonStream,ClientSideConnection}from'@agentclientprotocol/sdk';import {load}from'js-yaml';import {z as z$1}from'zod';import {createRequire}from'module';import*as se from'handlebars';import se__default from'handlebars';import {readFile,access}from'fs/promises';import {createHash,randomBytes}from'crypto';import {EventEmitter}from'events';import {AsyncLocalStorage}from'async_hooks';import {McpServer}from'@modelcontextprotocol/sdk/server/mcp.js';import {WebStandardStreamableHTTPServerTransport}from'@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';import gs,{homedir}from'os';import {sql,eq,or as or$1,isNull,desc,and,asc,inArray}from'drizzle-orm';import {sqliteTable,text,integer,real,index,unique}from'drizzle-orm/sqlite-core';import {performance}from'perf_hooks';var jt=Object.defineProperty;var Qn=Object.getOwnPropertyDescriptor;var Gn=Object.getOwnPropertyNames;var Yn=Object.prototype.hasOwnProperty;var B=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var N=(o,e)=>()=>(o&&(e=o(o=0)),e);var ct=(o,e)=>{for(var t in e)jt(o,t,{get:e[t],enumerable:true});},Zn=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Gn(e))!Yn.call(o,n)&&n!==t&&jt(o,n,{get:()=>e[n],enumerable:!(r=Qn(e,n))||r.enumerable});return o};var Ht=o=>Zn(jt({},"__esModule",{value:true}),o);var jr,ro,g,m,l=N(()=>{jr=()=>fileURLToPath(import.meta.url),ro=()=>W__default.dirname(jr()),g=ro(),m=jr();});function ft(o){return typeof o!="string"?void 0:o.trim()||void 0}function yt(o){return ft(o)?.toLowerCase()??""}function Ne(o){try{return statSync(o).isFile()}catch{return false}}function Fr(o,e){if(o.includes("/")||o.includes("\\")||W__default.isAbsolute(o))return o;let r=(e.PATH??e.Path??process.env.PATH??process.env.Path??"").split(";").map(a=>a.trim()).filter(Boolean),n=W__default.extname(o).length>0,s=e.PATHEXT??e.Pathext??process.env.PATHEXT??process.env.Pathext??".EXE;.CMD;.BAT;.COM",i=n?[""]:s.split(";").map(a=>a.trim()).filter(Boolean).map(a=>a.startsWith(".")?a:`.${a}`);for(let a of r)for(let d of i){let c=yt(d),u=d.toUpperCase();for(let p of [d,c,u]){let f=W__default.join(a,`${o}${p}`);if(Ne(f))return f}}return o}function fo(o){if(!Ne(o))return null;try{let e=readFileSync(o,"utf8"),t=W__default.dirname(o),r=[];for(let a of e.matchAll(/"([^"\r\n]*)"/g)){let u=(a[1]??"").match(/%~?dp0%?\s*[\\/]*(.*)$/i)?.[1]?.trim();if(!u)continue;let p=u.replace(/[\\/]+/g,W__default.sep).replace(/^[\\/]+/,""),f=W__default.resolve(t,p);Ne(f)&&r.push(f);}let n=[],s=new Map;for(let a of e.matchAll(/SET\s+"(\w+)=%~?dp0%?[\\/]?([^"]+)"/gi)){let d=a[1].toUpperCase(),c=a[2].trim().replace(/[\\/]+/g,W__default.sep).replace(/^[\\/]+/,"");s.set(d,W__default.resolve(t,c));}for(let a of e.split(/\r?\n/))if(a.includes("%*"))for(let d of a.matchAll(/"%(\w+)%"/g)){let c=s.get(d[1].toUpperCase());c&&Ne(c)&&n.push(c);}let i=a=>a.find(d=>{let c=yt(W__default.basename(d));return c!=="node.exe"&&c!=="node"})??null;return i(n)??i(r)}catch{return null}}function yo(o,e){if(typeof e=="string")return ft(e)||null;if(!e||typeof e!="object")return null;if(o){let t=e[o],r=typeof t=="string"?ft(t):void 0;if(r)return r}for(let t of Object.values(e)){let r=typeof t=="string"?ft(t):void 0;if(r)return r}return null}function ho(o,e){if(!e)return null;let t=W__default.dirname(o),r=[W__default.resolve(t,"..",e),W__default.resolve(t,"node_modules",e)];for(let n of r){let s=W__default.join(n,"package.json");if(Ne(s))try{let i=JSON.parse(readFileSync(s,"utf8")),a=yo(e,i.bin);if(!a)continue;let d=W__default.resolve(n,a);if(Ne(d))return d}catch{}}return null}function wo(o){let e=o.platform??process.platform,t=o.env??process.env,r=o.execPath??process.execPath;if(e!=="win32")return {command:o.command,leadingArgv:[],resolution:"direct"};let n=Fr(o.command,t),s=yt(W__default.extname(n));if(s===".js"||s===".cjs"||s===".mjs")return {command:r,leadingArgv:[n],resolution:"node-entrypoint",windowsHide:true};if(s===".cmd"||s===".bat"){let i=fo(n)??ho(n,o.packageName);return i?yt(W__default.extname(i))===".exe"?{command:i,leadingArgv:[],resolution:"exe-entrypoint",windowsHide:true}:{command:r,leadingArgv:[i],resolution:"node-entrypoint",windowsHide:true}:{command:n,leadingArgv:[],resolution:"unresolved-wrapper"}}return {command:n,leadingArgv:[],resolution:"direct"}}function xo(o){if(o.candidate.resolution!=="unresolved-wrapper")return {command:o.candidate.command,leadingArgv:o.candidate.leadingArgv,resolution:o.candidate.resolution,windowsHide:o.candidate.windowsHide};if(o.allowShellFallback===true)return {command:o.candidate.command,leadingArgv:[],resolution:"shell-fallback",shell:true};throw new Error(`${W__default.basename(o.candidate.command)} wrapper resolved, but no executable/Node entrypoint could be resolved without shell execution.`)}function qe(o){let e=wo(o);return xo({candidate:e,allowShellFallback:o.allowShellFallback})}function Fe(o,e){return {command:o.command,argv:[...o.leadingArgv,...e],resolution:o.resolution,shell:o.shell,windowsHide:o.windowsHide}}var ht=N(()=>{l();});function vo(o){if(o.type!=="usage"||!("input_tokens"in o))return null;let e=Number(o.input_tokens??0),t=Number(o.output_tokens??0),n="cache_read_input_tokens"in o?Number(o.cache_read_input_tokens):void 0,s="cached_input_tokens"in o?Number(o.cached_input_tokens):void 0,i=n!==void 0?n:s??0;return {inputTokens:n!==void 0?e+n:e,outputTokens:t,cachedInputTokens:i}}function ko(o){let e=o.usage;if(!e||typeof e!="object"||Array.isArray(e))return null;let t=e;if(!("input_tokens"in t))return null;let r=Number(t.input_tokens??0),n=Number(t.output_tokens??0),i="cache_read_input_tokens"in t?Number(t.cache_read_input_tokens):void 0,a="cached_input_tokens"in t?Number(t.cached_input_tokens):void 0,d=i!==void 0?i:a??0;return {inputTokens:i!==void 0?r+i:r,outputTokens:n,cachedInputTokens:d}}function _o(o){if(o.type!=="step_finish")return null;let t=o.part?.tokens;if(!t)return null;let r=Number(t.input??0),n=Number(t.output??0),s=t.cache,i=s?Number(s.read??0):0;return {inputTokens:r+i,outputTokens:n,cachedInputTokens:i}}function G(o){if(!o||!o.trim())return;let e=null;for(let t of o.split(`
2
+ `))if(t.trim())try{let r=JSON.parse(t),n=vo(r)??ko(r)??_o(r);n&&(e=n);}catch{}return e??void 0}var Ae=N(()=>{l();});var We,qt=N(()=>{l();We=class extends Error{name="RateLimitError";constructor(e){super(e);}};});function Y(o){return /crewx\s+(x|execute)\s/.test(o)}function Z(o,e){let t=e.match(/@(\S+)/);return {timestamp:o,type:"agent_call",targetAgent:t?.[1]?.replace(/["']/g,""),toolInput:e}}var De=N(()=>{l();});function ee(o){if(typeof o=="string")return o;if(!o||typeof o!="object")return JSON.stringify(o??{});let e=o;return typeof e.command=="string"?e.command:typeof e.file_path=="string"?e.file_path:typeof e.filePath=="string"?e.filePath:typeof e.path=="string"?e.path:typeof e.query=="string"?e.query:typeof e.pattern=="string"?e.pattern:typeof e.url=="string"?e.url:typeof e.prompt=="string"?e.prompt.length>200?e.prompt.slice(0,200)+"\u2026":e.prompt:typeof e.description=="string"?e.description:JSON.stringify(e)}var $e=N(()=>{l();});function Ro(o,e){let t=e.type;if(t==="text"){let r=String(e.text||"");return r?{timestamp:o,type:"text",content:r}:null}if(t==="thinking"){let r=String(e.thinking||"");return {timestamp:o,type:"thinking",content:r||"(thinking)"}}if(t==="tool_use"){let r=String(e.name||""),n=e.id,s=e.input,i=ee(s);return r==="Bash"&&Y(i)?Z(o,i):{timestamp:o,type:"tool_use",toolUseId:n,toolName:r,toolInput:i}}if(t==="tool_result"){let r=!!e.is_error,n=e.tool_use_id,s=e.output??e.content??"",i;return typeof s=="string"?i=s:Array.isArray(s)?i=s.filter(a=>a.type==="text"&&typeof a.text=="string").map(a=>a.text).join(`
3
+ `):i=JSON.stringify(s),{timestamp:o,type:"tool_result",toolUseId:n,resultPreview:i,isError:r}}return null}var wt,Ft=N(()=>{l();qt();De();$e();wt={command:"claude",buildArgs(o,e,t){if(e.additionalArgs!==void 0){let n=[...e.additionalArgs],s=n.indexOf("-p");return s!==-1?(n.splice(s+1,0,o),e.model&&n.push("--model",e.model),{args:n}):(e.model&&n.push("--model",e.model),{args:n,stdinMessage:o})}let r=["-p",o,"--output-format","stream-json","--verbose"];return e.model&&r.push("--model",e.model),{args:r}},extractText(o){let e=o.split(`
4
+ `).filter(n=>n.trim()),t=[],r=null;for(let n of e)try{let s=JSON.parse(n);if(s.type==="assistant"&&Array.isArray(s.message?.content))for(let i of s.message.content)i.type==="text"&&typeof i.text=="string"&&i.text.trim()&&t.push(i.text.trim());s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}return t.length>0?t.join(`
5
5
 
6
- `):n||r.trim()},extractFailure(r){if(r.includes('"rate_limit_event"'))try{let e=JSON.parse(r);if(e.type==="rate_limit_event"){let t=e.rate_limit_info??{};if(t.status==="rejected")return new ut(`Claude rate limit: ${t.rateLimitType??"unknown"} (status: ${t.status})`)}}catch{}return null},parseResultMeta(r){let e=r.split(`
7
- `);for(let t of e)if(t.trim())try{let n=JSON.parse(t);if(n.type==="result"){let o=n.usage,s=o?{inputTokens:Number(o.input_tokens??0)+Number(o.cache_read_input_tokens??0),outputTokens:Number(o.output_tokens??0),cachedInputTokens:Number(o.cache_read_input_tokens??0),costUsd:Number(n.total_cost_usd??0)}:null,i=n.modelUsage,a=i?Object.keys(i)[0]??null:null;return {usage:s,model:a}}}catch{}return {usage:null,model:null}},parseEvent(r,e){let t;try{t=JSON.parse(r);}catch{return []}let n=t.type;if(!n)return [];if(n!=="assistant"&&n!=="user")return [];let s=t.message?.content;if(!Array.isArray(s))return [];let i=e??new Date().toISOString(),a=[];for(let l of s){let u=Xi(i,l);u&&a.push(u);}return a}};});var Ut,wr=ee(()=>{g();Le();Ze();Ut={command:"gemini",buildArgs(r,e,t){if(e.additionalArgs!==void 0){let o=[...e.additionalArgs],s=o.indexOf("-p");return s!==-1?(o.splice(s+1,0,r),e.model&&o.push("--model",e.model),{args:o}):(e.model&&o.push("--model",e.model),{args:o,stdinMessage:r})}let n=["-p",r,"--output-format","stream-json","--verbose"];return e.model&&n.push("--model",e.model),{args:n}},extractText(r){let e=r.split(`
8
- `).filter(o=>o.trim()),t=[],n=null;for(let o of e)try{let s=JSON.parse(o);s.type==="message"&&s.role==="assistant"&&s.delta===!0&&typeof s.content=="string"&&t.push(s.content),s.type==="result"&&typeof s.result=="string"&&(n=s.result);}catch{}return t.length>0?t.join(""):n||r.trim()},parseResultMeta(r){let e=ge(r);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(r,e){let t;try{t=JSON.parse(r);}catch{return []}let n=t.type;if(!n)return [];if(n!=="message"&&n!=="tool_use"&&n!=="tool_result")return [];let o=e??new Date().toISOString();if(n==="message"){if(t.role!=="assistant")return [];let i=t.content;return i?[{timestamp:o,type:"text",content:i}]:[]}if(n==="tool_use"){let s=String(t.tool_name||""),i=t.tool_id,a=t.parameters,l=a?.command?String(a.command):JSON.stringify(a||{});return /^bash$/i.test(s)&&me(l)?[fe(o,l)]:[{timestamp:o,type:"tool_use",toolName:s,toolUseId:i,toolInput:l}]}if(n==="tool_result"){let s=t.tool_id,i=String(t.output||""),a=t.status!=="success";return [{timestamp:o,type:"tool_result",toolUseId:s,resultPreview:i,isError:a}]}return []}};});var Bt,br=ee(()=>{g();Le();Ze();Bt={command:"copilot",buildArgs(r,e,t){let n=e.additionalArgs?[...e.additionalArgs]:[];return e.model&&n.push("--model",e.model),{args:n,stdinMessage:r}},extractText(r){let e=r.split(`
9
- `).filter(o=>o.trim()),t=[],n=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="assistant.message"&&typeof s.data?.content=="string"){let i=s.data.content;i.trim()&&t.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(n=s.result);}catch{}return t.length>0?t.join(`
6
+ `):r||o.trim()},extractFailure(o){if(o.includes('"rate_limit_event"'))try{let e=JSON.parse(o);if(e.type==="rate_limit_event"){let t=e.rate_limit_info??{};if(t.status==="rejected")return new We(`Claude rate limit: ${t.rateLimitType??"unknown"} (status: ${t.status})`)}}catch{}return null},parseResultMeta(o){let e=o.split(`
7
+ `);for(let t of e)if(t.trim())try{let r=JSON.parse(t);if(r.type==="result"){let n=r.usage,s=n?{inputTokens:Number(n.input_tokens??0)+Number(n.cache_read_input_tokens??0),outputTokens:Number(n.output_tokens??0),cachedInputTokens:Number(n.cache_read_input_tokens??0),costUsd:Number(r.total_cost_usd??0)}:null,i=r.modelUsage,a=i?Object.keys(i)[0]??null:null;return {usage:s,model:a}}}catch{}return {usage:null,model:null}},parseEvent(o,e){let t;try{t=JSON.parse(o);}catch{return []}let r=t.type;if(!r)return [];if(r!=="assistant"&&r!=="user")return [];let s=t.message?.content;if(!Array.isArray(s))return [];let i=e??new Date().toISOString(),a=[];for(let d of s){let c=Ro(i,d);c&&a.push(c);}return a}};});var xt,Wt=N(()=>{l();Ae();De();$e();xt={command:"gemini",buildArgs(o,e,t){if(e.additionalArgs!==void 0){let n=[...e.additionalArgs],s=n.indexOf("-p");return s!==-1?(n.splice(s+1,0,o),e.model&&n.push("--model",e.model),{args:n}):(e.model&&n.push("--model",e.model),{args:n,stdinMessage:o})}let r=["-p",o,"--output-format","stream-json","--verbose"];return e.model&&r.push("--model",e.model),{args:r}},extractText(o){let e=o.split(`
8
+ `).filter(n=>n.trim()),t=[],r=null;for(let n of e)try{let s=JSON.parse(n);s.type==="message"&&s.role==="assistant"&&s.delta===!0&&typeof s.content=="string"&&t.push(s.content),s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}return t.length>0?t.join(""):r||o.trim()},parseResultMeta(o){let e=G(o);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(o,e){let t;try{t=JSON.parse(o);}catch{return []}let r=t.type;if(!r)return [];if(r!=="message"&&r!=="tool_use"&&r!=="tool_result")return [];let n=e??new Date().toISOString();if(r==="message"){if(t.role!=="assistant")return [];let i=t.content;return i?[{timestamp:n,type:"text",content:i}]:[]}if(r==="tool_use"){let s=String(t.tool_name||""),i=t.tool_id,a=t.parameters,d=ee(a);return /^bash$/i.test(s)&&Y(d)?[Z(n,d)]:[{timestamp:n,type:"tool_use",toolName:s,toolUseId:i,toolInput:d}]}if(r==="tool_result"){let s=t.tool_id,i=String(t.output||""),a=t.status!=="success";return [{timestamp:n,type:"tool_result",toolUseId:s,resultPreview:i,isError:a}]}return []}};});var vt,Bt=N(()=>{l();Ae();De();$e();vt={command:"copilot",buildArgs(o,e,t){let r=e.additionalArgs?[...e.additionalArgs]:[];return e.model&&r.push("--model",e.model),{args:r,stdinMessage:o}},extractText(o){let e=o.split(`
9
+ `).filter(n=>n.trim()),t=[],r=null;for(let n of e)try{let s=JSON.parse(n);if(s.type==="assistant.message"&&typeof s.data?.content=="string"){let i=s.data.content;i.trim()&&t.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}return t.length>0?t.join(`
10
10
 
11
- `):n||r.trim()},parseResultMeta(r){let e=ge(r);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(r,e){let t;try{t=JSON.parse(r);}catch{return []}let n=t.type;if(!n)return [];if(!n.startsWith("tool.execution")&&!n.startsWith("assistant.")&&n!=="user.message")return [];let o=t.data;if(!o)return [];let s=e??new Date().toISOString(),i=o.toolCallId;if(n==="tool.execution_start"){let a=String(o.toolName||""),l=o.arguments,u=l?.command?String(l.command):JSON.stringify(l||{});return (a==="bash"||a==="Bash")&&me(u)?[fe(s,u)]:[{timestamp:s,type:"tool_use",toolName:a,toolInput:u,...i&&{toolUseId:i}}]}if(n==="tool.execution_complete"){let a=o.error;if(a)return [{timestamp:s,type:"tool_result",isError:true,resultPreview:String(a.message||""),...i&&{toolUseId:i}}];let l=o.result,u=String(l?.content||"");return [{timestamp:s,type:"tool_result",resultPreview:u,isError:false,...i&&{toolUseId:i}}]}if(n==="assistant.message"){let a=String(o.content||"");return a?[{timestamp:s,type:"text",content:a}]:[]}return []}};});function Yi(r,e){if(e.type==="command_execution"){let n=String(e.command||"");return me(n)?[fe(r,n)]:[{timestamp:r,type:"tool_use",toolName:"Bash",toolInput:n}]}return []}function Qi(r,e){let t=e.type;if(t==="message"||t==="text"){let n=e.content;if(Array.isArray(n))for(let o of n){let s=Zi(r,o);if(s)return s}if(typeof e.text=="string")return {timestamp:r,type:"text",content:e.text}}if(t==="reasoning")return {timestamp:r,type:"text",content:String(e.text||"")};if(t==="command_execution"){let n=String(e.aggregated_output||e.output||""),o=!!e.is_error;return {timestamp:r,type:"tool_result",resultPreview:n,isError:o}}if(t==="tool_use"){let n=String(e.name||e.tool_name||""),o=e.input,s=o?.command?String(o.command):JSON.stringify(o||{});return n==="Bash"&&me(s)?fe(r,s):{timestamp:r,type:"tool_use",toolName:n,toolInput:s}}if(t==="tool_result"){let n=!!e.is_error,o=String(e.output||e.content||"");return {timestamp:r,type:"tool_result",resultPreview:o,isError:n}}return null}function Zi(r,e){let t=e.type;if(t==="text")return {timestamp:r,type:"text",content:String(e.text||"")};if(t==="tool_use"){let n=String(e.name||""),o=e.input,s=o?.command?String(o.command):JSON.stringify(o||{});return n==="Bash"&&me(s)?fe(r,s):{timestamp:r,type:"tool_use",toolName:n,toolInput:s}}return null}var Wt,xr=ee(()=>{g();Le();Ze();Wt={command:"codex",buildArgs(r,e,t){if(e.additionalArgs!==void 0){let o=[...e.additionalArgs];return !o.includes("--json")&&!o.includes("--experimental-json")&&o.push("--json"),e.model&&o.push("--model",e.model),{args:o,stdinMessage:r}}let n=["exec","--json"];return e.model&&n.push("--model",e.model),{args:n,stdinMessage:r}},extractText(r){let e=r.split(`
12
- `).filter(o=>o.trim()),t=[],n=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="item.completed"&&(s.item?.type==="message"||s.item?.type==="agent_message")&&typeof s.item?.text=="string"){let i=s.item.text;i.trim()&&t.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(n=s.result);}catch{}return t.length>0?t.join(`
11
+ `):r||o.trim()},parseResultMeta(o){let e=G(o);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(o,e){let t;try{t=JSON.parse(o);}catch{return []}let r=t.type;if(!r)return [];if(!r.startsWith("tool.execution")&&!r.startsWith("assistant.")&&r!=="user.message")return [];let n=t.data;if(!n)return [];let s=e??new Date().toISOString(),i=n.toolCallId;if(r==="tool.execution_start"){let a=String(n.toolName||""),d=n.arguments,c=ee(d);return (a==="bash"||a==="Bash")&&Y(c)?[Z(s,c)]:[{timestamp:s,type:"tool_use",toolName:a,toolInput:c,...i&&{toolUseId:i}}]}if(r==="tool.execution_complete"){let a=n.error;if(a)return [{timestamp:s,type:"tool_result",isError:true,resultPreview:String(a.message||""),...i&&{toolUseId:i}}];let d=n.result,c=String(d?.content||"");return [{timestamp:s,type:"tool_result",resultPreview:c,isError:false,...i&&{toolUseId:i}}]}if(r==="assistant.message"){let a=String(n.content||"");return a?[{timestamp:s,type:"text",content:a}]:[]}return []}};});function Po(o,e){if(e.type==="command_execution"){let r=String(e.command||"");return Y(r)?[Z(o,r)]:[{timestamp:o,type:"tool_use",toolName:"Bash",toolInput:r}]}return []}function Ao(o,e){let t=e.type;if(t==="message"||t==="text"){let r=e.content;if(Array.isArray(r))for(let n of r){let s=Co(o,n);if(s)return s}if(typeof e.text=="string")return {timestamp:o,type:"text",content:e.text}}if(t==="reasoning")return {timestamp:o,type:"text",content:String(e.text||"")};if(t==="command_execution"){let r=String(e.aggregated_output||e.output||""),n=!!e.is_error;return {timestamp:o,type:"tool_result",resultPreview:r,isError:n}}if(t==="tool_use"){let r=String(e.name||e.tool_name||""),n=e.input,s=ee(n);return r==="Bash"&&Y(s)?Z(o,s):{timestamp:o,type:"tool_use",toolName:r,toolInput:s}}if(t==="tool_result"){let r=!!e.is_error,n=String(e.output||e.content||"");return {timestamp:o,type:"tool_result",resultPreview:n,isError:r}}return null}function Co(o,e){let t=e.type;if(t==="text")return {timestamp:o,type:"text",content:String(e.text||"")};if(t==="tool_use"){let r=String(e.name||""),n=e.input,s=ee(n);return r==="Bash"&&Y(s)?Z(o,s):{timestamp:o,type:"tool_use",toolName:r,toolInput:s}}return null}var kt,zt=N(()=>{l();Ae();De();$e();kt={command:"codex",buildArgs(o,e,t){if(e.additionalArgs!==void 0){let n=[...e.additionalArgs];return !n.includes("--json")&&!n.includes("--experimental-json")&&n.push("--json"),e.model&&n.push("--model",e.model),{args:n,stdinMessage:o}}let r=["exec","--json"];return e.model&&r.push("--model",e.model),{args:r,stdinMessage:o}},extractText(o){let e=o.split(`
12
+ `).filter(n=>n.trim()),t=[],r=null;for(let n of e)try{let s=JSON.parse(n);if(s.type==="item.completed"&&(s.item?.type==="message"||s.item?.type==="agent_message")&&typeof s.item?.text=="string"){let i=s.item.text;i.trim()&&t.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}return t.length>0?t.join(`
13
13
 
14
- `):n||r.trim()},parseResultMeta(r){let e=ge(r);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(r,e){let t;try{t=JSON.parse(r);}catch{return []}let n=t.type;if(!n)return [];if(!n.startsWith("item.")&&!n.startsWith("turn.")&&!n.startsWith("thread."))return [];let o=t.item;if(!o)return [];let s=e??new Date().toISOString();if(n==="item.started")return Yi(s,o);if(n==="item.completed"){let i=Qi(s,o);return i?[i]:[]}return []}};});function ea(r){if(typeof r=="string")return r;if(!r||typeof r!="object")return JSON.stringify(r??{});let e=r;return e.command?String(e.command):e.filePath?String(e.filePath):e.pattern?String(e.pattern):JSON.stringify(e)}var Jt,kr=ee(()=>{g();Le();Jt={command:"opencode",buildArgs(r,e,t){let n=e.additionalArgs,o=n!==void 0?[...n]:["run"];return o.includes("--format")||o.push("--format","json"),e.model&&o.push("--model",e.model),o.push(r),{args:o}},extractText(r){let e=r.split(`
15
- `).filter(o=>o.trim()),t=[],n=null;for(let o of e)try{let s=JSON.parse(o);if(s.type==="text"&&typeof s.part?.text=="string"){let i=s.part.text;i.trim()&&t.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(n=s.result);}catch{}return t.length>0?t.join(""):n||r.trim()},parseResultMeta(r){let e=ge(r);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(r,e){let t;try{t=JSON.parse(r);}catch{return []}let n=t.type;if(!n)return [];let o=e??new Date().toISOString();if(n==="text"){let i=t.part?.text;return i?[{timestamp:o,type:"text",content:i}]:[]}if(n==="tool_use"){let s=t.part;if(!s)return [];let i=String(s.tool||""),a=String(s.callID||""),l=s.state,u=String(l?.status||""),d=l?.input,c=ea(d),p=[{timestamp:o,type:"tool_use",toolName:i,toolUseId:a,toolInput:c}];if(u==="completed"&&l?.output!==void 0){let f=l.output,v=typeof f=="string"?f:JSON.stringify(f);p.push({timestamp:o,type:"tool_result",toolUseId:a,resultPreview:v,isError:false});}else u==="error"&&p.push({timestamp:o,type:"tool_result",toolUseId:a,resultPreview:String(l?.error||"tool error"),isError:true});return p}return []}};});function Rr(r,e,t){if(t){let n=ze[t];if(n?.parseEvent)return n.parseEvent(e,r)}for(let n of Object.values(ze)){let o=n.parseEvent?.(e,r)??[];if(o.length>0)return o}return []}var ze,et=ee(()=>{g();_r();wr();br();xr();kr();_r();wr();br();xr();kr();Ze();ze={claude:Ft,gemini:Ut,copilot:Bt,codex:Wt,opencode:Jt};});function ra(r){let e=r.split(`
16
- `).filter(l=>l.trim()),t=[],n=[],o=[],s=[],i=[],a=null;for(let l of e)try{let u=JSON.parse(l);if(u.type==="assistant"&&Array.isArray(u.message?.content))for(let d of u.message.content)d.type==="text"&&typeof d.text=="string"&&d.text.trim()&&t.push(d.text.trim());if(u.type==="message"&&u.role==="assistant"&&u.delta===!0&&typeof u.content=="string"&&n.push(u.content),u.type==="assistant.message"&&typeof u.data?.content=="string"){let d=u.data.content;d.trim()&&o.push(d.trim());}if(u.type==="item.completed"&&(u.item?.type==="message"||u.item?.type==="agent_message")&&typeof u.item?.text=="string"){let d=u.item.text;d.trim()&&s.push(d.trim());}if(u.type==="text"&&typeof u.part?.text=="string"){let d=u.part.text;d.trim()&&i.push(d.trim());}u.type==="result"&&typeof u.result=="string"&&(a=u.result);}catch{}return t.length>0?t.join(`
14
+ `):r||o.trim()},parseResultMeta(o){let e=G(o);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(o,e){let t;try{t=JSON.parse(o);}catch{return []}let r=t.type;if(!r)return [];if(!r.startsWith("item.")&&!r.startsWith("turn.")&&!r.startsWith("thread."))return [];let n=t.item;if(!n)return [];let s=e??new Date().toISOString();if(r==="item.started")return Po(s,n);if(r==="item.completed"){let i=Ao(s,n);return i?[i]:[]}return []}};});var _t,Vt=N(()=>{l();Ae();$e();_t={command:"opencode",buildArgs(o,e,t){let r=e.additionalArgs,n=r!==void 0?[...r]:["run"];return n.includes("--format")||n.push("--format","json"),e.model&&n.push("--model",e.model),n.push(o),{args:n}},extractText(o){let e=o.split(`
15
+ `).filter(n=>n.trim()),t=[],r=null;for(let n of e)try{let s=JSON.parse(n);if(s.type==="text"&&typeof s.part?.text=="string"){let i=s.part.text;i.trim()&&t.push(i.trim());}s.type==="result"&&typeof s.result=="string"&&(r=s.result);}catch{}return t.length>0?t.join(""):r||o.trim()},parseResultMeta(o){let e=G(o);return e?{usage:{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0},model:null}:{usage:null,model:null}},parseEvent(o,e){let t;try{t=JSON.parse(o);}catch{return []}let r=t.type;if(!r)return [];let n=e??new Date().toISOString();if(r==="text"){let i=t.part?.text;return i?[{timestamp:n,type:"text",content:i}]:[]}if(r==="tool_use"){let s=t.part;if(!s)return [];let i=String(s.tool||""),a=String(s.callID||""),d=s.state,c=String(d?.status||""),u=d?.input,p=ee(u),f=[{timestamp:n,type:"tool_use",toolName:i,toolUseId:a,toolInput:p}];if(c==="completed"&&d?.output!==void 0){let y=d.output,h=typeof y=="string"?y:JSON.stringify(y);f.push({timestamp:n,type:"tool_result",toolUseId:a,resultPreview:h,isError:false});}else c==="error"&&f.push({timestamp:n,type:"tool_result",toolUseId:a,resultPreview:String(d?.error||"tool error"),isError:true});return f}return []}};});function Kt(o,e,t){if(t){let r=ye[t];if(r?.parseEvent)return r.parseEvent(e,o)}for(let r of Object.values(ye)){let n=r.parseEvent?.(e,o)??[];if(n.length>0)return n}return []}var ye,Le=N(()=>{l();Ft();Wt();Bt();zt();Vt();Ft();Wt();Bt();zt();Vt();De();ye={claude:wt,gemini:xt,copilot:vt,codex:kt,opencode:_t};});function To(o){let e=o.split(`
16
+ `).filter(d=>d.trim()),t=[],r=[],n=[],s=[],i=[],a=null;for(let d of e)try{let c=JSON.parse(d);if(c.type==="assistant"&&Array.isArray(c.message?.content))for(let u of c.message.content)u.type==="text"&&typeof u.text=="string"&&u.text.trim()&&t.push(u.text.trim());if(c.type==="message"&&c.role==="assistant"&&c.delta===!0&&typeof c.content=="string"&&r.push(c.content),c.type==="assistant.message"&&typeof c.data?.content=="string"){let u=c.data.content;u.trim()&&n.push(u.trim());}if(c.type==="item.completed"&&(c.item?.type==="message"||c.item?.type==="agent_message")&&typeof c.item?.text=="string"){let u=c.item.text;u.trim()&&s.push(u.trim());}if(c.type==="text"&&typeof c.part?.text=="string"){let u=c.part.text;u.trim()&&i.push(u.trim());}c.type==="result"&&typeof c.result=="string"&&(a=c.result);}catch{}return t.length>0?t.join(`
17
17
 
18
- `):n.length>0?n.join(""):o.length>0?o.join(`
18
+ `):r.length>0?r.join(""):n.length>0?n.join(`
19
19
 
20
20
  `):s.length>0?s.join(`
21
21
 
22
- `):i.length>0?i.join(""):a||r.trim()}function na(r){let e=ge(r);return e?{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0}:null}function oa(r,e,t,n,o,s,i){return new Promise((a,l)=>{let u=o?.timeoutMs??36e5,d=at({command:r,allowShellFallback:true}),c=lt(d,e),p=spawn(c.command,c.argv,{env:{...process.env,...o?.env??{}},cwd:o?.cwd,stdio:["pipe","pipe","pipe"],shell:c.shell??false,windowsHide:c.windowsHide});s!==void 0&&p.stdin.write(s),p.stdin.end(),p.pid!==void 0&&o?.onPid?.(p.pid);let f=false,v=false,h=()=>{try{p.kill("SIGKILL");}catch{}},y=setTimeout(()=>{if(!f){v=true;try{p.kill("SIGTERM");}catch{}setTimeout(h,zn).unref();}},u);y.unref();let w="",C="",_="",k="";p.stdout.on("data",S=>{let z=S.toString();w+=z,_+=z;let R=_.split(`
23
- `);_=R.pop()??"";for(let x of R)if(x.trim()&&(o?.onOutput?.(x,"stdout"),i?.extractFailure)){let M=i.extractFailure(x);if(M){f=true,clearTimeout(y);try{p.kill("SIGTERM");}catch{}setTimeout(h,zn).unref(),l(M);return}}}),p.stderr.on("data",S=>{let z=S.toString();C+=z,k+=z;let R=k.split(`
24
- `);k=R.pop()??"";for(let x of R)x.trim()&&o?.onOutput?.(x,"stderr");}),p.on("error",S=>{f=true,clearTimeout(y),S.code==="ENOENT"?l(new X(`CLI command "${r}" not found. Is ${t} installed?`,t)):l(new X(`Spawn error: ${S.message}`,t));}),p.on("close",S=>{if(f)return;f=true,clearTimeout(y),_.trim()&&o?.onOutput?.(_,"stdout"),k.trim()&&o?.onOutput?.(k,"stderr");let z=S??0;if(o?.onExitCode?.(z),v&&S!==0)return l(new Cr(`Total runtime exceeded ${u}ms; process killed.`,t));if(z!==0){if(i?.interpretExit){let x=i.interpretExit(z,C);if(x){l(x);return}}l(new X(`Process exited with code ${z}: ${C.slice(0,500)}`,t));return}let R=i?i.extractText(w):ra(w);a({stdout:w,parsed:R});});})}function tt(r,e){Mn.set(r,e);}function Ce(r){let e=r.split("/");if(e.length!==2)throw new X(`Invalid provider format: "${r}". Expected namespace/id (e.g., cli/claude)`,r);let[t,n]=e,o=Mn.get(t);if(o)return o(n,r);if(t==="cli"){let s=ze[n];if(!s)throw new X(`Unknown CLI provider id: "${n}". Supported: ${Object.keys(ze).join(", ")}`,r);return new Tr(n,s,r)}throw new X(`Unsupported provider namespace: "${t}". Register a factory with registerProviderFactory('${t}', factory).`,r)}var X,Cr,zn,he,Mn,Tr,Fe=ee(()=>{g();Lt();Le();et();X=class extends Error{constructor(t,n){super(t);this.providerStr=n;this.name="ProviderError";}providerStr},Cr=class extends X{constructor(e,t){super(e,t),this.name="TotalTimeoutError";}},zn=2e3;he=class extends Error{constructor(t,n){super(`Client tool call required: ${t.toolName}`);this.toolCall=t;this.continuationState=n;}toolCall;continuationState;name="ClientToolCallRequiredError"},Mn=new Map;Tr=class{constructor(e,t,n){this.providerId=e;this.adapter=t;this.providerStr=n;}providerId;adapter;providerStr;async execute(e,t){let n=this.composeMessage(e,t),{args:o,stdinMessage:s}=this.adapter.buildArgs(n,t??{},true);t?.onCommand?.(`${this.adapter.command} ${o.join(" ")}`);let{stdout:i,parsed:a}=await this.runProcess(o,t,s);return this.handleResultMeta(i,t),a}async query(e,t){let n=this.composeMessage(e,t),{args:o,stdinMessage:s}=this.adapter.buildArgs(n,t??{},false);t?.onCommand?.(`${this.adapter.command} ${o.join(" ")}`);let{stdout:i,parsed:a}=await this.runProcess(o,t,s);return this.handleResultMeta(i,t),a}composeMessage(e,t){return t?.systemPrompt?`${t.systemPrompt}
22
+ `):i.length>0?i.join(""):a||o.trim()}function Eo(o){let e=G(o);return e?{inputTokens:e.inputTokens,outputTokens:e.outputTokens,cachedInputTokens:e.cachedInputTokens,costUsd:0}:null}function So(o,e,t,r,n,s,i){return new Promise((a,d)=>{let c=n?.timeoutMs??36e5,u=qe({command:o,allowShellFallback:true}),p=Fe(u,e),f=spawn(p.command,p.argv,{env:{...process.env,...n?.env??{}},cwd:n?.cwd,stdio:["pipe","pipe","pipe"],shell:p.shell??false,windowsHide:p.windowsHide});s!==void 0&&f.stdin.write(s),f.stdin.end(),f.pid!==void 0&&n?.onPid?.(f.pid);let y=false,h=false,x=()=>{try{f.kill("SIGKILL");}catch{}},R=setTimeout(()=>{if(!y){h=true;try{f.kill("SIGTERM");}catch{}setTimeout(x,Wr).unref();}},c);R.unref();let k="",C="",S="",O="";f.stdout.on("data",U=>{let H=U.toString();k+=H,S+=H;let T=S.split(`
23
+ `);S=T.pop()??"";for(let M of T)if(M.trim()&&(n?.onOutput?.(M,"stdout"),i?.extractFailure)){let _=i.extractFailure(M);if(_){y=true,clearTimeout(R);try{f.kill("SIGTERM");}catch{}setTimeout(x,Wr).unref(),d(_);return}}}),f.stderr.on("data",U=>{let H=U.toString();C+=H,O+=H;let T=O.split(`
24
+ `);O=T.pop()??"";for(let M of T)M.trim()&&n?.onOutput?.(M,"stderr");}),f.on("error",U=>{y=true,clearTimeout(R),U.code==="ENOENT"?d(new b(`CLI command "${o}" not found. Is ${t} installed?`,t)):d(new b(`Spawn error: ${U.message}`,t));}),f.on("close",U=>{if(y)return;y=true,clearTimeout(R),S.trim()&&n?.onOutput?.(S,"stdout"),O.trim()&&n?.onOutput?.(O,"stderr");let H=U??0;if(n?.onExitCode?.(H),h&&U!==0)return d(new Be(`Total runtime exceeded ${c}ms; process killed.`,t));if(H!==0){if(i?.interpretExit){let M=i.interpretExit(H,C);if(M){d(M);return}}d(new b(`Process exited with code ${H}: ${C.slice(0,500)}`,t));return}let T=i?i.extractText(k):To(k);a({stdout:k,parsed:T});});})}function ce(o,e){Br.set(o,e);}function ue(o){let e=o.split("/");if(e.length!==2)throw new b(`Invalid provider format: "${o}". Expected namespace/id (e.g., cli/claude)`,o);let[t,r]=e,n=Br.get(t);if(n)return n(r,o);if(t==="cli"){let s=ye[r];if(!s)throw new b(`Unknown CLI provider id: "${r}". Supported: ${Object.keys(ye).join(", ")}`,o);return new Jt(r,s,o)}throw new b(`Unsupported provider namespace: "${t}". Register a factory with registerProviderFactory('${t}', factory).`,o)}var b,Be,Wr,te,Br,Jt,oe=N(()=>{l();ht();Ae();Le();b=class extends Error{constructor(t,r){super(t);this.providerStr=r;this.name="ProviderError";}providerStr},Be=class extends b{constructor(e,t){super(e,t),this.name="TotalTimeoutError";}},Wr=2e3;te=class extends Error{constructor(t,r){super(`Client tool call required: ${t.toolName}`);this.toolCall=t;this.continuationState=r;}toolCall;continuationState;name="ClientToolCallRequiredError"},Br=new Map;Jt=class{constructor(e,t,r){this.providerId=e;this.adapter=t;this.providerStr=r;}providerId;adapter;providerStr;async execute(e,t){let r=this.composeMessage(e,t),{args:n,stdinMessage:s}=this.adapter.buildArgs(r,t??{},true);t?.onCommand?.(`${this.adapter.command} ${n.join(" ")}`);let{stdout:i,parsed:a}=await this.runProcess(n,t,s);return this.handleResultMeta(i,t),a}async query(e,t){let r=this.composeMessage(e,t),{args:n,stdinMessage:s}=this.adapter.buildArgs(r,t??{},false);t?.onCommand?.(`${this.adapter.command} ${n.join(" ")}`);let{stdout:i,parsed:a}=await this.runProcess(n,t,s);return this.handleResultMeta(i,t),a}composeMessage(e,t){return t?.systemPrompt?`${t.systemPrompt}
25
25
 
26
26
  ---
27
27
 
28
- ${e}`:e}runProcess(e,t,n){return oa(this.adapter.command,e,this.providerStr,this.providerId,t,n,this.adapter)}handleResultMeta(e,t){if(!this.adapter.parseResultMeta){let i=na(e);i&&t?.onUsage&&t.onUsage(i);return}let{usage:n,model:o}=this.adapter.parseResultMeta(e);n&&t?.onUsage&&t.onUsage(n);let s=o??(this.providerId==="opencode"?t?.model??null:null);s&&t?.onModel&&t.onModel(s);}};});var W=$e((py,Xo)=>{g();var Br=Object.defineProperty,ml=Object.getOwnPropertyDescriptor,fl=Object.getOwnPropertyNames,hl=Object.prototype.hasOwnProperty,yl=(r,e)=>{for(var t in e)Br(r,t,{get:e[t],enumerable:true});},vl=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of fl(e))!hl.call(r,o)&&o!==t&&Br(r,o,{get:()=>e[o],enumerable:!(n=ml(e,o))||n.enumerable});return r},_l=r=>vl(Br({},"__esModule",{value:true}),r),io={};yl(io,{AISDKError:()=>U,APICallError:()=>kl,EmptyResponseBodyError:()=>Cl,InvalidArgumentError:()=>Pl,InvalidPromptError:()=>El,InvalidResponseDataError:()=>Il,JSONParseError:()=>zl,LoadAPIKeyError:()=>jl,LoadSettingError:()=>Dl,NoContentGeneratedError:()=>Hl,NoSuchModelError:()=>Ll,TooManyEmbeddingValuesForCallError:()=>Ul,TypeValidationError:()=>Jl,UnsupportedFunctionalityError:()=>Kl,getErrorMessage:()=>Wr,isJSONArray:()=>Gl,isJSONObject:()=>Xl,isJSONValue:()=>vt});Xo.exports=_l(io);var ao="vercel.ai.error",wl=Symbol.for(ao),lo,bl=class uo extends Error{constructor({name:e,message:t,cause:n}){super(t),this[lo]=true,this.name=e,this.cause=n;}static isInstance(e){return uo.hasMarker(e,ao)}static hasMarker(e,t){let n=Symbol.for(t);return e!=null&&typeof e=="object"&&n in e&&typeof e[n]=="boolean"&&e[n]===true}};lo=wl;var U=bl,co="AI_APICallError",po=`vercel.ai.error.${co}`,xl=Symbol.for(po),go,kl=class extends U{constructor({message:r,url:e,requestBodyValues:t,statusCode:n,responseHeaders:o,responseBody:s,cause:i,isRetryable:a=n!=null&&(n===408||n===409||n===429||n>=500),data:l}){super({name:co,message:r,cause:i}),this[go]=true,this.url=e,this.requestBodyValues=t,this.statusCode=n,this.responseHeaders=o,this.responseBody=s,this.isRetryable=a,this.data=l;}static isInstance(r){return U.hasMarker(r,po)}};go=xl;var mo="AI_EmptyResponseBodyError",fo=`vercel.ai.error.${mo}`,Rl=Symbol.for(fo),ho,Cl=class extends U{constructor({message:r="Empty response body"}={}){super({name:mo,message:r}),this[ho]=true;}static isInstance(r){return U.hasMarker(r,fo)}};ho=Rl;function Wr(r){return r==null?"unknown error":typeof r=="string"?r:r instanceof Error?r.message:JSON.stringify(r)}var yo="AI_InvalidArgumentError",vo=`vercel.ai.error.${yo}`,Tl=Symbol.for(vo),_o,Pl=class extends U{constructor({message:r,cause:e,argument:t}){super({name:yo,message:r,cause:e}),this[_o]=true,this.argument=t;}static isInstance(r){return U.hasMarker(r,vo)}};_o=Tl;var wo="AI_InvalidPromptError",bo=`vercel.ai.error.${wo}`,Al=Symbol.for(bo),xo,El=class extends U{constructor({prompt:r,message:e,cause:t}){super({name:wo,message:`Invalid prompt: ${e}`,cause:t}),this[xo]=true,this.prompt=r;}static isInstance(r){return U.hasMarker(r,bo)}};xo=Al;var ko="AI_InvalidResponseDataError",Ro=`vercel.ai.error.${ko}`,Sl=Symbol.for(Ro),Co,Il=class extends U{constructor({data:r,message:e=`Invalid response data: ${JSON.stringify(r)}.`}){super({name:ko,message:e}),this[Co]=true,this.data=r;}static isInstance(r){return U.hasMarker(r,Ro)}};Co=Sl;var To="AI_JSONParseError",Po=`vercel.ai.error.${To}`,Ol=Symbol.for(Po),Ao,zl=class extends U{constructor({text:r,cause:e}){super({name:To,message:`JSON parsing failed: Text: ${r}.
29
- Error message: ${Wr(e)}`,cause:e}),this[Ao]=true,this.text=r;}static isInstance(r){return U.hasMarker(r,Po)}};Ao=Ol;var Eo="AI_LoadAPIKeyError",So=`vercel.ai.error.${Eo}`,Ml=Symbol.for(So),Io,jl=class extends U{constructor({message:r}){super({name:Eo,message:r}),this[Io]=true;}static isInstance(r){return U.hasMarker(r,So)}};Io=Ml;var Oo="AI_LoadSettingError",zo=`vercel.ai.error.${Oo}`,Nl=Symbol.for(zo),Mo,Dl=class extends U{constructor({message:r}){super({name:Oo,message:r}),this[Mo]=true;}static isInstance(r){return U.hasMarker(r,zo)}};Mo=Nl;var jo="AI_NoContentGeneratedError",No=`vercel.ai.error.${jo}`,$l=Symbol.for(No),Do,Hl=class extends U{constructor({message:r="No content generated."}={}){super({name:jo,message:r}),this[Do]=true;}static isInstance(r){return U.hasMarker(r,No)}};Do=$l;var $o="AI_NoSuchModelError",Ho=`vercel.ai.error.${$o}`,ql=Symbol.for(Ho),qo,Ll=class extends U{constructor({errorName:r=$o,modelId:e,modelType:t,message:n=`No such ${t}: ${e}`}){super({name:r,message:n}),this[qo]=true,this.modelId=e,this.modelType=t;}static isInstance(r){return U.hasMarker(r,Ho)}};qo=ql;var Lo="AI_TooManyEmbeddingValuesForCallError",Fo=`vercel.ai.error.${Lo}`,Fl=Symbol.for(Fo),Uo,Ul=class extends U{constructor(r){super({name:Lo,message:`Too many values for a single embedding call. The ${r.provider} model "${r.modelId}" can only embed up to ${r.maxEmbeddingsPerCall} values per call, but ${r.values.length} values were provided.`}),this[Uo]=true,this.provider=r.provider,this.modelId=r.modelId,this.maxEmbeddingsPerCall=r.maxEmbeddingsPerCall,this.values=r.values;}static isInstance(r){return U.hasMarker(r,Fo)}};Uo=Fl;var Bo="AI_TypeValidationError",Wo=`vercel.ai.error.${Bo}`,Bl=Symbol.for(Wo),Jo,Wl=class Ur extends U{constructor({value:e,cause:t}){super({name:Bo,message:`Type validation failed: Value: ${JSON.stringify(e)}.
30
- Error message: ${Wr(t)}`,cause:t}),this[Jo]=true,this.value=e;}static isInstance(e){return U.hasMarker(e,Wo)}static wrap({value:e,cause:t}){return Ur.isInstance(t)&&t.value===e?t:new Ur({value:e,cause:t})}};Jo=Bl;var Jl=Wl,Vo="AI_UnsupportedFunctionalityError",Ko=`vercel.ai.error.${Vo}`,Vl=Symbol.for(Ko),Go,Kl=class extends U{constructor({functionality:r,message:e=`'${r}' functionality not supported.`}){super({name:Vo,message:e}),this[Go]=true,this.functionality=r;}static isInstance(r){return U.hasMarker(r,Ko)}};Go=Vl;function vt(r){return r===null||typeof r=="string"||typeof r=="number"||typeof r=="boolean"?true:Array.isArray(r)?r.every(vt):typeof r=="object"?Object.entries(r).every(([e,t])=>typeof e=="string"&&vt(t)):false}function Gl(r){return Array.isArray(r)&&r.every(vt)}function Xl(r){return r!=null&&typeof r=="object"&&Object.entries(r).every(([e,t])=>typeof e=="string"&&vt(t))}});var Qo=$e((Ty,Yo)=>{g();var Yl="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",Ql=(r,e=21)=>(t=e)=>{let n="",o=t|0;for(;o--;)n+=r[Math.random()*r.length|0];return n},Zl=(r=21)=>{let e="",t=r|0;for(;t--;)e+=Yl[Math.random()*64|0];return e};Yo.exports={nanoid:Zl,customAlphabet:Ql};});var ns=$e((Ay,ot)=>{g();var eu=typeof Buffer<"u",Zo=/"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/,es=/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;function ts(r,e,t){t==null&&e!==null&&typeof e=="object"&&(t=e,e=void 0),eu&&Buffer.isBuffer(r)&&(r=r.toString()),r&&r.charCodeAt(0)===65279&&(r=r.slice(1));let n=JSON.parse(r,e);if(n===null||typeof n!="object")return n;let o=t&&t.protoAction||"error",s=t&&t.constructorAction||"error";if(o==="ignore"&&s==="ignore")return n;if(o!=="ignore"&&s!=="ignore"){if(Zo.test(r)===false&&es.test(r)===false)return n}else if(o!=="ignore"&&s==="ignore"){if(Zo.test(r)===false)return n}else if(es.test(r)===false)return n;return rs(n,{protoAction:o,constructorAction:s,safe:t&&t.safe})}function rs(r,{protoAction:e="error",constructorAction:t="error",safe:n}={}){let o=[r];for(;o.length;){let s=o;o=[];for(let i of s){if(e!=="ignore"&&Object.prototype.hasOwnProperty.call(i,"__proto__")){if(n===true)return null;if(e==="error")throw new SyntaxError("Object contains forbidden prototype property");delete i.__proto__;}if(t!=="ignore"&&Object.prototype.hasOwnProperty.call(i,"constructor")&&Object.prototype.hasOwnProperty.call(i.constructor,"prototype")){if(n===true)return null;if(t==="error")throw new SyntaxError("Object contains forbidden prototype property");delete i.constructor;}for(let a in i){let l=i[a];l&&typeof l=="object"&&o.push(l);}}}return r}function Jr(r,e,t){let n=Error.stackTraceLimit;Error.stackTraceLimit=0;try{return ts(r,e,t)}finally{Error.stackTraceLimit=n;}}function tu(r,e){let t=Error.stackTraceLimit;Error.stackTraceLimit=0;try{return ts(r,e,{safe:!0})}catch{return null}finally{Error.stackTraceLimit=t;}}ot.exports=Jr;ot.exports.default=Jr;ot.exports.parse=Jr;ot.exports.safeParse=tu;ot.exports.scan=rs;});var Z=$e((Sy,ms)=>{g();var ru=Object.create,nr=Object.defineProperty,nu=Object.getOwnPropertyDescriptor,ou=Object.getOwnPropertyNames,su=Object.getPrototypeOf,iu=Object.prototype.hasOwnProperty,au=(r,e)=>{for(var t in e)nr(r,t,{get:e[t],enumerable:true});},os=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of ou(e))!iu.call(r,o)&&o!==t&&nr(r,o,{get:()=>e[o],enumerable:!(n=nu(e,o))||n.enumerable});return r},lu=(r,e,t)=>(t=r!=null?ru(su(r)):{},os(!r||!r.__esModule?nr(t,"default",{value:r,enumerable:true}):t,r)),uu=r=>os(nr({},"__esModule",{value:true}),r),ss={};au(ss,{asValidator:()=>ds,combineHeaders:()=>du,convertAsyncIteratorToReadableStream:()=>cu,convertBase64ToUint8Array:()=>$u,convertUint8ArrayToBase64:()=>Hu,createBinaryResponseHandler:()=>Mu,createEventSourceParserStream:()=>is,createEventSourceResponseHandler:()=>Iu,createIdGenerator:()=>as,createJsonErrorResponseHandler:()=>Su,createJsonResponseHandler:()=>zu,createJsonStreamResponseHandler:()=>Ou,createStatusCodeErrorResponseHandler:()=>ju,delay:()=>pu,extractResponseHeaders:()=>Se,generateId:()=>hu,getErrorMessage:()=>yu,getFromApi:()=>_u,isAbortError:()=>Ge,isParsableJson:()=>ku,isValidator:()=>us,loadApiKey:()=>wu,loadOptionalSetting:()=>bu,loadSetting:()=>xu,parseJSON:()=>gs,parseProviderOptions:()=>Cu,postFormDataToApi:()=>Au,postJsonToApi:()=>Pu,postToApi:()=>Xr,removeUndefinedEntries:()=>Kr,resolve:()=>Eu,safeParseJSON:()=>sr,safeValidateTypes:()=>or,validateTypes:()=>ps,validator:()=>ls,validatorSymbol:()=>rr,withoutTrailingSlash:()=>qu,zodValidator:()=>cs});ms.exports=uu(ss);function du(...r){return r.reduce((e,t)=>({...e,...t??{}}),{})}function cu(r){return new ReadableStream({async pull(e){try{let{value:t,done:n}=await r.next();n?e.close():e.enqueue(t);}catch(t){e.error(t);}},cancel(){}})}async function pu(r){return r==null?Promise.resolve():new Promise(e=>setTimeout(e,r))}function is(){let r="",e,t=[],n,o;function s(l,u){if(l===""){i(u);return}if(l.startsWith(":"))return;let d=l.indexOf(":");if(d===-1){a(l,"");return}let c=l.slice(0,d),p=d+1,f=p<l.length&&l[p]===" "?l.slice(p+1):l.slice(p);a(c,f);}function i(l){t.length>0&&(l.enqueue({event:e,data:t.join(`
31
- `),id:n,retry:o}),t=[],e=void 0,o=void 0);}function a(l,u){switch(l){case "event":e=u;break;case "data":t.push(u);break;case "id":n=u;break;case "retry":let d=parseInt(u,10);isNaN(d)||(o=d);break}}return new TransformStream({transform(l,u){let{lines:d,incompleteLine:c}=gu(r,l);r=c;for(let p=0;p<d.length;p++)s(d[p],u);},flush(l){s(r,l),i(l);}})}function gu(r,e){let t=[],n=r;for(let o=0;o<e.length;){let s=e[o++];s===`
32
- `?(t.push(n),n=""):s==="\r"?(t.push(n),n="",e[o]===`
33
- `&&o++):n+=s;}return {lines:t,incompleteLine:n}}function Se(r){let e={};return r.headers.forEach((t,n)=>{e[n]=t;}),e}var mu=W(),fu=Qo(),as=({prefix:r,size:e=16,alphabet:t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",separator:n="-"}={})=>{let o=(0, fu.customAlphabet)(t,e);if(r==null)return o;if(t.includes(n))throw new mu.InvalidArgumentError({argument:"separator",message:`The separator "${n}" must not be part of the alphabet "${t}".`});return s=>`${r}${n}${o(s)}`},hu=as();function yu(r){return r==null?"unknown error":typeof r=="string"?r:r instanceof Error?r.message:JSON.stringify(r)}var _t=W();function Kr(r){return Object.fromEntries(Object.entries(r).filter(([e,t])=>t!=null))}function Ge(r){return r instanceof Error&&(r.name==="AbortError"||r.name==="TimeoutError")}var vu=()=>globalThis.fetch,_u=async({url:r,headers:e={},successfulResponseHandler:t,failedResponseHandler:n,abortSignal:o,fetch:s=vu()})=>{try{let i=await s(r,{method:"GET",headers:Kr(e),signal:o}),a=Se(i);if(!i.ok){let l;try{l=await n({response:i,url:r,requestBodyValues:{}});}catch(u){throw Ge(u)||_t.APICallError.isInstance(u)?u:new _t.APICallError({message:"Failed to process error response",cause:u,statusCode:i.status,url:r,responseHeaders:a,requestBodyValues:{}})}throw l.value}try{return await t({response:i,url:r,requestBodyValues:{}})}catch(l){throw l instanceof Error&&(Ge(l)||_t.APICallError.isInstance(l))?l:new _t.APICallError({message:"Failed to process successful response",cause:l,statusCode:i.status,url:r,responseHeaders:a,requestBodyValues:{}})}}catch(i){if(Ge(i))throw i;if(i instanceof TypeError&&i.message==="fetch failed"){let a=i.cause;if(a!=null)throw new _t.APICallError({message:`Cannot connect to API: ${a.message}`,cause:a,url:r,isRetryable:true,requestBodyValues:{}})}throw i}},er=W();function wu({apiKey:r,environmentVariableName:e,apiKeyParameterName:t="apiKey",description:n}){if(typeof r=="string")return r;if(r!=null)throw new er.LoadAPIKeyError({message:`${n} API key must be a string.`});if(typeof process>"u")throw new er.LoadAPIKeyError({message:`${n} API key is missing. Pass it using the '${t}' parameter. Environment variables is not supported in this environment.`});if(r=process.env[e],r==null)throw new er.LoadAPIKeyError({message:`${n} API key is missing. Pass it using the '${t}' parameter or the ${e} environment variable.`});if(typeof r!="string")throw new er.LoadAPIKeyError({message:`${n} API key must be a string. The value of the ${e} environment variable is not a string.`});return r}function bu({settingValue:r,environmentVariableName:e}){if(typeof r=="string")return r;if(!(r!=null||typeof process>"u")&&(r=process.env[e],!(r==null||typeof r!="string")))return r}var tr=W();function xu({settingValue:r,environmentVariableName:e,settingName:t,description:n}){if(typeof r=="string")return r;if(r!=null)throw new tr.LoadSettingError({message:`${n} setting must be a string.`});if(typeof process>"u")throw new tr.LoadSettingError({message:`${n} setting is missing. Pass it using the '${t}' parameter. Environment variables is not supported in this environment.`});if(r=process.env[e],r==null)throw new tr.LoadSettingError({message:`${n} setting is missing. Pass it using the '${t}' parameter or the ${e} environment variable.`});if(typeof r!="string")throw new tr.LoadSettingError({message:`${n} setting must be a string. The value of the ${e} environment variable is not a string.`});return r}var bt=W(),Gr=lu(ns()),Vr=W(),rr=Symbol.for("vercel.ai.validator");function ls(r){return {[rr]:true,validate:r}}function us(r){return typeof r=="object"&&r!==null&&rr in r&&r[rr]===true&&"validate"in r}function ds(r){return us(r)?r:cs(r)}function cs(r){return ls(e=>{let t=r.safeParse(e);return t.success?{success:true,value:t.data}:{success:false,error:t.error}})}function ps({value:r,schema:e}){let t=or({value:r,schema:e});if(!t.success)throw Vr.TypeValidationError.wrap({value:r,cause:t.error});return t.value}function or({value:r,schema:e}){let t=ds(e);try{if(t.validate==null)return {success:!0,value:r};let n=t.validate(r);return n.success?n:{success:!1,error:Vr.TypeValidationError.wrap({value:r,cause:n.error})}}catch(n){return {success:false,error:Vr.TypeValidationError.wrap({value:r,cause:n})}}}function gs({text:r,schema:e}){try{let t=Gr.default.parse(r);return e==null?t:ps({value:t,schema:e})}catch(t){throw bt.JSONParseError.isInstance(t)||bt.TypeValidationError.isInstance(t)?t:new bt.JSONParseError({text:r,cause:t})}}function sr({text:r,schema:e}){try{let t=Gr.default.parse(r);if(e==null)return {success:!0,value:t,rawValue:t};let n=or({value:t,schema:e});return n.success?{...n,rawValue:t}:n}catch(t){return {success:false,error:bt.JSONParseError.isInstance(t)?t:new bt.JSONParseError({text:r,cause:t})}}}function ku(r){try{return Gr.default.parse(r),!0}catch{return false}}var Ru=W();function Cu({provider:r,providerOptions:e,schema:t}){if(e?.[r]==null)return;let n=or({value:e[r],schema:t});if(!n.success)throw new Ru.InvalidArgumentError({argument:"providerOptions",message:`invalid ${r} provider options`,cause:n.error});return n.value}var wt=W(),Tu=()=>globalThis.fetch,Pu=async({url:r,headers:e,body:t,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>Xr({url:r,headers:{"Content-Type":"application/json",...e},body:{content:JSON.stringify(t),values:t},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),Au=async({url:r,headers:e,formData:t,failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i})=>Xr({url:r,headers:e,body:{content:t,values:Object.fromEntries(t.entries())},failedResponseHandler:n,successfulResponseHandler:o,abortSignal:s,fetch:i}),Xr=async({url:r,headers:e={},body:t,successfulResponseHandler:n,failedResponseHandler:o,abortSignal:s,fetch:i=Tu()})=>{try{let a=await i(r,{method:"POST",headers:Kr(e),body:t.content,signal:s}),l=Se(a);if(!a.ok){let u;try{u=await o({response:a,url:r,requestBodyValues:t.values});}catch(d){throw Ge(d)||wt.APICallError.isInstance(d)?d:new wt.APICallError({message:"Failed to process error response",cause:d,statusCode:a.status,url:r,responseHeaders:l,requestBodyValues:t.values})}throw u.value}try{return await n({response:a,url:r,requestBodyValues:t.values})}catch(u){throw u instanceof Error&&(Ge(u)||wt.APICallError.isInstance(u))?u:new wt.APICallError({message:"Failed to process successful response",cause:u,statusCode:a.status,url:r,responseHeaders:l,requestBodyValues:t.values})}}catch(a){if(Ge(a))throw a;if(a instanceof TypeError&&a.message==="fetch failed"){let l=a.cause;if(l!=null)throw new wt.APICallError({message:`Cannot connect to API: ${l.message}`,cause:l,url:r,requestBodyValues:t.values,isRetryable:true})}throw a}};async function Eu(r){return typeof r=="function"&&(r=r()),Promise.resolve(r)}var Ee=W(),Su=({errorSchema:r,errorToMessage:e,isRetryable:t})=>async({response:n,url:o,requestBodyValues:s})=>{let i=await n.text(),a=Se(n);if(i.trim()==="")return {responseHeaders:a,value:new Ee.APICallError({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:t?.(n)})};try{let l=gs({text:i,schema:r});return {responseHeaders:a,value:new Ee.APICallError({message:e(l),url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,data:l,isRetryable:t?.(n,l)})}}catch{return {responseHeaders:a,value:new Ee.APICallError({message:n.statusText,url:o,requestBodyValues:s,statusCode:n.status,responseHeaders:a,responseBody:i,isRetryable:t?.(n)})}}},Iu=r=>async({response:e})=>{let t=Se(e);if(e.body==null)throw new Ee.EmptyResponseBodyError({});return {responseHeaders:t,value:e.body.pipeThrough(new TextDecoderStream).pipeThrough(is()).pipeThrough(new TransformStream({transform({data:n},o){n!=="[DONE]"&&o.enqueue(sr({text:n,schema:r}));}}))}},Ou=r=>async({response:e})=>{let t=Se(e);if(e.body==null)throw new Ee.EmptyResponseBodyError({});let n="";return {responseHeaders:t,value:e.body.pipeThrough(new TextDecoderStream).pipeThrough(new TransformStream({transform(o,s){o.endsWith(`
34
- `)?(s.enqueue(sr({text:n+o,schema:r})),n=""):n+=o;}}))}},zu=r=>async({response:e,url:t,requestBodyValues:n})=>{let o=await e.text(),s=sr({text:o,schema:r}),i=Se(e);if(!s.success)throw new Ee.APICallError({message:"Invalid JSON response",cause:s.error,statusCode:e.status,responseHeaders:i,responseBody:o,url:t,requestBodyValues:n});return {responseHeaders:i,value:s.value,rawValue:s.rawValue}},Mu=()=>async({response:r,url:e,requestBodyValues:t})=>{let n=Se(r);if(!r.body)throw new Ee.APICallError({message:"Response body is empty",url:e,requestBodyValues:t,statusCode:r.status,responseHeaders:n,responseBody:void 0});try{let o=await r.arrayBuffer();return {responseHeaders:n,value:new Uint8Array(o)}}catch(o){throw new Ee.APICallError({message:"Failed to read response as array buffer",url:e,requestBodyValues:t,statusCode:r.status,responseHeaders:n,responseBody:void 0,cause:o})}},ju=()=>async({response:r,url:e,requestBodyValues:t})=>{let n=Se(r),o=await r.text();return {responseHeaders:n,value:new Ee.APICallError({message:r.statusText,url:e,requestBodyValues:t,statusCode:r.status,responseHeaders:n,responseBody:o})}},{btoa:Nu,atob:Du}=globalThis;function $u(r){let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=Du(e);return Uint8Array.from(t,n=>n.codePointAt(0))}function Hu(r){let e="";for(let t=0;t<r.length;t++)e+=String.fromCodePoint(r[t]);return Nu(e)}function qu(r){return r?.replace(/\/$/,"")}});var on=$e((Oy,Ts)=>{g();var rn=Object.defineProperty,Lu=Object.getOwnPropertyDescriptor,Fu=Object.getOwnPropertyNames,Uu=Object.prototype.hasOwnProperty,Bu=(r,e)=>{for(var t in e)rn(r,t,{get:e[t],enumerable:true});},Wu=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Fu(e))!Uu.call(r,o)&&o!==t&&rn(r,o,{get:()=>e[o],enumerable:!(n=Lu(e,o))||n.enumerable});return r},Ju=r=>Wu(rn({},"__esModule",{value:true}),r),xs={};Bu(xs,{createOpenAI:()=>Cs,openai:()=>Xd});Ts.exports=Ju(xs);var fs=Z(),xt=W(),ae=Z(),I=J("zod"),Yr=W(),Vu=Z();function Ku({prompt:r,useLegacyFunctionCalling:e=false,systemMessageMode:t="system"}){let n=[],o=[];for(let{role:s,content:i}of r)switch(s){case "system":{switch(t){case "system":{n.push({role:"system",content:i});break}case "developer":{n.push({role:"developer",content:i});break}case "remove":{o.push({type:"other",message:"system messages are removed for this model"});break}default:{let a=t;throw new Error(`Unsupported system message mode: ${a}`)}}break}case "user":{if(i.length===1&&i[0].type==="text"){n.push({role:"user",content:i[0].text});break}n.push({role:"user",content:i.map((a,l)=>{var u,d,c,p;switch(a.type){case "text":return {type:"text",text:a.text};case "image":return {type:"image_url",image_url:{url:a.image instanceof URL?a.image.toString():`data:${(u=a.mimeType)!=null?u:"image/jpeg"};base64,${(0, Vu.convertUint8ArrayToBase64)(a.image)}`,detail:(c=(d=a.providerMetadata)==null?void 0:d.openai)==null?void 0:c.imageDetail}};case "file":{if(a.data instanceof URL)throw new Yr.UnsupportedFunctionalityError({functionality:"'File content parts with URL data' functionality not supported."});switch(a.mimeType){case "audio/wav":return {type:"input_audio",input_audio:{data:a.data,format:"wav"}};case "audio/mp3":case "audio/mpeg":return {type:"input_audio",input_audio:{data:a.data,format:"mp3"}};case "application/pdf":return {type:"file",file:{filename:(p=a.filename)!=null?p:`part-${l}.pdf`,file_data:`data:application/pdf;base64,${a.data}`}};default:throw new Yr.UnsupportedFunctionalityError({functionality:`File content part type ${a.mimeType} in user messages`})}}}})});break}case "assistant":{let a="",l=[];for(let u of i)switch(u.type){case "text":{a+=u.text;break}case "tool-call":{l.push({id:u.toolCallId,type:"function",function:{name:u.toolName,arguments:JSON.stringify(u.args)}});break}}if(e){if(l.length>1)throw new Yr.UnsupportedFunctionalityError({functionality:"useLegacyFunctionCalling with multiple tool calls in one message"});n.push({role:"assistant",content:a,function_call:l.length>0?l[0].function:void 0});}else n.push({role:"assistant",content:a,tool_calls:l.length>0?l:void 0});break}case "tool":{for(let a of i)e?n.push({role:"function",name:a.toolName,content:JSON.stringify(a.result)}):n.push({role:"tool",tool_call_id:a.toolCallId,content:JSON.stringify(a.result)});break}default:{let a=s;throw new Error(`Unsupported role: ${a}`)}}return {messages:n,warnings:o}}function hs(r){var e,t;return (t=(e=r?.content)==null?void 0:e.map(({token:n,logprob:o,top_logprobs:s})=>({token:n,logprob:o,topLogprobs:s?s.map(({token:i,logprob:a})=>({token:i,logprob:a})):[]})))!=null?t:void 0}function dr(r){switch(r){case "stop":return "stop";case "length":return "length";case "content_filter":return "content-filter";case "function_call":case "tool_calls":return "tool-calls";default:return "unknown"}}var Ne=J("zod"),Gu=Z(),nn=Ne.z.object({error:Ne.z.object({message:Ne.z.string(),type:Ne.z.string().nullish(),param:Ne.z.any().nullish(),code:Ne.z.union([Ne.z.string(),Ne.z.number()]).nullish()})}),xe=(0, Gu.createJsonErrorResponseHandler)({errorSchema:nn,errorToMessage:r=>r.error.message});function cr({id:r,model:e,created:t}){return {id:r??void 0,modelId:e??void 0,timestamp:t!=null?new Date(t*1e3):void 0}}var ys=W();function Xu({mode:r,useLegacyFunctionCalling:e=false,structuredOutputs:t}){var n;let o=(n=r.tools)!=null&&n.length?r.tools:void 0,s=[];if(o==null)return {tools:void 0,tool_choice:void 0,toolWarnings:s};let i=r.toolChoice;if(e){let u=[];for(let c of o)c.type==="provider-defined"?s.push({type:"unsupported-tool",tool:c}):u.push({name:c.name,description:c.description,parameters:c.parameters});if(i==null)return {functions:u,function_call:void 0,toolWarnings:s};switch(i.type){case "auto":case "none":case void 0:return {functions:u,function_call:void 0,toolWarnings:s};case "required":throw new ys.UnsupportedFunctionalityError({functionality:"useLegacyFunctionCalling and toolChoice: required"});default:return {functions:u,function_call:{name:i.toolName},toolWarnings:s}}}let a=[];for(let u of o)u.type==="provider-defined"?s.push({type:"unsupported-tool",tool:u}):a.push({type:"function",function:{name:u.name,description:u.description,parameters:u.parameters,strict:t?true:void 0}});if(i==null)return {tools:a,tool_choice:void 0,toolWarnings:s};let l=i.type;switch(l){case "auto":case "none":case "required":return {tools:a,tool_choice:l,toolWarnings:s};case "tool":return {tools:a,tool_choice:{type:"function",function:{name:i.toolName}},toolWarnings:s};default:{let u=l;throw new ys.UnsupportedFunctionalityError({functionality:`Unsupported tool choice type: ${u}`})}}}var Yu=class{constructor(r,e,t){this.specificationVersion="v1",this.modelId=r,this.settings=e,this.config=t;}get supportsStructuredOutputs(){var r;return (r=this.settings.structuredOutputs)!=null?r:tn(this.modelId)}get defaultObjectGenerationMode(){return ed(this.modelId)?"tool":this.supportsStructuredOutputs?"json":"tool"}get provider(){return this.config.provider}get supportsImageUrls(){return !this.settings.downloadImages}getArgs({mode:r,prompt:e,maxTokens:t,temperature:n,topP:o,topK:s,frequencyPenalty:i,presencePenalty:a,stopSequences:l,responseFormat:u,seed:d,providerMetadata:c}){var p,f,v,h,m,y,w,C;let _=r.type,k=[];s!=null&&k.push({type:"unsupported-setting",setting:"topK"}),u?.type==="json"&&u.schema!=null&&!this.supportsStructuredOutputs&&k.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format schema is only supported with structuredOutputs"});let S=this.settings.useLegacyFunctionCalling;if(S&&this.settings.parallelToolCalls===true)throw new xt.UnsupportedFunctionalityError({functionality:"useLegacyFunctionCalling with parallelToolCalls"});if(S&&this.supportsStructuredOutputs)throw new xt.UnsupportedFunctionalityError({functionality:"structuredOutputs with useLegacyFunctionCalling"});let{messages:z,warnings:R}=Ku({prompt:e,useLegacyFunctionCalling:S,systemMessageMode:td(this.modelId)});k.push(...R);let x={model:this.modelId,logit_bias:this.settings.logitBias,logprobs:this.settings.logprobs===true||typeof this.settings.logprobs=="number"?true:void 0,top_logprobs:typeof this.settings.logprobs=="number"?this.settings.logprobs:typeof this.settings.logprobs=="boolean"&&this.settings.logprobs?0:void 0,user:this.settings.user,parallel_tool_calls:this.settings.parallelToolCalls,max_tokens:t,temperature:n,top_p:o,frequency_penalty:i,presence_penalty:a,response_format:u?.type==="json"?this.supportsStructuredOutputs&&u.schema!=null?{type:"json_schema",json_schema:{schema:u.schema,strict:true,name:(p=u.name)!=null?p:"response",description:u.description}}:{type:"json_object"}:void 0,stop:l,seed:d,max_completion_tokens:(f=c?.openai)==null?void 0:f.maxCompletionTokens,store:(v=c?.openai)==null?void 0:v.store,metadata:(h=c?.openai)==null?void 0:h.metadata,prediction:(m=c?.openai)==null?void 0:m.prediction,reasoning_effort:(w=(y=c?.openai)==null?void 0:y.reasoningEffort)!=null?w:this.settings.reasoningEffort,messages:z};switch(tn(this.modelId)?(x.temperature!=null&&(x.temperature=void 0,k.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),x.top_p!=null&&(x.top_p=void 0,k.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"})),x.frequency_penalty!=null&&(x.frequency_penalty=void 0,k.push({type:"unsupported-setting",setting:"frequencyPenalty",details:"frequencyPenalty is not supported for reasoning models"})),x.presence_penalty!=null&&(x.presence_penalty=void 0,k.push({type:"unsupported-setting",setting:"presencePenalty",details:"presencePenalty is not supported for reasoning models"})),x.logit_bias!=null&&(x.logit_bias=void 0,k.push({type:"other",message:"logitBias is not supported for reasoning models"})),x.logprobs!=null&&(x.logprobs=void 0,k.push({type:"other",message:"logprobs is not supported for reasoning models"})),x.top_logprobs!=null&&(x.top_logprobs=void 0,k.push({type:"other",message:"topLogprobs is not supported for reasoning models"})),x.max_tokens!=null&&(x.max_completion_tokens==null&&(x.max_completion_tokens=x.max_tokens),x.max_tokens=void 0)):(this.modelId.startsWith("gpt-4o-search-preview")||this.modelId.startsWith("gpt-4o-mini-search-preview"))&&x.temperature!=null&&(x.temperature=void 0,k.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for the search preview models and has been removed."})),_){case "regular":{let{tools:M,tool_choice:O,functions:Y,function_call:re,toolWarnings:B}=Xu({mode:r,useLegacyFunctionCalling:S,structuredOutputs:this.supportsStructuredOutputs});return {args:{...x,tools:M,tool_choice:O,functions:Y,function_call:re},warnings:[...k,...B]}}case "object-json":return {args:{...x,response_format:this.supportsStructuredOutputs&&r.schema!=null?{type:"json_schema",json_schema:{schema:r.schema,strict:true,name:(C=r.name)!=null?C:"response",description:r.description}}:{type:"json_object"}},warnings:k};case "object-tool":return {args:S?{...x,function_call:{name:r.tool.name},functions:[{name:r.tool.name,description:r.tool.description,parameters:r.tool.parameters}]}:{...x,tool_choice:{type:"function",function:{name:r.tool.name}},tools:[{type:"function",function:{name:r.tool.name,description:r.tool.description,parameters:r.tool.parameters,strict:this.supportsStructuredOutputs?true:void 0}}]},warnings:k};default:{let M=_;throw new Error(`Unsupported type: ${M}`)}}}async doGenerate(r){var e,t,n,o,s,i,a,l;let{args:u,warnings:d}=this.getArgs(r),{responseHeaders:c,value:p,rawValue:f}=await(0, ae.postJsonToApi)({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:(0, ae.combineHeaders)(this.config.headers(),r.headers),body:u,failedResponseHandler:xe,successfulResponseHandler:(0, ae.createJsonResponseHandler)(Qu),abortSignal:r.abortSignal,fetch:this.config.fetch}),{messages:v,...h}=u,m=p.choices[0],y=(e=p.usage)==null?void 0:e.completion_tokens_details,w=(t=p.usage)==null?void 0:t.prompt_tokens_details,C={openai:{}};return y?.reasoning_tokens!=null&&(C.openai.reasoningTokens=y?.reasoning_tokens),y?.accepted_prediction_tokens!=null&&(C.openai.acceptedPredictionTokens=y?.accepted_prediction_tokens),y?.rejected_prediction_tokens!=null&&(C.openai.rejectedPredictionTokens=y?.rejected_prediction_tokens),w?.cached_tokens!=null&&(C.openai.cachedPromptTokens=w?.cached_tokens),{text:(n=m.message.content)!=null?n:void 0,toolCalls:this.settings.useLegacyFunctionCalling&&m.message.function_call?[{toolCallType:"function",toolCallId:(0, ae.generateId)(),toolName:m.message.function_call.name,args:m.message.function_call.arguments}]:(o=m.message.tool_calls)==null?void 0:o.map(_=>{var k;return {toolCallType:"function",toolCallId:(k=_.id)!=null?k:(0, ae.generateId)(),toolName:_.function.name,args:_.function.arguments}}),finishReason:dr(m.finish_reason),usage:{promptTokens:(i=(s=p.usage)==null?void 0:s.prompt_tokens)!=null?i:NaN,completionTokens:(l=(a=p.usage)==null?void 0:a.completion_tokens)!=null?l:NaN},rawCall:{rawPrompt:v,rawSettings:h},rawResponse:{headers:c,body:f},request:{body:JSON.stringify(u)},response:cr(p),warnings:d,logprobs:hs(m.logprobs),providerMetadata:C}}async doStream(r){if(this.settings.simulateStreaming){let h=await this.doGenerate(r);return {stream:new ReadableStream({start(y){if(y.enqueue({type:"response-metadata",...h.response}),h.text&&y.enqueue({type:"text-delta",textDelta:h.text}),h.toolCalls)for(let w of h.toolCalls)y.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:w.toolCallId,toolName:w.toolName,argsTextDelta:w.args}),y.enqueue({type:"tool-call",...w});y.enqueue({type:"finish",finishReason:h.finishReason,usage:h.usage,logprobs:h.logprobs,providerMetadata:h.providerMetadata}),y.close();}}),rawCall:h.rawCall,rawResponse:h.rawResponse,warnings:h.warnings}}let{args:e,warnings:t}=this.getArgs(r),n={...e,stream:true,stream_options:this.config.compatibility==="strict"?{include_usage:true}:void 0},{responseHeaders:o,value:s}=await(0, ae.postJsonToApi)({url:this.config.url({path:"/chat/completions",modelId:this.modelId}),headers:(0, ae.combineHeaders)(this.config.headers(),r.headers),body:n,failedResponseHandler:xe,successfulResponseHandler:(0, ae.createEventSourceResponseHandler)(Zu),abortSignal:r.abortSignal,fetch:this.config.fetch}),{messages:i,...a}=e,l=[],u="unknown",d={promptTokens:void 0,completionTokens:void 0},c,p=true,{useLegacyFunctionCalling:f}=this.settings,v={openai:{}};return {stream:s.pipeThrough(new TransformStream({transform(h,m){var y,w,C,_,k,S,z,R,x,M,O,Y;if(!h.success){u="error",m.enqueue({type:"error",error:h.error});return}let re=h.value;if("error"in re){u="error",m.enqueue({type:"error",error:re.error});return}if(p&&(p=false,m.enqueue({type:"response-metadata",...cr(re)})),re.usage!=null){let{prompt_tokens:V,completion_tokens:oe,prompt_tokens_details:Q,completion_tokens_details:K}=re.usage;d={promptTokens:V??void 0,completionTokens:oe??void 0},K?.reasoning_tokens!=null&&(v.openai.reasoningTokens=K?.reasoning_tokens),K?.accepted_prediction_tokens!=null&&(v.openai.acceptedPredictionTokens=K?.accepted_prediction_tokens),K?.rejected_prediction_tokens!=null&&(v.openai.rejectedPredictionTokens=K?.rejected_prediction_tokens),Q?.cached_tokens!=null&&(v.openai.cachedPromptTokens=Q?.cached_tokens);}let B=re.choices[0];if(B?.finish_reason!=null&&(u=dr(B.finish_reason)),B?.delta==null)return;let De=B.delta;De.content!=null&&m.enqueue({type:"text-delta",textDelta:De.content});let pe=hs(B?.logprobs);pe?.length&&(c===void 0&&(c=[]),c.push(...pe));let ye=f&&De.function_call!=null?[{type:"function",id:(0, ae.generateId)(),function:De.function_call,index:0}]:De.tool_calls;if(ye!=null)for(let V of ye){let oe=V.index;if(l[oe]==null){if(V.type!=="function")throw new xt.InvalidResponseDataError({data:V,message:"Expected 'function' type."});if(V.id==null)throw new xt.InvalidResponseDataError({data:V,message:"Expected 'id' to be a string."});if(((y=V.function)==null?void 0:y.name)==null)throw new xt.InvalidResponseDataError({data:V,message:"Expected 'function.name' to be a string."});l[oe]={id:V.id,type:"function",function:{name:V.function.name,arguments:(w=V.function.arguments)!=null?w:""},hasFinished:false};let K=l[oe];((C=K.function)==null?void 0:C.name)!=null&&((_=K.function)==null?void 0:_.arguments)!=null&&(K.function.arguments.length>0&&m.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:K.id,toolName:K.function.name,argsTextDelta:K.function.arguments}),(0, ae.isParsableJson)(K.function.arguments)&&(m.enqueue({type:"tool-call",toolCallType:"function",toolCallId:(k=K.id)!=null?k:(0, ae.generateId)(),toolName:K.function.name,args:K.function.arguments}),K.hasFinished=true));continue}let Q=l[oe];Q.hasFinished||(((S=V.function)==null?void 0:S.arguments)!=null&&(Q.function.arguments+=(R=(z=V.function)==null?void 0:z.arguments)!=null?R:""),m.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:Q.id,toolName:Q.function.name,argsTextDelta:(x=V.function.arguments)!=null?x:""}),((M=Q.function)==null?void 0:M.name)!=null&&((O=Q.function)==null?void 0:O.arguments)!=null&&(0, ae.isParsableJson)(Q.function.arguments)&&(m.enqueue({type:"tool-call",toolCallType:"function",toolCallId:(Y=Q.id)!=null?Y:(0, ae.generateId)(),toolName:Q.function.name,args:Q.function.arguments}),Q.hasFinished=true));}},flush(h){var m,y;h.enqueue({type:"finish",finishReason:u,logprobs:c,usage:{promptTokens:(m=d.promptTokens)!=null?m:NaN,completionTokens:(y=d.completionTokens)!=null?y:NaN},...v!=null?{providerMetadata:v}:{}});}})),rawCall:{rawPrompt:i,rawSettings:a},rawResponse:{headers:o},request:{body:JSON.stringify(n)},warnings:t}}},ks=I.z.object({prompt_tokens:I.z.number().nullish(),completion_tokens:I.z.number().nullish(),prompt_tokens_details:I.z.object({cached_tokens:I.z.number().nullish()}).nullish(),completion_tokens_details:I.z.object({reasoning_tokens:I.z.number().nullish(),accepted_prediction_tokens:I.z.number().nullish(),rejected_prediction_tokens:I.z.number().nullish()}).nullish()}).nullish(),Qu=I.z.object({id:I.z.string().nullish(),created:I.z.number().nullish(),model:I.z.string().nullish(),choices:I.z.array(I.z.object({message:I.z.object({role:I.z.literal("assistant").nullish(),content:I.z.string().nullish(),function_call:I.z.object({arguments:I.z.string(),name:I.z.string()}).nullish(),tool_calls:I.z.array(I.z.object({id:I.z.string().nullish(),type:I.z.literal("function"),function:I.z.object({name:I.z.string(),arguments:I.z.string()})})).nullish()}),index:I.z.number(),logprobs:I.z.object({content:I.z.array(I.z.object({token:I.z.string(),logprob:I.z.number(),top_logprobs:I.z.array(I.z.object({token:I.z.string(),logprob:I.z.number()}))})).nullable()}).nullish(),finish_reason:I.z.string().nullish()})),usage:ks}),Zu=I.z.union([I.z.object({id:I.z.string().nullish(),created:I.z.number().nullish(),model:I.z.string().nullish(),choices:I.z.array(I.z.object({delta:I.z.object({role:I.z.enum(["assistant"]).nullish(),content:I.z.string().nullish(),function_call:I.z.object({name:I.z.string().optional(),arguments:I.z.string().optional()}).nullish(),tool_calls:I.z.array(I.z.object({index:I.z.number(),id:I.z.string().nullish(),type:I.z.literal("function").nullish(),function:I.z.object({name:I.z.string().nullish(),arguments:I.z.string().nullish()})})).nullish()}).nullish(),logprobs:I.z.object({content:I.z.array(I.z.object({token:I.z.string(),logprob:I.z.number(),top_logprobs:I.z.array(I.z.object({token:I.z.string(),logprob:I.z.number()}))})).nullable()}).nullish(),finish_reason:I.z.string().nullish(),index:I.z.number()})),usage:ks}),nn]);function tn(r){return r.startsWith("o")||r.startsWith("gpt-5")}function ed(r){return r.startsWith("gpt-4o-audio-preview")}function td(r){var e,t;return tn(r)?(t=(e=rd[r])==null?void 0:e.systemMessageMode)!=null?t:"developer":"system"}var rd={"o1-mini":{systemMessageMode:"remove"},"o1-mini-2024-09-12":{systemMessageMode:"remove"},"o1-preview":{systemMessageMode:"remove"},"o1-preview-2024-09-12":{systemMessageMode:"remove"},o3:{systemMessageMode:"developer"},"o3-2025-04-16":{systemMessageMode:"developer"},"o3-mini":{systemMessageMode:"developer"},"o3-mini-2025-01-31":{systemMessageMode:"developer"},"o4-mini":{systemMessageMode:"developer"},"o4-mini-2025-04-16":{systemMessageMode:"developer"}},ir=W(),st=Z(),D=J("zod"),ar=W();function nd({prompt:r,inputFormat:e,user:t="user",assistant:n="assistant"}){if(e==="prompt"&&r.length===1&&r[0].role==="user"&&r[0].content.length===1&&r[0].content[0].type==="text")return {prompt:r[0].content[0].text};let o="";r[0].role==="system"&&(o+=`${r[0].content}
28
+ ${e}`:e}runProcess(e,t,r){return So(this.adapter.command,e,this.providerStr,this.providerId,t,r,this.adapter)}handleResultMeta(e,t){if(!this.adapter.parseResultMeta){let i=Eo(e);i&&t?.onUsage&&t.onUsage(i);return}let{usage:r,model:n}=this.adapter.parseResultMeta(e);r&&t?.onUsage&&t.onUsage(r);let s=n??(this.providerId==="opencode"?t?.model??null:null);s&&t?.onModel&&t.onModel(s);}};});var hn,wn,Ze,ur=N(()=>{l();oe();hn=10,wn=50,Ze=class{config;constructor(e){this.config=e;}async query(e,t){return this._run(e,"query",t)}async execute(e,t){return this._run(e,"execute",t)}async _run(e,t,r){let{generateText:n,tool:s}=await import('ai'),i=this.convertTools(r?.tools??[],s),a=this.createModel(r?.model),d=Math.min(r?.maxSteps??this.config.maxSteps??hn,wn);try{let c=0,u=await n({model:a,system:r?.systemPrompt??void 0,prompt:e,tools:i,maxSteps:d,...this.config.temperature!==void 0&&{temperature:this.config.temperature},...this.config.maxTokens!==void 0&&{maxTokens:this.config.maxTokens},onStepFinish:f=>{if(c++,!!r?.onOutput){if(f.toolCalls&&f.toolCalls.length>0)for(let y of f.toolCalls)r.onOutput(JSON.stringify({type:"assistant",message:{content:[{type:"tool_use",id:y.toolCallId,name:y.toolName,input:y.args}]}}),"stdout");if(f.toolResults&&f.toolResults.length>0)for(let y of f.toolResults){let h=typeof y.result=="string"?y.result:JSON.stringify(y.result);r.onOutput(JSON.stringify({type:"user",message:{content:[{type:"tool_result",tool_use_id:y.toolCallId,output:h,is_error:!1}]}}),"stdout");}}}}),p=new Set((r?.tools??[]).filter(f=>!f.execute).map(f=>f.name));if(u.finishReason==="tool-calls"&&Array.isArray(u.toolCalls)&&u.toolCalls.length>0){let f=u.toolCalls.filter(y=>p.has(y.toolName));if(f.length>0){let y=f[0];throw new te({toolCallId:y.toolCallId,toolName:y.toolName,args:y.args},{userMessage:e,responseMessages:u.response?.messages??[],toolDefinitions:r?.tools??[],maxSteps:d,systemPrompt:r?.systemPrompt,modelOverride:r?.model})}}if(r?.onUsage&&u.usage){let f={inputTokens:u.usage.promptTokens??0,outputTokens:u.usage.completionTokens??0,cachedInputTokens:0,costUsd:0};r.onUsage(f);}return r?.onModel&&r.onModel(r.model??this.config.model),u.text??""}catch(c){throw c instanceof te?c:c.status===401?new b(`Authentication failed for ${this.config.provider}. Check your API key.`,this.config.provider):c.status===429?new b(`Rate limit exceeded for ${this.config.provider}.`,this.config.provider):new b(`Provider error: ${c.message}`,this.config.provider)}}async continueWithToolResults(e,t,r){let{generateText:n,tool:s}=await import('ai'),i=this.convertTools(e.toolDefinitions,s),a=this.createModel(e.modelOverride),d=Math.min(e.maxSteps??this.config.maxSteps??hn,wn),c=[{role:"user",content:e.userMessage},...e.responseMessages,{role:"tool",content:t.map(u=>({type:"tool-result",toolCallId:u.toolCallId,toolName:u.toolName,result:typeof u.result=="string"?u.result:JSON.stringify(u.result)}))}];try{let u=await n({model:a,system:e.systemPrompt??void 0,messages:c,tools:i,maxSteps:d,...this.config.temperature!==void 0&&{temperature:this.config.temperature},...this.config.maxTokens!==void 0&&{maxTokens:this.config.maxTokens}}),p=new Set(e.toolDefinitions.filter(f=>!f.execute).map(f=>f.name));if(u.finishReason==="tool-calls"&&Array.isArray(u.toolCalls)&&u.toolCalls.length>0){let f=u.toolCalls.filter(y=>p.has(y.toolName));if(f.length>0){let y=f[0];throw new te({toolCallId:y.toolCallId,toolName:y.toolName,args:y.args},{userMessage:e.userMessage,responseMessages:[...e.responseMessages,{role:"tool",content:t.map(h=>({type:"tool-result",toolCallId:h.toolCallId,toolName:h.toolName,result:typeof h.result=="string"?h.result:JSON.stringify(h.result)}))},...u.response?.messages??[]],toolDefinitions:e.toolDefinitions,maxSteps:e.maxSteps,systemPrompt:e.systemPrompt,modelOverride:e.modelOverride})}}return r?.onUsage&&u.usage&&r.onUsage({inputTokens:u.usage.promptTokens??0,outputTokens:u.usage.completionTokens??0,cachedInputTokens:0,costUsd:0}),r?.onModel&&r.onModel(e.modelOverride??this.config.model),u.text??""}catch(u){throw u instanceof te?u:new b(`Provider error: ${u.message}`,this.config.provider)}}convertTools(e,t){let{z:r}=B("zod"),n={};for(let s of e){let i=this.jsonSchemaToZod(s.parameters??{},r);s.execute?n[s.name]=t({description:s.description,parameters:i,execute:async a=>s.execute(a)}):n[s.name]=t({description:s.description,parameters:i});}return n}jsonSchemaToZod(e,t){if(!e||!e.properties)return t.object({});let r={},n=e.properties,s=e.required??[];for(let[i,a]of Object.entries(n)){let d;switch(a.type){case "string":d=t.string();break;case "number":d=t.number();break;case "integer":d=t.number().int();break;case "boolean":d=t.boolean();break;case "array":d=t.array(t.any());break;default:d=t.any();}a.description&&(d=d.describe(a.description)),s.includes(i)||(d=d.optional()),r[i]=d;}return t.object(r)}createModel(e){let{provider:t,apiKey:r,baseURL:n}=this.config,s=e||this.config.model;switch(t){case "api/openrouter":{let{createOpenAI:i}=B("@ai-sdk/openai");return i({apiKey:r||process.env.OPENROUTER_API_KEY,baseURL:n||"https://openrouter.ai/api/v1"})(s)}case "api/openai":{let{createOpenAI:i}=B("@ai-sdk/openai");return i({apiKey:r||process.env.OPENAI_API_KEY,...n&&{baseURL:n}})(s)}case "api/anthropic":{let{createAnthropic:i}=B("@ai-sdk/anthropic");return i({apiKey:r||process.env.ANTHROPIC_API_KEY,...n&&{baseURL:n}})(s)}case "api/google":{let{createGoogleGenerativeAI:i}=B("@ai-sdk/google");return i({apiKey:r||process.env.GOOGLE_API_KEY})(s)}default:throw new b(`Unsupported API provider: ${t}`,t)}}};});var vn={};ct(vn,{registerApiProviders:()=>xn});function xn(o){ce("api",(e,t)=>{let r=o?.apiKeys?.[e];return new Ze({provider:t,model:"",apiKey:r,maxSteps:o?.defaults?.maxSteps,temperature:o?.defaults?.temperature})});}var pr=N(()=>{l();oe();ur();});function gr(o){let e=o.update;if(e.sessionUpdate==="agent_message_chunk"){let t=e.content;if(t.type==="text"&&typeof t.text=="string")return t.text}return null}function re(o,e){try{let t=JSON.parse(o);if(t!=null&&typeof t=="object"&&typeof t.type=="string"&&Us.has(t.type)){let r=e??new Date().toISOString();return [{...t,timestamp:t.timestamp||r}]}}catch{}return []}var Us,xe=N(()=>{l();Us=new Set(["text","tool_use","tool_result","error","agent_call"]);});var fe,mr=N(()=>{l();fe=class extends Error{constructor(t,r,n){super(t);this.code=r;this.data=n;}code;data;name="AcpProtocolError"};});var Bs,zs,kn,_n,et,fr=N(()=>{l();mr();oe();Bs=-32e3,zs=2e3,kn=3e4,_n=1e4,et=class{constructor(e){this.options=e;}options;proc=null;sdkConnection=null;disposed=false;stderrBuffer="";collectedStderr="";pendingUpdateCallback=null;authMethods=[];async connect(e){if(this.disposed)throw new b("AcpConnection has been disposed","acp");let t=this.options.spawn,r=process.platform==="win32"&&(t.shellOnWindows??true),n=spawn(t.command,t.args,{stdio:["pipe","pipe","pipe"],env:{...process.env,...this.options.env??{}},cwd:this.options.cwd,shell:r,windowsHide:true});n.pid!==void 0&&this.options.onPid?.(n.pid),n.stderr.on("data",y=>{let h=y.toString();this.collectedStderr+=h,this.stderrBuffer+=h;let x=this.stderrBuffer.split(`
29
+ `);this.stderrBuffer=x.pop()??"";for(let w of x)w.trim()&&this.options.onStderr?.(w);}),this.proc=n;let s=new WritableStream({write:y=>new Promise((h,x)=>{n.stdin.write(y,w=>{w?x(w):h();});}),close:()=>{n.stdin.end();}}),i=new ReadableStream({start:y=>{n.stdout.on("data",h=>{y.enqueue(new Uint8Array(h));}),n.stdout.on("end",()=>{y.close();}),n.stdout.on("error",h=>{y.error(h);});}}),a=ndJsonStream(s,i),d=this,c=new ClientSideConnection(y=>({requestPermission:async h=>{if(d.options.configOptions?.allow_all!==void 0){let x=h.options;if(Array.isArray(x)&&x.length>0)return {outcome:{outcome:"selected",optionId:(x.find(R=>R.kind==="allow_once")??x.find(R=>R.kind?.startsWith("allow_"))??x[0]).optionId}}}return {outcome:{outcome:"cancelled"}}},sessionUpdate:async h=>{d.pendingUpdateCallback?.(h);}}),a);this.sdkConnection=c;let u=new Promise((y,h)=>{n.on("error",x=>{if(x.code==="ENOENT"){let R=t.command==="npx"&&t.args.length>0?`@agentclientprotocol/${t.args[0]}`:t.command;h(new b(`ACP command "${t.command}" not found. Is the ACP adapter installed? Try: npm install -g ${R}`,"acp"));}else h(new b(`ACP spawn error: ${x.message}`,"acp"));});}),p=this.doInitialize(c,e),f=new Promise((y,h)=>{setTimeout(()=>{h(new fe(`ACP connect timeout after ${kn}ms. The ACP adapter may not be installed or may require interactive setup.`));},kn).unref();});await Promise.race([p,f,u]);}async doInitialize(e,t){let r=await e.initialize({protocolVersion:1,clientCapabilities:{auth:{}},clientInfo:{name:t?.name??"crewx-sdk",version:t?.version??"0.8.4"}});this.authMethods=r.authMethods??[];}async newSession(e){if(!this.sdkConnection)throw new b("AcpConnection not connected. Call connect() first.","acp");try{return await this.newSessionWithTimeout(e)}catch(t){if(!this.isAuthError(t))throw t;return await this.tryAuthenticate(),this.newSessionWithTimeout(e)}}async newSessionWithTimeout(e){let t=this.sdkConnection.newSession(e),r=new Promise((s,i)=>{setTimeout(()=>{i(new fe(`ACP session/new timeout after ${_n}ms`));},_n).unref();});return (await Promise.race([t,r])).sessionId}isAuthError(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code===Bs}async tryAuthenticate(){if(!this.sdkConnection)throw new b("AcpConnection not connected.","acp");let e=this.authMethods.find(r=>r.type==="env_var"&&this.hasEnvVarsFor(r));if(e){await this.sdkConnection.authenticate({methodId:e.id});return}let t=this.authMethods.map(r=>`${r.id} (${r.type??"agent"})`).join(", ");if(this.authMethods.length>0){let r=this.authMethods.filter(n=>n.type==="env_var");if(r.length>0){let n=r.flatMap(s=>(s.vars??[]).filter(i=>!i.optional&&!process.env[i.name]).map(i=>i.name));throw new fe(`ACP authentication required. Missing environment variables: ${n.join(", ")}. Set them in your shell or crewx.yaml env block.`)}throw new fe(`ACP authentication required but no supported method found. Available methods: ${t}. CrewX currently supports env_var authentication only.`)}throw new fe("ACP agent requires authentication but advertised no auth methods.")}hasEnvVarsFor(e){return !e.vars||e.vars.length===0?true:e.vars.filter(t=>!t.optional).every(t=>!!process.env[t.name])}async setModel(e,t){if(!this.sdkConnection)throw new b("AcpConnection not connected. Call connect() first.","acp");await this.sdkConnection.unstable_setSessionModel({sessionId:e,modelId:t});}async setMode(e,t){if(!this.sdkConnection)throw new b("AcpConnection not connected. Call connect() first.","acp");await this.sdkConnection.setSessionMode({sessionId:e,modeId:t});}async setConfigOption(e,t,r){if(!this.sdkConnection)throw new b("AcpConnection not connected. Call connect() first.","acp");await this.sdkConnection.setSessionConfigOption({sessionId:e,configId:t,value:r});}async prompt(e,t,r,n){if(!this.sdkConnection||!this.proc)throw new b("AcpConnection not connected. Call connect() first.","acp");this.pendingUpdateCallback=r??null;let s=this.sdkConnection,i=this.proc,a=n??36e5,d=s.prompt({sessionId:e,prompt:t}),c=new Promise((p,f)=>{setTimeout(()=>{s.cancel({sessionId:e}).catch(()=>{}),f(new Be(`ACP prompt timeout after ${a}ms`,"acp"));},a).unref();}),u=new Promise((p,f)=>{let y=h=>{h!==0&&f(new b(`ACP process exited unexpectedly (code=${String(h)}): ${this.collectedStderr.slice(0,500)}`,"acp"));};i.once("close",y),d.then(()=>i.off("close",y)).catch(()=>i.off("close",y));});try{return await Promise.race([d,c,u])}finally{this.pendingUpdateCallback=null;}}async dispose(){if(this.disposed)return;this.disposed=true,this.pendingUpdateCallback=null,this.sdkConnection=null;let e=this.proc;e&&(this.proc=null,this.stderrBuffer.trim()&&(this.options.onStderr?.(this.stderrBuffer),this.stderrBuffer=""),await new Promise(t=>{let r=()=>{clearTimeout(n),t();};e.once("close",r),e.once("error",r);try{e.kill("SIGTERM");}catch{r();return}let n=setTimeout(()=>{try{e.kill("SIGKILL");}catch{}},zs);}));}get isConnected(){return !this.disposed&&this.sdkConnection!==null&&this.proc!==null}};});function Rn(o,e){if(o!=null&&typeof o=="object"){let t=o;if(typeof t.command=="string")return t.command;if(typeof t.file_path=="string")return t.file_path;if(typeof t.filePath=="string")return t.filePath;if(typeof t.path=="string")return t.path;if(typeof t.query=="string")return t.query;if(typeof t.pattern=="string")return t.pattern;if(typeof t.url=="string")return t.url;if(Object.keys(t).length>0)return JSON.stringify(t)}if(e&&e.length>0)return e.map(t=>t.path).join(", ")}var Vs,tt,yr=N(()=>{l();xe();fr();Vs={read:"Read",edit:"Edit",delete:"Delete",move:"Move",search:"Search",execute:"Bash",think:"Think",fetch:"WebFetch",switch_mode:"SwitchMode"};tt=class{constructor(e,t,r){this.adapter=t;}adapter;async query(e,t){return this.runPrompt(e,t)}async execute(e,t){return this.runPrompt(e,t)}async dispose(){}async runPrompt(e,t){let{command:r,args:n}=this.adapter.spawn;t?.onCommand?.(`${r} ${n.join(" ")}`);let s=new et({spawn:this.adapter.spawn,env:t?.env,cwd:t?.cwd,timeoutMs:t?.timeoutMs,onPid:t?.onPid,onStderr:i=>t?.onOutput?.(i,"stderr"),configOptions:t?.configOptions});try{await s.connect(this.adapter.clientInfo);let i=this.adapter.buildSessionParams({cwd:t?.cwd,env:t?.env,model:t?.model,systemPrompt:t?.systemPrompt}),a=await s.newSession(i);await this.applySessionOptions(s,a,t);let d=this.composePrompt(e,t),c=[],u=await s.prompt(a,d,p=>this.handleUpdate(p,t,c),t?.timeoutMs);return this.handleUsage(u,t),c.join("")}finally{await s.dispose().catch(()=>{});}}async applySessionOptions(e,t,r){if(r?.model){let n=this.adapter.buildEffortAction?.(r.effort??"",r.model);n?.type==="set_model"?await e.setModel(t,n.modelId):await e.setModel(t,r.model);}if(r?.mode){let n=this.adapter.resolveMode?.(r.mode)??r.mode;if(n)try{await e.setMode(t,n);}catch(s){console.warn(`[acp] setMode(${n}) failed: ${s instanceof Error?s.message:String(s)}`);}}if(r?.effort){let n=this.adapter.buildEffortAction?.(r.effort,r.model);if(n&&n.type==="set_config_option")try{await e.setConfigOption(t,n.configId,n.value);}catch(s){console.warn(`[acp] setConfigOption(${n.configId}) effort failed: ${s instanceof Error?s.message:String(s)}`);}}if(r?.configOptions)for(let[n,s]of Object.entries(r.configOptions))try{await e.setConfigOption(t,n,s);}catch(i){console.warn(`[acp] setConfigOption(${n}) failed, retrying: ${i instanceof Error?i.message:String(i)}`);try{await new Promise(a=>setTimeout(a,500)),await e.setConfigOption(t,n,s);}catch(a){console.warn(`[acp] setConfigOption(${n}) retry failed: ${a instanceof Error?a.message:String(a)}`);}}}composePrompt(e,t){let r=[];return t?.systemPrompt?.trim()&&(r.push(t.systemPrompt),r.push("---")),t?.context&&(r.push(t.context),r.push("---")),r.push(e),[{type:"text",text:r.join(`
35
30
 
36
- `,r=r.slice(1));for(let{role:s,content:i}of r)switch(s){case "system":throw new ar.InvalidPromptError({message:"Unexpected system message in prompt: ${content}",prompt:r});case "user":{let a=i.map(l=>{switch(l.type){case "text":return l.text;case "image":throw new ar.UnsupportedFunctionalityError({functionality:"images"})}}).join("");o+=`${t}:
37
- ${a}
38
-
39
- `;break}case "assistant":{let a=i.map(l=>{switch(l.type){case "text":return l.text;case "tool-call":throw new ar.UnsupportedFunctionalityError({functionality:"tool-call messages"})}}).join("");o+=`${n}:
40
- ${a}
41
-
42
- `;break}case "tool":throw new ar.UnsupportedFunctionalityError({functionality:"tool messages"});default:{let a=s;throw new Error(`Unsupported role: ${a}`)}}return o+=`${n}:
43
- `,{prompt:o,stopSequences:[`
44
- ${t}:`]}}function vs(r){return r?.tokens.map((e,t)=>({token:e,logprob:r.token_logprobs[t],topLogprobs:r.top_logprobs?Object.entries(r.top_logprobs[t]).map(([n,o])=>({token:n,logprob:o})):[]}))}var od=class{constructor(r,e,t){this.specificationVersion="v1",this.defaultObjectGenerationMode=void 0,this.modelId=r,this.settings=e,this.config=t;}get provider(){return this.config.provider}getArgs({mode:r,inputFormat:e,prompt:t,maxTokens:n,temperature:o,topP:s,topK:i,frequencyPenalty:a,presencePenalty:l,stopSequences:u,responseFormat:d,seed:c}){var p;let f=r.type,v=[];i!=null&&v.push({type:"unsupported-setting",setting:"topK"}),d!=null&&d.type!=="text"&&v.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});let{prompt:h,stopSequences:m}=nd({prompt:t,inputFormat:e}),y=[...m??[],...u??[]],w={model:this.modelId,echo:this.settings.echo,logit_bias:this.settings.logitBias,logprobs:typeof this.settings.logprobs=="number"?this.settings.logprobs:typeof this.settings.logprobs=="boolean"&&this.settings.logprobs?0:void 0,suffix:this.settings.suffix,user:this.settings.user,max_tokens:n,temperature:o,top_p:s,frequency_penalty:a,presence_penalty:l,seed:c,prompt:h,stop:y.length>0?y:void 0};switch(f){case "regular":{if((p=r.tools)!=null&&p.length)throw new ir.UnsupportedFunctionalityError({functionality:"tools"});if(r.toolChoice)throw new ir.UnsupportedFunctionalityError({functionality:"toolChoice"});return {args:w,warnings:v}}case "object-json":throw new ir.UnsupportedFunctionalityError({functionality:"object-json mode"});case "object-tool":throw new ir.UnsupportedFunctionalityError({functionality:"object-tool mode"});default:{let C=f;throw new Error(`Unsupported type: ${C}`)}}}async doGenerate(r){let{args:e,warnings:t}=this.getArgs(r),{responseHeaders:n,value:o,rawValue:s}=await(0, st.postJsonToApi)({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:(0, st.combineHeaders)(this.config.headers(),r.headers),body:e,failedResponseHandler:xe,successfulResponseHandler:(0, st.createJsonResponseHandler)(sd),abortSignal:r.abortSignal,fetch:this.config.fetch}),{prompt:i,...a}=e,l=o.choices[0];return {text:l.text,usage:{promptTokens:o.usage.prompt_tokens,completionTokens:o.usage.completion_tokens},finishReason:dr(l.finish_reason),logprobs:vs(l.logprobs),rawCall:{rawPrompt:i,rawSettings:a},rawResponse:{headers:n,body:s},response:cr(o),warnings:t,request:{body:JSON.stringify(e)}}}async doStream(r){let{args:e,warnings:t}=this.getArgs(r),n={...e,stream:true,stream_options:this.config.compatibility==="strict"?{include_usage:true}:void 0},{responseHeaders:o,value:s}=await(0, st.postJsonToApi)({url:this.config.url({path:"/completions",modelId:this.modelId}),headers:(0, st.combineHeaders)(this.config.headers(),r.headers),body:n,failedResponseHandler:xe,successfulResponseHandler:(0, st.createEventSourceResponseHandler)(id),abortSignal:r.abortSignal,fetch:this.config.fetch}),{prompt:i,...a}=e,l="unknown",u={promptTokens:Number.NaN,completionTokens:Number.NaN},d,c=true;return {stream:s.pipeThrough(new TransformStream({transform(p,f){if(!p.success){l="error",f.enqueue({type:"error",error:p.error});return}let v=p.value;if("error"in v){l="error",f.enqueue({type:"error",error:v.error});return}c&&(c=false,f.enqueue({type:"response-metadata",...cr(v)})),v.usage!=null&&(u={promptTokens:v.usage.prompt_tokens,completionTokens:v.usage.completion_tokens});let h=v.choices[0];h?.finish_reason!=null&&(l=dr(h.finish_reason)),h?.text!=null&&f.enqueue({type:"text-delta",textDelta:h.text});let m=vs(h?.logprobs);m?.length&&(d===void 0&&(d=[]),d.push(...m));},flush(p){p.enqueue({type:"finish",finishReason:l,logprobs:d,usage:u});}})),rawCall:{rawPrompt:i,rawSettings:a},rawResponse:{headers:o},warnings:t,request:{body:JSON.stringify(n)}}}},sd=D.z.object({id:D.z.string().nullish(),created:D.z.number().nullish(),model:D.z.string().nullish(),choices:D.z.array(D.z.object({text:D.z.string(),finish_reason:D.z.string(),logprobs:D.z.object({tokens:D.z.array(D.z.string()),token_logprobs:D.z.array(D.z.number()),top_logprobs:D.z.array(D.z.record(D.z.string(),D.z.number())).nullable()}).nullish()})),usage:D.z.object({prompt_tokens:D.z.number(),completion_tokens:D.z.number()})}),id=D.z.union([D.z.object({id:D.z.string().nullish(),created:D.z.number().nullish(),model:D.z.string().nullish(),choices:D.z.array(D.z.object({text:D.z.string(),finish_reason:D.z.string().nullish(),index:D.z.number(),logprobs:D.z.object({tokens:D.z.array(D.z.string()),token_logprobs:D.z.array(D.z.number()),top_logprobs:D.z.array(D.z.record(D.z.string(),D.z.number())).nullable()}).nullish()})),usage:D.z.object({prompt_tokens:D.z.number(),completion_tokens:D.z.number()}).nullish()}),nn]),ad=W(),Qr=Z(),Xe=J("zod"),ld=class{constructor(r,e,t){this.specificationVersion="v1",this.modelId=r,this.settings=e,this.config=t;}get provider(){return this.config.provider}get maxEmbeddingsPerCall(){var r;return (r=this.settings.maxEmbeddingsPerCall)!=null?r:2048}get supportsParallelCalls(){var r;return (r=this.settings.supportsParallelCalls)!=null?r:true}async doEmbed({values:r,headers:e,abortSignal:t}){if(r.length>this.maxEmbeddingsPerCall)throw new ad.TooManyEmbeddingValuesForCallError({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:r});let{responseHeaders:n,value:o}=await(0, Qr.postJsonToApi)({url:this.config.url({path:"/embeddings",modelId:this.modelId}),headers:(0, Qr.combineHeaders)(this.config.headers(),e),body:{model:this.modelId,input:r,encoding_format:"float",dimensions:this.settings.dimensions,user:this.settings.user},failedResponseHandler:xe,successfulResponseHandler:(0, Qr.createJsonResponseHandler)(ud),abortSignal:t,fetch:this.config.fetch});return {embeddings:o.data.map(s=>s.embedding),usage:o.usage?{tokens:o.usage.prompt_tokens}:void 0,rawResponse:{headers:n}}}},ud=Xe.z.object({data:Xe.z.array(Xe.z.object({embedding:Xe.z.array(Xe.z.number())})),usage:Xe.z.object({prompt_tokens:Xe.z.number()}).nullish()}),Zr=Z(),lr=J("zod"),dd={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10},cd=new Set(["gpt-image-1"]),pd=class{constructor(r,e,t){this.modelId=r,this.settings=e,this.config=t,this.specificationVersion="v1";}get maxImagesPerCall(){var r,e;return (e=(r=this.settings.maxImagesPerCall)!=null?r:dd[this.modelId])!=null?e:1}get provider(){return this.config.provider}async doGenerate({prompt:r,n:e,size:t,aspectRatio:n,seed:o,providerOptions:s,headers:i,abortSignal:a}){var l,u,d,c;let p=[];n!=null&&p.push({type:"unsupported-setting",setting:"aspectRatio",details:"This model does not support aspect ratio. Use `size` instead."}),o!=null&&p.push({type:"unsupported-setting",setting:"seed"});let f=(d=(u=(l=this.config._internal)==null?void 0:l.currentDate)==null?void 0:u.call(l))!=null?d:new Date,{value:v,responseHeaders:h}=await(0, Zr.postJsonToApi)({url:this.config.url({path:"/images/generations",modelId:this.modelId}),headers:(0, Zr.combineHeaders)(this.config.headers(),i),body:{model:this.modelId,prompt:r,n:e,size:t,...(c=s.openai)!=null?c:{},...cd.has(this.modelId)?{}:{response_format:"b64_json"}},failedResponseHandler:xe,successfulResponseHandler:(0, Zr.createJsonResponseHandler)(gd),abortSignal:a,fetch:this.config.fetch});return {images:v.data.map(m=>m.b64_json),warnings:p,response:{timestamp:f,modelId:this.modelId,headers:h}}}},gd=lr.z.object({data:lr.z.array(lr.z.object({b64_json:lr.z.string()}))}),kt=Z(),te=J("zod"),md=te.z.object({include:te.z.array(te.z.string()).nullish(),language:te.z.string().nullish(),prompt:te.z.string().nullish(),temperature:te.z.number().min(0).max(1).nullish().default(0),timestampGranularities:te.z.array(te.z.enum(["word","segment"])).nullish().default(["segment"])}),_s={afrikaans:"af",arabic:"ar",armenian:"hy",azerbaijani:"az",belarusian:"be",bosnian:"bs",bulgarian:"bg",catalan:"ca",chinese:"zh",croatian:"hr",czech:"cs",danish:"da",dutch:"nl",english:"en",estonian:"et",finnish:"fi",french:"fr",galician:"gl",german:"de",greek:"el",hebrew:"he",hindi:"hi",hungarian:"hu",icelandic:"is",indonesian:"id",italian:"it",japanese:"ja",kannada:"kn",kazakh:"kk",korean:"ko",latvian:"lv",lithuanian:"lt",macedonian:"mk",malay:"ms",marathi:"mr",maori:"mi",nepali:"ne",norwegian:"no",persian:"fa",polish:"pl",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"sr",slovak:"sk",slovenian:"sl",spanish:"es",swahili:"sw",swedish:"sv",tagalog:"tl",tamil:"ta",thai:"th",turkish:"tr",ukrainian:"uk",urdu:"ur",vietnamese:"vi",welsh:"cy"},fd=class{constructor(r,e){this.modelId=r,this.config=e,this.specificationVersion="v1";}get provider(){return this.config.provider}getArgs({audio:r,mediaType:e,providerOptions:t}){var n,o,s,i,a;let l=[],u=(0, kt.parseProviderOptions)({provider:"openai",providerOptions:t,schema:md}),d=new FormData,c=r instanceof Uint8Array?new Blob([r]):new Blob([(0, kt.convertBase64ToUint8Array)(r)]);if(d.append("model",this.modelId),d.append("file",new File([c],"audio",{type:e})),u){let p={include:(n=u.include)!=null?n:void 0,language:(o=u.language)!=null?o:void 0,prompt:(s=u.prompt)!=null?s:void 0,temperature:(i=u.temperature)!=null?i:void 0,timestamp_granularities:(a=u.timestampGranularities)!=null?a:void 0};for(let f in p){let v=p[f];v!==void 0&&d.append(f,String(v));}}return {formData:d,warnings:l}}async doGenerate(r){var e,t,n,o,s,i;let a=(n=(t=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:t.call(e))!=null?n:new Date,{formData:l,warnings:u}=this.getArgs(r),{value:d,responseHeaders:c,rawValue:p}=await(0, kt.postFormDataToApi)({url:this.config.url({path:"/audio/transcriptions",modelId:this.modelId}),headers:(0, kt.combineHeaders)(this.config.headers(),r.headers),formData:l,failedResponseHandler:xe,successfulResponseHandler:(0, kt.createJsonResponseHandler)(hd),abortSignal:r.abortSignal,fetch:this.config.fetch}),f=d.language!=null&&d.language in _s?_s[d.language]:void 0;return {text:d.text,segments:(s=(o=d.words)==null?void 0:o.map(v=>({text:v.word,startSecond:v.start,endSecond:v.end})))!=null?s:[],language:f,durationInSeconds:(i=d.duration)!=null?i:void 0,warnings:u,response:{timestamp:a,modelId:this.modelId,headers:c,body:p}}}},hd=te.z.object({text:te.z.string(),language:te.z.string().nullish(),duration:te.z.number().nullish(),words:te.z.array(te.z.object({word:te.z.string(),start:te.z.number(),end:te.z.number()})).nullish()}),yd=W(),Ie=Z(),b=J("zod"),ws=W(),vd=Z();function _d({prompt:r,systemMessageMode:e}){let t=[],n=[];for(let{role:o,content:s}of r)switch(o){case "system":{switch(e){case "system":{t.push({role:"system",content:s});break}case "developer":{t.push({role:"developer",content:s});break}case "remove":{n.push({type:"other",message:"system messages are removed for this model"});break}default:{let i=e;throw new Error(`Unsupported system message mode: ${i}`)}}break}case "user":{t.push({role:"user",content:s.map((i,a)=>{var l,u,d,c;switch(i.type){case "text":return {type:"input_text",text:i.text};case "image":return {type:"input_image",image_url:i.image instanceof URL?i.image.toString():`data:${(l=i.mimeType)!=null?l:"image/jpeg"};base64,${(0, vd.convertUint8ArrayToBase64)(i.image)}`,detail:(d=(u=i.providerMetadata)==null?void 0:u.openai)==null?void 0:d.imageDetail};case "file":{if(i.data instanceof URL)throw new ws.UnsupportedFunctionalityError({functionality:"File URLs in user messages"});if(i.mimeType==="application/pdf")return {type:"input_file",filename:(c=i.filename)!=null?c:`part-${a}.pdf`,file_data:`data:application/pdf;base64,${i.data}`};throw new ws.UnsupportedFunctionalityError({functionality:"Only PDF files are supported in user messages"})}}})});break}case "assistant":{for(let i of s)switch(i.type){case "text":{t.push({role:"assistant",content:[{type:"output_text",text:i.text}]});break}case "tool-call":{t.push({type:"function_call",call_id:i.toolCallId,name:i.toolName,arguments:JSON.stringify(i.args)});break}}break}case "tool":{for(let i of s)t.push({type:"function_call_output",call_id:i.toolCallId,output:JSON.stringify(i.result)});break}default:{let i=o;throw new Error(`Unsupported role: ${i}`)}}return {messages:t,warnings:n}}function bs({finishReason:r,hasToolCalls:e}){switch(r){case void 0:case null:return e?"tool-calls":"stop";case "max_output_tokens":return "length";case "content_filter":return "content-filter";default:return e?"tool-calls":"unknown"}}var wd=W();function bd({mode:r,strict:e}){var t;let n=(t=r.tools)!=null&&t.length?r.tools:void 0,o=[];if(n==null)return {tools:void 0,tool_choice:void 0,toolWarnings:o};let s=r.toolChoice,i=[];for(let l of n)switch(l.type){case "function":i.push({type:"function",name:l.name,description:l.description,parameters:l.parameters,strict:e?true:void 0});break;case "provider-defined":l.id==="openai.web_search_preview"?i.push({type:"web_search_preview",search_context_size:l.args.searchContextSize,user_location:l.args.userLocation}):o.push({type:"unsupported-tool",tool:l});break;default:o.push({type:"unsupported-tool",tool:l});break}if(s==null)return {tools:i,tool_choice:void 0,toolWarnings:o};let a=s.type;switch(a){case "auto":case "none":case "required":return {tools:i,tool_choice:a,toolWarnings:o};case "tool":return s.toolName==="web_search_preview"?{tools:i,tool_choice:{type:"web_search_preview"},toolWarnings:o}:{tools:i,tool_choice:{type:"function",name:s.toolName},toolWarnings:o};default:{let l=a;throw new wd.UnsupportedFunctionalityError({functionality:`Unsupported tool choice type: ${l}`})}}}var xd=class{constructor(r,e){this.specificationVersion="v1",this.defaultObjectGenerationMode="json",this.supportsStructuredOutputs=true,this.modelId=r,this.config=e;}get provider(){return this.config.provider}getArgs({mode:r,maxTokens:e,temperature:t,stopSequences:n,topP:o,topK:s,presencePenalty:i,frequencyPenalty:a,seed:l,prompt:u,providerMetadata:d,responseFormat:c}){var p,f,v;let h=[],m=Fd(this.modelId),y=r.type;s!=null&&h.push({type:"unsupported-setting",setting:"topK"}),l!=null&&h.push({type:"unsupported-setting",setting:"seed"}),i!=null&&h.push({type:"unsupported-setting",setting:"presencePenalty"}),a!=null&&h.push({type:"unsupported-setting",setting:"frequencyPenalty"}),n!=null&&h.push({type:"unsupported-setting",setting:"stopSequences"});let{messages:w,warnings:C}=_d({prompt:u,systemMessageMode:m.systemMessageMode});h.push(...C);let _=(0, Ie.parseProviderOptions)({provider:"openai",providerOptions:d,schema:Ud}),k=(p=_?.strictSchemas)!=null?p:true,S={model:this.modelId,input:w,temperature:t,top_p:o,max_output_tokens:e,...c?.type==="json"&&{text:{format:c.schema!=null?{type:"json_schema",strict:k,name:(f=c.name)!=null?f:"response",description:c.description,schema:c.schema}:{type:"json_object"}}},metadata:_?.metadata,parallel_tool_calls:_?.parallelToolCalls,previous_response_id:_?.previousResponseId,store:_?.store,user:_?.user,instructions:_?.instructions,...m.isReasoningModel&&(_?.reasoningEffort!=null||_?.reasoningSummary!=null)&&{reasoning:{..._?.reasoningEffort!=null&&{effort:_.reasoningEffort},..._?.reasoningSummary!=null&&{summary:_.reasoningSummary}}},...m.requiredAutoTruncation};switch(m.isReasoningModel&&(S.temperature!=null&&(S.temperature=void 0,h.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported for reasoning models"})),S.top_p!=null&&(S.top_p=void 0,h.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported for reasoning models"}))),y){case "regular":{let{tools:z,tool_choice:R,toolWarnings:x}=bd({mode:r,strict:k});return {args:{...S,tools:z,tool_choice:R},warnings:[...h,...x]}}case "object-json":return {args:{...S,text:{format:r.schema!=null?{type:"json_schema",strict:k,name:(v=r.name)!=null?v:"response",description:r.description,schema:r.schema}:{type:"json_object"}}},warnings:h};case "object-tool":return {args:{...S,tool_choice:{type:"function",name:r.tool.name},tools:[{type:"function",name:r.tool.name,description:r.tool.description,parameters:r.tool.parameters,strict:k}]},warnings:h};default:{let z=y;throw new Error(`Unsupported type: ${z}`)}}}async doGenerate(r){var e,t,n,o,s,i,a;let{args:l,warnings:u}=this.getArgs(r),d=this.config.url({path:"/responses",modelId:this.modelId}),{responseHeaders:c,value:p,rawValue:f}=await(0, Ie.postJsonToApi)({url:d,headers:(0, Ie.combineHeaders)(this.config.headers(),r.headers),body:l,failedResponseHandler:xe,successfulResponseHandler:(0, Ie.createJsonResponseHandler)(b.z.object({id:b.z.string(),created_at:b.z.number(),error:b.z.object({message:b.z.string(),code:b.z.string()}).nullish(),model:b.z.string(),output:b.z.array(b.z.discriminatedUnion("type",[b.z.object({type:b.z.literal("message"),role:b.z.literal("assistant"),content:b.z.array(b.z.object({type:b.z.literal("output_text"),text:b.z.string(),annotations:b.z.array(b.z.object({type:b.z.literal("url_citation"),start_index:b.z.number(),end_index:b.z.number(),url:b.z.string(),title:b.z.string()}))}))}),b.z.object({type:b.z.literal("function_call"),call_id:b.z.string(),name:b.z.string(),arguments:b.z.string()}),b.z.object({type:b.z.literal("web_search_call")}),b.z.object({type:b.z.literal("computer_call")}),b.z.object({type:b.z.literal("reasoning"),summary:b.z.array(b.z.object({type:b.z.literal("summary_text"),text:b.z.string()}))})])),incomplete_details:b.z.object({reason:b.z.string()}).nullable(),usage:Rs})),abortSignal:r.abortSignal,fetch:this.config.fetch});if(p.error)throw new yd.APICallError({message:p.error.message,url:d,requestBodyValues:l,statusCode:400,responseHeaders:c,responseBody:f,isRetryable:false});let v=p.output.filter(y=>y.type==="message").flatMap(y=>y.content).filter(y=>y.type==="output_text"),h=p.output.filter(y=>y.type==="function_call").map(y=>({toolCallType:"function",toolCallId:y.call_id,toolName:y.name,args:y.arguments})),m=(t=(e=p.output.find(y=>y.type==="reasoning"))==null?void 0:e.summary)!=null?t:null;return {text:v.map(y=>y.text).join(`
45
- `),sources:v.flatMap(y=>y.annotations.map(w=>{var C,_,k;return {sourceType:"url",id:(k=(_=(C=this.config).generateId)==null?void 0:_.call(C))!=null?k:(0, Ie.generateId)(),url:w.url,title:w.title}})),finishReason:bs({finishReason:(n=p.incomplete_details)==null?void 0:n.reason,hasToolCalls:h.length>0}),toolCalls:h.length>0?h:void 0,reasoning:m?m.map(y=>({type:"text",text:y.text})):void 0,usage:{promptTokens:p.usage.input_tokens,completionTokens:p.usage.output_tokens},rawCall:{rawPrompt:void 0,rawSettings:{}},rawResponse:{headers:c,body:f},request:{body:JSON.stringify(l)},response:{id:p.id,timestamp:new Date(p.created_at*1e3),modelId:p.model},providerMetadata:{openai:{responseId:p.id,cachedPromptTokens:(s=(o=p.usage.input_tokens_details)==null?void 0:o.cached_tokens)!=null?s:null,reasoningTokens:(a=(i=p.usage.output_tokens_details)==null?void 0:i.reasoning_tokens)!=null?a:null}},warnings:u}}async doStream(r){let{args:e,warnings:t}=this.getArgs(r),{responseHeaders:n,value:o}=await(0, Ie.postJsonToApi)({url:this.config.url({path:"/responses",modelId:this.modelId}),headers:(0, Ie.combineHeaders)(this.config.headers(),r.headers),body:{...e,stream:true},failedResponseHandler:xe,successfulResponseHandler:(0, Ie.createEventSourceResponseHandler)(Od),abortSignal:r.abortSignal,fetch:this.config.fetch}),s=this,i="unknown",a=NaN,l=NaN,u=null,d=null,c=null,p={},f=false;return {stream:o.pipeThrough(new TransformStream({transform(v,h){var m,y,w,C,_,k,S,z;if(!v.success){i="error",h.enqueue({type:"error",error:v.error});return}let R=v.value;if($d(R))R.item.type==="function_call"&&(p[R.output_index]={toolName:R.item.name,toolCallId:R.item.call_id},h.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:R.item.call_id,toolName:R.item.name,argsTextDelta:R.item.arguments}));else if(Dd(R)){let x=p[R.output_index];x!=null&&h.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:x.toolCallId,toolName:x.toolName,argsTextDelta:R.delta});}else Nd(R)?(c=R.response.id,h.enqueue({type:"response-metadata",id:R.response.id,timestamp:new Date(R.response.created_at*1e3),modelId:R.response.model})):zd(R)?h.enqueue({type:"text-delta",textDelta:R.delta}):qd(R)?h.enqueue({type:"reasoning",textDelta:R.delta}):Md(R)&&R.item.type==="function_call"?(p[R.output_index]=void 0,f=true,h.enqueue({type:"tool-call",toolCallType:"function",toolCallId:R.item.call_id,toolName:R.item.name,args:R.item.arguments})):jd(R)?(i=bs({finishReason:(m=R.response.incomplete_details)==null?void 0:m.reason,hasToolCalls:f}),a=R.response.usage.input_tokens,l=R.response.usage.output_tokens,u=(w=(y=R.response.usage.input_tokens_details)==null?void 0:y.cached_tokens)!=null?w:u,d=(_=(C=R.response.usage.output_tokens_details)==null?void 0:C.reasoning_tokens)!=null?_:d):Hd(R)?h.enqueue({type:"source",source:{sourceType:"url",id:(z=(S=(k=s.config).generateId)==null?void 0:S.call(k))!=null?z:(0, Ie.generateId)(),url:R.annotation.url,title:R.annotation.title}}):Ld(R)&&h.enqueue({type:"error",error:R});},flush(v){v.enqueue({type:"finish",finishReason:i,usage:{promptTokens:a,completionTokens:l},...(u!=null||d!=null)&&{providerMetadata:{openai:{responseId:c,cachedPromptTokens:u,reasoningTokens:d}}}});}})),rawCall:{rawPrompt:void 0,rawSettings:{}},rawResponse:{headers:n},request:{body:JSON.stringify(e)},warnings:t}}},Rs=b.z.object({input_tokens:b.z.number(),input_tokens_details:b.z.object({cached_tokens:b.z.number().nullish()}).nullish(),output_tokens:b.z.number(),output_tokens_details:b.z.object({reasoning_tokens:b.z.number().nullish()}).nullish()}),kd=b.z.object({type:b.z.literal("response.output_text.delta"),delta:b.z.string()}),Rd=b.z.object({type:b.z.enum(["response.completed","response.incomplete"]),response:b.z.object({incomplete_details:b.z.object({reason:b.z.string()}).nullish(),usage:Rs})}),Cd=b.z.object({type:b.z.literal("response.created"),response:b.z.object({id:b.z.string(),created_at:b.z.number(),model:b.z.string()})}),Td=b.z.object({type:b.z.literal("response.output_item.done"),output_index:b.z.number(),item:b.z.discriminatedUnion("type",[b.z.object({type:b.z.literal("message")}),b.z.object({type:b.z.literal("function_call"),id:b.z.string(),call_id:b.z.string(),name:b.z.string(),arguments:b.z.string(),status:b.z.literal("completed")})])}),Pd=b.z.object({type:b.z.literal("response.function_call_arguments.delta"),item_id:b.z.string(),output_index:b.z.number(),delta:b.z.string()}),Ad=b.z.object({type:b.z.literal("response.output_item.added"),output_index:b.z.number(),item:b.z.discriminatedUnion("type",[b.z.object({type:b.z.literal("message")}),b.z.object({type:b.z.literal("function_call"),id:b.z.string(),call_id:b.z.string(),name:b.z.string(),arguments:b.z.string()})])}),Ed=b.z.object({type:b.z.literal("response.output_text.annotation.added"),annotation:b.z.object({type:b.z.literal("url_citation"),url:b.z.string(),title:b.z.string()})}),Sd=b.z.object({type:b.z.literal("response.reasoning_summary_text.delta"),item_id:b.z.string(),output_index:b.z.number(),summary_index:b.z.number(),delta:b.z.string()}),Id=b.z.object({type:b.z.literal("error"),code:b.z.string(),message:b.z.string(),param:b.z.string().nullish(),sequence_number:b.z.number()}),Od=b.z.union([kd,Rd,Cd,Td,Pd,Ad,Ed,Sd,Id,b.z.object({type:b.z.string()}).passthrough()]);function zd(r){return r.type==="response.output_text.delta"}function Md(r){return r.type==="response.output_item.done"}function jd(r){return r.type==="response.completed"||r.type==="response.incomplete"}function Nd(r){return r.type==="response.created"}function Dd(r){return r.type==="response.function_call_arguments.delta"}function $d(r){return r.type==="response.output_item.added"}function Hd(r){return r.type==="response.output_text.annotation.added"}function qd(r){return r.type==="response.reasoning_summary_text.delta"}function Ld(r){return r.type==="error"}function Fd(r){return r.startsWith("o")||r.startsWith("gpt-5")?r.startsWith("o1-mini")||r.startsWith("o1-preview")?{isReasoningModel:true,systemMessageMode:"remove",requiredAutoTruncation:false}:{isReasoningModel:true,systemMessageMode:"developer",requiredAutoTruncation:false}:{isReasoningModel:false,systemMessageMode:"system",requiredAutoTruncation:false}}var Ud=b.z.object({metadata:b.z.any().nullish(),parallelToolCalls:b.z.boolean().nullish(),previousResponseId:b.z.string().nullish(),store:b.z.boolean().nullish(),user:b.z.string().nullish(),reasoningEffort:b.z.string().nullish(),strictSchemas:b.z.boolean().nullish(),instructions:b.z.string().nullish(),reasoningSummary:b.z.string().nullish()}),Bd=J("zod"),Wd=Bd.z.object({});function Jd({searchContextSize:r,userLocation:e}={}){return {type:"provider-defined",id:"openai.web_search_preview",args:{searchContextSize:r,userLocation:e},parameters:Wd}}var Vd={webSearchPreview:Jd},ur=Z(),en=J("zod"),Kd=en.z.object({instructions:en.z.string().nullish(),speed:en.z.number().min(.25).max(4).default(1).nullish()}),Gd=class{constructor(r,e){this.modelId=r,this.config=e,this.specificationVersion="v1";}get provider(){return this.config.provider}getArgs({text:r,voice:e="alloy",outputFormat:t="mp3",speed:n,instructions:o,providerOptions:s}){let i=[],a=(0, ur.parseProviderOptions)({provider:"openai",providerOptions:s,schema:Kd}),l={model:this.modelId,input:r,voice:e,response_format:"mp3",speed:n,instructions:o};if(t&&(["mp3","opus","aac","flac","wav","pcm"].includes(t)?l.response_format=t:i.push({type:"unsupported-setting",setting:"outputFormat",details:`Unsupported output format: ${t}. Using mp3 instead.`})),a){let u={};for(let d in u){let c=u[d];c!==void 0&&(l[d]=c);}}return {requestBody:l,warnings:i}}async doGenerate(r){var e,t,n;let o=(n=(t=(e=this.config._internal)==null?void 0:e.currentDate)==null?void 0:t.call(e))!=null?n:new Date,{requestBody:s,warnings:i}=this.getArgs(r),{value:a,responseHeaders:l,rawValue:u}=await(0, ur.postJsonToApi)({url:this.config.url({path:"/audio/speech",modelId:this.modelId}),headers:(0, ur.combineHeaders)(this.config.headers(),r.headers),body:s,failedResponseHandler:xe,successfulResponseHandler:(0, ur.createBinaryResponseHandler)(),abortSignal:r.abortSignal,fetch:this.config.fetch});return {audio:a,warnings:i,request:{body:JSON.stringify(s)},response:{timestamp:o,modelId:this.modelId,headers:l,body:u}}}};function Cs(r={}){var e,t,n;let o=(e=(0, fs.withoutTrailingSlash)(r.baseURL))!=null?e:"https://api.openai.com/v1",s=(t=r.compatibility)!=null?t:"compatible",i=(n=r.name)!=null?n:"openai",a=()=>({Authorization:`Bearer ${(0, fs.loadApiKey)({apiKey:r.apiKey,environmentVariableName:"OPENAI_API_KEY",description:"OpenAI"})}`,"OpenAI-Organization":r.organization,"OpenAI-Project":r.project,...r.headers}),l=(y,w={})=>new Yu(y,w,{provider:`${i}.chat`,url:({path:C})=>`${o}${C}`,headers:a,compatibility:s,fetch:r.fetch}),u=(y,w={})=>new od(y,w,{provider:`${i}.completion`,url:({path:C})=>`${o}${C}`,headers:a,compatibility:s,fetch:r.fetch}),d=(y,w={})=>new ld(y,w,{provider:`${i}.embedding`,url:({path:C})=>`${o}${C}`,headers:a,fetch:r.fetch}),c=(y,w={})=>new pd(y,w,{provider:`${i}.image`,url:({path:C})=>`${o}${C}`,headers:a,fetch:r.fetch}),p=y=>new fd(y,{provider:`${i}.transcription`,url:({path:w})=>`${o}${w}`,headers:a,fetch:r.fetch}),f=y=>new Gd(y,{provider:`${i}.speech`,url:({path:w})=>`${o}${w}`,headers:a,fetch:r.fetch}),v=(y,w)=>{if(new.target)throw new Error("The OpenAI model function cannot be called with the new keyword.");return y==="gpt-3.5-turbo-instruct"?u(y,w):l(y,w)},h=y=>new xd(y,{provider:`${i}.responses`,url:({path:w})=>`${o}${w}`,headers:a,fetch:r.fetch}),m=function(y,w){return v(y,w)};return m.languageModel=v,m.chat=l,m.completion=u,m.responses=h,m.embedding=d,m.textEmbedding=d,m.textEmbeddingModel=d,m.image=c,m.imageModel=c,m.transcription=p,m.transcriptionModel=p,m.speech=f,m.speechModel=f,m.tools=Vd,m}var Xd=Cs({compatibility:"strict"});});var js=$e((Ly,Ms)=>{g();var sn=Object.defineProperty,Yd=Object.getOwnPropertyDescriptor,Qd=Object.getOwnPropertyNames,Zd=Object.prototype.hasOwnProperty,ec=(r,e)=>{for(var t in e)sn(r,t,{get:e[t],enumerable:true});},tc=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Qd(e))!Zd.call(r,o)&&o!==t&&sn(r,o,{get:()=>e[o],enumerable:!(n=Yd(e,o))||n.enumerable});return r},rc=r=>tc(sn({},"__esModule",{value:true}),r),Os={};ec(Os,{anthropic:()=>Ac,createAnthropic:()=>zs});Ms.exports=rc(Os);var nc=W(),Ps=Z(),As=W(),Ye=Z(),T=J("zod"),oc=Z(),Rt=J("zod"),sc=Rt.z.object({type:Rt.z.literal("error"),error:Rt.z.object({type:Rt.z.string(),message:Rt.z.string()})}),Es=(0, oc.createJsonErrorResponseHandler)({errorSchema:sc,errorToMessage:r=>r.error.message}),ic=W();function ac(r){var e;let t=(e=r.tools)!=null&&e.length?r.tools:void 0,n=[],o=new Set;if(t==null)return {tools:void 0,tool_choice:void 0,toolWarnings:n,betas:o};let s=[];for(let l of t)switch(l.type){case "function":s.push({name:l.name,description:l.description,input_schema:l.parameters});break;case "provider-defined":switch(l.id){case "anthropic.computer_20250124":o.add("computer-use-2025-01-24"),s.push({name:l.name,type:"computer_20250124",display_width_px:l.args.displayWidthPx,display_height_px:l.args.displayHeightPx,display_number:l.args.displayNumber});break;case "anthropic.computer_20241022":o.add("computer-use-2024-10-22"),s.push({name:l.name,type:"computer_20241022",display_width_px:l.args.displayWidthPx,display_height_px:l.args.displayHeightPx,display_number:l.args.displayNumber});break;case "anthropic.text_editor_20250124":o.add("computer-use-2025-01-24"),s.push({name:l.name,type:"text_editor_20250124"});break;case "anthropic.text_editor_20241022":o.add("computer-use-2024-10-22"),s.push({name:l.name,type:"text_editor_20241022"});break;case "anthropic.bash_20250124":o.add("computer-use-2025-01-24"),s.push({name:l.name,type:"bash_20250124"});break;case "anthropic.bash_20241022":o.add("computer-use-2024-10-22"),s.push({name:l.name,type:"bash_20241022"});break;default:n.push({type:"unsupported-tool",tool:l});break}break;default:n.push({type:"unsupported-tool",tool:l});break}let i=r.toolChoice;if(i==null)return {tools:s,tool_choice:void 0,toolWarnings:n,betas:o};let a=i.type;switch(a){case "auto":return {tools:s,tool_choice:{type:"auto"},toolWarnings:n,betas:o};case "required":return {tools:s,tool_choice:{type:"any"},toolWarnings:n,betas:o};case "none":return {tools:void 0,tool_choice:void 0,toolWarnings:n,betas:o};case "tool":return {tools:s,tool_choice:{type:"tool",name:i.toolName},toolWarnings:n,betas:o};default:{let l=a;throw new ic.UnsupportedFunctionalityError({functionality:`Unsupported tool choice type: ${l}`})}}}var Ss=W(),lc=Z();function uc({prompt:r,sendReasoning:e,warnings:t}){var n,o,s,i;let a=new Set,l=dc(r),u,d=[];function c(p){var f;let v=p?.anthropic;return (f=v?.cacheControl)!=null?f:v?.cache_control}for(let p=0;p<l.length;p++){let f=l[p],v=p===l.length-1,h=f.type;switch(h){case "system":{if(u!=null)throw new Ss.UnsupportedFunctionalityError({functionality:"Multiple system messages that are separated by user/assistant messages"});u=f.messages.map(({content:m,providerMetadata:y})=>({type:"text",text:m,cache_control:c(y)}));break}case "user":{let m=[];for(let y of f.messages){let{role:w,content:C}=y;switch(w){case "user":{for(let _=0;_<C.length;_++){let k=C[_],S=_===C.length-1,z=(n=c(k.providerMetadata))!=null?n:S?c(y.providerMetadata):void 0;switch(k.type){case "text":{m.push({type:"text",text:k.text,cache_control:z});break}case "image":{m.push({type:"image",source:k.image instanceof URL?{type:"url",url:k.image.toString()}:{type:"base64",media_type:(o=k.mimeType)!=null?o:"image/jpeg",data:(0, lc.convertUint8ArrayToBase64)(k.image)},cache_control:z});break}case "file":{if(k.mimeType!=="application/pdf")throw new Ss.UnsupportedFunctionalityError({functionality:"Non-PDF files in user messages"});a.add("pdfs-2024-09-25"),m.push({type:"document",source:k.data instanceof URL?{type:"url",url:k.data.toString()}:{type:"base64",media_type:"application/pdf",data:k.data},cache_control:z});break}}}break}case "tool":{for(let _=0;_<C.length;_++){let k=C[_],S=_===C.length-1,z=(s=c(k.providerMetadata))!=null?s:S?c(y.providerMetadata):void 0,R=k.content!=null?k.content.map(x=>{var M;switch(x.type){case "text":return {type:"text",text:x.text,cache_control:void 0};case "image":return {type:"image",source:{type:"base64",media_type:(M=x.mimeType)!=null?M:"image/jpeg",data:x.data},cache_control:void 0}}}):JSON.stringify(k.result);m.push({type:"tool_result",tool_use_id:k.toolCallId,content:R,is_error:k.isError,cache_control:z});}break}default:{let _=w;throw new Error(`Unsupported role: ${_}`)}}}d.push({role:"user",content:m});break}case "assistant":{let m=[];for(let y=0;y<f.messages.length;y++){let w=f.messages[y],C=y===f.messages.length-1,{content:_}=w;for(let k=0;k<_.length;k++){let S=_[k],z=k===_.length-1,R=(i=c(S.providerMetadata))!=null?i:z?c(w.providerMetadata):void 0;switch(S.type){case "text":{m.push({type:"text",text:v&&C&&z?S.text.trim():S.text,cache_control:R});break}case "reasoning":{e?m.push({type:"thinking",thinking:S.text,signature:S.signature,cache_control:R}):t.push({type:"other",message:"sending reasoning content is disabled for this model"});break}case "redacted-reasoning":{m.push({type:"redacted_thinking",data:S.data,cache_control:R});break}case "tool-call":{m.push({type:"tool_use",id:S.toolCallId,name:S.toolName,input:S.args,cache_control:R});break}}}}d.push({role:"assistant",content:m});break}default:{let m=h;throw new Error(`Unsupported type: ${m}`)}}}return {prompt:{system:u,messages:d},betas:a}}function dc(r){let e=[],t;for(let n of r){let{role:o}=n;switch(o){case "system":{t?.type!=="system"&&(t={type:"system",messages:[]},e.push(t)),t.messages.push(n);break}case "assistant":{t?.type!=="assistant"&&(t={type:"assistant",messages:[]},e.push(t)),t.messages.push(n);break}case "user":{t?.type!=="user"&&(t={type:"user",messages:[]},e.push(t)),t.messages.push(n);break}case "tool":{t?.type!=="user"&&(t={type:"user",messages:[]},e.push(t)),t.messages.push(n);break}default:{let s=o;throw new Error(`Unsupported role: ${s}`)}}}return e}function Is(r){switch(r){case "end_turn":case "stop_sequence":return "stop";case "tool_use":return "tool-calls";case "max_tokens":return "length";default:return "unknown"}}var cc=class{constructor(r,e,t){this.specificationVersion="v1",this.defaultObjectGenerationMode="tool",this.modelId=r,this.settings=e,this.config=t;}supportsUrl(r){return r.protocol==="https:"}get provider(){return this.config.provider}get supportsImageUrls(){return this.config.supportsImageUrls}async getArgs({mode:r,prompt:e,maxTokens:t=4096,temperature:n,topP:o,topK:s,frequencyPenalty:i,presencePenalty:a,stopSequences:l,responseFormat:u,seed:d,providerMetadata:c}){var p,f,v;let h=r.type,m=[];i!=null&&m.push({type:"unsupported-setting",setting:"frequencyPenalty"}),a!=null&&m.push({type:"unsupported-setting",setting:"presencePenalty"}),d!=null&&m.push({type:"unsupported-setting",setting:"seed"}),u!=null&&u.type!=="text"&&m.push({type:"unsupported-setting",setting:"responseFormat",details:"JSON response format is not supported."});let{prompt:y,betas:w}=uc({prompt:e,sendReasoning:(p=this.settings.sendReasoning)!=null?p:true,warnings:m}),C=(0, Ye.parseProviderOptions)({provider:"anthropic",providerOptions:c,schema:mc}),_=((f=C?.thinking)==null?void 0:f.type)==="enabled",k=(v=C?.thinking)==null?void 0:v.budgetTokens,S={model:this.modelId,max_tokens:t,temperature:n,top_k:s,top_p:o,stop_sequences:l,..._&&{thinking:{type:"enabled",budget_tokens:k}},system:y.system,messages:y.messages};if(_){if(k==null)throw new As.UnsupportedFunctionalityError({functionality:"thinking requires a budget"});S.temperature!=null&&(S.temperature=void 0,m.push({type:"unsupported-setting",setting:"temperature",details:"temperature is not supported when thinking is enabled"})),s!=null&&(S.top_k=void 0,m.push({type:"unsupported-setting",setting:"topK",details:"topK is not supported when thinking is enabled"})),o!=null&&(S.top_p=void 0,m.push({type:"unsupported-setting",setting:"topP",details:"topP is not supported when thinking is enabled"})),S.max_tokens=t+k;}switch(h){case "regular":{let{tools:z,tool_choice:R,toolWarnings:x,betas:M}=ac(r);return {args:{...S,tools:z,tool_choice:R},warnings:[...m,...x],betas:new Set([...w,...M])}}case "object-json":throw new As.UnsupportedFunctionalityError({functionality:"json-mode object generation"});case "object-tool":{let{name:z,description:R,parameters:x}=r.tool;return {args:{...S,tools:[{name:z,description:R,input_schema:x}],tool_choice:{type:"tool",name:z}},warnings:m,betas:w}}default:{let z=h;throw new Error(`Unsupported type: ${z}`)}}}async getHeaders({betas:r,headers:e}){return (0, Ye.combineHeaders)(await(0, Ye.resolve)(this.config.headers),r.size>0?{"anthropic-beta":Array.from(r).join(",")}:{},e)}buildRequestUrl(r){var e,t,n;return (n=(t=(e=this.config).buildRequestUrl)==null?void 0:t.call(e,this.config.baseURL,r))!=null?n:`${this.config.baseURL}/messages`}transformRequestBody(r){var e,t,n;return (n=(t=(e=this.config).transformRequestBody)==null?void 0:t.call(e,r))!=null?n:r}async doGenerate(r){var e,t,n,o;let{args:s,warnings:i,betas:a}=await this.getArgs(r),{responseHeaders:l,value:u,rawValue:d}=await(0, Ye.postJsonToApi)({url:this.buildRequestUrl(false),headers:await this.getHeaders({betas:a,headers:r.headers}),body:this.transformRequestBody(s),failedResponseHandler:Es,successfulResponseHandler:(0, Ye.createJsonResponseHandler)(pc),abortSignal:r.abortSignal,fetch:this.config.fetch}),{messages:c,...p}=s,f="";for(let m of u.content)m.type==="text"&&(f+=m.text);let v;if(u.content.some(m=>m.type==="tool_use")){v=[];for(let m of u.content)m.type==="tool_use"&&v.push({toolCallType:"function",toolCallId:m.id,toolName:m.name,args:JSON.stringify(m.input)});}let h=u.content.filter(m=>m.type==="redacted_thinking"||m.type==="thinking").map(m=>m.type==="thinking"?{type:"text",text:m.thinking,signature:m.signature}:{type:"redacted",data:m.data});return {text:f,reasoning:h.length>0?h:void 0,toolCalls:v,finishReason:Is(u.stop_reason),usage:{promptTokens:u.usage.input_tokens,completionTokens:u.usage.output_tokens},rawCall:{rawPrompt:c,rawSettings:p},rawResponse:{headers:l,body:d},response:{id:(e=u.id)!=null?e:void 0,modelId:(t=u.model)!=null?t:void 0},warnings:i,providerMetadata:{anthropic:{cacheCreationInputTokens:(n=u.usage.cache_creation_input_tokens)!=null?n:null,cacheReadInputTokens:(o=u.usage.cache_read_input_tokens)!=null?o:null}},request:{body:JSON.stringify(s)}}}async doStream(r){let{args:e,warnings:t,betas:n}=await this.getArgs(r),o={...e,stream:true},{responseHeaders:s,value:i}=await(0, Ye.postJsonToApi)({url:this.buildRequestUrl(true),headers:await this.getHeaders({betas:n,headers:r.headers}),body:this.transformRequestBody(o),failedResponseHandler:Es,successfulResponseHandler:(0, Ye.createEventSourceResponseHandler)(gc),abortSignal:r.abortSignal,fetch:this.config.fetch}),{messages:a,...l}=e,u="unknown",d={promptTokens:Number.NaN,completionTokens:Number.NaN},c={},p,f;return {stream:i.pipeThrough(new TransformStream({transform(v,h){var m,y,w,C;if(!v.success){h.enqueue({type:"error",error:v.error});return}let _=v.value;switch(_.type){case "ping":return;case "content_block_start":{let k=_.content_block.type;switch(f=k,k){case "text":case "thinking":return;case "redacted_thinking":{h.enqueue({type:"redacted-reasoning",data:_.content_block.data});return}case "tool_use":{c[_.index]={toolCallId:_.content_block.id,toolName:_.content_block.name,jsonText:""};return}default:{let S=k;throw new Error(`Unsupported content block type: ${S}`)}}}case "content_block_stop":{if(c[_.index]!=null){let k=c[_.index];h.enqueue({type:"tool-call",toolCallType:"function",toolCallId:k.toolCallId,toolName:k.toolName,args:k.jsonText}),delete c[_.index];}f=void 0;return}case "content_block_delta":{let k=_.delta.type;switch(k){case "text_delta":{h.enqueue({type:"text-delta",textDelta:_.delta.text});return}case "thinking_delta":{h.enqueue({type:"reasoning",textDelta:_.delta.thinking});return}case "signature_delta":{f==="thinking"&&h.enqueue({type:"reasoning-signature",signature:_.delta.signature});return}case "input_json_delta":{let S=c[_.index];h.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:S.toolCallId,toolName:S.toolName,argsTextDelta:_.delta.partial_json}),S.jsonText+=_.delta.partial_json;return}default:{let S=k;throw new Error(`Unsupported delta type: ${S}`)}}}case "message_start":{d.promptTokens=_.message.usage.input_tokens,d.completionTokens=_.message.usage.output_tokens,p={anthropic:{cacheCreationInputTokens:(m=_.message.usage.cache_creation_input_tokens)!=null?m:null,cacheReadInputTokens:(y=_.message.usage.cache_read_input_tokens)!=null?y:null}},h.enqueue({type:"response-metadata",id:(w=_.message.id)!=null?w:void 0,modelId:(C=_.message.model)!=null?C:void 0});return}case "message_delta":{d.completionTokens=_.usage.output_tokens,u=Is(_.delta.stop_reason);return}case "message_stop":{h.enqueue({type:"finish",finishReason:u,usage:d,providerMetadata:p});return}case "error":{h.enqueue({type:"error",error:_.error});return}default:{let k=_;throw new Error(`Unsupported chunk type: ${k}`)}}}})),rawCall:{rawPrompt:a,rawSettings:l},rawResponse:{headers:s},warnings:t,request:{body:JSON.stringify(o)}}}},pc=T.z.object({type:T.z.literal("message"),id:T.z.string().nullish(),model:T.z.string().nullish(),content:T.z.array(T.z.discriminatedUnion("type",[T.z.object({type:T.z.literal("text"),text:T.z.string()}),T.z.object({type:T.z.literal("thinking"),thinking:T.z.string(),signature:T.z.string()}),T.z.object({type:T.z.literal("redacted_thinking"),data:T.z.string()}),T.z.object({type:T.z.literal("tool_use"),id:T.z.string(),name:T.z.string(),input:T.z.unknown()})])),stop_reason:T.z.string().nullish(),usage:T.z.object({input_tokens:T.z.number(),output_tokens:T.z.number(),cache_creation_input_tokens:T.z.number().nullish(),cache_read_input_tokens:T.z.number().nullish()})}),gc=T.z.discriminatedUnion("type",[T.z.object({type:T.z.literal("message_start"),message:T.z.object({id:T.z.string().nullish(),model:T.z.string().nullish(),usage:T.z.object({input_tokens:T.z.number(),output_tokens:T.z.number(),cache_creation_input_tokens:T.z.number().nullish(),cache_read_input_tokens:T.z.number().nullish()})})}),T.z.object({type:T.z.literal("content_block_start"),index:T.z.number(),content_block:T.z.discriminatedUnion("type",[T.z.object({type:T.z.literal("text"),text:T.z.string()}),T.z.object({type:T.z.literal("thinking"),thinking:T.z.string()}),T.z.object({type:T.z.literal("tool_use"),id:T.z.string(),name:T.z.string()}),T.z.object({type:T.z.literal("redacted_thinking"),data:T.z.string()})])}),T.z.object({type:T.z.literal("content_block_delta"),index:T.z.number(),delta:T.z.discriminatedUnion("type",[T.z.object({type:T.z.literal("input_json_delta"),partial_json:T.z.string()}),T.z.object({type:T.z.literal("text_delta"),text:T.z.string()}),T.z.object({type:T.z.literal("thinking_delta"),thinking:T.z.string()}),T.z.object({type:T.z.literal("signature_delta"),signature:T.z.string()})])}),T.z.object({type:T.z.literal("content_block_stop"),index:T.z.number()}),T.z.object({type:T.z.literal("error"),error:T.z.object({type:T.z.string(),message:T.z.string()})}),T.z.object({type:T.z.literal("message_delta"),delta:T.z.object({stop_reason:T.z.string().nullish()}),usage:T.z.object({output_tokens:T.z.number()})}),T.z.object({type:T.z.literal("message_stop")}),T.z.object({type:T.z.literal("ping")})]),mc=T.z.object({thinking:T.z.object({type:T.z.union([T.z.literal("enabled"),T.z.literal("disabled")]),budgetTokens:T.z.number().optional()}).optional()}),$=J("zod"),fc=$.z.object({command:$.z.string(),restart:$.z.boolean().optional()});function hc(r={}){return {type:"provider-defined",id:"anthropic.bash_20241022",args:{},parameters:fc,execute:r.execute,experimental_toToolResultContent:r.experimental_toToolResultContent}}var yc=$.z.object({command:$.z.string(),restart:$.z.boolean().optional()});function vc(r={}){return {type:"provider-defined",id:"anthropic.bash_20250124",args:{},parameters:yc,execute:r.execute,experimental_toToolResultContent:r.experimental_toToolResultContent}}var _c=$.z.object({command:$.z.enum(["view","create","str_replace","insert","undo_edit"]),path:$.z.string(),file_text:$.z.string().optional(),insert_line:$.z.number().int().optional(),new_str:$.z.string().optional(),old_str:$.z.string().optional(),view_range:$.z.array($.z.number().int()).optional()});function wc(r={}){return {type:"provider-defined",id:"anthropic.text_editor_20241022",args:{},parameters:_c,execute:r.execute,experimental_toToolResultContent:r.experimental_toToolResultContent}}var bc=$.z.object({command:$.z.enum(["view","create","str_replace","insert","undo_edit"]),path:$.z.string(),file_text:$.z.string().optional(),insert_line:$.z.number().int().optional(),new_str:$.z.string().optional(),old_str:$.z.string().optional(),view_range:$.z.array($.z.number().int()).optional()});function xc(r={}){return {type:"provider-defined",id:"anthropic.text_editor_20250124",args:{},parameters:bc,execute:r.execute,experimental_toToolResultContent:r.experimental_toToolResultContent}}var kc=$.z.object({action:$.z.enum(["key","type","mouse_move","left_click","left_click_drag","right_click","middle_click","double_click","screenshot","cursor_position"]),coordinate:$.z.array($.z.number().int()).optional(),text:$.z.string().optional()});function Rc(r){return {type:"provider-defined",id:"anthropic.computer_20241022",args:{displayWidthPx:r.displayWidthPx,displayHeightPx:r.displayHeightPx,displayNumber:r.displayNumber},parameters:kc,execute:r.execute,experimental_toToolResultContent:r.experimental_toToolResultContent}}var Cc=$.z.object({action:$.z.enum(["key","hold_key","type","cursor_position","mouse_move","left_mouse_down","left_mouse_up","left_click","left_click_drag","right_click","middle_click","double_click","triple_click","scroll","wait","screenshot"]),coordinate:$.z.tuple([$.z.number().int(),$.z.number().int()]).optional(),duration:$.z.number().optional(),scroll_amount:$.z.number().optional(),scroll_direction:$.z.enum(["up","down","left","right"]).optional(),start_coordinate:$.z.tuple([$.z.number().int(),$.z.number().int()]).optional(),text:$.z.string().optional()});function Tc(r){return {type:"provider-defined",id:"anthropic.computer_20250124",args:{displayWidthPx:r.displayWidthPx,displayHeightPx:r.displayHeightPx,displayNumber:r.displayNumber},parameters:Cc,execute:r.execute,experimental_toToolResultContent:r.experimental_toToolResultContent}}var Pc={bash_20241022:hc,bash_20250124:vc,textEditor_20241022:wc,textEditor_20250124:xc,computer_20241022:Rc,computer_20250124:Tc};function zs(r={}){var e;let t=(e=(0, Ps.withoutTrailingSlash)(r.baseURL))!=null?e:"https://api.anthropic.com/v1",n=()=>({"anthropic-version":"2023-06-01","x-api-key":(0, Ps.loadApiKey)({apiKey:r.apiKey,environmentVariableName:"ANTHROPIC_API_KEY",description:"Anthropic"}),...r.headers}),o=(i,a={})=>new cc(i,a,{provider:"anthropic.messages",baseURL:t,headers:n,fetch:r.fetch,supportsImageUrls:true}),s=function(i,a){if(new.target)throw new Error("The Anthropic model function cannot be called with the new keyword.");return o(i,a)};return s.languageModel=o,s.chat=o,s.messages=o,s.textEmbeddingModel=i=>{throw new nc.NoSuchModelError({modelId:i,modelType:"textEmbeddingModel"})},s.tools=Pc,s}var Ac=zs();});var Gs=$e((By,Ks)=>{g();var dn=Object.defineProperty,Ec=Object.getOwnPropertyDescriptor,Sc=Object.getOwnPropertyNames,Ic=Object.prototype.hasOwnProperty,Oc=(r,e)=>{for(var t in e)dn(r,t,{get:e[t],enumerable:true});},zc=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Sc(e))!Ic.call(r,o)&&o!==t&&dn(r,o,{get:()=>e[o],enumerable:!(n=Ec(e,o))||n.enumerable});return r},Mc=r=>zc(dn({},"__esModule",{value:true}),r),Us={};Oc(Us,{createGoogleGenerativeAI:()=>Vs,google:()=>Yc});Ks.exports=Mc(Us);var an=Z(),Oe=Z(),E=J("zod");function ce(r){if(jc(r))return;if(typeof r=="boolean")return {type:"boolean",properties:{}};let{type:e,description:t,required:n,properties:o,items:s,allOf:i,anyOf:a,oneOf:l,format:u,const:d,minLength:c,enum:p}=r,f={};if(t&&(f.description=t),n&&(f.required=n),u&&(f.format=u),d!==void 0&&(f.enum=[d]),e&&(Array.isArray(e)?e.includes("null")?(f.type=e.filter(v=>v!=="null")[0],f.nullable=true):f.type=e:e==="null"?f.type="null":f.type=e),p!==void 0&&(f.enum=p),o!=null&&(f.properties=Object.entries(o).reduce((v,[h,m])=>(v[h]=ce(m),v),{})),s&&(f.items=Array.isArray(s)?s.map(ce):ce(s)),i&&(f.allOf=i.map(ce)),a)if(a.some(v=>typeof v=="object"&&v?.type==="null")){let v=a.filter(h=>!(typeof h=="object"&&h?.type==="null"));if(v.length===1){let h=ce(v[0]);typeof h=="object"&&(f.nullable=true,Object.assign(f,h));}else f.anyOf=v.map(ce),f.nullable=true;}else f.anyOf=a.map(ce);return l&&(f.oneOf=l.map(ce)),c!==void 0&&(f.minLength=c),f}function jc(r){return r!=null&&typeof r=="object"&&r.type==="object"&&(r.properties==null||Object.keys(r.properties).length===0)&&!r.additionalProperties}var ln=W(),Nc=Z();function Dc(r){var e,t;let n=[],o=[],s=true;for(let{role:i,content:a}of r)switch(i){case "system":{if(!s)throw new ln.UnsupportedFunctionalityError({functionality:"system messages are only supported at the beginning of the conversation"});n.push({text:a});break}case "user":{s=false;let l=[];for(let u of a)switch(u.type){case "text":{l.push({text:u.text});break}case "image":{l.push(u.image instanceof URL?{fileData:{mimeType:(e=u.mimeType)!=null?e:"image/jpeg",fileUri:u.image.toString()}}:{inlineData:{mimeType:(t=u.mimeType)!=null?t:"image/jpeg",data:(0, Nc.convertUint8ArrayToBase64)(u.image)}});break}case "file":{l.push(u.data instanceof URL?{fileData:{mimeType:u.mimeType,fileUri:u.data.toString()}}:{inlineData:{mimeType:u.mimeType,data:u.data}});break}}o.push({role:"user",parts:l});break}case "assistant":{s=false,o.push({role:"model",parts:a.map(l=>{switch(l.type){case "text":return l.text.length===0?void 0:{text:l.text};case "file":{if(l.mimeType!=="image/png")throw new ln.UnsupportedFunctionalityError({functionality:"Only PNG images are supported in assistant messages"});if(l.data instanceof URL)throw new ln.UnsupportedFunctionalityError({functionality:"File data URLs in assistant messages are not supported"});return {inlineData:{mimeType:l.mimeType,data:l.data}}}case "tool-call":return {functionCall:{name:l.toolName,args:l.args}}}}).filter(l=>l!==void 0)});break}case "tool":{s=false,o.push({role:"user",parts:a.map(l=>({functionResponse:{name:l.toolName,response:{name:l.toolName,content:l.result}}}))});break}}return {systemInstruction:n.length>0?{parts:n}:void 0,contents:o}}function Ns(r){return r.includes("/")?r:`models/${r}`}var $c=Z(),Ct=J("zod"),Hc=Ct.z.object({error:Ct.z.object({code:Ct.z.number().nullable(),message:Ct.z.string(),status:Ct.z.string()})}),un=(0, $c.createJsonErrorResponseHandler)({errorSchema:Hc,errorToMessage:r=>r.error.message}),qc=W();function Lc(r,e,t,n){var o,s;let i=(o=r.tools)!=null&&o.length?r.tools:void 0,a=[],l=n.includes("gemini-2"),u=n.includes("gemini-1.5-flash")&&!n.includes("-8b");if(e)return {tools:l?{googleSearch:{}}:{googleSearchRetrieval:!u||!t?{}:{dynamicRetrievalConfig:t}},toolConfig:void 0,toolWarnings:a};if(i==null)return {tools:void 0,toolConfig:void 0,toolWarnings:a};let d=[];for(let f of i)f.type==="provider-defined"?a.push({type:"unsupported-tool",tool:f}):d.push({name:f.name,description:(s=f.description)!=null?s:"",parameters:ce(f.parameters)});let c=r.toolChoice;if(c==null)return {tools:{functionDeclarations:d},toolConfig:void 0,toolWarnings:a};let p=c.type;switch(p){case "auto":return {tools:{functionDeclarations:d},toolConfig:{functionCallingConfig:{mode:"AUTO"}},toolWarnings:a};case "none":return {tools:{functionDeclarations:d},toolConfig:{functionCallingConfig:{mode:"NONE"}},toolWarnings:a};case "required":return {tools:{functionDeclarations:d},toolConfig:{functionCallingConfig:{mode:"ANY"}},toolWarnings:a};case "tool":return {tools:{functionDeclarations:d},toolConfig:{functionCallingConfig:{mode:"ANY",allowedFunctionNames:[c.toolName]}},toolWarnings:a};default:{let f=p;throw new qc.UnsupportedFunctionalityError({functionality:`Unsupported tool choice type: ${f}`})}}}function Ds({finishReason:r,hasToolCalls:e}){switch(r){case "STOP":return e?"tool-calls":"stop";case "MAX_TOKENS":return "length";case "IMAGE_SAFETY":case "RECITATION":case "SAFETY":case "BLOCKLIST":case "PROHIBITED_CONTENT":case "SPII":return "content-filter";case "FINISH_REASON_UNSPECIFIED":case "OTHER":return "other";case "MALFORMED_FUNCTION_CALL":return "error";default:return "unknown"}}var Fc=class{constructor(r,e,t){this.specificationVersion="v1",this.defaultObjectGenerationMode="json",this.supportsImageUrls=false,this.modelId=r,this.settings=e,this.config=t;}get supportsStructuredOutputs(){var r;return (r=this.settings.structuredOutputs)!=null?r:true}get provider(){return this.config.provider}async getArgs({mode:r,prompt:e,maxTokens:t,temperature:n,topP:o,topK:s,frequencyPenalty:i,presencePenalty:a,stopSequences:l,responseFormat:u,seed:d,providerMetadata:c}){var p,f,v;let h=r.type,m=[],y=(0, Oe.parseProviderOptions)({provider:"google",providerOptions:c,schema:Jc});((p=y?.thinkingConfig)==null?void 0:p.includeThoughts)===true&&!this.config.provider.startsWith("google.vertex.")&&m.push({type:"other",message:`The 'includeThoughts' option is only supported with the Google Vertex provider and might not be supported or could behave unexpectedly with the current Google provider (${this.config.provider}).`});let w={maxOutputTokens:t,temperature:n,topK:s,topP:o,frequencyPenalty:i,presencePenalty:a,stopSequences:l,seed:d,responseMimeType:u?.type==="json"?"application/json":void 0,responseSchema:u?.type==="json"&&u.schema!=null&&this.supportsStructuredOutputs?ce(u.schema):void 0,...this.settings.audioTimestamp&&{audioTimestamp:this.settings.audioTimestamp},responseModalities:y?.responseModalities,thinkingConfig:y?.thinkingConfig},{contents:C,systemInstruction:_}=Dc(e);switch(h){case "regular":{let{tools:k,toolConfig:S,toolWarnings:z}=Lc(r,(f=this.settings.useSearchGrounding)!=null?f:false,this.settings.dynamicRetrievalConfig,this.modelId);return {args:{generationConfig:w,contents:C,systemInstruction:_,safetySettings:this.settings.safetySettings,tools:k,toolConfig:S,cachedContent:this.settings.cachedContent},warnings:[...m,...z]}}case "object-json":return {args:{generationConfig:{...w,responseMimeType:"application/json",responseSchema:r.schema!=null&&this.supportsStructuredOutputs?ce(r.schema):void 0},contents:C,systemInstruction:_,safetySettings:this.settings.safetySettings,cachedContent:this.settings.cachedContent},warnings:m};case "object-tool":return {args:{generationConfig:w,contents:C,systemInstruction:_,tools:{functionDeclarations:[{name:r.tool.name,description:(v=r.tool.description)!=null?v:"",parameters:ce(r.tool.parameters)}]},toolConfig:{functionCallingConfig:{mode:"ANY"}},safetySettings:this.settings.safetySettings,cachedContent:this.settings.cachedContent},warnings:m};default:{let k=h;throw new Error(`Unsupported type: ${k}`)}}}supportsUrl(r){return this.config.isSupportedUrl(r)}async doGenerate(r){var e,t,n,o,s;let{args:i,warnings:a}=await this.getArgs(r),l=JSON.stringify(i),u=(0, Oe.combineHeaders)(await(0, Oe.resolve)(this.config.headers),r.headers),{responseHeaders:d,value:c,rawValue:p}=await(0, Oe.postJsonToApi)({url:`${this.config.baseURL}/${Ns(this.modelId)}:generateContent`,headers:u,body:i,failedResponseHandler:un,successfulResponseHandler:(0, Oe.createJsonResponseHandler)(Bc),abortSignal:r.abortSignal,fetch:this.config.fetch}),{contents:f,...v}=i,h=c.candidates[0],m=h.content==null||typeof h.content!="object"||!("parts"in h.content)?[]:h.content.parts,y=$s({parts:m,generateId:this.config.generateId}),w=c.usageMetadata;return {text:Hs(m),reasoning:qs(m),files:(e=Ls(m))==null?void 0:e.map(C=>({data:C.inlineData.data,mimeType:C.inlineData.mimeType})),toolCalls:y,finishReason:Ds({finishReason:h.finishReason,hasToolCalls:y!=null&&y.length>0}),usage:{promptTokens:(t=w?.promptTokenCount)!=null?t:NaN,completionTokens:(n=w?.candidatesTokenCount)!=null?n:NaN},rawCall:{rawPrompt:f,rawSettings:v},rawResponse:{headers:d,body:p},warnings:a,providerMetadata:{google:{groundingMetadata:(o=h.groundingMetadata)!=null?o:null,safetyRatings:(s=h.safetyRatings)!=null?s:null}},sources:Fs({groundingMetadata:h.groundingMetadata,generateId:this.config.generateId}),request:{body:l}}}async doStream(r){let{args:e,warnings:t}=await this.getArgs(r),n=JSON.stringify(e),o=(0, Oe.combineHeaders)(await(0, Oe.resolve)(this.config.headers),r.headers),{responseHeaders:s,value:i}=await(0, Oe.postJsonToApi)({url:`${this.config.baseURL}/${Ns(this.modelId)}:streamGenerateContent?alt=sse`,headers:o,body:e,failedResponseHandler:un,successfulResponseHandler:(0, Oe.createEventSourceResponseHandler)(Wc),abortSignal:r.abortSignal,fetch:this.config.fetch}),{contents:a,...l}=e,u="unknown",d={promptTokens:Number.NaN,completionTokens:Number.NaN},c,p=this.config.generateId,f=false;return {stream:i.pipeThrough(new TransformStream({transform(v,h){var m,y,w,C,_,k;if(!v.success){h.enqueue({type:"error",error:v.error});return}let S=v.value,z=S.usageMetadata;z!=null&&(d={promptTokens:(m=z.promptTokenCount)!=null?m:NaN,completionTokens:(y=z.candidatesTokenCount)!=null?y:NaN});let R=(w=S.candidates)==null?void 0:w[0];if(R==null)return;let x=R.content;if(x!=null){let M=Hs(x.parts);M!=null&&h.enqueue({type:"text-delta",textDelta:M});let O=qs(x.parts);if(O!=null)for(let B of O)h.enqueue({type:"reasoning",textDelta:B.text});let Y=Ls(x.parts);if(Y!=null)for(let B of Y)h.enqueue({type:"file",mimeType:B.inlineData.mimeType,data:B.inlineData.data});let re=$s({parts:x.parts,generateId:p});if(re!=null)for(let B of re)h.enqueue({type:"tool-call-delta",toolCallType:"function",toolCallId:B.toolCallId,toolName:B.toolName,argsTextDelta:B.args}),h.enqueue({type:"tool-call",toolCallType:"function",toolCallId:B.toolCallId,toolName:B.toolName,args:B.args}),f=true;}if(R.finishReason!=null){u=Ds({finishReason:R.finishReason,hasToolCalls:f});let M=(C=Fs({groundingMetadata:R.groundingMetadata,generateId:p}))!=null?C:[];for(let O of M)h.enqueue({type:"source",source:O});c={google:{groundingMetadata:(_=R.groundingMetadata)!=null?_:null,safetyRatings:(k=R.safetyRatings)!=null?k:null}};}},flush(v){v.enqueue({type:"finish",finishReason:u,usage:d,providerMetadata:c});}})),rawCall:{rawPrompt:a,rawSettings:l},rawResponse:{headers:s},warnings:t,request:{body:n}}}};function $s({parts:r,generateId:e}){let t=r?.filter(n=>"functionCall"in n);return t==null||t.length===0?void 0:t.map(n=>({toolCallType:"function",toolCallId:e(),toolName:n.functionCall.name,args:JSON.stringify(n.functionCall.args)}))}function Hs(r){let e=r?.filter(t=>"text"in t&&t.thought!==true);return e==null||e.length===0?void 0:e.map(t=>t.text).join("")}function qs(r){let e=r?.filter(t=>"text"in t&&t.thought===true&&t.text!=null);return e==null||e.length===0?void 0:e.map(t=>({type:"text",text:t.text}))}function Ls(r){return r?.filter(e=>"inlineData"in e)}function Fs({groundingMetadata:r,generateId:e}){var t;return (t=r?.groundingChunks)==null?void 0:t.filter(n=>n.web!=null).map(n=>({sourceType:"url",id:e(),url:n.web.uri,title:n.web.title}))}var Bs=E.z.object({parts:E.z.array(E.z.union([E.z.object({functionCall:E.z.object({name:E.z.string(),args:E.z.unknown()})}),E.z.object({inlineData:E.z.object({mimeType:E.z.string(),data:E.z.string()})}),E.z.object({text:E.z.string().nullish(),thought:E.z.boolean().nullish()})])).nullish()}),Uc=E.z.object({web:E.z.object({uri:E.z.string(),title:E.z.string()}).nullish(),retrievedContext:E.z.object({uri:E.z.string(),title:E.z.string()}).nullish()}),Ws=E.z.object({webSearchQueries:E.z.array(E.z.string()).nullish(),retrievalQueries:E.z.array(E.z.string()).nullish(),searchEntryPoint:E.z.object({renderedContent:E.z.string()}).nullish(),groundingChunks:E.z.array(Uc).nullish(),groundingSupports:E.z.array(E.z.object({segment:E.z.object({startIndex:E.z.number().nullish(),endIndex:E.z.number().nullish(),text:E.z.string().nullish()}),segment_text:E.z.string().nullish(),groundingChunkIndices:E.z.array(E.z.number()).nullish(),supportChunkIndices:E.z.array(E.z.number()).nullish(),confidenceScores:E.z.array(E.z.number()).nullish(),confidenceScore:E.z.array(E.z.number()).nullish()})).nullish(),retrievalMetadata:E.z.union([E.z.object({webDynamicRetrievalScore:E.z.number()}),E.z.object({})]).nullish()}),Js=E.z.object({category:E.z.string().nullish(),probability:E.z.string().nullish(),probabilityScore:E.z.number().nullish(),severity:E.z.string().nullish(),severityScore:E.z.number().nullish(),blocked:E.z.boolean().nullish()}),Bc=E.z.object({candidates:E.z.array(E.z.object({content:Bs.nullish().or(E.z.object({}).strict()),finishReason:E.z.string().nullish(),safetyRatings:E.z.array(Js).nullish(),groundingMetadata:Ws.nullish()})),usageMetadata:E.z.object({promptTokenCount:E.z.number().nullish(),candidatesTokenCount:E.z.number().nullish(),totalTokenCount:E.z.number().nullish()}).nullish()}),Wc=E.z.object({candidates:E.z.array(E.z.object({content:Bs.nullish(),finishReason:E.z.string().nullish(),safetyRatings:E.z.array(Js).nullish(),groundingMetadata:Ws.nullish()})).nullish(),usageMetadata:E.z.object({promptTokenCount:E.z.number().nullish(),candidatesTokenCount:E.z.number().nullish(),totalTokenCount:E.z.number().nullish()}).nullish()}),Jc=E.z.object({responseModalities:E.z.array(E.z.enum(["TEXT","IMAGE"])).nullish(),thinkingConfig:E.z.object({thinkingBudget:E.z.number().nullish(),includeThoughts:E.z.boolean().nullish()}).nullish()}),Vc=W(),pr=Z(),Tt=J("zod"),Kc=class{constructor(r,e,t){this.specificationVersion="v1",this.modelId=r,this.settings=e,this.config=t;}get provider(){return this.config.provider}get maxEmbeddingsPerCall(){return 2048}get supportsParallelCalls(){return true}async doEmbed({values:r,headers:e,abortSignal:t}){if(r.length>this.maxEmbeddingsPerCall)throw new Vc.TooManyEmbeddingValuesForCallError({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:r});let n=(0, pr.combineHeaders)(await(0, pr.resolve)(this.config.headers),e),{responseHeaders:o,value:s}=await(0, pr.postJsonToApi)({url:`${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`,headers:n,body:{requests:r.map(i=>({model:`models/${this.modelId}`,content:{role:"user",parts:[{text:i}]},outputDimensionality:this.settings.outputDimensionality,taskType:this.settings.taskType}))},failedResponseHandler:un,successfulResponseHandler:(0, pr.createJsonResponseHandler)(Gc),abortSignal:t,fetch:this.config.fetch});return {embeddings:s.embeddings.map(i=>i.values),usage:void 0,rawResponse:{headers:o}}}},Gc=Tt.z.object({embeddings:Tt.z.array(Tt.z.object({values:Tt.z.array(Tt.z.number())}))});function Xc(r){return r.toString().startsWith("https://generativelanguage.googleapis.com/v1beta/files/")}function Vs(r={}){var e;let t=(e=(0, an.withoutTrailingSlash)(r.baseURL))!=null?e:"https://generativelanguage.googleapis.com/v1beta",n=()=>({"x-goog-api-key":(0, an.loadApiKey)({apiKey:r.apiKey,environmentVariableName:"GOOGLE_GENERATIVE_AI_API_KEY",description:"Google Generative AI"}),...r.headers}),o=(a,l={})=>{var u;return new Fc(a,l,{provider:"google.generative-ai",baseURL:t,headers:n,generateId:(u=r.generateId)!=null?u:an.generateId,isSupportedUrl:Xc,fetch:r.fetch})},s=(a,l={})=>new Kc(a,l,{provider:"google.generative-ai",baseURL:t,headers:n,fetch:r.fetch}),i=function(a,l){if(new.target)throw new Error("The Google Generative AI model function cannot be called with the new keyword.");return o(a,l)};return i.languageModel=o,i.chat=o,i.generativeAI=o,i.embedding=s,i.textEmbedding=s,i.textEmbeddingModel=s,i}var Yc=Vs();});var Xs,Ys,Pt,cn=ee(()=>{g();Fe();Xs=10,Ys=50,Pt=class{config;constructor(e){this.config=e;}async query(e,t){return this._run(e,"query",t)}async execute(e,t){return this._run(e,"execute",t)}async _run(e,t,n){let{generateText:o,tool:s}=await import('ai'),i=this.convertTools(n?.tools??[],s),a=this.createModel(n?.model),l=Math.min(n?.maxSteps??this.config.maxSteps??Xs,Ys);try{let u=0,d=await o({model:a,system:n?.systemPrompt??void 0,prompt:e,tools:i,maxSteps:l,...this.config.temperature!==void 0&&{temperature:this.config.temperature},...this.config.maxTokens!==void 0&&{maxTokens:this.config.maxTokens},onStepFinish:p=>{if(u++,!!n?.onOutput){if(p.toolCalls&&p.toolCalls.length>0)for(let f of p.toolCalls)n.onOutput(JSON.stringify({type:"assistant",message:{content:[{type:"tool_use",id:f.toolCallId,name:f.toolName,input:f.args}]}}),"stdout");if(p.toolResults&&p.toolResults.length>0)for(let f of p.toolResults){let v=typeof f.result=="string"?f.result:JSON.stringify(f.result);n.onOutput(JSON.stringify({type:"user",message:{content:[{type:"tool_result",tool_use_id:f.toolCallId,output:v,is_error:!1}]}}),"stdout");}}}}),c=new Set((n?.tools??[]).filter(p=>!p.execute).map(p=>p.name));if(d.finishReason==="tool-calls"&&Array.isArray(d.toolCalls)&&d.toolCalls.length>0){let p=d.toolCalls.filter(f=>c.has(f.toolName));if(p.length>0){let f=p[0];throw new he({toolCallId:f.toolCallId,toolName:f.toolName,args:f.args},{userMessage:e,responseMessages:d.response?.messages??[],toolDefinitions:n?.tools??[],maxSteps:l,systemPrompt:n?.systemPrompt,modelOverride:n?.model})}}if(n?.onUsage&&d.usage){let p={inputTokens:d.usage.promptTokens??0,outputTokens:d.usage.completionTokens??0,cachedInputTokens:0,costUsd:0};n.onUsage(p);}return n?.onModel&&n.onModel(n.model??this.config.model),d.text??""}catch(u){throw u instanceof he?u:u.status===401?new X(`Authentication failed for ${this.config.provider}. Check your API key.`,this.config.provider):u.status===429?new X(`Rate limit exceeded for ${this.config.provider}.`,this.config.provider):new X(`Provider error: ${u.message}`,this.config.provider)}}async continueWithToolResults(e,t,n){let{generateText:o,tool:s}=await import('ai'),i=this.convertTools(e.toolDefinitions,s),a=this.createModel(e.modelOverride),l=Math.min(e.maxSteps??this.config.maxSteps??Xs,Ys),u=[{role:"user",content:e.userMessage},...e.responseMessages,{role:"tool",content:t.map(d=>({type:"tool-result",toolCallId:d.toolCallId,toolName:d.toolName,result:typeof d.result=="string"?d.result:JSON.stringify(d.result)}))}];try{let d=await o({model:a,system:e.systemPrompt??void 0,messages:u,tools:i,maxSteps:l,...this.config.temperature!==void 0&&{temperature:this.config.temperature},...this.config.maxTokens!==void 0&&{maxTokens:this.config.maxTokens}}),c=new Set(e.toolDefinitions.filter(p=>!p.execute).map(p=>p.name));if(d.finishReason==="tool-calls"&&Array.isArray(d.toolCalls)&&d.toolCalls.length>0){let p=d.toolCalls.filter(f=>c.has(f.toolName));if(p.length>0){let f=p[0];throw new he({toolCallId:f.toolCallId,toolName:f.toolName,args:f.args},{userMessage:e.userMessage,responseMessages:[...e.responseMessages,{role:"tool",content:t.map(v=>({type:"tool-result",toolCallId:v.toolCallId,toolName:v.toolName,result:typeof v.result=="string"?v.result:JSON.stringify(v.result)}))},...d.response?.messages??[]],toolDefinitions:e.toolDefinitions,maxSteps:e.maxSteps,systemPrompt:e.systemPrompt,modelOverride:e.modelOverride})}}return n?.onUsage&&d.usage&&n.onUsage({inputTokens:d.usage.promptTokens??0,outputTokens:d.usage.completionTokens??0,cachedInputTokens:0,costUsd:0}),n?.onModel&&n.onModel(e.modelOverride??this.config.model),d.text??""}catch(d){throw d instanceof he?d:new X(`Provider error: ${d.message}`,this.config.provider)}}convertTools(e,t){let{z:n}=J("zod"),o={};for(let s of e){let i=this.jsonSchemaToZod(s.parameters??{},n);s.execute?o[s.name]=t({description:s.description,parameters:i,execute:async a=>s.execute(a)}):o[s.name]=t({description:s.description,parameters:i});}return o}jsonSchemaToZod(e,t){if(!e||!e.properties)return t.object({});let n={},o=e.properties,s=e.required??[];for(let[i,a]of Object.entries(o)){let l;switch(a.type){case "string":l=t.string();break;case "number":l=t.number();break;case "integer":l=t.number().int();break;case "boolean":l=t.boolean();break;case "array":l=t.array(t.any());break;default:l=t.any();}a.description&&(l=l.describe(a.description)),s.includes(i)||(l=l.optional()),n[i]=l;}return t.object(n)}createModel(e){let{provider:t,apiKey:n,baseURL:o}=this.config,s=e||this.config.model;switch(t){case "api/openrouter":{let{createOpenAI:i}=on();return i({apiKey:n||process.env.OPENROUTER_API_KEY,baseURL:o||"https://openrouter.ai/api/v1"})(s)}case "api/openai":{let{createOpenAI:i}=on();return i({apiKey:n||process.env.OPENAI_API_KEY,...o&&{baseURL:o}})(s)}case "api/anthropic":{let{createAnthropic:i}=js();return i({apiKey:n||process.env.ANTHROPIC_API_KEY,...o&&{baseURL:o}})(s)}case "api/google":{let{createGoogleGenerativeAI:i}=Gs();return i({apiKey:n||process.env.GOOGLE_API_KEY})(s)}default:throw new X(`Unsupported API provider: ${t}`,t)}}};});var Zs={};hr(Zs,{registerApiProviders:()=>Qs});function Qs(r){tt("api",(e,t)=>{let n=r?.apiKeys?.[e];return new Pt({provider:t,model:"",apiKey:n,maxSteps:r?.defaults?.maxSteps,temperature:r?.defaults?.temperature})});}var pn=ee(()=>{g();Fe();cn();});function Qc(r){if(!r)return r;let e=r.trim().replace(/\/+$/,"");return e.toLowerCase().endsWith("/mcp")?e.slice(0,-4):e}var At,gn=ee(()=>{g();At=class{endpoint;headers;timeoutMs;constructor(e){let t=Qc(e.url);this.endpoint=`${t}/mcp`,this.headers={"Content-Type":"application/json",...e.headers??{}},e.apiKey&&(this.headers.Authorization=`Bearer ${e.apiKey}`),this.timeoutMs=e.timeoutMs??3e4;}async send(e){let t=new AbortController,n=setTimeout(()=>t.abort(),this.timeoutMs);try{let o=await fetch(this.endpoint,{method:"POST",headers:this.headers,body:JSON.stringify(e),signal:t.signal});if(clearTimeout(n),!o.ok){let a=await o.text();throw new Error(`HTTP ${o.status}: ${o.statusText}${a?` - ${a}`:""}`)}let s=o.headers.get("content-type");if(s?.includes("application/json"))return await o.json();let i=await o.text();return {jsonrpc:"2.0",id:e.id,error:{code:-32600,message:`Unexpected response content-type: ${s}`,data:i}}}catch(o){throw clearTimeout(n),o instanceof Error&&o.name==="AbortError"?new Error(`MCP-HTTP request timeout after ${this.timeoutMs}ms to ${this.endpoint}`):o}}async close(){}};});var Et,mn=ee(()=>{g();gn();Et=class{logger;configs=new Map;transports=new Map;constructor(e={}){this.logger=e.logger??(()=>{});}loadConfig(e,t){this.validateConfig(t),this.configs.set(e,t),this.transports.set(e,new At({url:t.url,apiKey:t.apiKey,headers:t.headers,timeoutMs:t.timeoutMs})),this.logger(`Loaded remote agent config for: ${e}`,"debug");}loadConfigWithTransport(e,t,n){this.validateConfig(t),this.configs.set(e,t),this.transports.set(e,n),this.logger(`Loaded remote agent config for: ${e} (custom transport)`,"debug");}getConfig(e){return this.configs.get(e)}isRemoteAgent(e){return this.configs.has(e)}getRemoteAgentIds(){return Array.from(this.configs.keys())}async query(e,t){let n=this.requireConfig(e),o=n.tools?.query??"crewx_queryAgent",i={agentId:n.agentId??e,query:t.query};t.context&&(i.context=t.context),t.model&&(i.model=t.model),t.platform&&(i.platform=t.platform),t.messages?.length&&(i.messages=t.messages);try{let a=await this.callRemoteTool(e,o,i);return this.normalizeResponse(a)}catch(a){let l=a instanceof Error?a.message:String(a);throw this.logger(`Remote query failed for agent ${e}: ${l}`,"error"),a}}async execute(e,t){let n=this.requireConfig(e),o=n.tools?.execute??"crewx_executeAgent",i={agentId:n.agentId??e,task:t.task};t.context&&(i.context=t.context),t.model&&(i.model=t.model),t.platform&&(i.platform=t.platform),t.messages?.length&&(i.messages=t.messages);try{let a=await this.callRemoteTool(e,o,i);return this.normalizeResponse(a)}catch(a){let l=a instanceof Error?a.message:String(a);throw this.logger(`Remote execute failed for agent ${e}: ${l}`,"error"),a}}mapToolNames(e,t){let n=this.requireConfig(e);n.tools={query:t.query??n.tools?.query??"crewx_queryAgent",execute:t.execute??n.tools?.execute??"crewx_executeAgent"},this.logger(`Updated tool name mapping for agent ${e}`,"debug");}async clearConfigs(){for(let e of this.transports.values())await e.close();this.configs.clear(),this.transports.clear(),this.logger("Cleared all remote agent configurations","debug");}requireConfig(e){let t=this.configs.get(e);if(!t)throw new Error(`Agent ${e} is not configured as a remote agent`);return t}async callRemoteTool(e,t,n){let o=this.transports.get(e);if(!o)throw new Error(`No transport available for agent ${e}`);let s={jsonrpc:"2.0",id:`${t}-${Date.now()}`,method:"tools/call",params:{name:t,arguments:n}};this.logger(`Calling remote MCP tool ${t} for agent ${e}`,"debug");let i=await o.send(s);if(i.error)throw new Error(i.error.message||"MCP server returned an error");return i.result}normalizeResponse(e){if(!e)return {success:false,content:[{type:"text",text:"Remote agent returned no response."}]};let t=e;if(Array.isArray(t.content)&&t.content.length>0)return t;let n=t.response??t.implementation??t.message??t.output,o=typeof n=="string"?n:JSON.stringify(n??e,null,2);return {...t,content:[{type:"text",text:o}]}}validateConfig(e){if(!e.url)throw new Error("Remote agent configuration requires a URL");if(!e.url.startsWith("http://")&&!e.url.startsWith("https://"))throw new Error("Remote agent URL must start with http:// or https://");if(e.type!=="mcp-http")throw new Error(`Unsupported remote agent type: ${e.type}`)}};});var ti={};hr(ti,{RemoteProviderRuntime:()=>St,createRemoteProviderFactory:()=>ei,resolveFileRemoteAgent:()=>ip});function op(r){let e=readFileSync(r,"utf-8"),t=load(e);return {agents:Array.isArray(t?.agents)?t.agents:void 0}}function sp(r){let e=Array.isArray(r.provider)?r.provider[0]:r.provider;return e||(Array.isArray(r.inline?.provider)?r.inline.provider[0]:r.inline?.provider)}function ip(r,e=op,t=existsSync){let n=r.location.replace("file://","");if(!t(n))throw new Error(`Remote config file not found: ${n}`);if(!r.external_agent_id)throw new Error(`external_agent_id is required for file:// remote provider "${r.id}"`);let s=e(n).agents?.find(l=>l.id===r.external_agent_id);if(!s)throw new Error(`Agent "${r.external_agent_id}" not found in ${n}`);let i=sp(s);if(!i)throw new Error(`Agent "${r.external_agent_id}" in ${n} has no provider configured`);if(i.startsWith("remote/"))throw new Error(`Chained remotes not allowed: ${r.id} \u2192 ${i}`);let a=resolve(dirname(n),s.working_directory??".");return {agent:{...s,working_directory:a},provider:i}}function ei(r,e=Ce){return (t,n)=>{let o=r.get(t);if(!o)throw new Error(`Remote provider "${t}" not found. Available: ${Array.from(r.keys()).join(", ")||"(none)"}`);if(o.location.startsWith("file://"))throw new Error(`Remote provider "${t}" uses file:// location which is not supported at the SDK level. Use the CLI commands (crewx query / crewx execute) which handle file:// remotes automatically.`);return new St(t,o,e)}}function ap(r,e){let t=e.location;if(!t)throw new Error("Remote provider config requires a location");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Unsupported remote location protocol for MCP-HTTP: ${t}`);return {type:"mcp-http",url:t,apiKey:e.apiKey,headers:e.headers,timeoutMs:e.timeout?.query??3e4,agentId:e.external_agent_id??r}}var St,fn=ee(()=>{g();Fe();mn();St=class{manager;agentId;constructor(e,t,n=Ce){this.agentId=t.external_agent_id??e,this.manager=new Et;let o=ap(e,t);this.manager.loadConfig(this.agentId,o);}async query(e,t){return (await this.manager.query(this.agentId,{agentId:this.agentId,query:e,model:t?.model,context:t?.context??t?.systemPrompt})).content.map(o=>o.text).join(`
46
- `)}async execute(e,t){return (await this.manager.execute(this.agentId,{agentId:this.agentId,task:e,model:t?.model,context:t?.context??t?.systemPrompt})).content.map(o=>o.text).join(`
47
- `)}};});var si={};hr(si,{PluginProviderRuntime:()=>It,createPluginProviderFactory:()=>oi});function oi(r){return (e,t)=>{let n=r.get(e);if(!n)throw new X(`Plugin provider "${e}" not found. Available: ${Array.from(r.keys()).join(", ")||"(none)"}`,`plugin/${e}`);return new It(e,n)}}function ri(r,e,t,n){let o=r.map(s=>s.replace(/\{model\}/g,e));return n&&o.push(t),o}function up(r){if(!r||typeof r!="string")throw new Error("Plugin provider requires a cli_command")}function ni(r){if(!Array.isArray(r))throw new Error("CLI arguments must be an array");for(let e of r)if(typeof e!="string")throw new Error("Each CLI argument must be a string")}function dp(r){for(let{pattern:e}of r)if(typeof e!="string")throw new Error("Error pattern must be a string")}function cp(r){for(let[e,t]of Object.entries(r))if(typeof e!="string"||typeof t!="string")throw new Error("env entries must be string key/value pairs")}var It,hn=ee(()=>{g();Fe();Lt();It=class{constructor(e,t){this.config=t;this.providerStr=`plugin/${e}`,up(t.cli_command),ni(t.query_args),ni(t.execute_args),t.error_patterns&&dp(t.error_patterns),t.env&&cp(t.env);}config;providerStr;async query(e,t){let n=t?.model??this.config.default_model??"default",o=ri(this.config.query_args,n,e,this.config.prompt_in_args),s=this.config.prompt_in_args?void 0:e;t?.onCommand?.(`${this.config.cli_command} ${o.join(" ")}`);let i=this.config.timeout?.query??6e5;return this.runProcess(o,t,s,i)}async execute(e,t){let n=t?.model??this.config.default_model??"default",o=ri(this.config.execute_args,n,e,this.config.prompt_in_args),s=this.config.prompt_in_args?void 0:e;t?.onCommand?.(`${this.config.cli_command} ${o.join(" ")}`);let i=this.config.timeout?.execute??6e5;return this.runProcess(o,t,s,i)}runProcess(e,t,n,o){return new Promise((s,i)=>{let a={...process.env,...this.config.env??{}},l=at({command:this.config.cli_command,allowShellFallback:true}),u=lt(l,e),d=spawn(u.command,u.argv,{env:a,shell:u.shell??false,stdio:["pipe","pipe","pipe"],windowsHide:u.windowsHide});n!==void 0&&d.stdin.write(n),d.stdin.end(),d.pid!==void 0&&t?.onPid?.(d.pid);let c="",p="",f="",v="";d.stdout.on("data",m=>{let y=m.toString();c+=y,f+=y;let w=f.split(`
48
- `);f=w.pop()??"";for(let C of w)C.trim()&&t?.onOutput?.(C,"stdout");}),d.stderr.on("data",m=>{let y=m.toString();p+=y,v+=y;let w=v.split(`
49
- `);v=w.pop()??"";for(let C of w)C.trim()&&t?.onOutput?.(C,"stderr");});let h=setTimeout(()=>{d.kill("SIGTERM"),i(new X(`Plugin provider "${this.providerStr}" timed out after ${o}ms`,this.providerStr));},o);d.on("error",m=>{if(clearTimeout(h),m.code==="ENOENT"){let y=this.config.not_installed_message??`CLI command "${this.config.cli_command}" not found. Is ${this.config.id} installed?`;i(new X(y,this.providerStr));}else i(new X(`Spawn error: ${m.message}`,this.providerStr));}),d.on("close",m=>{clearTimeout(h),f.trim()&&t?.onOutput?.(f,"stdout"),v.trim()&&t?.onOutput?.(v,"stderr");let y=m??0;if(t?.onExitCode?.(y),this.config.error_patterns){let w=p||c;for(let C of this.config.error_patterns)if(w.includes(C.pattern)){i(new X(C.message,this.providerStr));return}}if(m!==0){i(new X(`Process exited with code ${m}: ${p.slice(0,500)}`,this.providerStr));return}s(c.trim());});})}};});g();g();g();function Ii(r){let e=o=>o.replace(/[.+^${}()|[\]\\]/g,"\\$&"),n=r.split("/").map(o=>o==="**"?".*":o.split("*").map(e).join("[^/]*"));return new RegExp(`^${n.join("\\/")}$`)}function ve(r,e){try{return Ii(e).test(r)}catch{return false}}g();g();var Oi=z.object({model:z.string().optional(),system_prompt:z.string().optional(),prompt:z.string().optional(),layout:z.union([z.string(),z.object({id:z.string(),props:z.record(z.unknown()).optional()}),z.object({props:z.record(z.unknown())}),z.object({template:z.string()})]).optional()}).catchall(z.unknown()),En=z.object({include:z.array(z.string()).optional()}).optional(),zi=z.object({id:z.string(),name:z.string().optional(),role:z.string().optional(),team:z.string().optional(),provider:z.union([z.string(),z.array(z.string())]),working_directory:z.string().optional(),description:z.string().optional(),tags:z.array(z.string()).optional(),inline:Oi.optional(),skills:En}).catchall(z.unknown()),Sn=z.object({agents:z.array(zi).optional(),hooks:z.array(z.unknown()).optional(),settings:z.record(z.unknown()).optional(),skills:z.unknown().optional(),layouts:z.record(z.unknown()).optional(),documents:z.record(z.unknown()).optional()}).catchall(z.unknown());var He=class extends Error{constructor(t,n){super(t);this.cause=n;this.name="ConfigLoadError";}cause};function jt(r){if(!r||typeof r!="string"||!r.trim())throw new He("YAML content must be a non-empty string");let e;try{e=load(r);}catch(o){throw new He(`YAML parse error: ${o.message}`,o)}let t=Ni(e),n=Sn.safeParse(t);if(!n.success)throw new He(`Config validation error: ${n.error.message}`);return n.data}function Nt(r){let e;try{e=readFileSync(r,"utf-8");}catch(t){throw new He(`Cannot read file: ${r}`,t)}return jt(e)}function Ni(r){if(!r||typeof r!="object")return {agents:[]};let e=r,t;if(e.agents&&typeof e.agents=="object"&&!Array.isArray(e.agents)){let o=e.agents;t=Object.entries(o).map(([s,i])=>({id:s,...i&&typeof i=="object"?i:{}}));}else if(Array.isArray(e.agents))t=e.agents;else return {...e,agents:[]};let n=t.map(o=>{if(o.provider===void 0&&o.inline&&typeof o.inline=="object"){let s=o.inline;if(s.provider!==void 0)return {...o,provider:s.provider}}return o});return {...e,agents:n}}g();var qe=join("templates","agents");function Hi(){try{let e=(typeof J=="function"?J:createRequire(typeof A<"u"?A:process.cwd()+"/")).resolve("@crewx/sdk/package.json");return dirname(e)}catch{return null}}function Qe(r){if(r&&existsSync(r))return r;let e=process.env.CREWX_SDK_TEMPLATES_PATH;if(e&&existsSync(e))return e;let t=Hi();if(t){let o=join(t,qe);if(existsSync(o))return o}let n=[join(P,"..",qe),join(P,"..","..",qe),join(P,"..","..","..",qe),join(process.cwd(),"packages","sdk",qe),join(process.cwd(),qe)];for(let o of n)if(existsSync(o))return o;throw new Error(`[@crewx/sdk] Templates directory not found.
50
- `+(t?` package anchor: ${join(t,qe)}
31
+ `)}]}handleUpdate(e,t,r){let n=e.update;if(n.sessionUpdate==="agent_message_chunk"){let s=null;this.adapter.extractTextFromUpdate?s=this.adapter.extractTextFromUpdate(e):s=gr(e),s!==null&&(r.push(s),t?.onOutput?.(s,"stdout"));}else if(n.sessionUpdate==="tool_call"){let s=new Date().toISOString(),i=n,a={title:i.title??"",kind:i.kind,rawInput:i.rawInput,rawOutput:i.rawOutput,locations:i.locations,_meta:i._meta},d=this.resolveToolCall(a),c={timestamp:s,type:"tool_use",toolUseId:i.toolCallId,toolName:d.toolName,toolInput:d.toolInput};t?.onTaskLog?.([c]);}else if(n.sessionUpdate==="tool_call_update"){let s=new Date().toISOString(),i=n;if(i.status==="completed"||i.status==="failed"){let d=this.extractResultPreview(i.rawOutput),c={timestamp:s,type:"tool_result",toolUseId:i.toolCallId,resultPreview:d,isError:i.status==="failed"};t?.onTaskLog?.([c]);}else if(i.rawInput!=null&&typeof i.rawInput=="object"&&Object.keys(i.rawInput).length>0){let d={title:i.title??"",kind:i.kind,rawInput:i.rawInput,rawOutput:i.rawOutput,locations:i.locations,_meta:i._meta},c=this.resolveToolCall(d),u={timestamp:s,type:"tool_use",toolUseId:i.toolCallId,toolName:c.toolName,toolInput:c.toolInput};t?.onTaskLog?.([u]);}}else n.sessionUpdate;}resolveToolCall(e){let t=e._meta;if(t?.claudeCode?.toolName)return {toolName:t.claudeCode.toolName,toolInput:Rn(e.rawInput,e.locations)??(e.title||void 0)};if(this.adapter.parseToolCall){let s=this.adapter.parseToolCall(e);if(s)return {toolName:s.toolName??e.title??"unknown",toolInput:s.toolInput}}let r=Vs[e.kind??""]??e.title??"unknown",n=Rn(e.rawInput,e.locations)??(e.title||void 0);return {toolName:r,toolInput:n}}extractResultPreview(e){if(e!=null){if(typeof e=="string")return e;if(Array.isArray(e)){let t=e.filter(r=>r!=null&&typeof r=="object"&&r.type==="text"&&typeof r.text=="string").map(r=>r.text);if(t.length>0)return t.join(`
32
+ `)}if(typeof e=="object"){let t=e;if(typeof t.formatted_output=="string")return t.formatted_output;if(typeof t.content=="string")return t.content;if(Array.isArray(t.content)){let r=this.extractResultPreview(t.content);if(r)return r}if(typeof t.output=="string")return t.output;if(typeof t.text=="string")return t.text;if(typeof t.message=="string")return t.message;if(t.result!=null){let r=this.extractResultPreview(t.result);if(r)return r}if(t.error!=null){let r=this.extractResultPreview(t.error);if(r)return r}}return JSON.stringify(e)}}handleUsage(e,t){if(!t?.onUsage)return;if(this.adapter.extractUsage){let n=this.adapter.extractUsage(e);if(n){t.onUsage(n);return}}let r=e.usage;r&&t.onUsage({inputTokens:r.inputTokens??0,outputTokens:r.outputTokens??0,cachedInputTokens:r.cachedReadTokens??0,costUsd:0});}};});var St,hr=N(()=>{l();xe();St={spawn:{command:"npx",args:["claude-agent-acp"],shellOnWindows:true},npmPackage:"@agentclientprotocol/claude-agent-acp",clientInfo:{name:"crewx-sdk",version:"0.8.4"},buildSessionParams(o){return {cwd:o.cwd??process.cwd(),mcpServers:[]}},extractUsage(o){let e=o.usage;return e?{inputTokens:e.inputTokens??0,outputTokens:e.outputTokens??0,cachedInputTokens:e.cachedReadTokens??0,costUsd:0}:null},yoloModeId:"bypassPermissions",buildEffortAction(o){return o?{type:"set_config_option",configId:"effort",value:o}:null},resolveMode(o){return {yolo:"bypassPermissions"}[o]??o},parseEvent:re};});var It,wr=N(()=>{l();xe();It={spawn:{command:"npx",args:["codex-acp"],shellOnWindows:true},npmPackage:"@agentclientprotocol/codex-acp",clientInfo:{name:"crewx-sdk",version:"0.8.4"},buildSessionParams(o){return {cwd:o.cwd??process.cwd(),mcpServers:[]}},extractUsage(o){let e=o.usage;return e?{inputTokens:e.inputTokens??0,outputTokens:e.outputTokens??0,cachedInputTokens:e.cachedReadTokens??0,costUsd:0}:null},yoloModeId:"agent-full-access",buildEffortAction(o,e){return e&&o?{type:"set_model",modelId:`${e}[${o}]`}:e&&!o?{type:"set_model",modelId:`${e}[medium]`}:null},resolveMode(o){return {yolo:"agent-full-access",default:"agent",plan:"read-only"}[o]??o},parseEvent:re};});var Ot,xr=N(()=>{l();xe();Ot={spawn:{command:"gemini",args:["--acp"],shellOnWindows:false},clientInfo:{name:"crewx-sdk",version:"0.8.4"},buildSessionParams(o){return {cwd:o.cwd??process.cwd(),mcpServers:[]}},yoloModeId:"yolo",buildEffortAction(o){return null},resolveMode(o){return {acceptEdits:"autoEdit"}[o]??o},parseEvent:re};});var Ue,Mt,vr=N(()=>{l();xe();Ue="https://agentclientprotocol.com/protocol/session-modes",Mt={spawn:{command:"copilot",args:["--acp"],shellOnWindows:false},clientInfo:{name:"crewx-sdk",version:"0.8.4"},buildSessionParams(o){return {cwd:o.cwd?resolve(o.cwd):process.cwd(),mcpServers:[]}},yoloModeId:`${Ue}#autopilot`,buildEffortAction(o){return o?{type:"set_config_option",configId:"reasoning_effort",value:o}:null},resolveMode(o){return o.startsWith("https://")?o:{yolo:`${Ue}#autopilot`,default:`${Ue}#agent`,agent:`${Ue}#agent`,plan:`${Ue}#plan`,autopilot:`${Ue}#autopilot`}[o]??null},parseEvent:re};});var Nt,kr=N(()=>{l();xe();Nt={spawn:{command:"opencode",args:["acp"],shellOnWindows:false},clientInfo:{name:"crewx-sdk",version:"0.8.4"},buildSessionParams(o){return {cwd:o.cwd??process.cwd(),mcpServers:[]}},yoloModeId:void 0,buildEffortAction(o){return o?{type:"set_config_option",configId:"effort",value:o}:null},resolveMode(o){let e={default:"build"};return o==="yolo"?null:e[o]??o},parseEvent:re};});var Dt,_r=N(()=>{l();hr();wr();xr();vr();kr();hr();wr();xr();vr();kr();Dt={claude:St,codex:It,gemini:Ot,copilot:Mt,opencode:Nt};});var An={};ct(An,{registerAcpProviders:()=>Pn});function Pn(o){if(o){ce("acp",o);return}ce("acp",(e,t)=>{let r=Dt[e];if(!r)throw new b(`Unknown ACP provider id: "${e}". Supported: ${Object.keys(Dt).join(", ")}`,t);return new tt(e,r,t)});}var Rr=N(()=>{l();oe();yr();_r();oe();});function Js(o){if(!o)return o;let e=o.trim().replace(/\/+$/,"");return e.toLowerCase().endsWith("/mcp")?e.slice(0,-4):e}var rt,Pr=N(()=>{l();rt=class{endpoint;headers;timeoutMs;constructor(e){let t=Js(e.url);this.endpoint=`${t}/mcp`,this.headers={"Content-Type":"application/json",...e.headers??{}},e.apiKey&&(this.headers.Authorization=`Bearer ${e.apiKey}`),this.timeoutMs=e.timeoutMs??3e4;}async send(e){let t=new AbortController,r=setTimeout(()=>t.abort(),this.timeoutMs);try{let n=await fetch(this.endpoint,{method:"POST",headers:this.headers,body:JSON.stringify(e),signal:t.signal});if(clearTimeout(r),!n.ok){let a=await n.text();throw new Error(`HTTP ${n.status}: ${n.statusText}${a?` - ${a}`:""}`)}let s=n.headers.get("content-type");if(s?.includes("application/json"))return await n.json();let i=await n.text();return {jsonrpc:"2.0",id:e.id,error:{code:-32600,message:`Unexpected response content-type: ${s}`,data:i}}}catch(n){throw clearTimeout(r),n instanceof Error&&n.name==="AbortError"?new Error(`MCP-HTTP request timeout after ${this.timeoutMs}ms to ${this.endpoint}`):n}}async close(){}};});var nt,Ar=N(()=>{l();Pr();nt=class{logger;configs=new Map;transports=new Map;constructor(e={}){this.logger=e.logger??(()=>{});}loadConfig(e,t){this.validateConfig(t),this.configs.set(e,t),this.transports.set(e,new rt({url:t.url,apiKey:t.apiKey,headers:t.headers,timeoutMs:t.timeoutMs})),this.logger(`Loaded remote agent config for: ${e}`,"debug");}loadConfigWithTransport(e,t,r){this.validateConfig(t),this.configs.set(e,t),this.transports.set(e,r),this.logger(`Loaded remote agent config for: ${e} (custom transport)`,"debug");}getConfig(e){return this.configs.get(e)}isRemoteAgent(e){return this.configs.has(e)}getRemoteAgentIds(){return Array.from(this.configs.keys())}async query(e,t){let r=this.requireConfig(e),n=r.tools?.query??"crewx_queryAgent",i={agentId:r.agentId??e,query:t.query};t.context&&(i.context=t.context),t.model&&(i.model=t.model),t.platform&&(i.platform=t.platform),t.messages?.length&&(i.messages=t.messages);try{let a=await this.callRemoteTool(e,n,i);return this.normalizeResponse(a)}catch(a){let d=a instanceof Error?a.message:String(a);throw this.logger(`Remote query failed for agent ${e}: ${d}`,"error"),a}}async execute(e,t){let r=this.requireConfig(e),n=r.tools?.execute??"crewx_executeAgent",i={agentId:r.agentId??e,task:t.task};t.context&&(i.context=t.context),t.model&&(i.model=t.model),t.platform&&(i.platform=t.platform),t.messages?.length&&(i.messages=t.messages);try{let a=await this.callRemoteTool(e,n,i);return this.normalizeResponse(a)}catch(a){let d=a instanceof Error?a.message:String(a);throw this.logger(`Remote execute failed for agent ${e}: ${d}`,"error"),a}}mapToolNames(e,t){let r=this.requireConfig(e);r.tools={query:t.query??r.tools?.query??"crewx_queryAgent",execute:t.execute??r.tools?.execute??"crewx_executeAgent"},this.logger(`Updated tool name mapping for agent ${e}`,"debug");}async clearConfigs(){for(let e of this.transports.values())await e.close();this.configs.clear(),this.transports.clear(),this.logger("Cleared all remote agent configurations","debug");}requireConfig(e){let t=this.configs.get(e);if(!t)throw new Error(`Agent ${e} is not configured as a remote agent`);return t}async callRemoteTool(e,t,r){let n=this.transports.get(e);if(!n)throw new Error(`No transport available for agent ${e}`);let s={jsonrpc:"2.0",id:`${t}-${Date.now()}`,method:"tools/call",params:{name:t,arguments:r}};this.logger(`Calling remote MCP tool ${t} for agent ${e}`,"debug");let i=await n.send(s);if(i.error)throw new Error(i.error.message||"MCP server returned an error");return i.result}normalizeResponse(e){if(!e)return {success:false,content:[{type:"text",text:"Remote agent returned no response."}]};let t=e;if(Array.isArray(t.content)&&t.content.length>0)return t;let r=t.response??t.implementation??t.message??t.output,n=typeof r=="string"?r:JSON.stringify(r??e,null,2);return {...t,content:[{type:"text",text:n}]}}validateConfig(e){if(!e.url)throw new Error("Remote agent configuration requires a URL");if(!e.url.startsWith("http://")&&!e.url.startsWith("https://"))throw new Error("Remote agent URL must start with http:// or https://");if(e.type!=="mcp-http")throw new Error(`Unsupported remote agent type: ${e.type}`)}};});var bn={};ct(bn,{RemoteProviderRuntime:()=>ot,createRemoteProviderFactory:()=>Cn,resolveFileRemoteAgent:()=>ri});function ei(o){let e=readFileSync(o,"utf-8"),t=load(e);return {agents:Array.isArray(t?.agents)?t.agents:void 0}}function ti(o){let e=Array.isArray(o.provider)?o.provider[0]:o.provider;return e||(Array.isArray(o.inline?.provider)?o.inline.provider[0]:o.inline?.provider)}function ri(o,e=ei,t=existsSync){let r=o.location.replace("file://","");if(!t(r))throw new Error(`Remote config file not found: ${r}`);if(!o.external_agent_id)throw new Error(`external_agent_id is required for file:// remote provider "${o.id}"`);let s=e(r).agents?.find(d=>d.id===o.external_agent_id);if(!s)throw new Error(`Agent "${o.external_agent_id}" not found in ${r}`);let i=ti(s);if(!i)throw new Error(`Agent "${o.external_agent_id}" in ${r} has no provider configured`);if(i.startsWith("remote/"))throw new Error(`Chained remotes not allowed: ${o.id} \u2192 ${i}`);let a=resolve(dirname(r),s.working_directory??".");return {agent:{...s,working_directory:a},provider:i}}function Cn(o,e=ue){return (t,r)=>{let n=o.get(t);if(!n)throw new Error(`Remote provider "${t}" not found. Available: ${Array.from(o.keys()).join(", ")||"(none)"}`);if(n.location.startsWith("file://"))throw new Error(`Remote provider "${t}" uses file:// location which is not supported at the SDK level. Use the CLI commands (crewx query / crewx execute) which handle file:// remotes automatically.`);return new ot(t,n,e)}}function ni(o,e){let t=e.location;if(!t)throw new Error("Remote provider config requires a location");if(!t.startsWith("http://")&&!t.startsWith("https://"))throw new Error(`Unsupported remote location protocol for MCP-HTTP: ${t}`);return {type:"mcp-http",url:t,apiKey:e.apiKey,headers:e.headers,timeoutMs:e.timeout?.query??3e4,agentId:e.external_agent_id??o}}var ot,Cr=N(()=>{l();oe();Ar();ot=class{manager;agentId;constructor(e,t,r=ue){this.agentId=t.external_agent_id??e,this.manager=new nt;let n=ni(e,t);this.manager.loadConfig(this.agentId,n);}async query(e,t){return (await this.manager.query(this.agentId,{agentId:this.agentId,query:e,model:t?.model,context:t?.context??t?.systemPrompt})).content.map(n=>n.text).join(`
33
+ `)}async execute(e,t){return (await this.manager.execute(this.agentId,{agentId:this.agentId,task:e,model:t?.model,context:t?.context??t?.systemPrompt})).content.map(n=>n.text).join(`
34
+ `)}};});var In={};ct(In,{PluginProviderRuntime:()=>st,createPluginProviderFactory:()=>Sn});function Sn(o){return (e,t)=>{let r=o.get(e);if(!r)throw new b(`Plugin provider "${e}" not found. Available: ${Array.from(o.keys()).join(", ")||"(none)"}`,`plugin/${e}`);return new st(e,r)}}function Tn(o,e,t,r){let n=o.map(s=>s.replace(/\{model\}/g,e));return r&&n.push(t),n}function si(o){if(!o||typeof o!="string")throw new Error("Plugin provider requires a cli_command")}function En(o){if(!Array.isArray(o))throw new Error("CLI arguments must be an array");for(let e of o)if(typeof e!="string")throw new Error("Each CLI argument must be a string")}function ii(o){for(let{pattern:e}of o)if(typeof e!="string")throw new Error("Error pattern must be a string")}function ai(o){for(let[e,t]of Object.entries(o))if(typeof e!="string"||typeof t!="string")throw new Error("env entries must be string key/value pairs")}var st,br=N(()=>{l();oe();ht();st=class{constructor(e,t){this.config=t;this.providerStr=`plugin/${e}`,si(t.cli_command),En(t.query_args),En(t.execute_args),t.error_patterns&&ii(t.error_patterns),t.env&&ai(t.env);}config;providerStr;async query(e,t){let r=t?.model??this.config.default_model??"default",n=Tn(this.config.query_args,r,e,this.config.prompt_in_args),s=this.config.prompt_in_args?void 0:e;t?.onCommand?.(`${this.config.cli_command} ${n.join(" ")}`);let i=this.config.timeout?.query??6e5;return this.runProcess(n,t,s,i)}async execute(e,t){let r=t?.model??this.config.default_model??"default",n=Tn(this.config.execute_args,r,e,this.config.prompt_in_args),s=this.config.prompt_in_args?void 0:e;t?.onCommand?.(`${this.config.cli_command} ${n.join(" ")}`);let i=this.config.timeout?.execute??6e5;return this.runProcess(n,t,s,i)}runProcess(e,t,r,n){return new Promise((s,i)=>{let a={...process.env,...this.config.env??{}},d=qe({command:this.config.cli_command,allowShellFallback:true}),c=Fe(d,e),u=spawn(c.command,c.argv,{env:a,shell:c.shell??false,stdio:["pipe","pipe","pipe"],windowsHide:c.windowsHide});r!==void 0&&u.stdin.write(r),u.stdin.end(),u.pid!==void 0&&t?.onPid?.(u.pid);let p="",f="",y="",h="";u.stdout.on("data",w=>{let R=w.toString();p+=R,y+=R;let k=y.split(`
35
+ `);y=k.pop()??"";for(let C of k)C.trim()&&t?.onOutput?.(C,"stdout");}),u.stderr.on("data",w=>{let R=w.toString();f+=R,h+=R;let k=h.split(`
36
+ `);h=k.pop()??"";for(let C of k)C.trim()&&t?.onOutput?.(C,"stderr");});let x=setTimeout(()=>{u.kill("SIGTERM"),i(new b(`Plugin provider "${this.providerStr}" timed out after ${n}ms`,this.providerStr));},n);u.on("error",w=>{if(clearTimeout(x),w.code==="ENOENT"){let R=this.config.not_installed_message??`CLI command "${this.config.cli_command}" not found. Is ${this.config.id} installed?`;i(new b(R,this.providerStr));}else i(new b(`Spawn error: ${w.message}`,this.providerStr));}),u.on("close",w=>{clearTimeout(x),y.trim()&&t?.onOutput?.(y,"stdout"),h.trim()&&t?.onOutput?.(h,"stderr");let R=w??0;if(t?.onExitCode?.(R),this.config.error_patterns){let k=f||p;for(let C of this.config.error_patterns)if(k.includes(C.pattern)){i(new b(C.message,this.providerStr));return}}if(w!==0){i(new b(`Process exited with code ${w}: ${f.slice(0,500)}`,this.providerStr));return}s(p.trim());});})}};});l();l();l();function no(o){let e=n=>n.replace(/[.+^${}()|[\]\\]/g,"\\$&"),r=o.split("/").map(n=>n==="**"?".*":n.split("*").map(e).join("[^/]*"));return new RegExp(`^${r.join("\\/")}$`)}function ne(o,e){try{return no(e).test(o)}catch{return false}}l();l();var oo=z$1.object({model:z$1.string().optional(),system_prompt:z$1.string().optional(),prompt:z$1.string().optional(),layout:z$1.union([z$1.string(),z$1.object({id:z$1.string(),props:z$1.record(z$1.unknown()).optional()}),z$1.object({props:z$1.record(z$1.unknown())}),z$1.object({template:z$1.string()})]).optional()}).catchall(z$1.unknown()),Hr=z$1.object({include:z$1.array(z$1.string()).optional()}).optional(),so=z$1.object({id:z$1.string(),name:z$1.string().optional(),role:z$1.string().optional(),team:z$1.string().optional(),provider:z$1.union([z$1.string(),z$1.array(z$1.string())]),working_directory:z$1.string().optional(),description:z$1.string().optional(),tags:z$1.array(z$1.string()).optional(),inline:oo.optional(),skills:Hr}).catchall(z$1.unknown()),Ur=z$1.object({agents:z$1.array(so).optional(),hooks:z$1.array(z$1.unknown()).optional(),settings:z$1.record(z$1.unknown()).optional(),skills:z$1.unknown().optional(),layouts:z$1.record(z$1.unknown()).optional(),documents:z$1.record(z$1.unknown()).optional()}).catchall(z$1.unknown());var Re=class extends Error{constructor(t,r){super(t);this.cause=r;this.name="ConfigLoadError";}cause};function ut(o){if(!o||typeof o!="string"||!o.trim())throw new Re("YAML content must be a non-empty string");let e;try{e=load(o);}catch(n){throw new Re(`YAML parse error: ${n.message}`,n)}let t=lo(e),r=Ur.safeParse(t);if(!r.success)throw new Re(`Config validation error: ${r.error.message}`);return r.data}function pt(o){let e;try{e=readFileSync(o,"utf-8");}catch(t){throw new Re(`Cannot read file: ${o}`,t)}return ut(e)}function lo(o){if(!o||typeof o!="object")return {agents:[]};let e=o,t;if(e.agents&&typeof e.agents=="object"&&!Array.isArray(e.agents)){let n=e.agents;t=Object.entries(n).map(([s,i])=>({id:s,...i&&typeof i=="object"?i:{}}));}else if(Array.isArray(e.agents))t=e.agents;else return {...e,agents:[]};let r=t.map(n=>{if(n.provider===void 0&&n.inline&&typeof n.inline=="object"){let s=n.inline;if(s.provider!==void 0)return {...n,provider:s.provider}}return n});return {...e,agents:r}}l();var Pe=join("templates","agents");function po(){try{let e=(typeof B=="function"?B:createRequire(typeof m<"u"?m:process.cwd()+"/")).resolve("@crewx/sdk/package.json");return dirname(e)}catch{return null}}function Me(o){if(o&&existsSync(o))return o;let e=process.env.CREWX_SDK_TEMPLATES_PATH;if(e&&existsSync(e))return e;let t=po();if(t){let n=join(t,Pe);if(existsSync(n))return n}let r=[join(g,"..",Pe),join(g,"..","..",Pe),join(g,"..","..","..",Pe),join(process.cwd(),"packages","sdk",Pe),join(process.cwd(),Pe)];for(let n of r)if(existsSync(n))return n;throw new Error(`[@crewx/sdk] Templates directory not found.
37
+ `+(t?` package anchor: ${join(t,Pe)}
51
38
  `:` package anchor: (unresolved)
52
- `)+n.map(o=>` candidate: ${o}`).join(`
39
+ `)+r.map(n=>` candidate: ${n}`).join(`
53
40
  `)+`
54
- Set CREWX_SDK_TEMPLATES_PATH or pass options.templatesPath.`)}function yr(){let r=Qe();return {yamlPath:join(r,"default.yaml"),dir:r}}g();var Re=class extends Error{constructor(e,t){let n=t.length>0?` Available: ${t.join(", ")}`:"";super(`Agent not found: "${e}".${n}`),this.name="AgentNotFoundError";}},qi={claude:{id:"claude",provider:"cli/claude"},gemini:{id:"gemini",provider:"cli/gemini"},copilot:{id:"copilot",provider:"cli/copilot"},codex:{id:"codex",provider:"cli/codex"}};function $t(r,e){let t=r.startsWith("@")?r.slice(1):r,n=e.find(s=>s.id===t);if(n)return n;let o=qi[t];if(o)return o;throw new Re(r,e.map(s=>s.id))}Fe();g();function jn(r,e){if(r===void 0||r==="")return e;let t=parseInt(r,10);return Number.isNaN(t)?e:t}function Nn(r=process.env){return {queryMs:jn(r.CREWX_TIMEOUT_QUERY,36e5),executeMs:jn(r.CREWX_TIMEOUT_EXECUTE,36e5)}}g();g();var ia=[/^ANTHROPIC_/i,/^OPENAI_/i,/^AWS_SECRET/i,/^SLACK_/i,/^GITHUB_TOKEN$/i,/^CREWX_MCP_KEY$/i,/^DATABASE_/i,/^AWS_ACCESS_KEY/i,/^AWS_SESSION_TOKEN$/i,/^GH_TOKEN$/i,/^GH_APP_/i,/^NPM_TOKEN$/i,/^NPM_AUTH/i,/^GOOGLE_APPLICATION/i,/^GCLOUD_/i,/^AZURE_/i,/^ARM_/i,/^DOCKER_PASSWORD$/i,/^DOCKER_AUTH/i,/^SSH_PRIVATE/i,/^SSH_AUTH_SOCK$/i,/^CI_JOB_TOKEN$/i,/^ACTIONS_RUNTIME_TOKEN$/i,/^VAULT_TOKEN$/i,/^SONAR_TOKEN$/i,/^CODECOV_TOKEN$/i,/TOKEN$/i,/SECRET$/i,/PASSWORD$/i,/API_KEY$/i],aa=/[;|&`$(){}!><\n\r]/,la=2,ua=["*","**","*:*","* *","**/*"];function da(){let r={};for(let[e,t]of Object.entries(process.env))t!==void 0&&(ia.some(n=>n.test(e))||(r[e]=t));return r}function ca(r){if(aa.test(r))throw new Error(`exec blocked: shell metacharacter detected in "${r}"`)}function pa(r){return /^npx\s+@crewx\/[\w-]+/.test(r)}function ga(r){if(ua.includes(r.trim()))throw new Error(`exec config error: overly broad pattern "${r}" is not allowed`);if(!/^[\w./@-]/.test(r))throw new Error("exec config error: pattern must start with a command name")}function ma(r,e){let t=e.allow??[],n=e.deny??[];for(let o of [...t,...n])ga(o);return n.some(o=>ve(r,o))?false:pa(r)?true:t.some(o=>ve(r,o))}var Dn=false;function fa(r){Dn=r;}function dt(r){if(!Dn)return;let e=JSON.stringify({span:"template_exec",...r,timestamp:new Date().toISOString()});console.error(e);}function ha(r){let e=[],t="",n=false,o=false;for(let s=0;s<r.length;s++){let i=r[s];i==="'"&&!o?n=!n:i==='"'&&!n?o=!o:i===" "&&!n&&!o?t.length>0&&(e.push(t),t=""):t+=i;}return t.length>0&&e.push(t),e}function $n(r,e){let t=Date.now(),n=parseInt(process.env.CREWX_EXEC_DEPTH??"0",10);if(isNaN(n)||n>=la)return dt({command:r,status:"denied",reason:"invalid or max recursion depth"}),"(exec blocked: max recursion depth reached)";try{ca(r);}catch{return dt({command:r,status:"denied",reason:"shell metacharacter detected"}),`(exec blocked: shell metacharacter detected in "${r}")`}if(!ma(r,e))return dt({command:r,status:"denied",reason:"not in allow list"}),`(exec blocked: ${r})`;try{let o=ha(r),[s,...i]=o;if(!s)return `(exec failed: ${r})`;let a=da(),l=execFileSync(s,i,{timeout:e.timeout??5e3,maxBuffer:64*1024,encoding:"utf-8",env:{...a,CREWX_EXEC_DEPTH:String(n+1)},stdio:["pipe","pipe","pipe"]}),u=Date.now()-t;return dt({command:r,status:"allowed",allowed_by:"policy",duration_ms:u}),`<exec-output cmd="${r}">
55
- ${l.trim()}
56
- </exec-output>`}catch{return dt({command:r,status:"error",reason:"execution failed"}),`(exec failed: ${r})`}}g();function Hn(r){return r==null?"":String(r)}g();function qn(r,e){return `\`\`\`${e?.hash?.lang??""}
57
- ${r??""}
58
- \`\`\``}g();function Pr(r,e){if(!r)return "";if(r.length<=e)return r;let t=r.length-e;return `${r.substring(0,e)} (...+${t} chars)`}function Ar(r){return Array.isArray(r)||typeof r=="string"?r.length:0}function Er(r){return typeof r!="string"?"":r.replace(/\{\{/g,"&#123;&#123;").replace(/\}\}/g,"&#125;&#125;")}var Ln=["B","KB","MB","GB"];function Sr(r){if(r===0)return "0 B";let e=Math.min(Math.floor(Math.log(r)/Math.log(1024)),Ln.length-1);return `${Math.round(r/Math.pow(1024,e)*100)/100} ${Ln[e]}`}function Ir(r){if(!r)return "";try{let e=r instanceof Date?r:new Date(r);return isNaN(e.getTime())?"":e.toLocaleString("ko-KR",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}catch{return ""}}var ct=class{hbs;execPolicy;execEnabled;constructor(e={}){this.hbs=_e.create(),this.execPolicy=e.execPolicy??{allow:[],deny:[]},this.execEnabled=e.execEnabled??true,this.registerHelpers();}registerHelpers(){let e=this.hbs,t=this.execPolicy,n=this.execEnabled;e.registerHelper("exec",function(o){return typeof o!="string"?"":n?new e.SafeString($n(o,t)):"(exec disabled)"}),e.registerHelper("include",function(o){return new e.SafeString(Hn(o))}),e.registerHelper("fenced_code",function(o,s){return new e.SafeString(qn(o,s))}),e.registerHelper("eq",function(o,s){return o===s}),e.registerHelper("ne",function(o,s){return o!==s}),e.registerHelper("and",function(o,s){return o&&s}),e.registerHelper("or",function(o,s){return o||s}),e.registerHelper("not",function(o){return !o}),e.registerHelper("contains",function(o,s){return Array.isArray(o)&&o.includes(s)}),e.registerHelper("json",function(o){return JSON.stringify(o,null,2)}),e.registerHelper("truncate",function(o,s){return Pr(o,s)}),e.registerHelper("length",function(o){return Ar(o)}),e.registerHelper("escapeHandlebars",function(o){return new e.SafeString(Er(o))}),e.registerHelper("formatFileSize",function(o){return Sr(o)}),e.registerHelper("formatTimestamp",function(o){return Ir(o)});}async render(e,t={}){return this.hbs.compile(e,{noEscape:true})(t)}};g();g();var Vt=class{async readFile(e){return readFile(e,"utf-8")}async exists(e){try{return await access(e),!0}catch{return false}}resolvePath(...e){return e.length===1?resolve(e[0]):resolve(join(...e))}isAbsolute(e){return isAbsolute(e)}},Or=new Vt;var Ue=class{docs=new Map;fs;constructor(e){this.fs=e??Or;}async load(e,t){if(e)for(let[n,o]of Object.entries(e)){let s=o;if(typeof s=="string")this.docs.set(n,{content:s});else if(s&&typeof s=="object"){let i=s;"content"in i&&typeof i.content=="string"?this.docs.set(n,{content:i.content}):"path"in i&&typeof i.path=="string"?await this.loadFromFile(n,i.path,t):console.warn(`[DocumentLoader] Skipping '${n}': unsupported format`);}else console.warn(`[DocumentLoader] Skipping '${n}': unsupported format`);}}async getContent(e){return this.docs.get(e)?.content}async getToc(e){let t=this.docs.get(e);if(!t)return;let n=[];for(let o of t.content.split(`
59
- `)){let s=/^(#{1,6})\s+(.+)$/.exec(o.trim());s&&n.push({depth:s[1].length,text:s[2].trim()});}if(n.length!==0)return n.map(({depth:o,text:s})=>`${" ".repeat(o-1)}- ${s}`).join(`
60
- `)}getPath(e){return this.docs.get(e)?.path}getNames(){return Array.from(this.docs.keys())}async buildContext(){let e={};for(let t of this.docs.keys()){let n=await this.getContent(t)??"",o=await this.getToc(t),s=this.getPath(t);e[t]={content:n,toc:o,...s?{path:s}:{}};}return e}async loadFromFile(e,t,n){try{let o=this.resolve(t,n),s=await this.fs.readFile(o);this.docs.set(e,{content:s,path:o});}catch(o){let s=o instanceof Error?o.message:String(o);console.warn(`[DocumentLoader] Failed to load '${e}' from '${t}': ${s}`);}}resolve(e,t){return this.fs.isAbsolute(e)?e:t?this.fs.resolvePath(t,e):this.fs.resolvePath(e)}};g();g();var se=class extends Error{constructor(t,n,o){super(t);this.layoutId=n;this.cause=o;this.name="LayoutLoadError";}layoutId;cause},Te=class extends Error{constructor(t,n=[],o){super(t);this.errors=n;this.cause=o;this.name="PropsValidationError";}errors;cause};var Ca={validationMode:"lenient",fallbackLayoutId:"crewx/default"},pt=class{layouts=new Map;options;constructor(e){this.options={...Ca,...e,templatesPath:e?.templatesPath??Qe()},this.loadAllLayouts();}load(e,t){let n=this.layouts.get(e);if(!n){let o=this.normalizeLayoutId(e);n=this.layouts.get(o);}if(!n&&(console.warn(`Layout not found: ${e}, falling back to ${this.options.fallbackLayoutId}`),n=this.layouts.get(this.options.fallbackLayoutId),!n))throw new se(`Fallback layout not found: ${this.options.fallbackLayoutId}`,this.options.fallbackLayoutId);return t&&Object.keys(t).length>0?{...n,defaultProps:{...n.defaultProps,...t}}:n}getLayoutIds(){return Array.from(this.layouts.keys())}hasLayout(e){if(this.layouts.has(e))return true;let t=this.normalizeLayoutId(e);return this.layouts.has(t)}reload(){this.layouts.clear(),this.loadAllLayouts();}registerLayout(e,t){if(!e||typeof e!="string")throw new se("Layout ID must be a non-empty string",e);let n=typeof t=="string"?{template:t}:t,o=typeof n.template=="string"?n.template:"";if(!o||o.trim().length===0)throw new se(`Custom layout template is empty for ${e}`,e);let s=n.propsSchema||{},i=this.extractDefaultProps(s),a=n.defaultProps||{},l={id:e,version:n.version||"1.0.0",description:n.description||`Custom layout ${e}`,template:o,propsSchema:this.parsePropsSchema(s),defaultProps:{...i,...a}},u=this.layouts.get(e),d=u?.template===o&&JSON.stringify(u?.defaultProps??{})===JSON.stringify(l.defaultProps??{})&&JSON.stringify(u?.propsSchema??{})===JSON.stringify(l.propsSchema??{});this.layouts.set(e,l),process.env.CREWX_VERBOSE==="1"&&(u?d||console.error(`Updated custom layout: ${e}`):console.error(`Registered custom layout: ${e}`));}registerLayouts(e){for(let[t,n]of Object.entries(e))try{this.registerLayout(t,n);}catch(o){console.warn(`Failed to register custom layout ${t}:`,o instanceof Error?o.message:o);}}loadAllLayouts(){let e=this.options.templatesPath;if(!existsSync(e))throw new se(`Templates directory not found: ${e}`,void 0,new Error(`Directory does not exist: ${e}`));try{let t=readdirSync(e).filter(n=>n.endsWith(".yaml")||n.endsWith(".yml"));t.length===0&&console.warn(`No layout files found in ${e}`);for(let n of t){let o=n.replace(/\.(yaml|yml)$/,""),s=ne.join(e,n);try{let i=this.loadLayoutFile(s,o),a=`crewx/${o}`;this.layouts.set(a,i),a!=="crewx/minimal"&&process.env.CREWX_VERBOSE==="1"&&console.error(`Loaded layout: ${a} from ${n}`);}catch(i){console.error(`Failed to load layout file ${n}:`,i);}}process.env.CREWX_VERBOSE==="1"&&console.error(`Loaded ${this.layouts.size} layouts from ${e}`);}catch(t){throw new se(`Failed to read layouts directory: ${e}`,void 0,t instanceof Error?t:new Error(String(t)))}}loadLayoutFile(e,t){try{let n=readFileSync(e,"utf-8");if(!n||n.trim().length===0)throw console.warn(`Empty YAML file: ${e}, will use fallback`),new se(`Empty YAML file: ${e}`,t,new Error("File content is empty"));let o=load(n);if(!o||typeof o!="object")throw console.warn(`Invalid YAML content in ${e} (parsed as ${typeof o}), will use fallback`),new se(`Invalid or empty YAML in ${e}`,t,new Error("YAML parsing returned null/undefined or non-object"));if(o.layouts&&typeof o.layouts=="object"){let s=this.resolveLayoutEntry(o.layouts,t);if(!s||s.template.trim().length===0)throw console.warn(`Empty or missing layout template in ${e} for ${t}`),new se(`Layout template not found or empty in layouts map: ${t}`,t);let i=s.propsSchema||o.propsSchema||{};return {id:`crewx/${t}`,version:o.version||"1.0.0",description:o.description||`CrewX ${t} layout`,template:s.template,propsSchema:this.parsePropsSchema(i),defaultProps:this.extractDefaultProps(i)}}else {if(!o.template||typeof o.template=="string"&&o.template.trim().length===0)throw console.warn(`Empty or missing template field in ${e}`),new se(`Layout template is missing or empty in ${e}`,t);return {id:o.id||`crewx/${t}`,version:o.version||"1.0.0",description:o.description||"",template:o.template,propsSchema:this.parsePropsSchema(o.propsSchema||{}),defaultProps:this.extractDefaultProps(o.propsSchema||{})}}}catch(n){throw new se(`Failed to load layout file: ${e}`,t,n instanceof Error?n:new Error(String(n)))}}parsePropsSchema(e){let t={};for(let[n,o]of Object.entries(e))typeof o=="object"&&o!==null&&(t[n]=o);return t}extractDefaultProps(e){let t={};for(let[n,o]of Object.entries(e))o&&typeof o=="object"&&("defaultValue"in o?t[n]=o.defaultValue:"default"in o&&(t[n]=o.default));return t}normalizeLayoutId(e){return e?e.includes("/")?e:`crewx/${e}`:this.options.fallbackLayoutId}resolveLayoutEntry(e,t){let n=new Set;if(t)if(n.add(t),t.includes("/")){let o=t.split("/"),s=o[o.length-1];s&&n.add(s);}else n.add(`crewx/${t}`);n.add("default");for(let o of n){let s=e[o];if(typeof s=="string"&&s.trim().length>0)return {template:s};if(s&&typeof s=="object"&&typeof s.template=="string"&&s.template.trim().length>0)return {template:s.template,propsSchema:s.propsSchema}}for(let o of Object.values(e)){if(typeof o=="string"&&o.trim().length>0)return {template:o};let s=o;if(s&&typeof s=="object"&&typeof s.template=="string"&&s.template.trim().length>0)return {template:s.template,propsSchema:s.propsSchema}}}};g();g();function Ta(r){return Array.from(new Set(r.filter(e=>e?.isAssistant&&e?.metadata?.agent_id).map(e=>String(e.metadata.agent_id))))}function Wn(r,e,t){if(!Array.isArray(r)||r.length===0||!(t&&typeof t.fn=="function"))return "";let o=Ta(r),s=o.length>0?o[0]:"",i={messages:r,platform:typeof e=="string"?e:"",messagesCount:r.length,agentIds:o,primaryAgentId:s};return t.fn(i)}g();var gt=class{defaultMode;constructor(e={}){this.defaultMode=e.defaultMode??"lenient";}validate(e,t,n=this.defaultMode){let o=[],s=this.validateObject(e??{},t,n,["props"],o);if(o.length>0&&n==="strict")throw new Te("Props validation failed in strict mode",o);return {valid:o.length===0,props:s,errors:o}}validateObject(e,t,n,o,s){let i={};if(n==="strict")for(let a of Object.keys(e))t[a]||s.push({path:this.buildPath([...o,a]),message:`Unknown prop '${a}'`,value:e[a]});for(let[a,l]of Object.entries(t)){let u=[...o,a],d=e[a],c=this.resolveProp(d,l,u,n,s);c.shouldAssign&&(i[a]=c.value);}return i}resolveProp(e,t,n,o,s){let i=this.buildPath(n);if(this.isNil(e)){if(t.isRequired&&s.push({path:i,message:`Required prop '${n[n.length-1]}' is missing`}),t.defaultValue!==void 0)return {shouldAssign:true,value:this.cloneValue(t.defaultValue)};if(t.type==="shape"&&t.shape){let l=this.applyDefaults(t.shape);if(Object.keys(l).length>0)return {shouldAssign:true,value:l}}return {shouldAssign:false}}let a=this.validateType(e,t,n,o,s);if(!a.valid){if(t.type==="shape"&&a.value&&this.isPlainObject(a.value))return {shouldAssign:true,value:a.value};if(s.push({path:i,message:a.error??"Invalid value",value:e}),t.defaultValue!==void 0)return {shouldAssign:true,value:this.cloneValue(t.defaultValue)};if(t.type==="shape"&&t.shape){let l=this.applyDefaults(t.shape);if(Object.keys(l).length>0)return {shouldAssign:true,value:l}}return {shouldAssign:false}}return {shouldAssign:true,value:a.value}}validateType(e,t,n,o,s){let{type:i}=t;switch(i){case "string":return this.validateString(e,t);case "number":return this.validateNumber(e,t);case "bool":return this.validateBoolean(e);case "array":return this.validateArray(e,t);case "arrayOf":return this.validateArrayOf(e,t,n,o,s);case "object":return this.validatePlainObject(e);case "shape":return this.validateShape(e,t,n,o,s);case "oneOfType":return this.validateOneOfType(e,t);case "func":return this.validateFunction(e);case "node":return {valid:true,value:e};default:return {valid:true,value:e}}}validateString(e,t){return typeof e!="string"?{valid:false,error:`Expected string, got ${this.describeType(e)}`}:t.oneOf&&!t.oneOf.includes(e)?{valid:false,error:`Expected one of: ${t.oneOf.join(", ")}`}:t.minLength!==void 0&&e.length<t.minLength?{valid:false,error:`String length must be >= ${t.minLength}`}:t.maxLength!==void 0&&e.length>t.maxLength?{valid:false,error:`String length must be <= ${t.maxLength}`}:t.pattern&&!new RegExp(t.pattern).test(e)?{valid:false,error:`String does not match pattern ${t.pattern}`}:{valid:true,value:e}}validateNumber(e,t){return typeof e!="number"||Number.isNaN(e)?{valid:false,error:`Expected number, got ${this.describeType(e)}`}:t.min!==void 0&&e<t.min?{valid:false,error:`Number must be >= ${t.min}`}:t.max!==void 0&&e>t.max?{valid:false,error:`Number must be <= ${t.max}`}:t.oneOf&&!t.oneOf.includes(e)?{valid:false,error:`Expected one of: ${t.oneOf.join(", ")}`}:{valid:true,value:e}}validateBoolean(e){return typeof e!="boolean"?{valid:false,error:`Expected boolean, got ${this.describeType(e)}`}:{valid:true,value:e}}validateArray(e,t){return Array.isArray(e)?t.minLength!==void 0&&e.length<t.minLength?{valid:false,error:`Array length must be >= ${t.minLength}`}:t.maxLength!==void 0&&e.length>t.maxLength?{valid:false,error:`Array length must be <= ${t.maxLength}`}:{valid:true,value:[...e]}:{valid:false,error:`Expected array, got ${this.describeType(e)}`}}validateArrayOf(e,t,n,o,s){let i=this.validateArray(e,t);if(!i.valid)return i;let a=[],l=t.itemType,u=t.itemOneOf,d=s.length;return i.value.forEach((c,p)=>{let f=[...n,String(p)];if(l){let v=this.validateType(c,{type:l},f,o,s);v.valid?a.push(v.value):s.push({path:this.buildPath(f),message:v.error??"Invalid array item",value:c});}else a.push(c);u&&!u.includes(c)&&s.push({path:this.buildPath(f),message:`Array item must be one of: ${u.join(", ")}`,value:c});}),{valid:s.length===d,value:a}}validatePlainObject(e){return this.isPlainObject(e)?{valid:true,value:{...e}}:{valid:false,error:`Expected object, got ${this.describeType(e)}`}}validateFunction(e){return typeof e!="function"?{valid:false,error:`Expected function, got ${this.describeType(e)}`}:{valid:true,value:e}}validateShape(e,t,n,o,s){if(!this.isPlainObject(e))return {valid:false,error:`Expected object, got ${this.describeType(e)}`};let i=s.length,a=this.validateObject(e,t.shape??{},o,n,s);return {valid:s.length===i,value:a}}validateOneOfType(e,t){let n=t.types??[];return n.some(s=>this.matchesType(e,s))?{valid:true,value:e}:{valid:false,error:`Value does not match any allowed type: ${n.join(", ")}`}}matchesType(e,t){switch(t){case "string":return typeof e=="string";case "number":return typeof e=="number"&&!Number.isNaN(e);case "bool":case "boolean":return typeof e=="boolean";case "array":return Array.isArray(e);case "object":return this.isPlainObject(e);case "func":case "function":return typeof e=="function";case "shape":return this.isPlainObject(e);case "node":return e==null||typeof e!="symbol";default:return true}}applyDefaults(e){let t={};for(let[n,o]of Object.entries(e)){if(o.defaultValue!==void 0){t[n]=this.cloneValue(o.defaultValue);continue}if(o.type==="shape"&&o.shape){let s=this.applyDefaults(o.shape);Object.keys(s).length>0&&(t[n]=s);}}return t}cloneValue(e){if(Array.isArray(e))return e.map(t=>this.cloneValue(t));if(this.isPlainObject(e)){let t={};for(let[n,o]of Object.entries(e))t[n]=this.cloneValue(o);return t}return e}isPlainObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}isNil(e){return e==null}buildPath(e){return e.join(".")}describeType(e){return Array.isArray(e)?"array":e===null?"null":typeof e}};var mt=class{handlebars;propsValidator;constructor(e){this.handlebars=_e__default.create(),this.propsValidator=e??new gt,this.registerHelpers();}render(e,t,n={}){try{let o=this.prepareRenderContext(e,t,n);return this.handlebars.compile(e.template,{noEscape:!0})(o)}catch(o){throw o instanceof Error?new Error(`Template rendering failed for layout '${e.id}': ${o.message}`):new Error(`Unknown error rendering layout '${e.id}'`)}}validate(e,t,n="lenient"){return this.executeValidation(e,t,n)}resolveProps(e,t,n="lenient"){let o=this.mergeProps(e.defaultProps,t);return !e.propsSchema||Object.keys(e.propsSchema).length===0?{valid:true,props:o,errors:[]}:this.executeValidation(o,e.propsSchema,n)}prepareRenderContext(e,t,n){let{validationMode:o="lenient",skipValidation:s=false}=n,i=s?this.mergeProps(e.defaultProps,t.props):this.resolveProps(e,t.props,o).props;return {...t,vars:this.sanitizeVars(t.vars),props:i}}registerHelpers(){this.handlebars.registerHelper("formatConversation",Wn),_e__default.helpers.each&&this.handlebars.registerHelper("each",_e__default.helpers.each),_e__default.helpers.if&&this.handlebars.registerHelper("if",_e__default.helpers.if),_e__default.helpers.unless&&this.handlebars.registerHelper("unless",_e__default.helpers.unless),_e__default.helpers.with&&this.handlebars.registerHelper("with",_e__default.helpers.with),this.handlebars.registerHelper("eq",function(e,t){return e===t}),this.handlebars.registerHelper("ne",function(e,t){return e!==t}),this.handlebars.registerHelper("gt",function(e,t){return e>t}),this.handlebars.registerHelper("lt",function(e,t){return e<t}),this.handlebars.registerHelper("json",function(e){return new _e__default.SafeString(JSON.stringify(e))}),this.handlebars.registerHelper("raw",function(e){return typeof e?.fn=="function"?e.fn(this):""}),this.handlebars.registerHelper("escapeHandlebars",function(e){return typeof e!="string"?"":e.replace(/\{\{/g,"&#123;&#123;").replace(/\}\}/g,"&#125;&#125;")}),this.handlebars.registerHelper("formatFileSize",function(e){if(e===0)return "0 B";let t=["B","KB","MB","GB"],n=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,n)*100)/100+" "+t[n]});}executeValidation(e,t,n){try{return this.propsValidator.validate(e,t,n)}catch(o){if(o instanceof Te&&o.errors&&o.errors.length>0){let s=o.errors[0];if(s)throw new Te(s.message,o.errors)}throw o}}mergeProps(e,t){let n=this.cloneDeep(e??{});return t?this.deepMerge(n,t):n}deepMerge(e,t){for(let[n,o]of Object.entries(t)){if(this.isPlainObject(o)){let s=e[n];e[n]=this.deepMerge(this.isPlainObject(s)?s:{},o);continue}if(Array.isArray(o)){e[n]=this.cloneDeep(o);continue}e[n]=o;}return e}cloneDeep(e){if(Array.isArray(e))return e.map(t=>this.cloneDeep(t));if(this.isPlainObject(e)){let t={};for(let[n,o]of Object.entries(e))t[n]=this.cloneDeep(o);return t}return e}isPlainObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}sanitizeVars(e){if(!e)return {};let t={...e};if(typeof e.user_input=="string"){t.user_input_raw=e.user_input;let n=e.user_input.replace(/\{\{\{/g,"&#123;&#123;&#123;").replace(/\}\}\}/g,"&#125;&#125;&#125;").replace(/\{\{/g,"&#123;&#123;").replace(/\}\}/g,"&#125;&#125;");t.user_input=this.handlebars.escapeExpression(n);}return t}};g();var zr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Pa(r){let e=randomBytes(r*2),t="";for(let n=0;n<e.length&&t.length<r;n++){let o=e[n];o<248&&(t+=zr[o%62]);}for(;t.length<r;)t+=zr[randomBytes(1)[0]%62];return t}function Be(r){return `${r}_${Pa(8)}`}function Aa(r,e){let{createHash:t}=J("crypto"),n=t("sha256").update(e).digest(),o=Buffer.alloc(8);for(let i=0;i<32;i++)o[i%8]^=n[i];let s="";for(let i of o)s+=zr[i%62];return `${r}_${s}`}g();function Mr(r){let e=t=>String(t).padStart(2,"0");return `${r.getFullYear()}${e(r.getMonth()+1)}${e(r.getDate())}T${e(r.getHours())}${e(r.getMinutes())}${e(r.getSeconds())}`}g();function Vn(r,e){return t=>{try{let n=e(t);n instanceof Promise&&n.catch(o=>{console.error(`[crewx] event listener error (${r}): ${o instanceof Error?o.message:String(o)}`);});}catch(n){console.error(`[crewx] event listener error (${r}): ${n instanceof Error?n.message:String(n)}`);}}}var ft=class{_emitter=new EventEmitter;on(e,t){let n=Vn(e,t);return this._emitter.on(e,n),()=>this._emitter.off(e,n)}once(e,t){let n=Vn(e,t);return this._emitter.once(e,n),()=>this._emitter.off(e,n)}emit(e,t){this._emitter.emit(e,t);}};g();function jr(r){let e=new Map,t=n=>n.startsWith(`${r}::`)?n:`${r}::${n}`;return {async get(n){let o=e.get(t(n));return o?o.value:void 0},async set(n,o){e.set(t(n),{value:o});},async delete(n){return e.delete(t(n))},async list(n){let o=n?t(n):`${r}::`,s=[];for(let i of e.keys())i.startsWith(o)&&s.push(i.slice(r.length+2));return s}}}g();var Nr=new AsyncLocalStorage;function Ia(){return Nr}function Oa(r,e){return Nr.run(r,e)}function Dr(r){let e=r.log??r.logger??{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},t=r.agentRunner??{run:async()=>({output:""})},n=r.db??{get:async()=>{},set:async()=>{},delete:async()=>false,list:async()=>[]},o=r.storage??{put:async()=>"",get:async()=>{},delete:async()=>false},s=r.audit??{log:async()=>{}},i=r.onInbound??(async()=>({accepted:true})),a=r.onEmitEvent??(async()=>({accepted:true})),l=r.onUpdateMessage??(async()=>{}),u=r.onResolveUser??(async p=>({userId:p,displayName:p})),d=async p=>{let f=Nr.getStore();if(!f){e.warn("respondSync called outside sync window \u2014 graceful degradation (no-op)",{textPreview:typeof p=="object"&&"text"in p?p.text.slice(0,80):void 0});return}let v="text"in p?p.text:"";f.res.status(200).json({text:v});},c=r.httpRouter??{registerRoute:()=>{e.warn("httpRouter not configured \u2014 registerRoute is a no-op");}};return {instanceId:r.instanceId,config:r.config,capabilities:r.capabilities,log:e,agentRunner:t,db:n,storage:o,audit:s,abortSignal:r.abortSignal??new AbortController().signal,httpRouter:c,inbound:i,emitEvent:a,updateMessage:l,resolveUser:u,respondSync:d}}et();et();g();function za(r){return typeof r!="string"?"":r.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function $r(r){return r.messages.map(e=>({text:za(e.text),isAssistant:e.isAssistant,metadata:e.metadata,files:void 0}))}g();g();var Ma={agentId:z.string().describe("The agent ID to query"),query:z.string().describe("The query message to send"),context:z.string().optional().describe("Additional context"),thread:z.string().optional().describe("Thread ID for conversation continuity")},ja={agentId:z.string().describe("The agent ID to execute"),task:z.string().describe("The task description to execute"),context:z.string().optional().describe("Additional context"),thread:z.string().optional().describe("Thread ID for conversation continuity")};function Kn(r,e,t){r.tool("crewx_listAgents","List available CrewX agents exposed by this server",async()=>{let n=[];for(let o of t){let s=e.agents.get(o);s&&n.push({id:s.id,name:s.name??s.id,description:s.description??""});}return {content:[{type:"text",text:JSON.stringify(n,null,2)}]}}),r.tool("crewx_queryAgent","Query a CrewX agent with a read-only question",Ma,async({agentId:n,query:o,context:s,thread:i})=>{if(!t.has(n))return {content:[{type:"text",text:`Agent '${n}' is not exposed by this server`}],isError:true};let a=await e.query(n,o,{context:s,threadId:i});return a.ok?{content:[{type:"text",text:a.data}]}:{content:[{type:"text",text:a.error?.message??"Query failed"}],isError:true}}),r.tool("crewx_executeAgent","Execute a task on a CrewX agent (may modify state)",ja,async({agentId:n,task:o,context:s,thread:i})=>{if(!t.has(n))return {content:[{type:"text",text:`Agent '${n}' is not exposed by this server`}],isError:true};let a=await e.execute(n,o,{context:s,threadId:i});return a.ok?{content:[{type:"text",text:a.data}]}:{content:[{type:"text",text:a.error?.message??"Execute failed"}],isError:true}});}g();function Gn(r){return r.headers.get("Origin")?null:new Response(JSON.stringify({error:"Forbidden: Origin header required"}),{status:403,headers:{"Content-Type":"application/json"}})}async function Xn(r,e){return e?await e(r)?null:new Response(JSON.stringify({error:"Unauthorized"}),{status:401,headers:{"Content-Type":"application/json"}}):null}function $a(r,e){let t=new McpServer({name:"crewx-mcp-server",version:"1.0.0"},{capabilities:{tools:{}}});return Kn(t,r,e),t}function Hr(r,e){if(!e.agents||e.agents.length===0)throw new Error("crewx.handler() requires at least one agent in the agents option");let t=new Set(e.agents),n=new Map;return async o=>{let s=Gn(o);if(s)return s;let i=await Xn(o,e.auth);if(i)return i;let a=o.headers.get("mcp-session-id");if(a&&n.has(a))return n.get(a).transport.handleRequest(o);let l=$a(r,t),u=new WebStandardStreamableHTTPServerTransport({sessionIdGenerator:()=>crypto.randomUUID(),onsessioninitialized:d=>{n.set(d,{transport:u,server:l});},onsessionclosed:d=>{n.delete(d);},enableJsonResponse:true});return await l.connect(u),u.handleRequest(o)}}g();g();var ht=class{detach(e){}};g();g();g();var Kt=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(La.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return existsSync(e??this.resolveDbPath())}};g();function we(r){let e=J("better-sqlite3"),{drizzle:t}=J("drizzle-orm/better-sqlite3"),n=new e(r);return n.exec("PRAGMA journal_mode = WAL"),n.exec("PRAGMA busy_timeout = 5000"),n.exec("PRAGMA foreign_keys = ON"),{db:t(n),runRaw:(o,s=[])=>n.prepare(o).run(...s),close:()=>n.close()}}g();var Yn=new Set;function Ua(r){let{migrate:e}=J("drizzle-orm/better-sqlite3/migrator"),t=[ne__default.join(P,"../migrations"),ne__default.join(P,"migrations")],n=t.find(o=>existsSync(ne__default.join(o,"meta/_journal.json")));if(!n)throw new Error(`migrations folder not found. Searched:
41
+ Set CREWX_SDK_TEMPLATES_PATH or pass options.templatesPath.`)}function Ut(){let o=Me();return {yamlPath:join(o,"default.yaml"),dir:o}}l();var le=class extends Error{constructor(e,t){let r=t.length>0?` Available: ${t.join(", ")}`:"";super(`Agent not found: "${e}".${r}`),this.name="AgentNotFoundError";}},go={claude:{id:"claude",provider:"cli/claude"},gemini:{id:"gemini",provider:"cli/gemini"},copilot:{id:"copilot",provider:"cli/copilot"},codex:{id:"codex",provider:"cli/codex"}};function mt(o,e){let t=o.startsWith("@")?o.slice(1):o,r=e.find(s=>s.id===t);if(r)return r;let n=go[t];if(n)return n;throw new le(o,e.map(s=>s.id))}oe();l();function zr(o,e){if(o===void 0||o==="")return e;let t=parseInt(o,10);return Number.isNaN(t)?e:t}function Vr(o=process.env){return {queryMs:zr(o.CREWX_TIMEOUT_QUERY,36e5),executeMs:zr(o.CREWX_TIMEOUT_EXECUTE,36e5)}}l();l();var Oo=[/^ANTHROPIC_/i,/^OPENAI_/i,/^AWS_SECRET/i,/^SLACK_/i,/^GITHUB_TOKEN$/i,/^CREWX_MCP_KEY$/i,/^DATABASE_/i,/^AWS_ACCESS_KEY/i,/^AWS_SESSION_TOKEN$/i,/^GH_TOKEN$/i,/^GH_APP_/i,/^NPM_TOKEN$/i,/^NPM_AUTH/i,/^GOOGLE_APPLICATION/i,/^GCLOUD_/i,/^AZURE_/i,/^ARM_/i,/^DOCKER_PASSWORD$/i,/^DOCKER_AUTH/i,/^SSH_PRIVATE/i,/^SSH_AUTH_SOCK$/i,/^CI_JOB_TOKEN$/i,/^ACTIONS_RUNTIME_TOKEN$/i,/^VAULT_TOKEN$/i,/^SONAR_TOKEN$/i,/^CODECOV_TOKEN$/i,/TOKEN$/i,/SECRET$/i,/PASSWORD$/i,/API_KEY$/i],Mo=/[;|&`$(){}!><\n\r]/,No=2,Do=["*","**","*:*","* *","**/*"];function $o(){let o={};for(let[e,t]of Object.entries(process.env))t!==void 0&&(Oo.some(r=>r.test(e))||(o[e]=t));return o}function Lo(o){if(Mo.test(o))throw new Error(`exec blocked: shell metacharacter detected in "${o}"`)}function jo(o){return /^npx\s+@crewx\/[\w-]+/.test(o)}function Ho(o){if(Do.includes(o.trim()))throw new Error(`exec config error: overly broad pattern "${o}" is not allowed`);if(!/^[\w./@-]/.test(o))throw new Error("exec config error: pattern must start with a command name")}function Uo(o,e){let t=e.allow??[],r=e.deny??[];for(let n of [...t,...r])Ho(n);return r.some(n=>ne(o,n))?false:jo(o)?true:t.some(n=>ne(o,n))}var Kr=false;function qo(o){Kr=o;}function ze(o){if(!Kr)return;let e=JSON.stringify({span:"template_exec",...o,timestamp:new Date().toISOString()});console.error(e);}function Fo(o){let e=[],t="",r=false,n=false;for(let s=0;s<o.length;s++){let i=o[s];i==="'"&&!n?r=!r:i==='"'&&!r?n=!n:i===" "&&!r&&!n?t.length>0&&(e.push(t),t=""):t+=i;}return t.length>0&&e.push(t),e}function Jr(o,e){let t=Date.now(),r=parseInt(process.env.CREWX_EXEC_DEPTH??"0",10);if(isNaN(r)||r>=No)return ze({command:o,status:"denied",reason:"invalid or max recursion depth"}),"(exec blocked: max recursion depth reached)";try{Lo(o);}catch{return ze({command:o,status:"denied",reason:"shell metacharacter detected"}),`(exec blocked: shell metacharacter detected in "${o}")`}if(!Uo(o,e))return ze({command:o,status:"denied",reason:"not in allow list"}),`(exec blocked: ${o})`;try{let n=Fo(o),[s,...i]=n;if(!s)return `(exec failed: ${o})`;let a=$o(),d=execFileSync(s,i,{timeout:e.timeout??5e3,maxBuffer:64*1024,encoding:"utf-8",env:{...a,CREWX_EXEC_DEPTH:String(r+1)},stdio:["pipe","pipe","pipe"]}),c=Date.now()-t;return ze({command:o,status:"allowed",allowed_by:"policy",duration_ms:c}),`<exec-output cmd="${o}">
42
+ ${d.trim()}
43
+ </exec-output>`}catch{return ze({command:o,status:"error",reason:"execution failed"}),`(exec failed: ${o})`}}l();function Xr(o){return o==null?"":String(o)}l();function Qr(o,e){return `\`\`\`${e?.hash?.lang??""}
44
+ ${o??""}
45
+ \`\`\``}l();function Xt(o,e){if(!o)return "";if(o.length<=e)return o;let t=o.length-e;return `${o.substring(0,e)} (...+${t} chars)`}function Qt(o){return Array.isArray(o)||typeof o=="string"?o.length:0}function Gt(o){return typeof o!="string"?"":o.replace(/\{\{/g,"&#123;&#123;").replace(/\}\}/g,"&#125;&#125;")}var Gr=["B","KB","MB","GB"];function Yt(o){if(o===0)return "0 B";let e=Math.min(Math.floor(Math.log(o)/Math.log(1024)),Gr.length-1);return `${Math.round(o/Math.pow(1024,e)*100)/100} ${Gr[e]}`}function Zt(o){if(!o)return "";try{let e=o instanceof Date?o:new Date(o);return isNaN(e.getTime())?"":e.toLocaleString("ko-KR",{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1})}catch{return ""}}var Ve=class{hbs;execPolicy;execEnabled;constructor(e={}){this.hbs=se.create(),this.execPolicy=e.execPolicy??{allow:[],deny:[]},this.execEnabled=e.execEnabled??true,this.registerHelpers();}registerHelpers(){let e=this.hbs,t=this.execPolicy,r=this.execEnabled;e.registerHelper("exec",function(n){return typeof n!="string"?"":r?new e.SafeString(Jr(n,t)):"(exec disabled)"}),e.registerHelper("include",function(n){return new e.SafeString(Xr(n))}),e.registerHelper("fenced_code",function(n,s){return new e.SafeString(Qr(n,s))}),e.registerHelper("eq",function(n,s){return n===s}),e.registerHelper("ne",function(n,s){return n!==s}),e.registerHelper("and",function(n,s){return n&&s}),e.registerHelper("or",function(n,s){return n||s}),e.registerHelper("not",function(n){return !n}),e.registerHelper("contains",function(n,s){return Array.isArray(n)&&n.includes(s)}),e.registerHelper("json",function(n){return JSON.stringify(n,null,2)}),e.registerHelper("truncate",function(n,s){return Xt(n,s)}),e.registerHelper("length",function(n){return Qt(n)}),e.registerHelper("escapeHandlebars",function(n){return new e.SafeString(Gt(n))}),e.registerHelper("formatFileSize",function(n){return Yt(n)}),e.registerHelper("formatTimestamp",function(n){return Zt(n)});}async render(e,t={}){return this.hbs.compile(e,{noEscape:true})(t)}};l();l();var Rt=class{async readFile(e){return readFile(e,"utf-8")}async exists(e){try{return await access(e),!0}catch{return false}}resolvePath(...e){return e.length===1?resolve(e[0]):resolve(join(...e))}isAbsolute(e){return isAbsolute(e)}},er=new Rt;var Ce=class{docs=new Map;fs;constructor(e){this.fs=e??er;}async load(e,t){if(e)for(let[r,n]of Object.entries(e)){let s=n;if(typeof s=="string")this.docs.set(r,{content:s});else if(s&&typeof s=="object"){let i=s;"content"in i&&typeof i.content=="string"?this.docs.set(r,{content:i.content}):"path"in i&&typeof i.path=="string"?await this.loadFromFile(r,i.path,t):console.warn(`[DocumentLoader] Skipping '${r}': unsupported format`);}else console.warn(`[DocumentLoader] Skipping '${r}': unsupported format`);}}async getContent(e){return this.docs.get(e)?.content}async getToc(e){let t=this.docs.get(e);if(!t)return;let r=[];for(let n of t.content.split(`
46
+ `)){let s=/^(#{1,6})\s+(.+)$/.exec(n.trim());s&&r.push({depth:s[1].length,text:s[2].trim()});}if(r.length!==0)return r.map(({depth:n,text:s})=>`${" ".repeat(n-1)}- ${s}`).join(`
47
+ `)}getPath(e){return this.docs.get(e)?.path}getNames(){return Array.from(this.docs.keys())}async buildContext(){let e={};for(let t of this.docs.keys()){let r=await this.getContent(t)??"",n=await this.getToc(t),s=this.getPath(t);e[t]={content:r,toc:n,...s?{path:s}:{}};}return e}async loadFromFile(e,t,r){try{let n=this.resolve(t,r),s=await this.fs.readFile(n);this.docs.set(e,{content:s,path:n});}catch(n){let s=n instanceof Error?n.message:String(n);console.warn(`[DocumentLoader] Failed to load '${e}' from '${t}': ${s}`);}}resolve(e,t){return this.fs.isAbsolute(e)?e:t?this.fs.resolvePath(t,e):this.fs.resolvePath(e)}};l();l();var z=class extends Error{constructor(t,r,n){super(t);this.layoutId=r;this.cause=n;this.name="LayoutLoadError";}layoutId;cause},pe=class extends Error{constructor(t,r=[],n){super(t);this.errors=r;this.cause=n;this.name="PropsValidationError";}errors;cause};var Go={validationMode:"lenient",fallbackLayoutId:"crewx/default"},Ke=class{layouts=new Map;options;constructor(e){this.options={...Go,...e,templatesPath:e?.templatesPath??Me()},this.loadAllLayouts();}load(e,t){let r=this.layouts.get(e);if(!r){let n=this.normalizeLayoutId(e);r=this.layouts.get(n);}if(!r&&(console.warn(`Layout not found: ${e}, falling back to ${this.options.fallbackLayoutId}`),r=this.layouts.get(this.options.fallbackLayoutId),!r))throw new z(`Fallback layout not found: ${this.options.fallbackLayoutId}`,this.options.fallbackLayoutId);return t&&Object.keys(t).length>0?{...r,defaultProps:{...r.defaultProps,...t}}:r}getLayoutIds(){return Array.from(this.layouts.keys())}hasLayout(e){if(this.layouts.has(e))return true;let t=this.normalizeLayoutId(e);return this.layouts.has(t)}reload(){this.layouts.clear(),this.loadAllLayouts();}registerLayout(e,t){if(!e||typeof e!="string")throw new z("Layout ID must be a non-empty string",e);let r=typeof t=="string"?{template:t}:t,n=typeof r.template=="string"?r.template:"";if(!n||n.trim().length===0)throw new z(`Custom layout template is empty for ${e}`,e);let s=r.propsSchema||{},i=this.extractDefaultProps(s),a=r.defaultProps||{},d={id:e,version:r.version||"1.0.0",description:r.description||`Custom layout ${e}`,template:n,propsSchema:this.parsePropsSchema(s),defaultProps:{...i,...a}},c=this.layouts.get(e),u=c?.template===n&&JSON.stringify(c?.defaultProps??{})===JSON.stringify(d.defaultProps??{})&&JSON.stringify(c?.propsSchema??{})===JSON.stringify(d.propsSchema??{});this.layouts.set(e,d),process.env.CREWX_VERBOSE==="1"&&(c?u||console.error(`Updated custom layout: ${e}`):console.error(`Registered custom layout: ${e}`));}registerLayouts(e){for(let[t,r]of Object.entries(e))try{this.registerLayout(t,r);}catch(n){console.warn(`Failed to register custom layout ${t}:`,n instanceof Error?n.message:n);}}loadAllLayouts(){let e=this.options.templatesPath;if(!existsSync(e))throw new z(`Templates directory not found: ${e}`,void 0,new Error(`Directory does not exist: ${e}`));try{let t=readdirSync(e).filter(r=>r.endsWith(".yaml")||r.endsWith(".yml"));t.length===0&&console.warn(`No layout files found in ${e}`);for(let r of t){let n=r.replace(/\.(yaml|yml)$/,""),s=W.join(e,r);try{let i=this.loadLayoutFile(s,n),a=`crewx/${n}`;this.layouts.set(a,i),a!=="crewx/minimal"&&process.env.CREWX_VERBOSE==="1"&&console.error(`Loaded layout: ${a} from ${r}`);}catch(i){console.error(`Failed to load layout file ${r}:`,i);}}process.env.CREWX_VERBOSE==="1"&&console.error(`Loaded ${this.layouts.size} layouts from ${e}`);}catch(t){throw new z(`Failed to read layouts directory: ${e}`,void 0,t instanceof Error?t:new Error(String(t)))}}loadLayoutFile(e,t){try{let r=readFileSync(e,"utf-8");if(!r||r.trim().length===0)throw console.warn(`Empty YAML file: ${e}, will use fallback`),new z(`Empty YAML file: ${e}`,t,new Error("File content is empty"));let n=load(r);if(!n||typeof n!="object")throw console.warn(`Invalid YAML content in ${e} (parsed as ${typeof n}), will use fallback`),new z(`Invalid or empty YAML in ${e}`,t,new Error("YAML parsing returned null/undefined or non-object"));if(n.layouts&&typeof n.layouts=="object"){let s=this.resolveLayoutEntry(n.layouts,t);if(!s||s.template.trim().length===0)throw console.warn(`Empty or missing layout template in ${e} for ${t}`),new z(`Layout template not found or empty in layouts map: ${t}`,t);let i=s.propsSchema||n.propsSchema||{};return {id:`crewx/${t}`,version:n.version||"1.0.0",description:n.description||`CrewX ${t} layout`,template:s.template,propsSchema:this.parsePropsSchema(i),defaultProps:this.extractDefaultProps(i)}}else {if(!n.template||typeof n.template=="string"&&n.template.trim().length===0)throw console.warn(`Empty or missing template field in ${e}`),new z(`Layout template is missing or empty in ${e}`,t);return {id:n.id||`crewx/${t}`,version:n.version||"1.0.0",description:n.description||"",template:n.template,propsSchema:this.parsePropsSchema(n.propsSchema||{}),defaultProps:this.extractDefaultProps(n.propsSchema||{})}}}catch(r){throw new z(`Failed to load layout file: ${e}`,t,r instanceof Error?r:new Error(String(r)))}}parsePropsSchema(e){let t={};for(let[r,n]of Object.entries(e))typeof n=="object"&&n!==null&&(t[r]=n);return t}extractDefaultProps(e){let t={};for(let[r,n]of Object.entries(e))n&&typeof n=="object"&&("defaultValue"in n?t[r]=n.defaultValue:"default"in n&&(t[r]=n.default));return t}normalizeLayoutId(e){return e?e.includes("/")?e:`crewx/${e}`:this.options.fallbackLayoutId}resolveLayoutEntry(e,t){let r=new Set;if(t)if(r.add(t),t.includes("/")){let n=t.split("/"),s=n[n.length-1];s&&r.add(s);}else r.add(`crewx/${t}`);r.add("default");for(let n of r){let s=e[n];if(typeof s=="string"&&s.trim().length>0)return {template:s};if(s&&typeof s=="object"&&typeof s.template=="string"&&s.template.trim().length>0)return {template:s.template,propsSchema:s.propsSchema}}for(let n of Object.values(e)){if(typeof n=="string"&&n.trim().length>0)return {template:n};let s=n;if(s&&typeof s=="object"&&typeof s.template=="string"&&s.template.trim().length>0)return {template:s.template,propsSchema:s.propsSchema}}}};l();l();function Yo(o){return Array.from(new Set(o.filter(e=>e?.isAssistant&&e?.metadata?.agent_id).map(e=>String(e.metadata.agent_id))))}function tn(o,e,t){if(!Array.isArray(o)||o.length===0||!(t&&typeof t.fn=="function"))return "";let n=Yo(o),s=n.length>0?n[0]:"",i={messages:o,platform:typeof e=="string"?e:"",messagesCount:o.length,agentIds:n,primaryAgentId:s};return t.fn(i)}l();var Je=class{defaultMode;constructor(e={}){this.defaultMode=e.defaultMode??"lenient";}validate(e,t,r=this.defaultMode){let n=[],s=this.validateObject(e??{},t,r,["props"],n);if(n.length>0&&r==="strict")throw new pe("Props validation failed in strict mode",n);return {valid:n.length===0,props:s,errors:n}}validateObject(e,t,r,n,s){let i={};if(r==="strict")for(let a of Object.keys(e))t[a]||s.push({path:this.buildPath([...n,a]),message:`Unknown prop '${a}'`,value:e[a]});for(let[a,d]of Object.entries(t)){let c=[...n,a],u=e[a],p=this.resolveProp(u,d,c,r,s);p.shouldAssign&&(i[a]=p.value);}return i}resolveProp(e,t,r,n,s){let i=this.buildPath(r);if(this.isNil(e)){if(t.isRequired&&s.push({path:i,message:`Required prop '${r[r.length-1]}' is missing`}),t.defaultValue!==void 0)return {shouldAssign:true,value:this.cloneValue(t.defaultValue)};if(t.type==="shape"&&t.shape){let d=this.applyDefaults(t.shape);if(Object.keys(d).length>0)return {shouldAssign:true,value:d}}return {shouldAssign:false}}let a=this.validateType(e,t,r,n,s);if(!a.valid){if(t.type==="shape"&&a.value&&this.isPlainObject(a.value))return {shouldAssign:true,value:a.value};if(s.push({path:i,message:a.error??"Invalid value",value:e}),t.defaultValue!==void 0)return {shouldAssign:true,value:this.cloneValue(t.defaultValue)};if(t.type==="shape"&&t.shape){let d=this.applyDefaults(t.shape);if(Object.keys(d).length>0)return {shouldAssign:true,value:d}}return {shouldAssign:false}}return {shouldAssign:true,value:a.value}}validateType(e,t,r,n,s){let{type:i}=t;switch(i){case "string":return this.validateString(e,t);case "number":return this.validateNumber(e,t);case "bool":return this.validateBoolean(e);case "array":return this.validateArray(e,t);case "arrayOf":return this.validateArrayOf(e,t,r,n,s);case "object":return this.validatePlainObject(e);case "shape":return this.validateShape(e,t,r,n,s);case "oneOfType":return this.validateOneOfType(e,t);case "func":return this.validateFunction(e);case "node":return {valid:true,value:e};default:return {valid:true,value:e}}}validateString(e,t){return typeof e!="string"?{valid:false,error:`Expected string, got ${this.describeType(e)}`}:t.oneOf&&!t.oneOf.includes(e)?{valid:false,error:`Expected one of: ${t.oneOf.join(", ")}`}:t.minLength!==void 0&&e.length<t.minLength?{valid:false,error:`String length must be >= ${t.minLength}`}:t.maxLength!==void 0&&e.length>t.maxLength?{valid:false,error:`String length must be <= ${t.maxLength}`}:t.pattern&&!new RegExp(t.pattern).test(e)?{valid:false,error:`String does not match pattern ${t.pattern}`}:{valid:true,value:e}}validateNumber(e,t){return typeof e!="number"||Number.isNaN(e)?{valid:false,error:`Expected number, got ${this.describeType(e)}`}:t.min!==void 0&&e<t.min?{valid:false,error:`Number must be >= ${t.min}`}:t.max!==void 0&&e>t.max?{valid:false,error:`Number must be <= ${t.max}`}:t.oneOf&&!t.oneOf.includes(e)?{valid:false,error:`Expected one of: ${t.oneOf.join(", ")}`}:{valid:true,value:e}}validateBoolean(e){return typeof e!="boolean"?{valid:false,error:`Expected boolean, got ${this.describeType(e)}`}:{valid:true,value:e}}validateArray(e,t){return Array.isArray(e)?t.minLength!==void 0&&e.length<t.minLength?{valid:false,error:`Array length must be >= ${t.minLength}`}:t.maxLength!==void 0&&e.length>t.maxLength?{valid:false,error:`Array length must be <= ${t.maxLength}`}:{valid:true,value:[...e]}:{valid:false,error:`Expected array, got ${this.describeType(e)}`}}validateArrayOf(e,t,r,n,s){let i=this.validateArray(e,t);if(!i.valid)return i;let a=[],d=t.itemType,c=t.itemOneOf,u=s.length;return i.value.forEach((p,f)=>{let y=[...r,String(f)];if(d){let h=this.validateType(p,{type:d},y,n,s);h.valid?a.push(h.value):s.push({path:this.buildPath(y),message:h.error??"Invalid array item",value:p});}else a.push(p);c&&!c.includes(p)&&s.push({path:this.buildPath(y),message:`Array item must be one of: ${c.join(", ")}`,value:p});}),{valid:s.length===u,value:a}}validatePlainObject(e){return this.isPlainObject(e)?{valid:true,value:{...e}}:{valid:false,error:`Expected object, got ${this.describeType(e)}`}}validateFunction(e){return typeof e!="function"?{valid:false,error:`Expected function, got ${this.describeType(e)}`}:{valid:true,value:e}}validateShape(e,t,r,n,s){if(!this.isPlainObject(e))return {valid:false,error:`Expected object, got ${this.describeType(e)}`};let i=s.length,a=this.validateObject(e,t.shape??{},n,r,s);return {valid:s.length===i,value:a}}validateOneOfType(e,t){let r=t.types??[];return r.some(s=>this.matchesType(e,s))?{valid:true,value:e}:{valid:false,error:`Value does not match any allowed type: ${r.join(", ")}`}}matchesType(e,t){switch(t){case "string":return typeof e=="string";case "number":return typeof e=="number"&&!Number.isNaN(e);case "bool":case "boolean":return typeof e=="boolean";case "array":return Array.isArray(e);case "object":return this.isPlainObject(e);case "func":case "function":return typeof e=="function";case "shape":return this.isPlainObject(e);case "node":return e==null||typeof e!="symbol";default:return true}}applyDefaults(e){let t={};for(let[r,n]of Object.entries(e)){if(n.defaultValue!==void 0){t[r]=this.cloneValue(n.defaultValue);continue}if(n.type==="shape"&&n.shape){let s=this.applyDefaults(n.shape);Object.keys(s).length>0&&(t[r]=s);}}return t}cloneValue(e){if(Array.isArray(e))return e.map(t=>this.cloneValue(t));if(this.isPlainObject(e)){let t={};for(let[r,n]of Object.entries(e))t[r]=this.cloneValue(n);return t}return e}isPlainObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}isNil(e){return e==null}buildPath(e){return e.join(".")}describeType(e){return Array.isArray(e)?"array":e===null?"null":typeof e}};var Xe=class{handlebars;propsValidator;constructor(e){this.handlebars=se__default.create(),this.propsValidator=e??new Je,this.registerHelpers();}render(e,t,r={}){try{let n=this.prepareRenderContext(e,t,r);return this.handlebars.compile(e.template,{noEscape:!0})(n)}catch(n){throw n instanceof Error?new Error(`Template rendering failed for layout '${e.id}': ${n.message}`):new Error(`Unknown error rendering layout '${e.id}'`)}}validate(e,t,r="lenient"){return this.executeValidation(e,t,r)}resolveProps(e,t,r="lenient"){let n=this.mergeProps(e.defaultProps,t);return !e.propsSchema||Object.keys(e.propsSchema).length===0?{valid:true,props:n,errors:[]}:this.executeValidation(n,e.propsSchema,r)}prepareRenderContext(e,t,r){let{validationMode:n="lenient",skipValidation:s=false}=r,i=s?this.mergeProps(e.defaultProps,t.props):this.resolveProps(e,t.props,n).props;return {...t,vars:this.sanitizeVars(t.vars),props:i}}registerHelpers(){this.handlebars.registerHelper("formatConversation",tn),se__default.helpers.each&&this.handlebars.registerHelper("each",se__default.helpers.each),se__default.helpers.if&&this.handlebars.registerHelper("if",se__default.helpers.if),se__default.helpers.unless&&this.handlebars.registerHelper("unless",se__default.helpers.unless),se__default.helpers.with&&this.handlebars.registerHelper("with",se__default.helpers.with),this.handlebars.registerHelper("eq",function(e,t){return e===t}),this.handlebars.registerHelper("ne",function(e,t){return e!==t}),this.handlebars.registerHelper("gt",function(e,t){return e>t}),this.handlebars.registerHelper("lt",function(e,t){return e<t}),this.handlebars.registerHelper("json",function(e){return new se__default.SafeString(JSON.stringify(e))}),this.handlebars.registerHelper("raw",function(e){return typeof e?.fn=="function"?e.fn(this):""}),this.handlebars.registerHelper("escapeHandlebars",function(e){return typeof e!="string"?"":e.replace(/\{\{/g,"&#123;&#123;").replace(/\}\}/g,"&#125;&#125;")}),this.handlebars.registerHelper("formatFileSize",function(e){if(e===0)return "0 B";let t=["B","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(1024));return Math.round(e/Math.pow(1024,r)*100)/100+" "+t[r]});}executeValidation(e,t,r){try{return this.propsValidator.validate(e,t,r)}catch(n){if(n instanceof pe&&n.errors&&n.errors.length>0){let s=n.errors[0];if(s)throw new pe(s.message,n.errors)}throw n}}mergeProps(e,t){let r=this.cloneDeep(e??{});return t?this.deepMerge(r,t):r}deepMerge(e,t){for(let[r,n]of Object.entries(t)){if(this.isPlainObject(n)){let s=e[r];e[r]=this.deepMerge(this.isPlainObject(s)?s:{},n);continue}if(Array.isArray(n)){e[r]=this.cloneDeep(n);continue}e[r]=n;}return e}cloneDeep(e){if(Array.isArray(e))return e.map(t=>this.cloneDeep(t));if(this.isPlainObject(e)){let t={};for(let[r,n]of Object.entries(e))t[r]=this.cloneDeep(n);return t}return e}isPlainObject(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}sanitizeVars(e){if(!e)return {};let t={...e};if(typeof e.user_input=="string"){t.user_input_raw=e.user_input;let r=e.user_input.replace(/\{\{\{/g,"&#123;&#123;&#123;").replace(/\}\}\}/g,"&#125;&#125;&#125;").replace(/\{\{/g,"&#123;&#123;").replace(/\}\}/g,"&#125;&#125;");t.user_input=this.handlebars.escapeExpression(r);}return t}};l();var tr="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Zo(o){let e=randomBytes(o*2),t="";for(let r=0;r<e.length&&t.length<o;r++){let n=e[r];n<248&&(t+=tr[n%62]);}for(;t.length<o;)t+=tr[randomBytes(1)[0]%62];return t}function be(o){return `${o}_${Zo(8)}`}function es(o,e){let{createHash:t}=B("crypto"),r=t("sha256").update(e).digest(),n=Buffer.alloc(8);for(let i=0;i<32;i++)n[i%8]^=r[i];let s="";for(let i of n)s+=tr[i%62];return `${o}_${s}`}l();function rr(o){let e=t=>String(t).padStart(2,"0");return `${o.getFullYear()}${e(o.getMonth()+1)}${e(o.getDate())}T${e(o.getHours())}${e(o.getMinutes())}${e(o.getSeconds())}`}l();function nn(o,e){return t=>{try{let r=e(t);r instanceof Promise&&r.catch(n=>{console.error(`[crewx] event listener error (${o}): ${n instanceof Error?n.message:String(n)}`);});}catch(r){console.error(`[crewx] event listener error (${o}): ${r instanceof Error?r.message:String(r)}`);}}}var Qe=class{_emitter=new EventEmitter;on(e,t){let r=nn(e,t);return this._emitter.on(e,r),()=>this._emitter.off(e,r)}once(e,t){let r=nn(e,t);return this._emitter.once(e,r),()=>this._emitter.off(e,r)}emit(e,t){this._emitter.emit(e,t);}};l();function nr(o){let e=new Map,t=r=>r.startsWith(`${o}::`)?r:`${o}::${r}`;return {async get(r){let n=e.get(t(r));return n?n.value:void 0},async set(r,n){e.set(t(r),{value:n});},async delete(r){return e.delete(t(r))},async list(r){let n=r?t(r):`${o}::`,s=[];for(let i of e.keys())i.startsWith(n)&&s.push(i.slice(o.length+2));return s}}}l();var or=new AsyncLocalStorage;function ns(){return or}function os(o,e){return or.run(o,e)}function sr(o){let e=o.log??o.logger??{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},t=o.agentRunner??{run:async()=>({output:""})},r=o.db??{get:async()=>{},set:async()=>{},delete:async()=>false,list:async()=>[]},n=o.storage??{put:async()=>"",get:async()=>{},delete:async()=>false},s=o.audit??{log:async()=>{}},i=o.onInbound??(async()=>({accepted:true})),a=o.onEmitEvent??(async()=>({accepted:true})),d=o.onUpdateMessage??(async()=>{}),c=o.onResolveUser??(async f=>({userId:f,displayName:f})),u=async f=>{let y=or.getStore();if(!y){e.warn("respondSync called outside sync window \u2014 graceful degradation (no-op)",{textPreview:typeof f=="object"&&"text"in f?f.text.slice(0,80):void 0});return}let h="text"in f?f.text:"";y.res.status(200).json({text:h});},p=o.httpRouter??{registerRoute:()=>{e.warn("httpRouter not configured \u2014 registerRoute is a no-op");}};return {instanceId:o.instanceId,config:o.config,capabilities:o.capabilities,log:e,agentRunner:t,db:r,storage:n,audit:s,abortSignal:o.abortSignal??new AbortController().signal,httpRouter:p,inbound:i,emitEvent:a,updateMessage:d,resolveUser:c,respondSync:u}}Le();Le();l();function ss(o){return typeof o!="string"?"":o.replace(/</g,"&lt;").replace(/>/g,"&gt;")}function ir(o){return o.messages.map(e=>({text:ss(e.text),isAssistant:e.isAssistant,metadata:e.metadata,files:void 0}))}l();l();var is={agentId:z$1.string().describe("The agent ID to query"),query:z$1.string().describe("The query message to send"),context:z$1.string().optional().describe("Additional context"),thread:z$1.string().optional().describe("Thread ID for conversation continuity")},as={agentId:z$1.string().describe("The agent ID to execute"),task:z$1.string().describe("The task description to execute"),context:z$1.string().optional().describe("Additional context"),thread:z$1.string().optional().describe("Thread ID for conversation continuity")};function on(o,e,t){o.tool("crewx_listAgents","List available CrewX agents exposed by this server",async()=>{let r=[];for(let n of t){let s=e.agents.get(n);s&&r.push({id:s.id,name:s.name??s.id,description:s.description??""});}return {content:[{type:"text",text:JSON.stringify(r,null,2)}]}}),o.tool("crewx_queryAgent","Query a CrewX agent with a read-only question",is,async({agentId:r,query:n,context:s,thread:i})=>{if(!t.has(r))return {content:[{type:"text",text:`Agent '${r}' is not exposed by this server`}],isError:true};let a=await e.query(r,n,{context:s,threadId:i});return a.ok?{content:[{type:"text",text:a.data}]}:{content:[{type:"text",text:a.error?.message??"Query failed"}],isError:true}}),o.tool("crewx_executeAgent","Execute a task on a CrewX agent (may modify state)",as,async({agentId:r,task:n,context:s,thread:i})=>{if(!t.has(r))return {content:[{type:"text",text:`Agent '${r}' is not exposed by this server`}],isError:true};let a=await e.execute(r,n,{context:s,threadId:i});return a.ok?{content:[{type:"text",text:a.data}]}:{content:[{type:"text",text:a.error?.message??"Execute failed"}],isError:true}});}l();function sn(o){return o.headers.get("Origin")?null:new Response(JSON.stringify({error:"Forbidden: Origin header required"}),{status:403,headers:{"Content-Type":"application/json"}})}async function an(o,e){return e?await e(o)?null:new Response(JSON.stringify({error:"Unauthorized"}),{status:401,headers:{"Content-Type":"application/json"}}):null}function cs(o,e){let t=new McpServer({name:"crewx-mcp-server",version:"1.0.0"},{capabilities:{tools:{}}});return on(t,o,e),t}function ar(o,e){if(!e.agents||e.agents.length===0)throw new Error("crewx.handler() requires at least one agent in the agents option");let t=new Set(e.agents),r=new Map;return async n=>{let s=sn(n);if(s)return s;let i=await an(n,e.auth);if(i)return i;let a=n.headers.get("mcp-session-id");if(a&&r.has(a))return r.get(a).transport.handleRequest(n);let d=cs(o,t),c=new WebStandardStreamableHTTPServerTransport({sessionIdGenerator:()=>crypto.randomUUID(),onsessioninitialized:u=>{r.set(u,{transport:c,server:d});},onsessionclosed:u=>{r.delete(u);},enableJsonResponse:true});return await d.connect(c),c.handleRequest(n)}}l();l();var Ge=class{detach(e){}};l();l();l();var Pt=class{resolveDbPath(){return process.env.CREWX_DB?process.env.CREWX_DB:process.env.CREWX_TRACES_DB?process.env.CREWX_TRACES_DB:join(gs.homedir(),".crewx","crewx.db")}resolveDbPaths(){return [this.resolveDbPath()]}isMissingTableError(e){return e instanceof Error&&/no such table:/i.test(e.message)}dbExists(e){return existsSync(e??this.resolveDbPath())}};l();function ie(o){let e=B("better-sqlite3"),{drizzle:t}=B("drizzle-orm/better-sqlite3"),r=new e(o);return r.exec("PRAGMA journal_mode = WAL"),r.exec("PRAGMA busy_timeout = 5000"),r.exec("PRAGMA foreign_keys = ON"),{db:t(r),runRaw:(n,s=[])=>r.prepare(n).run(...s),close:()=>r.close()}}l();var dn=new Set;function fs(o){let{migrate:e}=B("drizzle-orm/better-sqlite3/migrator"),t=[W__default.join(g,"../migrations"),W__default.join(g,"migrations")],r=t.find(n=>existsSync(W__default.join(n,"meta/_journal.json")));if(!r)throw new Error(`migrations folder not found. Searched:
61
48
  ${t.join(`
62
- `)}`);e(r,{migrationsFolder:n});}function Qn(r,e){Yn.has(e)||(Ua(r),Yn.add(e));}g();var G=class extends Error{code;cause;constructor(e,t,n){super(t),this.name="RepositoryError",this.code=e,this.cause=n,Object.setPrototypeOf(this,new.target.prototype);}};g();g();var rt=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});g();var q=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),workspace_name:text("workspace_name"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_name:text("project_name"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0)},r=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(r.agent_id),idx_tasks_status:index("idx_tasks_status").on(r.status),idx_tasks_started_at:index("idx_tasks_started_at").on(r.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(r.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(r.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(r.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(r.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(r.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(r.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(r.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(r.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(r.workspace_id,r.started_at)}));g();var N=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>rt.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0)},r=>({idx_threads_updated_at:index("idx_threads_updated_at").on(r.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(r.workspace_id)}));g();var Ya=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>q.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>Ya.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},r=>({idx_spans_task_id:index("idx_spans_task_id").on(r.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(r.parent_span_id)}));g();sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").notNull().references(()=>q.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},r=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(r.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(r.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(r.timestamp)}));g();sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>N.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},r=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(r.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(r.thread_id,r.seq),uniq_thread_boxes_thread_seq:unique().on(r.thread_id,r.seq)}));g();sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},r=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(r.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(r.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(r.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(r.partition_key)}));var Qt=class extends Kt{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let o=dirname(t);existsSync(o)||mkdirSync(o,{recursive:true});}else if(!existsSync(t))throw new G("NOT_FOUND","Database not found");let n=we(t);if(e)try{Qn(n.db,t);}catch(o){throw n.close(),o}return n}validateWorkspaceId(e,t){return e.db.select({id:rt.id}).from(rt).where(eq(rt.id,t)).limit(1).get()?t:null}findAllThreads(e){let t=this.resolveDbPaths(),n=new Set,o=[];for(let s of t){if(!existsSync(s))continue;let i=we(s);try{let a=e?or(eq(N.workspace_id,e),isNull(N.workspace_id)):void 0,l=i.db.select().from(N).where(a).orderBy(desc(N.updated_at)).all();for(let u of l)n.has(u.id)||(n.add(u.id),o.push(u));}catch(a){throw new G("DB_ERROR","Failed to find all threads",a)}finally{i.close();}}return o}findThreadById(e,t){let n=this.resolveDbPaths();for(let o of n){if(!existsSync(o))continue;let s=we(o);try{let i=eq(N.id,e),a=t?and(i,or(eq(N.workspace_id,t),isNull(N.workspace_id))):i,l=s.db.select().from(N).where(a).limit(1).get()??void 0;if(l)return l}catch(i){throw new G("DB_ERROR","Failed to find thread by id",i)}finally{s.close();}}}threadExists(e,t){let n=this.resolveDbPaths();for(let o of n){if(!existsSync(o))continue;let s=we(o);try{let i=eq(N.id,e),a=t?and(i,or(eq(N.workspace_id,t),isNull(N.workspace_id))):i;if(s.db.select({id:N.id}).from(N).where(a).limit(1).get())return !0}catch(i){throw new G("DB_ERROR","Failed to check thread existence",i)}finally{s.close();}}return false}aggregateTaskStats(e,t){let n=this.resolveDbPaths(),o=0,s=0,i=0,a=0,l=0,u=new Set;for(let d of n){if(!existsSync(d))continue;let c=we(d);try{let p=and(eq(q.thread_id,e),or(isNull(q.parent_task_id),eq(q.parent_task_id,""))),f=t?and(p,eq(q.workspace_id,t)):p,v=c.db.select({cnt:sql`count(*)`,total_input:sql`COALESCE(SUM(input_tokens), 0)`,total_output:sql`COALESCE(SUM(output_tokens), 0)`,total_cached:sql`COALESCE(SUM(cached_input_tokens), 0)`,total_cost:sql`COALESCE(SUM(cost_usd), 0)`}).from(q).where(f).get();v&&(o+=v.cnt,s+=v.total_input,i+=v.total_output,a+=v.total_cached,l+=v.total_cost);let h=c.db.all(sql`
49
+ `)}`);e(o,{migrationsFolder:r});}function ln(o,e){dn.has(e)||(fs(o),dn.add(e));}l();var j=class extends Error{code;cause;constructor(e,t,r){super(t),this.name="RepositoryError",this.code=e,this.cause=r,Object.setPrototypeOf(this,new.target.prototype);}};l();l();var je=sqliteTable("workspaces",{id:text("id").primaryKey(),slug:text("slug").notNull().unique(),name:text("name").notNull(),workspace_path:text("workspace_path"),description:text("description"),is_active:integer("is_active").notNull().default(1),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull()});l();var I=sqliteTable("tasks",{id:text("id").primaryKey(),agent_id:text("agent_id").notNull(),user_id:text("user_id"),prompt:text("prompt").notNull(),mode:text("mode").notNull().default("execute"),status:text("status").notNull().default("running"),result:text("result"),error:text("error"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),metadata:text("metadata"),workspace_id:text("workspace_id"),workspace_name:text("workspace_name"),trace_id:text("trace_id"),parent_task_id:text("parent_task_id"),caller_agent_id:text("caller_agent_id"),model:text("model"),platform:text("platform").default("cli"),crewx_version:text("crewx_version"),input_tokens:integer("input_tokens").default(0),output_tokens:integer("output_tokens").default(0),cost_usd:real("cost_usd").default(0),pid:integer("pid"),rendered_prompt:text("rendered_prompt"),command:text("command"),coding_agent_command:text("coding_agent_command"),exit_code:integer("exit_code"),logs:text("logs"),thread_id:text("thread_id"),workspace_ref:text("workspace_ref"),project_id:text("project_id"),project_name:text("project_name"),project_ref:text("project_ref"),cached_input_tokens:integer("cached_input_tokens").default(0)},o=>({idx_tasks_agent_id:index("idx_tasks_agent_id").on(o.agent_id),idx_tasks_status:index("idx_tasks_status").on(o.status),idx_tasks_started_at:index("idx_tasks_started_at").on(o.started_at),idx_tasks_trace_id:index("idx_tasks_trace_id").on(o.trace_id),idx_tasks_parent_task_id:index("idx_tasks_parent_task_id").on(o.parent_task_id),idx_tasks_crewx_version:index("idx_tasks_crewx_version").on(o.crewx_version),idx_tasks_pid:index("idx_tasks_pid").on(o.pid),idx_tasks_thread_id:index("idx_tasks_thread_id").on(o.thread_id),idx_tasks_workspace_id:index("idx_tasks_workspace_id").on(o.workspace_id),idx_tasks_workspace_ref:index("idx_tasks_workspace_ref").on(o.workspace_ref),idx_tasks_project_id:index("idx_tasks_project_id").on(o.project_id),idx_tasks_ws_started:index("idx_tasks_ws_started").on(o.workspace_id,o.started_at)}));l();var A=sqliteTable("threads",{id:text("id").primaryKey(),workspace_id:text("workspace_id").references(()=>je.id,{onDelete:"set null"}),platform:text("platform").notNull().default("cli"),title:text("title"),first_message:text("first_message"),last_message:text("last_message"),message_count:integer("message_count").notNull().default(0),created_at:text("created_at").notNull(),updated_at:text("updated_at").notNull(),metadata:text("metadata"),title_locked:integer("title_locked").notNull().default(0)},o=>({idx_threads_updated_at:index("idx_threads_updated_at").on(o.updated_at),idx_threads_workspace_id:index("idx_threads_workspace_id").on(o.workspace_id)}));l();var Rs=sqliteTable("spans",{id:text("id").primaryKey(),task_id:text("task_id").references(()=>I.id,{onDelete:"set null"}),parent_span_id:text("parent_span_id").references(()=>Rs.id,{onDelete:"set null"}),name:text("name").notNull(),kind:text("kind").notNull().default("internal"),status:text("status").notNull().default("ok"),started_at:text("started_at").notNull(),completed_at:text("completed_at"),duration_ms:integer("duration_ms"),input:text("input"),output:text("output"),error:text("error"),attributes:text("attributes")},o=>({idx_spans_task_id:index("idx_spans_task_id").on(o.task_id),idx_spans_parent_span_id:index("idx_spans_parent_span_id").on(o.parent_span_id)}));l();sqliteTable("tool_calls",{id:text("id").primaryKey(),task_id:text("task_id").notNull().references(()=>I.id,{onDelete:"cascade"}),session_id:text("session_id"),tool_name:text("tool_name").notNull(),files:text("files"),input:text("input"),output:text("output"),duration_ms:integer("duration_ms"),timestamp:text("timestamp").notNull()},o=>({idx_tool_calls_task_id:index("idx_tool_calls_task_id").on(o.task_id),idx_tool_calls_tool_name:index("idx_tool_calls_tool_name").on(o.tool_name),idx_tool_calls_timestamp:index("idx_tool_calls_timestamp").on(o.timestamp)}));l();sqliteTable("thread_boxes",{id:text("id").primaryKey(),thread_id:text("thread_id").notNull().references(()=>A.id,{onDelete:"cascade"}),seq:integer("seq").notNull(),first_task_id:text("first_task_id").notNull(),mid_task_id:text("mid_task_id").notNull(),last_task_id:text("last_task_id").notNull(),task_count:integer("task_count").notNull(),summary:text("summary"),source_tokens:integer("source_tokens").notNull(),summary_tokens:integer("summary_tokens"),created_at:text("created_at").notNull()},o=>({idx_thread_boxes_thread_id:index("idx_thread_boxes_thread_id").on(o.thread_id),idx_thread_boxes_seq:index("idx_thread_boxes_seq").on(o.thread_id,o.seq),uniq_thread_boxes_thread_seq:unique().on(o.thread_id,o.seq)}));l();sqliteTable("request_logs",{id:text("id").primaryKey(),path:text("path").notNull(),method:text("method").notNull(),status_code:integer("status_code").notNull(),duration_ms:integer("duration_ms").notNull(),ip:text("ip"),request_headers:text("request_headers"),response_headers:text("response_headers"),request_body:text("request_body"),response_body:text("response_body"),query:text("query"),user_id:text("user_id"),project_id:text("project_id"),partition_key:text("partition_key").notNull(),timestamp:text("timestamp").notNull().default(sql`(datetime('now'))`),metadata:text("metadata")},o=>({idx_request_logs_timestamp:index("idx_request_logs_timestamp").on(o.timestamp),idx_request_logs_path:index("idx_request_logs_path").on(o.path),idx_request_logs_status_code:index("idx_request_logs_status_code").on(o.status_code),idx_request_logs_partition_key:index("idx_request_logs_partition_key").on(o.partition_key)}));var Tt=class extends Pt{dbPath;constructor(e={}){super(),e.dbPath?this.dbPath=e.dbPath:e.dbRoot&&(this.dbPath=join(e.dbRoot,".crewx","crewx.db"));}resolveDbPath(){return this.dbPath?this.dbPath:super.resolveDbPath()}openHandle(e){let t=this.resolveDbPath();if(e){let n=dirname(t);existsSync(n)||mkdirSync(n,{recursive:true});}else if(!existsSync(t))throw new j("NOT_FOUND","Database not found");let r=ie(t);if(e)try{ln(r.db,t);}catch(n){throw r.close(),n}return r}validateWorkspaceId(e,t){return e.db.select({id:je.id}).from(je).where(eq(je.id,t)).limit(1).get()?t:null}findAllThreads(e){let t=this.resolveDbPaths(),r=new Set,n=[];for(let s of t){if(!existsSync(s))continue;let i=ie(s);try{let a=e?or$1(eq(A.workspace_id,e),isNull(A.workspace_id)):void 0,d=i.db.select().from(A).where(a).orderBy(desc(A.updated_at)).all();for(let c of d)r.has(c.id)||(r.add(c.id),n.push(c));}catch(a){throw new j("DB_ERROR","Failed to find all threads",a)}finally{i.close();}}return n}findThreadById(e,t){let r=this.resolveDbPaths();for(let n of r){if(!existsSync(n))continue;let s=ie(n);try{let i=eq(A.id,e),a=t?and(i,or$1(eq(A.workspace_id,t),isNull(A.workspace_id))):i,d=s.db.select().from(A).where(a).limit(1).get()??void 0;if(d)return d}catch(i){throw new j("DB_ERROR","Failed to find thread by id",i)}finally{s.close();}}}threadExists(e,t){let r=this.resolveDbPaths();for(let n of r){if(!existsSync(n))continue;let s=ie(n);try{let i=eq(A.id,e),a=t?and(i,or$1(eq(A.workspace_id,t),isNull(A.workspace_id))):i;if(s.db.select({id:A.id}).from(A).where(a).limit(1).get())return !0}catch(i){throw new j("DB_ERROR","Failed to check thread existence",i)}finally{s.close();}}return false}aggregateTaskStats(e,t){let r=this.resolveDbPaths(),n=0,s=0,i=0,a=0,d=0,c=new Set;for(let u of r){if(!existsSync(u))continue;let p=ie(u);try{let f=and(eq(I.thread_id,e),or$1(isNull(I.parent_task_id),eq(I.parent_task_id,""))),y=t?and(f,eq(I.workspace_id,t)):f,h=p.db.select({cnt:sql`count(*)`,total_input:sql`COALESCE(SUM(input_tokens), 0)`,total_output:sql`COALESCE(SUM(output_tokens), 0)`,total_cached:sql`COALESCE(SUM(cached_input_tokens), 0)`,total_cost:sql`COALESCE(SUM(cost_usd), 0)`}).from(I).where(y).get();h&&(n+=h.cnt,s+=h.total_input,i+=h.total_output,a+=h.total_cached,d+=h.total_cost);let x=p.db.all(sql`
63
50
  SELECT DISTINCT agent_id FROM tasks
64
51
  WHERE thread_id = ${e}
65
52
  AND agent_id IS NOT NULL AND agent_id != ''
66
53
  AND (parent_task_id IS NULL OR parent_task_id = '')
67
54
  ${t?sql`AND workspace_id = ${t}`:sql``}
68
- `);for(let m of h)u.add(m.agent_id);}catch(p){throw new G("DB_ERROR","Failed to aggregate task stats",p)}finally{c.close();}}return {taskCount:o,inputTokens:s,outputTokens:i,cachedInputTokens:a,costUsd:l,agentIds:Array.from(u)}}findTopLevelTasks(e,t){let n=this.resolveDbPaths(),o=new Set,s=[];for(let i of n){if(!existsSync(i))continue;let a=we(i);try{let l=and(eq(q.thread_id,e),or(isNull(q.parent_task_id),eq(q.parent_task_id,""))),u=t?and(l,eq(q.workspace_id,t)):l,d=a.db.select().from(q).where(u).orderBy(asc(q.started_at)).all();for(let c of d)o.has(c.id)||(o.add(c.id),s.push(c));}catch(l){throw new G("DB_ERROR","Failed to find top-level tasks",l)}finally{a.close();}}return s}findAllTasks(e,t){let n=this.resolveDbPaths(),o=new Set,s=[];for(let i of n){if(!existsSync(i))continue;let a=we(i);try{let l=eq(q.thread_id,e),u=t?and(l,eq(q.workspace_id,t)):l,d=a.db.select().from(q).where(u).orderBy(asc(q.started_at)).all();for(let c of d)o.has(c.id)||(o.add(c.id),s.push(c));}catch(l){throw new G("DB_ERROR","Failed to find all tasks for thread",l)}finally{a.close();}}return s}findTaskById(e,t,n){let o=this.resolveDbPaths();for(let s of o){if(!existsSync(s))continue;let i=we(s);try{let a=and(eq(q.id,t),eq(q.thread_id,e)),l=n?and(a,eq(q.workspace_id,n)):a,u=i.db.select().from(q).where(l).limit(1).get();if(!u)continue;let d=i.db.select().from(q).where(eq(q.parent_task_id,u.id)).orderBy(asc(q.started_at)).all();return {task:u,children:d}}catch(a){throw new G("DB_ERROR","Failed to find task by id",a)}finally{i.close();}}}batchFetchTasks(e,t){let n=new Map;if(e.length===0)return n;let o=this.resolveDbPaths();for(let s of o){if(!existsSync(s))continue;let i=we(s);try{let a=and(inArray(q.thread_id,e),or(isNull(q.parent_task_id),eq(q.parent_task_id,""))),l=t?and(a,eq(q.workspace_id,t)):a,u=i.db.select().from(q).where(l).orderBy(asc(q.started_at)).all();for(let d of u){let c=d.thread_id;n.has(c)||n.set(c,[]),n.get(c).push(d);}}catch(a){throw new G("DB_ERROR","Failed to batch fetch tasks",a)}finally{i.close();}}return n}updateThreadTitle(e,t,n){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=eq(N.id,e),i=n?and(s,or(eq(N.workspace_id,n),isNull(N.workspace_id))):s;if(!o.db.select({id:N.id}).from(N).where(i).limit(1).get())return;o.db.update(N).set({title:t,title_locked:1,updated_at:new Date().toISOString()}).where(eq(N.id,e)).run();}catch(s){throw s instanceof G?s:new G("DB_ERROR","Failed to update thread title",s)}finally{o.close();}}upsertThread(e,t){let n=this.openHandle(true);try{let o=t.workspaceId?this.validateWorkspaceId(n,t.workspaceId):null,s=new Date().toISOString();if(n.db.select({id:N.id,message_count:N.message_count}).from(N).where(eq(N.id,e)).limit(1).get()){let a={updated_at:s};t.title!==void 0&&(a.title=t.title),t.titleLocked!==void 0&&(a.title_locked=t.titleLocked?1:0),n.db.update(N).set(a).where(eq(N.id,e)).run();}else n.db.insert(N).values({id:e,platform:t.platform,workspace_id:o,title:t.title??null,title_locked:t.titleLocked?1:0,message_count:0,created_at:s,updated_at:s}).run();}catch(o){throw o instanceof G?o:new G("DB_ERROR","Failed to upsert thread",o)}finally{n.close();}}ensureThread(e,t,n){let o=this.openHandle(true);try{let s=n?this.validateWorkspaceId(o,n):null,i=o.db.select({id:N.id,platform:N.platform,workspace_id:N.workspace_id}).from(N).where(eq(N.id,e)).limit(1).get();if(i){s&&!i.workspace_id&&o.db.update(N).set({workspace_id:s}).where(eq(N.id,e)).run();return}let a=new Date().toISOString();o.db.insert(N).values({id:e,platform:t,workspace_id:s,message_count:0,created_at:a,updated_at:a}).run();}catch(s){throw s instanceof G?s:new G("DB_ERROR","Failed to ensure thread",s)}finally{o.close();}}saveUserMessage(e,t,n){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString();o.db.run(sql`
55
+ `);for(let w of x)c.add(w.agent_id);}catch(f){throw new j("DB_ERROR","Failed to aggregate task stats",f)}finally{p.close();}}return {taskCount:n,inputTokens:s,outputTokens:i,cachedInputTokens:a,costUsd:d,agentIds:Array.from(c)}}findTopLevelTasks(e,t){let r=this.resolveDbPaths(),n=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let a=ie(i);try{let d=and(eq(I.thread_id,e),or$1(isNull(I.parent_task_id),eq(I.parent_task_id,""))),c=t?and(d,eq(I.workspace_id,t)):d,u=a.db.select().from(I).where(c).orderBy(asc(I.started_at)).all();for(let p of u)n.has(p.id)||(n.add(p.id),s.push(p));}catch(d){throw new j("DB_ERROR","Failed to find top-level tasks",d)}finally{a.close();}}return s}findAllTasks(e,t){let r=this.resolveDbPaths(),n=new Set,s=[];for(let i of r){if(!existsSync(i))continue;let a=ie(i);try{let d=eq(I.thread_id,e),c=t?and(d,eq(I.workspace_id,t)):d,u=a.db.select().from(I).where(c).orderBy(asc(I.started_at)).all();for(let p of u)n.has(p.id)||(n.add(p.id),s.push(p));}catch(d){throw new j("DB_ERROR","Failed to find all tasks for thread",d)}finally{a.close();}}return s}findTaskById(e,t,r){let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let i=ie(s);try{let a=and(eq(I.id,t),eq(I.thread_id,e)),d=r?and(a,eq(I.workspace_id,r)):a,c=i.db.select().from(I).where(d).limit(1).get();if(!c)continue;let u=i.db.select().from(I).where(eq(I.parent_task_id,c.id)).orderBy(asc(I.started_at)).all();return {task:c,children:u}}catch(a){throw new j("DB_ERROR","Failed to find task by id",a)}finally{i.close();}}}batchFetchTasks(e,t){let r=new Map;if(e.length===0)return r;let n=this.resolveDbPaths();for(let s of n){if(!existsSync(s))continue;let i=ie(s);try{let a=and(inArray(I.thread_id,e),or$1(isNull(I.parent_task_id),eq(I.parent_task_id,""))),d=t?and(a,eq(I.workspace_id,t)):a,c=i.db.select().from(I).where(d).orderBy(asc(I.started_at)).all();for(let u of c){let p=u.thread_id;r.has(p)||r.set(p,[]),r.get(p).push(u);}}catch(a){throw new j("DB_ERROR","Failed to batch fetch tasks",a)}finally{i.close();}}return r}updateThreadTitle(e,t,r){if(!this.dbExists())return;let n=this.openHandle(true);try{let s=eq(A.id,e),i=r?and(s,or$1(eq(A.workspace_id,r),isNull(A.workspace_id))):s;if(!n.db.select({id:A.id}).from(A).where(i).limit(1).get())return;n.db.update(A).set({title:t,title_locked:1,updated_at:new Date().toISOString()}).where(eq(A.id,e)).run();}catch(s){throw s instanceof j?s:new j("DB_ERROR","Failed to update thread title",s)}finally{n.close();}}upsertThread(e,t){let r=this.openHandle(true);try{let n=t.workspaceId?this.validateWorkspaceId(r,t.workspaceId):null,s=new Date().toISOString();if(r.db.select({id:A.id,message_count:A.message_count}).from(A).where(eq(A.id,e)).limit(1).get()){let a={updated_at:s};t.title!==void 0&&(a.title=t.title),t.titleLocked!==void 0&&(a.title_locked=t.titleLocked?1:0),r.db.update(A).set(a).where(eq(A.id,e)).run();}else r.db.insert(A).values({id:e,platform:t.platform,workspace_id:n,title:t.title??null,title_locked:t.titleLocked?1:0,message_count:0,created_at:s,updated_at:s}).run();}catch(n){throw n instanceof j?n:new j("DB_ERROR","Failed to upsert thread",n)}finally{r.close();}}ensureThread(e,t,r){let n=this.openHandle(true);try{let s=r?this.validateWorkspaceId(n,r):null,i=n.db.select({id:A.id,platform:A.platform,workspace_id:A.workspace_id}).from(A).where(eq(A.id,e)).limit(1).get();if(i){s&&!i.workspace_id&&n.db.update(A).set({workspace_id:s}).where(eq(A.id,e)).run();return}let a=new Date().toISOString();n.db.insert(A).values({id:e,platform:t,workspace_id:s,message_count:0,created_at:a,updated_at:a}).run();}catch(s){throw s instanceof j?s:new j("DB_ERROR","Failed to ensure thread",s)}finally{n.close();}}saveUserMessage(e,t,r){if(!this.dbExists())return;let n=this.openHandle(true);try{let s=new Date().toISOString();n.db.run(sql`
69
56
  UPDATE threads
70
57
  SET first_message = COALESCE(first_message, ${t}),
71
58
  title = CASE WHEN title_locked = 0 AND title IS NULL THEN substr(${t}, 1, 60) ELSE title END,
@@ -73,14 +60,14 @@ ${t.join(`
73
60
  message_count = message_count + 1,
74
61
  updated_at = ${s}
75
62
  WHERE id = ${e}
76
- `);}catch(s){throw s instanceof G?s:new G("DB_ERROR","Failed to save user message",s)}finally{o.close();}}saveAssistantMessage(e,t,n){if(!this.dbExists())return;let o=this.openHandle(true);try{let s=new Date().toISOString();o.db.update(N).set({last_message:t,updated_at:s}).where(eq(N.id,e)).run();}catch(s){throw s instanceof G?s:new G("DB_ERROR","Failed to save assistant message",s)}finally{o.close();}}updateThread(e,t){if(!this.dbExists())return;let n=this.openHandle(true);try{let o={updated_at:new Date().toISOString()};t.title!==void 0&&(o.title=t.title,o.title_locked=1),t.titleLocked!==void 0&&(o.title_locked=t.titleLocked?1:0),n.db.update(N).set(o).where(eq(N.id,e)).run();}catch(o){throw o instanceof G?o:new G("DB_ERROR","Failed to update thread",o)}finally{n.close();}}};function cl(r){return r.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
77
- `).filter(o=>!(o.startsWith("Loaded ")&&o.includes("layouts from")||o.includes("[dotenv@")||o.includes("[Nest]")&&o.includes("DEBUG")||o.startsWith("Registered custom layout:")||o.startsWith("Updated custom layout:"))).join(`
78
- `).trim()}function pl(r){if(!r)return "";let e=r;try{let t=JSON.parse(e);Array.isArray(t)?e=t.filter(n=>n?.type==="text"&&n?.text).map(n=>n.text).join(`
79
- `):t&&typeof t=="object"&&t.result!==void 0&&(e=t.result||"");}catch{e=cl(e);}return e}var Zt=class{dbPath;constructor(e){this.dbPath=e??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new Qt({dbPath:this.dbPath})}updateThread(e,t){this.getThreadRepo().updateThread(e,{title:t.title});}async ensureThread(e,t,n){let o=this.getThreadRepo(),s=o.findThreadById(e);if(s){if(s.platform!==t)throw new Error(`Thread '${e}' already exists with platform '${s.platform}' \u2014 cannot change to '${t}' (platform is immutable)`);return}o.ensureThread(e,t,n);}async fetchHistory(e,t){let n=t?.limit??100,o=this.getThreadRepo(),s=o.findThreadById(e),i=o.findTopLevelTasks(e),a=new Set(["done","completed","success"]);i=i.filter(d=>(!d.status||a.has(d.status))&&(!t?.currentTraceId||d.trace_id!==t.currentTraceId)),i=i.slice(0,n);let l=s?.platform??"cli",u=this.rowsToMessages(i);return {threadId:e,platform:l,messages:u,metadata:{title:s?.title??void 0,firstMessage:s?.first_message??void 0,lastMessage:s?.last_message??void 0,messageCount:s?.message_count??0,updatedAt:s?.updated_at?new Date(s.updated_at).getTime():void 0}}}async saveUserMessage(e,t,n,o){this.getThreadRepo().saveUserMessage(e,t);}async saveAssistantMessage(e,t,n,o){this.getThreadRepo().saveAssistantMessage(e,t);}close(){}rowsToMessages(e){let t=[];for(let n of e){n.prompt&&t.push({id:`${n.id}-user`,text:n.prompt,isAssistant:false,timestamp:new Date(n.started_at).getTime()});let o=pl(n.result);o&&t.push({id:`${n.id}-assistant`,text:o,isAssistant:true,timestamp:new Date(n.started_at).getTime()});}return t}};var yt=class extends ht{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(e){super(),this._provider=new Zt(e?.dbPath);}get conversationProvider(){return this._provider}attach(e){this.unsubStart=e.on("task:start",async t=>{if(!t.threadId)return;let n=t.platform??"cli";try{await this._provider.ensureThread(t.threadId,n,t.workspaceId),await this._provider.saveUserMessage(t.threadId,t.message??"");}catch{}}),this.unsubEnd=e.on("task:end",async t=>{if(!t.result)return;let n=t.metadata?.threadId;if(!n)return;let o=t.agentRef?.replace(/^@/,"")??"";try{await this._provider.saveAssistantMessage(n,t.result,o);}catch{}});}detach(e){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};g();function so(r){let e=ne.resolve(r);return process.platform==="win32"&&(e=e.replace(/\\/g,"/"),e=e.replace(/^([A-Z]):/,(t,n)=>`${n.toLowerCase()}:`)),e.length>1&&!/^[a-zA-Z]:\/$/.test(e)&&(e=e.replace(/\/+$/,"")),e}function Fr(r){let e=so(r);return createHash("sha256").update(e).digest("hex")}function hp(r){return r?r.settings?.template?.exec:void 0}function yp(){try{let r=new Uint8Array(8);return globalThis.crypto.getRandomValues(r),Array.from(r,e=>e.toString(16).padStart(2,"0")).join("")}catch{let{randomBytes:r}=J("crypto");return r(8).toString("hex")}}var yn=class r extends ft{_agents;_templateEngine;_documentLoader;_layoutLoader;_layoutRenderer;_config;_projectRoot;_workspaceId;_workspaceName;_plugins=[];_tools=new Map;_activeAdapters=new Map;_pendingThreads=new Map;_remoteFactory;_remoteTargets=new Map;constructor(e,t={},n,o,s){super(),this._agents=new Map(e.map(l=>[l.id,l])),this._config=n,this._projectRoot=s??(typeof process<"u"?process.cwd():"/");let i=s??(typeof process<"u"?process.env.CREWX_WORKSPACE??process.cwd():"/");this._workspaceId=Fr(i),this._workspaceName=basename(i);let a=hp(n);this._templateEngine=new ct({execPolicy:t.execPolicy??a}),this._documentLoader=o??new Ue,this._layoutLoader=new pt({templatesPath:Qe()}),this._layoutRenderer=new mt,this._remoteFactory=t.remoteFactory;}async resolveFileRemoteTarget(e){let t=this.getAgent(e),n=Array.isArray(t?.provider)?t?.provider[0]:t?.provider;if(!n?.startsWith("remote/"))return null;let o=n.slice(7),s=this.getRemoteProviderConfig(o);if(!s?.location?.startsWith("file://"))return null;let i=resolve(s.location.replace("file://","")),a=s.external_agent_id??e.replace(/^@/,""),l=this._remoteTargets.get(i);l||(l=(this._remoteFactory??(f=>r.loadYaml(f)))(i),this._remoteTargets.set(i,l),l.catch(()=>this._remoteTargets.delete(i)));let u=await l,d=u.getAgent("@"+a),c=Array.isArray(d?.provider)?d?.provider[0]:d?.provider;if(c?.startsWith("remote/"))throw new Error(`Chained remotes not allowed: "${o}" \u2192 "${c}"`);return {target:u,agentRef:"@"+a}}static async loadBuiltInConfig(e){let{yamlPath:t,dir:n}=yr(),o;try{o=readFileSync(t,"utf-8");}catch(i){throw new Error(`[@crewx/sdk] Cannot read built-in config: ${t}
80
- ${i.message}`)}let s=jt(o);if(s.documents&&typeof s.documents=="object"){let i={};for(let[a,l]of Object.entries(s.documents))if(l&&typeof l=="object"){let u=l;typeof u.path=="string"&&!isAbsolute(u.path)?i[a]={...u,path:resolve(n,u.path)}:i[a]=u;}else i[a]=l;return {...s,documents:i}}return s}static mergeCrewxConfig(e,t){let n=new Map;for(let w of e.agents??[])n.set(w.id,w);for(let w of t.agents??[])n.has(w.id)&&console.warn(`[agent-loader] User agent "${w.id}" overrides built-in`),n.set(w.id,w);let o=Array.from(n.values()),s={...e.layouts??{},...t.layouts??{}},i={...e.documents??{},...t.documents??{}},a=e,l=t,u=li(a.vars,l.vars),d=li(a.settings,l.settings),c;e.skills&&t.skills&&typeof e.skills=="object"&&typeof t.skills=="object"&&!Array.isArray(e.skills)&&!Array.isArray(t.skills)?c={...e.skills,...t.skills}:c=t.skills??e.skills;let p=[...e.hooks??[],...t.hooks??[]],f=vp(a.providers,l.providers),v={...e},h={...t};for(let w of ["agents","layouts","documents","skills","hooks","vars","settings","providers"])delete v[w],delete h[w];let y={...{...v,...h},agents:o,layouts:s,documents:i,skills:c};return p.length>0&&(y.hooks=p),u!==void 0&&(y.vars=u),d!==void 0&&(y.settings=d),f!==void 0&&(y.providers=f),y}static async loadYaml(e,t,n){let o=t?.includeBuiltIns!==false,s,i;if(o){let d=await r.loadBuiltInConfig(n);if(e!==void 0){let c=Nt(e);s=r.mergeCrewxConfig(d,c),i=dirname(e);}else s=d,i=process.cwd();}else {if(e===void 0)throw new Error("[@crewx/sdk] loadYaml: path is required when includeBuiltIns is false");s=Nt(e),i=dirname(e);}let a=new Ue(n);await a.load(s.documents,i);let l=s.agents??[];await ui(l,s,t);let u=new r(l,t??{},s,a,i);return await u.use(new yt),u}static async fromConfig(e,t,n,o){let s=t?.includeBuiltIns===true,i=e;if(s){let d=await r.loadBuiltInConfig(o);i=r.mergeCrewxConfig(d,e);}let a=new Ue(o);await a.load(i.documents,n??(typeof process<"u"?process.cwd():"/"));let l=i.agents??[];await ui(l,i,t);let u=new r(l,t??{},i,a,n);return await u.use(new yt),u}get agents(){return this._agents}get config(){return this._config}get plugins(){return this._plugins}get tools(){return this._tools}get workspaceId(){return this._workspaceId}get workspaceName(){return this._workspaceName}getAgent(e){let t=e.startsWith("@")?e.slice(1):e;return this._agents.get(t)}getRemoteProviderConfig(e){let t=this._config?.providers;return Array.isArray(t)?t.find(o=>o.type==="remote"&&o.id===e):void 0}computeTaskLogPath(e,t){let n=Mr(t);return join(this._projectRoot,".crewx","logs",`${n}_${e}.log`)}registerTool(e,t){this._tools.set(e,{name:e,...t});}async use(e){this._plugins.includes(e)||(await e.attach(this),this._plugins.push(e));}handler(e){return Hr(this,e)}async registerChannelAdapter(e){let{adapter:t,instanceId:n,config:o}=e;if(this._activeAdapters.has(n))throw new Error(`Adapter instance already registered: ${n}`);let s=new Set(t.manifest.capabilities),i=e.store??jr(n),a=e.defaultMode??"query",l=t.manifest.platform,u=e.agentRunner??{run:async(f,v,h)=>{let y=await(a==="execute"?this.execute.bind(this):this.query.bind(this))(`@${f}`,v,{threadId:h?.threadId,platform:l});return {output:y.ok?y.data:y.error?.message??""}}},d=e.onInbound??(async f=>{let v=f.routingHints?.agentId??e.defaultAgent;if(!v)return {accepted:false,reason:"no_agent"};let{output:h}=await u.run(v,f.text,{threadId:f.threadId});return {accepted:true,output:h}}),c=Dr({instanceId:n,config:o,capabilities:s,db:i,agentRunner:u,onInbound:d}),p={adapter:t,ctx:c,state:"starting"};this._activeAdapters.set(n,p),this.emit("adapter:lifecycle",{adapterId:t.manifest.id,instanceId:n,state:"starting",timestamp:new Date});try{await t.start(c),p.state="started",this.emit("adapter:lifecycle",{adapterId:t.manifest.id,instanceId:n,state:"started",timestamp:new Date});}catch(f){throw p.state="failed",this.emit("adapter:lifecycle",{adapterId:t.manifest.id,instanceId:n,state:"failed",error:f instanceof Error?f:new Error(String(f)),timestamp:new Date}),this._activeAdapters.delete(n),f}}async unregisterChannelAdapter(e){let t=this._activeAdapters.get(e);if(t){t.state="stopping",this.emit("adapter:lifecycle",{adapterId:t.adapter.manifest.id,instanceId:e,state:"stopping",timestamp:new Date});try{await t.adapter.stop(t.ctx),t.state="stopped",this.emit("adapter:lifecycle",{adapterId:t.adapter.manifest.id,instanceId:e,state:"stopped",timestamp:new Date});}catch(n){t.state="failed",this.emit("adapter:lifecycle",{adapterId:t.adapter.manifest.id,instanceId:e,state:"failed",error:n instanceof Error?n:new Error(String(n)),timestamp:new Date});}finally{this._activeAdapters.delete(e);}}}async stopAllAdapters(e={}){let t=e.timeoutMs??1e4,n=Array.from(this._activeAdapters.keys()),o=await Promise.allSettled(n.map(s=>Promise.race([this.unregisterChannelAdapter(s),new Promise((i,a)=>setTimeout(()=>a(new Error(`Adapter stop timeout: ${s}`)),t))])));for(let s=0;s<o.length;s++)o[s].status==="rejected"&&console.error(`[crewx] adapter stop error (${n[s]}): ${o[s].reason}`);}async close(){await this.stopAllAdapters({timeoutMs:1e4});let e=[...this._remoteTargets.values()];this._remoteTargets.clear(),await Promise.allSettled(e.map(async n=>{try{await(await n).close();}catch(o){console.error(`[crewx] remote target close error: ${o instanceof Error?o.message:String(o)}`);}}));let t=[...this._plugins].reverse();for(let n of t)try{await n.detach(this);}catch(o){console.error(`[crewx] plugin ${n.name} detach error: ${o instanceof Error?o.message:String(o)}`);}this._plugins.length=0;}filterAgents(e){let t=a=>a?a.split(",").map(l=>l.trim().toLowerCase()).filter(Boolean):void 0,n=t(e.role),o=t(e.team),s=t(e.provider),i=Array.from(this._agents.values());return n&&(i=i.filter(a=>a.role&&n.some(l=>ve(a.role.toLowerCase(),l)))),o&&(i=i.filter(a=>a.team&&o.some(l=>ve(a.team.toLowerCase(),l)))),s&&(i=i.filter(a=>(Array.isArray(a.provider)?a.provider:[a.provider]).some(u=>s.some(d=>ve(u.toLowerCase(),d))))),i}renderAgentPrompt(e){let t=e.startsWith("@")?e.slice(1):e,n=this._agents.get(t);if(!n)throw new Re(t,Array.from(this._agents.keys()));return n.inline?.prompt??n.inline?.system_prompt??n.description??`You are an expert ${t}.`}async renderPrompt(e,t){let o={...await this._documentLoader.buildContext(),...t?.documents??{}},s={...t,documents:o};return this._templateEngine.render(e,s)}registerLayout(e,t){this._layoutLoader.registerLayout(e,t);}async renderAgentPromptFull(e,t){let n=e.startsWith("@")?e.slice(1):e,o=this._agents.get(n);if(!o)throw new Re(n,Array.from(this._agents.keys()));let s=this._resolveLayoutSpec(o,t?.layout),i=this._extractLayoutId(s),a=this._extractLayoutProps(o,s,t?.layout),l=this._layoutLoader.load(i,a),u=o.inline?.prompt??o.inline?.system_prompt??o.description??`You are an expert ${n}.`,d=await this._documentLoader.buildContext(),c=t?.env??(typeof process<"u"?process.env:{}),p=t?.vars?.security_key??yp(),f={...t?.vars??{},documents:d,env:c,agent:{id:o.id,name:o.name??o.id,role:o.role??"",team:o.team??"",description:o.description??""}},v=await this._templateEngine.render(u,f),h={mode:t?.session?.mode??"query",platform:t?.session?.platform??"cli",options:t?.session?.options??[]},m=o.provider,y=Array.isArray(m)?m:typeof m=="string"&&m.length>0?[m]:[],w=y.join(", ")||(typeof m=="string"?m:""),C=o.options,_=!Array.isArray(C)&&typeof C=="object"&&C!==null?C:void 0,k=Array.isArray(C)?C:void 0,S={};for(let[x,M]of Object.entries(d))S[x]={content:M.content??"",toc:M.toc,summary:M.summary,path:M.path};let R={user_input:t?.vars?.user_input??void 0,agent:{id:o.id,name:o.name??o.id,role:o.role??"",team:o.team??"",description:o.description??"",provider:w,providerList:y,model:o.inline?.model,workingDirectory:o.working_directory??o.workingDirectory??".",inline:{...o.inline??{},prompt:v},specialties:o.specialties??[],capabilities:o.capabilities??[],remote:o.remote??null,optionsByMode:_,optionsArray:k},agentMetadata:{specialties:o.specialties??[],capabilities:o.capabilities??[],description:o.description??""},documents:S,skills:t?.skills??[],session:h,env:c,vars:{security_key:p,...t?.vars??{}},props:{...a??{},...t?.messages&&t.messages.length>0?{showConversationHistory:true}:{}},platform:h.platform,mode:h.mode,messages:t?.messages??[],tools:this._tools.size>0?{list:Array.from(this._tools.values()).map(x=>({name:x.name,description:x.description,parameters:x.parameters})),json:JSON.stringify(Array.from(this._tools.values()).map(x=>({name:x.name,description:x.description,parameters:x.parameters})),null,2),count:this._tools.size}:null,metadata:{}};return this._layoutRenderer.render(l,R)}_filterToolsByMode(e){return e?e.map(t=>this._tools.get(t)).filter(t=>t!==void 0):Array.from(this._tools.values())}_resolveLayoutSpec(e,t){if(t!==void 0)return t;let n=e.inline?.layout;if(n!==void 0)return n;let o=this._config?.layouts?.default;return typeof o=="string"&&o?o:"crewx/default"}_extractLayoutId(e){if(typeof e=="string")return e;if("id"in e)return e.id;let t=`crewx/__inline_${Date.now()}`;return this._layoutLoader.registerLayout(t,e.template),t}_extractLayoutProps(e,t,n){let o=e.inline?.layout,s=o&&typeof o=="object"&&"props"in o?o.props:void 0,i=n&&typeof n=="object"&&"id"in n?n.props:void 0;if(s||i)return {...s??{},...i??{}}}_getConversationProvider(){return this._plugins.find(t=>t.name==="conversation")?.conversationProvider}async _fetchHistoryMessages(e,t,n){if(n&&n.length>0)return n;if(!e)return;let o=this._getConversationProvider();if(o)try{let s=await o.fetchHistory(e,{currentTraceId:t});return s.messages.length===0?void 0:$r(s)}catch{return}}_resolveTimeout(e){let t=Nn();return e==="query"?t.queryMs:t.executeMs}emitToolEvents(e,t,n,o,s,i,a){try{let u=ze[n]?.parseEvent?.(o)??Rr(new Date().toISOString(),o);for(let d of u)d.type==="tool_use"&&d.toolName&&this.emit("tool:observed:before",{traceId:e,timestamp:new Date,agentRef:t,agentId:s,threadId:i,sessionId:a,provider:n,tool:{name:d.toolName,rawName:d.toolName,input:d.toolInput?this.tryParseJson(d.toolInput):void 0,toolUseId:d.toolUseId}}),d.type==="tool_result"&&this.emit("tool:observed:after",{traceId:e,timestamp:new Date,agentRef:t,agentId:s,threadId:i,sessionId:a,provider:n,tool:{name:d.toolName??"unknown",rawName:d.toolName??"unknown",toolUseId:d.toolUseId,result:d.resultPreview,isError:d.isError}});}catch{}}tryParseJson(e){try{return JSON.parse(e)}catch{return e}}async query(e,t,n){let o=await this.resolveFileRemoteTarget(e);if(o)return o.target.query(o.agentRef,t,n);let s=Date.now(),i=Be("tsk"),a=new Date,l;try{l=$t(e,Array.from(this._agents.values()));}catch(x){if(x instanceof Re){this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"query",metadata:{...n?.metadata??{}},threadId:n?.threadId,platform:n?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName});let M=Date.now()-s,O={code:"AGENT_NOT_FOUND",message:x.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"query",durationMs:M,error:O,metadata:n?.metadata?{...n.metadata}:void 0}),{ok:false,data:"",error:O,meta:{agentId:e.replace(/^@/,""),provider:"",durationMs:M}}}throw x}let u=Array.isArray(l.provider)?l.provider[0]??"cli/claude":l.provider,d=n?.provider??u,c=n?.model??l.inline?.model,p;try{p=Ce(d);}catch(x){this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"query",metadata:{...n?.metadata??{}},threadId:n?.threadId,platform:n?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName});let M=Date.now()-s,O={code:"PROVIDER_ERROR",message:x.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"query",durationMs:M,error:O,metadata:n?.metadata?{...n.metadata}:void 0}),{ok:false,data:"",error:O,meta:{agentId:l.id,provider:d,model:c,durationMs:M}}}let f=await this._fetchHistoryMessages(n?.threadId,i,n?.messages),v;try{v=await this.renderAgentPromptFull(e,{session:{mode:"query",platform:n?.platform},vars:{user_input:t},messages:f});}catch{}let h,m,y,w=c,C=false,_=x=>{C||(C=true,this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"query",pid:x,model:w,provider:d,codingAgentCommand:h,renderedPrompt:v,metadata:{...n?.metadata??{},provider:d},threadId:n?.threadId,platform:n?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName}));},k=l.options,S=Array.isArray(k?.query?.tools)?k.query.tools:void 0,z=this._tools.size>0?this._filterToolsByMode(S):[],R=l.inline?.max_steps;d.startsWith("api/")&&_();try{let x=await p.query(t,{model:c,context:n?.context,systemPrompt:v??l.inline?.system_prompt??l.inline?.prompt,additionalArgs:Array.isArray(k?.query)?k.query:void 0,tools:z.length>0?z:void 0,maxSteps:R,timeoutMs:this._resolveTimeout("query"),env:{CREWX_AGENT_ID:l.id,CREWX_AGENT_ROLE:l.role??"",CREWX_AGENT_TEAM:l.team??"",CREWX_USER_ID:process.env.USER||process.env.USERNAME||"unknown",CREWX_TRACE_ID:i,CREWX_PARENT_TASK_ID:i,CREWX_TASK_ID:i,CREWX_CALLER_AGENT_ID:process.env.CREWX_AGENT_ID??"",CREWX_THREAD_ID:n?.threadId??"",CREWX_PROVIDER:d,CREWX_SESSION_ID:"",CREWX_TASK_LOG_PATH:this.computeTaskLogPath(i,a)},onPid:O=>_(O),onOutput:(O,Y)=>{this.emit("task:output",{traceId:i,timestamp:new Date,agentRef:e,output:O,level:Y}),Y==="stdout"&&this.emitToolEvents(i,e,d,O,l.id,n?.threadId??"","");},onCommand:O=>{h=O;},onUsage:O=>{m=O;},onExitCode:O=>{y=O;},onModel:O=>{w||(w=O);}});_();let M=Date.now()-s;return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"query",result:x,durationMs:M,exitCode:y,inputTokens:m?.inputTokens,outputTokens:m?.outputTokens,cachedInputTokens:m?.cachedInputTokens,costUsd:m?.costUsd,model:w,metadata:{...n?.metadata??{},...n?.threadId?{threadId:n.threadId}:{}}}),{ok:!0,data:x,meta:{agentId:l.id,provider:d,model:c,durationMs:M}}}catch(x){if(x instanceof he){let Y=Be("thd");return this._pendingThreads.set(Y,{agentRef:l.id,providerStr:d,continuationState:x.continuationState,toolCall:x.toolCall,traceId:i,startMs:s,model:c}),{ok:true,status:"requires_action",data:"",toolCall:x.toolCall,threadId:Y,meta:{agentId:l.id,provider:d,model:c,durationMs:Date.now()-s}}}_();let M=Date.now()-s,O={code:"QUERY_FAILED",message:x.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"query",durationMs:M,error:O,exitCode:y,inputTokens:m?.inputTokens,outputTokens:m?.outputTokens,cachedInputTokens:m?.cachedInputTokens,costUsd:m?.costUsd,model:w,metadata:n?.metadata?{...n.metadata}:void 0}),{ok:false,data:"",error:O,meta:{agentId:l.id,provider:d,model:c,durationMs:M}}}}async continueQuery(e,t){let n=this._pendingThreads.get(e);if(!n)return {ok:false,data:"",error:{code:"THREAD_NOT_FOUND",message:`No pending thread: ${e}`},meta:{agentId:"",provider:"",durationMs:0}};this._pendingThreads.delete(e);let o=Ce(n.providerStr);if(!o.continueWithToolResults)return {ok:false,data:"",error:{code:"UNSUPPORTED",message:"Provider does not support client tool continuation"},meta:{agentId:n.agentRef,provider:n.providerStr,durationMs:0}};let s=t.map(i=>({...i,toolName:n.toolCall.toolCallId===i.toolCallId?n.toolCall.toolName:i.toolCallId}));try{let i=await o.continueWithToolResults(n.continuationState,s),a=Date.now()-n.startMs;return this.emit("task:end",{traceId:n.traceId,timestamp:new Date,agentRef:n.agentRef,mode:"query",result:i,durationMs:a}),{ok:!0,status:"complete",data:i,meta:{agentId:n.agentRef,provider:n.providerStr,model:n.model,durationMs:a}}}catch(i){if(i instanceof he)return this._pendingThreads.set(e,{...n,continuationState:i.continuationState,toolCall:i.toolCall}),{ok:true,status:"requires_action",data:"",toolCall:i.toolCall,threadId:e,meta:{agentId:n.agentRef,provider:n.providerStr,model:n.model,durationMs:Date.now()-n.startMs}};let a=Date.now()-n.startMs;return {ok:false,data:"",error:{code:"CONTINUE_FAILED",message:i.message},meta:{agentId:n.agentRef,provider:n.providerStr,model:n.model,durationMs:a}}}}async execute(e,t,n){let o=await this.resolveFileRemoteTarget(e);if(o)return o.target.execute(o.agentRef,t,n);let s=Date.now(),i=Be("tsk"),a=new Date,l;try{l=$t(e,Array.from(this._agents.values()));}catch(x){if(x instanceof Re){this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"execute",metadata:{...n?.metadata??{}},threadId:n?.threadId,platform:n?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName});let M=Date.now()-s,O={code:"AGENT_NOT_FOUND",message:x.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"execute",durationMs:M,error:O,metadata:n?.metadata?{...n.metadata}:void 0}),{ok:false,data:"",error:O,meta:{agentId:e.replace(/^@/,""),provider:"",durationMs:M}}}throw x}let u=Array.isArray(l.provider)?l.provider[0]??"cli/claude":l.provider,d=n?.provider??u,c=n?.model??l.inline?.model,p;try{p=Ce(d);}catch(x){this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"execute",metadata:{...n?.metadata??{}},threadId:n?.threadId,platform:n?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName});let M=Date.now()-s,O={code:"PROVIDER_ERROR",message:x.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"execute",durationMs:M,error:O,metadata:n?.metadata?{...n.metadata}:void 0}),{ok:false,data:"",error:O,meta:{agentId:l.id,provider:d,model:c,durationMs:M}}}let f=await this._fetchHistoryMessages(n?.threadId,i,n?.messages),v;try{v=await this.renderAgentPromptFull(e,{session:{mode:"execute",platform:n?.platform},vars:{user_input:t},messages:f});}catch{}let h,m,y,w=c,C=false,_=x=>{C||(C=true,this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"execute",pid:x,model:w,provider:d,codingAgentCommand:h,renderedPrompt:v,metadata:{...n?.metadata??{},provider:d},threadId:n?.threadId,platform:n?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName}));},k=l.options,S=Array.isArray(k?.execute?.tools)?k.execute.tools:void 0,z=this._tools.size>0?this._filterToolsByMode(S):[],R=l.inline?.max_steps;d.startsWith("api/")&&_();try{let x=await p.execute(t,{model:c,context:n?.context,systemPrompt:v??l.inline?.system_prompt??l.inline?.prompt,additionalArgs:Array.isArray(k?.execute)?k.execute:void 0,tools:z.length>0?z:void 0,maxSteps:R,timeoutMs:this._resolveTimeout("execute"),env:{CREWX_AGENT_ID:l.id,CREWX_AGENT_ROLE:l.role??"",CREWX_AGENT_TEAM:l.team??"",CREWX_USER_ID:process.env.USER||process.env.USERNAME||"unknown",CREWX_TRACE_ID:i,CREWX_PARENT_TASK_ID:i,CREWX_TASK_ID:i,CREWX_CALLER_AGENT_ID:process.env.CREWX_AGENT_ID??"",CREWX_THREAD_ID:n?.threadId??"",CREWX_PROVIDER:d,CREWX_SESSION_ID:"",CREWX_TASK_LOG_PATH:this.computeTaskLogPath(i,a)},onPid:O=>_(O),onOutput:(O,Y)=>{this.emit("task:output",{traceId:i,timestamp:new Date,agentRef:e,output:O,level:Y}),Y==="stdout"&&this.emitToolEvents(i,e,d,O,l.id,n?.threadId??"","");},onCommand:O=>{h=O;},onUsage:O=>{m=O;},onExitCode:O=>{y=O;},onModel:O=>{w||(w=O);}});_();let M=Date.now()-s;return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"execute",result:x,durationMs:M,exitCode:y,inputTokens:m?.inputTokens,outputTokens:m?.outputTokens,cachedInputTokens:m?.cachedInputTokens,costUsd:m?.costUsd,model:w,metadata:{...n?.metadata??{},...n?.threadId?{threadId:n.threadId}:{}}}),{ok:!0,data:x,meta:{agentId:l.id,provider:d,model:c,durationMs:M}}}catch(x){_();let M=Date.now()-s,O={code:"EXECUTE_FAILED",message:x.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"execute",durationMs:M,error:O,exitCode:y,inputTokens:m?.inputTokens,outputTokens:m?.outputTokens,cachedInputTokens:m?.cachedInputTokens,costUsd:m?.costUsd,model:w,metadata:n?.metadata?{...n.metadata}:void 0}),{ok:false,data:"",error:O,meta:{agentId:l.id,provider:d,model:c,durationMs:M}}}}};function li(r,e){let t=vn(r)?r:void 0,n=vn(e)?e:void 0;if(!(!t&&!n))return {...t??{},...n??{}}}function vn(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function vp(r,e){let t=Array.isArray(r)?r:void 0,n=Array.isArray(e)?e:void 0;if(!t&&!n)return;let o=a=>{if(!vn(a))return;let l=a.id;if(typeof l=="string")return `id:${l}`;let u=a.name;if(typeof u=="string")return `name:${u}`},s=new Set;for(let a of n??[]){let l=o(a);l&&s.add(l);}let i=[];for(let a of t??[]){let l=o(a);l&&s.has(l)||i.push(a);}for(let a of n??[])i.push(a);return i}async function ui(r,e,t){if(r.some(o=>(Array.isArray(o.provider)?o.provider:[o.provider]).some(i=>i.startsWith("api/")))){let{registerApiProviders:o}=await Promise.resolve().then(()=>(pn(),Zs));o(t?.api);}_p(r,e),wp(r,e);}function _p(r,e){if(!r.some(i=>(Array.isArray(i.provider)?i.provider:[i.provider]).some(l=>l.startsWith("remote/"))))return;let n=e.providers;if(!Array.isArray(n))return;let{createRemoteProviderFactory:o}=(fn(),Pn(ti)),s=new Map;for(let i of n)i.type==="remote"&&typeof i.id=="string"&&s.set(i.id,i);s.size>0&&tt("remote",o(s,Ce));}function wp(r,e){if(!r.some(i=>(Array.isArray(i.provider)?i.provider:[i.provider]).some(l=>l.startsWith("plugin/"))))return;let n=e.providers;if(!Array.isArray(n))return;let{createPluginProviderFactory:o}=(hn(),Pn(si)),s=new Map;for(let i of n)i.type==="plugin"&&typeof i.id=="string"&&s.set(i.id,i);s.size>0&&tt("plugin",o(s));}g();var bp="crewx:fs:",_n=class{prefix;store;constructor(e){this.prefix=e?.prefix??bp,this.store=e?.storage??new Map;}async readFile(e){let t=this.toKey(e),n=this.store.get(t);if(n===void 0)throw new Error(`BrowserFsAdapter: file not found: ${e}`);return n}async exists(e){return this.store.has(this.toKey(e))}resolvePath(...e){let t=e.map(i=>i.replace(/\\/g,"/")).join("/").replace(/\/+/g,"/"),n=t.split("/"),o=[];for(let i of n)i==="."||i===""||(i===".."?o.pop():o.push(i));let s=o.join("/");return t.startsWith("/")?`/${s}`:s}isAbsolute(e){return e.startsWith("/")}setItem(e,t){this.store.set(this.toKey(e),t);}removeItem(e){this.store.delete(this.toKey(e));}keys(){return Array.from(this.store.keys()).filter(e=>e.startsWith(this.prefix)).map(e=>e.slice(this.prefix.length))}toKey(e){return `${this.prefix}${e.replace(/\\/g,"/")}`}};g();function xp(r,e){let t=r.skills?.include;if(t===void 0)return [...e];if(t.length===0)return [];let n=new Set(t);return e.filter(o=>n.has(o))}Fe();cn();pn();vr();et();g();var wn=0;function kp(r){let e=Array.from(r.agents.keys());return {name:"delegate_to_agent",description:`Delegate a task to another agent. Available agents: ${e.join(", ")}`,parameters:{type:"object",properties:{agent:{type:"string",description:`Agent ID to delegate to. One of: ${e.join(", ")}`},message:{type:"string",description:"Task description for the target agent"},mode:{type:"string",description:'Execution mode: "query" for questions, "execute" for actions. Default: query'}},required:["agent","message"]},execute:async t=>{if(wn>=3)return "Error: Maximum delegation depth (3) reached. Cannot delegate further.";let n=t.agent,o=t.message,s=t.mode??"query";if(!e.includes(n))return `Error: Unknown agent "${n}". Available: ${e.join(", ")}`;wn++;try{if(s==="execute"){let a=await r.execute(n,o);return a.ok?a.data:`Error: ${a.error?.message??"Unknown error"}`}let i=await r.query(n,o);return i.ok?i.data:`Error: ${i.error?.message??"Unknown error"}`}finally{wn--;}}}}g();var di=typeof process<"u"?process.env:{};function Rp(){return di.CREWX_CLI||"npx crewx"}function Cp(){return di.CREWX_WORKSPACE||(typeof process<"u"?process.cwd():"/")}g();var Tp=/^[a-zA-Z0-9._-]+$/,bn=class{constructor(e){this.storage=e;}storage;listBoxes(e){this.validateId(e);let n=this.storage.listBoxes(e).map(o=>this.toBoxResponse(o));return {boxes:n,total:n.length}}getBox(e,t){this.validateId(e),this.validateId(t);let n=this.storage.findBox(e,t);return n?this.toBoxResponse(n):null}createBox(e,t){this.validateId(e);let n=this.generateBoxId(),o=new Date().toISOString(),s=this.storage.insertBox(e,{id:n,seq:t.seq,firstTaskId:t.firstTaskId,midTaskId:t.midTaskId,lastTaskId:t.lastTaskId,taskCount:t.taskCount,summary:t.summary??null,sourceTokens:t.sourceTokens,summaryTokens:t.summaryTokens??null,createdAt:o});return this.toBoxResponse(s)}toBoxResponse(e){return {id:e.id,threadId:e.thread_id,seq:e.seq,firstTaskId:e.first_task_id,lastTaskId:e.last_task_id,taskCount:e.task_count,sourceTokens:e.source_tokens,summaryTokens:e.summary_tokens,summary:e.summary,previewFirst:this.storage.getTaskPreview(e.first_task_id,200),previewMid:this.storage.getTaskPreview(e.mid_task_id,200),previewLast:this.storage.getTaskPreview(e.last_task_id,200),createdAt:e.created_at}}validateId(e){if(!Tp.test(e))throw new Error(`Invalid ID format: ${e}`)}generateBoxId(){return Be("box")}};g();function Pp(r,e,t,n,o){let{maxTokens:s,hotzoneRatio:i,warmzoneRatio:a}=n,l=s*i,u=s*a,d=l+u,c=e.getThreadMessages(r),p=[],f=0,v=false,h=[];for(let w=0;w<c.length;w+=2){let C=c[w],_=c[w+1],k=C?.content||"",S=_?.content||"",z=o.countTokens(k+S),R=[];C&&R.push(C),_&&R.push(_),h.push({messages:R,tokens:z});}for(let w=h.length-1;w>=0;w--){let C=h[w];if(f+C.tokens>l){v=true;break}f+=C.tokens,p.unshift(...C.messages);}let m=[],y=0;if(v&&u>0)try{let{boxes:w}=t.listBoxes(r);for(let C=w.length-1;C>=0;C--){let _=w[C],k=_.summaryTokens??_.sourceTokens;if(y+k>u)break;y+=k,m.unshift({boxId:_.id,seq:_.seq,taskCount:_.taskCount,sourceTokens:_.sourceTokens,summary:_.summary,previewFirst:_.previewFirst,previewMid:_.previewMid,previewLast:_.previewLast,createdAt:_.createdAt});}}catch(w){if(w instanceof Error&&!/not found/i.test(w.message))throw w}return {hot:p,warm:m,hotTokens:f,warmTokens:y,hotOverflow:v,totalBudget:d,config:{maxTokens:s,hotzoneRatio:i,warmzoneRatio:a}}}et();Le();g();var gr=class extends Error{constructor(t,n){super(`Task ${t} timed out after ${n}ms`);this.taskId=t;this.timeoutMs=n;this.name="ParallelRunnerTimeoutError";}taskId;timeoutMs},zt=class{constructor(e={}){this.defaults=e;}defaults;metrics={totalTasks:0,startedTasks:0,completedTasks:0,successCount:0,failureCount:0,totalDurationMs:0,averageDurationMs:0,throughput:0};async run(e,t={}){if(!Array.isArray(e))throw new TypeError("ParallelRunner.run expects an array of tasks");if(e.length===0)return this.metrics={totalTasks:0,startedTasks:0,completedTasks:0,successCount:0,failureCount:0,totalDurationMs:0,averageDurationMs:0,throughput:0},[];let n=this.mergeOptions(t),o=Math.max(1,n.maxConcurrency??5),s=n.timeoutMs,i=n.failFast??false,a=n.callbacks,l=n.evaluateTaskSuccess??(()=>true),u=[],d=0,c=0,p=0,f=false,v=0,h=performance.now(),m=async R=>{a?.onTaskStart&&await a.onTaskStart(R),p+=1;let x=new AbortController,M={signal:x.signal},O,Y;typeof s=="number"&&Number.isFinite(s)&&s>0&&(Y=new Promise((pe,ye)=>{O=setTimeout(()=>{let V=new gr(R.id,s);x.abort(V),ye(V);},s);}));let re=performance.now(),B=R.run(M),De=Y?Promise.race([B,Y]):B;try{let pe=await De,ye=performance.now(),V=ye-re,oe=l(pe,R),Q={taskId:R.id,success:oe,value:pe,durationMs:V,startedAt:re,finishedAt:ye,metadata:R.metadata,aborted:!1};u.push(Q),oe?d+=1:c+=1,a?.onTaskComplete&&await a.onTaskComplete(Q),i&&!oe&&(f=!0);}catch(pe){let ye=performance.now(),V=ye-re,oe=pe instanceof Error?pe:new Error(String(pe)),Q={taskId:R.id,success:false,error:oe,durationMs:V,startedAt:re,finishedAt:ye,metadata:R.metadata,aborted:x.signal.aborted};u.push(Q),c+=1,a?.onError&&await a.onError(R,oe,V),i&&(f=true);}finally{O&&clearTimeout(O),Y&&B.catch(()=>{});}},y=async()=>{for(;!f;){let R=v;if(R>=e.length)break;v+=1;let x=e[R];if(!x||(await m(x),f))break}},w=Math.min(o,e.length),C=[];for(let R=0;R<w;R++)C.push(y());await Promise.all(C);let k=performance.now()-h,S=u.length?u.reduce((R,x)=>R+x.durationMs,0)/u.length:0,z=k>0?u.length/(k/1e3):u.length;return this.metrics={totalTasks:e.length,startedTasks:p,completedTasks:u.length,successCount:d,failureCount:c,totalDurationMs:k,averageDurationMs:S,throughput:z},u}getMetrics(){return this.metrics}mergeOptions(e){return {maxConcurrency:e.maxConcurrency??this.defaults.maxConcurrency,timeoutMs:e.timeoutMs??this.defaults.timeoutMs,failFast:e.failFast??this.defaults.failFast,evaluateTaskSuccess:e.evaluateTaskSuccess??this.defaults.evaluateTaskSuccess,callbacks:this.mergeCallbacks(this.defaults.callbacks,e.callbacks)}}mergeCallbacks(e,t){if(!(!e&&!t))return {onTaskStart:async n=>{e?.onTaskStart&&await e.onTaskStart(n),t?.onTaskStart&&await t.onTaskStart(n);},onTaskComplete:async n=>{e?.onTaskComplete&&await e.onTaskComplete(n),t?.onTaskComplete&&await t.onTaskComplete(n);},onError:async(n,o,s)=>{e?.onError&&await e.onError(n,o,s),t?.onError&&await t.onError(n,o,s);}}}};g();g();var Mt=class{async query(e){throw new Error("AgentRuntime.query is not implemented. Provide a subclass or mock AgentRuntime.prototype.query.")}async execute(e){throw new Error("AgentRuntime.execute is not implemented. Provide a subclass or mock AgentRuntime.prototype.execute.")}};var ci=3,pi=3e4,gi=500,Ap=r=>{if(typeof r!="number"||Number.isNaN(r)||!Number.isFinite(r))return ci;let e=Math.floor(r);return e>0?e:ci},Ep=r=>r===void 0||typeof r!="number"||Number.isNaN(r)||r<=0?pi:r,Sp=r=>{if(!r)return {maxRetries:0,retryDelay:gi};let e=Number.isInteger(r.maxRetries)&&r.maxRetries>=0?r.maxRetries:0,t=typeof r.retryDelay=="number"&&r.retryDelay>=0?r.retryDelay:gi;return {maxRetries:e,retryDelay:t}},xn=r=>{let e=r.reason;return e instanceof Error?e:typeof e=="string"?new Error(e):new Error("Parallel operation aborted")},Ip=(r,e)=>r<=0?Promise.resolve():new Promise((t,n)=>{let o=setTimeout(()=>{e.removeEventListener("abort",s),t();},r),s=()=>{clearTimeout(o),n(xn(e));};if(e.aborted){s();return}e.addEventListener("abort",s,{once:true});}),Op=async(r,e,t)=>{let n,o;for(let s=0;s<=e.maxRetries;s++){if(t.aborted)throw xn(t);try{let i=await r();if(n=i,i.success||s===e.maxRetries)return i}catch(i){if(o=i,t.aborted)throw xn(t);if(s===e.maxRetries)throw i instanceof Error?i:new Error(String(i))}s<e.maxRetries&&await Ip(e.retryDelay,t);}if(n)return n;throw o?o instanceof Error?o:new Error(String(o)):new Error("Parallel helper encountered an unexpected state")},mi=(r,e,t)=>{e.completed+=1,t?e.success+=1:e.failure+=1;try{r.onProgress?.(e.completed,e.total);}catch(n){process.env.NODE_ENV!=="production"&&console.warn("Parallel helper onProgress callback threw an error:",n);}},zp=r=>r.map(t=>({metadata:t.metadata,taskResult:t})).slice().sort((t,n)=>t.metadata.index-n.metadata.index).map(({metadata:t,taskResult:n})=>{if(n.value){let s=n.value;return {...s,agentId:s.agentId??t.request.agentId,metadata:{...s.metadata,requestIndex:t.index,mode:t.mode}}}let o=n.error??new Error("Unknown error");return {agentId:t.request.agentId,content:o.message,success:false,metadata:{error:o.message,aborted:n.aborted??false,requestIndex:t.index,mode:t.mode}}}),Mp=r=>r.filter(e=>!e.success).map(e=>{let t=e.metadata;if(e.error instanceof Error)return {index:t.index,error:e.error};if(e.value&&!e.value.success){let n=String(e.value.metadata?.error??e.value.content??"Agent returned unsuccessful result");return {index:t.index,error:new Error(n)}}return {index:t.index,error:new Error("Unknown failure")}}),jp=(r,e)=>({onTaskComplete:async t=>{mi(e,r,t.success);},onError:async()=>{mi(e,r,false);}}),fi=async(r,e,t={})=>{if(!Array.isArray(r))throw new TypeError("Parallel helpers expect an array of requests");if(r.length===0){let m={total:0,completed:0,successCount:0,failureCount:0,results:[],errors:[],metrics:{totalTasks:0,startedTasks:0,completedTasks:0,successCount:0,failureCount:0,totalDurationMs:0,averageDurationMs:0,throughput:0}};return t.onComplete?.(m),[]}let n=Ap(t.concurrency),o=Ep(t.timeout),s=Sp(t.retryPolicy),i=new zt,a=new Mt,l=r.map((h,m)=>({id:`${e}:${h.agentId??"anonymous"}:${m}`,metadata:{index:m,mode:e,request:h},run:y=>Op(()=>e==="query"?a.query(h):a.execute(h),s,y.signal)})),u={completed:0,success:0,failure:0,total:r.length},d=await i.run(l,{maxConcurrency:n,timeoutMs:o,evaluateTaskSuccess:h=>h.success,callbacks:jp(u,t)}),c=zp(d),p=Mp(d),f=i.getMetrics(),v={total:r.length,completed:r.length,successCount:c.filter(h=>h.success).length,failureCount:c.filter(h=>!h.success).length,results:c,errors:p,metrics:f};return t.onComplete?.(v),c},Np=(r,e)=>fi(r,"query",e),Dp=(r,e)=>fi(r,"execute",e);hn();fn();mn();gn();g();g();var mr=class{capabilities={required:[]}};g();g();g();var hi=2e3;function yi(r){let e=r.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\u2028\u2029]/g,"");return e.length<=hi?e:e.slice(0,hi-11)+" [redacted]"}var Wp=10*1024*1024,Jp={b:1,kb:1024,mb:1024*1024,gb:1024*1024*1024};function kn(r,e){return r===void 0?true:Array.isArray(r)?r.includes(e):r===e}function Vp(r,e){return r===void 0?true:Array.isArray(r)?r.some(t=>e.includes(t)):e.includes(r)}function _i(r){if(typeof r=="number")return r;let e=r.match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)?$/i);if(!e)return 0;let t=parseFloat(e[1]),n=(e[2]??"b").toLowerCase();return Math.floor(t*(Jp[n]??1))}function wi(r){return typeof r=="string"}function bi(r){try{let e=statSync(r);return e.size>Wp?(process.stderr.write(`[YamlHookPlugin] File too large for line count: ${r} (${e.size} bytes)
81
- `),null):readFileSync(r,"utf8").split(`
82
- `).length}catch{return null}}function xi(r){try{return statSync(r).size}catch{return null}}function Kp(r,e,t){if(!r)return true;let n=e,o=n?.path??n?.file_path??n?.filePath??n?.filename;if(typeof o!="string")return false;if(ve(o,r))return true;if(t&&o.startsWith("/")){let{relative:s,isAbsolute:i}=J("path");if(i(o)){let a=s(t,o);if(a&&!a.startsWith("..")&&ve(a,r))return true}}return false}function Gp(r,e){return r?JSON.stringify(e).includes(r):true}function Xp(r,e){if(!r)return true;try{let t=new RegExp(r),n=JSON.stringify(e);return t.test(n)}catch{return false}}function Yp(r,e){if(!r)return true;try{let t=new RegExp(r),n=JSON.stringify(e);return t.test(n)}catch{return false}}function Qp(r,e){if(r.pathSizeMin===void 0&&r.pathSizeMax===void 0)return true;let t=e,n=t?.path??t?.file_path??t?.filePath??t?.filename;if(typeof n!="string")return false;if(r.pathSizeMin!==void 0)if(wi(r.pathSizeMin)){let o=xi(n);if(o===null||o<_i(r.pathSizeMin))return false}else {let o=bi(n);if(o===null||o<r.pathSizeMin)return false}if(r.pathSizeMax!==void 0)if(wi(r.pathSizeMax)){let o=xi(n);if(o===null||o>_i(r.pathSizeMax))return false}else {let o=bi(n);if(o===null||o>r.pathSizeMax)return false}return true}function Zp(r){let e=[],t=[];for(let n=0;n<r.length;n++){let o=r[n];if(!o||typeof o!="object"){t.push(`Hook at index ${n}: not an object, skipping`);continue}let s=o;if(typeof s.name!="string"||!s.name){t.push(`Hook at index ${n}: missing or invalid "name", skipping`);continue}let i=s.guide&&typeof s.guide=="object",a=s.deny&&typeof s.deny=="object",l=typeof s.plugin=="string";if(!i&&!a&&!l){t.push(`Hook "${s.name}": missing guide/deny/plugin, skipping`);continue}if(i&&typeof s.guide.say!="string"){t.push(`Hook "${s.name}": guide.say is required and must be string, skipping`);continue}if(a&&typeof s.deny.reason!="string"){t.push(`Hook "${s.name}": deny.reason is required and must be string, skipping`);continue}e.push(s);}return {valid:e,warnings:t}}var Cn=class extends mr{name="@crewx/yaml-hook-plugin";version="0.1.0";capabilities={required:["inject"]};hooks;agentMap;constructor(e){super(),this.hooks=e.hooks,this.agentMap=new Map((e.agents??[]).map(t=>[t.id,t]));}async run(e){let t=[],n=process.env.CREWX_TASK_LOG_PATH,o=process.env.CREWX_HOOK_LOG_VERBOSE==="1";for(let s of this.hooks)if(this.matchEntryLevel(s,e)&&s.guide){if(!this.matchRuleLevel(s.guide,e)){o&&n&&this.appendHookLog(n,{rule:s.name,action:"pass",once:s.guide.once??false,ctx:e,matched:false});continue}s.guide.once&&this.hasFired(e.sessionId,s.name)||(s.guide.once&&this.markFired(e.sessionId,s.name),t.push(s.guide.say),n&&this.appendHookLog(n,{rule:s.name,action:"inject",once:s.guide.once??false,ctx:e,matched:true,message:s.guide.say}));}return t.length?e.inject(t.join(`
63
+ `);}catch(s){throw s instanceof j?s:new j("DB_ERROR","Failed to save user message",s)}finally{n.close();}}saveAssistantMessage(e,t,r){if(!this.dbExists())return;let n=this.openHandle(true);try{let s=new Date().toISOString();n.db.update(A).set({last_message:t,updated_at:s}).where(eq(A.id,e)).run();}catch(s){throw s instanceof j?s:new j("DB_ERROR","Failed to save assistant message",s)}finally{n.close();}}updateThread(e,t){if(!this.dbExists())return;let r=this.openHandle(true);try{let n={updated_at:new Date().toISOString()};t.title!==void 0&&(n.title=t.title,n.title_locked=1),t.titleLocked!==void 0&&(n.title_locked=t.titleLocked?1:0),r.db.update(A).set(n).where(eq(A.id,e)).run();}catch(n){throw n instanceof j?n:new j("DB_ERROR","Failed to update thread",n)}finally{r.close();}}};function Ls(o){return o.replace(/<conversation_history[^>]*>[\s\S]*?<\/conversation_history>/g,"").split(`
64
+ `).filter(n=>!(n.startsWith("Loaded ")&&n.includes("layouts from")||n.includes("[dotenv@")||n.includes("[Nest]")&&n.includes("DEBUG")||n.startsWith("Registered custom layout:")||n.startsWith("Updated custom layout:"))).join(`
65
+ `).trim()}function js(o){if(!o)return "";let e=o;try{let t=JSON.parse(e);Array.isArray(t)?e=t.filter(r=>r?.type==="text"&&r?.text).map(r=>r.text).join(`
66
+ `):t&&typeof t=="object"&&t.result!==void 0&&(e=t.result||"");}catch{e=Ls(e);}return e}var Et=class{dbPath;constructor(e){this.dbPath=e??join(homedir(),".crewx","crewx.db");}getThreadRepo(){return new Tt({dbPath:this.dbPath})}updateThread(e,t){this.getThreadRepo().updateThread(e,{title:t.title});}async ensureThread(e,t,r){let n=this.getThreadRepo(),s=n.findThreadById(e);if(s){if(s.platform!==t)throw new Error(`Thread '${e}' already exists with platform '${s.platform}' \u2014 cannot change to '${t}' (platform is immutable)`);return}n.ensureThread(e,t,r);}async fetchHistory(e,t){let r=t?.limit??100,n=this.getThreadRepo(),s=n.findThreadById(e),i=n.findTopLevelTasks(e),a=new Set(["done","completed","success"]);i=i.filter(u=>(!u.status||a.has(u.status))&&(!t?.currentTraceId||u.trace_id!==t.currentTraceId)),i=i.slice(0,r);let d=s?.platform??"cli",c=this.rowsToMessages(i);return {threadId:e,platform:d,messages:c,metadata:{title:s?.title??void 0,firstMessage:s?.first_message??void 0,lastMessage:s?.last_message??void 0,messageCount:s?.message_count??0,updatedAt:s?.updated_at?new Date(s.updated_at).getTime():void 0}}}async saveUserMessage(e,t,r,n){this.getThreadRepo().saveUserMessage(e,t);}async saveAssistantMessage(e,t,r,n){this.getThreadRepo().saveAssistantMessage(e,t);}close(){}rowsToMessages(e){let t=[];for(let r of e){r.prompt&&t.push({id:`${r.id}-user`,text:r.prompt,isAssistant:false,timestamp:new Date(r.started_at).getTime()});let n=js(r.result);n&&t.push({id:`${r.id}-assistant`,text:n,isAssistant:true,timestamp:new Date(r.started_at).getTime()});}return t}};var Ye=class extends Ge{name="conversation";_provider;unsubStart=null;unsubEnd=null;constructor(e){super(),this._provider=new Et(e?.dbPath);}get conversationProvider(){return this._provider}attach(e){this.unsubStart=e.on("task:start",async t=>{if(!t.threadId)return;let r=t.platform??"cli";try{await this._provider.ensureThread(t.threadId,r,t.workspaceId),await this._provider.saveUserMessage(t.threadId,t.message??"");}catch{}}),this.unsubEnd=e.on("task:end",async t=>{if(!t.result)return;let r=t.metadata?.threadId;if(!r)return;let n=t.agentRef?.replace(/^@/,"")??"";try{await this._provider.saveAssistantMessage(r,t.result,n);}catch{}});}detach(e){this.unsubStart?.(),this.unsubStart=null,this.unsubEnd?.(),this.unsubEnd=null,this._provider.close?.();}};l();function yn(o){let e=W.resolve(o);return process.platform==="win32"&&(e=e.replace(/\\/g,"/"),e=e.replace(/^([A-Z]):/,(t,r)=>`${r.toLowerCase()}:`)),e.length>1&&!/^[a-zA-Z]:\/$/.test(e)&&(e=e.replace(/\/+$/,"")),e}function cr(o){let e=yn(o);return createHash("sha256").update(e).digest("hex")}function pi(o){return o?o.settings?.template?.exec:void 0}function gi(){try{let o=new Uint8Array(8);return globalThis.crypto.getRandomValues(o),Array.from(o,e=>e.toString(16).padStart(2,"0")).join("")}catch{let{randomBytes:o}=B("crypto");return o(8).toString("hex")}}var Tr=class o extends Qe{_agents;_templateEngine;_documentLoader;_layoutLoader;_layoutRenderer;_config;_projectRoot;_workspaceId;_workspaceName;_plugins=[];_tools=new Map;_activeAdapters=new Map;_pendingThreads=new Map;_remoteFactory;_remoteTargets=new Map;constructor(e,t={},r,n,s){super(),this._agents=new Map(e.map(d=>[d.id,d])),this._config=r,this._projectRoot=s??(typeof process<"u"?process.cwd():"/");let i=s??(typeof process<"u"?process.env.CREWX_WORKSPACE??process.cwd():"/");this._workspaceId=cr(i),this._workspaceName=basename(i);let a=pi(r);this._templateEngine=new Ve({execPolicy:t.execPolicy??a}),this._documentLoader=n??new Ce,this._layoutLoader=new Ke({templatesPath:Me()}),this._layoutRenderer=new Xe,this._remoteFactory=t.remoteFactory;}async resolveFileRemoteTarget(e){let t=this.getAgent(e),r=Array.isArray(t?.provider)?t?.provider[0]:t?.provider;if(!r?.startsWith("remote/"))return null;let n=r.slice(7),s=this.getRemoteProviderConfig(n);if(!s?.location?.startsWith("file://"))return null;let i=resolve(s.location.replace("file://","")),a=s.external_agent_id??e.replace(/^@/,""),d=this._remoteTargets.get(i);d||(d=(this._remoteFactory??(y=>o.loadYaml(y)))(i),this._remoteTargets.set(i,d),d.catch(()=>this._remoteTargets.delete(i)));let c=await d,u=c.getAgent("@"+a),p=Array.isArray(u?.provider)?u?.provider[0]:u?.provider;if(p?.startsWith("remote/"))throw new Error(`Chained remotes not allowed: "${n}" \u2192 "${p}"`);return {target:c,agentRef:"@"+a}}static async loadBuiltInConfig(e){let{yamlPath:t,dir:r}=Ut(),n;try{n=readFileSync(t,"utf-8");}catch(i){throw new Error(`[@crewx/sdk] Cannot read built-in config: ${t}
67
+ ${i.message}`)}let s=ut(n);if(s.documents&&typeof s.documents=="object"){let i={};for(let[a,d]of Object.entries(s.documents))if(d&&typeof d=="object"){let c=d;typeof c.path=="string"&&!isAbsolute(c.path)?i[a]={...c,path:resolve(r,c.path)}:i[a]=c;}else i[a]=d;return {...s,documents:i}}return s}static mergeCrewxConfig(e,t){let r=new Map;for(let k of e.agents??[])r.set(k.id,k);for(let k of t.agents??[])r.has(k.id)&&console.warn(`[agent-loader] User agent "${k.id}" overrides built-in`),r.set(k.id,k);let n=Array.from(r.values()),s={...e.layouts??{},...t.layouts??{}},i={...e.documents??{},...t.documents??{}},a=e,d=t,c=Nn(a.vars,d.vars),u=Nn(a.settings,d.settings),p;e.skills&&t.skills&&typeof e.skills=="object"&&typeof t.skills=="object"&&!Array.isArray(e.skills)&&!Array.isArray(t.skills)?p={...e.skills,...t.skills}:p=t.skills??e.skills;let f=[...e.hooks??[],...t.hooks??[]],y=mi(a.providers,d.providers),h={...e},x={...t};for(let k of ["agents","layouts","documents","skills","hooks","vars","settings","providers"])delete h[k],delete x[k];let R={...{...h,...x},agents:n,layouts:s,documents:i,skills:p};return f.length>0&&(R.hooks=f),c!==void 0&&(R.vars=c),u!==void 0&&(R.settings=u),y!==void 0&&(R.providers=y),R}static async loadYaml(e,t,r){let n=t?.includeBuiltIns!==false,s,i;if(n){let u=await o.loadBuiltInConfig(r);if(e!==void 0){let p=pt(e);s=o.mergeCrewxConfig(u,p),i=dirname(e);}else s=u,i=process.cwd();}else {if(e===void 0)throw new Error("[@crewx/sdk] loadYaml: path is required when includeBuiltIns is false");s=pt(e),i=dirname(e);}let a=new Ce(r);await a.load(s.documents,i);let d=s.agents??[];await Dn(d,s,t);let c=new o(d,t??{},s,a,i);return await c.use(new Ye),c}static async fromConfig(e,t,r,n){let s=t?.includeBuiltIns===true,i=e;if(s){let u=await o.loadBuiltInConfig(n);i=o.mergeCrewxConfig(u,e);}let a=new Ce(n);await a.load(i.documents,r??(typeof process<"u"?process.cwd():"/"));let d=i.agents??[];await Dn(d,i,t);let c=new o(d,t??{},i,a,r);return await c.use(new Ye),c}get agents(){return this._agents}get config(){return this._config}get plugins(){return this._plugins}get tools(){return this._tools}get workspaceId(){return this._workspaceId}get workspaceName(){return this._workspaceName}getAgent(e){let t=e.startsWith("@")?e.slice(1):e;return this._agents.get(t)}getRemoteProviderConfig(e){let t=this._config?.providers;return Array.isArray(t)?t.find(n=>n.type==="remote"&&n.id===e):void 0}computeTaskLogPath(e,t){let r=rr(t);return join(this._projectRoot,".crewx","logs",`${r}_${e}.log`)}registerTool(e,t){this._tools.set(e,{name:e,...t});}async use(e){this._plugins.includes(e)||(await e.attach(this),this._plugins.push(e));}handler(e){return ar(this,e)}async registerChannelAdapter(e){let{adapter:t,instanceId:r,config:n}=e;if(this._activeAdapters.has(r))throw new Error(`Adapter instance already registered: ${r}`);let s=new Set(t.manifest.capabilities),i=e.store??nr(r),a=e.defaultMode??"query",d=t.manifest.platform,c=e.agentRunner??{run:async(y,h,x)=>{let R=await(a==="execute"?this.execute.bind(this):this.query.bind(this))(`@${y}`,h,{threadId:x?.threadId,platform:d});return {output:R.ok?R.data:R.error?.message??""}}},u=e.onInbound??(async y=>{let h=y.routingHints?.agentId??e.defaultAgent;if(!h)return {accepted:false,reason:"no_agent"};let{output:x}=await c.run(h,y.text,{threadId:y.threadId});return {accepted:true,output:x}}),p=sr({instanceId:r,config:n,capabilities:s,db:i,agentRunner:c,onInbound:u}),f={adapter:t,ctx:p,state:"starting"};this._activeAdapters.set(r,f),this.emit("adapter:lifecycle",{adapterId:t.manifest.id,instanceId:r,state:"starting",timestamp:new Date});try{await t.start(p),f.state="started",this.emit("adapter:lifecycle",{adapterId:t.manifest.id,instanceId:r,state:"started",timestamp:new Date});}catch(y){throw f.state="failed",this.emit("adapter:lifecycle",{adapterId:t.manifest.id,instanceId:r,state:"failed",error:y instanceof Error?y:new Error(String(y)),timestamp:new Date}),this._activeAdapters.delete(r),y}}async unregisterChannelAdapter(e){let t=this._activeAdapters.get(e);if(t){t.state="stopping",this.emit("adapter:lifecycle",{adapterId:t.adapter.manifest.id,instanceId:e,state:"stopping",timestamp:new Date});try{await t.adapter.stop(t.ctx),t.state="stopped",this.emit("adapter:lifecycle",{adapterId:t.adapter.manifest.id,instanceId:e,state:"stopped",timestamp:new Date});}catch(r){t.state="failed",this.emit("adapter:lifecycle",{adapterId:t.adapter.manifest.id,instanceId:e,state:"failed",error:r instanceof Error?r:new Error(String(r)),timestamp:new Date});}finally{this._activeAdapters.delete(e);}}}async stopAllAdapters(e={}){let t=e.timeoutMs??1e4,r=Array.from(this._activeAdapters.keys()),n=await Promise.allSettled(r.map(s=>Promise.race([this.unregisterChannelAdapter(s),new Promise((i,a)=>setTimeout(()=>a(new Error(`Adapter stop timeout: ${s}`)),t))])));for(let s=0;s<n.length;s++)n[s].status==="rejected"&&console.error(`[crewx] adapter stop error (${r[s]}): ${n[s].reason}`);}async close(){await this.stopAllAdapters({timeoutMs:1e4});let e=[...this._remoteTargets.values()];this._remoteTargets.clear(),await Promise.allSettled(e.map(async r=>{try{await(await r).close();}catch(n){console.error(`[crewx] remote target close error: ${n instanceof Error?n.message:String(n)}`);}}));let t=[...this._plugins].reverse();for(let r of t)try{await r.detach(this);}catch(n){console.error(`[crewx] plugin ${r.name} detach error: ${n instanceof Error?n.message:String(n)}`);}this._plugins.length=0;}filterAgents(e){let t=a=>a?a.split(",").map(d=>d.trim().toLowerCase()).filter(Boolean):void 0,r=t(e.role),n=t(e.team),s=t(e.provider),i=Array.from(this._agents.values());return r&&(i=i.filter(a=>a.role&&r.some(d=>ne(a.role.toLowerCase(),d)))),n&&(i=i.filter(a=>a.team&&n.some(d=>ne(a.team.toLowerCase(),d)))),s&&(i=i.filter(a=>(Array.isArray(a.provider)?a.provider:[a.provider]).some(c=>s.some(u=>ne(c.toLowerCase(),u))))),i}renderAgentPrompt(e){let t=e.startsWith("@")?e.slice(1):e,r=this._agents.get(t);if(!r)throw new le(t,Array.from(this._agents.keys()));return r.inline?.prompt??r.inline?.system_prompt??r.description??`You are an expert ${t}.`}async renderPrompt(e,t){let n={...await this._documentLoader.buildContext(),...t?.documents??{}},s={...t,documents:n};return this._templateEngine.render(e,s)}registerLayout(e,t){this._layoutLoader.registerLayout(e,t);}async renderAgentPromptFull(e,t){let r=e.startsWith("@")?e.slice(1):e,n=this._agents.get(r);if(!n)throw new le(r,Array.from(this._agents.keys()));let s=this._resolveLayoutSpec(n,t?.layout),i=this._extractLayoutId(s),a=this._extractLayoutProps(n,s,t?.layout),d=this._layoutLoader.load(i,a),c=n.inline?.prompt??n.inline?.system_prompt??n.description??`You are an expert ${r}.`,u=await this._documentLoader.buildContext(),p=t?.env??(typeof process<"u"?process.env:{}),f=t?.vars?.security_key??gi(),y={...t?.vars??{},documents:u,env:p,agent:{id:n.id,name:n.name??n.id,role:n.role??"",team:n.team??"",description:n.description??""}},h=await this._templateEngine.render(c,y),x={mode:t?.session?.mode??"query",platform:t?.session?.platform??"cli",options:t?.session?.options??[]},w=n.provider,R=Array.isArray(w)?w:typeof w=="string"&&w.length>0?[w]:[],k=R.join(", ")||(typeof w=="string"?w:""),C=n.options,S=!Array.isArray(C)&&typeof C=="object"&&C!==null?C:void 0,O=Array.isArray(C)?C:void 0,U={};for(let[M,_]of Object.entries(u))U[M]={content:_.content??"",toc:_.toc,summary:_.summary,path:_.path};let T={user_input:t?.vars?.user_input??void 0,agent:{id:n.id,name:n.name??n.id,role:n.role??"",team:n.team??"",description:n.description??"",provider:k,providerList:R,model:n.inline?.model,workingDirectory:n.working_directory??n.workingDirectory??".",inline:{...n.inline??{},prompt:h},specialties:n.specialties??[],capabilities:n.capabilities??[],remote:n.remote??null,optionsByMode:S,optionsArray:O},agentMetadata:{specialties:n.specialties??[],capabilities:n.capabilities??[],description:n.description??""},documents:U,skills:t?.skills??[],session:x,env:p,vars:{security_key:f,...t?.vars??{}},props:{...a??{},...t?.messages&&t.messages.length>0?{showConversationHistory:true}:{}},platform:x.platform,mode:x.mode,messages:t?.messages??[],tools:this._tools.size>0?{list:Array.from(this._tools.values()).map(M=>({name:M.name,description:M.description,parameters:M.parameters})),json:JSON.stringify(Array.from(this._tools.values()).map(M=>({name:M.name,description:M.description,parameters:M.parameters})),null,2),count:this._tools.size}:null,metadata:{}};return this._layoutRenderer.render(d,T)}_filterToolsByMode(e){return e?e.map(t=>this._tools.get(t)).filter(t=>t!==void 0):Array.from(this._tools.values())}_resolveLayoutSpec(e,t){if(t!==void 0)return t;let r=e.inline?.layout;if(r!==void 0)return r;let n=this._config?.layouts?.default;return typeof n=="string"&&n?n:"crewx/default"}_extractLayoutId(e){if(typeof e=="string")return e;if("id"in e)return e.id;let t=`crewx/__inline_${Date.now()}`;return this._layoutLoader.registerLayout(t,e.template),t}_extractLayoutProps(e,t,r){let n=e.inline?.layout,s=n&&typeof n=="object"&&"props"in n?n.props:void 0,i=r&&typeof r=="object"&&"id"in r?r.props:void 0;if(s||i)return {...s??{},...i??{}}}_getConversationProvider(){return this._plugins.find(t=>t.name==="conversation")?.conversationProvider}async _fetchHistoryMessages(e,t,r){if(r&&r.length>0)return r;if(!e)return;let n=this._getConversationProvider();if(n)try{let s=await n.fetchHistory(e,{currentTraceId:t});return s.messages.length===0?void 0:ir(s)}catch{return}}_resolveTimeout(e){let t=Vr();return e==="query"?t.queryMs:t.executeMs}emitToolEvents(e,t,r,n,s,i,a){try{let c=ye[r]?.parseEvent?.(n)??Kt(new Date().toISOString(),n);for(let u of c)u.type==="tool_use"&&u.toolName&&this.emit("tool:observed:before",{traceId:e,timestamp:new Date,agentRef:t,agentId:s,threadId:i,sessionId:a,provider:r,tool:{name:u.toolName,rawName:u.toolName,input:u.toolInput?this.tryParseJson(u.toolInput):void 0,toolUseId:u.toolUseId}}),u.type==="tool_result"&&this.emit("tool:observed:after",{traceId:e,timestamp:new Date,agentRef:t,agentId:s,threadId:i,sessionId:a,provider:r,tool:{name:u.toolName??"unknown",rawName:u.toolName??"unknown",toolUseId:u.toolUseId,result:u.resultPreview,isError:u.isError}});}catch{}}emitTaskLogEntries(e,t,r,n,s,i,a){try{for(let d of a)d.type==="tool_use"&&d.toolName&&this.emit("tool:observed:before",{traceId:e,timestamp:new Date,agentRef:t,agentId:r,threadId:n,sessionId:s,provider:i,tool:{name:d.toolName,rawName:d.toolName,input:d.toolInput?this.tryParseJson(d.toolInput):void 0,toolUseId:d.toolUseId}}),d.type==="tool_result"&&this.emit("tool:observed:after",{traceId:e,timestamp:new Date,agentRef:t,agentId:r,threadId:n,sessionId:s,provider:i,tool:{name:d.toolName??"unknown",rawName:d.toolName??"unknown",toolUseId:d.toolUseId,result:d.resultPreview,isError:d.isError}});}catch{}}tryParseJson(e){try{return JSON.parse(e)}catch{return e}}async query(e,t,r){let n=await this.resolveFileRemoteTarget(e);if(n)return n.target.query(n.agentRef,t,r);let s=Date.now(),i=be("tsk"),a=new Date,d;try{d=mt(e,Array.from(this._agents.values()));}catch(_){if(_ instanceof le){this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"query",metadata:{...r?.metadata??{}},threadId:r?.threadId,platform:r?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName});let D=Date.now()-s,v={code:"AGENT_NOT_FOUND",message:_.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"query",durationMs:D,error:v,metadata:r?.metadata?{...r.metadata}:void 0}),{ok:false,data:"",error:v,meta:{agentId:e.replace(/^@/,""),provider:"",durationMs:D}}}throw _}let c=Array.isArray(d.provider)?d.provider[0]??"cli/claude":d.provider,u=r?.provider??c,p=r?.model??d.inline?.model;p&&p.includes("{{")&&(p=await this._templateEngine.render(p,{...r?.vars??{}}));let f;try{f=ue(u);}catch(_){this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"query",metadata:{...r?.metadata??{}},threadId:r?.threadId,platform:r?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName});let D=Date.now()-s,v={code:"PROVIDER_ERROR",message:_.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"query",durationMs:D,error:v,metadata:r?.metadata?{...r.metadata}:void 0}),{ok:false,data:"",error:v,meta:{agentId:d.id,provider:u,model:p,durationMs:D}}}let y=await this._fetchHistoryMessages(r?.threadId,i,r?.messages),h;try{h=await this.renderAgentPromptFull(e,{session:{mode:"query",platform:r?.platform},vars:{user_input:t,...r?.vars??{}},messages:y});}catch(_){console.error(`[crewx] renderAgentPromptFull failed for ${e}: ${_ instanceof Error?_.message:String(_)}`);}let x,w,R,k=p,C=false,S=_=>{C||(C=true,this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"query",pid:_,model:k,provider:u,codingAgentCommand:x,renderedPrompt:h,metadata:{...r?.metadata??{},provider:u},threadId:r?.threadId,platform:r?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName}));},O=d.options,U=Array.isArray(O?.query?.tools)?O.query.tools:void 0,H=this._tools.size>0?this._filterToolsByMode(U):[],T=(()=>{let _=O?.query;if(!_||Array.isArray(_))return;let{tools:D,effort:v,mode:q,...ve}=_,ke=Object.entries(ve).filter(([,F])=>F!=null);if(ke.length!==0)return Object.fromEntries(ke.map(([F,Q])=>[F,String(Q)]))})(),M=d.inline?.max_steps;u.startsWith("api/")&&S();try{let _=await f.query(t,{model:p,effort:O?.query?.effort,mode:O?.query?.mode,context:r?.context,systemPrompt:h??d.inline?.system_prompt??d.inline?.prompt??d.description??`You are ${d.id}.`,additionalArgs:Array.isArray(O?.query)?O.query:void 0,tools:H.length>0?H:void 0,maxSteps:M,configOptions:T,timeoutMs:this._resolveTimeout("query"),env:{CREWX_AGENT_ID:d.id,CREWX_AGENT_ROLE:d.role??"",CREWX_AGENT_TEAM:d.team??"",CREWX_USER_ID:process.env.USER||process.env.USERNAME||"unknown",CREWX_TRACE_ID:i,CREWX_PARENT_TASK_ID:i,CREWX_TASK_ID:i,CREWX_CALLER_AGENT_ID:process.env.CREWX_AGENT_ID??"",CREWX_THREAD_ID:r?.threadId??"",CREWX_PROVIDER:u,CREWX_SESSION_ID:"",CREWX_TASK_LOG_PATH:this.computeTaskLogPath(i,a)},onPid:v=>S(v),onOutput:(v,q)=>{this.emit("task:output",{traceId:i,timestamp:new Date,agentRef:e,output:v,level:q}),q==="stdout"&&this.emitToolEvents(i,e,u,v,d.id,r?.threadId??"","");},onTaskLog:v=>{this.emitTaskLogEntries(i,e,d.id,r?.threadId??"","",u,v);for(let q of v)this.emit("task:output",{traceId:i,timestamp:new Date,agentRef:e,output:JSON.stringify(q),level:"info"});},onCommand:v=>{x=v;},onUsage:v=>{w=v;},onExitCode:v=>{R=v;},onModel:v=>{k||(k=v);}});S();let D=Date.now()-s;return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"query",result:_,durationMs:D,exitCode:R,inputTokens:w?.inputTokens,outputTokens:w?.outputTokens,cachedInputTokens:w?.cachedInputTokens,costUsd:w?.costUsd,model:k,metadata:{...r?.metadata??{},...r?.threadId?{threadId:r.threadId}:{}}}),{ok:!0,data:_,meta:{agentId:d.id,provider:u,model:p,durationMs:D}}}catch(_){if(_ instanceof te){let q=be("thd");return this._pendingThreads.set(q,{agentRef:d.id,providerStr:u,continuationState:_.continuationState,toolCall:_.toolCall,traceId:i,startMs:s,model:p}),{ok:true,status:"requires_action",data:"",toolCall:_.toolCall,threadId:q,meta:{agentId:d.id,provider:u,model:p,durationMs:Date.now()-s}}}S();let D=Date.now()-s,v={code:"QUERY_FAILED",message:_.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"query",durationMs:D,error:v,exitCode:R,inputTokens:w?.inputTokens,outputTokens:w?.outputTokens,cachedInputTokens:w?.cachedInputTokens,costUsd:w?.costUsd,model:k,metadata:r?.metadata?{...r.metadata}:void 0}),{ok:false,data:"",error:v,meta:{agentId:d.id,provider:u,model:p,durationMs:D}}}}async continueQuery(e,t){let r=this._pendingThreads.get(e);if(!r)return {ok:false,data:"",error:{code:"THREAD_NOT_FOUND",message:`No pending thread: ${e}`},meta:{agentId:"",provider:"",durationMs:0}};this._pendingThreads.delete(e);let n=ue(r.providerStr);if(!n.continueWithToolResults)return {ok:false,data:"",error:{code:"UNSUPPORTED",message:"Provider does not support client tool continuation"},meta:{agentId:r.agentRef,provider:r.providerStr,durationMs:0}};let s=t.map(i=>({...i,toolName:r.toolCall.toolCallId===i.toolCallId?r.toolCall.toolName:i.toolCallId}));try{let i=await n.continueWithToolResults(r.continuationState,s),a=Date.now()-r.startMs;return this.emit("task:end",{traceId:r.traceId,timestamp:new Date,agentRef:r.agentRef,mode:"query",result:i,durationMs:a}),{ok:!0,status:"complete",data:i,meta:{agentId:r.agentRef,provider:r.providerStr,model:r.model,durationMs:a}}}catch(i){if(i instanceof te)return this._pendingThreads.set(e,{...r,continuationState:i.continuationState,toolCall:i.toolCall}),{ok:true,status:"requires_action",data:"",toolCall:i.toolCall,threadId:e,meta:{agentId:r.agentRef,provider:r.providerStr,model:r.model,durationMs:Date.now()-r.startMs}};let a=Date.now()-r.startMs;return {ok:false,data:"",error:{code:"CONTINUE_FAILED",message:i.message},meta:{agentId:r.agentRef,provider:r.providerStr,model:r.model,durationMs:a}}}}async execute(e,t,r){let n=await this.resolveFileRemoteTarget(e);if(n)return n.target.execute(n.agentRef,t,r);let s=Date.now(),i=be("tsk"),a=new Date,d;try{d=mt(e,Array.from(this._agents.values()));}catch(_){if(_ instanceof le){this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"execute",metadata:{...r?.metadata??{}},threadId:r?.threadId,platform:r?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName});let D=Date.now()-s,v={code:"AGENT_NOT_FOUND",message:_.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"execute",durationMs:D,error:v,metadata:r?.metadata?{...r.metadata}:void 0}),{ok:false,data:"",error:v,meta:{agentId:e.replace(/^@/,""),provider:"",durationMs:D}}}throw _}let c=Array.isArray(d.provider)?d.provider[0]??"cli/claude":d.provider,u=r?.provider??c,p=r?.model??d.inline?.model;p&&p.includes("{{")&&(p=await this._templateEngine.render(p,{...r?.vars??{}}));let f;try{f=ue(u);}catch(_){this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"execute",metadata:{...r?.metadata??{}},threadId:r?.threadId,platform:r?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName});let D=Date.now()-s,v={code:"PROVIDER_ERROR",message:_.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"execute",durationMs:D,error:v,metadata:r?.metadata?{...r.metadata}:void 0}),{ok:false,data:"",error:v,meta:{agentId:d.id,provider:u,model:p,durationMs:D}}}let y=await this._fetchHistoryMessages(r?.threadId,i,r?.messages),h;try{h=await this.renderAgentPromptFull(e,{session:{mode:"execute",platform:r?.platform},vars:{user_input:t,...r?.vars??{}},messages:y});}catch(_){console.error(`[crewx] renderAgentPromptFull failed for ${e}: ${_ instanceof Error?_.message:String(_)}`);}let x,w,R,k=p,C=false,S=_=>{C||(C=true,this.emit("task:start",{traceId:i,timestamp:a,agentRef:e,message:t,mode:"execute",pid:_,model:k,provider:u,codingAgentCommand:x,renderedPrompt:h,metadata:{...r?.metadata??{},provider:u},threadId:r?.threadId,platform:r?.platform??"cli",workspaceId:this._workspaceId,workspaceName:this._workspaceName}));},O=d.options,U=Array.isArray(O?.execute?.tools)?O.execute.tools:void 0,H=this._tools.size>0?this._filterToolsByMode(U):[],T=(()=>{let _=O?.execute;if(!_||Array.isArray(_))return;let{tools:D,effort:v,mode:q,...ve}=_,ke=Object.entries(ve).filter(([,F])=>F!=null);if(ke.length!==0)return Object.fromEntries(ke.map(([F,Q])=>[F,String(Q)]))})(),M=d.inline?.max_steps;u.startsWith("api/")&&S();try{let _=await f.execute(t,{model:p,effort:O?.execute?.effort,mode:O?.execute?.mode,context:r?.context,systemPrompt:h??d.inline?.system_prompt??d.inline?.prompt??d.description??`You are ${d.id}.`,additionalArgs:Array.isArray(O?.execute)?O.execute:void 0,tools:H.length>0?H:void 0,maxSteps:M,configOptions:T,timeoutMs:this._resolveTimeout("execute"),env:{CREWX_AGENT_ID:d.id,CREWX_AGENT_ROLE:d.role??"",CREWX_AGENT_TEAM:d.team??"",CREWX_USER_ID:process.env.USER||process.env.USERNAME||"unknown",CREWX_TRACE_ID:i,CREWX_PARENT_TASK_ID:i,CREWX_TASK_ID:i,CREWX_CALLER_AGENT_ID:process.env.CREWX_AGENT_ID??"",CREWX_THREAD_ID:r?.threadId??"",CREWX_PROVIDER:u,CREWX_SESSION_ID:"",CREWX_TASK_LOG_PATH:this.computeTaskLogPath(i,a)},onPid:v=>S(v),onOutput:(v,q)=>{this.emit("task:output",{traceId:i,timestamp:new Date,agentRef:e,output:v,level:q}),q==="stdout"&&this.emitToolEvents(i,e,u,v,d.id,r?.threadId??"","");},onTaskLog:v=>{this.emitTaskLogEntries(i,e,d.id,r?.threadId??"","",u,v);for(let q of v)this.emit("task:output",{traceId:i,timestamp:new Date,agentRef:e,output:JSON.stringify(q),level:"info"});},onCommand:v=>{x=v;},onUsage:v=>{w=v;},onExitCode:v=>{R=v;},onModel:v=>{k||(k=v);}});S();let D=Date.now()-s;return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"execute",result:_,durationMs:D,exitCode:R,inputTokens:w?.inputTokens,outputTokens:w?.outputTokens,cachedInputTokens:w?.cachedInputTokens,costUsd:w?.costUsd,model:k,metadata:{...r?.metadata??{},...r?.threadId?{threadId:r.threadId}:{}}}),{ok:!0,data:_,meta:{agentId:d.id,provider:u,model:p,durationMs:D}}}catch(_){S();let D=Date.now()-s,v={code:"EXECUTE_FAILED",message:_.message};return this.emit("task:end",{traceId:i,timestamp:new Date,agentRef:e,mode:"execute",durationMs:D,error:v,exitCode:R,inputTokens:w?.inputTokens,outputTokens:w?.outputTokens,cachedInputTokens:w?.cachedInputTokens,costUsd:w?.costUsd,model:k,metadata:r?.metadata?{...r.metadata}:void 0}),{ok:false,data:"",error:v,meta:{agentId:d.id,provider:u,model:p,durationMs:D}}}}};function Nn(o,e){let t=Er(o)?o:void 0,r=Er(e)?e:void 0;if(!(!t&&!r))return {...t??{},...r??{}}}function Er(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}function mi(o,e){let t=Array.isArray(o)?o:void 0,r=Array.isArray(e)?e:void 0;if(!t&&!r)return;let n=a=>{if(!Er(a))return;let d=a.id;if(typeof d=="string")return `id:${d}`;let c=a.name;if(typeof c=="string")return `name:${c}`},s=new Set;for(let a of r??[]){let d=n(a);d&&s.add(d);}let i=[];for(let a of t??[]){let d=n(a);d&&s.has(d)||i.push(a);}for(let a of r??[])i.push(a);return i}async function Dn(o,e,t){if(o.some(n=>(Array.isArray(n.provider)?n.provider:[n.provider]).some(i=>i.startsWith("api/")))){let{registerApiProviders:n}=await Promise.resolve().then(()=>(pr(),vn));n(t?.api);}yi(o,e),hi(o,e),fi(o);}function fi(o){if(!o.some(r=>(Array.isArray(r.provider)?r.provider:[r.provider]).some(s=>s.startsWith("acp/"))))return;let{registerAcpProviders:t}=(Rr(),Ht(An));t();}function yi(o,e){if(!o.some(i=>(Array.isArray(i.provider)?i.provider:[i.provider]).some(d=>d.startsWith("remote/"))))return;let r=e.providers;if(!Array.isArray(r))return;let{createRemoteProviderFactory:n}=(Cr(),Ht(bn)),s=new Map;for(let i of r)i.type==="remote"&&typeof i.id=="string"&&s.set(i.id,i);s.size>0&&ce("remote",n(s,ue));}function hi(o,e){if(!o.some(i=>(Array.isArray(i.provider)?i.provider:[i.provider]).some(d=>d.startsWith("plugin/"))))return;let r=e.providers;if(!Array.isArray(r))return;let{createPluginProviderFactory:n}=(br(),Ht(In)),s=new Map;for(let i of r)i.type==="plugin"&&typeof i.id=="string"&&s.set(i.id,i);s.size>0&&ce("plugin",n(s));}l();var wi="crewx:fs:",Sr=class{prefix;store;constructor(e){this.prefix=e?.prefix??wi,this.store=e?.storage??new Map;}async readFile(e){let t=this.toKey(e),r=this.store.get(t);if(r===void 0)throw new Error(`BrowserFsAdapter: file not found: ${e}`);return r}async exists(e){return this.store.has(this.toKey(e))}resolvePath(...e){let t=e.map(i=>i.replace(/\\/g,"/")).join("/").replace(/\/+/g,"/"),r=t.split("/"),n=[];for(let i of r)i==="."||i===""||(i===".."?n.pop():n.push(i));let s=n.join("/");return t.startsWith("/")?`/${s}`:s}isAbsolute(e){return e.startsWith("/")}setItem(e,t){this.store.set(this.toKey(e),t);}removeItem(e){this.store.delete(this.toKey(e));}keys(){return Array.from(this.store.keys()).filter(e=>e.startsWith(this.prefix)).map(e=>e.slice(this.prefix.length))}toKey(e){return `${this.prefix}${e.replace(/\\/g,"/")}`}};l();function xi(o,e){let t=o.skills?.include;if(t===void 0)return [...e];if(t.length===0)return [];let r=new Set(t);return e.filter(n=>r.has(n))}oe();ur();pr();l();mr();xe();fr();yr();_r();Rr();qt();Le();l();var Ir=0;function vi(o){let e=Array.from(o.agents.keys());return {name:"delegate_to_agent",description:`Delegate a task to another agent. Available agents: ${e.join(", ")}`,parameters:{type:"object",properties:{agent:{type:"string",description:`Agent ID to delegate to. One of: ${e.join(", ")}`},message:{type:"string",description:"Task description for the target agent"},mode:{type:"string",description:'Execution mode: "query" for questions, "execute" for actions. Default: query'}},required:["agent","message"]},execute:async t=>{if(Ir>=3)return "Error: Maximum delegation depth (3) reached. Cannot delegate further.";let r=t.agent,n=t.message,s=t.mode??"query";if(!e.includes(r))return `Error: Unknown agent "${r}". Available: ${e.join(", ")}`;Ir++;try{if(s==="execute"){let a=await o.execute(r,n);return a.ok?a.data:`Error: ${a.error?.message??"Unknown error"}`}let i=await o.query(r,n);return i.ok?i.data:`Error: ${i.error?.message??"Unknown error"}`}finally{Ir--;}}}}l();var $n=typeof process<"u"?process.env:{};function ki(){return $n.CREWX_CLI||"npx crewx"}function _i(){return $n.CREWX_WORKSPACE||(typeof process<"u"?process.cwd():"/")}l();var Ri=/^[a-zA-Z0-9._-]+$/,Or=class{constructor(e){this.storage=e;}storage;listBoxes(e){this.validateId(e);let r=this.storage.listBoxes(e).map(n=>this.toBoxResponse(n));return {boxes:r,total:r.length}}getBox(e,t){this.validateId(e),this.validateId(t);let r=this.storage.findBox(e,t);return r?this.toBoxResponse(r):null}createBox(e,t){this.validateId(e);let r=this.generateBoxId(),n=new Date().toISOString(),s=this.storage.insertBox(e,{id:r,seq:t.seq,firstTaskId:t.firstTaskId,midTaskId:t.midTaskId,lastTaskId:t.lastTaskId,taskCount:t.taskCount,summary:t.summary??null,sourceTokens:t.sourceTokens,summaryTokens:t.summaryTokens??null,createdAt:n});return this.toBoxResponse(s)}toBoxResponse(e){return {id:e.id,threadId:e.thread_id,seq:e.seq,firstTaskId:e.first_task_id,lastTaskId:e.last_task_id,taskCount:e.task_count,sourceTokens:e.source_tokens,summaryTokens:e.summary_tokens,summary:e.summary,previewFirst:this.storage.getTaskPreview(e.first_task_id,200),previewMid:this.storage.getTaskPreview(e.mid_task_id,200),previewLast:this.storage.getTaskPreview(e.last_task_id,200),createdAt:e.created_at}}validateId(e){if(!Ri.test(e))throw new Error(`Invalid ID format: ${e}`)}generateBoxId(){return be("box")}};l();function Pi(o,e,t,r,n){let{maxTokens:s,hotzoneRatio:i,warmzoneRatio:a}=r,d=s*i,c=s*a,u=d+c,p=e.getThreadMessages(o),f=[],y=0,h=false,x=[];for(let k=0;k<p.length;k+=2){let C=p[k],S=p[k+1],O=C?.content||"",U=S?.content||"",H=n.countTokens(O+U),T=[];C&&T.push(C),S&&T.push(S),x.push({messages:T,tokens:H});}for(let k=x.length-1;k>=0;k--){let C=x[k];if(y+C.tokens>d){h=true;break}y+=C.tokens,f.unshift(...C.messages);}let w=[],R=0;if(h&&c>0)try{let{boxes:k}=t.listBoxes(o);for(let C=k.length-1;C>=0;C--){let S=k[C],O=S.summaryTokens??S.sourceTokens;if(R+O>c)break;R+=O,w.unshift({boxId:S.id,seq:S.seq,taskCount:S.taskCount,sourceTokens:S.sourceTokens,summary:S.summary,previewFirst:S.previewFirst,previewMid:S.previewMid,previewLast:S.previewLast,createdAt:S.createdAt});}}catch(k){if(k instanceof Error&&!/not found/i.test(k.message))throw k}return {hot:f,warm:w,hotTokens:y,warmTokens:R,hotOverflow:h,totalBudget:u,config:{maxTokens:s,hotzoneRatio:i,warmzoneRatio:a}}}Le();Ae();l();var $t=class extends Error{constructor(t,r){super(`Task ${t} timed out after ${r}ms`);this.taskId=t;this.timeoutMs=r;this.name="ParallelRunnerTimeoutError";}taskId;timeoutMs},at=class{constructor(e={}){this.defaults=e;}defaults;metrics={totalTasks:0,startedTasks:0,completedTasks:0,successCount:0,failureCount:0,totalDurationMs:0,averageDurationMs:0,throughput:0};async run(e,t={}){if(!Array.isArray(e))throw new TypeError("ParallelRunner.run expects an array of tasks");if(e.length===0)return this.metrics={totalTasks:0,startedTasks:0,completedTasks:0,successCount:0,failureCount:0,totalDurationMs:0,averageDurationMs:0,throughput:0},[];let r=this.mergeOptions(t),n=Math.max(1,r.maxConcurrency??5),s=r.timeoutMs,i=r.failFast??false,a=r.callbacks,d=r.evaluateTaskSuccess??(()=>true),c=[],u=0,p=0,f=0,y=false,h=0,x=performance.now(),w=async T=>{a?.onTaskStart&&await a.onTaskStart(T),f+=1;let M=new AbortController,_={signal:M.signal},D,v;typeof s=="number"&&Number.isFinite(s)&&s>0&&(v=new Promise((F,Q)=>{D=setTimeout(()=>{let _e=new $t(T.id,s);M.abort(_e),Q(_e);},s);}));let q=performance.now(),ve=T.run(_),ke=v?Promise.race([ve,v]):ve;try{let F=await ke,Q=performance.now(),_e=Q-q,Oe=d(F,T),lt={taskId:T.id,success:Oe,value:F,durationMs:_e,startedAt:q,finishedAt:Q,metadata:T.metadata,aborted:!1};c.push(lt),Oe?u+=1:p+=1,a?.onTaskComplete&&await a.onTaskComplete(lt),i&&!Oe&&(y=!0);}catch(F){let Q=performance.now(),_e=Q-q,Oe=F instanceof Error?F:new Error(String(F)),lt={taskId:T.id,success:false,error:Oe,durationMs:_e,startedAt:q,finishedAt:Q,metadata:T.metadata,aborted:M.signal.aborted};c.push(lt),p+=1,a?.onError&&await a.onError(T,Oe,_e),i&&(y=true);}finally{D&&clearTimeout(D),v&&ve.catch(()=>{});}},R=async()=>{for(;!y;){let T=h;if(T>=e.length)break;h+=1;let M=e[T];if(!M||(await w(M),y))break}},k=Math.min(n,e.length),C=[];for(let T=0;T<k;T++)C.push(R());await Promise.all(C);let O=performance.now()-x,U=c.length?c.reduce((T,M)=>T+M.durationMs,0)/c.length:0,H=O>0?c.length/(O/1e3):c.length;return this.metrics={totalTasks:e.length,startedTasks:f,completedTasks:c.length,successCount:u,failureCount:p,totalDurationMs:O,averageDurationMs:U,throughput:H},c}getMetrics(){return this.metrics}mergeOptions(e){return {maxConcurrency:e.maxConcurrency??this.defaults.maxConcurrency,timeoutMs:e.timeoutMs??this.defaults.timeoutMs,failFast:e.failFast??this.defaults.failFast,evaluateTaskSuccess:e.evaluateTaskSuccess??this.defaults.evaluateTaskSuccess,callbacks:this.mergeCallbacks(this.defaults.callbacks,e.callbacks)}}mergeCallbacks(e,t){if(!(!e&&!t))return {onTaskStart:async r=>{e?.onTaskStart&&await e.onTaskStart(r),t?.onTaskStart&&await t.onTaskStart(r);},onTaskComplete:async r=>{e?.onTaskComplete&&await e.onTaskComplete(r),t?.onTaskComplete&&await t.onTaskComplete(r);},onError:async(r,n,s)=>{e?.onError&&await e.onError(r,n,s),t?.onError&&await t.onError(r,n,s);}}}};l();l();var dt=class{async query(e){throw new Error("AgentRuntime.query is not implemented. Provide a subclass or mock AgentRuntime.prototype.query.")}async execute(e){throw new Error("AgentRuntime.execute is not implemented. Provide a subclass or mock AgentRuntime.prototype.execute.")}};var Ln=3,jn=3e4,Hn=500,Ai=o=>{if(typeof o!="number"||Number.isNaN(o)||!Number.isFinite(o))return Ln;let e=Math.floor(o);return e>0?e:Ln},Ci=o=>o===void 0||typeof o!="number"||Number.isNaN(o)||o<=0?jn:o,bi=o=>{if(!o)return {maxRetries:0,retryDelay:Hn};let e=Number.isInteger(o.maxRetries)&&o.maxRetries>=0?o.maxRetries:0,t=typeof o.retryDelay=="number"&&o.retryDelay>=0?o.retryDelay:Hn;return {maxRetries:e,retryDelay:t}},Mr=o=>{let e=o.reason;return e instanceof Error?e:typeof e=="string"?new Error(e):new Error("Parallel operation aborted")},Ti=(o,e)=>o<=0?Promise.resolve():new Promise((t,r)=>{let n=setTimeout(()=>{e.removeEventListener("abort",s),t();},o),s=()=>{clearTimeout(n),r(Mr(e));};if(e.aborted){s();return}e.addEventListener("abort",s,{once:true});}),Ei=async(o,e,t)=>{let r,n;for(let s=0;s<=e.maxRetries;s++){if(t.aborted)throw Mr(t);try{let i=await o();if(r=i,i.success||s===e.maxRetries)return i}catch(i){if(n=i,t.aborted)throw Mr(t);if(s===e.maxRetries)throw i instanceof Error?i:new Error(String(i))}s<e.maxRetries&&await Ti(e.retryDelay,t);}if(r)return r;throw n?n instanceof Error?n:new Error(String(n)):new Error("Parallel helper encountered an unexpected state")},Un=(o,e,t)=>{e.completed+=1,t?e.success+=1:e.failure+=1;try{o.onProgress?.(e.completed,e.total);}catch(r){process.env.NODE_ENV!=="production"&&console.warn("Parallel helper onProgress callback threw an error:",r);}},Si=o=>o.map(t=>({metadata:t.metadata,taskResult:t})).slice().sort((t,r)=>t.metadata.index-r.metadata.index).map(({metadata:t,taskResult:r})=>{if(r.value){let s=r.value;return {...s,agentId:s.agentId??t.request.agentId,metadata:{...s.metadata,requestIndex:t.index,mode:t.mode}}}let n=r.error??new Error("Unknown error");return {agentId:t.request.agentId,content:n.message,success:false,metadata:{error:n.message,aborted:r.aborted??false,requestIndex:t.index,mode:t.mode}}}),Ii=o=>o.filter(e=>!e.success).map(e=>{let t=e.metadata;if(e.error instanceof Error)return {index:t.index,error:e.error};if(e.value&&!e.value.success){let r=String(e.value.metadata?.error??e.value.content??"Agent returned unsuccessful result");return {index:t.index,error:new Error(r)}}return {index:t.index,error:new Error("Unknown failure")}}),Oi=(o,e)=>({onTaskComplete:async t=>{Un(e,o,t.success);},onError:async()=>{Un(e,o,false);}}),qn=async(o,e,t={})=>{if(!Array.isArray(o))throw new TypeError("Parallel helpers expect an array of requests");if(o.length===0){let w={total:0,completed:0,successCount:0,failureCount:0,results:[],errors:[],metrics:{totalTasks:0,startedTasks:0,completedTasks:0,successCount:0,failureCount:0,totalDurationMs:0,averageDurationMs:0,throughput:0}};return t.onComplete?.(w),[]}let r=Ai(t.concurrency),n=Ci(t.timeout),s=bi(t.retryPolicy),i=new at,a=new dt,d=o.map((x,w)=>({id:`${e}:${x.agentId??"anonymous"}:${w}`,metadata:{index:w,mode:e,request:x},run:R=>Ei(()=>e==="query"?a.query(x):a.execute(x),s,R.signal)})),c={completed:0,success:0,failure:0,total:o.length},u=await i.run(d,{maxConcurrency:r,timeoutMs:n,evaluateTaskSuccess:x=>x.success,callbacks:Oi(c,t)}),p=Si(u),f=Ii(u),y=i.getMetrics(),h={total:o.length,completed:o.length,successCount:p.filter(x=>x.success).length,failureCount:p.filter(x=>!x.success).length,results:p,errors:f,metrics:y};return t.onComplete?.(h),p},Mi=(o,e)=>qn(o,"query",e),Ni=(o,e)=>qn(o,"execute",e);br();Cr();Ar();Pr();l();l();var Lt=class{capabilities={required:[]}};l();l();l();var Fn=2e3;function Wn(o){let e=o.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\u2028\u2029]/g,"");return e.length<=Fn?e:e.slice(0,Fn-11)+" [redacted]"}var Fi=10*1024*1024,Wi={b:1,kb:1024,mb:1024*1024,gb:1024*1024*1024};function Nr(o,e){return o===void 0?true:Array.isArray(o)?o.includes(e):o===e}function Bi(o,e){return o===void 0?true:Array.isArray(o)?o.some(t=>e.includes(t)):e.includes(o)}function zn(o){if(typeof o=="number")return o;let e=o.match(/^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb)?$/i);if(!e)return 0;let t=parseFloat(e[1]),r=(e[2]??"b").toLowerCase();return Math.floor(t*(Wi[r]??1))}function Vn(o){return typeof o=="string"}function Kn(o){try{let e=statSync(o);return e.size>Fi?(process.stderr.write(`[YamlHookPlugin] File too large for line count: ${o} (${e.size} bytes)
68
+ `),null):readFileSync(o,"utf8").split(`
69
+ `).length}catch{return null}}function Jn(o){try{return statSync(o).size}catch{return null}}function zi(o,e,t){if(!o)return true;let r=e,n=r?.path??r?.file_path??r?.filePath??r?.filename;if(typeof n!="string")return false;if(ne(n,o))return true;if(t&&n.startsWith("/")){let{relative:s,isAbsolute:i}=B("path");if(i(n)){let a=s(t,n);if(a&&!a.startsWith("..")&&ne(a,o))return true}}return false}function Vi(o,e){return o?JSON.stringify(e).includes(o):true}function Ki(o,e){if(!o)return true;try{let t=new RegExp(o),r=JSON.stringify(e);return t.test(r)}catch{return false}}function Ji(o,e){if(!o)return true;try{let t=new RegExp(o),r=JSON.stringify(e);return t.test(r)}catch{return false}}function Xi(o,e){if(o.pathSizeMin===void 0&&o.pathSizeMax===void 0)return true;let t=e,r=t?.path??t?.file_path??t?.filePath??t?.filename;if(typeof r!="string")return false;if(o.pathSizeMin!==void 0)if(Vn(o.pathSizeMin)){let n=Jn(r);if(n===null||n<zn(o.pathSizeMin))return false}else {let n=Kn(r);if(n===null||n<o.pathSizeMin)return false}if(o.pathSizeMax!==void 0)if(Vn(o.pathSizeMax)){let n=Jn(r);if(n===null||n>zn(o.pathSizeMax))return false}else {let n=Kn(r);if(n===null||n>o.pathSizeMax)return false}return true}function Qi(o){let e=[],t=[];for(let r=0;r<o.length;r++){let n=o[r];if(!n||typeof n!="object"){t.push(`Hook at index ${r}: not an object, skipping`);continue}let s=n;if(typeof s.name!="string"||!s.name){t.push(`Hook at index ${r}: missing or invalid "name", skipping`);continue}let i=s.guide&&typeof s.guide=="object",a=s.deny&&typeof s.deny=="object",d=typeof s.plugin=="string";if(!i&&!a&&!d){t.push(`Hook "${s.name}": missing guide/deny/plugin, skipping`);continue}if(i&&typeof s.guide.say!="string"){t.push(`Hook "${s.name}": guide.say is required and must be string, skipping`);continue}if(a&&typeof s.deny.reason!="string"){t.push(`Hook "${s.name}": deny.reason is required and must be string, skipping`);continue}e.push(s);}return {valid:e,warnings:t}}var $r=class extends Lt{name="@crewx/yaml-hook-plugin";version="0.1.0";capabilities={required:["inject"]};hooks;agentMap;constructor(e){super(),this.hooks=e.hooks,this.agentMap=new Map((e.agents??[]).map(t=>[t.id,t]));}async run(e){let t=[],r=process.env.CREWX_TASK_LOG_PATH,n=process.env.CREWX_HOOK_LOG_VERBOSE==="1";for(let s of this.hooks)if(this.matchEntryLevel(s,e)&&s.guide){if(!this.matchRuleLevel(s.guide,e)){n&&r&&this.appendHookLog(r,{rule:s.name,action:"pass",once:s.guide.once??false,ctx:e,matched:false});continue}s.guide.once&&this.hasFired(e.sessionId,s.name)||(s.guide.once&&this.markFired(e.sessionId,s.name),t.push(s.guide.say),r&&this.appendHookLog(r,{rule:s.name,action:"inject",once:s.guide.once??false,ctx:e,matched:true,message:s.guide.say}));}return t.length?e.inject(t.join(`
83
70
 
84
- `)):e.pass()}appendHookLog(e,t){try{let n={rule:t.rule,action:t.action,once:t.once,sessionId:t.ctx.sessionId,provider:t.ctx.provider,agent:t.ctx.agent.id,toolName:t.ctx.tool.name,rawToolName:t.ctx.tool.rawName};t.message&&(n.chars=t.message.length,process.env.CREWX_HOOK_LOG_VERBOSE==="1"&&(n.message=yi(t.message).slice(0,500)));let o=`[${new Date().toISOString()}] HOOK: ${JSON.stringify(n)}
85
- `;appendFileSync(e,o,{encoding:"utf8",mode:384});}catch{}}matchEntryLevel(e,t){if(e.provider!==void 0){let n=t.provider.replace(/^cli\//,"");if(!kn(e.provider,n))return false}if(e.team!==void 0){let o=this.agentMap.get(t.agent.id)?.team??t.agent.team;if(!kn(e.team,o))return false}if(e.role!==void 0){let o=this.agentMap.get(t.agent.id)?.role??t.agent.role;if(!kn(e.role,o))return false}if(e.tag!==void 0){let o=this.agentMap.get(t.agent.id)?.tags??[];if(!Vp(e.tag,o))return false}return !(e.agents!==void 0&&!e.agents.includes(t.agent.id))}matchRuleLevel(e,t){return !(e.when!==void 0&&e.when.length>0&&!e.when.includes(t.tool.name)&&!e.when.includes(t.tool.rawName)||!Gp(e.pattern,t.tool.input)||!Xp(e.regex,t.tool.input)||!Kp(e.pathPattern,t.tool.input,t.cwd)||!Qp(e,t.tool.input)||!Yp(e.whenInputRegex,t.tool.input))}hasFired(e,t){try{let n=this.firedFilePath(e);if(!existsSync(n))return !1;let o=JSON.parse(readFileSync(n,"utf8"));return Array.isArray(o.fired)&&o.fired.includes(t)}catch{return false}}markFired(e,t){try{let n=this.firedFilePath(e);mkdirSync(dirname(n),{recursive:!0,mode:448});let o=existsSync(n)?JSON.parse(readFileSync(n,"utf8")):{fired:[]};Array.isArray(o.fired)||(o.fired=[]),o.fired.includes(t)||(o.fired.push(t),writeFileSync(n,JSON.stringify(o),{mode:384}));}catch(n){process.stderr.write(`[YamlHookPlugin] once state write failed: ${n}
86
- `);}}firedFilePath(e){let t=createHash("sha1").update(e).digest("hex");return join(homedir(),".crewx","sessions",t,"fired-rules.json")}};g();g();g();function eg(r){let e=r.messages.map(t=>({id:t.id,role:t.isAssistant?"assistant":"user",content:t.text,timestamp:new Date(t.timestamp).toISOString(),metadata:t.metadata??null}));return {getThreadMessages(t){return e}}}g();var Tn=class extends Error{code;kind;retryAfterMs;constructor(e,t,n){super(`AdapterError: ${e}`),this.name="AdapterError",this.code=e,this.kind=t,this.retryAfterMs=n;}};g();function tg(r){return r}function rg(r){return {name:r.name,async attach(e){let t=await r.configFactory(e),o=e.registerChannelAdapter,s=r.instanceId??r.name;o&&await o({adapter:r.adapter,instanceId:s,config:t}),r.onAttach&&await r.onAttach(e);},async detach(e){let n=e.unregisterChannelAdapter;n&&await n(r.instanceId??r.name),r.onDetach&&await r.onDetach(e);}}}Lt();export{Tn as AdapterError,Re as AgentNotFoundError,Mt as AgentRuntime,En as AgentSkillsSchema,ze as BUILTIN_ADAPTERS,_n as BrowserFsAdapter,he as ClientToolCallRequiredError,He as ConfigLoadError,yn as Crewx,ht as CrewxPlugin,Ue as DocumentLoader,se as LayoutLoadError,pt as LayoutLoader,mt as LayoutRenderer,At as McpHttpTransport,Vt as NodeFsAdapter,zt as ParallelRunner,gr as ParallelRunnerTimeoutError,It as PluginProviderRuntime,Te as PropsValidationError,gt as PropsValidator,X as ProviderError,ut as RateLimitError,Et as RemoteAgentManager,St as RemoteProviderRuntime,bn as SdkBoxService,ct as TemplateEngine,ft as TypedEventEmitter,Pt as VercelProviderRuntime,Cn as YamlHookPlugin,Pp as buildContext,Ft as claudeAdapter,Wt as codexAdapter,Bt as copilotAdapter,Dr as createAdapterContext,kp as createDelegateTool,Hr as createHandler,oi as createPluginProviderFactory,Ce as createProvider,ei as createRemoteProviderFactory,jr as createScopedAdapterStore,Or as defaultFsAdapter,tg as defineChannelAdapter,rg as defineChannelAdapterPlugin,Er as escapeHandlebarsHelper,Sr as formatFileSizeHelper,Mr as formatTimestamp,Ir as formatTimestampHelper,Ut as geminiAdapter,Aa as generateFingerprint,Be as generateId,Ia as getSyncWindowStore,Fr as hashWorkspaceId,Ar as lengthHelper,Nt as loadYamlFile,lt as materializeWindowsSpawnProgram,so as normalizeWorkspacePath,Jt as opencodeAdapter,Rr as parseStdoutEvent,ge as parseUsage,jt as parseYamlContent,Qs as registerApiProviders,tt as registerProviderFactory,$t as resolveAgent,xp as resolveAgentSkills,Rp as resolveCrewxCli,Cp as resolveCrewxWorkspace,yr as resolveDefaultAgentsYaml,Qe as resolveTemplatesPath,On as resolveWindowsExecutablePath,at as resolveWindowsSpawnProgram,Dp as runExecutesParallel,Oa as runInSyncWindow,Np as runQueriesParallel,fa as setAuditVerbose,eg as toTaskReader,$r as toTemplateMessages,Pr as truncateHelper,Zp as validateHooksSchema};
71
+ `)):e.pass()}appendHookLog(e,t){try{let r={rule:t.rule,action:t.action,once:t.once,sessionId:t.ctx.sessionId,provider:t.ctx.provider,agent:t.ctx.agent.id,toolName:t.ctx.tool.name,rawToolName:t.ctx.tool.rawName};t.message&&(r.chars=t.message.length,process.env.CREWX_HOOK_LOG_VERBOSE==="1"&&(r.message=Wn(t.message).slice(0,500)));let n=`[${new Date().toISOString()}] HOOK: ${JSON.stringify(r)}
72
+ `;appendFileSync(e,n,{encoding:"utf8",mode:384});}catch{}}matchEntryLevel(e,t){if(e.provider!==void 0){let r=t.provider.replace(/^cli\//,"");if(!Nr(e.provider,r))return false}if(e.team!==void 0){let n=this.agentMap.get(t.agent.id)?.team??t.agent.team;if(!Nr(e.team,n))return false}if(e.role!==void 0){let n=this.agentMap.get(t.agent.id)?.role??t.agent.role;if(!Nr(e.role,n))return false}if(e.tag!==void 0){let n=this.agentMap.get(t.agent.id)?.tags??[];if(!Bi(e.tag,n))return false}return !(e.agents!==void 0&&!e.agents.includes(t.agent.id))}matchRuleLevel(e,t){return !(e.when!==void 0&&e.when.length>0&&!e.when.includes(t.tool.name)&&!e.when.includes(t.tool.rawName)||!Vi(e.pattern,t.tool.input)||!Ki(e.regex,t.tool.input)||!zi(e.pathPattern,t.tool.input,t.cwd)||!Xi(e,t.tool.input)||!Ji(e.whenInputRegex,t.tool.input))}hasFired(e,t){try{let r=this.firedFilePath(e);if(!existsSync(r))return !1;let n=JSON.parse(readFileSync(r,"utf8"));return Array.isArray(n.fired)&&n.fired.includes(t)}catch{return false}}markFired(e,t){try{let r=this.firedFilePath(e);mkdirSync(dirname(r),{recursive:!0,mode:448});let n=existsSync(r)?JSON.parse(readFileSync(r,"utf8")):{fired:[]};Array.isArray(n.fired)||(n.fired=[]),n.fired.includes(t)||(n.fired.push(t),writeFileSync(r,JSON.stringify(n),{mode:384}));}catch(r){process.stderr.write(`[YamlHookPlugin] once state write failed: ${r}
73
+ `);}}firedFilePath(e){let t=createHash("sha1").update(e).digest("hex");return join(homedir(),".crewx","sessions",t,"fired-rules.json")}};l();l();l();function Gi(o){let e=o.messages.map(t=>({id:t.id,role:t.isAssistant?"assistant":"user",content:t.text,timestamp:new Date(t.timestamp).toISOString(),metadata:t.metadata??null}));return {getThreadMessages(t){return e}}}l();var Lr=class extends Error{code;kind;retryAfterMs;constructor(e,t,r){super(`AdapterError: ${e}`),this.name="AdapterError",this.code=e,this.kind=t,this.retryAfterMs=r;}};l();function Yi(o){return o}function Zi(o){return {name:o.name,async attach(e){let t=await o.configFactory(e),n=e.registerChannelAdapter,s=o.instanceId??o.name;n&&await n({adapter:o.adapter,instanceId:s,config:t}),o.onAttach&&await o.onAttach(e);},async detach(e){let r=e.unregisterChannelAdapter;r&&await r(o.instanceId??o.name),o.onDetach&&await o.onDetach(e);}}}ht();export{Dt as ACP_ADAPTERS,et as AcpConnection,fe as AcpProtocolError,tt as AcpProviderRuntime,Lr as AdapterError,le as AgentNotFoundError,dt as AgentRuntime,Hr as AgentSkillsSchema,ye as BUILTIN_ADAPTERS,Sr as BrowserFsAdapter,te as ClientToolCallRequiredError,Re as ConfigLoadError,Tr as Crewx,Ge as CrewxPlugin,Ce as DocumentLoader,z as LayoutLoadError,Ke as LayoutLoader,Xe as LayoutRenderer,rt as McpHttpTransport,Rt as NodeFsAdapter,at as ParallelRunner,$t as ParallelRunnerTimeoutError,st as PluginProviderRuntime,pe as PropsValidationError,Je as PropsValidator,b as ProviderError,We as RateLimitError,nt as RemoteAgentManager,ot as RemoteProviderRuntime,Or as SdkBoxService,Ve as TemplateEngine,Qe as TypedEventEmitter,Ze as VercelProviderRuntime,$r as YamlHookPlugin,Pi as buildContext,St as claudeAcpAdapter,wt as claudeAdapter,It as codexAcpAdapter,kt as codexAdapter,Mt as copilotAcpAdapter,vt as copilotAdapter,sr as createAdapterContext,vi as createDelegateTool,ar as createHandler,Sn as createPluginProviderFactory,ue as createProvider,Cn as createRemoteProviderFactory,nr as createScopedAdapterStore,gr as defaultExtractText,er as defaultFsAdapter,re as defaultParseEvent,Yi as defineChannelAdapter,Zi as defineChannelAdapterPlugin,Gt as escapeHandlebarsHelper,Yt as formatFileSizeHelper,rr as formatTimestamp,Zt as formatTimestampHelper,Ot as geminiAcpAdapter,xt as geminiAdapter,es as generateFingerprint,be as generateId,ns as getSyncWindowStore,cr as hashWorkspaceId,Qt as lengthHelper,pt as loadYamlFile,Fe as materializeWindowsSpawnProgram,yn as normalizeWorkspacePath,Nt as opencodeAcpAdapter,_t as opencodeAdapter,Kt as parseStdoutEvent,G as parseUsage,ut as parseYamlContent,Pn as registerAcpProviders,xn as registerApiProviders,ce as registerProviderFactory,mt as resolveAgent,xi as resolveAgentSkills,ki as resolveCrewxCli,_i as resolveCrewxWorkspace,Ut as resolveDefaultAgentsYaml,Me as resolveTemplatesPath,Fr as resolveWindowsExecutablePath,qe as resolveWindowsSpawnProgram,Ni as runExecutesParallel,os as runInSyncWindow,Mi as runQueriesParallel,qo as setAuditVerbose,Gi as toTaskReader,ir as toTemplateMessages,Xt as truncateHelper,Qi as validateHooksSchema};