@lssm/bundle.contractspec-workspace 0.0.0-canary-20251216062412 → 0.0.0-canary-20251217034842

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 (34) hide show
  1. package/dist/_virtual/rolldown_runtime.js +1 -1
  2. package/dist/adapters/ai.js +1 -1
  3. package/dist/ai/agents/claude-code-agent.js +1 -1
  4. package/dist/ai/agents/cursor-agent.js +4 -4
  5. package/dist/ai/agents/openai-codex-agent.js +1 -1
  6. package/dist/ai/providers.js +1 -1
  7. package/dist/index.js +1 -1
  8. package/dist/node_modules/@ai-sdk/anthropic/dist/index.js +1 -0
  9. package/dist/node_modules/@ai-sdk/openai/dist/index.js +11 -0
  10. package/dist/node_modules/@ai-sdk/provider/dist/index.js +3 -0
  11. package/dist/node_modules/@ai-sdk/provider-utils/dist/index.js +5 -0
  12. package/dist/node_modules/eventsource-parser/dist/index.js +5 -0
  13. package/dist/node_modules/eventsource-parser/dist/stream.js +1 -0
  14. package/dist/services/ci-check/ci-check-service.js +1 -1
  15. package/dist/services/ci-check/types.js +1 -1
  16. package/dist/services/implementation/discovery.js +2 -0
  17. package/dist/services/implementation/index.js +1 -0
  18. package/dist/services/implementation/resolver.js +1 -0
  19. package/dist/services/index.js +1 -1
  20. package/dist/services/openapi/import-service.js +1 -0
  21. package/dist/services/openapi/index.js +1 -0
  22. package/dist/services/openapi/sync-service.js +1 -0
  23. package/dist/services/openapi/validate-service.js +1 -0
  24. package/dist/services/verification-cache/adapters/filesystem.js +1 -0
  25. package/dist/services/verification-cache/adapters/in-memory.js +1 -0
  26. package/dist/services/verification-cache/adapters/index.js +1 -0
  27. package/dist/services/verification-cache/adapters/workspace-state.js +1 -0
  28. package/dist/services/verification-cache/cache-service.js +1 -0
  29. package/dist/services/verification-cache/index.js +1 -0
  30. package/dist/services/verification-cache/types.js +1 -0
  31. package/dist/services/verify/ai-verifier.js +50 -2
  32. package/dist/services/verify/index.js +1 -1
  33. package/package.json +3 -4
  34. /package/dist/services/{openapi.js → openapi/export-service.js} +0 -0
@@ -1 +1 @@
1
- var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n&&e(r,Symbol.toStringTag,{value:`Module`}),r};export{t as __export};
1
+ var e=Object.defineProperty,t=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n&&e(r,Symbol.toStringTag,{value:`Module`}),r},n=(e=>typeof require<`u`?require:typeof Proxy<`u`?new Proxy(e,{get:(e,t)=>(typeof require<`u`?require:e)[t]}):e)(function(e){if(typeof require<`u`)return require.apply(this,arguments);throw Error('Calling `require` for "'+e+"\" in an environment that doesn't expose the `require` function.")});export{t as __export,n as __require};
@@ -1 +1 @@
1
- import{anthropic as e}from"@ai-sdk/anthropic";import{openai as t}from"@ai-sdk/openai";import{ollama as n}from"ollama-ai-provider";import{generateObject as r,generateText as i,streamText as a}from"ai";function o(e){return{async validateProvider(e){try{let{aiProvider:t}=e;return t===`ollama`?{success:!0}:t===`claude`&&!process.env.ANTHROPIC_API_KEY?{success:!1,error:`ANTHROPIC_API_KEY environment variable not set`}:t===`openai`&&!process.env.OPENAI_API_KEY?{success:!1,error:`OPENAI_API_KEY environment variable not set`}:{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}},async generateText(t){return{text:(await i({model:s(e),prompt:t.prompt,system:t.systemPrompt})).text}},async generateStructured(t){return{object:(await r({model:s(e),schema:t.schema,prompt:t.prompt,system:t.systemPrompt})).object}},async streamText(t,n){let r=await a({model:s(e),prompt:t.prompt,system:t.systemPrompt}),i=``;for await(let e of r.textStream)i+=e,n(e);return i}}}function s(r){let{aiProvider:i,aiModel:a,customEndpoint:o}=r;switch(i){case`claude`:return e(a??`claude-3-5-sonnet-20241022`);case`openai`:return t(a??`gpt-4o`);case`ollama`:return n(a??`codellama`);case`custom`:if(!o)throw Error(`Custom endpoint required. Set customEndpoint in config or CONTRACTSPEC_LLM_ENDPOINT env var`);return t(a??`default`);default:throw Error(`Unknown AI provider: ${i}`)}}export{o as createNodeAiAdapter};
1
+ import{anthropic as e}from"../node_modules/@ai-sdk/anthropic/dist/index.js";import{openai as t}from"../node_modules/@ai-sdk/openai/dist/index.js";import{ollama as n}from"ollama-ai-provider";import{generateObject as r,generateText as i,streamText as a}from"ai";function o(e){return{async validateProvider(e){try{let{aiProvider:t}=e;return t===`ollama`?{success:!0}:t===`claude`&&!process.env.ANTHROPIC_API_KEY?{success:!1,error:`ANTHROPIC_API_KEY environment variable not set`}:t===`openai`&&!process.env.OPENAI_API_KEY?{success:!1,error:`OPENAI_API_KEY environment variable not set`}:{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}},async generateText(t){return{text:(await i({model:s(e),prompt:t.prompt,system:t.systemPrompt})).text}},async generateStructured(t){return{object:(await r({model:s(e),schema:t.schema,prompt:t.prompt,system:t.systemPrompt})).object}},async streamText(t,n){let r=await a({model:s(e),prompt:t.prompt,system:t.systemPrompt}),i=``;for await(let e of r.textStream)i+=e,n(e);return i}}}function s(r){let{aiProvider:i,aiModel:a,customEndpoint:o}=r;switch(i){case`claude`:return e(a??`claude-3-5-sonnet-20241022`);case`openai`:return t(a??`gpt-4o`);case`ollama`:return n(a??`codellama`);case`custom`:if(!o)throw Error(`Custom endpoint required. Set customEndpoint in config or CONTRACTSPEC_LLM_ENDPOINT env var`);return t(a??`default`);default:throw Error(`Unknown AI provider: ${i}`)}}export{o as createNodeAiAdapter};
@@ -1,4 +1,4 @@
1
- import{anthropic as e}from"@ai-sdk/anthropic";import{generateText as t}from"ai";var n=class{name=`claude-code`;apiKey;constructor(){this.apiKey=process.env.ANTHROPIC_API_KEY}canHandle(e){return!!this.apiKey}async generate(n){if(!this.apiKey)return{success:!1,errors:[`ANTHROPIC_API_KEY not set. Claude Code agent requires API access.`]};try{let r=e(`claude-3-7-sonnet-20250219`),i=this.buildSystemPrompt(n),a=await t({model:r,prompt:this.buildUserPrompt(n),system:i,temperature:.2});return{success:!0,code:this.extractCode(a.text),metadata:{model:`claude-3-7-sonnet`,agentMode:`claude-code`,usage:a.usage}}}catch(e){return{success:!1,errors:[e instanceof Error?e.message:String(e)]}}}async validate(n){if(!this.apiKey)return{success:!1,errors:[`ANTHROPIC_API_KEY not set`]};try{let r=await t({model:e(`claude-3-7-sonnet-20250219`),prompt:`
1
+ import{anthropic as e}from"../../node_modules/@ai-sdk/anthropic/dist/index.js";import{generateText as t}from"ai";var n=class{name=`claude-code`;apiKey;constructor(){this.apiKey=process.env.ANTHROPIC_API_KEY}canHandle(e){return!!this.apiKey}async generate(n){if(!this.apiKey)return{success:!1,errors:[`ANTHROPIC_API_KEY not set. Claude Code agent requires API access.`]};try{let r=e(`claude-3-7-sonnet-20250219`),i=this.buildSystemPrompt(n),a=await t({model:r,prompt:this.buildUserPrompt(n),system:i,temperature:.2});return{success:!0,code:this.extractCode(a.text),metadata:{model:`claude-3-7-sonnet`,agentMode:`claude-code`,usage:a.usage}}}catch(e){return{success:!1,errors:[e instanceof Error?e.message:String(e)]}}}async validate(n){if(!this.apiKey)return{success:!1,errors:[`ANTHROPIC_API_KEY not set`]};try{let r=await t({model:e(`claude-3-7-sonnet-20250219`),prompt:`
2
2
  You are an expert code reviewer. Carefully analyze this implementation against its specification.
3
3
 
4
4
  SPECIFICATION:
@@ -1,4 +1,4 @@
1
- import{exec as e,spawn as t}from"child_process";import{mkdir as n,readFile as r,rm as i,writeFile as a}from"fs/promises";import{join as o}from"path";import{homedir as s,tmpdir as c}from"os";import{existsSync as l}from"fs";import{promisify as u}from"util";u(e);var d=class{name=`cursor`;cursorPath=null;isWindsurf=!1;composerPort;constructor(){this.composerPort=process.env.CURSOR_COMPOSER_PORT||`3000`,this.detectEnvironment()}canHandle(e){return this.isCursorAvailable()}async generate(e){try{let t=o(c(),`cursor-agent-${Date.now()}`);await n(t,{recursive:!0});let r=await this.executeWithBestMethod(e,t);return await this.cleanupWorkDir(t),r}catch(e){return{success:!1,errors:[e instanceof Error?e.message:String(e)]}}}async validate(e){try{let t=o(c(),`cursor-validate-${Date.now()}`);await n(t,{recursive:!0}),await this.setupValidationWorkspace(e,t);let r=await this.executeWithBestMethod({...e,type:`validate`},t);return await this.cleanupWorkDir(t),r}catch(e){return{success:!1,errors:[e instanceof Error?e.message:String(e)]}}}detectEnvironment(){this.isWindsurf=!!(process.env.WINDSURF_SESSION||process.env.CURSOR_USER_DATA||process.env.VSCODE_CWD?.includes(`Cursor`)||process.env.VSCODE_CWD?.includes(`Windsurf`));let e=[`/usr/local/bin/cursor`,`/Applications/Cursor.app/Contents/MacOS/Cursor`,`/Applications/Windsurf.app/Contents/MacOS/Windsurf`,o(s(),`.cursor`,`cursor`),o(s(),`AppData`,`Local`,`Programs`,`cursor`,`Cursor.exe`),o(s(),`AppData`,`Local`,`Programs`,`windsurf`,`Windsurf.exe`),`cursor`,`windsurf`];for(let t of e)if(t.includes(`cursor`)||t.includes(`Cursor`)||t.includes(`windsurf`)||t.includes(`Windsurf`))try{if(l(t)){this.cursorPath=t;break}}catch{continue}}async executeWithBestMethod(e,t){let n=[{name:`cursor-cli`,fn:()=>this.useCursorCLI(e,t)},{name:`file-based`,fn:()=>this.useFileBasedApproach(e,t)}];for(let e of n)try{let t=await e.fn();if(t.success)return t}catch{continue}return{success:!1,warnings:[`Cursor agent could not connect to IDE.`,`Ensure Cursor/Windsurf is running with API enabled.`,`Falling back to simple agent mode is recommended.`],errors:[`All Cursor integration methods failed`],metadata:{agentMode:`cursor`,status:`unavailable`,suggestion:`Use --agent-mode claude-code or --agent-mode simple`}}}async useCursorCLI(e,n){if(!this.cursorPath)throw Error(`Cursor executable not found`);let i=o(n,`spec.ts`),s=o(n,`output.ts`),c=o(n,`INSTRUCTIONS.md`);return await a(i,e.specCode),await a(c,this.buildDetailedPrompt(e)),e.existingCode&&await a(o(n,`existing.ts`),e.existingCode),new Promise((e,i)=>{let a=[`--wait`,`--new-window`,n],o=t(this.cursorPath,a,{cwd:n,stdio:`pipe`,detached:!1}),c=``,u=``;o.stdout?.on(`data`,e=>{c+=e.toString()}),o.stderr?.on(`data`,e=>{u+=e.toString()}),o.on(`error`,e=>{i(e)}),o.on(`close`,async t=>{if(l(s))try{e({success:!0,code:await r(s,`utf-8`),metadata:{agentMode:`cursor`,method:`cli`,exitCode:t}})}catch{i(Error(`Failed to read generated output`))}else i(Error(`Cursor CLI exited with code ${t}. No output generated.`))}),setTimeout(()=>{o.kill(),i(Error(`Cursor CLI timeout`))},6e4)})}async useFileBasedApproach(e,t){let n=o(t,`SPECIFICATION.ts`),r=o(t,`INSTRUCTIONS.md`),i=o(t,`template.ts`);return await a(n,e.specCode),await a(r,this.buildDetailedPrompt(e)),await a(i,this.generateTemplate(e)),await a(o(t,`README.md`),`# Cursor Agent Workspace
1
+ import{join as e}from"path";import{existsSync as t}from"fs";import{exec as n,spawn as r}from"child_process";import{mkdir as i,readFile as a,rm as o,writeFile as s}from"fs/promises";import{homedir as c,tmpdir as l}from"os";import{promisify as u}from"util";u(n);var d=class{name=`cursor`;cursorPath=null;isWindsurf=!1;composerPort;constructor(){this.composerPort=process.env.CURSOR_COMPOSER_PORT||`3000`,this.detectEnvironment()}canHandle(e){return this.isCursorAvailable()}async generate(t){try{let n=e(l(),`cursor-agent-${Date.now()}`);await i(n,{recursive:!0});let r=await this.executeWithBestMethod(t,n);return await this.cleanupWorkDir(n),r}catch(e){return{success:!1,errors:[e instanceof Error?e.message:String(e)]}}}async validate(t){try{let n=e(l(),`cursor-validate-${Date.now()}`);await i(n,{recursive:!0}),await this.setupValidationWorkspace(t,n);let r=await this.executeWithBestMethod({...t,type:`validate`},n);return await this.cleanupWorkDir(n),r}catch(e){return{success:!1,errors:[e instanceof Error?e.message:String(e)]}}}detectEnvironment(){this.isWindsurf=!!(process.env.WINDSURF_SESSION||process.env.CURSOR_USER_DATA||process.env.VSCODE_CWD?.includes(`Cursor`)||process.env.VSCODE_CWD?.includes(`Windsurf`));let n=[`/usr/local/bin/cursor`,`/Applications/Cursor.app/Contents/MacOS/Cursor`,`/Applications/Windsurf.app/Contents/MacOS/Windsurf`,e(c(),`.cursor`,`cursor`),e(c(),`AppData`,`Local`,`Programs`,`cursor`,`Cursor.exe`),e(c(),`AppData`,`Local`,`Programs`,`windsurf`,`Windsurf.exe`),`cursor`,`windsurf`];for(let e of n)if(e.includes(`cursor`)||e.includes(`Cursor`)||e.includes(`windsurf`)||e.includes(`Windsurf`))try{if(t(e)){this.cursorPath=e;break}}catch{continue}}async executeWithBestMethod(e,t){let n=[{name:`cursor-cli`,fn:()=>this.useCursorCLI(e,t)},{name:`file-based`,fn:()=>this.useFileBasedApproach(e,t)}];for(let e of n)try{let t=await e.fn();if(t.success)return t}catch{continue}return{success:!1,warnings:[`Cursor agent could not connect to IDE.`,`Ensure Cursor/Windsurf is running with API enabled.`,`Falling back to simple agent mode is recommended.`],errors:[`All Cursor integration methods failed`],metadata:{agentMode:`cursor`,status:`unavailable`,suggestion:`Use --agent-mode claude-code or --agent-mode simple`}}}async useCursorCLI(n,i){if(!this.cursorPath)throw Error(`Cursor executable not found`);let o=e(i,`spec.ts`),c=e(i,`output.ts`),l=e(i,`INSTRUCTIONS.md`);return await s(o,n.specCode),await s(l,this.buildDetailedPrompt(n)),n.existingCode&&await s(e(i,`existing.ts`),n.existingCode),new Promise((e,n)=>{let o=[`--wait`,`--new-window`,i],s=r(this.cursorPath,o,{cwd:i,stdio:`pipe`,detached:!1}),l=``,u=``;s.stdout?.on(`data`,e=>{l+=e.toString()}),s.stderr?.on(`data`,e=>{u+=e.toString()}),s.on(`error`,e=>{n(e)}),s.on(`close`,async r=>{if(t(c))try{e({success:!0,code:await a(c,`utf-8`),metadata:{agentMode:`cursor`,method:`cli`,exitCode:r}})}catch{n(Error(`Failed to read generated output`))}else n(Error(`Cursor CLI exited with code ${r}. No output generated.`))}),setTimeout(()=>{s.kill(),n(Error(`Cursor CLI timeout`))},6e4)})}async useFileBasedApproach(t,n){let r=e(n,`SPECIFICATION.ts`),i=e(n,`INSTRUCTIONS.md`),a=e(n,`template.ts`);return await s(r,t.specCode),await s(i,this.buildDetailedPrompt(t)),await s(a,this.generateTemplate(t)),await s(e(n,`README.md`),`# Cursor Agent Workspace
2
2
 
3
3
  This workspace was prepared for Cursor AI code generation.
4
4
 
@@ -13,8 +13,8 @@ This workspace was prepared for Cursor AI code generation.
13
13
  3. Use Cursor AI to generate code based on the spec
14
14
  4. Save the result as output.ts
15
15
 
16
- Workspace path: ${t}
17
- `),{success:!1,warnings:[`Cursor agent created workspace but cannot auto-execute.`,`Workspace prepared at: ${t}`,`Open this folder in Cursor IDE to complete code generation.`],code:this.generateTemplate(e),metadata:{agentMode:`cursor`,method:`file-based`,workDir:t}}}async setupValidationWorkspace(e,t){await a(o(t,`specification.ts`),e.specCode),await a(o(t,`implementation.ts`),e.existingCode||`// No implementation`),await a(o(t,`VALIDATION_INSTRUCTIONS.md`),this.buildValidationPrompt(e))}async prepareFilesForAPI(e,t){let n=[{path:`spec.ts`,content:e.specCode}];return e.existingCode&&n.push({path:`existing.ts`,content:e.existingCode}),n}buildDetailedPrompt(e){let t=`# AI Code Generation Task - Cursor Agent\n\n**Task Type:** ${e.type}\n**Generated:** ${new Date().toISOString()}\n\n`,n=`## Specification\n\n\`\`\`typescript\n${e.specCode}\n\`\`\`\n\n`,r={generate:`## Task: Generate Implementation
16
+ Workspace path: ${n}
17
+ `),{success:!1,warnings:[`Cursor agent created workspace but cannot auto-execute.`,`Workspace prepared at: ${n}`,`Open this folder in Cursor IDE to complete code generation.`],code:this.generateTemplate(t),metadata:{agentMode:`cursor`,method:`file-based`,workDir:n}}}async setupValidationWorkspace(t,n){await s(e(n,`specification.ts`),t.specCode),await s(e(n,`implementation.ts`),t.existingCode||`// No implementation`),await s(e(n,`VALIDATION_INSTRUCTIONS.md`),this.buildValidationPrompt(t))}async prepareFilesForAPI(e,t){let n=[{path:`spec.ts`,content:e.specCode}];return e.existingCode&&n.push({path:`existing.ts`,content:e.existingCode}),n}buildDetailedPrompt(e){let t=`# AI Code Generation Task - Cursor Agent\n\n**Task Type:** ${e.type}\n**Generated:** ${new Date().toISOString()}\n\n`,n=`## Specification\n\n\`\`\`typescript\n${e.specCode}\n\`\`\`\n\n`,r={generate:`## Task: Generate Implementation
18
18
 
19
19
  ### Requirements:
20
20
  1. **Type Safety**: Use strict TypeScript with comprehensive types
@@ -165,4 +165,4 @@ export function implementation() {
165
165
  // Implementation goes here
166
166
  throw new Error('Not implemented');
167
167
  }
168
- `}async cleanupWorkDir(e){try{await i(e,{recursive:!0,force:!0})}catch{}}isCursorAvailable(){return this.isWindsurf||this.cursorPath!==null||this.hasComposerAPI()}hasComposerAPI(){return!!(process.env.CURSOR_COMPOSER_PORT||process.env.CURSOR_API_ENABLED||this.isWindsurf)}};export{d as CursorAgent};
168
+ `}async cleanupWorkDir(e){try{await o(e,{recursive:!0,force:!0})}catch{}}isCursorAvailable(){return this.isWindsurf||this.cursorPath!==null||this.hasComposerAPI()}hasComposerAPI(){return!!(process.env.CURSOR_COMPOSER_PORT||process.env.CURSOR_API_ENABLED||this.isWindsurf)}};export{d as CursorAgent};
@@ -1,4 +1,4 @@
1
- import{openai as e}from"@ai-sdk/openai";import{generateText as t}from"ai";var n=class{name=`openai-codex`;apiKey;constructor(){this.apiKey=process.env.OPENAI_API_KEY}canHandle(e){return!!this.apiKey}async generate(n){if(!this.apiKey)return{success:!1,errors:[`OPENAI_API_KEY not set. OpenAI Codex agent requires API access.`]};try{let r=this.isComplexTask(n)?`o1`:`gpt-4o`,i=e(r),a=this.buildSystemPrompt(n),o=await t({model:i,prompt:this.buildUserPrompt(n),system:a,temperature:.2});return{success:!0,code:this.extractCode(o.text),metadata:{model:r,agentMode:`openai-codex`,usage:o.usage}}}catch(e){return{success:!1,errors:[e instanceof Error?e.message:String(e)]}}}async validate(n){if(!this.apiKey)return{success:!1,errors:[`OPENAI_API_KEY not set`]};try{let r=await t({model:e(`gpt-4o`),prompt:`
1
+ import{openai as e}from"../../node_modules/@ai-sdk/openai/dist/index.js";import{generateText as t}from"ai";var n=class{name=`openai-codex`;apiKey;constructor(){this.apiKey=process.env.OPENAI_API_KEY}canHandle(e){return!!this.apiKey}async generate(n){if(!this.apiKey)return{success:!1,errors:[`OPENAI_API_KEY not set. OpenAI Codex agent requires API access.`]};try{let r=this.isComplexTask(n)?`o1`:`gpt-4o`,i=e(r),a=this.buildSystemPrompt(n),o=await t({model:i,prompt:this.buildUserPrompt(n),system:a,temperature:.2});return{success:!0,code:this.extractCode(o.text),metadata:{model:r,agentMode:`openai-codex`,usage:o.usage}}}catch(e){return{success:!1,errors:[e instanceof Error?e.message:String(e)]}}}async validate(n){if(!this.apiKey)return{success:!1,errors:[`OPENAI_API_KEY not set`]};try{let r=await t({model:e(`gpt-4o`),prompt:`
2
2
  Review this code implementation against its specification.
3
3
 
4
4
  SPECIFICATION:
@@ -1 +1 @@
1
- import{anthropic as e}from"@ai-sdk/anthropic";import{openai as t}from"@ai-sdk/openai";import{ollama as n}from"ollama-ai-provider";function r(r){let{aiProvider:i,aiModel:a,customEndpoint:o}=r;switch(i){case`claude`:return e(a||`claude-3-5-sonnet-20241022`);case`openai`:return t(a||`gpt-4o`);case`ollama`:return n(a||`codellama`);case`custom`:if(!o)throw Error(`Custom endpoint required. Set customEndpoint in .contractsrc.json or CONTRACTSPEC_LLM_ENDPOINT env var`);return t(a||`default`);default:throw Error(`Unknown AI provider: ${i}`)}}async function i(e){try{let{aiProvider:t}=e;return t===`ollama`?{success:!0}:t===`claude`&&!process.env.ANTHROPIC_API_KEY?{success:!1,error:`ANTHROPIC_API_KEY environment variable not set`}:t===`openai`&&!process.env.OPENAI_API_KEY?{success:!1,error:`OPENAI_API_KEY environment variable not set`}:{success:!0}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}function a(e){switch(e){case`claude`:return[`claude-3-5-sonnet-20241022`,`claude-3-opus-20240229`,`claude-3-sonnet-20240229`];case`openai`:return[`gpt-4o`,`gpt-4-turbo`,`gpt-3.5-turbo`];case`ollama`:return[`codellama`,`llama3.1`,`mistral`,`deepseek-coder`];case`custom`:return[];default:return[]}}export{r as getAIProvider,a as getRecommendedModels,i as validateProvider};
1
+ import{getAIProvider as e,getRecommendedModels as t,validateLegacyProvider as n}from"@lssm/lib.ai-providers";function r(t){return e({aiProvider:t.aiProvider,aiModel:t.aiModel||void 0,customEndpoint:t.customEndpoint||void 0})}async function i(e){return await n({aiProvider:e.aiProvider,aiModel:e.aiModel||void 0,customEndpoint:e.customEndpoint||void 0})}function a(e){return t(e)}export{r as getAIProvider,a as getRecommendedModels,i as validateProvider};
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{createNodeFsAdapter as e}from"./adapters/fs.js";import{createNodeGitAdapter as t}from"./adapters/git.js";import{createNodeWatcherAdapter as n}from"./adapters/watcher.js";import{createNodeAiAdapter as r}from"./adapters/ai.js";import{createConsoleLoggerAdapter as i,createNoopLoggerAdapter as a}from"./adapters/logger.js";import{createNodeAdapters as o}from"./adapters/factory.js";import{detectPackageManager as s,findPackageRoot as c,findWorkspaceRoot as l,getExecCommand as u,getInstallCommand as d,getPackageName as f,getRunCommand as p,getWorkspaceInfo as m,getWorkspacePackages as h,isMonorepo as g}from"./adapters/workspace.js";import"./adapters/index.js";import{validateSpec as _,validateSpecs as v}from"./services/validate.js";import{validateImplementationFiles as y}from"./services/validate-implementation.js";import{compareSpecs as b}from"./services/diff.js";import{analyzeDeps as x,exportGraphAsDot as S,getContractNode as C,getGraphStats as w}from"./services/deps.js";import{groupSpecsByType as T,listSpecs as E}from"./services/list.js";import{getApiKey as D,loadWorkspaceConfig as O,mergeWorkspaceConfig as k}from"./services/config.js";import{buildSpec as A}from"./services/build.js";import{exportOpenApi as j}from"./services/openapi.js";import{RegistryClient as M,addToRegistry as N,listFromRegistry as P,resolveRegistryUrl as F,searchRegistry as I}from"./services/registry.js";import{syncSpecs as L}from"./services/sync.js";import{watchSpecs as R}from"./services/watch.js";import{cleanArtifacts as z}from"./services/clean.js";import{runTests as B}from"./services/test.js";import{createRegeneratorService as V}from"./services/regenerator.js";import{findAllConfigFiles as H,formatWorkspaceInfo as U,getExtendedWorkspaceInfo as W,mergeMonorepoConfigs as G}from"./services/workspace-info.js";import{analyzeIntegrity as K,filterIssuesBySeverity as q,filterIssuesByType as J,getAllSpecs as Y}from"./services/integrity.js";import{generateMermaidDiagram as X}from"./services/integrity-diagram.js";import{ALL_SETUP_TARGETS as Z,SETUP_TARGET_LABELS as Q}from"./services/setup/types.js";import{generateAgentsMd as $,generateClaudeMcpConfig as ee,generateContractsrcConfig as te,generateCursorMcpConfig as ne,generateCursorRules as re,generateVscodeSettings as ie,getClaudeDesktopConfigPath as ae}from"./services/setup/config-generators.js";import{deepMergeOverwrite as oe,deepMergePreserve as se,formatJson as ce,safeParseJson as le}from"./services/setup/file-merger.js";import{runSetup as ue}from"./services/setup/setup-service.js";import{ALL_CHECK_CATEGORIES as de,CHECK_CATEGORY_LABELS as fe}from"./services/doctor/types.js";import{formatCheckResult as pe,formatDoctorSummary as me,runDoctor as he}from"./services/doctor/doctor-service.js";import{ALL_CI_CHECK_CATEGORIES as ge,CI_CHECK_CATEGORY_LABELS as _e}from"./services/ci-check/types.js";import{runCIChecks as ve}from"./services/ci-check/ci-check-service.js";import{ClaudeCodeAdapter as ye,claudeCodeAdapter as be}from"./services/agent-guide/adapters/claude-code.js";import{CursorCLIAdapter as xe,cursorCLIAdapter as Se}from"./services/agent-guide/adapters/cursor-cli.js";import{GenericMCPAdapter as Ce,genericMCPAdapter as we}from"./services/agent-guide/adapters/generic-mcp.js";import{agentAdapters as Te,getAgentAdapter as Ee,listAgentTypes as De}from"./services/agent-guide/adapters/index.js";import{AgentGuideService as Oe,agentGuideService as ke,createAgentGuideService as Ae}from"./services/agent-guide/agent-guide-service.js";import{verifyStructure as je}from"./services/verify/structure-verifier.js";import{verifyBehavior as Me}from"./services/verify/behavior-verifier.js";import{createQuickAIReview as Ne,verifyWithAI as Pe}from"./services/verify/ai-verifier.js";import{VerifyService as Fe,createVerifyService as Ie,verifyService as Le}from"./services/verify/verify-service.js";import"./services/index.js";import{formatters_exports as Re}from"./formatters/index.js";import{templates_exports as ze}from"./templates/index.js";import{ai_exports as Be}from"./ai/index.js";export*from"@lssm/module.contractspec-workspace";export{de as ALL_CHECK_CATEGORIES,ge as ALL_CI_CHECK_CATEGORIES,Z as ALL_SETUP_TARGETS,Oe as AgentGuideService,fe as CHECK_CATEGORY_LABELS,_e as CI_CHECK_CATEGORY_LABELS,ye as ClaudeCodeAdapter,xe as CursorCLIAdapter,Ce as GenericMCPAdapter,M as RegistryClient,Q as SETUP_TARGET_LABELS,Fe as VerifyService,N as addToRegistry,Te as agentAdapters,ke as agentGuideService,Be as ai,x as analyzeDeps,K as analyzeIntegrity,A as buildSpec,be as claudeCodeAdapter,z as cleanArtifacts,b as compareSpecs,Ae as createAgentGuideService,i as createConsoleLoggerAdapter,o as createNodeAdapters,r as createNodeAiAdapter,e as createNodeFsAdapter,t as createNodeGitAdapter,n as createNodeWatcherAdapter,a as createNoopLoggerAdapter,Ne as createQuickAIReview,V as createRegeneratorService,Ie as createVerifyService,Se as cursorCLIAdapter,oe as deepMergeOverwrite,se as deepMergePreserve,s as detectPackageManager,S as exportGraphAsDot,j as exportOpenApi,q as filterIssuesBySeverity,J as filterIssuesByType,H as findAllConfigFiles,c as findPackageRoot,l as findWorkspaceRoot,pe as formatCheckResult,me as formatDoctorSummary,ce as formatJson,U as formatWorkspaceInfo,Re as formatters,$ as generateAgentsMd,ee as generateClaudeMcpConfig,te as generateContractsrcConfig,ne as generateCursorMcpConfig,re as generateCursorRules,X as generateMermaidDiagram,ie as generateVscodeSettings,we as genericMCPAdapter,Ee as getAgentAdapter,Y as getAllSpecs,D as getApiKey,ae as getClaudeDesktopConfigPath,C as getContractNode,u as getExecCommand,W as getExtendedWorkspaceInfo,w as getGraphStats,d as getInstallCommand,f as getPackageName,p as getRunCommand,m as getWorkspaceInfo,h as getWorkspacePackages,T as groupSpecsByType,g as isMonorepo,De as listAgentTypes,P as listFromRegistry,E as listSpecs,O as loadWorkspaceConfig,G as mergeMonorepoConfigs,k as mergeWorkspaceConfig,F as resolveRegistryUrl,ve as runCIChecks,he as runDoctor,ue as runSetup,B as runTests,le as safeParseJson,I as searchRegistry,L as syncSpecs,ze as templates,y as validateImplementationFiles,_ as validateSpec,v as validateSpecs,Me as verifyBehavior,Le as verifyService,je as verifyStructure,Pe as verifyWithAI,R as watchSpecs};
1
+ import{createNodeFsAdapter as e}from"./adapters/fs.js";import{createNodeGitAdapter as t}from"./adapters/git.js";import{createNodeWatcherAdapter as n}from"./adapters/watcher.js";import{createNodeAiAdapter as r}from"./adapters/ai.js";import{createConsoleLoggerAdapter as i,createNoopLoggerAdapter as a}from"./adapters/logger.js";import{createNodeAdapters as o}from"./adapters/factory.js";import{detectPackageManager as s,findPackageRoot as c,findWorkspaceRoot as l,getExecCommand as u,getInstallCommand as d,getPackageName as f,getRunCommand as p,getWorkspaceInfo as m,getWorkspacePackages as h,isMonorepo as g}from"./adapters/workspace.js";import"./adapters/index.js";import{validateSpec as _,validateSpecs as v}from"./services/validate.js";import{validateImplementationFiles as y}from"./services/validate-implementation.js";import{compareSpecs as b}from"./services/diff.js";import{analyzeDeps as x,exportGraphAsDot as S,getContractNode as C,getGraphStats as w}from"./services/deps.js";import{groupSpecsByType as T,listSpecs as E}from"./services/list.js";import{getApiKey as D,loadWorkspaceConfig as O,mergeWorkspaceConfig as k}from"./services/config.js";import{buildSpec as A}from"./services/build.js";import{importFromOpenApiService as j}from"./services/openapi/import-service.js";import{syncWithOpenApiService as M}from"./services/openapi/sync-service.js";import{validateAgainstOpenApiService as N}from"./services/openapi/validate-service.js";import{exportOpenApi as P}from"./services/openapi/export-service.js";import{RegistryClient as F,addToRegistry as I,listFromRegistry as L,resolveRegistryUrl as R,searchRegistry as z}from"./services/registry.js";import{syncSpecs as B}from"./services/sync.js";import{watchSpecs as V}from"./services/watch.js";import{cleanArtifacts as H}from"./services/clean.js";import{runTests as U}from"./services/test.js";import{createRegeneratorService as W}from"./services/regenerator.js";import{findAllConfigFiles as G,formatWorkspaceInfo as K,getExtendedWorkspaceInfo as q,mergeMonorepoConfigs as J}from"./services/workspace-info.js";import{analyzeIntegrity as Y,filterIssuesBySeverity as X,filterIssuesByType as Z,getAllSpecs as Q}from"./services/integrity.js";import{generateMermaidDiagram as $}from"./services/integrity-diagram.js";import{ALL_SETUP_TARGETS as ee,SETUP_TARGET_LABELS as te}from"./services/setup/types.js";import{generateAgentsMd as ne,generateClaudeMcpConfig as re,generateContractsrcConfig as ie,generateCursorMcpConfig as ae,generateCursorRules as oe,generateVscodeSettings as se,getClaudeDesktopConfigPath as ce}from"./services/setup/config-generators.js";import{deepMergeOverwrite as le,deepMergePreserve as ue,formatJson as de,safeParseJson as fe}from"./services/setup/file-merger.js";import{runSetup as pe}from"./services/setup/setup-service.js";import{ALL_CHECK_CATEGORIES as me,CHECK_CATEGORY_LABELS as he}from"./services/doctor/types.js";import{formatCheckResult as ge,formatDoctorSummary as _e,runDoctor as ve}from"./services/doctor/doctor-service.js";import{ALL_CI_CHECK_CATEGORIES as ye,CI_CHECK_CATEGORY_LABELS as be}from"./services/ci-check/types.js";import{discoverAllImplementations as xe,discoverImplementationsForSpec as Se,extractSpecReferences as Ce,inferImplementationType as we}from"./services/implementation/discovery.js";import{getImplementationSummary as Te,resolveAllImplementations as Ee,resolveImplementations as De}from"./services/implementation/resolver.js";import{DEFAULT_CACHE_CONFIG as Oe}from"./services/verification-cache/types.js";import{VerificationCacheService as ke,cacheKeyToString as Ae,computeContentHash as je,createVerificationCacheService as Me,stringToCacheKey as Ne}from"./services/verification-cache/cache-service.js";import{InMemoryCacheStorage as Pe,createInMemoryCacheStorage as Fe}from"./services/verification-cache/adapters/in-memory.js";import{FileSystemCacheStorage as Ie,createFileSystemCacheStorage as Le}from"./services/verification-cache/adapters/filesystem.js";import{WorkspaceStateCacheStorage as Re,createWorkspaceStateCacheStorage as ze}from"./services/verification-cache/adapters/workspace-state.js";import{runCIChecks as Be}from"./services/ci-check/ci-check-service.js";import{ClaudeCodeAdapter as Ve,claudeCodeAdapter as He}from"./services/agent-guide/adapters/claude-code.js";import{CursorCLIAdapter as Ue,cursorCLIAdapter as We}from"./services/agent-guide/adapters/cursor-cli.js";import{GenericMCPAdapter as Ge,genericMCPAdapter as Ke}from"./services/agent-guide/adapters/generic-mcp.js";import{agentAdapters as qe,getAgentAdapter as Je,listAgentTypes as Ye}from"./services/agent-guide/adapters/index.js";import{AgentGuideService as Xe,agentGuideService as Ze,createAgentGuideService as Qe}from"./services/agent-guide/agent-guide-service.js";import{verifyStructure as $e}from"./services/verify/structure-verifier.js";import{verifyBehavior as et}from"./services/verify/behavior-verifier.js";import{createQuickAIReview as tt,verifySemanticFields as nt,verifyWithAI as rt,verifyWithAIEnhanced as it}from"./services/verify/ai-verifier.js";import{VerifyService as at,createVerifyService as ot,verifyService as st}from"./services/verify/verify-service.js";import"./services/index.js";import{formatters_exports as ct}from"./formatters/index.js";import{templates_exports as lt}from"./templates/index.js";import{ai_exports as ut}from"./ai/index.js";export*from"@lssm/module.contractspec-workspace";export{me as ALL_CHECK_CATEGORIES,ye as ALL_CI_CHECK_CATEGORIES,ee as ALL_SETUP_TARGETS,Xe as AgentGuideService,he as CHECK_CATEGORY_LABELS,be as CI_CHECK_CATEGORY_LABELS,Ve as ClaudeCodeAdapter,Ue as CursorCLIAdapter,Oe as DEFAULT_CACHE_CONFIG,Ie as FileSystemCacheStorage,Ge as GenericMCPAdapter,Pe as InMemoryCacheStorage,F as RegistryClient,te as SETUP_TARGET_LABELS,ke as VerificationCacheService,at as VerifyService,Re as WorkspaceStateCacheStorage,I as addToRegistry,qe as agentAdapters,Ze as agentGuideService,ut as ai,x as analyzeDeps,Y as analyzeIntegrity,A as buildSpec,Ae as cacheKeyToString,He as claudeCodeAdapter,H as cleanArtifacts,b as compareSpecs,je as computeContentHash,Qe as createAgentGuideService,i as createConsoleLoggerAdapter,Le as createFileSystemCacheStorage,Fe as createInMemoryCacheStorage,o as createNodeAdapters,r as createNodeAiAdapter,e as createNodeFsAdapter,t as createNodeGitAdapter,n as createNodeWatcherAdapter,a as createNoopLoggerAdapter,tt as createQuickAIReview,W as createRegeneratorService,Me as createVerificationCacheService,ot as createVerifyService,ze as createWorkspaceStateCacheStorage,We as cursorCLIAdapter,le as deepMergeOverwrite,ue as deepMergePreserve,s as detectPackageManager,xe as discoverAllImplementations,Se as discoverImplementationsForSpec,S as exportGraphAsDot,P as exportOpenApi,Ce as extractSpecReferences,X as filterIssuesBySeverity,Z as filterIssuesByType,G as findAllConfigFiles,c as findPackageRoot,l as findWorkspaceRoot,ge as formatCheckResult,_e as formatDoctorSummary,de as formatJson,K as formatWorkspaceInfo,ct as formatters,ne as generateAgentsMd,re as generateClaudeMcpConfig,ie as generateContractsrcConfig,ae as generateCursorMcpConfig,oe as generateCursorRules,$ as generateMermaidDiagram,se as generateVscodeSettings,Ke as genericMCPAdapter,Je as getAgentAdapter,Q as getAllSpecs,D as getApiKey,ce as getClaudeDesktopConfigPath,C as getContractNode,u as getExecCommand,q as getExtendedWorkspaceInfo,w as getGraphStats,Te as getImplementationSummary,d as getInstallCommand,f as getPackageName,p as getRunCommand,m as getWorkspaceInfo,h as getWorkspacePackages,T as groupSpecsByType,j as importFromOpenApiService,we as inferImplementationType,g as isMonorepo,Ye as listAgentTypes,L as listFromRegistry,E as listSpecs,O as loadWorkspaceConfig,J as mergeMonorepoConfigs,k as mergeWorkspaceConfig,Ee as resolveAllImplementations,De as resolveImplementations,R as resolveRegistryUrl,Be as runCIChecks,ve as runDoctor,pe as runSetup,U as runTests,fe as safeParseJson,z as searchRegistry,Ne as stringToCacheKey,B as syncSpecs,M as syncWithOpenApiService,lt as templates,N as validateAgainstOpenApiService,y as validateImplementationFiles,_ as validateSpec,v as validateSpecs,et as verifyBehavior,nt as verifySemanticFields,st as verifyService,$e as verifyStructure,rt as verifyWithAI,it as verifyWithAIEnhanced,V as watchSpecs};
@@ -0,0 +1 @@
1
+ import{APICallError as e,NoSuchModelError as t,UnsupportedFunctionalityError as n}from"../../provider/dist/index.js";import{combineHeaders as r,convertToBase64 as i,createEventSourceResponseHandler as a,createJsonErrorResponseHandler as o,createJsonResponseHandler as s,createProviderToolFactory as c,createProviderToolFactoryWithOutputSchema as l,createToolNameMapping as u,generateId as d,isNonNullable as f,lazySchema as p,loadApiKey as m,loadOptionalSetting as h,parseProviderOptions as g,postJsonToApi as _,resolve as v,validateTypes as y,withUserAgentSuffix as b,withoutTrailingSlash as x,zodSchema as S}from"../../provider-utils/dist/index.js";import{z as C}from"zod/v4";var w=`3.0.0-beta.89`,T=o({errorSchema:p(()=>S(C.object({type:C.literal(`error`),error:C.object({type:C.string(),message:C.string()})}))),errorToMessage:e=>e.error.message});function E(e){let t=e.input_tokens,n=e.output_tokens,r=e.cache_creation_input_tokens??0,i=e.cache_read_input_tokens??0;return{inputTokens:{total:t+r+i,noCache:t,cacheRead:i,cacheWrite:r},outputTokens:{total:n,text:void 0,reasoning:void 0},raw:e}}var D=p(()=>S(C.object({type:C.literal(`message`),id:C.string().nullish(),model:C.string().nullish(),content:C.array(C.discriminatedUnion(`type`,[C.object({type:C.literal(`text`),text:C.string(),citations:C.array(C.discriminatedUnion(`type`,[C.object({type:C.literal(`web_search_result_location`),cited_text:C.string(),url:C.string(),title:C.string(),encrypted_index:C.string()}),C.object({type:C.literal(`page_location`),cited_text:C.string(),document_index:C.number(),document_title:C.string().nullable(),start_page_number:C.number(),end_page_number:C.number()}),C.object({type:C.literal(`char_location`),cited_text:C.string(),document_index:C.number(),document_title:C.string().nullable(),start_char_index:C.number(),end_char_index:C.number()})])).optional()}),C.object({type:C.literal(`thinking`),thinking:C.string(),signature:C.string()}),C.object({type:C.literal(`redacted_thinking`),data:C.string()}),C.object({type:C.literal(`tool_use`),id:C.string(),name:C.string(),input:C.unknown()}),C.object({type:C.literal(`server_tool_use`),id:C.string(),name:C.string(),input:C.record(C.string(),C.unknown()).nullish()}),C.object({type:C.literal(`mcp_tool_use`),id:C.string(),name:C.string(),input:C.unknown(),server_name:C.string()}),C.object({type:C.literal(`mcp_tool_result`),tool_use_id:C.string(),is_error:C.boolean(),content:C.array(C.union([C.string(),C.object({type:C.literal(`text`),text:C.string()})]))}),C.object({type:C.literal(`web_fetch_tool_result`),tool_use_id:C.string(),content:C.union([C.object({type:C.literal(`web_fetch_result`),url:C.string(),retrieved_at:C.string(),content:C.object({type:C.literal(`document`),title:C.string().nullable(),citations:C.object({enabled:C.boolean()}).optional(),source:C.union([C.object({type:C.literal(`base64`),media_type:C.literal(`application/pdf`),data:C.string()}),C.object({type:C.literal(`text`),media_type:C.literal(`text/plain`),data:C.string()})])})}),C.object({type:C.literal(`web_fetch_tool_result_error`),error_code:C.string()})])}),C.object({type:C.literal(`web_search_tool_result`),tool_use_id:C.string(),content:C.union([C.array(C.object({type:C.literal(`web_search_result`),url:C.string(),title:C.string(),encrypted_content:C.string(),page_age:C.string().nullish()})),C.object({type:C.literal(`web_search_tool_result_error`),error_code:C.string()})])}),C.object({type:C.literal(`code_execution_tool_result`),tool_use_id:C.string(),content:C.union([C.object({type:C.literal(`code_execution_result`),stdout:C.string(),stderr:C.string(),return_code:C.number()}),C.object({type:C.literal(`code_execution_tool_result_error`),error_code:C.string()})])}),C.object({type:C.literal(`bash_code_execution_tool_result`),tool_use_id:C.string(),content:C.discriminatedUnion(`type`,[C.object({type:C.literal(`bash_code_execution_result`),content:C.array(C.object({type:C.literal(`bash_code_execution_output`),file_id:C.string()})),stdout:C.string(),stderr:C.string(),return_code:C.number()}),C.object({type:C.literal(`bash_code_execution_tool_result_error`),error_code:C.string()})])}),C.object({type:C.literal(`text_editor_code_execution_tool_result`),tool_use_id:C.string(),content:C.discriminatedUnion(`type`,[C.object({type:C.literal(`text_editor_code_execution_tool_result_error`),error_code:C.string()}),C.object({type:C.literal(`text_editor_code_execution_view_result`),content:C.string(),file_type:C.string(),num_lines:C.number().nullable(),start_line:C.number().nullable(),total_lines:C.number().nullable()}),C.object({type:C.literal(`text_editor_code_execution_create_result`),is_file_update:C.boolean()}),C.object({type:C.literal(`text_editor_code_execution_str_replace_result`),lines:C.array(C.string()).nullable(),new_lines:C.number().nullable(),new_start:C.number().nullable(),old_lines:C.number().nullable(),old_start:C.number().nullable()})])}),C.object({type:C.literal(`tool_search_tool_result`),tool_use_id:C.string(),content:C.union([C.object({type:C.literal(`tool_search_tool_search_result`),tool_references:C.array(C.object({type:C.literal(`tool_reference`),tool_name:C.string()}))}),C.object({type:C.literal(`tool_search_tool_result_error`),error_code:C.string()})])})])),stop_reason:C.string().nullish(),stop_sequence:C.string().nullish(),usage:C.looseObject({input_tokens:C.number(),output_tokens:C.number(),cache_creation_input_tokens:C.number().nullish(),cache_read_input_tokens:C.number().nullish()}),container:C.object({expires_at:C.string(),id:C.string(),skills:C.array(C.object({type:C.union([C.literal(`anthropic`),C.literal(`custom`)]),skill_id:C.string(),version:C.string()})).nullish()}).nullish(),context_management:C.object({applied_edits:C.array(C.union([C.object({type:C.literal(`clear_tool_uses_20250919`),cleared_tool_uses:C.number(),cleared_input_tokens:C.number()}),C.object({type:C.literal(`clear_thinking_20251015`),cleared_thinking_turns:C.number(),cleared_input_tokens:C.number()})]))}).nullish()}))),O=p(()=>S(C.discriminatedUnion(`type`,[C.object({type:C.literal(`message_start`),message:C.object({id:C.string().nullish(),model:C.string().nullish(),usage:C.looseObject({input_tokens:C.number(),cache_creation_input_tokens:C.number().nullish(),cache_read_input_tokens:C.number().nullish()})})}),C.object({type:C.literal(`content_block_start`),index:C.number(),content_block:C.discriminatedUnion(`type`,[C.object({type:C.literal(`text`),text:C.string()}),C.object({type:C.literal(`thinking`),thinking:C.string()}),C.object({type:C.literal(`tool_use`),id:C.string(),name:C.string()}),C.object({type:C.literal(`redacted_thinking`),data:C.string()}),C.object({type:C.literal(`server_tool_use`),id:C.string(),name:C.string(),input:C.record(C.string(),C.unknown()).nullish()}),C.object({type:C.literal(`mcp_tool_use`),id:C.string(),name:C.string(),input:C.unknown(),server_name:C.string()}),C.object({type:C.literal(`mcp_tool_result`),tool_use_id:C.string(),is_error:C.boolean(),content:C.array(C.union([C.string(),C.object({type:C.literal(`text`),text:C.string()})]))}),C.object({type:C.literal(`web_fetch_tool_result`),tool_use_id:C.string(),content:C.union([C.object({type:C.literal(`web_fetch_result`),url:C.string(),retrieved_at:C.string(),content:C.object({type:C.literal(`document`),title:C.string().nullable(),citations:C.object({enabled:C.boolean()}).optional(),source:C.union([C.object({type:C.literal(`base64`),media_type:C.literal(`application/pdf`),data:C.string()}),C.object({type:C.literal(`text`),media_type:C.literal(`text/plain`),data:C.string()})])})}),C.object({type:C.literal(`web_fetch_tool_result_error`),error_code:C.string()})])}),C.object({type:C.literal(`web_search_tool_result`),tool_use_id:C.string(),content:C.union([C.array(C.object({type:C.literal(`web_search_result`),url:C.string(),title:C.string(),encrypted_content:C.string(),page_age:C.string().nullish()})),C.object({type:C.literal(`web_search_tool_result_error`),error_code:C.string()})])}),C.object({type:C.literal(`code_execution_tool_result`),tool_use_id:C.string(),content:C.union([C.object({type:C.literal(`code_execution_result`),stdout:C.string(),stderr:C.string(),return_code:C.number()}),C.object({type:C.literal(`code_execution_tool_result_error`),error_code:C.string()})])}),C.object({type:C.literal(`bash_code_execution_tool_result`),tool_use_id:C.string(),content:C.discriminatedUnion(`type`,[C.object({type:C.literal(`bash_code_execution_result`),content:C.array(C.object({type:C.literal(`bash_code_execution_output`),file_id:C.string()})),stdout:C.string(),stderr:C.string(),return_code:C.number()}),C.object({type:C.literal(`bash_code_execution_tool_result_error`),error_code:C.string()})])}),C.object({type:C.literal(`text_editor_code_execution_tool_result`),tool_use_id:C.string(),content:C.discriminatedUnion(`type`,[C.object({type:C.literal(`text_editor_code_execution_tool_result_error`),error_code:C.string()}),C.object({type:C.literal(`text_editor_code_execution_view_result`),content:C.string(),file_type:C.string(),num_lines:C.number().nullable(),start_line:C.number().nullable(),total_lines:C.number().nullable()}),C.object({type:C.literal(`text_editor_code_execution_create_result`),is_file_update:C.boolean()}),C.object({type:C.literal(`text_editor_code_execution_str_replace_result`),lines:C.array(C.string()).nullable(),new_lines:C.number().nullable(),new_start:C.number().nullable(),old_lines:C.number().nullable(),old_start:C.number().nullable()})])}),C.object({type:C.literal(`tool_search_tool_result`),tool_use_id:C.string(),content:C.union([C.object({type:C.literal(`tool_search_tool_search_result`),tool_references:C.array(C.object({type:C.literal(`tool_reference`),tool_name:C.string()}))}),C.object({type:C.literal(`tool_search_tool_result_error`),error_code:C.string()})])})])}),C.object({type:C.literal(`content_block_delta`),index:C.number(),delta:C.discriminatedUnion(`type`,[C.object({type:C.literal(`input_json_delta`),partial_json:C.string()}),C.object({type:C.literal(`text_delta`),text:C.string()}),C.object({type:C.literal(`thinking_delta`),thinking:C.string()}),C.object({type:C.literal(`signature_delta`),signature:C.string()}),C.object({type:C.literal(`citations_delta`),citation:C.discriminatedUnion(`type`,[C.object({type:C.literal(`web_search_result_location`),cited_text:C.string(),url:C.string(),title:C.string(),encrypted_index:C.string()}),C.object({type:C.literal(`page_location`),cited_text:C.string(),document_index:C.number(),document_title:C.string().nullable(),start_page_number:C.number(),end_page_number:C.number()}),C.object({type:C.literal(`char_location`),cited_text:C.string(),document_index:C.number(),document_title:C.string().nullable(),start_char_index:C.number(),end_char_index:C.number()})])})])}),C.object({type:C.literal(`content_block_stop`),index:C.number()}),C.object({type:C.literal(`error`),error:C.object({type:C.string(),message:C.string()})}),C.object({type:C.literal(`message_delta`),delta:C.object({stop_reason:C.string().nullish(),stop_sequence:C.string().nullish(),container:C.object({expires_at:C.string(),id:C.string(),skills:C.array(C.object({type:C.union([C.literal(`anthropic`),C.literal(`custom`)]),skill_id:C.string(),version:C.string()})).nullish()}).nullish(),context_management:C.object({applied_edits:C.array(C.union([C.object({type:C.literal(`clear_tool_uses_20250919`),cleared_tool_uses:C.number(),cleared_input_tokens:C.number()}),C.object({type:C.literal(`clear_thinking_20251015`),cleared_thinking_turns:C.number(),cleared_input_tokens:C.number()})]))}).nullish()}),usage:C.looseObject({output_tokens:C.number(),cache_creation_input_tokens:C.number().nullish()})}),C.object({type:C.literal(`message_stop`)}),C.object({type:C.literal(`ping`)})]))),k=p(()=>S(C.object({signature:C.string().optional(),redactedData:C.string().optional()}))),A=C.object({citations:C.object({enabled:C.boolean()}).optional(),title:C.string().optional(),context:C.string().optional()}),j=C.object({sendReasoning:C.boolean().optional(),structuredOutputMode:C.enum([`outputFormat`,`jsonTool`,`auto`]).optional(),thinking:C.object({type:C.union([C.literal(`enabled`),C.literal(`disabled`)]),budgetTokens:C.number().optional()}).optional(),disableParallelToolUse:C.boolean().optional(),cacheControl:C.object({type:C.literal(`ephemeral`),ttl:C.union([C.literal(`5m`),C.literal(`1h`)]).optional()}).optional(),mcpServers:C.array(C.object({type:C.literal(`url`),name:C.string(),url:C.string(),authorizationToken:C.string().nullish(),toolConfiguration:C.object({enabled:C.boolean().nullish(),allowedTools:C.array(C.string()).nullish()}).nullish()})).optional(),container:C.object({id:C.string().optional(),skills:C.array(C.object({type:C.union([C.literal(`anthropic`),C.literal(`custom`)]),skillId:C.string(),version:C.string().optional()})).optional()}).optional(),toolStreaming:C.boolean().optional(),effort:C.enum([`low`,`medium`,`high`]).optional(),contextManagement:C.object({edits:C.array(C.discriminatedUnion(`type`,[C.object({type:C.literal(`clear_tool_uses_20250919`),trigger:C.discriminatedUnion(`type`,[C.object({type:C.literal(`input_tokens`),value:C.number()}),C.object({type:C.literal(`tool_uses`),value:C.number()})]).optional(),keep:C.object({type:C.literal(`tool_uses`),value:C.number()}).optional(),clearAtLeast:C.object({type:C.literal(`input_tokens`),value:C.number()}).optional(),clearToolInputs:C.boolean().optional(),excludeTools:C.array(C.string()).optional()}),C.object({type:C.literal(`clear_thinking_20251015`),keep:C.union([C.literal(`all`),C.object({type:C.literal(`thinking_turns`),value:C.number()})]).optional()})]))}).optional()}),M=4;function N(e){let t=e?.anthropic;return t?.cacheControl??t?.cache_control}var P=class{constructor(){this.breakpointCount=0,this.warnings=[]}getCacheControl(e,t){let n=N(e);if(n){if(!t.canCache){this.warnings.push({type:`unsupported`,feature:`cache_control on non-cacheable context`,details:`cache_control cannot be set on ${t.type}. It will be ignored.`});return}if(this.breakpointCount++,this.breakpointCount>M){this.warnings.push({type:`unsupported`,feature:`cacheControl breakpoint limit`,details:`Maximum ${M} cache breakpoints exceeded (found ${this.breakpointCount}). This breakpoint will be ignored.`});return}return n}}getWarnings(){return this.warnings}},F=p(()=>S(C.object({maxCharacters:C.number().optional()}))),I=c({id:`anthropic.text_editor_20250728`,inputSchema:p(()=>S(C.object({command:C.enum([`view`,`create`,`str_replace`,`insert`]),path:C.string(),file_text:C.string().optional(),insert_line:C.number().int().optional(),new_str:C.string().optional(),old_str:C.string().optional(),view_range:C.array(C.number().int()).optional()})))}),L=(e={})=>I(e),R=p(()=>S(C.object({maxUses:C.number().optional(),allowedDomains:C.array(C.string()).optional(),blockedDomains:C.array(C.string()).optional(),userLocation:C.object({type:C.literal(`approximate`),city:C.string().optional(),region:C.string().optional(),country:C.string().optional(),timezone:C.string().optional()}).optional()}))),z=p(()=>S(C.array(C.object({url:C.string(),title:C.string().nullable(),pageAge:C.string().nullable(),encryptedContent:C.string(),type:C.literal(`web_search_result`)})))),B=l({id:`anthropic.web_search_20250305`,inputSchema:p(()=>S(C.object({query:C.string()}))),outputSchema:z}),V=(e={})=>B(e),ee=p(()=>S(C.object({maxUses:C.number().optional(),allowedDomains:C.array(C.string()).optional(),blockedDomains:C.array(C.string()).optional(),citations:C.object({enabled:C.boolean()}).optional(),maxContentTokens:C.number().optional()}))),H=p(()=>S(C.object({type:C.literal(`web_fetch_result`),url:C.string(),content:C.object({type:C.literal(`document`),title:C.string().nullable(),citations:C.object({enabled:C.boolean()}).optional(),source:C.union([C.object({type:C.literal(`base64`),mediaType:C.literal(`application/pdf`),data:C.string()}),C.object({type:C.literal(`text`),mediaType:C.literal(`text/plain`),data:C.string()})])}),retrievedAt:C.string().nullable()}))),U=l({id:`anthropic.web_fetch_20250910`,inputSchema:p(()=>S(C.object({url:C.string()}))),outputSchema:H}),W=(e={})=>U(e);async function te({tools:e,toolChoice:t,disableParallelToolUse:r,cacheControlValidator:i,supportsStructuredOutput:a}){e=e?.length?e:void 0;let o=[],s=new Set,c=i||new P;if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:o,betas:s};let l=[];for(let t of e)switch(t.type){case`function`:{let e=c.getCacheControl(t.providerOptions,{type:`tool definition`,canCache:!0}),n=t.providerOptions?.anthropic?.deferLoading;l.push({name:t.name,description:t.description,input_schema:t.inputSchema,cache_control:e,...a===!0&&t.strict!=null?{strict:t.strict}:{},...n==null?{}:{defer_loading:n},...t.inputExamples==null?{}:{input_examples:t.inputExamples.map(e=>e.input)}}),a===!0&&s.add(`structured-outputs-2025-11-13`),t.inputExamples!=null&&s.add(`advanced-tool-use-2025-11-20`);break}case`provider`:switch(t.id){case`anthropic.code_execution_20250522`:s.add(`code-execution-2025-05-22`),l.push({type:`code_execution_20250522`,name:`code_execution`,cache_control:void 0});break;case`anthropic.code_execution_20250825`:s.add(`code-execution-2025-08-25`),l.push({type:`code_execution_20250825`,name:`code_execution`});break;case`anthropic.computer_20250124`:s.add(`computer-use-2025-01-24`),l.push({name:`computer`,type:`computer_20250124`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber,cache_control:void 0});break;case`anthropic.computer_20241022`:s.add(`computer-use-2024-10-22`),l.push({name:`computer`,type:`computer_20241022`,display_width_px:t.args.displayWidthPx,display_height_px:t.args.displayHeightPx,display_number:t.args.displayNumber,cache_control:void 0});break;case`anthropic.text_editor_20250124`:s.add(`computer-use-2025-01-24`),l.push({name:`str_replace_editor`,type:`text_editor_20250124`,cache_control:void 0});break;case`anthropic.text_editor_20241022`:s.add(`computer-use-2024-10-22`),l.push({name:`str_replace_editor`,type:`text_editor_20241022`,cache_control:void 0});break;case`anthropic.text_editor_20250429`:s.add(`computer-use-2025-01-24`),l.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250429`,cache_control:void 0});break;case`anthropic.text_editor_20250728`:{let e=await y({value:t.args,schema:F});l.push({name:`str_replace_based_edit_tool`,type:`text_editor_20250728`,max_characters:e.maxCharacters,cache_control:void 0});break}case`anthropic.bash_20250124`:s.add(`computer-use-2025-01-24`),l.push({name:`bash`,type:`bash_20250124`,cache_control:void 0});break;case`anthropic.bash_20241022`:s.add(`computer-use-2024-10-22`),l.push({name:`bash`,type:`bash_20241022`,cache_control:void 0});break;case`anthropic.memory_20250818`:s.add(`context-management-2025-06-27`),l.push({name:`memory`,type:`memory_20250818`});break;case`anthropic.web_fetch_20250910`:{s.add(`web-fetch-2025-09-10`);let e=await y({value:t.args,schema:ee});l.push({type:`web_fetch_20250910`,name:`web_fetch`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,citations:e.citations,max_content_tokens:e.maxContentTokens,cache_control:void 0});break}case`anthropic.web_search_20250305`:{let e=await y({value:t.args,schema:R});l.push({type:`web_search_20250305`,name:`web_search`,max_uses:e.maxUses,allowed_domains:e.allowedDomains,blocked_domains:e.blockedDomains,user_location:e.userLocation,cache_control:void 0});break}case`anthropic.tool_search_regex_20251119`:s.add(`advanced-tool-use-2025-11-20`),l.push({type:`tool_search_tool_regex_20251119`,name:`tool_search_tool_regex`});break;case`anthropic.tool_search_bm25_20251119`:s.add(`advanced-tool-use-2025-11-20`),l.push({type:`tool_search_tool_bm25_20251119`,name:`tool_search_tool_bm25`});break;default:o.push({type:`unsupported`,feature:`provider-defined tool ${t.id}`});break}break;default:o.push({type:`unsupported`,feature:`tool ${t}`});break}if(t==null)return{tools:l,toolChoice:r?{type:`auto`,disable_parallel_tool_use:r}:void 0,toolWarnings:o,betas:s};let u=t.type;switch(u){case`auto`:return{tools:l,toolChoice:{type:`auto`,disable_parallel_tool_use:r},toolWarnings:o,betas:s};case`required`:return{tools:l,toolChoice:{type:`any`,disable_parallel_tool_use:r},toolWarnings:o,betas:s};case`none`:return{tools:void 0,toolChoice:void 0,toolWarnings:o,betas:s};case`tool`:return{tools:l,toolChoice:{type:`tool`,name:t.toolName,disable_parallel_tool_use:r},toolWarnings:o,betas:s};default:throw new n({functionality:`tool choice type: ${u}`})}}var G=p(()=>S(C.object({type:C.literal(`code_execution_result`),stdout:C.string(),stderr:C.string(),return_code:C.number()}))),ne=l({id:`anthropic.code_execution_20250522`,inputSchema:p(()=>S(C.object({code:C.string()}))),outputSchema:G}),re=(e={})=>ne(e),K=p(()=>S(C.discriminatedUnion(`type`,[C.object({type:C.literal(`bash_code_execution_result`),content:C.array(C.object({type:C.literal(`bash_code_execution_output`),file_id:C.string()})),stdout:C.string(),stderr:C.string(),return_code:C.number()}),C.object({type:C.literal(`bash_code_execution_tool_result_error`),error_code:C.string()}),C.object({type:C.literal(`text_editor_code_execution_tool_result_error`),error_code:C.string()}),C.object({type:C.literal(`text_editor_code_execution_view_result`),content:C.string(),file_type:C.string(),num_lines:C.number().nullable(),start_line:C.number().nullable(),total_lines:C.number().nullable()}),C.object({type:C.literal(`text_editor_code_execution_create_result`),is_file_update:C.boolean()}),C.object({type:C.literal(`text_editor_code_execution_str_replace_result`),lines:C.array(C.string()).nullable(),new_lines:C.number().nullable(),new_start:C.number().nullable(),old_lines:C.number().nullable(),old_start:C.number().nullable()})]))),q=l({id:`anthropic.code_execution_20250825`,inputSchema:p(()=>S(C.discriminatedUnion(`type`,[C.object({type:C.literal(`bash_code_execution`),command:C.string()}),C.discriminatedUnion(`command`,[C.object({type:C.literal(`text_editor_code_execution`),command:C.literal(`view`),path:C.string()}),C.object({type:C.literal(`text_editor_code_execution`),command:C.literal(`create`),path:C.string(),file_text:C.string().nullish()}),C.object({type:C.literal(`text_editor_code_execution`),command:C.literal(`str_replace`),path:C.string(),old_str:C.string(),new_str:C.string()})])]))),outputSchema:K}),J=(e={})=>q(e),Y=p(()=>S(C.array(C.object({type:C.literal(`tool_reference`),toolName:C.string()})))),ie=l({id:`anthropic.tool_search_regex_20251119`,inputSchema:p(()=>S(C.object({pattern:C.string(),limit:C.number().optional()}))),outputSchema:Y}),ae=(e={})=>ie(e);function oe(e){if(typeof e==`string`)return Buffer.from(e,`base64`).toString(`utf-8`);if(e instanceof Uint8Array)return new TextDecoder().decode(e);throw e instanceof URL?new n({functionality:`URL-based text documents are not supported for citations`}):new n({functionality:`unsupported data type for text documents: ${typeof e}`})}async function se({prompt:e,sendReasoning:t,warnings:r,cacheControlValidator:a,toolNameMapping:o}){let s=new Set,c=ce(e),l=a||new P,u,d=[];async function p(e){return(await g({provider:`anthropic`,providerOptions:e,schema:A}))?.citations?.enabled??!1}async function m(e){let t=await g({provider:`anthropic`,providerOptions:e,schema:A});return{title:t?.title,context:t?.context}}for(let e=0;e<c.length;e++){let a=c[e],h=e===c.length-1,_=a.type;switch(_){case`system`:if(u!=null)throw new n({functionality:`Multiple system messages that are separated by user/assistant messages`});u=a.messages.map(({content:e,providerOptions:t})=>({type:`text`,text:e,cache_control:l.getCacheControl(t,{type:`system message`,canCache:!0})}));break;case`user`:{let e=[];for(let t of a.messages){let{role:a,content:o}=t;switch(a){case`user`:for(let r=0;r<o.length;r++){let a=o[r],c=r===o.length-1,u=l.getCacheControl(a.providerOptions,{type:`user message part`,canCache:!0})??(c?l.getCacheControl(t.providerOptions,{type:`user message`,canCache:!0}):void 0);switch(a.type){case`text`:e.push({type:`text`,text:a.text,cache_control:u});break;case`file`:if(a.mediaType.startsWith(`image/`))e.push({type:`image`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:a.mediaType===`image/*`?`image/jpeg`:a.mediaType,data:i(a.data)},cache_control:u});else if(a.mediaType===`application/pdf`){s.add(`pdfs-2024-09-25`);let t=await p(a.providerOptions),n=await m(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`base64`,media_type:`application/pdf`,data:i(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:u})}else if(a.mediaType===`text/plain`){let t=await p(a.providerOptions),n=await m(a.providerOptions);e.push({type:`document`,source:a.data instanceof URL?{type:`url`,url:a.data.toString()}:{type:`text`,media_type:`text/plain`,data:oe(a.data)},title:n.title??a.filename,...n.context&&{context:n.context},...t&&{citations:{enabled:!0}},cache_control:u})}else throw new n({functionality:`media type: ${a.mediaType}`});break}}break;case`tool`:for(let n=0;n<o.length;n++){let i=o[n],a=n===o.length-1,c=l.getCacheControl(i.providerOptions,{type:`tool result part`,canCache:!0})??(a?l.getCacheControl(t.providerOptions,{type:`tool result message`,canCache:!0}):void 0),u=i.output,d;switch(u.type){case`content`:d=u.value.map(e=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`image-data`:return{type:`image`,source:{type:`base64`,media_type:e.mediaType,data:e.data}};case`image-url`:return{type:`image`,source:{type:`url`,url:e.url}};case`file-url`:return{type:`document`,source:{type:`url`,url:e.url}};case`file-data`:if(e.mediaType===`application/pdf`)return s.add(`pdfs-2024-09-25`),{type:`document`,source:{type:`base64`,media_type:e.mediaType,data:e.data}};r.push({type:`other`,message:`unsupported tool content part type: ${e.type} with media type: ${e.mediaType}`});return;default:r.push({type:`other`,message:`unsupported tool content part type: ${e.type}`});return}}).filter(f);break;case`text`:case`error-text`:d=u.value;break;case`execution-denied`:d=u.reason??`Tool execution denied.`;break;case`json`:case`error-json`:default:d=JSON.stringify(u.value);break}e.push({type:`tool_result`,tool_use_id:i.toolCallId,content:d,is_error:u.type===`error-text`||u.type===`error-json`?!0:void 0,cache_control:c})}break;default:{let e=a;throw Error(`Unsupported role: ${e}`)}}}d.push({role:`user`,content:e});break}case`assistant`:{let e=[],n=new Set;for(let i=0;i<a.messages.length;i++){let s=a.messages[i],c=i===a.messages.length-1,{content:u}=s;for(let i=0;i<u.length;i++){let a=u[i],d=i===u.length-1,f=l.getCacheControl(a.providerOptions,{type:`assistant message part`,canCache:!0})??(d?l.getCacheControl(s.providerOptions,{type:`assistant message`,canCache:!0}):void 0);switch(a.type){case`text`:e.push({type:`text`,text:h&&c&&d?a.text.trim():a.text,cache_control:f});break;case`reasoning`:if(t){let t=await g({provider:`anthropic`,providerOptions:a.providerOptions,schema:k});t==null?r.push({type:`other`,message:`unsupported reasoning metadata`}):t.signature==null?t.redactedData==null?r.push({type:`other`,message:`unsupported reasoning metadata`}):(l.getCacheControl(a.providerOptions,{type:`redacted thinking block`,canCache:!1}),e.push({type:`redacted_thinking`,data:t.redactedData})):(l.getCacheControl(a.providerOptions,{type:`thinking block`,canCache:!1}),e.push({type:`thinking`,thinking:a.text,signature:t.signature}))}else r.push({type:`other`,message:`sending reasoning content is disabled for this model`});break;case`tool-call`:if(a.providerExecuted){let t=o.toProviderToolName(a.toolName);if(a.providerOptions?.anthropic?.type===`mcp-tool-use`){n.add(a.toolCallId);let t=a.providerOptions?.anthropic?.serverName;if(t==null||typeof t!=`string`){r.push({type:`other`,message:`mcp tool use server name is required and must be a string`});break}e.push({type:`mcp_tool_use`,id:a.toolCallId,name:a.toolName,input:a.input,server_name:t,cache_control:f})}else t===`code_execution`&&a.input!=null&&typeof a.input==`object`&&`type`in a.input&&typeof a.input.type==`string`&&(a.input.type===`bash_code_execution`||a.input.type===`text_editor_code_execution`)?e.push({type:`server_tool_use`,id:a.toolCallId,name:a.input.type,input:a.input,cache_control:f}):t===`code_execution`||t===`web_fetch`||t===`web_search`||t===`tool_search_tool_regex`||t===`tool_search_tool_bm25`?e.push({type:`server_tool_use`,id:a.toolCallId,name:t,input:a.input,cache_control:f}):r.push({type:`other`,message:`provider executed tool call for tool ${a.toolName} is not supported`});break}e.push({type:`tool_use`,id:a.toolCallId,name:a.toolName,input:a.input,cache_control:f});break;case`tool-result`:{let t=o.toProviderToolName(a.toolName);if(n.has(a.toolCallId)){let t=a.output;if(t.type!==`json`&&t.type!==`error-json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${a.toolName} is not supported`});break}e.push({type:`mcp_tool_result`,tool_use_id:a.toolCallId,is_error:t.type===`error-json`,content:t.value,cache_control:f})}else if(t===`code_execution`){let t=a.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${a.toolName} is not supported`});break}if(t.value==null||typeof t.value!=`object`||!(`type`in t.value)||typeof t.value.type!=`string`){r.push({type:`other`,message:`provider executed tool result output value is not a valid code execution result for tool ${a.toolName}`});break}if(t.value.type===`code_execution_result`){let n=await y({value:t.value,schema:G});e.push({type:`code_execution_tool_result`,tool_use_id:a.toolCallId,content:{type:n.type,stdout:n.stdout,stderr:n.stderr,return_code:n.return_code},cache_control:f})}else{let n=await y({value:t.value,schema:K});e.push(n.type===`bash_code_execution_result`||n.type===`bash_code_execution_tool_result_error`?{type:`bash_code_execution_tool_result`,tool_use_id:a.toolCallId,cache_control:f,content:n}:{type:`text_editor_code_execution_tool_result`,tool_use_id:a.toolCallId,cache_control:f,content:n})}break}if(t===`web_fetch`){let t=a.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${a.toolName} is not supported`});break}let n=await y({value:t.value,schema:H});e.push({type:`web_fetch_tool_result`,tool_use_id:a.toolCallId,content:{type:`web_fetch_result`,url:n.url,retrieved_at:n.retrievedAt,content:{type:`document`,title:n.content.title,citations:n.content.citations,source:{type:n.content.source.type,media_type:n.content.source.mediaType,data:n.content.source.data}}},cache_control:f});break}if(t===`web_search`){let t=a.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${a.toolName} is not supported`});break}let n=await y({value:t.value,schema:z});e.push({type:`web_search_tool_result`,tool_use_id:a.toolCallId,content:n.map(e=>({url:e.url,title:e.title,page_age:e.pageAge,encrypted_content:e.encryptedContent,type:e.type})),cache_control:f});break}if(t===`tool_search_tool_regex`||t===`tool_search_tool_bm25`){let t=a.output;if(t.type!==`json`){r.push({type:`other`,message:`provider executed tool result output type ${t.type} for tool ${a.toolName} is not supported`});break}let n=(await y({value:t.value,schema:Y})).map(e=>({type:`tool_reference`,tool_name:e.toolName}));e.push({type:`tool_search_tool_result`,tool_use_id:a.toolCallId,content:{type:`tool_search_tool_search_result`,tool_references:n},cache_control:f});break}r.push({type:`other`,message:`provider executed tool result for tool ${a.toolName} is not supported`});break}}}}d.push({role:`assistant`,content:e});break}default:{let e=_;throw Error(`content type: ${e}`)}}}return{prompt:{system:u,messages:d},betas:s}}function ce(e){let t=[],n;for(let r of e){let{role:e}=r;switch(e){case`system`:n?.type!==`system`&&(n={type:`system`,messages:[]},t.push(n)),n.messages.push(r);break;case`assistant`:n?.type!==`assistant`&&(n={type:`assistant`,messages:[]},t.push(n)),n.messages.push(r);break;case`user`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;case`tool`:n?.type!==`user`&&(n={type:`user`,messages:[]},t.push(n)),n.messages.push(r);break;default:{let t=e;throw Error(`Unsupported role: ${t}`)}}}return t}function X({finishReason:e,isJsonResponseFromTool:t}){switch(e){case`pause_turn`:case`end_turn`:case`stop_sequence`:return`stop`;case`refusal`:return`content-filter`;case`tool_use`:return t?`stop`:`tool-calls`;case`max_tokens`:return`length`;case`model_context_window_exceeded`:return`length`;default:return`unknown`}}function Z(e,t,n){if(e.type!==`page_location`&&e.type!==`char_location`)return;let r=t[e.document_index];if(r)return{type:`source`,sourceType:`document`,id:n(),mediaType:r.mediaType,title:e.document_title??r.title,filename:r.filename,providerMetadata:{anthropic:e.type===`page_location`?{citedText:e.cited_text,startPageNumber:e.start_page_number,endPageNumber:e.end_page_number}:{citedText:e.cited_text,startCharIndex:e.start_char_index,endCharIndex:e.end_char_index}}}}var le=class{constructor(e,t){this.specificationVersion=`v3`,this.modelId=e,this.config=t,this.generateId=t.generateId??d}supportsUrl(e){return e.protocol===`https:`}get provider(){return this.config.provider}get supportedUrls(){var e;return(e=this.config).supportedUrls?.call(e)??{}}async getArgs({userSuppliedBetas:e,prompt:t,maxOutputTokens:n,temperature:r,topP:i,topK:a,frequencyPenalty:o,presencePenalty:s,stopSequences:c,responseFormat:l,seed:d,tools:f,toolChoice:p,providerOptions:m,stream:h}){let _=[];o!=null&&_.push({type:`unsupported`,feature:`frequencyPenalty`}),s!=null&&_.push({type:`unsupported`,feature:`presencePenalty`}),d!=null&&_.push({type:`unsupported`,feature:`seed`}),r!=null&&r>1?(_.push({type:`unsupported`,feature:`temperature`,details:`${r} exceeds anthropic maximum of 1.0. clamped to 1.0`}),r=1):r!=null&&r<0&&(_.push({type:`unsupported`,feature:`temperature`,details:`${r} is below anthropic minimum of 0. clamped to 0`}),r=0),l?.type===`json`&&(l.schema??_.push({type:`unsupported`,feature:`responseFormat`,details:`JSON response format requires a schema. The response format is ignored.`}));let v=await g({provider:`anthropic`,providerOptions:m,schema:j}),{maxOutputTokens:y,supportsStructuredOutput:b,isKnownModel:x}=ue(this.modelId),S=(this.config.supportsNativeStructuredOutput??!0)&&b,C=v?.structuredOutputMode??`auto`,w=C===`outputFormat`||C===`auto`&&S,T=l?.type===`json`&&l.schema!=null&&!w?{type:`function`,name:`json`,description:`Respond with a JSON object.`,inputSchema:l.schema}:void 0,E=v?.contextManagement,D=new P,O=u({tools:f,providerToolNames:{"anthropic.code_execution_20250522":`code_execution`,"anthropic.code_execution_20250825":`code_execution`,"anthropic.computer_20241022":`computer`,"anthropic.computer_20250124":`computer`,"anthropic.text_editor_20241022":`str_replace_editor`,"anthropic.text_editor_20250124":`str_replace_editor`,"anthropic.text_editor_20250429":`str_replace_based_edit_tool`,"anthropic.text_editor_20250728":`str_replace_based_edit_tool`,"anthropic.bash_20241022":`bash`,"anthropic.bash_20250124":`bash`,"anthropic.memory_20250818":`memory`,"anthropic.web_search_20250305":`web_search`,"anthropic.web_fetch_20250910":`web_fetch`,"anthropic.tool_search_regex_20251119":`tool_search_tool_regex`,"anthropic.tool_search_bm25_20251119":`tool_search_tool_bm25`}}),{prompt:k,betas:A}=await se({prompt:t,sendReasoning:v?.sendReasoning??!0,warnings:_,cacheControlValidator:D,toolNameMapping:O}),M=v?.thinking?.type===`enabled`,N=v?.thinking?.budgetTokens,F=n??y,I={model:this.modelId,max_tokens:F,temperature:r,top_k:a,top_p:i,stop_sequences:c,...M&&{thinking:{type:`enabled`,budget_tokens:N}},...v?.effort&&{output_config:{effort:v.effort}},...w&&l?.type===`json`&&l.schema!=null&&{output_format:{type:`json_schema`,schema:l.schema}},...v?.mcpServers&&v.mcpServers.length>0&&{mcp_servers:v.mcpServers.map(e=>({type:e.type,name:e.name,url:e.url,authorization_token:e.authorizationToken,tool_configuration:e.toolConfiguration?{allowed_tools:e.toolConfiguration.allowedTools,enabled:e.toolConfiguration.enabled}:void 0}))},...v?.container&&{container:{id:v.container.id,skills:v.container.skills?.map(e=>({type:e.type,skill_id:e.skillId,version:e.version}))}},system:k.system,messages:k.messages,...E&&{context_management:{edits:E.edits.map(e=>{let t=e.type;switch(t){case`clear_tool_uses_20250919`:return{type:e.type,...e.trigger!==void 0&&{trigger:e.trigger},...e.keep!==void 0&&{keep:e.keep},...e.clearAtLeast!==void 0&&{clear_at_least:e.clearAtLeast},...e.clearToolInputs!==void 0&&{clear_tool_inputs:e.clearToolInputs},...e.excludeTools!==void 0&&{exclude_tools:e.excludeTools}};case`clear_thinking_20251015`:return{type:e.type,...e.keep!==void 0&&{keep:e.keep}};default:_.push({type:`other`,message:`Unknown context management strategy: ${t}`});return}}).filter(e=>e!==void 0)}}};M&&(N??=(_.push({type:`compatibility`,feature:`extended thinking`,details:`thinking budget is required when thinking is enabled. using default budget of 1024 tokens.`}),I.thinking={type:`enabled`,budget_tokens:1024},1024),I.temperature!=null&&(I.temperature=void 0,_.push({type:`unsupported`,feature:`temperature`,details:`temperature is not supported when thinking is enabled`})),a!=null&&(I.top_k=void 0,_.push({type:`unsupported`,feature:`topK`,details:`topK is not supported when thinking is enabled`})),i!=null&&(I.top_p=void 0,_.push({type:`unsupported`,feature:`topP`,details:`topP is not supported when thinking is enabled`})),I.max_tokens=F+(N??0)),x&&I.max_tokens>y&&(n!=null&&_.push({type:`unsupported`,feature:`maxOutputTokens`,details:`${I.max_tokens} (maxOutputTokens + thinkingBudget) is greater than ${this.modelId} ${y} max output tokens. The max output tokens have been limited to ${y}.`}),I.max_tokens=y),v?.mcpServers&&v.mcpServers.length>0&&A.add(`mcp-client-2025-04-04`),E&&A.add(`context-management-2025-06-27`),v?.container&&v.container.skills&&v.container.skills.length>0&&(A.add(`code-execution-2025-08-25`),A.add(`skills-2025-10-02`),A.add(`files-api-2025-04-14`),f?.some(e=>e.type===`provider`&&e.id===`anthropic.code_execution_20250825`)||_.push({type:`other`,message:`code execution tool is required when using skills`})),v?.effort&&A.add(`effort-2025-11-24`),h&&(v?.toolStreaming??!0)&&A.add(`fine-grained-tool-streaming-2025-05-14`),w&&l?.type===`json`&&l.schema!=null&&A.add(`structured-outputs-2025-11-13`);let{tools:L,toolChoice:R,toolWarnings:z,betas:B}=await te(T==null?{tools:f??[],toolChoice:p,disableParallelToolUse:v?.disableParallelToolUse,cacheControlValidator:D,supportsStructuredOutput:S}:{tools:[...f??[],T],toolChoice:{type:`required`},disableParallelToolUse:!0,cacheControlValidator:D,supportsStructuredOutput:S}),V=D.getWarnings();return{args:{...I,tools:L,tool_choice:R,stream:h===!0?!0:void 0},warnings:[..._,...z,...V],betas:new Set([...A,...B,...e]),usesJsonResponseTool:T!=null,toolNameMapping:O}}async getHeaders({betas:e,headers:t}){return r(await v(this.config.headers),t,e.size>0?{"anthropic-beta":Array.from(e).join(`,`)}:{})}async getBetasFromHeaders(e){let t=(await v(this.config.headers))[`anthropic-beta`]??``,n=e?.[`anthropic-beta`]??``;return new Set([...t.toLowerCase().split(`,`),...n.toLowerCase().split(`,`)].map(e=>e.trim()).filter(e=>e!==``))}buildRequestUrl(e){var t;return(t=this.config).buildRequestUrl?.call(t,this.config.baseURL,e)??`${this.config.baseURL}/messages`}transformRequestBody(e){var t;return(t=this.config).transformRequestBody?.call(t,e)??e}extractCitationDocuments(e){return e.filter(e=>e.role===`user`).flatMap(e=>e.content).filter(e=>e.type!==`file`||e.mediaType!==`application/pdf`&&e.mediaType!==`text/plain`?!1:e.providerOptions?.anthropic?.citations?.enabled??!1).map(e=>{let t=e;return{title:t.filename??`Untitled Document`,filename:t.filename,mediaType:t.mediaType}})}async doGenerate(e){let{args:t,warnings:n,betas:r,usesJsonResponseTool:i,toolNameMapping:a}=await this.getArgs({...e,stream:!1,userSuppliedBetas:await this.getBetasFromHeaders(e.headers)}),o=this.extractCitationDocuments(e.prompt),{responseHeaders:c,value:l,rawValue:u}=await _({url:this.buildRequestUrl(!1),headers:await this.getHeaders({betas:r,headers:e.headers}),body:this.transformRequestBody(t),failedResponseHandler:T,successfulResponseHandler:s(D),abortSignal:e.abortSignal,fetch:this.config.fetch}),d=[],f={},p=!1;for(let e of l.content)switch(e.type){case`text`:if(!i&&(d.push({type:`text`,text:e.text}),e.citations))for(let t of e.citations){let e=Z(t,o,this.generateId);e&&d.push(e)}break;case`thinking`:d.push({type:`reasoning`,text:e.thinking,providerMetadata:{anthropic:{signature:e.signature}}});break;case`redacted_thinking`:d.push({type:`reasoning`,text:``,providerMetadata:{anthropic:{redactedData:e.data}}});break;case`tool_use`:i&&e.name===`json`?(p=!0,d.push({type:`text`,text:JSON.stringify(e.input)})):d.push({type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input)});break;case`server_tool_use`:e.name===`text_editor_code_execution`||e.name===`bash_code_execution`?d.push({type:`tool-call`,toolCallId:e.id,toolName:a.toCustomToolName(`code_execution`),input:JSON.stringify({type:e.name,...e.input}),providerExecuted:!0}):(e.name===`web_search`||e.name===`code_execution`||e.name===`web_fetch`||e.name===`tool_search_tool_regex`||e.name===`tool_search_tool_bm25`)&&d.push({type:`tool-call`,toolCallId:e.id,toolName:a.toCustomToolName(e.name),input:JSON.stringify(e.input),providerExecuted:!0});break;case`mcp_tool_use`:f[e.id]={type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:`mcp-tool-use`,serverName:e.server_name}}},d.push(f[e.id]);break;case`mcp_tool_result`:d.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:f[e.tool_use_id].toolName,isError:e.is_error,result:e.content,dynamic:!0,providerMetadata:f[e.tool_use_id].providerMetadata});break;case`web_fetch_tool_result`:e.content.type===`web_fetch_result`?d.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:a.toCustomToolName(`web_fetch`),result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}}}):e.content.type===`web_fetch_tool_result_error`&&d.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:a.toCustomToolName(`web_fetch`),isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code}});break;case`web_search_tool_result`:if(Array.isArray(e.content)){d.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:a.toCustomToolName(`web_search`),result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type}))});for(let t of e.content)d.push({type:`source`,sourceType:`url`,id:this.generateId(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else d.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:a.toCustomToolName(`web_search`),isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code}});break;case`code_execution_tool_result`:e.content.type===`code_execution_result`?d.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:a.toCustomToolName(`code_execution`),result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code}}):e.content.type===`code_execution_tool_result_error`&&d.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:a.toCustomToolName(`code_execution`),isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code}});break;case`bash_code_execution_tool_result`:case`text_editor_code_execution_tool_result`:d.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:a.toCustomToolName(`code_execution`),result:e.content});break;case`tool_search_tool_result`:e.content.type===`tool_search_tool_search_result`?d.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:a.toCustomToolName(`tool_search`),result:e.content.tool_references.map(e=>({type:e.type,toolName:e.tool_name}))}):d.push({type:`tool-result`,toolCallId:e.tool_use_id,toolName:a.toCustomToolName(`tool_search`),isError:!0,result:{type:`tool_search_tool_result_error`,errorCode:e.content.error_code}});break}return{content:d,finishReason:X({finishReason:l.stop_reason,isJsonResponseFromTool:p}),usage:E(l.usage),request:{body:t},response:{id:l.id??void 0,modelId:l.model??void 0,headers:c,body:u},warnings:n,providerMetadata:{anthropic:{usage:l.usage,cacheCreationInputTokens:l.usage.cache_creation_input_tokens??null,stopSequence:l.stop_sequence??null,container:l.container?{expiresAt:l.container.expires_at,id:l.container.id,skills:l.container.skills?.map(e=>({type:e.type,skillId:e.skill_id,version:e.version}))??null}:null,contextManagement:Q(l.context_management)??null}}}}async doStream(t){let{args:n,warnings:r,betas:i,usesJsonResponseTool:o,toolNameMapping:s}=await this.getArgs({...t,stream:!0,userSuppliedBetas:await this.getBetasFromHeaders(t.headers)}),c=this.extractCitationDocuments(t.prompt),l=this.buildRequestUrl(!0),{responseHeaders:u,value:d}=await _({url:l,headers:await this.getHeaders({betas:i,headers:t.headers}),body:this.transformRequestBody(n),failedResponseHandler:T,successfulResponseHandler:a(O),abortSignal:t.abortSignal,fetch:this.config.fetch}),f=`unknown`,p={input_tokens:0,output_tokens:0,cache_creation_input_tokens:0,cache_read_input_tokens:0},m={},h={},g=null,v,y=null,b=null,x=null,S=!1,C,w=this.generateId,[D,k]=d.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:r})},transform(e,n){if(t.includeRawChunks&&n.enqueue({type:`raw`,rawValue:e.rawValue}),!e.success){n.enqueue({type:`error`,error:e.error});return}let r=e.value;switch(r.type){case`ping`:return;case`content_block_start`:{let e=r.content_block,t=e.type;switch(C=t,t){case`text`:if(o)return;m[r.index]={type:`text`},n.enqueue({type:`text-start`,id:String(r.index)});return;case`thinking`:m[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index)});return;case`redacted_thinking`:m[r.index]={type:`reasoning`},n.enqueue({type:`reasoning-start`,id:String(r.index),providerMetadata:{anthropic:{redactedData:e.data}}});return;case`tool_use`:o&&e.name===`json`?(S=!0,m[r.index]={type:`text`},n.enqueue({type:`text-start`,id:String(r.index)})):(m[r.index]={type:`tool-call`,toolCallId:e.id,toolName:e.name,input:``,firstDelta:!0},n.enqueue({type:`tool-input-start`,id:e.id,toolName:e.name}));return;case`server_tool_use`:if([`web_fetch`,`web_search`,`code_execution`,`text_editor_code_execution`,`bash_code_execution`].includes(e.name)){let t=e.name===`text_editor_code_execution`||e.name===`bash_code_execution`?`code_execution`:e.name,i=s.toCustomToolName(t);m[r.index]={type:`tool-call`,toolCallId:e.id,toolName:i,input:``,providerExecuted:!0,firstDelta:!0,providerToolName:e.name},n.enqueue({type:`tool-input-start`,id:e.id,toolName:i,providerExecuted:!0})}else if(e.name===`tool_search_tool_regex`||e.name===`tool_search_tool_bm25`){let t=s.toCustomToolName(e.name);m[r.index]={type:`tool-call`,toolCallId:e.id,toolName:t,input:``,providerExecuted:!0,firstDelta:!0,providerToolName:e.name},n.enqueue({type:`tool-input-start`,id:e.id,toolName:t,providerExecuted:!0})}return;case`web_fetch_tool_result`:e.content.type===`web_fetch_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:s.toCustomToolName(`web_fetch`),result:{type:`web_fetch_result`,url:e.content.url,retrievedAt:e.content.retrieved_at,content:{type:e.content.content.type,title:e.content.content.title,citations:e.content.content.citations,source:{type:e.content.content.source.type,mediaType:e.content.content.source.media_type,data:e.content.content.source.data}}}}):e.content.type===`web_fetch_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:s.toCustomToolName(`web_fetch`),isError:!0,result:{type:`web_fetch_tool_result_error`,errorCode:e.content.error_code}});return;case`web_search_tool_result`:if(Array.isArray(e.content)){n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:s.toCustomToolName(`web_search`),result:e.content.map(e=>({url:e.url,title:e.title,pageAge:e.page_age??null,encryptedContent:e.encrypted_content,type:e.type}))});for(let t of e.content)n.enqueue({type:`source`,sourceType:`url`,id:w(),url:t.url,title:t.title,providerMetadata:{anthropic:{pageAge:t.page_age??null}}})}else n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:s.toCustomToolName(`web_search`),isError:!0,result:{type:`web_search_tool_result_error`,errorCode:e.content.error_code}});return;case`code_execution_tool_result`:e.content.type===`code_execution_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:s.toCustomToolName(`code_execution`),result:{type:e.content.type,stdout:e.content.stdout,stderr:e.content.stderr,return_code:e.content.return_code}}):e.content.type===`code_execution_tool_result_error`&&n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:s.toCustomToolName(`code_execution`),isError:!0,result:{type:`code_execution_tool_result_error`,errorCode:e.content.error_code}});return;case`bash_code_execution_tool_result`:case`text_editor_code_execution_tool_result`:n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:s.toCustomToolName(`code_execution`),result:e.content});return;case`tool_search_tool_result`:e.content.type===`tool_search_tool_search_result`?n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:s.toCustomToolName(`tool_search`),result:e.content.tool_references.map(e=>({type:e.type,toolName:e.tool_name}))}):n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:s.toCustomToolName(`tool_search`),isError:!0,result:{type:`tool_search_tool_result_error`,errorCode:e.content.error_code}});return;case`mcp_tool_use`:h[e.id]={type:`tool-call`,toolCallId:e.id,toolName:e.name,input:JSON.stringify(e.input),providerExecuted:!0,dynamic:!0,providerMetadata:{anthropic:{type:`mcp-tool-use`,serverName:e.server_name}}},n.enqueue(h[e.id]);return;case`mcp_tool_result`:n.enqueue({type:`tool-result`,toolCallId:e.tool_use_id,toolName:h[e.tool_use_id].toolName,isError:e.is_error,result:e.content,dynamic:!0,providerMetadata:h[e.tool_use_id].providerMetadata});return;default:{let e=t;throw Error(`Unsupported content block type: ${e}`)}}}case`content_block_stop`:if(m[r.index]!=null){let e=m[r.index];switch(e.type){case`text`:n.enqueue({type:`text-end`,id:String(r.index)});break;case`reasoning`:n.enqueue({type:`reasoning-end`,id:String(r.index)});break;case`tool-call`:o&&e.toolName===`json`||(n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.input===``?`{}`:e.input,providerExecuted:e.providerExecuted}));break}delete m[r.index]}C=void 0;return;case`content_block_delta`:{let e=r.delta.type;switch(e){case`text_delta`:if(o)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:r.delta.text});return;case`thinking_delta`:n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:r.delta.thinking});return;case`signature_delta`:C===`thinking`&&n.enqueue({type:`reasoning-delta`,id:String(r.index),delta:``,providerMetadata:{anthropic:{signature:r.delta.signature}}});return;case`input_json_delta`:{let e=m[r.index],t=r.delta.partial_json;if(t.length===0)return;if(S){if(e?.type!==`text`)return;n.enqueue({type:`text-delta`,id:String(r.index),delta:t})}else{if(e?.type!==`tool-call`)return;e.firstDelta&&(e.providerToolName===`bash_code_execution`||e.providerToolName===`text_editor_code_execution`)&&(t=`{"type": "${e.providerToolName}",${t.substring(1)}`),n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:t}),e.input+=t,e.firstDelta=!1}return}case`citations_delta`:{let e=r.delta.citation,t=Z(e,c,w);t&&n.enqueue(t);return}default:{let t=e;throw Error(`Unsupported delta type: ${t}`)}}}case`message_start`:p.input_tokens=r.message.usage.input_tokens,p.cache_read_input_tokens=r.message.usage.cache_read_input_tokens??0,p.cache_creation_input_tokens=r.message.usage.cache_creation_input_tokens??0,v={...r.message.usage},y=r.message.usage.cache_creation_input_tokens??null,n.enqueue({type:`response-metadata`,id:r.message.id??void 0,modelId:r.message.model??void 0});return;case`message_delta`:p.output_tokens=r.usage.output_tokens,f=X({finishReason:r.delta.stop_reason,isJsonResponseFromTool:S}),b=r.delta.stop_sequence??null,x=r.delta.container==null?null:{expiresAt:r.delta.container.expires_at,id:r.delta.container.id,skills:r.delta.container.skills?.map(e=>({type:e.type,skillId:e.skill_id,version:e.version}))??null},r.delta.context_management&&(g=Q(r.delta.context_management)),v={...v,...r.usage};return;case`message_stop`:n.enqueue({type:`finish`,finishReason:f,usage:E(p),providerMetadata:{anthropic:{usage:v??null,cacheCreationInputTokens:y,stopSequence:b,container:x,contextManagement:g}}});return;case`error`:n.enqueue({type:`error`,error:r.error});return;default:{let e=r;throw Error(`Unsupported chunk type: ${e}`)}}}})).tee(),A=D.getReader();try{await A.read();let t=await A.read();if(t.value?.type===`raw`&&(t=await A.read()),t.value?.type===`error`){let r=t.value.error;throw new e({message:r.message,url:l,requestBodyValues:n,statusCode:r.type===`overloaded_error`?529:500,responseHeaders:u,responseBody:JSON.stringify(r),isRetryable:r.type===`overloaded_error`})}}finally{A.cancel().catch(()=>{}),A.releaseLock()}return{stream:k,request:{body:n},response:{headers:u}}}};function ue(e){return e.includes(`claude-sonnet-4-5`)||e.includes(`claude-opus-4-5`)?{maxOutputTokens:64e3,supportsStructuredOutput:!0,isKnownModel:!0}:e.includes(`claude-opus-4-1`)?{maxOutputTokens:32e3,supportsStructuredOutput:!0,isKnownModel:!0}:e.includes(`claude-sonnet-4-`)||e.includes(`claude-3-7-sonnet`)||e.includes(`claude-haiku-4-5`)?{maxOutputTokens:64e3,supportsStructuredOutput:!1,isKnownModel:!0}:e.includes(`claude-opus-4-`)?{maxOutputTokens:32e3,supportsStructuredOutput:!1,isKnownModel:!0}:e.includes(`claude-3-5-haiku`)?{maxOutputTokens:8192,supportsStructuredOutput:!1,isKnownModel:!0}:e.includes(`claude-3-haiku`)?{maxOutputTokens:4096,supportsStructuredOutput:!1,isKnownModel:!0}:{maxOutputTokens:4096,supportsStructuredOutput:!1,isKnownModel:!1}}function Q(e){return e?{appliedEdits:e.applied_edits.map(e=>{switch(e.type){case`clear_tool_uses_20250919`:return{type:e.type,clearedToolUses:e.cleared_tool_uses,clearedInputTokens:e.cleared_input_tokens};case`clear_thinking_20251015`:return{type:e.type,clearedThinkingTurns:e.cleared_thinking_turns,clearedInputTokens:e.cleared_input_tokens}}}).filter(e=>e!==void 0)}:null}var de=c({id:`anthropic.bash_20241022`,inputSchema:p(()=>S(C.object({command:C.string(),restart:C.boolean().optional()})))}),fe=c({id:`anthropic.bash_20250124`,inputSchema:p(()=>S(C.object({command:C.string(),restart:C.boolean().optional()})))}),$=c({id:`anthropic.computer_20241022`,inputSchema:p(()=>S(C.object({action:C.enum([`key`,`type`,`mouse_move`,`left_click`,`left_click_drag`,`right_click`,`middle_click`,`double_click`,`screenshot`,`cursor_position`]),coordinate:C.array(C.number().int()).optional(),text:C.string().optional()})))}),pe=c({id:`anthropic.computer_20250124`,inputSchema:p(()=>S(C.object({action:C.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:C.tuple([C.number().int(),C.number().int()]).optional(),duration:C.number().optional(),scroll_amount:C.number().optional(),scroll_direction:C.enum([`up`,`down`,`left`,`right`]).optional(),start_coordinate:C.tuple([C.number().int(),C.number().int()]).optional(),text:C.string().optional()})))}),me=c({id:`anthropic.memory_20250818`,inputSchema:p(()=>S(C.discriminatedUnion(`command`,[C.object({command:C.literal(`view`),path:C.string(),view_range:C.tuple([C.number(),C.number()]).optional()}),C.object({command:C.literal(`create`),path:C.string(),file_text:C.string()}),C.object({command:C.literal(`str_replace`),path:C.string(),old_str:C.string(),new_str:C.string()}),C.object({command:C.literal(`insert`),path:C.string(),insert_line:C.number(),insert_text:C.string()}),C.object({command:C.literal(`delete`),path:C.string()}),C.object({command:C.literal(`rename`),old_path:C.string(),new_path:C.string()})])))}),he=c({id:`anthropic.text_editor_20241022`,inputSchema:p(()=>S(C.object({command:C.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:C.string(),file_text:C.string().optional(),insert_line:C.number().int().optional(),new_str:C.string().optional(),old_str:C.string().optional(),view_range:C.array(C.number().int()).optional()})))}),ge=c({id:`anthropic.text_editor_20250124`,inputSchema:p(()=>S(C.object({command:C.enum([`view`,`create`,`str_replace`,`insert`,`undo_edit`]),path:C.string(),file_text:C.string().optional(),insert_line:C.number().int().optional(),new_str:C.string().optional(),old_str:C.string().optional(),view_range:C.array(C.number().int()).optional()})))}),_e=c({id:`anthropic.text_editor_20250429`,inputSchema:p(()=>S(C.object({command:C.enum([`view`,`create`,`str_replace`,`insert`]),path:C.string(),file_text:C.string().optional(),insert_line:C.number().int().optional(),new_str:C.string().optional(),old_str:C.string().optional(),view_range:C.array(C.number().int()).optional()})))}),ve=p(()=>S(C.array(C.object({type:C.literal(`tool_reference`),toolName:C.string()})))),ye=l({id:`anthropic.tool_search_bm25_20251119`,inputSchema:p(()=>S(C.object({query:C.string(),limit:C.number().optional()}))),outputSchema:ve}),be={bash_20241022:de,bash_20250124:fe,codeExecution_20250522:re,codeExecution_20250825:J,computer_20241022:$,computer_20250124:pe,memory_20250818:me,textEditor_20241022:he,textEditor_20250124:ge,textEditor_20250429:_e,textEditor_20250728:L,webFetch_20250910:W,webSearch_20250305:V,toolSearchRegex_20251119:ae,toolSearchBm25_20251119:(e={})=>ye(e)};function xe(e={}){let n=x(h({settingValue:e.baseURL,environmentVariableName:`ANTHROPIC_BASE_URL`}))??`https://api.anthropic.com/v1`,r=e.name??`anthropic.messages`,i=()=>b({"anthropic-version":`2023-06-01`,"x-api-key":m({apiKey:e.apiKey,environmentVariableName:`ANTHROPIC_API_KEY`,description:`Anthropic`}),...e.headers},`ai-sdk/anthropic/${w}`),a=t=>new le(t,{provider:r,baseURL:n,headers:i,fetch:e.fetch,generateId:e.generateId??d,supportedUrls:()=>({"image/*":[/^https?:\/\/.*$/]})}),o=function(e){if(new.target)throw Error(`The Anthropic model function cannot be called with the new keyword.`);return a(e)};return o.specificationVersion=`v3`,o.languageModel=a,o.chat=a,o.messages=a,o.embeddingModel=e=>{throw new t({modelId:e,modelType:`embeddingModel`})},o.imageModel=e=>{throw new t({modelId:e,modelType:`imageModel`})},o.tools=be,o}var Se=xe();export{Se as anthropic};
@@ -0,0 +1,11 @@
1
+ import{APICallError as e,InvalidPromptError as t,InvalidResponseDataError as n,TooManyEmbeddingValuesForCallError as r,UnsupportedFunctionalityError as i}from"../../provider/dist/index.js";import{combineHeaders as a,convertBase64ToUint8Array as o,convertToBase64 as s,createBinaryResponseHandler as c,createEventSourceResponseHandler as l,createJsonErrorResponseHandler as u,createJsonResponseHandler as d,createProviderToolFactoryWithOutputSchema as f,createToolNameMapping as p,generateId as m,isNonNullable as h,isParsableJson as g,lazySchema as _,loadApiKey as v,loadOptionalSetting as y,mediaTypeToExtension as b,parseProviderOptions as x,postFormDataToApi as S,postJsonToApi as C,validateTypes as w,withUserAgentSuffix as T,withoutTrailingSlash as E,zodSchema as D}from"../../provider-utils/dist/index.js";import{z as O}from"zod/v4";var k=O.object({error:O.object({message:O.string(),type:O.string().nullish(),param:O.any().nullish(),code:O.union([O.string(),O.number()]).nullish()})}),A=u({errorSchema:k,errorToMessage:e=>e.error.message});function j(e){let t=e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`),n=e.startsWith(`gpt-4`)||e.startsWith(`gpt-5-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-nano`)&&!e.startsWith(`gpt-5-chat`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`),r=!(e.startsWith(`gpt-3`)||e.startsWith(`gpt-4`)||e.startsWith(`chatgpt-4o`)||e.startsWith(`gpt-5-chat`)),i=e.startsWith(`gpt-5.1`)||e.startsWith(`gpt-5.2`);return{supportsFlexProcessing:t,supportsPriorityProcessing:n,isReasoningModel:r,systemMessageMode:r?`developer`:`system`,supportsNonReasoningParameters:i}}function M(e){if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let t=e.prompt_tokens??0,n=e.completion_tokens??0,r=e.prompt_tokens_details?.cached_tokens??0,i=e.completion_tokens_details?.reasoning_tokens??0;return{inputTokens:{total:t,noCache:t-r,cacheRead:r,cacheWrite:void 0},outputTokens:{total:n,text:n-i,reasoning:i},raw:e}}function ee({prompt:e,systemMessageMode:t=`system`}){let n=[],r=[];for(let{role:a,content:o}of e)switch(a){case`system`:switch(t){case`system`:n.push({role:`system`,content:o});break;case`developer`:n.push({role:`developer`,content:o});break;case`remove`:r.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=t;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:if(o.length===1&&o[0].type===`text`){n.push({role:`user`,content:o[0].text});break}n.push({role:`user`,content:o.map((e,t)=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`image_url`,image_url:{url:e.data instanceof URL?e.data.toString():`data:${t};base64,${s(e.data)}`,detail:e.providerOptions?.openai?.imageDetail}}}else if(e.mediaType.startsWith(`audio/`)){if(e.data instanceof URL)throw new i({functionality:`audio file parts with URLs`});switch(e.mediaType){case`audio/wav`:return{type:`input_audio`,input_audio:{data:s(e.data),format:`wav`}};case`audio/mp3`:case`audio/mpeg`:return{type:`input_audio`,input_audio:{data:s(e.data),format:`mp3`}};default:throw new i({functionality:`audio content parts with media type ${e.mediaType}`})}}else if(e.mediaType===`application/pdf`){if(e.data instanceof URL)throw new i({functionality:`PDF file parts with URLs`});return{type:`file`,file:typeof e.data==`string`&&e.data.startsWith(`file-`)?{file_id:e.data}:{filename:e.filename??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${s(e.data)}`}}}else throw new i({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e=``,t=[];for(let n of o)switch(n.type){case`text`:e+=n.text;break;case`tool-call`:t.push({id:n.toolCallId,type:`function`,function:{name:n.toolName,arguments:JSON.stringify(n.input)}});break}n.push({role:`assistant`,content:e,tool_calls:t.length>0?t:void 0});break}case`tool`:for(let e of o){let t=e.output,r;switch(t.type){case`text`:case`error-text`:r=t.value;break;case`execution-denied`:r=t.reason??`Tool execution denied.`;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(t.value);break}n.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:{let e=a;throw Error(`Unsupported role: ${e}`)}}return{messages:n,warnings:r}}function N({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n?new Date(n*1e3):void 0}}function P(e){switch(e){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 te=_(()=>D(O.object({id:O.string().nullish(),created:O.number().nullish(),model:O.string().nullish(),choices:O.array(O.object({message:O.object({role:O.literal(`assistant`).nullish(),content:O.string().nullish(),tool_calls:O.array(O.object({id:O.string().nullish(),type:O.literal(`function`),function:O.object({name:O.string(),arguments:O.string()})})).nullish(),annotations:O.array(O.object({type:O.literal(`url_citation`),url_citation:O.object({start_index:O.number(),end_index:O.number(),url:O.string(),title:O.string()})})).nullish()}),index:O.number(),logprobs:O.object({content:O.array(O.object({token:O.string(),logprob:O.number(),top_logprobs:O.array(O.object({token:O.string(),logprob:O.number()}))})).nullish()}).nullish(),finish_reason:O.string().nullish()})),usage:O.object({prompt_tokens:O.number().nullish(),completion_tokens:O.number().nullish(),total_tokens:O.number().nullish(),prompt_tokens_details:O.object({cached_tokens:O.number().nullish()}).nullish(),completion_tokens_details:O.object({reasoning_tokens:O.number().nullish(),accepted_prediction_tokens:O.number().nullish(),rejected_prediction_tokens:O.number().nullish()}).nullish()}).nullish()}))),ne=_(()=>D(O.union([O.object({id:O.string().nullish(),created:O.number().nullish(),model:O.string().nullish(),choices:O.array(O.object({delta:O.object({role:O.enum([`assistant`]).nullish(),content:O.string().nullish(),tool_calls:O.array(O.object({index:O.number(),id:O.string().nullish(),type:O.literal(`function`).nullish(),function:O.object({name:O.string().nullish(),arguments:O.string().nullish()})})).nullish(),annotations:O.array(O.object({type:O.literal(`url_citation`),url_citation:O.object({start_index:O.number(),end_index:O.number(),url:O.string(),title:O.string()})})).nullish()}).nullish(),logprobs:O.object({content:O.array(O.object({token:O.string(),logprob:O.number(),top_logprobs:O.array(O.object({token:O.string(),logprob:O.number()}))})).nullish()}).nullish(),finish_reason:O.string().nullish(),index:O.number()})),usage:O.object({prompt_tokens:O.number().nullish(),completion_tokens:O.number().nullish(),total_tokens:O.number().nullish(),prompt_tokens_details:O.object({cached_tokens:O.number().nullish()}).nullish(),completion_tokens_details:O.object({reasoning_tokens:O.number().nullish(),accepted_prediction_tokens:O.number().nullish(),rejected_prediction_tokens:O.number().nullish()}).nullish()}).nullish()}),k]))),re=_(()=>D(O.object({logitBias:O.record(O.coerce.number(),O.number()).optional(),logprobs:O.union([O.boolean(),O.number()]).optional(),parallelToolCalls:O.boolean().optional(),user:O.string().optional(),reasoningEffort:O.enum([`none`,`minimal`,`low`,`medium`,`high`,`xhigh`]).optional(),maxCompletionTokens:O.number().optional(),store:O.boolean().optional(),metadata:O.record(O.string().max(64),O.string().max(512)).optional(),prediction:O.record(O.string(),O.any()).optional(),serviceTier:O.enum([`auto`,`flex`,`priority`,`default`]).optional(),strictJsonSchema:O.boolean().optional(),textVerbosity:O.enum([`low`,`medium`,`high`]).optional(),promptCacheKey:O.string().optional(),promptCacheRetention:O.enum([`in_memory`,`24h`]).optional(),safetyIdentifier:O.string().optional()})));function ie({tools:e,toolChoice:t}){e=e?.length?e:void 0;let n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let r=[];for(let t of e)switch(t.type){case`function`:r.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema,...t.strict==null?{}:{strict:t.strict}}});break;default:n.push({type:`unsupported`,feature:`tool type: ${t.type}`});break}if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};let a=t.type;switch(a){case`auto`:case`none`:case`required`:return{tools:r,toolChoice:a,toolWarnings:n};case`tool`:return{tools:r,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:n};default:throw new i({functionality:`tool choice type: ${a}`})}}var ae=class{constructor(e,t){this.specificationVersion=`v3`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,seed:l,tools:u,toolChoice:d,providerOptions:f}){let p=[],m=await x({provider:`openai`,providerOptions:f,schema:re})??{},h=j(this.modelId);i!=null&&p.push({type:`unsupported`,feature:`topK`});let{messages:g,warnings:_}=ee({prompt:e,systemMessageMode:h.systemMessageMode});p.push(..._);let v=m.strictJsonSchema??!0,y={model:this.modelId,logit_bias:m.logitBias,logprobs:m.logprobs===!0||typeof m.logprobs==`number`?!0:void 0,top_logprobs:typeof m.logprobs==`number`?m.logprobs:typeof m.logprobs==`boolean`&&m.logprobs?0:void 0,user:m.user,parallel_tool_calls:m.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,response_format:c?.type===`json`?c.schema==null?{type:`json_object`}:{type:`json_schema`,json_schema:{schema:c.schema,strict:v,name:c.name??`response`,description:c.description}}:void 0,stop:s,seed:l,verbosity:m.textVerbosity,max_completion_tokens:m.maxCompletionTokens,store:m.store,metadata:m.metadata,prediction:m.prediction,reasoning_effort:m.reasoningEffort,service_tier:m.serviceTier,prompt_cache_key:m.promptCacheKey,prompt_cache_retention:m.promptCacheRetention,safety_identifier:m.safetyIdentifier,messages:g};h.isReasoningModel?((m.reasoningEffort!==`none`||!h.supportsNonReasoningParameters)&&(y.temperature!=null&&(y.temperature=void 0,p.push({type:`unsupported`,feature:`temperature`,details:`temperature is not supported for reasoning models`})),y.top_p!=null&&(y.top_p=void 0,p.push({type:`unsupported`,feature:`topP`,details:`topP is not supported for reasoning models`})),y.logprobs!=null&&(y.logprobs=void 0,p.push({type:`other`,message:`logprobs is not supported for reasoning models`}))),y.frequency_penalty!=null&&(y.frequency_penalty=void 0,p.push({type:`unsupported`,feature:`frequencyPenalty`,details:`frequencyPenalty is not supported for reasoning models`})),y.presence_penalty!=null&&(y.presence_penalty=void 0,p.push({type:`unsupported`,feature:`presencePenalty`,details:`presencePenalty is not supported for reasoning models`})),y.logit_bias!=null&&(y.logit_bias=void 0,p.push({type:`other`,message:`logitBias is not supported for reasoning models`})),y.top_logprobs!=null&&(y.top_logprobs=void 0,p.push({type:`other`,message:`topLogprobs is not supported for reasoning models`})),y.max_tokens!=null&&(y.max_completion_tokens??=y.max_tokens,y.max_tokens=void 0)):(this.modelId.startsWith(`gpt-4o-search-preview`)||this.modelId.startsWith(`gpt-4o-mini-search-preview`))&&y.temperature!=null&&(y.temperature=void 0,p.push({type:`unsupported`,feature:`temperature`,details:`temperature is not supported for the search preview models and has been removed.`})),m.serviceTier===`flex`&&!h.supportsFlexProcessing&&(p.push({type:`unsupported`,feature:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),y.service_tier=void 0),m.serviceTier===`priority`&&!h.supportsPriorityProcessing&&(p.push({type:`unsupported`,feature:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),y.service_tier=void 0);let{tools:b,toolChoice:S,toolWarnings:C}=ie({tools:u,toolChoice:d});return{args:{...y,tools:b,tool_choice:S},warnings:[...p,...C]}}async doGenerate(e){var t;let{args:n,warnings:r}=await this.getArgs(e),{responseHeaders:i,value:o,rawValue:s}=await C({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:a(this.config.headers(),e.headers),body:n,failedResponseHandler:A,successfulResponseHandler:d(te),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=o.choices[0],l=[],u=c.message.content;u!=null&&u.length>0&&l.push({type:`text`,text:u});for(let e of c.message.tool_calls??[])l.push({type:`tool-call`,toolCallId:e.id??m(),toolName:e.function.name,input:e.function.arguments});for(let e of c.message.annotations??[])l.push({type:`source`,sourceType:`url`,id:m(),url:e.url_citation.url,title:e.url_citation.title});let f=o.usage?.completion_tokens_details;(t=o.usage)==null||t.prompt_tokens_details;let p={openai:{}};return f?.accepted_prediction_tokens!=null&&(p.openai.acceptedPredictionTokens=f?.accepted_prediction_tokens),f?.rejected_prediction_tokens!=null&&(p.openai.rejectedPredictionTokens=f?.rejected_prediction_tokens),c.logprobs?.content!=null&&(p.openai.logprobs=c.logprobs.content),{content:l,finishReason:P(c.finish_reason),usage:M(o.usage),request:{body:n},response:{...N(o),headers:i,body:s},warnings:r,providerMetadata:p}}async doStream(e){let{args:t,warnings:r}=await this.getArgs(e),i={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:o,value:s}=await C({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:a(this.config.headers(),e.headers),body:i,failedResponseHandler:A,successfulResponseHandler:l(ne),abortSignal:e.abortSignal,fetch:this.config.fetch}),c=[],u=`unknown`,d,f=!1,p=!1,h={openai:{}};return{stream:s.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:r})},transform(t,r){if(e.includeRawChunks&&r.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){u=`error`,r.enqueue({type:`error`,error:t.error});return}let i=t.value;if(`error`in i){u=`error`,r.enqueue({type:`error`,error:i.error});return}if(!f){let e=N(i);Object.values(e).some(Boolean)&&(f=!0,r.enqueue({type:`response-metadata`,...N(i)}))}i.usage!=null&&(d=i.usage,i.usage.completion_tokens_details?.accepted_prediction_tokens!=null&&(h.openai.acceptedPredictionTokens=i.usage.completion_tokens_details?.accepted_prediction_tokens),i.usage.completion_tokens_details?.rejected_prediction_tokens!=null&&(h.openai.rejectedPredictionTokens=i.usage.completion_tokens_details?.rejected_prediction_tokens));let a=i.choices[0];if(a?.finish_reason!=null&&(u=P(a.finish_reason)),a?.logprobs?.content!=null&&(h.openai.logprobs=a.logprobs.content),a?.delta==null)return;let o=a.delta;if(o.content!=null&&(p||=(r.enqueue({type:`text-start`,id:`0`}),!0),r.enqueue({type:`text-delta`,id:`0`,delta:o.content})),o.tool_calls!=null)for(let e of o.tool_calls){let t=e.index;if(c[t]==null){if(e.type!==`function`)throw new n({data:e,message:`Expected 'function' type.`});if(e.id==null)throw new n({data:e,message:`Expected 'id' to be a string.`});if(e.function?.name==null)throw new n({data:e,message:`Expected 'function.name' to be a string.`});r.enqueue({type:`tool-input-start`,id:e.id,toolName:e.function.name}),c[t]={id:e.id,type:`function`,function:{name:e.function.name,arguments:e.function.arguments??``},hasFinished:!1};let i=c[t];i.function?.name!=null&&i.function?.arguments!=null&&(i.function.arguments.length>0&&r.enqueue({type:`tool-input-delta`,id:i.id,delta:i.function.arguments}),g(i.function.arguments)&&(r.enqueue({type:`tool-input-end`,id:i.id}),r.enqueue({type:`tool-call`,toolCallId:i.id??m(),toolName:i.function.name,input:i.function.arguments}),i.hasFinished=!0));continue}let i=c[t];i.hasFinished||(e.function?.arguments!=null&&(i.function.arguments+=e.function?.arguments??``),r.enqueue({type:`tool-input-delta`,id:i.id,delta:e.function.arguments??``}),i.function?.name!=null&&i.function?.arguments!=null&&g(i.function.arguments)&&(r.enqueue({type:`tool-input-end`,id:i.id}),r.enqueue({type:`tool-call`,toolCallId:i.id??m(),toolName:i.function.name,input:i.function.arguments}),i.hasFinished=!0))}if(o.annotations!=null)for(let e of o.annotations)r.enqueue({type:`source`,sourceType:`url`,id:m(),url:e.url_citation.url,title:e.url_citation.title})},flush(e){p&&e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:u,usage:M(d),...h==null?{}:{providerMetadata:h}})}})),request:{body:i},response:{headers:o}}}};function F(e){if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let t=e.prompt_tokens??0,n=e.completion_tokens??0;return{inputTokens:{total:e.prompt_tokens??void 0,noCache:t,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:e.completion_tokens??void 0,text:n,reasoning:void 0},raw:e}}function oe({prompt:e,user:n=`user`,assistant:r=`assistant`}){let a=``;e[0].role===`system`&&(a+=`${e[0].content}
2
+
3
+ `,e=e.slice(1));for(let{role:o,content:s}of e)switch(o){case`system`:throw new t({message:"Unexpected system message in prompt: ${content}",prompt:e});case`user`:{let e=s.map(e=>{switch(e.type){case`text`:return e.text}}).filter(Boolean).join(``);a+=`${n}:
4
+ ${e}
5
+
6
+ `;break}case`assistant`:{let e=s.map(e=>{switch(e.type){case`text`:return e.text;case`tool-call`:throw new i({functionality:`tool-call messages`})}}).join(``);a+=`${r}:
7
+ ${e}
8
+
9
+ `;break}case`tool`:throw new i({functionality:`tool messages`});default:{let e=o;throw Error(`Unsupported role: ${e}`)}}return a+=`${r}:
10
+ `,{prompt:a,stopSequences:[`
11
+ ${n}:`]}}function I({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function L(e){switch(e){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 se=_(()=>D(O.object({id:O.string().nullish(),created:O.number().nullish(),model:O.string().nullish(),choices:O.array(O.object({text:O.string(),finish_reason:O.string(),logprobs:O.object({tokens:O.array(O.string()),token_logprobs:O.array(O.number()),top_logprobs:O.array(O.record(O.string(),O.number())).nullish()}).nullish()})),usage:O.object({prompt_tokens:O.number(),completion_tokens:O.number(),total_tokens:O.number()}).nullish()}))),ce=_(()=>D(O.union([O.object({id:O.string().nullish(),created:O.number().nullish(),model:O.string().nullish(),choices:O.array(O.object({text:O.string(),finish_reason:O.string().nullish(),index:O.number(),logprobs:O.object({tokens:O.array(O.string()),token_logprobs:O.array(O.number()),top_logprobs:O.array(O.record(O.string(),O.number())).nullish()}).nullish()})),usage:O.object({prompt_tokens:O.number(),completion_tokens:O.number(),total_tokens:O.number()}).nullish()}),k]))),R=_(()=>D(O.object({echo:O.boolean().optional(),logitBias:O.record(O.string(),O.number()).optional(),suffix:O.string().optional(),user:O.string().optional(),logprobs:O.union([O.boolean(),O.number()]).optional()}))),le=class{constructor(e,t){this.specificationVersion=`v3`,this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(`.`)[0].trim()}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,tools:l,toolChoice:u,seed:d,providerOptions:f}){let p=[],m={...await x({provider:`openai`,providerOptions:f,schema:R}),...await x({provider:this.providerOptionsName,providerOptions:f,schema:R})};i!=null&&p.push({type:`unsupported`,feature:`topK`}),l?.length&&p.push({type:`unsupported`,feature:`tools`}),u!=null&&p.push({type:`unsupported`,feature:`toolChoice`}),c!=null&&c.type!==`text`&&p.push({type:`unsupported`,feature:`responseFormat`,details:`JSON response format is not supported.`});let{prompt:h,stopSequences:g}=oe({prompt:e}),_=[...g??[],...s??[]];return{args:{model:this.modelId,echo:m.echo,logit_bias:m.logitBias,logprobs:m?.logprobs===!0?0:m?.logprobs===!1?void 0:m?.logprobs,suffix:m.suffix,user:m.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,seed:d,prompt:h,stop:_.length>0?_:void 0},warnings:p}}async doGenerate(e){let{args:t,warnings:n}=await this.getArgs(e),{responseHeaders:r,value:i,rawValue:o}=await C({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:a(this.config.headers(),e.headers),body:t,failedResponseHandler:A,successfulResponseHandler:d(se),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=i.choices[0],c={openai:{}};return s.logprobs!=null&&(c.openai.logprobs=s.logprobs),{content:[{type:`text`,text:s.text}],usage:F(i.usage),finishReason:L(s.finish_reason),request:{body:t},response:{...I(i),headers:r,body:o},providerMetadata:c,warnings:n}}async doStream(e){let{args:t,warnings:n}=await this.getArgs(e),r={...t,stream:!0,stream_options:{include_usage:!0}},{responseHeaders:i,value:o}=await C({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:a(this.config.headers(),e.headers),body:r,failedResponseHandler:A,successfulResponseHandler:l(ce),abortSignal:e.abortSignal,fetch:this.config.fetch}),s=`unknown`,c={openai:{}},u,d=!0;return{stream:o.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){s=`error`,n.enqueue({type:`error`,error:t.error});return}let r=t.value;if(`error`in r){s=`error`,n.enqueue({type:`error`,error:r.error});return}d&&(d=!1,n.enqueue({type:`response-metadata`,...I(r)}),n.enqueue({type:`text-start`,id:`0`})),r.usage!=null&&(u=r.usage);let i=r.choices[0];i?.finish_reason!=null&&(s=L(i.finish_reason)),i?.logprobs!=null&&(c.openai.logprobs=i.logprobs),i?.text!=null&&i.text.length>0&&n.enqueue({type:`text-delta`,id:`0`,delta:i.text})},flush(e){d||e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:s,providerMetadata:c,usage:F(u)})}})),request:{body:r},response:{headers:i}}}},ue=_(()=>D(O.object({dimensions:O.number().optional(),user:O.string().optional()}))),de=_(()=>D(O.object({data:O.array(O.object({embedding:O.array(O.number())})),usage:O.object({prompt_tokens:O.number()}).nullish()}))),fe=class{constructor(e,t){this.specificationVersion=`v3`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}get provider(){return this.config.provider}async doEmbed({values:e,headers:t,abortSignal:n,providerOptions:i}){if(e.length>this.maxEmbeddingsPerCall)throw new r({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:e});let o=await x({provider:`openai`,providerOptions:i,schema:ue})??{},{responseHeaders:s,value:c,rawValue:l}=await C({url:this.config.url({path:`/embeddings`,modelId:this.modelId}),headers:a(this.config.headers(),t),body:{model:this.modelId,input:e,encoding_format:`float`,dimensions:o.dimensions,user:o.user},failedResponseHandler:A,successfulResponseHandler:d(de),abortSignal:n,fetch:this.config.fetch});return{warnings:[],embeddings:c.data.map(e=>e.embedding),usage:c.usage?{tokens:c.usage.prompt_tokens}:void 0,response:{headers:s,body:l}}}},pe=_(()=>D(O.object({created:O.number().nullish(),data:O.array(O.object({b64_json:O.string(),revised_prompt:O.string().nullish()})),background:O.string().nullish(),output_format:O.string().nullish(),size:O.string().nullish(),quality:O.string().nullish(),usage:O.object({input_tokens:O.number().nullish(),output_tokens:O.number().nullish(),total_tokens:O.number().nullish(),input_tokens_details:O.object({image_tokens:O.number().nullish(),text_tokens:O.number().nullish()}).nullish()}).nullish()}))),me={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10},he=new Set([`gpt-image-1`,`gpt-image-1-mini`]),ge=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v3`}get maxImagesPerCall(){return me[this.modelId]??1}get provider(){return this.config.provider}async doGenerate({prompt:e,n:t,size:n,aspectRatio:r,seed:i,providerOptions:o,headers:s,abortSignal:c}){var l;let u=[];r!=null&&u.push({type:`unsupported`,feature:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),i!=null&&u.push({type:`unsupported`,feature:`seed`});let f=((l=this.config._internal)?.currentDate)?.call(l)??new Date,{value:p,responseHeaders:m}=await C({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:a(this.config.headers(),s),body:{model:this.modelId,prompt:e,n:t,size:n,...o.openai??{},...he.has(this.modelId)?{}:{response_format:`b64_json`}},failedResponseHandler:A,successfulResponseHandler:d(pe),abortSignal:c,fetch:this.config.fetch});return{images:p.data.map(e=>e.b64_json),warnings:u,usage:p.usage==null?void 0:{inputTokens:p.usage.input_tokens??void 0,outputTokens:p.usage.output_tokens??void 0,totalTokens:p.usage.total_tokens??void 0},response:{timestamp:f,modelId:this.modelId,headers:m},providerMetadata:{openai:{images:p.data.map(e=>({...e.revised_prompt?{revisedPrompt:e.revised_prompt}:{},created:p.created??void 0,size:p.size??void 0,quality:p.quality??void 0,background:p.background??void 0,outputFormat:p.output_format??void 0}))}}}}},_e=_(()=>D(O.object({callId:O.string(),operation:O.discriminatedUnion(`type`,[O.object({type:O.literal(`create_file`),path:O.string(),diff:O.string()}),O.object({type:O.literal(`delete_file`),path:O.string()}),O.object({type:O.literal(`update_file`),path:O.string(),diff:O.string()})])}))),z=_(()=>D(O.object({status:O.enum([`completed`,`failed`]),output:O.string().optional()})));_(()=>D(O.object({})));var ve=f({id:`openai.apply_patch`,inputSchema:_e,outputSchema:z}),ye=_(()=>D(O.object({code:O.string().nullish(),containerId:O.string()}))),be=_(()=>D(O.object({outputs:O.array(O.discriminatedUnion(`type`,[O.object({type:O.literal(`logs`),logs:O.string()}),O.object({type:O.literal(`image`),url:O.string()})])).nullish()}))),xe=_(()=>D(O.object({container:O.union([O.string(),O.object({fileIds:O.array(O.string()).optional()})]).optional()}))),Se=f({id:`openai.code_interpreter`,inputSchema:ye,outputSchema:be}),Ce=(e={})=>Se(e),B=O.object({key:O.string(),type:O.enum([`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`in`,`nin`]),value:O.union([O.string(),O.number(),O.boolean(),O.array(O.string())])}),V=O.object({type:O.enum([`and`,`or`]),filters:O.array(O.union([B,O.lazy(()=>V)]))}),we=_(()=>D(O.object({vectorStoreIds:O.array(O.string()),maxNumResults:O.number().optional(),ranking:O.object({ranker:O.string().optional(),scoreThreshold:O.number().optional()}).optional(),filters:O.union([B,V]).optional()}))),Te=_(()=>D(O.object({queries:O.array(O.string()),results:O.array(O.object({attributes:O.record(O.string(),O.unknown()),fileId:O.string(),filename:O.string(),score:O.number(),text:O.string()})).nullable()}))),Ee=f({id:`openai.file_search`,inputSchema:O.object({}),outputSchema:Te}),De=_(()=>D(O.object({background:O.enum([`auto`,`opaque`,`transparent`]).optional(),inputFidelity:O.enum([`low`,`high`]).optional(),inputImageMask:O.object({fileId:O.string().optional(),imageUrl:O.string().optional()}).optional(),model:O.string().optional(),moderation:O.enum([`auto`]).optional(),outputCompression:O.number().int().min(0).max(100).optional(),outputFormat:O.enum([`png`,`jpeg`,`webp`]).optional(),partialImages:O.number().int().min(0).max(3).optional(),quality:O.enum([`auto`,`low`,`medium`,`high`]).optional(),size:O.enum([`1024x1024`,`1024x1536`,`1536x1024`,`auto`]).optional()}).strict())),Oe=f({id:`openai.image_generation`,inputSchema:_(()=>D(O.object({}))),outputSchema:_(()=>D(O.object({result:O.string()})))}),ke=(e={})=>Oe(e),H=_(()=>D(O.object({action:O.object({type:O.literal(`exec`),command:O.array(O.string()),timeoutMs:O.number().optional(),user:O.string().optional(),workingDirectory:O.string().optional(),env:O.record(O.string(),O.string()).optional()})}))),U=_(()=>D(O.object({output:O.string()}))),Ae=f({id:`openai.local_shell`,inputSchema:H,outputSchema:U}),W=_(()=>D(O.object({action:O.object({commands:O.array(O.string()),timeoutMs:O.number().optional(),maxOutputLength:O.number().optional()})}))),G=_(()=>D(O.object({output:O.array(O.object({stdout:O.string(),stderr:O.string(),outcome:O.discriminatedUnion(`type`,[O.object({type:O.literal(`timeout`)}),O.object({type:O.literal(`exit`),exitCode:O.number()})])}))}))),je=f({id:`openai.shell`,inputSchema:W,outputSchema:G}),Me=_(()=>D(O.object({externalWebAccess:O.boolean().optional(),filters:O.object({allowedDomains:O.array(O.string()).optional()}).optional(),searchContextSize:O.enum([`low`,`medium`,`high`]).optional(),userLocation:O.object({type:O.literal(`approximate`),country:O.string().optional(),city:O.string().optional(),region:O.string().optional(),timezone:O.string().optional()}).optional()}))),Ne=f({id:`openai.web_search`,inputSchema:_(()=>D(O.object({}))),outputSchema:_(()=>D(O.object({action:O.discriminatedUnion(`type`,[O.object({type:O.literal(`search`),query:O.string().optional()}),O.object({type:O.literal(`openPage`),url:O.string().nullish()}),O.object({type:O.literal(`findInPage`),url:O.string().nullish(),pattern:O.string().nullish()})]),sources:O.array(O.discriminatedUnion(`type`,[O.object({type:O.literal(`url`),url:O.string()}),O.object({type:O.literal(`api`),name:O.string()})])).optional()})))}),Pe=(e={})=>Ne(e),Fe=_(()=>D(O.object({searchContextSize:O.enum([`low`,`medium`,`high`]).optional(),userLocation:O.object({type:O.literal(`approximate`),country:O.string().optional(),city:O.string().optional(),region:O.string().optional(),timezone:O.string().optional()}).optional()}))),Ie=f({id:`openai.web_search_preview`,inputSchema:_(()=>D(O.object({}))),outputSchema:_(()=>D(O.object({action:O.discriminatedUnion(`type`,[O.object({type:O.literal(`search`),query:O.string().optional()}),O.object({type:O.literal(`openPage`),url:O.string().nullish()}),O.object({type:O.literal(`findInPage`),url:O.string().nullish(),pattern:O.string().nullish()})])})))}),K=O.lazy(()=>O.union([O.string(),O.number(),O.boolean(),O.null(),O.array(K),O.record(O.string(),K)])),Le=_(()=>D(O.object({serverLabel:O.string(),allowedTools:O.union([O.array(O.string()),O.object({readOnly:O.boolean().optional(),toolNames:O.array(O.string()).optional()})]).optional(),authorization:O.string().optional(),connectorId:O.string().optional(),headers:O.record(O.string(),O.string()).optional(),serverDescription:O.string().optional(),serverUrl:O.string().optional()}).refine(e=>e.serverUrl!=null||e.connectorId!=null,`One of serverUrl or connectorId must be provided.`))),Re=f({id:`openai.mcp`,inputSchema:_(()=>D(O.object({}))),outputSchema:_(()=>D(O.discriminatedUnion(`type`,[O.object({type:O.literal(`call`),serverLabel:O.string(),name:O.string(),arguments:O.string(),output:O.string().nullable().optional(),error:O.union([O.string(),K]).optional()}),O.object({type:O.literal(`listTools`),serverLabel:O.string(),tools:O.array(O.object({name:O.string(),description:O.string().optional(),inputSchema:K,annotations:O.record(O.string(),K).optional()})),error:O.union([O.string(),K]).optional()}),O.object({type:O.literal(`approvalRequest`),serverLabel:O.string(),name:O.string(),arguments:O.string(),approvalRequestId:O.string()})])))}),ze={applyPatch:ve,codeInterpreter:Ce,fileSearch:Ee,imageGeneration:ke,localShell:Ae,shell:je,webSearchPreview:Ie,webSearch:Pe,mcp:e=>Re(e)};function q(e){if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let t=e.input_tokens,n=e.output_tokens,r=e.input_tokens_details?.cached_tokens??0,i=e.output_tokens_details?.reasoning_tokens??0;return{inputTokens:{total:t,noCache:t-r,cacheRead:r,cacheWrite:void 0},outputTokens:{total:n,text:n-i,reasoning:i},raw:e}}function J(e,t){return t?t.some(t=>e.startsWith(t)):!1}async function Be({prompt:e,toolNameMapping:t,systemMessageMode:n,fileIdPrefixes:r,store:a,hasLocalShellTool:o=!1,hasShellTool:c=!1,hasApplyPatchTool:l=!1}){let u=[],d=[];for(let{role:f,content:p}of e)switch(f){case`system`:switch(n){case`system`:u.push({role:`system`,content:p});break;case`developer`:u.push({role:`developer`,content:p});break;case`remove`:d.push({type:`other`,message:`system messages are removed for this model`});break;default:{let e=n;throw Error(`Unsupported system message mode: ${e}`)}}break;case`user`:u.push({role:`user`,content:p.map((e,t)=>{switch(e.type){case`text`:return{type:`input_text`,text:e.text};case`file`:if(e.mediaType.startsWith(`image/`)){let t=e.mediaType===`image/*`?`image/jpeg`:e.mediaType;return{type:`input_image`,...e.data instanceof URL?{image_url:e.data.toString()}:typeof e.data==`string`&&J(e.data,r)?{file_id:e.data}:{image_url:`data:${t};base64,${s(e.data)}`},detail:e.providerOptions?.openai?.imageDetail}}else if(e.mediaType===`application/pdf`)return e.data instanceof URL?{type:`input_file`,file_url:e.data.toString()}:{type:`input_file`,...typeof e.data==`string`&&J(e.data,r)?{file_id:e.data}:{filename:e.filename??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${s(e.data)}`}};else throw new i({functionality:`file part media type ${e.mediaType}`})}})});break;case`assistant`:{let e={};for(let n of p)switch(n.type){case`text`:{let e=n.providerOptions?.openai?.itemId;if(a&&e!=null){u.push({type:`item_reference`,id:e});break}u.push({role:`assistant`,content:[{type:`output_text`,text:n.text}],id:e});break}case`tool-call`:{if(n.providerExecuted)break;let e=n.providerOptions?.openai?.itemId;if(a&&e!=null){u.push({type:`item_reference`,id:e});break}let r=t.toProviderToolName(n.toolName);if(o&&r===`local_shell`){let t=await w({value:n.input,schema:H});u.push({type:`local_shell_call`,call_id:n.toolCallId,id:e,action:{type:`exec`,command:t.action.command,timeout_ms:t.action.timeoutMs,user:t.action.user,working_directory:t.action.workingDirectory,env:t.action.env}});break}if(c&&r===`shell`){let t=await w({value:n.input,schema:W});u.push({type:`shell_call`,call_id:n.toolCallId,id:e,status:`completed`,action:{commands:t.action.commands,timeout_ms:t.action.timeoutMs,max_output_length:t.action.maxOutputLength}});break}u.push({type:`function_call`,call_id:n.toolCallId,name:r,arguments:JSON.stringify(n.input),id:e});break}case`tool-result`:a?u.push({type:`item_reference`,id:n.toolCallId}):d.push({type:`other`,message:`Results for OpenAI tool ${n.toolName} are not sent to the API when store is false`});break;case`reasoning`:{let t=await x({provider:`openai`,providerOptions:n.providerOptions,schema:Ve}),r=t?.itemId;if(r!=null){let i=e[r];if(a)i===void 0&&(u.push({type:`item_reference`,id:r}),e[r]={type:`reasoning`,id:r,summary:[]});else{let a=[];n.text.length>0?a.push({type:`summary_text`,text:n.text}):i!==void 0&&d.push({type:`other`,message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(n)}.`}),i===void 0?(e[r]={type:`reasoning`,id:r,encrypted_content:t?.reasoningEncryptedContent,summary:a},u.push(e[r])):(i.summary.push(...a),t?.reasoningEncryptedContent!=null&&(i.encrypted_content=t.reasoningEncryptedContent))}}else d.push({type:`other`,message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(n)}.`});break}}break}case`tool`:for(let e of p){let n=e.output,r=t.toProviderToolName(e.toolName);if(o&&r===`local_shell`&&n.type===`json`){let t=await w({value:n.value,schema:U});u.push({type:`local_shell_call_output`,call_id:e.toolCallId,output:t.output});continue}if(c&&r===`shell`&&n.type===`json`){let t=await w({value:n.value,schema:G});u.push({type:`shell_call_output`,call_id:e.toolCallId,output:t.output.map(e=>({stdout:e.stdout,stderr:e.stderr,outcome:e.outcome.type===`timeout`?{type:`timeout`}:{type:`exit`,exit_code:e.outcome.exitCode}}))});continue}if(l&&e.toolName===`apply_patch`&&n.type===`json`){let t=await w({value:n.value,schema:z});u.push({type:`apply_patch_call_output`,call_id:e.toolCallId,status:t.status,output:t.output});continue}let i;switch(n.type){case`text`:case`error-text`:i=n.value;break;case`execution-denied`:i=n.reason??`Tool execution denied.`;break;case`json`:case`error-json`:i=JSON.stringify(n.value);break;case`content`:i=n.value.map(e=>{switch(e.type){case`text`:return{type:`input_text`,text:e.text};case`image-data`:return{type:`input_image`,image_url:`data:${e.mediaType};base64,${e.data}`};case`file-data`:return{type:`input_file`,filename:e.filename??`data`,file_data:`data:${e.mediaType};base64,${e.data}`};default:d.push({type:`other`,message:`unsupported tool content part type: ${e.type}`});return}}).filter(h);break}u.push({type:`function_call_output`,call_id:e.toolCallId,output:i})}break;default:{let e=f;throw Error(`Unsupported role: ${e}`)}}return{input:u,warnings:d}}var Ve=O.object({itemId:O.string().nullish(),reasoningEncryptedContent:O.string().nullish()});function Y({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?`tool-calls`:`stop`;case`max_output_tokens`:return`length`;case`content_filter`:return`content-filter`;default:return t?`tool-calls`:`unknown`}}var He=_(()=>D(O.union([O.object({type:O.literal(`response.output_text.delta`),item_id:O.string(),delta:O.string(),logprobs:O.array(O.object({token:O.string(),logprob:O.number(),top_logprobs:O.array(O.object({token:O.string(),logprob:O.number()}))})).nullish()}),O.object({type:O.enum([`response.completed`,`response.incomplete`]),response:O.object({incomplete_details:O.object({reason:O.string()}).nullish(),usage:O.object({input_tokens:O.number(),input_tokens_details:O.object({cached_tokens:O.number().nullish()}).nullish(),output_tokens:O.number(),output_tokens_details:O.object({reasoning_tokens:O.number().nullish()}).nullish()}),service_tier:O.string().nullish()})}),O.object({type:O.literal(`response.created`),response:O.object({id:O.string(),created_at:O.number(),model:O.string(),service_tier:O.string().nullish()})}),O.object({type:O.literal(`response.output_item.added`),output_index:O.number(),item:O.discriminatedUnion(`type`,[O.object({type:O.literal(`message`),id:O.string()}),O.object({type:O.literal(`reasoning`),id:O.string(),encrypted_content:O.string().nullish()}),O.object({type:O.literal(`function_call`),id:O.string(),call_id:O.string(),name:O.string(),arguments:O.string()}),O.object({type:O.literal(`web_search_call`),id:O.string(),status:O.string()}),O.object({type:O.literal(`computer_call`),id:O.string(),status:O.string()}),O.object({type:O.literal(`file_search_call`),id:O.string()}),O.object({type:O.literal(`image_generation_call`),id:O.string()}),O.object({type:O.literal(`code_interpreter_call`),id:O.string(),container_id:O.string(),code:O.string().nullable(),outputs:O.array(O.discriminatedUnion(`type`,[O.object({type:O.literal(`logs`),logs:O.string()}),O.object({type:O.literal(`image`),url:O.string()})])).nullable(),status:O.string()}),O.object({type:O.literal(`mcp_call`),id:O.string(),status:O.string()}),O.object({type:O.literal(`mcp_list_tools`),id:O.string()}),O.object({type:O.literal(`mcp_approval_request`),id:O.string()}),O.object({type:O.literal(`apply_patch_call`),id:O.string(),call_id:O.string(),status:O.enum([`in_progress`,`completed`]),operation:O.discriminatedUnion(`type`,[O.object({type:O.literal(`create_file`),path:O.string(),diff:O.string()}),O.object({type:O.literal(`delete_file`),path:O.string()}),O.object({type:O.literal(`update_file`),path:O.string(),diff:O.string()})])}),O.object({type:O.literal(`shell_call`),id:O.string(),call_id:O.string(),status:O.enum([`in_progress`,`completed`,`incomplete`]),action:O.object({commands:O.array(O.string())})})])}),O.object({type:O.literal(`response.output_item.done`),output_index:O.number(),item:O.discriminatedUnion(`type`,[O.object({type:O.literal(`message`),id:O.string()}),O.object({type:O.literal(`reasoning`),id:O.string(),encrypted_content:O.string().nullish()}),O.object({type:O.literal(`function_call`),id:O.string(),call_id:O.string(),name:O.string(),arguments:O.string(),status:O.literal(`completed`)}),O.object({type:O.literal(`code_interpreter_call`),id:O.string(),code:O.string().nullable(),container_id:O.string(),outputs:O.array(O.discriminatedUnion(`type`,[O.object({type:O.literal(`logs`),logs:O.string()}),O.object({type:O.literal(`image`),url:O.string()})])).nullable()}),O.object({type:O.literal(`image_generation_call`),id:O.string(),result:O.string()}),O.object({type:O.literal(`web_search_call`),id:O.string(),status:O.string(),action:O.discriminatedUnion(`type`,[O.object({type:O.literal(`search`),query:O.string().nullish(),sources:O.array(O.discriminatedUnion(`type`,[O.object({type:O.literal(`url`),url:O.string()}),O.object({type:O.literal(`api`),name:O.string()})])).nullish()}),O.object({type:O.literal(`open_page`),url:O.string().nullish()}),O.object({type:O.literal(`find_in_page`),url:O.string().nullish(),pattern:O.string().nullish()})])}),O.object({type:O.literal(`file_search_call`),id:O.string(),queries:O.array(O.string()),results:O.array(O.object({attributes:O.record(O.string(),O.union([O.string(),O.number(),O.boolean()])),file_id:O.string(),filename:O.string(),score:O.number(),text:O.string()})).nullish()}),O.object({type:O.literal(`local_shell_call`),id:O.string(),call_id:O.string(),action:O.object({type:O.literal(`exec`),command:O.array(O.string()),timeout_ms:O.number().optional(),user:O.string().optional(),working_directory:O.string().optional(),env:O.record(O.string(),O.string()).optional()})}),O.object({type:O.literal(`computer_call`),id:O.string(),status:O.literal(`completed`)}),O.object({type:O.literal(`mcp_call`),id:O.string(),status:O.string(),arguments:O.string(),name:O.string(),server_label:O.string(),output:O.string().nullish(),error:O.union([O.string(),O.object({type:O.string().optional(),code:O.union([O.number(),O.string()]).optional(),message:O.string().optional()}).loose()]).nullish()}),O.object({type:O.literal(`mcp_list_tools`),id:O.string(),server_label:O.string(),tools:O.array(O.object({name:O.string(),description:O.string().optional(),input_schema:O.any(),annotations:O.record(O.string(),O.unknown()).optional()})),error:O.union([O.string(),O.object({type:O.string().optional(),code:O.union([O.number(),O.string()]).optional(),message:O.string().optional()}).loose()]).optional()}),O.object({type:O.literal(`mcp_approval_request`),id:O.string(),server_label:O.string(),name:O.string(),arguments:O.string(),approval_request_id:O.string()}),O.object({type:O.literal(`apply_patch_call`),id:O.string(),call_id:O.string(),status:O.enum([`in_progress`,`completed`]),operation:O.discriminatedUnion(`type`,[O.object({type:O.literal(`create_file`),path:O.string(),diff:O.string()}),O.object({type:O.literal(`delete_file`),path:O.string()}),O.object({type:O.literal(`update_file`),path:O.string(),diff:O.string()})])}),O.object({type:O.literal(`shell_call`),id:O.string(),call_id:O.string(),status:O.enum([`in_progress`,`completed`,`incomplete`]),action:O.object({commands:O.array(O.string())})})])}),O.object({type:O.literal(`response.function_call_arguments.delta`),item_id:O.string(),output_index:O.number(),delta:O.string()}),O.object({type:O.literal(`response.image_generation_call.partial_image`),item_id:O.string(),output_index:O.number(),partial_image_b64:O.string()}),O.object({type:O.literal(`response.code_interpreter_call_code.delta`),item_id:O.string(),output_index:O.number(),delta:O.string()}),O.object({type:O.literal(`response.code_interpreter_call_code.done`),item_id:O.string(),output_index:O.number(),code:O.string()}),O.object({type:O.literal(`response.output_text.annotation.added`),annotation:O.discriminatedUnion(`type`,[O.object({type:O.literal(`url_citation`),start_index:O.number(),end_index:O.number(),url:O.string(),title:O.string()}),O.object({type:O.literal(`file_citation`),file_id:O.string(),filename:O.string().nullish(),index:O.number().nullish(),start_index:O.number().nullish(),end_index:O.number().nullish(),quote:O.string().nullish()}),O.object({type:O.literal(`container_file_citation`),container_id:O.string(),file_id:O.string(),filename:O.string().nullish(),start_index:O.number().nullish(),end_index:O.number().nullish(),index:O.number().nullish()}),O.object({type:O.literal(`file_path`),file_id:O.string(),index:O.number().nullish()})])}),O.object({type:O.literal(`response.reasoning_summary_part.added`),item_id:O.string(),summary_index:O.number()}),O.object({type:O.literal(`response.reasoning_summary_text.delta`),item_id:O.string(),summary_index:O.number(),delta:O.string()}),O.object({type:O.literal(`response.reasoning_summary_part.done`),item_id:O.string(),summary_index:O.number()}),O.object({type:O.literal(`error`),sequence_number:O.number(),error:O.object({type:O.string(),code:O.string(),message:O.string(),param:O.string().nullish()})}),O.object({type:O.string()}).loose().transform(e=>({type:`unknown_chunk`,message:e.type}))]))),Ue=_(()=>D(O.object({id:O.string().optional(),created_at:O.number().optional(),error:O.object({message:O.string(),type:O.string(),param:O.string().nullish(),code:O.string()}).nullish(),model:O.string().optional(),output:O.array(O.discriminatedUnion(`type`,[O.object({type:O.literal(`message`),role:O.literal(`assistant`),id:O.string(),content:O.array(O.object({type:O.literal(`output_text`),text:O.string(),logprobs:O.array(O.object({token:O.string(),logprob:O.number(),top_logprobs:O.array(O.object({token:O.string(),logprob:O.number()}))})).nullish(),annotations:O.array(O.discriminatedUnion(`type`,[O.object({type:O.literal(`url_citation`),start_index:O.number(),end_index:O.number(),url:O.string(),title:O.string()}),O.object({type:O.literal(`file_citation`),file_id:O.string(),filename:O.string().nullish(),index:O.number().nullish(),start_index:O.number().nullish(),end_index:O.number().nullish(),quote:O.string().nullish()}),O.object({type:O.literal(`container_file_citation`),container_id:O.string(),file_id:O.string(),filename:O.string().nullish(),start_index:O.number().nullish(),end_index:O.number().nullish(),index:O.number().nullish()}),O.object({type:O.literal(`file_path`),file_id:O.string(),index:O.number().nullish()})]))}))}),O.object({type:O.literal(`web_search_call`),id:O.string(),status:O.string(),action:O.discriminatedUnion(`type`,[O.object({type:O.literal(`search`),query:O.string().nullish(),sources:O.array(O.discriminatedUnion(`type`,[O.object({type:O.literal(`url`),url:O.string()}),O.object({type:O.literal(`api`),name:O.string()})])).nullish()}),O.object({type:O.literal(`open_page`),url:O.string().nullish()}),O.object({type:O.literal(`find_in_page`),url:O.string().nullish(),pattern:O.string().nullish()})])}),O.object({type:O.literal(`file_search_call`),id:O.string(),queries:O.array(O.string()),results:O.array(O.object({attributes:O.record(O.string(),O.union([O.string(),O.number(),O.boolean()])),file_id:O.string(),filename:O.string(),score:O.number(),text:O.string()})).nullish()}),O.object({type:O.literal(`code_interpreter_call`),id:O.string(),code:O.string().nullable(),container_id:O.string(),outputs:O.array(O.discriminatedUnion(`type`,[O.object({type:O.literal(`logs`),logs:O.string()}),O.object({type:O.literal(`image`),url:O.string()})])).nullable()}),O.object({type:O.literal(`image_generation_call`),id:O.string(),result:O.string()}),O.object({type:O.literal(`local_shell_call`),id:O.string(),call_id:O.string(),action:O.object({type:O.literal(`exec`),command:O.array(O.string()),timeout_ms:O.number().optional(),user:O.string().optional(),working_directory:O.string().optional(),env:O.record(O.string(),O.string()).optional()})}),O.object({type:O.literal(`function_call`),call_id:O.string(),name:O.string(),arguments:O.string(),id:O.string()}),O.object({type:O.literal(`computer_call`),id:O.string(),status:O.string().optional()}),O.object({type:O.literal(`reasoning`),id:O.string(),encrypted_content:O.string().nullish(),summary:O.array(O.object({type:O.literal(`summary_text`),text:O.string()}))}),O.object({type:O.literal(`mcp_call`),id:O.string(),status:O.string(),arguments:O.string(),name:O.string(),server_label:O.string(),output:O.string().nullish(),error:O.union([O.string(),O.object({type:O.string().optional(),code:O.union([O.number(),O.string()]).optional(),message:O.string().optional()}).loose()]).nullish()}),O.object({type:O.literal(`mcp_list_tools`),id:O.string(),server_label:O.string(),tools:O.array(O.object({name:O.string(),description:O.string().optional(),input_schema:O.any(),annotations:O.record(O.string(),O.unknown()).optional()})),error:O.union([O.string(),O.object({type:O.string().optional(),code:O.union([O.number(),O.string()]).optional(),message:O.string().optional()}).loose()]).optional()}),O.object({type:O.literal(`mcp_approval_request`),id:O.string(),server_label:O.string(),name:O.string(),arguments:O.string(),approval_request_id:O.string()}),O.object({type:O.literal(`apply_patch_call`),id:O.string(),call_id:O.string(),status:O.enum([`in_progress`,`completed`]),operation:O.discriminatedUnion(`type`,[O.object({type:O.literal(`create_file`),path:O.string(),diff:O.string()}),O.object({type:O.literal(`delete_file`),path:O.string()}),O.object({type:O.literal(`update_file`),path:O.string(),diff:O.string()})])}),O.object({type:O.literal(`shell_call`),id:O.string(),call_id:O.string(),status:O.enum([`in_progress`,`completed`,`incomplete`]),action:O.object({commands:O.array(O.string())})})])).optional(),service_tier:O.string().nullish(),incomplete_details:O.object({reason:O.string()}).nullish(),usage:O.object({input_tokens:O.number(),input_tokens_details:O.object({cached_tokens:O.number().nullish()}).nullish(),output_tokens:O.number(),output_tokens_details:O.object({reasoning_tokens:O.number().nullish()}).nullish()}).optional()}))),X=20,We=_(()=>D(O.object({conversation:O.string().nullish(),include:O.array(O.enum([`reasoning.encrypted_content`,`file_search_call.results`,`message.output_text.logprobs`])).nullish(),instructions:O.string().nullish(),logprobs:O.union([O.boolean(),O.number().min(1).max(X)]).optional(),maxToolCalls:O.number().nullish(),metadata:O.any().nullish(),parallelToolCalls:O.boolean().nullish(),previousResponseId:O.string().nullish(),promptCacheKey:O.string().nullish(),promptCacheRetention:O.enum([`in_memory`,`24h`]).nullish(),reasoningEffort:O.string().nullish(),reasoningSummary:O.string().nullish(),safetyIdentifier:O.string().nullish(),serviceTier:O.enum([`auto`,`flex`,`priority`,`default`]).nullish(),store:O.boolean().nullish(),strictJsonSchema:O.boolean().nullish(),textVerbosity:O.enum([`low`,`medium`,`high`]).nullish(),truncation:O.enum([`auto`,`disabled`]).nullish(),user:O.string().nullish()})));async function Ge({tools:e,toolChoice:t}){e=e?.length?e:void 0;let n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let r=[];for(let t of e)switch(t.type){case`function`:r.push({type:`function`,name:t.name,description:t.description,parameters:t.inputSchema,...t.strict==null?{}:{strict:t.strict}});break;case`provider`:switch(t.id){case`openai.file_search`:{let e=await w({value:t.args,schema:we});r.push({type:`file_search`,vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker,score_threshold:e.ranking.scoreThreshold}:void 0,filters:e.filters});break}case`openai.local_shell`:r.push({type:`local_shell`});break;case`openai.shell`:r.push({type:`shell`});break;case`openai.apply_patch`:r.push({type:`apply_patch`});break;case`openai.web_search_preview`:{let e=await w({value:t.args,schema:Fe});r.push({type:`web_search_preview`,search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.web_search`:{let e=await w({value:t.args,schema:Me});r.push({type:`web_search`,filters:e.filters==null?void 0:{allowed_domains:e.filters.allowedDomains},external_web_access:e.externalWebAccess,search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.code_interpreter`:{let e=await w({value:t.args,schema:xe});r.push({type:`code_interpreter`,container:e.container==null?{type:`auto`,file_ids:void 0}:typeof e.container==`string`?e.container:{type:`auto`,file_ids:e.container.fileIds}});break}case`openai.image_generation`:{let e=await w({value:t.args,schema:De});r.push({type:`image_generation`,background:e.background,input_fidelity:e.inputFidelity,input_image_mask:e.inputImageMask?{file_id:e.inputImageMask.fileId,image_url:e.inputImageMask.imageUrl}:void 0,model:e.model,moderation:e.moderation,partial_images:e.partialImages,quality:e.quality,output_compression:e.outputCompression,output_format:e.outputFormat,size:e.size});break}case`openai.mcp`:{let e=await w({value:t.args,schema:Le});r.push({type:`mcp`,server_label:e.serverLabel,allowed_tools:Array.isArray(e.allowedTools)?e.allowedTools:e.allowedTools?{read_only:e.allowedTools.readOnly,tool_names:e.allowedTools.toolNames}:void 0,authorization:e.authorization,connector_id:e.connectorId,headers:e.headers,require_approval:`never`,server_description:e.serverDescription,server_url:e.serverUrl});break}}break;default:n.push({type:`unsupported`,feature:`function tool ${t}`});break}if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};let a=t.type;switch(a){case`auto`:case`none`:case`required`:return{tools:r,toolChoice:a,toolWarnings:n};case`tool`:return{tools:r,toolChoice:t.toolName===`code_interpreter`||t.toolName===`file_search`||t.toolName===`image_generation`||t.toolName===`web_search_preview`||t.toolName===`web_search`||t.toolName===`mcp`||t.toolName===`apply_patch`?{type:t.toolName}:{type:`function`,name:t.toolName},toolWarnings:n};default:throw new i({functionality:`tool choice type: ${a}`})}}var Ke=class{constructor(e,t){this.specificationVersion=`v3`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:i,presencePenalty:a,frequencyPenalty:o,seed:s,prompt:c,providerOptions:l,tools:u,toolChoice:d,responseFormat:f}){let m=[],h=j(this.modelId);i!=null&&m.push({type:`unsupported`,feature:`topK`}),s!=null&&m.push({type:`unsupported`,feature:`seed`}),a!=null&&m.push({type:`unsupported`,feature:`presencePenalty`}),o!=null&&m.push({type:`unsupported`,feature:`frequencyPenalty`}),n!=null&&m.push({type:`unsupported`,feature:`stopSequences`});let g=await x({provider:`openai`,providerOptions:l,schema:We});g?.conversation&&g?.previousResponseId&&m.push({type:`unsupported`,feature:`conversation`,details:`conversation and previousResponseId cannot be used together`});let _=p({tools:u,providerToolNames:{"openai.code_interpreter":`code_interpreter`,"openai.file_search":`file_search`,"openai.image_generation":`image_generation`,"openai.local_shell":`local_shell`,"openai.shell":`shell`,"openai.web_search":`web_search`,"openai.web_search_preview":`web_search_preview`,"openai.mcp":`mcp`,"openai.apply_patch":`apply_patch`}}),{input:v,warnings:y}=await Be({prompt:c,toolNameMapping:_,systemMessageMode:h.systemMessageMode,fileIdPrefixes:this.config.fileIdPrefixes,store:g?.store??!0,hasLocalShellTool:w(`openai.local_shell`),hasShellTool:w(`openai.shell`),hasApplyPatchTool:w(`openai.apply_patch`)});m.push(...y);let b=g?.strictJsonSchema??!0,S=g?.include;function C(e){S==null?S=[e]:S.includes(e)||(S=[...S,e])}function w(e){return u?.find(t=>t.type===`provider`&&t.id===e)!=null}let T=typeof g?.logprobs==`number`?g?.logprobs:g?.logprobs===!0?X:void 0;T&&C(`message.output_text.logprobs`);let E=u?.find(e=>e.type===`provider`&&(e.id===`openai.web_search`||e.id===`openai.web_search_preview`))?.name;E&&C(`web_search_call.action.sources`),w(`openai.code_interpreter`)&&C(`code_interpreter_call.outputs`);let D=g?.store;D===!1&&h.isReasoningModel&&C(`reasoning.encrypted_content`);let O={model:this.modelId,input:v,temperature:t,top_p:r,max_output_tokens:e,...(f?.type===`json`||g?.textVerbosity)&&{text:{...f?.type===`json`&&{format:f.schema==null?{type:`json_object`}:{type:`json_schema`,strict:b,name:f.name??`response`,description:f.description,schema:f.schema}},...g?.textVerbosity&&{verbosity:g.textVerbosity}}},conversation:g?.conversation,max_tool_calls:g?.maxToolCalls,metadata:g?.metadata,parallel_tool_calls:g?.parallelToolCalls,previous_response_id:g?.previousResponseId,store:D,user:g?.user,instructions:g?.instructions,service_tier:g?.serviceTier,include:S,prompt_cache_key:g?.promptCacheKey,prompt_cache_retention:g?.promptCacheRetention,safety_identifier:g?.safetyIdentifier,top_logprobs:T,truncation:g?.truncation,...h.isReasoningModel&&(g?.reasoningEffort!=null||g?.reasoningSummary!=null)&&{reasoning:{...g?.reasoningEffort!=null&&{effort:g.reasoningEffort},...g?.reasoningSummary!=null&&{summary:g.reasoningSummary}}}};h.isReasoningModel?g?.reasoningEffort===`none`&&h.supportsNonReasoningParameters||(O.temperature!=null&&(O.temperature=void 0,m.push({type:`unsupported`,feature:`temperature`,details:`temperature is not supported for reasoning models`})),O.top_p!=null&&(O.top_p=void 0,m.push({type:`unsupported`,feature:`topP`,details:`topP is not supported for reasoning models`}))):(g?.reasoningEffort!=null&&m.push({type:`unsupported`,feature:`reasoningEffort`,details:`reasoningEffort is not supported for non-reasoning models`}),g?.reasoningSummary!=null&&m.push({type:`unsupported`,feature:`reasoningSummary`,details:`reasoningSummary is not supported for non-reasoning models`})),g?.serviceTier===`flex`&&!h.supportsFlexProcessing&&(m.push({type:`unsupported`,feature:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),delete O.service_tier),g?.serviceTier===`priority`&&!h.supportsPriorityProcessing&&(m.push({type:`unsupported`,feature:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),delete O.service_tier);let{tools:k,toolChoice:A,toolWarnings:M}=await Ge({tools:u,toolChoice:d});return{webSearchToolName:E,args:{...O,tools:k,tool_choice:A},warnings:[...m,...M],store:D,toolNameMapping:_}}async doGenerate(t){var n,r,i,o;let{args:s,warnings:c,webSearchToolName:l,toolNameMapping:u}=await this.getArgs(t),f=this.config.url({path:`/responses`,modelId:this.modelId}),p=this.config.provider.replace(`.responses`,``),{responseHeaders:h,value:g,rawValue:_}=await C({url:f,headers:a(this.config.headers(),t.headers),body:s,failedResponseHandler:A,successfulResponseHandler:d(Ue),abortSignal:t.abortSignal,fetch:this.config.fetch});if(g.error)throw new e({message:g.error.message,url:f,requestBodyValues:s,statusCode:400,responseHeaders:h,responseBody:_,isRetryable:!1});let v=[],y=[],b=!1;for(let e of g.output)switch(e.type){case`reasoning`:e.summary.length===0&&e.summary.push({type:`summary_text`,text:``});for(let t of e.summary)v.push({type:`reasoning`,text:t.text,providerMetadata:{[p]:{itemId:e.id,reasoningEncryptedContent:e.encrypted_content??null}}});break;case`image_generation_call`:v.push({type:`tool-call`,toolCallId:e.id,toolName:u.toCustomToolName(`image_generation`),input:`{}`,providerExecuted:!0}),v.push({type:`tool-result`,toolCallId:e.id,toolName:u.toCustomToolName(`image_generation`),result:{result:e.result}});break;case`local_shell_call`:v.push({type:`tool-call`,toolCallId:e.call_id,toolName:u.toCustomToolName(`local_shell`),input:JSON.stringify({action:e.action}),providerMetadata:{[p]:{itemId:e.id}}});break;case`shell_call`:v.push({type:`tool-call`,toolCallId:e.call_id,toolName:u.toCustomToolName(`shell`),input:JSON.stringify({action:{commands:e.action.commands}}),providerMetadata:{[p]:{itemId:e.id}}});break;case`message`:for(let a of e.content){t.providerOptions?.openai?.logprobs&&a.logprobs&&y.push(a.logprobs);let s={itemId:e.id,...a.annotations.length>0&&{annotations:a.annotations}};v.push({type:`text`,text:a.text,providerMetadata:{[p]:s}});for(let e of a.annotations)e.type===`url_citation`?v.push({type:`source`,sourceType:`url`,id:(n=this.config).generateId?.call(n)??m(),url:e.url,title:e.title}):e.type===`file_citation`?v.push({type:`source`,sourceType:`document`,id:(r=this.config).generateId?.call(r)??m(),mediaType:`text/plain`,title:e.quote??e.filename??`Document`,filename:e.filename??e.file_id,...e.file_id?{providerMetadata:{[p]:{fileId:e.file_id}}}:{}}):e.type===`container_file_citation`?v.push({type:`source`,sourceType:`document`,id:(i=this.config).generateId?.call(i)??m(),mediaType:`text/plain`,title:e.filename??e.file_id??`Document`,filename:e.filename??e.file_id,providerMetadata:{[p]:{fileId:e.file_id,containerId:e.container_id,...e.index==null?{}:{index:e.index}}}}):e.type===`file_path`&&v.push({type:`source`,sourceType:`document`,id:(o=this.config).generateId?.call(o)??m(),mediaType:`application/octet-stream`,title:e.file_id,filename:e.file_id,providerMetadata:{[p]:{fileId:e.file_id,...e.index==null?{}:{index:e.index}}}})}break;case`function_call`:b=!0,v.push({type:`tool-call`,toolCallId:e.call_id,toolName:e.name,input:e.arguments,providerMetadata:{[p]:{itemId:e.id}}});break;case`web_search_call`:v.push({type:`tool-call`,toolCallId:e.id,toolName:u.toCustomToolName(l??`web_search`),input:JSON.stringify({}),providerExecuted:!0}),v.push({type:`tool-result`,toolCallId:e.id,toolName:u.toCustomToolName(l??`web_search`),result:Q(e.action)});break;case`mcp_call`:v.push({type:`tool-call`,toolCallId:e.id,toolName:u.toCustomToolName(`mcp`),input:JSON.stringify({}),providerExecuted:!0}),v.push({type:`tool-result`,toolCallId:e.id,toolName:u.toCustomToolName(`mcp`),result:{type:`call`,serverLabel:e.server_label,name:e.name,arguments:e.arguments,...e.output==null?{}:{output:e.output},...e.error==null?{}:{error:e.error}}});break;case`mcp_list_tools`:v.push({type:`tool-call`,toolCallId:e.id,toolName:u.toCustomToolName(`mcp`),input:JSON.stringify({}),providerExecuted:!0}),v.push({type:`tool-result`,toolCallId:e.id,toolName:u.toCustomToolName(`mcp`),result:{type:`listTools`,serverLabel:e.server_label,tools:e.tools.map(e=>({name:e.name,description:e.description??void 0,inputSchema:e.input_schema,annotations:e.annotations??void 0})),...e.error==null?{}:{error:e.error}}});break;case`mcp_approval_request`:v.push({type:`tool-call`,toolCallId:e.id,toolName:u.toCustomToolName(`mcp`),input:JSON.stringify({}),providerExecuted:!0}),v.push({type:`tool-result`,toolCallId:e.id,toolName:u.toCustomToolName(`mcp`),result:{type:`approvalRequest`,serverLabel:e.server_label,name:e.name,arguments:e.arguments,approvalRequestId:e.approval_request_id}});break;case`computer_call`:v.push({type:`tool-call`,toolCallId:e.id,toolName:u.toCustomToolName(`computer_use`),input:``,providerExecuted:!0}),v.push({type:`tool-result`,toolCallId:e.id,toolName:u.toCustomToolName(`computer_use`),result:{type:`computer_use_tool_result`,status:e.status||`completed`}});break;case`file_search_call`:v.push({type:`tool-call`,toolCallId:e.id,toolName:u.toCustomToolName(`file_search`),input:`{}`,providerExecuted:!0}),v.push({type:`tool-result`,toolCallId:e.id,toolName:u.toCustomToolName(`file_search`),result:{queries:e.queries,results:e.results?.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text}))??null}});break;case`code_interpreter_call`:v.push({type:`tool-call`,toolCallId:e.id,toolName:u.toCustomToolName(`code_interpreter`),input:JSON.stringify({code:e.code,containerId:e.container_id}),providerExecuted:!0}),v.push({type:`tool-result`,toolCallId:e.id,toolName:u.toCustomToolName(`code_interpreter`),result:{outputs:e.outputs}});break;case`apply_patch_call`:v.push({type:`tool-call`,toolCallId:e.call_id,toolName:u.toCustomToolName(`apply_patch`),input:JSON.stringify({callId:e.call_id,operation:e.operation}),providerMetadata:{[p]:{itemId:e.id}}});break}let x={[p]:{responseId:g.id}};y.length>0&&(x[p].logprobs=y),typeof g.service_tier==`string`&&(x[p].serviceTier=g.service_tier);let S=g.usage;return{content:v,finishReason:Y({finishReason:g.incomplete_details?.reason,hasFunctionCall:b}),usage:q(S),request:{body:s},response:{id:g.id,timestamp:new Date(g.created_at*1e3),modelId:g.model,headers:h,body:_},providerMetadata:x,warnings:c}}async doStream(e){let{args:t,warnings:n,webSearchToolName:r,toolNameMapping:i,store:o}=await this.getArgs(e),{responseHeaders:s,value:c}=await C({url:this.config.url({path:`/responses`,modelId:this.modelId}),headers:a(this.config.headers(),e.headers),body:{...t,stream:!0},failedResponseHandler:A,successfulResponseHandler:l(He),abortSignal:e.abortSignal,fetch:this.config.fetch}),u=this,d=this.config.provider.replace(`.responses`,``),f=`unknown`,p,h=[],g=null,_={},v=[],y=!1,b={},x;return{stream:c.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:n})},transform(t,n){var a,s,c,l;if(e.includeRawChunks&&n.enqueue({type:`raw`,rawValue:t.rawValue}),!t.success){f=`error`,n.enqueue({type:`error`,error:t.error});return}let S=t.value;if(Z(S))S.item.type===`function_call`?(_[S.output_index]={toolName:S.item.name,toolCallId:S.item.call_id},n.enqueue({type:`tool-input-start`,id:S.item.call_id,toolName:S.item.name})):S.item.type===`web_search_call`?(_[S.output_index]={toolName:i.toCustomToolName(r??`web_search`),toolCallId:S.item.id},n.enqueue({type:`tool-input-start`,id:S.item.id,toolName:i.toCustomToolName(r??`web_search`),providerExecuted:!0}),n.enqueue({type:`tool-input-end`,id:S.item.id}),n.enqueue({type:`tool-call`,toolCallId:S.item.id,toolName:i.toCustomToolName(r??`web_search`),input:JSON.stringify({}),providerExecuted:!0})):S.item.type===`computer_call`?(_[S.output_index]={toolName:i.toCustomToolName(`computer_use`),toolCallId:S.item.id},n.enqueue({type:`tool-input-start`,id:S.item.id,toolName:i.toCustomToolName(`computer_use`),providerExecuted:!0})):S.item.type===`code_interpreter_call`?(_[S.output_index]={toolName:i.toCustomToolName(`code_interpreter`),toolCallId:S.item.id,codeInterpreter:{containerId:S.item.container_id}},n.enqueue({type:`tool-input-start`,id:S.item.id,toolName:i.toCustomToolName(`code_interpreter`),providerExecuted:!0}),n.enqueue({type:`tool-input-delta`,id:S.item.id,delta:`{"containerId":"${S.item.container_id}","code":"`})):S.item.type===`file_search_call`?n.enqueue({type:`tool-call`,toolCallId:S.item.id,toolName:i.toCustomToolName(`file_search`),input:`{}`,providerExecuted:!0}):S.item.type===`image_generation_call`?n.enqueue({type:`tool-call`,toolCallId:S.item.id,toolName:i.toCustomToolName(`image_generation`),input:`{}`,providerExecuted:!0}):S.item.type===`mcp_call`||S.item.type===`mcp_list_tools`||S.item.type===`mcp_approval_request`?n.enqueue({type:`tool-call`,toolCallId:S.item.id,toolName:i.toCustomToolName(`mcp`),input:`{}`,providerExecuted:!0}):S.item.type===`apply_patch_call`?(_[S.output_index]={toolName:i.toCustomToolName(`apply_patch`),toolCallId:S.item.call_id},S.item.status===`completed`&&n.enqueue({type:`tool-call`,toolCallId:S.item.call_id,toolName:i.toCustomToolName(`apply_patch`),input:JSON.stringify({callId:S.item.call_id,operation:S.item.operation}),providerMetadata:{[d]:{itemId:S.item.id}}})):S.item.type===`shell_call`?_[S.output_index]={toolName:i.toCustomToolName(`shell`),toolCallId:S.item.call_id}:S.item.type===`message`?(v.splice(0,v.length),n.enqueue({type:`text-start`,id:S.item.id,providerMetadata:{[d]:{itemId:S.item.id}}})):Z(S)&&S.item.type===`reasoning`&&(b[S.item.id]={encryptedContent:S.item.encrypted_content,summaryParts:{0:`active`}},n.enqueue({type:`reasoning-start`,id:`${S.item.id}:0`,providerMetadata:{[d]:{itemId:S.item.id,reasoningEncryptedContent:S.item.encrypted_content??null}}}));else if(Je(S)){if(S.item.type===`message`)n.enqueue({type:`text-end`,id:S.item.id,providerMetadata:{[d]:{itemId:S.item.id,...v.length>0&&{annotations:v}}}});else if(S.item.type===`function_call`)_[S.output_index]=void 0,y=!0,n.enqueue({type:`tool-input-end`,id:S.item.call_id}),n.enqueue({type:`tool-call`,toolCallId:S.item.call_id,toolName:S.item.name,input:S.item.arguments,providerMetadata:{[d]:{itemId:S.item.id}}});else if(S.item.type===`web_search_call`)_[S.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:S.item.id,toolName:i.toCustomToolName(r??`web_search`),result:Q(S.item.action)});else if(S.item.type===`computer_call`)_[S.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:S.item.id}),n.enqueue({type:`tool-call`,toolCallId:S.item.id,toolName:i.toCustomToolName(`computer_use`),input:``,providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:S.item.id,toolName:i.toCustomToolName(`computer_use`),result:{type:`computer_use_tool_result`,status:S.item.status||`completed`}});else if(S.item.type===`file_search_call`)_[S.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:S.item.id,toolName:i.toCustomToolName(`file_search`),result:{queries:S.item.queries,results:S.item.results?.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text}))??null}});else if(S.item.type===`code_interpreter_call`)_[S.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:S.item.id,toolName:i.toCustomToolName(`code_interpreter`),result:{outputs:S.item.outputs}});else if(S.item.type===`image_generation_call`)n.enqueue({type:`tool-result`,toolCallId:S.item.id,toolName:i.toCustomToolName(`image_generation`),result:{result:S.item.result}});else if(S.item.type===`mcp_call`)_[S.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:S.item.id,toolName:i.toCustomToolName(`mcp`),result:{type:`call`,serverLabel:S.item.server_label,name:S.item.name,arguments:S.item.arguments,...S.item.output==null?{}:{output:S.item.output},...S.item.error==null?{}:{error:S.item.error}}});else if(S.item.type===`mcp_list_tools`)_[S.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:S.item.id,toolName:i.toCustomToolName(`mcp`),result:{type:`listTools`,serverLabel:S.item.server_label,tools:S.item.tools.map(e=>({name:e.name,description:e.description??void 0,inputSchema:e.input_schema,annotations:e.annotations??void 0})),...S.item.error==null?{}:{error:S.item.error}}});else if(S.item.type===`apply_patch_call`)_[S.output_index]=void 0,S.item.status===`completed`&&n.enqueue({type:`tool-call`,toolCallId:S.item.call_id,toolName:i.toCustomToolName(`apply_patch`),input:JSON.stringify({callId:S.item.call_id,operation:S.item.operation}),providerMetadata:{[d]:{itemId:S.item.id}}});else if(S.item.type===`mcp_approval_request`)_[S.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:S.item.id,toolName:i.toCustomToolName(`mcp`),result:{type:`approvalRequest`,serverLabel:S.item.server_label,name:S.item.name,arguments:S.item.arguments,approvalRequestId:S.item.approval_request_id}});else if(S.item.type===`local_shell_call`)_[S.output_index]=void 0,n.enqueue({type:`tool-call`,toolCallId:S.item.call_id,toolName:i.toCustomToolName(`local_shell`),input:JSON.stringify({action:{type:`exec`,command:S.item.action.command,timeoutMs:S.item.action.timeout_ms,user:S.item.action.user,workingDirectory:S.item.action.working_directory,env:S.item.action.env}}),providerMetadata:{[d]:{itemId:S.item.id}}});else if(S.item.type===`shell_call`)_[S.output_index]=void 0,n.enqueue({type:`tool-call`,toolCallId:S.item.call_id,toolName:i.toCustomToolName(`shell`),input:JSON.stringify({action:{commands:S.item.action.commands}}),providerMetadata:{[d]:{itemId:S.item.id}}});else if(S.item.type===`reasoning`){let e=b[S.item.id],t=Object.entries(e.summaryParts).filter(([e,t])=>t===`active`||t===`can-conclude`).map(([e])=>e);for(let e of t)n.enqueue({type:`reasoning-end`,id:`${S.item.id}:${e}`,providerMetadata:{[d]:{itemId:S.item.id,reasoningEncryptedContent:S.item.encrypted_content??null}}});delete b[S.item.id]}}else if(Ze(S)){let e=_[S.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:S.delta})}else if(Qe(S))n.enqueue({type:`tool-result`,toolCallId:S.item_id,toolName:i.toCustomToolName(`image_generation`),result:{result:S.partial_image_b64},preliminary:!0});else if($e(S)){let e=_[S.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:JSON.stringify(S.delta).slice(1,-1)})}else if(et(S)){let e=_[S.output_index];e!=null&&(n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:`"}`}),n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:i.toCustomToolName(`code_interpreter`),input:JSON.stringify({code:S.code,containerId:e.codeInterpreter.containerId}),providerExecuted:!0}))}else if(Xe(S))g=S.response.id,n.enqueue({type:`response-metadata`,id:S.response.id,timestamp:new Date(S.response.created_at*1e3),modelId:S.response.model});else if(qe(S))n.enqueue({type:`text-delta`,id:S.item_id,delta:S.delta}),e.providerOptions?.openai?.logprobs&&S.logprobs&&h.push(S.logprobs);else if(S.type===`response.reasoning_summary_part.added`){if(S.summary_index>0){let e=b[S.item_id];e.summaryParts[S.summary_index]=`active`;for(let t of Object.keys(e.summaryParts))e.summaryParts[t]===`can-conclude`&&(n.enqueue({type:`reasoning-end`,id:`${S.item_id}:${t}`,providerMetadata:{[d]:{itemId:S.item_id}}}),e.summaryParts[t]=`concluded`);n.enqueue({type:`reasoning-start`,id:`${S.item_id}:${S.summary_index}`,providerMetadata:{[d]:{itemId:S.item_id,reasoningEncryptedContent:b[S.item_id]?.encryptedContent??null}}})}}else S.type===`response.reasoning_summary_text.delta`?n.enqueue({type:`reasoning-delta`,id:`${S.item_id}:${S.summary_index}`,delta:S.delta,providerMetadata:{[d]:{itemId:S.item_id}}}):S.type===`response.reasoning_summary_part.done`?o?(n.enqueue({type:`reasoning-end`,id:`${S.item_id}:${S.summary_index}`,providerMetadata:{[d]:{itemId:S.item_id}}}),b[S.item_id].summaryParts[S.summary_index]=`concluded`):b[S.item_id].summaryParts[S.summary_index]=`can-conclude`:Ye(S)?(f=Y({finishReason:S.response.incomplete_details?.reason,hasFunctionCall:y}),p=S.response.usage,typeof S.response.service_tier==`string`&&(x=S.response.service_tier)):tt(S)?(v.push(S.annotation),S.annotation.type===`url_citation`?n.enqueue({type:`source`,sourceType:`url`,id:(a=u.config).generateId?.call(a)??m(),url:S.annotation.url,title:S.annotation.title}):S.annotation.type===`file_citation`?n.enqueue({type:`source`,sourceType:`document`,id:(s=u.config).generateId?.call(s)??m(),mediaType:`text/plain`,title:S.annotation.quote??S.annotation.filename??`Document`,filename:S.annotation.filename??S.annotation.file_id,...S.annotation.file_id?{providerMetadata:{[d]:{fileId:S.annotation.file_id}}}:{}}):S.annotation.type===`container_file_citation`?n.enqueue({type:`source`,sourceType:`document`,id:(c=u.config).generateId?.call(c)??m(),mediaType:`text/plain`,title:S.annotation.filename??S.annotation.file_id??`Document`,filename:S.annotation.filename??S.annotation.file_id,providerMetadata:{[d]:{fileId:S.annotation.file_id,containerId:S.annotation.container_id,...S.annotation.index==null?{}:{index:S.annotation.index}}}}):S.annotation.type===`file_path`&&n.enqueue({type:`source`,sourceType:`document`,id:(l=u.config).generateId?.call(l)??m(),mediaType:`application/octet-stream`,title:S.annotation.file_id,filename:S.annotation.file_id,providerMetadata:{[d]:{fileId:S.annotation.file_id,...S.annotation.index==null?{}:{index:S.annotation.index}}}})):nt(S)&&n.enqueue({type:`error`,error:S})},flush(e){let t={[d]:{responseId:g}};h.length>0&&(t[d].logprobs=h),x!==void 0&&(t[d].serviceTier=x),e.enqueue({type:`finish`,finishReason:f,usage:q(p),providerMetadata:t})}})),request:{body:t},response:{headers:s}}}};function qe(e){return e.type===`response.output_text.delta`}function Je(e){return e.type===`response.output_item.done`}function Ye(e){return e.type===`response.completed`||e.type===`response.incomplete`}function Xe(e){return e.type===`response.created`}function Ze(e){return e.type===`response.function_call_arguments.delta`}function Qe(e){return e.type===`response.image_generation_call.partial_image`}function $e(e){return e.type===`response.code_interpreter_call_code.delta`}function et(e){return e.type===`response.code_interpreter_call_code.done`}function Z(e){return e.type===`response.output_item.added`}function tt(e){return e.type===`response.output_text.annotation.added`}function nt(e){return e.type===`error`}function Q(e){switch(e.type){case`search`:return{action:{type:`search`,query:e.query??void 0},...e.sources!=null&&{sources:e.sources}};case`open_page`:return{action:{type:`openPage`,url:e.url}};case`find_in_page`:return{action:{type:`findInPage`,url:e.url,pattern:e.pattern}}}}var rt=_(()=>D(O.object({instructions:O.string().nullish(),speed:O.number().min(.25).max(4).default(1).nullish()}))),it=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v3`}get provider(){return this.config.provider}async getArgs({text:e,voice:t=`alloy`,outputFormat:n=`mp3`,speed:r,instructions:i,language:a,providerOptions:o}){let s=[],c=await x({provider:`openai`,providerOptions:o,schema:rt}),l={model:this.modelId,input:e,voice:t,response_format:`mp3`,speed:r,instructions:i};if(n&&([`mp3`,`opus`,`aac`,`flac`,`wav`,`pcm`].includes(n)?l.response_format=n:s.push({type:`unsupported`,feature:`outputFormat`,details:`Unsupported output format: ${n}. Using mp3 instead.`})),c){let e={};for(let t in e){let n=e[t];n!==void 0&&(l[t]=n)}}return a&&s.push({type:`unsupported`,feature:`language`,details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`}),{requestBody:l,warnings:s}}async doGenerate(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{requestBody:r,warnings:i}=await this.getArgs(e),{value:o,responseHeaders:s,rawValue:l}=await C({url:this.config.url({path:`/audio/speech`,modelId:this.modelId}),headers:a(this.config.headers(),e.headers),body:r,failedResponseHandler:A,successfulResponseHandler:c(),abortSignal:e.abortSignal,fetch:this.config.fetch});return{audio:o,warnings:i,request:{body:JSON.stringify(r)},response:{timestamp:n,modelId:this.modelId,headers:s,body:l}}}},at=_(()=>D(O.object({text:O.string(),language:O.string().nullish(),duration:O.number().nullish(),words:O.array(O.object({word:O.string(),start:O.number(),end:O.number()})).nullish(),segments:O.array(O.object({id:O.number(),seek:O.number(),start:O.number(),end:O.number(),text:O.string(),tokens:O.array(O.number()),temperature:O.number(),avg_logprob:O.number(),compression_ratio:O.number(),no_speech_prob:O.number()})).nullish()}))),ot=_(()=>D(O.object({include:O.array(O.string()).optional(),language:O.string().optional(),prompt:O.string().optional(),temperature:O.number().min(0).max(1).default(0).optional(),timestampGranularities:O.array(O.enum([`word`,`segment`])).default([`segment`]).optional()}))),$={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`},st=class{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v3`}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){let r=[],i=await x({provider:`openai`,providerOptions:n,schema:ot}),a=new FormData,s=e instanceof Uint8Array?new Blob([e]):new Blob([o(e)]);a.append(`model`,this.modelId);let c=b(t);if(a.append(`file`,new File([s],`audio`,{type:t}),`audio.${c}`),i){let e={include:i.include,language:i.language,prompt:i.prompt,response_format:[`gpt-4o-transcribe`,`gpt-4o-mini-transcribe`].includes(this.modelId)?`json`:`verbose_json`,temperature:i.temperature,timestamp_granularities:i.timestampGranularities};for(let[t,n]of Object.entries(e))if(n!=null)if(Array.isArray(n))for(let e of n)a.append(`${t}[]`,String(e));else a.append(t,String(n))}return{formData:a,warnings:r}}async doGenerate(e){var t;let n=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{formData:r,warnings:i}=await this.getArgs(e),{value:o,responseHeaders:s,rawValue:c}=await S({url:this.config.url({path:`/audio/transcriptions`,modelId:this.modelId}),headers:a(this.config.headers(),e.headers),formData:r,failedResponseHandler:A,successfulResponseHandler:d(at),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=o.language!=null&&o.language in $?$[o.language]:void 0;return{text:o.text,segments:o.segments?.map(e=>({text:e.text,startSecond:e.start,endSecond:e.end}))??o.words?.map(e=>({text:e.word,startSecond:e.start,endSecond:e.end}))??[],language:l,durationInSeconds:o.duration??void 0,warnings:i,response:{timestamp:n,modelId:this.modelId,headers:s,body:c}}}},ct=`3.0.0-beta.102`;function lt(e={}){let t=E(y({settingValue:e.baseURL,environmentVariableName:`OPENAI_BASE_URL`}))??`https://api.openai.com/v1`,n=e.name??`openai`,r=()=>T({Authorization:`Bearer ${v({apiKey:e.apiKey,environmentVariableName:`OPENAI_API_KEY`,description:`OpenAI`})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${ct}`),i=i=>new ae(i,{provider:`${n}.chat`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),a=i=>new le(i,{provider:`${n}.completion`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),o=i=>new fe(i,{provider:`${n}.embedding`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),s=i=>new ge(i,{provider:`${n}.image`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),c=i=>new st(i,{provider:`${n}.transcription`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),l=i=>new it(i,{provider:`${n}.speech`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),u=e=>{if(new.target)throw Error(`The OpenAI model function cannot be called with the new keyword.`);return d(e)},d=i=>new Ke(i,{provider:`${n}.responses`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch,fileIdPrefixes:[`file-`]}),f=function(e){return u(e)};return f.specificationVersion=`v3`,f.languageModel=u,f.chat=i,f.completion=a,f.responses=d,f.embedding=o,f.embeddingModel=o,f.image=s,f.imageModel=s,f.transcription=c,f.transcriptionModel=c,f.speech=l,f.speechModel=l,f.tools=ze,f}var ut=lt();export{ut as openai};
@@ -0,0 +1,3 @@
1
+ var e=`vercel.ai.error`,t=Symbol.for(e),n,r,i=class i extends (r=Error,n=t,r){constructor({name:e,message:t,cause:r}){super(t),this[n]=!0,this.name=e,this.cause=r}static isInstance(t){return i.hasMarker(t,e)}static hasMarker(e,t){let n=Symbol.for(t);return typeof e==`object`&&!!e&&n in e&&typeof e[n]==`boolean`&&e[n]===!0}},a=`AI_APICallError`,o=`vercel.ai.error.${a}`,s=Symbol.for(o),c,l,u=class extends (l=i,c=s,l){constructor({message:e,url:t,requestBodyValues:n,statusCode:r,responseHeaders:i,responseBody:o,cause:s,isRetryable:l=r!=null&&(r===408||r===409||r===429||r>=500),data:u}){super({name:a,message:e,cause:s}),this[c]=!0,this.url=t,this.requestBodyValues=n,this.statusCode=r,this.responseHeaders=i,this.responseBody=o,this.isRetryable=l,this.data=u}static isInstance(e){return i.hasMarker(e,o)}},d=`AI_EmptyResponseBodyError`,f=`vercel.ai.error.${d}`,ee=Symbol.for(f),p,m,te=class extends (m=i,p=ee,m){constructor({message:e=`Empty response body`}={}){super({name:d,message:e}),this[p]=!0}static isInstance(e){return i.hasMarker(e,f)}};function h(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.message:JSON.stringify(e)}var g=`AI_InvalidArgumentError`,_=`vercel.ai.error.${g}`,ne=Symbol.for(_),v,y,re=class extends (y=i,v=ne,y){constructor({message:e,cause:t,argument:n}){super({name:g,message:e,cause:t}),this[v]=!0,this.argument=n}static isInstance(e){return i.hasMarker(e,_)}},b=`AI_InvalidPromptError`,x=`vercel.ai.error.${b}`,ie=Symbol.for(x),S,C,ae=class extends (C=i,S=ie,C){constructor({prompt:e,message:t,cause:n}){super({name:b,message:`Invalid prompt: ${t}`,cause:n}),this[S]=!0,this.prompt=e}static isInstance(e){return i.hasMarker(e,x)}},w=`AI_InvalidResponseDataError`,T=`vercel.ai.error.${w}`,oe=Symbol.for(T),E,D,se=class extends (D=i,E=oe,D){constructor({data:e,message:t=`Invalid response data: ${JSON.stringify(e)}.`}){super({name:w,message:t}),this[E]=!0,this.data=e}static isInstance(e){return i.hasMarker(e,T)}},O=`AI_JSONParseError`,k=`vercel.ai.error.${O}`,ce=Symbol.for(k),A,j,le=class extends (j=i,A=ce,j){constructor({text:e,cause:t}){super({name:O,message:`JSON parsing failed: Text: ${e}.
2
+ Error message: ${h(t)}`,cause:t}),this[A]=!0,this.text=e}static isInstance(e){return i.hasMarker(e,k)}},M=`AI_LoadAPIKeyError`,N=`vercel.ai.error.${M}`,ue=Symbol.for(N),P,F,de=class extends (F=i,P=ue,F){constructor({message:e}){super({name:M,message:e}),this[P]=!0}static isInstance(e){return i.hasMarker(e,N)}},I=`AI_NoSuchModelError`,L=`vercel.ai.error.${I}`,fe=Symbol.for(L),R,z,B=class extends (z=i,R=fe,z){constructor({errorName:e=I,modelId:t,modelType:n,message:r=`No such ${n}: ${t}`}){super({name:e,message:r}),this[R]=!0,this.modelId=t,this.modelType=n}static isInstance(e){return i.hasMarker(e,L)}},V=`AI_TooManyEmbeddingValuesForCallError`,H=`vercel.ai.error.${V}`,pe=Symbol.for(H),U,W,me=class extends (W=i,U=pe,W){constructor(e){super({name:V,message:`Too many values for a single embedding call. The ${e.provider} model "${e.modelId}" can only embed up to ${e.maxEmbeddingsPerCall} values per call, but ${e.values.length} values were provided.`}),this[U]=!0,this.provider=e.provider,this.modelId=e.modelId,this.maxEmbeddingsPerCall=e.maxEmbeddingsPerCall,this.values=e.values}static isInstance(e){return i.hasMarker(e,H)}},G=`AI_TypeValidationError`,K=`vercel.ai.error.${G}`,he=Symbol.for(K),q,J,ge=class e extends (J=i,q=he,J){constructor({value:e,cause:t}){super({name:G,message:`Type validation failed: Value: ${JSON.stringify(e)}.
3
+ Error message: ${h(t)}`,cause:t}),this[q]=!0,this.value=e}static isInstance(e){return i.hasMarker(e,K)}static wrap({value:t,cause:n}){return e.isInstance(n)&&n.value===t?n:new e({value:t,cause:n})}},Y=`AI_UnsupportedFunctionalityError`,X=`vercel.ai.error.${Y}`,_e=Symbol.for(X),Z,Q,$=class extends (Q=i,Z=_e,Q){constructor({functionality:e,message:t=`'${e}' functionality not supported.`}){super({name:Y,message:t}),this[Z]=!0,this.functionality=e}static isInstance(e){return i.hasMarker(e,X)}};export{u as APICallError,te as EmptyResponseBodyError,re as InvalidArgumentError,ae as InvalidPromptError,se as InvalidResponseDataError,le as JSONParseError,de as LoadAPIKeyError,B as NoSuchModelError,me as TooManyEmbeddingValuesForCallError,ge as TypeValidationError,$ as UnsupportedFunctionalityError};
@@ -0,0 +1,5 @@
1
+ import{APICallError as e,EmptyResponseBodyError as t,InvalidArgumentError as n,JSONParseError as r,LoadAPIKeyError as i,TypeValidationError as a}from"../../provider/dist/index.js";import{EventSourceParserStream as o}from"../../../eventsource-parser/dist/stream.js";import*as s from"zod/v4";import{ZodFirstPartyTypeKind as c}from"zod/v3";function l(...e){return e.reduce((e,t)=>({...e,...t??{}}),{})}function ee({tools:e=[],providerToolNames:t}){let n={},r={};for(let i of e)if(i.type===`provider`&&i.id in t){let e=t[i.id];n[i.name]=e,r[e]=i.name}return{toProviderToolName:e=>n[e]??e,toCustomToolName:e=>r[e]??e}}function u(e){return Object.fromEntries([...e.headers])}var te=(({prefix:e,size:t=16,alphabet:r=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,separator:i=`-`}={})=>{let a=()=>{let e=r.length,n=Array(t);for(let i=0;i<t;i++)n[i]=r[Math.random()*e|0];return n.join(``)};if(e==null)return a;if(r.includes(i))throw new n({argument:`separator`,message:`The separator "${i}" must not be part of the alphabet "${r}".`});return()=>`${e}${i}${a()}`})();function d(e){return(e instanceof Error||e instanceof DOMException)&&(e.name===`AbortError`||e.name===`ResponseAborted`||e.name===`TimeoutError`)}var ne=[`fetch failed`,`failed to fetch`];function re({error:t,url:n,requestBodyValues:r}){if(d(t))return t;if(t instanceof TypeError&&ne.includes(t.message.toLowerCase())){let i=t.cause;if(i!=null)return new e({message:`Cannot connect to API: ${i.message}`,cause:i,url:n,requestBodyValues:r,isRetryable:!0})}return t}function ie(e=globalThis){return e.window?`runtime/browser`:e.navigator?.userAgent?`runtime/${e.navigator.userAgent.toLowerCase()}`:e.process?.versions?.node?`runtime/node.js/${e.process.version.substring(0)}`:e.EdgeRuntime?`runtime/vercel-edge`:`runtime/unknown`}function ae(e){if(e==null)return{};let t={};if(e instanceof Headers)e.forEach((e,n)=>{t[n.toLowerCase()]=e});else{Array.isArray(e)||(e=Object.entries(e));for(let[n,r]of e)r!=null&&(t[n.toLowerCase()]=r)}return t}function f(e,...t){let n=new Headers(ae(e)),r=n.get(`user-agent`)||``;return n.set(`user-agent`,[r,...t].filter(Boolean).join(` `)),Object.fromEntries(n.entries())}var oe=`4.0.0-beta.52`;function p(e){return e!=null}function m({apiKey:e,environmentVariableName:t,apiKeyParameterName:n=`apiKey`,description:r}){if(typeof e==`string`)return e;if(e!=null)throw new i({message:`${r} API key must be a string.`});if(typeof process>`u`)throw new i({message:`${r} API key is missing. Pass it using the '${n}' parameter. Environment variables is not supported in this environment.`});if(e=process.env[t],e==null)throw new i({message:`${r} API key is missing. Pass it using the '${n}' parameter or the ${t} environment variable.`});if(typeof e!=`string`)throw new i({message:`${r} API key must be a string. The value of the ${t} environment variable is not a string.`});return e}function h({settingValue:e,environmentVariableName:t}){if(typeof e==`string`||!(e!=null||typeof process>`u`)&&(e=process.env[t],!(e==null||typeof e!=`string`)))return e}function g(e){let[t,n=``]=e.toLowerCase().split(`/`);return{mpeg:`mp3`,"x-wav":`wav`,opus:`ogg`,mp4:`m4a`,"x-m4a":`m4a`}[n]??n}var _=/"__proto__"\s*:/,v=/"constructor"\s*:/;function y(e){let t=JSON.parse(e);return typeof t!=`object`||!t||_.test(e)===!1&&v.test(e)===!1?t:se(t)}function se(e){let t=[e];for(;t.length;){let e=t;t=[];for(let n of e){if(Object.prototype.hasOwnProperty.call(n,`__proto__`)||Object.prototype.hasOwnProperty.call(n,`constructor`)&&Object.prototype.hasOwnProperty.call(n.constructor,`prototype`))throw SyntaxError(`Object contains forbidden prototype property`);for(let e in n){let r=n[e];r&&typeof r==`object`&&t.push(r)}}}return e}function b(e){let{stackTraceLimit:t}=Error;try{Error.stackTraceLimit=0}catch{return y(e)}try{return y(e)}finally{Error.stackTraceLimit=t}}function x(e){if(e.type===`object`){e.additionalProperties=!1;let t=e.properties;if(t!=null)for(let e in t)t[e]=x(t[e])}return e.type===`array`&&e.items!=null&&(Array.isArray(e.items)?e.items=e.items.map(e=>x(e)):e.items=x(e.items)),e}var ce=Symbol(`Let zodToJsonSchema decide on which parser to use`),S={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,strictUnions:!1,definitions:{},errorMessages:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`},le=e=>typeof e==`string`?{...S,name:e}:{...S,...e};function C(){return{}}function ue(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==c.ZodAny&&(n.items=W(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&(n.minItems=e.minLength.value),e.maxLength&&(n.maxItems=e.maxLength.value),e.exactLength&&(n.minItems=e.exactLength.value,n.maxItems=e.exactLength.value),n}function de(e){let t={type:`integer`,format:`int64`};if(!e.checks)return t;for(let n of e.checks)switch(n.kind){case`min`:n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case`max`:n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case`multipleOf`:t.multipleOf=n.value;break}return t}function fe(){return{type:`boolean`}}function w(e,t){return W(e.type._def,t)}var pe=(e,t)=>W(e.innerType._def,t);function T(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>T(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return E(e)}}var E=e=>{let t={type:`integer`,format:`unix-time`};for(let n of e.checks)switch(n.kind){case`min`:t.minimum=n.value;break;case`max`:t.maximum=n.value;break}return t};function D(e,t){return{...W(e.innerType._def,t),default:e.defaultValue()}}function O(e,t){return t.effectStrategy===`input`?W(e.schema._def,t):C()}function k(e){return{type:`string`,enum:Array.from(e.values)}}var A=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function j(e,t){let n=[W(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),W(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=[];return n.forEach(e=>{if(A(e))r.push(...e.allOf);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}r.push(t)}}),r.length?{allOf:r}:void 0}function M(e){let t=typeof e.value;return t!==`bigint`&&t!==`number`&&t!==`boolean`&&t!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:{type:t===`bigint`?`integer`:t,const:e.value}}var N=void 0,P={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(N===void 0&&(N=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),N),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function F(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:n.minLength=typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value;break;case`max`:n.maxLength=typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value;break;case`email`:switch(t.emailStrategy){case`format:email`:z(n,`email`,r.message,t);break;case`format:idn-email`:z(n,`idn-email`,r.message,t);break;case`pattern:zod`:B(n,P.email,r.message,t);break}break;case`url`:z(n,`uri`,r.message,t);break;case`uuid`:z(n,`uuid`,r.message,t);break;case`regex`:B(n,r.regex,r.message,t);break;case`cuid`:B(n,P.cuid,r.message,t);break;case`cuid2`:B(n,P.cuid2,r.message,t);break;case`startsWith`:B(n,RegExp(`^${I(r.value,t)}`),r.message,t);break;case`endsWith`:B(n,RegExp(`${I(r.value,t)}$`),r.message,t);break;case`datetime`:z(n,`date-time`,r.message,t);break;case`date`:z(n,`date`,r.message,t);break;case`time`:z(n,`time`,r.message,t);break;case`duration`:z(n,`duration`,r.message,t);break;case`length`:n.minLength=typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,n.maxLength=typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value;break;case`includes`:B(n,RegExp(I(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&z(n,`ipv4`,r.message,t),r.version!==`v4`&&z(n,`ipv6`,r.message,t);break;case`base64url`:B(n,P.base64url,r.message,t);break;case`jwt`:B(n,P.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&B(n,P.ipv4Cidr,r.message,t),r.version!==`v4`&&B(n,P.ipv6Cidr,r.message,t);break;case`emoji`:B(n,P.emoji(),r.message,t);break;case`ulid`:B(n,P.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:z(n,`binary`,r.message,t);break;case`contentEncoding:base64`:n.contentEncoding=`base64`;break;case`pattern:zod`:B(n,P.base64,r.message,t);break}break;case`nanoid`:B(n,P.nanoid,r.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:}return n}function I(e,t){return t.patternStrategy===`escape`?R(e):e}var L=new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function R(e){let t=``;for(let n=0;n<e.length;n++)L.has(e[n])||(t+=`\\`),t+=e[n];return t}function z(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format}),delete e.format),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):e.format=t}function B(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern}),delete e.pattern),e.allOf.push({pattern:V(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):e.pattern=V(t,r)}function V(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++){if(a){i+=r[e],a=!1;continue}if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
2
+ ]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
3
+ ]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r
4
+ `:`[${r[e]}\r
5
+ ]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function H(e,t){let n={type:`object`,additionalProperties:W(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(e.keyType?._def.typeName===c.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=F(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===c.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===c.ZodBranded&&e.keyType._def.type._def.typeName===c.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=w(e.keyType._def,t);return{...n,propertyNames:i}}return n}function me(e,t){return t.mapStrategy===`record`?H(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[W(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||C(),W(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||C()],minItems:2,maxItems:2}}}function he(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function ge(){return{not:C()}}function _e(){return{type:`null`}}var U={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function ve(e,t){let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in U&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=U[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];case`symbol`:case`undefined`:case`function`:default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return ye(e,t)}var ye=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>W(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function be(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[U[e.innerType._def.typeName],`null`]};let n=W(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function xe(e){let t={type:`number`};if(!e.checks)return t;for(let n of e.checks)switch(n.kind){case`int`:t.type=`integer`;break;case`min`:n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case`max`:n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case`multipleOf`:t.multipleOf=n.value;break}return t}function Se(e,t){let n={type:`object`,properties:{}},r=[],i=e.shape();for(let e in i){let a=i[e];if(a===void 0||a._def===void 0)continue;let o=we(a),s=W(a._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});s!==void 0&&(n.properties[e]=s,o||r.push(e))}r.length&&(n.required=r);let a=Ce(e,t);return a!==void 0&&(n.additionalProperties=a),n}function Ce(e,t){if(e.catchall._def.typeName!==`ZodNever`)return W(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function we(e){try{return e.isOptional()}catch{return!0}}var Te=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return W(e.innerType._def,t);let n=W(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:C()},n]}:C()},Ee=(e,t)=>{if(t.pipeStrategy===`input`)return W(e.in._def,t);if(t.pipeStrategy===`output`)return W(e.out._def,t);let n=W(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,W(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function De(e,t){return W(e.type._def,t)}function Oe(e,t){let n={type:`array`,uniqueItems:!0,items:W(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}function ke(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>W(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:W(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>W(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function Ae(){return{not:C()}}function je(){return C()}var Me=(e,t)=>W(e.innerType._def,t),Ne=(e,t,n)=>{switch(t){case c.ZodString:return F(e,n);case c.ZodNumber:return xe(e);case c.ZodObject:return Se(e,n);case c.ZodBigInt:return de(e);case c.ZodBoolean:return fe();case c.ZodDate:return T(e,n);case c.ZodUndefined:return Ae();case c.ZodNull:return _e();case c.ZodArray:return ue(e,n);case c.ZodUnion:case c.ZodDiscriminatedUnion:return ve(e,n);case c.ZodIntersection:return j(e,n);case c.ZodTuple:return ke(e,n);case c.ZodRecord:return H(e,n);case c.ZodLiteral:return M(e);case c.ZodEnum:return k(e);case c.ZodNativeEnum:return he(e);case c.ZodNullable:return be(e,n);case c.ZodOptional:return Te(e,n);case c.ZodMap:return me(e,n);case c.ZodSet:return Oe(e,n);case c.ZodLazy:return()=>e.getter()._def;case c.ZodPromise:return De(e,n);case c.ZodNaN:case c.ZodNever:return ge();case c.ZodEffects:return O(e,n);case c.ZodAny:return C();case c.ZodUnknown:return je();case c.ZodDefault:return D(e,n);case c.ZodBranded:return w(e,n);case c.ZodReadonly:return Me(e,n);case c.ZodCatch:return pe(e,n);case c.ZodPipeline:return Ee(e,n);case c.ZodFunction:case c.ZodVoid:case c.ZodSymbol:return;default:return(e=>void 0)(t)}},Pe=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function W(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.call(t,e,t,r,n);if(i!==ce)return i}if(r&&!n){let e=Fe(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=Ne(e,e.typeName,t),o=typeof a==`function`?W(a(),t):a;if(o&&Ie(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var Fe=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:Pe(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),C()):t.$refStrategy===`seen`?C():void 0}},Ie=(e,t,n)=>(e.description&&(n.description=e.description),n),Le=e=>{let t=le(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}},Re=(e,t)=>{let n=Le(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:W(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??C()}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=W(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??C(),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o);let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return s.$schema=`http://json-schema.org/draft-07/schema#`,s},G=Symbol.for(`vercel.ai.schema`);function ze(e){let t;return()=>(t??=e(),t)}function K(e,{validate:t}={}){return{[G]:!0,_type:void 0,get jsonSchema(){return typeof e==`function`&&(e=e()),e},validate:t}}function Be(e){return typeof e==`object`&&!!e&&G in e&&e[G]===!0&&`jsonSchema`in e&&`validate`in e}function Ve(e){return e==null?K({properties:{},additionalProperties:!1}):Be(e)?e:`~standard`in e?e[`~standard`].vendor===`zod`?q(e):He(e):e()}function He(e){return K(()=>e[`~standard`].jsonSchema.input({target:`draft-07`}),{validate:async t=>{let n=await e[`~standard`].validate(t);return`value`in n?{success:!0,value:n.value}:{success:!1,error:new a({value:t,cause:n.issues})}}})}function Ue(e,t){let n=t?.useReferences??!1;return K(()=>Re(e,{$refStrategy:n?`root`:`none`}),{validate:async t=>{let n=await e.safeParseAsync(t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function We(e,t){let n=t?.useReferences??!1;return K(()=>x(s.toJSONSchema(e,{target:`draft-7`,io:`input`,reused:n?`ref`:`inline`})),{validate:async t=>{let n=await s.safeParseAsync(e,t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function Ge(e){return`_zod`in e}function q(e,t){return Ge(e)?We(e,t):Ue(e,t)}async function J({value:e,schema:t}){let n=await Y({value:e,schema:t});if(!n.success)throw a.wrap({value:e,cause:n.error});return n.value}async function Y({value:e,schema:t}){let n=Ve(t);try{if(n.validate==null)return{success:!0,value:e,rawValue:e};let t=await n.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:a.wrap({value:e,cause:t.error}),rawValue:e}}catch(t){return{success:!1,error:a.wrap({value:e,cause:t}),rawValue:e}}}async function Ke({text:e,schema:t}){try{let n=b(e);return t==null?n:J({value:n,schema:t})}catch(t){throw r.isInstance(t)||a.isInstance(t)?t:new r({text:e,cause:t})}}async function X({text:e,schema:t}){try{let n=b(e);return t==null?{success:!0,value:n,rawValue:n}:await Y({value:n,schema:t})}catch(t){return{success:!1,error:r.isInstance(t)?t:new r({text:e,cause:t}),rawValue:void 0}}}function qe(e){try{return b(e),!0}catch{return!1}}function Je({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new o).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await X({text:e,schema:t}))}}))}async function Ye({provider:e,providerOptions:t,schema:r}){if(t?.[e]==null)return;let i=await Y({value:t[e],schema:r});if(!i.success)throw new n({argument:`providerOptions`,message:`invalid ${e} provider options`,cause:i.error});return i.value}var Xe=()=>globalThis.fetch,Z=async({url:e,headers:t,body:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>Q({url:e,headers:{"Content-Type":`application/json`,...t},body:{content:JSON.stringify(n),values:n},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),Ze=async({url:e,headers:t,formData:n,failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o})=>Q({url:e,headers:t,body:{content:n,values:Object.fromEntries(n.entries())},failedResponseHandler:r,successfulResponseHandler:i,abortSignal:a,fetch:o}),Q=async({url:t,headers:n={},body:r,successfulResponseHandler:i,failedResponseHandler:a,abortSignal:o,fetch:s=Xe()})=>{try{let c=await s(t,{method:`POST`,headers:f(n,`ai-sdk/provider-utils/${oe}`,ie()),body:r.content,signal:o}),l=u(c);if(!c.ok){let n;try{n=await a({response:c,url:t,requestBodyValues:r.values})}catch(n){throw d(n)||e.isInstance(n)?n:new e({message:`Failed to process error response`,cause:n,statusCode:c.status,url:t,responseHeaders:l,requestBodyValues:r.values})}throw n.value}try{return await i({response:c,url:t,requestBodyValues:r.values})}catch(n){throw n instanceof Error&&(d(n)||e.isInstance(n))?n:new e({message:`Failed to process successful response`,cause:n,statusCode:c.status,url:t,responseHeaders:l,requestBodyValues:r.values})}}catch(e){throw re({error:e,url:t,requestBodyValues:r.values})}};function $(e){return e}function Qe({id:e,inputSchema:t}){return({execute:n,outputSchema:r,needsApproval:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>$({type:`provider`,id:e,args:l,inputSchema:t,outputSchema:r,execute:n,needsApproval:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}function $e({id:e,inputSchema:t,outputSchema:n}){return({execute:r,needsApproval:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c,...l})=>$({type:`provider`,id:e,args:l,inputSchema:t,outputSchema:n,execute:r,needsApproval:i,toModelOutput:a,onInputStart:o,onInputDelta:s,onInputAvailable:c})}async function et(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}var tt=({errorSchema:t,errorToMessage:n,isRetryable:r})=>async({response:i,url:a,requestBodyValues:o})=>{let s=await i.text(),c=u(i);if(s.trim()===``)return{responseHeaders:c,value:new e({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})};try{let l=await Ke({text:s,schema:t});return{responseHeaders:c,value:new e({message:n(l),url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,data:l,isRetryable:r?.(i,l)})}}catch{return{responseHeaders:c,value:new e({message:i.statusText,url:a,requestBodyValues:o,statusCode:i.status,responseHeaders:c,responseBody:s,isRetryable:r?.(i)})}}},nt=e=>async({response:n})=>{let r=u(n);if(n.body==null)throw new t({});return{responseHeaders:r,value:Je({stream:n.body,schema:e})}},rt=t=>async({response:n,url:r,requestBodyValues:i})=>{let a=await n.text(),o=await X({text:a,schema:t}),s=u(n);if(!o.success)throw new e({message:`Invalid JSON response`,cause:o.error,statusCode:n.status,responseHeaders:s,responseBody:a,url:r,requestBodyValues:i});return{responseHeaders:s,value:o.value,rawValue:o.rawValue}},it=()=>async({response:t,url:n,requestBodyValues:r})=>{let i=u(t);if(!t.body)throw new e({message:`Response body is empty`,url:n,requestBodyValues:r,statusCode:t.status,responseHeaders:i,responseBody:void 0});try{let e=await t.arrayBuffer();return{responseHeaders:i,value:new Uint8Array(e)}}catch(a){throw new e({message:`Failed to read response as array buffer`,url:n,requestBodyValues:r,statusCode:t.status,responseHeaders:i,responseBody:void 0,cause:a})}},{btoa:at,atob:ot}=globalThis;function st(e){let t=ot(e.replace(/-/g,`+`).replace(/_/g,`/`));return Uint8Array.from(t,e=>e.codePointAt(0))}function ct(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCodePoint(e[n]);return at(t)}function lt(e){return e instanceof Uint8Array?ct(e):e}function ut(e){return e?.replace(/\/$/,``)}export{l as combineHeaders,st as convertBase64ToUint8Array,lt as convertToBase64,it as createBinaryResponseHandler,nt as createEventSourceResponseHandler,tt as createJsonErrorResponseHandler,rt as createJsonResponseHandler,Qe as createProviderToolFactory,$e as createProviderToolFactoryWithOutputSchema,ee as createToolNameMapping,te as generateId,p as isNonNullable,qe as isParsableJson,ze as lazySchema,m as loadApiKey,h as loadOptionalSetting,g as mediaTypeToExtension,Ye as parseProviderOptions,Ze as postFormDataToApi,Z as postJsonToApi,et as resolve,J as validateTypes,f as withUserAgentSuffix,ut as withoutTrailingSlash,q as zodSchema};
@@ -0,0 +1,5 @@
1
+ var e=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}};function t(e){}function n(n){if(typeof n==`function`)throw TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:i=t,onError:a=t,onRetry:o=t,onComment:s}=n,c=``,l=!0,u,d=``,f=``;function p(e){let t=l?e.replace(/^\xEF\xBB\xBF/,``):e,[n,i]=r(`${c}${t}`);for(let e of n)m(e);c=i,l=!1}function m(e){if(e===``){g();return}if(e.startsWith(`:`)){s&&s(e.slice(e.startsWith(`: `)?2:1));return}let t=e.indexOf(`:`);if(t!==-1){let n=e.slice(0,t),r=e[t+1]===` `?2:1;h(n,e.slice(t+r),e);return}h(e,``,e)}function h(t,n,r){switch(t){case`event`:f=n;break;case`data`:d=`${d}${n}
2
+ `;break;case`id`:u=n.includes(`\0`)?void 0:n;break;case`retry`:/^\d+$/.test(n)?o(parseInt(n,10)):a(new e(`Invalid \`retry\` value: "${n}"`,{type:`invalid-retry`,value:n,line:r}));break;default:a(new e(`Unknown field "${t.length>20?`${t.slice(0,20)}\u2026`:t}"`,{type:`unknown-field`,field:t,value:n,line:r}));break}}function g(){d.length>0&&i({id:u,event:f||void 0,data:d.endsWith(`
3
+ `)?d.slice(0,-1):d}),u=void 0,d=``,f=``}function _(e={}){c&&e.consume&&m(c),l=!0,u=void 0,d=``,f=``,c=``}return{feed:p,reset:_}}function r(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e.indexOf(`\r`,r),a=e.indexOf(`
4
+ `,r),o=-1;if(i!==-1&&a!==-1?o=Math.min(i,a):i===-1?a!==-1&&(o=a):o=i===e.length-1?-1:i,o===-1){n=e.slice(r);break}else{let n=e.slice(r,o);t.push(n),r=o+1,e[r-1]===`\r`&&e[r]===`
5
+ `&&r++}}return[t,n]}export{e as ParseError,n as createParser};
@@ -0,0 +1 @@
1
+ import{ParseError as e,createParser as t}from"./index.js";var n=class extends TransformStream{constructor({onError:e,onRetry:n,onComment:r}={}){let i;super({start(a){i=t({onEvent:e=>{a.enqueue(e)},onError(t){e===`terminate`?a.error(t):typeof e==`function`&&e(t)},onRetry:n,onComment:r})},transform(e){i.feed(e)}})}};export{n as EventSourceParserStream};
@@ -1 +1 @@
1
- import{validateImplementationFiles as e}from"../validate-implementation.js";import{analyzeDeps as t}from"../deps.js";import{loadWorkspaceConfig as n}from"../config.js";import{analyzeIntegrity as r}from"../integrity.js";import{runDoctor as i}from"../doctor/doctor-service.js";import{isFeatureFile as a,validateSpecStructure as o}from"@lssm/module.contractspec-workspace";async function s(e,t={}){let n=Date.now(),{fs:r,logger:i}=e,o=[],s=[],_=c(t);i.info(`Starting CI checks...`,{checks:_});let v=(await r.glob({pattern:t.pattern})).filter(e=>!a(e)&&!e.includes(`.test.`)&&!e.includes(`.spec.`));if(_.includes(`structure`)){let t=Date.now(),n=await l(e,v);o.push(...n),s.push(h(`structure`,n,Date.now()-t))}if(_.includes(`integrity`)){let n=Date.now(),r=await u(e,t);o.push(...r),s.push(h(`integrity`,r,Date.now()-n))}if(_.includes(`deps`)){let n=Date.now(),r=await d(e,t);o.push(...r),s.push(h(`deps`,r,Date.now()-n))}if(_.includes(`doctor`)){let n=Date.now(),r=await f(e,t);o.push(...r),s.push(h(`doctor`,r,Date.now()-n))}if(_.includes(`handlers`)||t.checkHandlers){let t=Date.now(),n=await p(e,v);o.push(...n),s.push(h(`handlers`,n,Date.now()-t))}if(_.includes(`tests`)||t.checkTests){let t=Date.now(),n=await m(e,v);o.push(...n),s.push(h(`tests`,n,Date.now()-t))}let y=o.filter(e=>e.severity===`error`).length,b=o.filter(e=>e.severity===`warning`).length,x=o.filter(e=>e.severity===`note`).length,S=t.failOnWarnings?y===0&&b===0:y===0,C=await g(r),w={success:S,totalErrors:y,totalWarnings:b,totalNotes:x,issues:o,categories:s,durationMs:Date.now()-n,timestamp:new Date().toISOString(),...C};return i.info(`CI checks complete`,{success:S,errors:y,warnings:b,durationMs:w.durationMs}),w}function c(e){let t=[`structure`,`integrity`,`deps`,`doctor`];return e.checkHandlers&&t.push(`handlers`),e.checkTests&&t.push(`tests`),e.checks&&e.checks.length>0?e.checks:e.skip&&e.skip.length>0?t.filter(t=>!e.skip?.includes(t)):t}async function l(e,t){let{fs:n}=e,r=[];for(let e of t){let t=o(await n.readFile(e),n.basename(e));for(let n of t.errors)r.push({ruleId:`spec-structure-error`,severity:`error`,message:n,category:`structure`,file:e});for(let n of t.warnings)r.push({ruleId:`spec-structure-warning`,severity:`warning`,message:n,category:`structure`,file:e})}return r}async function u(e,t){let n=[],i=await r(e,{pattern:t.pattern,all:!0});for(let e of i.issues)n.push({ruleId:`integrity-${e.type}`,severity:e.severity===`error`?`error`:`warning`,message:e.message,category:`integrity`,file:e.file,context:{specName:e.specName,specType:e.specType,featureKey:e.featureKey,ref:e.ref}});return n}async function d(e,n){let r=[],i=await t(e,{pattern:n.pattern});for(let e of i.cycles)r.push({ruleId:`deps-circular`,severity:`error`,message:`Circular dependency detected: ${e.join(` → `)}`,category:`deps`,context:{cycle:e}});for(let e of i.missing)for(let t of e.missing)r.push({ruleId:`deps-missing`,severity:`error`,message:`Missing dependency: ${e.contract} requires ${t}`,category:`deps`,context:{contract:e.contract,missing:t}});return r}async function f(e,t){let n=[],r=await i(e,{workspaceRoot:t.workspaceRoot??process.cwd(),skipAi:!0,categories:[`cli`,`config`,`deps`,`workspace`]});for(let e of r.checks)e.status===`fail`?n.push({ruleId:`doctor-${e.category}-${e.name.toLowerCase().replace(/\s+/g,`-`)}`,severity:`error`,message:`${e.name}: ${e.message}`,category:`doctor`,context:{details:e.details}}):e.status===`warn`&&n.push({ruleId:`doctor-${e.category}-${e.name.toLowerCase().replace(/\s+/g,`-`)}`,severity:`warning`,message:`${e.name}: ${e.message}`,category:`doctor`,context:{details:e.details}});return n}async function p(t,r){let{fs:i}=t,a=[],o=await n(i);for(let t of r){if(!t.includes(`.contracts.`))continue;let n=await e(t,{fs:i},o,{checkHandlers:!0,outputDir:o.outputDir});for(let e of n.errors)a.push({ruleId:`handler-missing`,severity:`warning`,message:e,category:`handlers`,file:t});for(let e of n.warnings)a.push({ruleId:`handler-warning`,severity:`warning`,message:e,category:`handlers`,file:t})}return a}async function m(t,r){let{fs:i}=t,a=[],o=await n(i);for(let t of r){if(!t.includes(`.contracts.`))continue;let n=await e(t,{fs:i},o,{checkTests:!0,outputDir:o.outputDir});for(let e of n.errors)a.push({ruleId:`test-missing`,severity:`warning`,message:e,category:`tests`,file:t});for(let e of n.warnings)a.push({ruleId:`test-warning`,severity:`warning`,message:e,category:`tests`,file:t})}return a}function h(e,t,n){let r={structure:`Spec Structure Validation`,integrity:`Contract Integrity Analysis`,deps:`Dependency Analysis`,doctor:`Installation Health`,handlers:`Handler Implementation`,tests:`Test Coverage`},i=t.filter(e=>e.severity===`error`).length,a=t.filter(e=>e.severity===`warning`).length,o=t.filter(e=>e.severity===`note`).length;return{category:e,label:r[e],errors:i,warnings:a,notes:o,passed:i===0,durationMs:n}}async function g(e){try{let t=`.git/HEAD`;if(!await e.exists(t))return{};let n=await e.readFile(t),r=n.match(/^ref: (.+)$/m);if(r){let t=r[1]?.replace(`refs/heads/`,``),n=`.git/${r[1]}`;return await e.exists(n)?{commitSha:(await e.readFile(n)).trim(),branch:t}:{branch:t}}return{commitSha:n.trim()}}catch{return{}}}export{s as runCIChecks};
1
+ import{validateImplementationFiles as e}from"../validate-implementation.js";import{analyzeDeps as t}from"../deps.js";import{loadWorkspaceConfig as n}from"../config.js";import{analyzeIntegrity as r}from"../integrity.js";import{runDoctor as i}from"../doctor/doctor-service.js";import{resolveAllImplementations as a}from"../implementation/resolver.js";import"../verification-cache/index.js";import{isFeatureFile as o,validateSpecStructure as s}from"@lssm/module.contractspec-workspace";async function c(e,t={}){let n=Date.now(),{fs:r,logger:i}=e,a=[],s=[],c=l(t);i.info(`Starting CI checks...`,{checks:c});let y=(await r.glob({pattern:t.pattern})).filter(e=>!o(e)&&!e.includes(`.test.`)&&!e.includes(`.spec.`));if(c.includes(`structure`)){let t=Date.now(),n=await u(e,y);a.push(...n),s.push(_(`structure`,n,Date.now()-t))}if(c.includes(`integrity`)){let n=Date.now(),r=await d(e,t);a.push(...r),s.push(_(`integrity`,r,Date.now()-n))}if(c.includes(`deps`)){let n=Date.now(),r=await f(e,t);a.push(...r),s.push(_(`deps`,r,Date.now()-n))}if(c.includes(`doctor`)){let n=Date.now(),r=await p(e,t);a.push(...r),s.push(_(`doctor`,r,Date.now()-n))}if(c.includes(`handlers`)||t.checkHandlers){let t=Date.now(),n=await m(e,y);a.push(...n),s.push(_(`handlers`,n,Date.now()-t))}if(c.includes(`tests`)||t.checkTests){let t=Date.now(),n=await h(e,y);a.push(...n),s.push(_(`tests`,n,Date.now()-t))}if(c.includes(`implementation`)){let n=Date.now(),r=await g(e,y,t);a.push(...r),s.push(_(`implementation`,r,Date.now()-n))}let b=a.filter(e=>e.severity===`error`).length,x=a.filter(e=>e.severity===`warning`).length,S=a.filter(e=>e.severity===`note`).length,C=t.failOnWarnings?b===0&&x===0:b===0,w=await v(r),T={success:C,totalErrors:b,totalWarnings:x,totalNotes:S,issues:a,categories:s,durationMs:Date.now()-n,timestamp:new Date().toISOString(),...w};return i.info(`CI checks complete`,{success:C,errors:b,warnings:x,durationMs:T.durationMs}),T}function l(e){let t=[`structure`,`integrity`,`deps`,`doctor`];return e.checkHandlers&&t.push(`handlers`),e.checkTests&&t.push(`tests`),e.implementation&&t.push(`implementation`),e.checks&&e.checks.length>0?e.checks:e.skip&&e.skip.length>0?t.filter(t=>!e.skip?.includes(t)):t}async function u(e,t){let{fs:n}=e,r=[];for(let e of t){let t=s(await n.readFile(e),n.basename(e));for(let n of t.errors)r.push({ruleId:`spec-structure-error`,severity:`error`,message:n,category:`structure`,file:e});for(let n of t.warnings)r.push({ruleId:`spec-structure-warning`,severity:`warning`,message:n,category:`structure`,file:e})}return r}async function d(e,t){let n=[],i=await r(e,{pattern:t.pattern,all:!0});for(let e of i.issues)n.push({ruleId:`integrity-${e.type}`,severity:e.severity===`error`?`error`:`warning`,message:e.message,category:`integrity`,file:e.file,context:{specName:e.specName,specType:e.specType,featureKey:e.featureKey,ref:e.ref}});return n}async function f(e,n){let r=[],i=await t(e,{pattern:n.pattern});for(let e of i.cycles)r.push({ruleId:`deps-circular`,severity:`error`,message:`Circular dependency detected: ${e.join(` → `)}`,category:`deps`,context:{cycle:e}});for(let e of i.missing)for(let t of e.missing)r.push({ruleId:`deps-missing`,severity:`error`,message:`Missing dependency: ${e.contract} requires ${t}`,category:`deps`,context:{contract:e.contract,missing:t}});return r}async function p(e,t){let n=[],r=await i(e,{workspaceRoot:t.workspaceRoot??process.cwd(),skipAi:!0,categories:[`cli`,`config`,`deps`,`workspace`]});for(let e of r.checks)e.status===`fail`?n.push({ruleId:`doctor-${e.category}-${e.name.toLowerCase().replace(/\s+/g,`-`)}`,severity:`error`,message:`${e.name}: ${e.message}`,category:`doctor`,context:{details:e.details}}):e.status===`warn`&&n.push({ruleId:`doctor-${e.category}-${e.name.toLowerCase().replace(/\s+/g,`-`)}`,severity:`warning`,message:`${e.name}: ${e.message}`,category:`doctor`,context:{details:e.details}});return n}async function m(t,r){let{fs:i}=t,a=[],o=await n(i);for(let t of r){if(!t.includes(`.contracts.`))continue;let n=await e(t,{fs:i},o,{checkHandlers:!0,outputDir:o.outputDir});for(let e of n.errors)a.push({ruleId:`handler-missing`,severity:`warning`,message:e,category:`handlers`,file:t});for(let e of n.warnings)a.push({ruleId:`handler-warning`,severity:`warning`,message:e,category:`handlers`,file:t})}return a}async function h(t,r){let{fs:i}=t,a=[],o=await n(i);for(let t of r){if(!t.includes(`.contracts.`))continue;let n=await e(t,{fs:i},o,{checkTests:!0,outputDir:o.outputDir});for(let e of n.errors)a.push({ruleId:`test-missing`,severity:`warning`,message:e,category:`tests`,file:t});for(let e of n.warnings)a.push({ruleId:`test-warning`,severity:`warning`,message:e,category:`tests`,file:t})}return a}async function g(e,t,r){let{fs:i}=e,o=[],s=await n(i),c=r.implementation??{},l=await a(t.filter(e=>e.includes(`.contracts.`)),{fs:i},s,{computeHashes:c.useCache??!0});for(let e of l){if(c.requireImplemented&&e.status===`missing`?o.push({ruleId:`impl-missing`,severity:`error`,message:`Spec ${e.specName} has no implementation`,category:`implementation`,file:e.specPath,context:{specName:e.specName,specVersion:e.specVersion,status:e.status}}):e.status===`missing`&&o.push({ruleId:`impl-missing`,severity:`warning`,message:`Spec ${e.specName} has no implementation`,category:`implementation`,file:e.specPath,context:{specName:e.specName,specVersion:e.specVersion,status:e.status}}),!c.allowPartial&&e.status===`partial`){let t=e.implementations.filter(e=>!e.exists&&e.type!==`test`).map(e=>e.path);o.push({ruleId:`impl-partial`,severity:`warning`,message:`Spec ${e.specName} has partial implementation: missing ${t.join(`, `)}`,category:`implementation`,file:e.specPath,context:{specName:e.specName,specVersion:e.specVersion,status:e.status,missingFiles:t}})}let t=e.implementations.filter(e=>!e.exists&&e.type===`test`);t.length>0&&o.push({ruleId:`impl-missing-tests`,severity:`note`,message:`Spec ${e.specName} missing test files: ${t.map(e=>e.path).join(`, `)}`,category:`implementation`,file:e.specPath,context:{specName:e.specName,missingTests:t.map(e=>e.path)}})}return o}function _(e,t,n){let r={structure:`Spec Structure Validation`,integrity:`Contract Integrity Analysis`,deps:`Dependency Analysis`,doctor:`Installation Health`,handlers:`Handler Implementation`,tests:`Test Coverage`,implementation:`Implementation Verification`},i=t.filter(e=>e.severity===`error`).length,a=t.filter(e=>e.severity===`warning`).length,o=t.filter(e=>e.severity===`note`).length;return{category:e,label:r[e],errors:i,warnings:a,notes:o,passed:i===0,durationMs:n}}async function v(e){try{let t=`.git/HEAD`;if(!await e.exists(t))return{};let n=await e.readFile(t),r=n.match(/^ref: (.+)$/m);if(r){let t=r[1]?.replace(`refs/heads/`,``),n=`.git/${r[1]}`;return await e.exists(n)?{commitSha:(await e.readFile(n)).trim(),branch:t}:{branch:t}}return{commitSha:n.trim()}}catch{return{}}}export{c as runCIChecks};
@@ -1 +1 @@
1
- const e=[`structure`,`integrity`,`deps`,`doctor`,`handlers`,`tests`],t={structure:`Spec Structure Validation`,integrity:`Contract Integrity Analysis`,deps:`Dependency Analysis`,doctor:`Installation Health`,handlers:`Handler Implementation`,tests:`Test Coverage`};export{e as ALL_CI_CHECK_CATEGORIES,t as CI_CHECK_CATEGORY_LABELS};
1
+ const e=[`structure`,`integrity`,`deps`,`doctor`,`handlers`,`tests`,`implementation`],t={structure:`Spec Structure Validation`,integrity:`Contract Integrity Analysis`,deps:`Dependency Analysis`,doctor:`Installation Health`,handlers:`Handler Implementation`,tests:`Test Coverage`,implementation:`Implementation Verification`};export{e as ALL_CI_CHECK_CATEGORIES,t as CI_CHECK_CATEGORY_LABELS};
@@ -0,0 +1,2 @@
1
+ const e={namedImport:/import\s*\{[^}]*\b(\w+(?:Spec|Contract|Command|Query))\b[^}]*\}\s*from/g,defaultImport:/import\s+(\w+(?:Spec|Contract|Command|Query))\s+from/g,contractHandler:/ContractHandler\s*<\s*typeof\s+(\w+)\s*>/g,typeofSpec:/typeof\s+(\w+(?:Spec|Contract|Command|Query))\b/g,specAssignment:/(?:spec|contract)\s*[:=]\s*(\w+(?:Spec|Contract|Command|Query))\b/gi},t={".handler.ts":`handler`,".handler.tsx":`handler`,".service.ts":`service`,".service.tsx":`service`,".test.ts":`test`,".test.tsx":`test`,".spec.ts":`test`,".spec.tsx":`test`,".component.tsx":`component`,".tsx":`component`,".form.tsx":`form`,".hook.ts":`hook`,".hook.tsx":`hook`};function n(e){let n=e.toLowerCase();for(let[e,r]of Object.entries(t))if(n.endsWith(e))return r;return n.includes(`/handlers/`)?`handler`:n.includes(`/services/`)?`service`:n.includes(`/components/`)?`component`:n.includes(`/forms/`)?`form`:n.includes(`/hooks/`)?`hook`:n.includes(`/__tests__/`)?`test`:`other`}function r(t,r){let i=[],a=new Set,o=(e,t,o)=>{let s=`${e}:${t}`;a.has(s)||(a.add(s),i.push({filePath:r,specName:e,referenceType:t,lineNumber:o,inferredType:n(r)}))},s=e=>t.substring(0,e).split(`
2
+ `).length,c,l=new RegExp(e.contractHandler);for(;(c=l.exec(t))!==null;)o(c[1],`handler`,s(c.index));let u=new RegExp(e.typeofSpec);for(;(c=u.exec(t))!==null;)o(c[1],`typeof`,s(c.index));let d=new RegExp(e.namedImport);for(;(c=d.exec(t))!==null;){let e=c[0].match(/\b(\w+(?:Spec|Contract|Command|Query))\b/g);if(e)for(let t of e)o(t,`import`,s(c.index))}let f=new RegExp(e.defaultImport);for(;(c=f.exec(t))!==null;)o(c[1],`import`,s(c.index));let p=new RegExp(e.specAssignment);for(;(c=p.exec(t))!==null;)o(c[1],`unknown`,s(c.index));return i}const i=[`**/*.ts`,`**/*.tsx`],a=[`**/node_modules/**`,`**/dist/**`,`**/.git/**`,`**/*.d.ts`,`**/*.contracts.ts`,`**/*.spec.ts`,`**/*.feature.ts`,`**/*.event.ts`,`**/*.presentation.ts`];async function o(e,t,n={}){let{fs:o}=t,s=n.includePatterns??i,c=n.excludePatterns??a,l=[];for(let t of s){let n=await o.glob({pattern:t,ignore:c});for(let t of n)try{let n=r(await o.readFile(t),t).filter(t=>t.specName===e);l.push(...n)}catch{}}return l}async function s(e,t={}){let{fs:n}=e,o=t.includePatterns??i,s=t.excludePatterns??a,c=new Map;for(let e of o){let t=await n.glob({pattern:e,ignore:s});for(let e of t)try{let t=r(await n.readFile(e),e);for(let e of t){let t=c.get(e.specName)??[];t.push(e),c.set(e.specName,t)}}catch{}}return c}export{s as discoverAllImplementations,o as discoverImplementationsForSpec,r as extractSpecReferences,n as inferImplementationType};
@@ -0,0 +1 @@
1
+ import{discoverAllImplementations as e,discoverImplementationsForSpec as t,extractSpecReferences as n,inferImplementationType as r}from"./discovery.js";import{getImplementationSummary as i,resolveAllImplementations as a,resolveImplementations as o}from"./resolver.js";
@@ -0,0 +1 @@
1
+ import{discoverImplementationsForSpec as e}from"./discovery.js";import{scanSpecSource as t}from"@lssm/module.contractspec-workspace";import{createHash as n}from"crypto";const r={includeExplicit:!0,includeDiscovered:!0,includeConvention:!0,computeHashes:!0};function i(e){return e.replace(/\./g,`-`).replace(/([a-z])([A-Z])/g,`$1-$2`).toLowerCase()}function a(e){return n(`sha256`).update(e).digest(`hex`)}function o(e,t,n){let r=i(t),a=[];return e===`operation`&&(a.push({path:`${n}/handlers/${r}.handler.ts`,type:`handler`}),a.push({path:`${n}/handlers/${r}.handler.test.ts`,type:`test`})),e===`presentation`&&(a.push({path:`${n}/components/${r}.tsx`,type:`component`}),a.push({path:`${n}/components/${r}.test.tsx`,type:`test`})),e===`form`&&(a.push({path:`${n}/forms/${r}.form.tsx`,type:`form`}),a.push({path:`${n}/forms/${r}.form.test.tsx`,type:`test`})),e===`event`&&(a.push({path:`${n}/handlers/${r}.handler.ts`,type:`handler`}),a.push({path:`${n}/handlers/${r}.handler.test.ts`,type:`test`})),a}function s(e){if(e.length===0)return`missing`;let t=e.filter(e=>e.exists);return e.filter(e=>e.type!==`test`),t.filter(e=>e.type!==`test`).length===0?`missing`:e.every(e=>e.exists)?`implemented`:`partial`}async function c(n,i,c,d={}){let f={...r,...d},{fs:p}=i;if(!await p.exists(n))throw Error(`Spec file not found: ${n}`);let m=await p.readFile(n),h=f.computeHashes?a(m):void 0,g=t(m,n),_=g.name??p.basename(n).replace(/\.[jt]s$/,``),v=g.version??1,y=g.specType??`operation`,b=[],x=new Set,S=async(e,t,n,r)=>{if(x.has(e))return;x.add(e);let i=await p.exists(e),o;if(i&&f.computeHashes)try{o=a(await p.readFile(e))}catch{}b.push({path:e,type:t,source:n,exists:i,contentHash:o,description:r})};if(f.includeExplicit){let e=l(m);for(let t of e)await S(t.path,t.type,`explicit`,t.description)}if(f.includeDiscovered){let t=await e(_,i,f),r=u(_);for(let n of r){let r=await e(n,i,f);t.push(...r)}for(let e of t)e.filePath!==n&&await S(e.filePath,e.inferredType,`discovered`)}if(f.includeConvention){let e=o(y,_,f.outputDir??c.outputDir??`./src`);for(let{path:t,type:n}of e)await S(t,n,`convention`)}return{specName:_,specVersion:v,specPath:n,specType:y,implementations:b,status:s(b),specHash:h}}function l(e){let t=[],n=e.match(/implementations\s*:\s*\[([\s\S]*?)\]/);if(!n)return t;let r=n[1];if(!r)return t;let i=/\{\s*path\s*:\s*['"`]([^'"`]+)['"`]\s*,\s*type\s*:\s*['"`]([^'"`]+)['"`](?:\s*,\s*description\s*:\s*['"`]([^'"`]+)['"`])?\s*\}/g,a;for(;(a=i.exec(r))!==null;)t.push({path:a[1],type:a[2],description:a[3]});return t}function u(e){let t=[],n=e.replace(/Spec$/,``).replace(/Contract$/,``).replace(/Command$/,``).replace(/Query$/,``);n!==e&&(t.push(n),t.push(`${n}Spec`),t.push(`${n}Contract`));let r=e.split(`.`);if(r.length>1){let e=r.map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join(``);t.push(e)}return t}async function d(e,t,n,r={}){let i=[];for(let a of e)try{let e=await c(a,t,n,r);i.push(e)}catch(e){console.error(`Failed to resolve implementations for ${a}:`,e)}return i}function f(e){let t=e.filter(e=>e.status===`implemented`).length,n=e.filter(e=>e.status===`partial`).length,r=e.filter(e=>e.status===`missing`).length;return{total:e.length,implemented:t,partial:n,missing:r,coverage:e.length>0?Math.round(t/e.length*100):100}}export{f as getImplementationSummary,d as resolveAllImplementations,c as resolveImplementations};
@@ -1 +1 @@
1
- import{detectPackageManager as e,findPackageRoot as t,findWorkspaceRoot as n,getWorkspaceInfo as r}from"../adapters/workspace.js";import{validateSpec as i,validateSpecs as a}from"./validate.js";import{validateImplementationFiles as o}from"./validate-implementation.js";import{compareSpecs as s}from"./diff.js";import{analyzeDeps as c,exportGraphAsDot as l,getContractNode as u,getGraphStats as d}from"./deps.js";import{groupSpecsByType as f,listSpecs as p}from"./list.js";import{getApiKey as m,loadWorkspaceConfig as h,mergeWorkspaceConfig as g}from"./config.js";import{buildSpec as _}from"./build.js";import{exportOpenApi as v}from"./openapi.js";import{RegistryClient as y,addToRegistry as b,listFromRegistry as x,resolveRegistryUrl as S,searchRegistry as C}from"./registry.js";import{syncSpecs as w}from"./sync.js";import{watchSpecs as T}from"./watch.js";import{cleanArtifacts as E}from"./clean.js";import{runTests as D}from"./test.js";import{createRegeneratorService as O}from"./regenerator.js";import{findAllConfigFiles as k,formatWorkspaceInfo as A,getExtendedWorkspaceInfo as j,mergeMonorepoConfigs as M}from"./workspace-info.js";import{analyzeIntegrity as N,filterIssuesBySeverity as P,filterIssuesByType as F,getAllSpecs as I}from"./integrity.js";import{generateMermaidDiagram as L}from"./integrity-diagram.js";import{ALL_SETUP_TARGETS as R,SETUP_TARGET_LABELS as z}from"./setup/types.js";import{generateAgentsMd as B,generateClaudeMcpConfig as V,generateContractsrcConfig as H,generateCursorMcpConfig as U,generateCursorRules as W,generateVscodeSettings as G,getClaudeDesktopConfigPath as K}from"./setup/config-generators.js";import{deepMergeOverwrite as q,deepMergePreserve as J,formatJson as Y,safeParseJson as X}from"./setup/file-merger.js";import{runSetup as Z}from"./setup/setup-service.js";import"./setup/index.js";import{ALL_CHECK_CATEGORIES as Q,CHECK_CATEGORY_LABELS as $}from"./doctor/types.js";import{formatCheckResult as ee,formatDoctorSummary as te,runDoctor as ne}from"./doctor/doctor-service.js";import"./doctor/index.js";import{ALL_CI_CHECK_CATEGORIES as re,CI_CHECK_CATEGORY_LABELS as ie}from"./ci-check/types.js";import{runCIChecks as ae}from"./ci-check/ci-check-service.js";import"./ci-check/index.js";import{ClaudeCodeAdapter as oe,claudeCodeAdapter as se}from"./agent-guide/adapters/claude-code.js";import{CursorCLIAdapter as ce,cursorCLIAdapter as le}from"./agent-guide/adapters/cursor-cli.js";import{GenericMCPAdapter as ue,genericMCPAdapter as de}from"./agent-guide/adapters/generic-mcp.js";import{agentAdapters as fe,getAgentAdapter as pe,listAgentTypes as me}from"./agent-guide/adapters/index.js";import{AgentGuideService as he,agentGuideService as ge,createAgentGuideService as _e}from"./agent-guide/agent-guide-service.js";import"./agent-guide/index.js";import{verifyStructure as ve}from"./verify/structure-verifier.js";import{verifyBehavior as ye}from"./verify/behavior-verifier.js";import{createQuickAIReview as be,verifyWithAI as xe}from"./verify/ai-verifier.js";import{VerifyService as Se,createVerifyService as Ce,verifyService as we}from"./verify/verify-service.js";import"./verify/index.js";
1
+ import{detectPackageManager as e,findPackageRoot as t,findWorkspaceRoot as n,getWorkspaceInfo as r}from"../adapters/workspace.js";import{validateSpec as i,validateSpecs as a}from"./validate.js";import{validateImplementationFiles as o}from"./validate-implementation.js";import{compareSpecs as s}from"./diff.js";import{analyzeDeps as c,exportGraphAsDot as l,getContractNode as u,getGraphStats as d}from"./deps.js";import{groupSpecsByType as f,listSpecs as p}from"./list.js";import{getApiKey as m,loadWorkspaceConfig as h,mergeWorkspaceConfig as g}from"./config.js";import{buildSpec as _}from"./build.js";import{importFromOpenApiService as v}from"./openapi/import-service.js";import{syncWithOpenApiService as y}from"./openapi/sync-service.js";import{validateAgainstOpenApiService as b}from"./openapi/validate-service.js";import{exportOpenApi as x}from"./openapi/export-service.js";import"./openapi/index.js";import{RegistryClient as S,addToRegistry as C,listFromRegistry as w,resolveRegistryUrl as T,searchRegistry as E}from"./registry.js";import{syncSpecs as D}from"./sync.js";import{watchSpecs as O}from"./watch.js";import{cleanArtifacts as k}from"./clean.js";import{runTests as A}from"./test.js";import{createRegeneratorService as j}from"./regenerator.js";import{findAllConfigFiles as M,formatWorkspaceInfo as N,getExtendedWorkspaceInfo as P,mergeMonorepoConfigs as F}from"./workspace-info.js";import{analyzeIntegrity as I,filterIssuesBySeverity as L,filterIssuesByType as R,getAllSpecs as z}from"./integrity.js";import{generateMermaidDiagram as B}from"./integrity-diagram.js";import{ALL_SETUP_TARGETS as V,SETUP_TARGET_LABELS as H}from"./setup/types.js";import{generateAgentsMd as U,generateClaudeMcpConfig as W,generateContractsrcConfig as G,generateCursorMcpConfig as K,generateCursorRules as q,generateVscodeSettings as J,getClaudeDesktopConfigPath as Y}from"./setup/config-generators.js";import{deepMergeOverwrite as X,deepMergePreserve as Z,formatJson as Q,safeParseJson as $}from"./setup/file-merger.js";import{runSetup as ee}from"./setup/setup-service.js";import"./setup/index.js";import{ALL_CHECK_CATEGORIES as te,CHECK_CATEGORY_LABELS as ne}from"./doctor/types.js";import{formatCheckResult as re,formatDoctorSummary as ie,runDoctor as ae}from"./doctor/doctor-service.js";import"./doctor/index.js";import{ALL_CI_CHECK_CATEGORIES as oe,CI_CHECK_CATEGORY_LABELS as se}from"./ci-check/types.js";import{discoverAllImplementations as ce,discoverImplementationsForSpec as le,extractSpecReferences as ue,inferImplementationType as de}from"./implementation/discovery.js";import{getImplementationSummary as fe,resolveAllImplementations as pe,resolveImplementations as me}from"./implementation/resolver.js";import{DEFAULT_CACHE_CONFIG as he}from"./verification-cache/types.js";import{VerificationCacheService as ge,cacheKeyToString as _e,computeContentHash as ve,createVerificationCacheService as ye,stringToCacheKey as be}from"./verification-cache/cache-service.js";import{InMemoryCacheStorage as xe,createInMemoryCacheStorage as Se}from"./verification-cache/adapters/in-memory.js";import{FileSystemCacheStorage as Ce,createFileSystemCacheStorage as we}from"./verification-cache/adapters/filesystem.js";import{WorkspaceStateCacheStorage as Te,createWorkspaceStateCacheStorage as Ee}from"./verification-cache/adapters/workspace-state.js";import"./verification-cache/index.js";import{runCIChecks as De}from"./ci-check/ci-check-service.js";import"./ci-check/index.js";import{ClaudeCodeAdapter as Oe,claudeCodeAdapter as ke}from"./agent-guide/adapters/claude-code.js";import{CursorCLIAdapter as Ae,cursorCLIAdapter as je}from"./agent-guide/adapters/cursor-cli.js";import{GenericMCPAdapter as Me,genericMCPAdapter as Ne}from"./agent-guide/adapters/generic-mcp.js";import{agentAdapters as Pe,getAgentAdapter as Fe,listAgentTypes as Ie}from"./agent-guide/adapters/index.js";import{AgentGuideService as Le,agentGuideService as Re,createAgentGuideService as ze}from"./agent-guide/agent-guide-service.js";import"./agent-guide/index.js";import{verifyStructure as Be}from"./verify/structure-verifier.js";import{verifyBehavior as Ve}from"./verify/behavior-verifier.js";import{createQuickAIReview as He,verifySemanticFields as Ue,verifyWithAI as We,verifyWithAIEnhanced as Ge}from"./verify/ai-verifier.js";import{VerifyService as Ke,createVerifyService as qe,verifyService as Je}from"./verify/verify-service.js";import"./verify/index.js";import"./implementation/index.js";
@@ -0,0 +1 @@
1
+ import{importFromOpenApi as e,parseOpenApi as t}from"@lssm/lib.contracts-transformers/openapi";import{dirname as n,join as r}from"path";async function i(i,a){let{fs:o,logger:s}=a,{source:c,outputDir:l,prefix:u,tags:d,exclude:f,defaultStability:p,defaultOwners:m,defaultAuth:h,dryRun:g=!1}=i;s.info(`Importing from OpenAPI: ${c}`);let _=await t(c,{fetch:globalThis.fetch,readFile:e=>o.readFile(e)});if(_.warnings.length>0)for(let e of _.warnings)s.warn(`Parse warning: ${e}`);s.info(`Parsed ${_.operations.length} operations from ${_.info.title} v${_.info.version}`);let v=e(_,{prefix:u,tags:d,exclude:f,defaultStability:p,defaultOwners:m,defaultAuth:h});s.info(`Import result: ${v.summary.imported} imported, ${v.summary.skipped} skipped, ${v.summary.errors} errors`);let y=[],b=[],x=[];for(let e of v.specs){let t=r(l,e.fileName);if(g)s.info(`[DRY RUN] Would create: ${t}`);else{let r=n(t);await o.mkdir(r),await o.writeFile(t,e.code),s.info(`Created: ${t}`)}y.push({path:t,operationId:e.source.sourceId,specName:e.fileName.replace(`.ts`,``)})}for(let e of v.skipped)b.push({operationId:e.sourceId,reason:e.reason}),s.debug(`Skipped: ${e.sourceId} - ${e.reason}`);for(let e of v.errors)x.push({operationId:e.sourceId,error:e.error}),s.error(`Error: ${e.sourceId} - ${e.error}`);return{imported:v.summary.imported,skipped:v.summary.skipped,errors:v.summary.errors,files:y,skippedOperations:b,errorMessages:x}}export{i as importFromOpenApiService};
@@ -0,0 +1 @@
1
+ import{importFromOpenApiService as e}from"./import-service.js";import{syncWithOpenApiService as t}from"./sync-service.js";import{validateAgainstOpenApiService as n}from"./validate-service.js";import{exportOpenApi as r}from"./export-service.js";
@@ -0,0 +1 @@
1
+ import{importFromOpenApi as e,parseOpenApi as t}from"@lssm/lib.contracts-transformers/openapi";import{dirname as n,join as r}from"path";async function i(i,a,o){let{fs:s,logger:c}=o,{sources:l,sourceName:u,interactive:d,force:f,dryRun:p}=i,{sources:m,outputDir:h}=a,g=l??m??[];if(u&&(g=g.filter(e=>e.name===u),g.length===0))throw Error(`Source not found: ${u}`);if(g.length===0)return c.warn(`No OpenAPI sources configured. Add sources to .contractsrc.json`),{added:0,updated:0,unchanged:0,conflicts:0,changes:[]};let _={added:0,updated:0,unchanged:0,conflicts:0,changes:[]};for(let i of g){c.info(`Syncing with source: ${i.name}`);let a=i.url??i.file;if(!a){c.warn(`Source ${i.name} has no url or file configured`);continue}let o=await t(a,{fetch:globalThis.fetch,readFile:e=>s.readFile(e)});c.info(`Parsed ${o.operations.length} operations from ${i.name}`);let l=e(o,{prefix:i.prefix,tags:i.tags,exclude:i.exclude,defaultStability:i.defaultStability,defaultAuth:i.defaultAuth});for(let e of l.specs){let t=r(h,e.fileName);if(await s.exists(t))await s.readFile(t)===e.code?(_.unchanged++,_.changes.push({operationId:e.source.sourceId,action:`unchanged`,path:t})):f===`openapi`?(p||await s.writeFile(t,e.code),_.updated++,_.changes.push({operationId:e.source.sourceId,action:`updated`,path:t}),c.info(`Updated: ${e.source.sourceId}`)):f===`contractspec`?(_.unchanged++,_.changes.push({operationId:e.source.sourceId,action:`unchanged`,path:t}),c.info(`Kept: ${e.source.sourceId}`)):d?(_.conflicts++,_.changes.push({operationId:e.source.sourceId,action:`conflict`,path:t}),c.warn(`Conflict: ${e.source.sourceId} - needs resolution`)):(_.conflicts++,_.changes.push({operationId:e.source.sourceId,action:`conflict`,path:t}),c.warn(`Conflict: ${e.source.sourceId}`));else{if(!p){let r=n(t);await s.mkdir(r),await s.writeFile(t,e.code)}_.added++,_.changes.push({operationId:e.source.sourceId,action:`added`,path:t}),c.info(`Added: ${e.source.sourceId}`)}}}return c.info(`Sync complete: ${_.added} added, ${_.updated} updated, ${_.unchanged} unchanged, ${_.conflicts} conflicts`),_}export{i as syncWithOpenApiService};
@@ -0,0 +1 @@
1
+ import{parseOpenApi as e}from"@lssm/lib.contracts-transformers/openapi";async function t(t,n){let{fs:r,logger:i}=n,{specPath:a,openApiSource:o,ignoreDescriptions:s,ignoreTags:c,ignoreTransport:l}=t;i.info(`Validating specs against OpenAPI: ${o}`);let u=await e(o,{fetch:globalThis.fetch,readFile:e=>r.readFile(e)});i.info(`Parsed ${u.operations.length} operations from ${u.info.title}`);let d=new Map;for(let e of u.operations)d.set(e.operationId,e);let f=[],p=0,m=0,h=await r.stat(a),g=[];if(h.isDirectory){let e=await r.glob({pattern:`**/*.ts`,cwd:a,ignore:[`node_modules/**`,`dist/**`,`*.test.ts`,`*.spec.ts`],absolute:!0});g.push(...e)}else g.push(a);i.info(`Found ${g.length} spec files to validate`);for(let e of g)try{let t=await r.readFile(e),n=t.match(/operationId:\s*['"]([^'"]+)['"]/)||t.match(/name:\s*['"]([^'"]+)['"]/)||t.match(/export\s+const\s+(\w+)Spec\s*=/);if(!n||!n[1]){i.debug(`Could not extract operationId from ${e}`);continue}let a=n[1];p++;let o;if(o=d.get(a),!o){let e=a.replace(/([A-Z])/g,`_$1`).toLowerCase();o=d.get(e)}if(!o){for(let[e,t]of d)if(e.toLowerCase().includes(a.toLowerCase())||a.toLowerCase().includes(e.toLowerCase())){o=t;break}}if(!o){f.push({specPath:e,valid:!1,diffs:[{path:``,type:`removed`,description:`No matching operation found in OpenAPI for spec: ${a}`}]}),m++;continue}let s=[];if(o.deprecated&&!t.includes(`deprecated`)&&s.push({path:`meta.stability`,type:`modified`,description:`OpenAPI operation is deprecated but spec does not indicate deprecation`}),!l){let e=t.match(/path:\s*['"]([^'"]+)['"]/);e&&e[1]!==o.path&&s.push({path:`transport.rest.path`,type:`modified`,description:`Path mismatch: spec has "${e[1]}", OpenAPI has "${o.path}"`})}if(!l){let e=t.match(/method:\s*['"]([^'"]+)['"]/);e?.[1]&&e[1].toLowerCase()!==o.method.toLowerCase()&&s.push({path:`transport.rest.method`,type:`modified`,description:`Method mismatch: spec has "${e[1]}", OpenAPI has "${o.method.toUpperCase()}"`})}let c=s.length===0;c||m++,f.push({specPath:e,operationId:o.operationId,valid:c,diffs:s})}catch(t){i.error(`Error validating ${e}: ${t}`),f.push({specPath:e,valid:!1,diffs:[{path:``,type:`modified`,description:`Error: ${t instanceof Error?t.message:String(t)}`}]}),m++}let _=m===0;return i.info(`Validation ${_?`passed`:`failed`}: ${p} specs checked, ${m} with differences`),{valid:_,specsValidated:p,specsWithDiffs:m,results:f}}export{t as validateAgainstOpenApiService};
@@ -0,0 +1 @@
1
+ import{__require as e}from"../../../_virtual/rolldown_runtime.js";import{dirname as t,join as n}from"path";import{existsSync as r,mkdirSync as i,readFileSync as a,statSync as o,writeFileSync as s}from"fs";var c=class{filePath;cache;isDirty=!1;constructor(e,t){let r=t??process.cwd();this.filePath=e??n(r,`.contractspec/verification-cache.json`),this.cache=new Map,this.loadSync()}loadSync(){try{if(!r(this.filePath))return;let e=a(this.filePath,`utf-8`),t=JSON.parse(e);if(t.version!==1)return;for(let[e,n]of Object.entries(t.entries))this.cache.set(e,n)}catch{}}saveSync(){if(this.isDirty)try{let n=t(this.filePath);r(n)||i(n,{recursive:!0});let a={version:1,entries:Object.fromEntries(this.cache.entries())},o=`${this.filePath}.tmp`;s(o,JSON.stringify(a,null,2),`utf-8`);let{renameSync:c}=e(`fs`);c(o,this.filePath),this.isDirty=!1}catch{}}async get(e){return this.cache.get(e)??null}async set(e,t){this.cache.set(e,t),this.isDirty=!0,this.saveSync()}async delete(e){let t=this.cache.delete(e);return t&&(this.isDirty=!0,this.saveSync()),t}async has(e){return this.cache.has(e)}async keys(){return Array.from(this.cache.keys())}async clear(){this.cache.clear(),this.isDirty=!0,this.saveSync()}async stats(){let e=0;try{r(this.filePath)&&(e=o(this.filePath).size)}catch{}return{entryCount:this.cache.size,memoryUsage:e}}flush(){this.saveSync()}reload(){this.cache.clear(),this.loadSync(),this.isDirty=!1}};function l(e,t){return new c(e,t)}export{c as FileSystemCacheStorage,l as createFileSystemCacheStorage};
@@ -0,0 +1 @@
1
+ var e=class{cache=new Map;async get(e){return this.cache.get(e)??null}async set(e,t){this.cache.set(e,t)}async delete(e){return this.cache.delete(e)}async has(e){return this.cache.has(e)}async keys(){return Array.from(this.cache.keys())}async clear(){this.cache.clear()}async stats(){let e=0;for(let[t,n]of this.cache.entries())e+=t.length*2,e+=JSON.stringify(n).length*2;return{entryCount:this.cache.size,memoryUsage:e}}};function t(){return new e}export{e as InMemoryCacheStorage,t as createInMemoryCacheStorage};
@@ -0,0 +1 @@
1
+ import{InMemoryCacheStorage as e,createInMemoryCacheStorage as t}from"./in-memory.js";import{FileSystemCacheStorage as n,createFileSystemCacheStorage as r}from"./filesystem.js";import{WorkspaceStateCacheStorage as i,createWorkspaceStateCacheStorage as a}from"./workspace-state.js";
@@ -0,0 +1 @@
1
+ const e=`contractspec.verification-cache.`,t=`${e}__index__`;var n=class{store;keyIndex;constructor(e){this.store=e,this.keyIndex=new Set(this.loadKeyIndex())}loadKeyIndex(){try{return this.store.get(t)??[]}catch{return[]}}async saveKeyIndex(){await this.store.update(t,Array.from(this.keyIndex))}getStorageKey(t){return`${e}${t}`}async get(e){let t=this.getStorageKey(e);return this.store.get(t)??null}async set(e,t){let n=this.getStorageKey(e);await this.store.update(n,t),this.keyIndex.has(e)||(this.keyIndex.add(e),await this.saveKeyIndex())}async delete(e){let t=this.getStorageKey(e),n=this.keyIndex.has(e);return n&&(await this.store.update(t,void 0),this.keyIndex.delete(e),await this.saveKeyIndex()),n}async has(e){return this.keyIndex.has(e)}async keys(){return Array.from(this.keyIndex)}async clear(){for(let e of this.keyIndex){let t=this.getStorageKey(e);await this.store.update(t,void 0)}this.keyIndex.clear(),await this.saveKeyIndex()}async stats(){return{entryCount:this.keyIndex.size}}};function r(e){return new n(e)}export{n as WorkspaceStateCacheStorage,r as createWorkspaceStateCacheStorage};
@@ -0,0 +1 @@
1
+ import{DEFAULT_CACHE_CONFIG as e}from"./types.js";import{createHash as t}from"crypto";function n(e){return t(`sha256`).update(e).digest(`hex`)}function r(e){let t=[`spec:${e.specHash.substring(0,16)}`,`impl:${e.implHash.substring(0,16)}`,`tier:${e.tier}`];return e.aiModelVersion&&t.push(`model:${e.aiModelVersion}`),t.join(`|`)}function i(e){try{let t=e.split(`|`),n=new Map;for(let e of t){let[t,r]=e.split(`:`);t&&r&&n.set(t,r)}let r=n.get(`spec`),i=n.get(`impl`),a=n.get(`tier`);return!r||!i||!a?null:{specHash:r,implHash:i,tier:a,aiModelVersion:n.get(`model`)}}catch{return null}}function a(e,t){switch(e){case`structure`:return t.structureTtlMs;case`behavior`:return t.behaviorTtlMs;case`ai_review`:return t.aiTtlMs;default:return t.defaultTtlMs}}var o=class{storage;config;stats;constructor(t,n={}){this.storage=t,this.config={...e,...n},this.stats={hits:0,misses:0}}createKey(e,t,r,i){return{specHash:n(e),implHash:n(t),tier:r,aiModelVersion:r===`ai_review`?i:void 0}}async lookup(e){let t=r(e),n=await this.storage.get(t);if(!n)return this.stats.misses++,{hit:!1,reason:`not_found`};if(n.meta.expiresAt){let e=new Date(n.meta.expiresAt).getTime();if(Date.now()>e)return this.stats.misses++,await this.storage.delete(t),{hit:!1,reason:`expired`}}return n.key.specHash===e.specHash?n.key.implHash===e.implHash?e.tier===`ai_review`&&e.aiModelVersion&&n.key.aiModelVersion!==e.aiModelVersion?(this.stats.misses++,{hit:!1,reason:`model_changed`}):(this.stats.hits++,{hit:!0,entry:n}):(this.stats.misses++,{hit:!1,reason:`impl_changed`}):(this.stats.misses++,{hit:!1,reason:`spec_changed`})}async store(e,t,n={}){let i=r(e),o=a(e.tier,this.config),s={key:e,result:t,meta:{createdAt:new Date().toISOString(),expiresAt:new Date(Date.now()+o).toISOString(),dependencies:n.dependencies??[],specName:n.specName,implPath:n.implPath}};await this.storage.set(i,s),await this.pruneIfNeeded()}async invalidateForFile(e){if(!this.config.transitiveInvalidation)return 0;let t=await this.storage.keys(),n=0;for(let r of t){let t=await this.storage.get(r);t&&(t.meta.dependencies.includes(e)&&(await this.storage.delete(r),n++),(t.meta.specName===e||t.meta.implPath===e)&&(await this.storage.delete(r),n++))}return n}async invalidateForSpec(e){let t=await this.storage.keys(),n=0;for(let r of t){let t=i(r);t&&t.specHash.startsWith(e.substring(0,16))&&(await this.storage.delete(r),n++)}return n}async clear(){await this.storage.clear(),this.stats={hits:0,misses:0}}async getStats(){let e=await this.storage.stats?.();return{totalEntries:e?.entryCount??(await this.storage.keys()).length,hits:this.stats.hits,misses:this.stats.misses,hitRate:this.stats.hits+this.stats.misses>0?Math.round(this.stats.hits/(this.stats.hits+this.stats.misses)*100):0,memoryUsage:e?.memoryUsage}}async pruneIfNeeded(){let e=await this.storage.keys();if(e.length<=this.config.maxEntries)return;let t=[];for(let n of e){let e=await this.storage.get(n);e&&t.push({key:n,createdAt:new Date(e.meta.createdAt).getTime()})}t.sort((e,t)=>e.createdAt-t.createdAt);let n=t.length-this.config.maxEntries;for(let e=0;e<n;e++){let n=t[e];n&&await this.storage.delete(n.key)}}};function s(e,t){return new o(e,t)}export{o as VerificationCacheService,r as cacheKeyToString,n as computeContentHash,s as createVerificationCacheService,i as stringToCacheKey};
@@ -0,0 +1 @@
1
+ import{DEFAULT_CACHE_CONFIG as e}from"./types.js";import{VerificationCacheService as t,cacheKeyToString as n,computeContentHash as r,createVerificationCacheService as i,stringToCacheKey as a}from"./cache-service.js";import{InMemoryCacheStorage as o,createInMemoryCacheStorage as s}from"./adapters/in-memory.js";import{FileSystemCacheStorage as c,createFileSystemCacheStorage as l}from"./adapters/filesystem.js";import{WorkspaceStateCacheStorage as u,createWorkspaceStateCacheStorage as d}from"./adapters/workspace-state.js";import"./adapters/index.js";
@@ -0,0 +1 @@
1
+ const e={maxEntries:1e3,defaultTtlMs:1440*60*1e3,structureTtlMs:10080*60*1e3,behaviorTtlMs:1440*60*1e3,aiTtlMs:1440*60*1e3,transitiveInvalidation:!0};export{e as DEFAULT_CACHE_CONFIG};
@@ -16,7 +16,7 @@ import{generateVerificationPrompt as e,specToFullMarkdown as t}from"@lssm/lib.co
16
16
  ],
17
17
  "summary": "AI verification skipped - no API key configured. Structure and behavior checks have been performed."
18
18
  }
19
- \`\`\``;try{let n=t.aiProvider??`anthropic`;if(n===`anthropic`){let{anthropic:t}=await import(`@ai-sdk/anthropic`),{generateText:n}=await import(`ai`);return(await n({model:t(`claude-3-5-sonnet-20241022`),prompt:e,system:`You are an expert code reviewer analyzing implementation compliance with specifications. Respond with structured JSON.`})).text}else if(n===`openai`){let{openai:t}=await import(`@ai-sdk/openai`),{generateText:n}=await import(`ai`);return(await n({model:t(`gpt-4o`),prompt:e,system:`You are an expert code reviewer analyzing implementation compliance with specifications. Respond with structured JSON.`})).text}throw Error(`Unknown AI provider: ${n}`)}catch(e){return`\`\`\`json
19
+ \`\`\``;try{let n=t.aiProvider??`anthropic`;if(n===`anthropic`){let{anthropic:t}=await import(`../../node_modules/@ai-sdk/anthropic/dist/index.js`),{generateText:n}=await import(`ai`);return(await n({model:t(`claude-3-5-sonnet-20241022`),prompt:e,system:`You are an expert code reviewer analyzing implementation compliance with specifications. Respond with structured JSON.`})).text}else if(n===`openai`){let{openai:t}=await import(`../../node_modules/@ai-sdk/openai/dist/index.js`),{generateText:n}=await import(`ai`);return(await n({model:t(`gpt-4o`),prompt:e,system:`You are an expert code reviewer analyzing implementation compliance with specifications. Respond with structured JSON.`})).text}throw Error(`Unknown AI provider: ${n}`)}catch(e){return`\`\`\`json
20
20
  {
21
21
  "passed": false,
22
22
  "score": 0,
@@ -25,4 +25,52 @@ import{generateVerificationPrompt as e,specToFullMarkdown as t}from"@lssm/lib.co
25
25
  ],
26
26
  "summary": "AI verification encountered an error"
27
27
  }
28
- \`\`\``}}async function i(t,i={}){let{spec:a,implementationCode:o,implementationPath:s}=t,c=Date.now(),l=n(await r(e(a,o).taskPrompt,i)),u=l.findings.map(e=>({severity:e.severity,category:`semantic`,message:e.message,location:e.location?{file:e.location}:s?{file:s}:void 0,suggestion:e.suggestion})),d=Math.round(l.confidence*100),f=l.compliant;return{tier:`ai_review`,passed:f,score:d,issues:u,suggestions:l.findings.filter(e=>e.suggestion).map(e=>e.suggestion),coverage:{scenarios:{total:0,covered:0},errors:{total:0,handled:0},fields:{total:1,implemented:f?1:0}},meta:{specName:a.meta.name,specVersion:a.meta.version,implementationPath:s??`unknown`,verifiedAt:new Date().toISOString(),duration:Date.now()-c}}}function a(e){let{spec:t,implementationCode:n,implementationPath:r}=e,i=Date.now(),a=[];n.includes(`console.log`)&&a.push({severity:`warning`,category:`semantic`,message:`Console.log statements found - consider using proper logging`,suggestion:`Use a structured logger instead of console.log`}),(n.includes(`// TODO`)||n.includes(`// FIXME`))&&a.push({severity:`info`,category:`semantic`,message:`TODO/FIXME comments found - implementation may be incomplete`,suggestion:`Address TODO items before finalizing implementation`}),t.policy.auth!==`anonymous`&&!n.includes(`auth`)&&a.push({severity:`warning`,category:`semantic`,message:`Spec requires ${t.policy.auth} auth but no auth check found`,suggestion:`Add authentication check at the handler entry point`});let o=a.filter(e=>e.severity===`error`).length===0?80:40,s=a.filter(e=>e.severity===`error`).length===0;return{tier:`ai_review`,passed:s,score:o,issues:a,suggestions:a.filter(e=>e.suggestion).map(e=>e.suggestion),coverage:{scenarios:{total:0,covered:0},errors:{total:0,handled:0},fields:{total:1,implemented:s?1:0}},meta:{specName:t.meta.name,specVersion:t.meta.version,implementationPath:r??`unknown`,verifiedAt:new Date().toISOString(),duration:Date.now()-i}}}export{a as createQuickAIReview,i as verifyWithAI};
28
+ \`\`\``}}async function i(t,i={}){let{spec:a,implementationCode:o,implementationPath:s}=t,c=Date.now(),l=n(await r(e(a,o).taskPrompt,i)),u=l.findings.map(e=>({severity:e.severity,category:`semantic`,message:e.message,location:e.location?{file:e.location}:s?{file:s}:void 0,suggestion:e.suggestion})),d=Math.round(l.confidence*100),f=l.compliant;return{tier:`ai_review`,passed:f,score:d,issues:u,suggestions:l.findings.filter(e=>e.suggestion).map(e=>e.suggestion),coverage:{scenarios:{total:0,covered:0},errors:{total:0,handled:0},fields:{total:1,implemented:f?1:0}},meta:{specName:a.meta.name,specVersion:a.meta.version,implementationPath:s??`unknown`,verifiedAt:new Date().toISOString(),duration:Date.now()-c}}}function a(e){let{spec:t,implementationCode:n,implementationPath:r}=e,i=Date.now(),a=[];n.includes(`console.log`)&&a.push({severity:`warning`,category:`semantic`,message:`Console.log statements found - consider using proper logging`,suggestion:`Use a structured logger instead of console.log`}),(n.includes(`// TODO`)||n.includes(`// FIXME`))&&a.push({severity:`info`,category:`semantic`,message:`TODO/FIXME comments found - implementation may be incomplete`,suggestion:`Address TODO items before finalizing implementation`}),t.policy.auth!==`anonymous`&&!n.includes(`auth`)&&a.push({severity:`warning`,category:`semantic`,message:`Spec requires ${t.policy.auth} auth but no auth check found`,suggestion:`Add authentication check at the handler entry point`});let o=a.filter(e=>e.severity===`error`).length===0?80:40,s=a.filter(e=>e.severity===`error`).length===0;return{tier:`ai_review`,passed:s,score:o,issues:a,suggestions:a.filter(e=>e.suggestion).map(e=>e.suggestion),coverage:{scenarios:{total:0,covered:0},errors:{total:0,handled:0},fields:{total:1,implemented:s?1:0}},meta:{specName:t.meta.name,specVersion:t.meta.version,implementationPath:r??`unknown`,verifiedAt:new Date().toISOString(),duration:Date.now()-i}}}function o(e,t){return`You are analyzing a code implementation against its specification.
29
+
30
+ ## Spec Schema Fields
31
+ ${e}
32
+
33
+ ## Implementation Code
34
+ \`\`\`typescript
35
+ ${t}
36
+ \`\`\`
37
+
38
+ ## Task
39
+ Analyze the implementation to verify it correctly implements the spec schema fields.
40
+
41
+ For each field in the spec:
42
+ 1. Find the corresponding field/property in the implementation
43
+ 2. Determine if the naming matches (exact, compatible synonym, or mismatch)
44
+ 3. Check if the types are compatible
45
+ 4. Identify any missing fields
46
+
47
+ Respond with JSON in this format:
48
+ \`\`\`json
49
+ {
50
+ "fieldMappings": [
51
+ {
52
+ "specField": "nickname",
53
+ "specType": "string",
54
+ "implementationField": "username",
55
+ "implementationType": "string",
56
+ "match": "compatible",
57
+ "aiConfidence": 0.85,
58
+ "suggestion": "Consider renaming 'username' to 'nickname' for exact spec compliance"
59
+ }
60
+ ],
61
+ "intentAlignment": {
62
+ "score": 85,
63
+ "issues": ["Field naming differs from spec"],
64
+ "suggestions": ["Rename fields to match spec exactly for better maintainability"]
65
+ },
66
+ "semanticIssues": []
67
+ }
68
+ \`\`\`
69
+
70
+ Match types:
71
+ - "exact": Field name and type match exactly
72
+ - "compatible": Semantically similar (e.g., "email" vs "emailAddress")
73
+ - "mismatch": Different meaning despite similar naming
74
+ - "missing": Spec field not found in implementation
75
+ `}function s(e){let t=[],n=(e,n)=>{try{let r=e?._def?.shape;if(r&&typeof r==`function`){let e=r();for(let[r,i]of Object.entries(e)){let e=i?._def?.typeName??`unknown`;t.push(`- ${r}: ${String(e).replace(`Zod`,``).toLowerCase()} (${n})`)}}}catch{t.push(`- [unable to extract ${n} fields]`)}};return e.io.input&&n(e.io.input,`input`),e.io.output&&!(`resourceRef`in e.io.output)&&n(e.io.output,`output`),t.length===0?`- [no schema fields could be extracted]`:t.join(`
76
+ `)}function c(e){let t=e.match(/```json\n?([\s\S]*?)\n?```/);if(t?.[1])try{let n=JSON.parse(t[1]);return{fieldMappings:(n.fieldMappings??[]).map(e=>({specField:String(e.specField??``),specType:String(e.specType??`unknown`),implementationField:e.implementationField?String(e.implementationField):void 0,implementationType:e.implementationType?String(e.implementationType):void 0,match:e.match??`missing`,aiConfidence:typeof e.aiConfidence==`number`?e.aiConfidence:.5,suggestion:e.suggestion?String(e.suggestion):void 0})),intentAlignment:{score:typeof n.intentAlignment?.score==`number`?n.intentAlignment.score:50,issues:Array.isArray(n.intentAlignment?.issues)?n.intentAlignment.issues:[],suggestions:Array.isArray(n.intentAlignment?.suggestions)?n.intentAlignment.suggestions:[]},semanticIssues:(n.semanticIssues??[]).map(e=>({category:String(e.category??`semantic`),severity:e.severity??`warning`,message:String(e.message??``),suggestion:e.suggestion?String(e.suggestion):void 0})),rawResponse:e}}catch{}return{fieldMappings:[],intentAlignment:{score:50,issues:[`Unable to parse AI response for semantic analysis`],suggestions:[]},semanticIssues:[],rawResponse:e}}async function l(e,t={}){let{spec:n,implementationCode:i}=e;return c(await r(o(s(n),i),t))}async function u(e,t={}){let{spec:n,implementationCode:r,implementationPath:a}=e,o=Date.now(),s=await i(e,t),c;if(t.aiApiKey)try{c=await l(e,t)}catch{}if(c){let e=[];for(let t of c.fieldMappings)t.match===`missing`?e.push({severity:`error`,category:`semantic`,message:`Missing field: '${t.specField}' (${t.specType}) not found in implementation`,suggestion:t.suggestion??`Add field '${t.specField}' to implementation`}):t.match===`mismatch`?e.push({severity:`warning`,category:`semantic`,message:`Field mismatch: '${t.specField}' has incorrect implementation as '${t.implementationField}'`,suggestion:t.suggestion}):t.match===`compatible`&&t.aiConfidence<.8&&e.push({severity:`info`,category:`semantic`,message:`Field naming: '${t.specField}' implemented as '${t.implementationField}' (compatible but not exact)`,suggestion:t.suggestion});for(let t of c.intentAlignment.issues)e.push({severity:`warning`,category:`semantic`,message:t});for(let t of c.semanticIssues)e.push({severity:t.severity,category:`semantic`,message:t.message,suggestion:t.suggestion});s.issues=[...s.issues,...e];let t=c.fieldMappings.length,n=c.fieldMappings.filter(e=>e.match===`exact`||e.match===`compatible`).length;if(t>0){let e=Math.round(n/t*100);s.score=Math.round((s.score+e)/2),s.coverage.fields={total:t,implemented:n}}e.some(e=>e.severity===`error`)&&(s.passed=!1),s.suggestions=[...s.suggestions,...c.intentAlignment.suggestions]}return s.meta={...s.meta,duration:Date.now()-o},s}export{a as createQuickAIReview,l as verifySemanticFields,i as verifyWithAI,u as verifyWithAIEnhanced};
@@ -1 +1 @@
1
- import{verifyStructure as e}from"./structure-verifier.js";import{verifyBehavior as t}from"./behavior-verifier.js";import{createQuickAIReview as n,verifyWithAI as r}from"./ai-verifier.js";import{VerifyService as i,createVerifyService as a,verifyService as o}from"./verify-service.js";
1
+ import{verifyStructure as e}from"./structure-verifier.js";import{verifyBehavior as t}from"./behavior-verifier.js";import{createQuickAIReview as n,verifySemanticFields as r,verifyWithAI as i,verifyWithAIEnhanced as a}from"./ai-verifier.js";import{VerifyService as o,createVerifyService as s,verifyService as c}from"./verify-service.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lssm/bundle.contractspec-workspace",
3
- "version": "0.0.0-canary-20251216062412",
3
+ "version": "0.0.0-canary-20251217034842",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",
@@ -24,12 +24,11 @@
24
24
  "dependencies": {
25
25
  "@lssm/module.contractspec-workspace": "workspace:*",
26
26
  "@lssm/lib.contracts": "workspace:*",
27
+ "@lssm/lib.contracts-transformers": "workspace:*",
28
+ "@lssm/lib.ai-providers": "workspace:*",
27
29
  "@lssm/lib.schema": "workspace:*",
28
30
  "@lssm/lib.testing": "workspace:*",
29
31
  "ai": "beta",
30
- "@ai-sdk/anthropic": "beta",
31
- "@ai-sdk/openai": "beta",
32
- "ollama-ai-provider": "^1.2.0",
33
32
  "zod": "^4.1.13",
34
33
  "glob": "^13.0.0",
35
34
  "chokidar": "^4.0.1"