From 474b1af1457f699a16120cf9bb98246f363d7816 Mon Sep 17 00:00:00 2001 From: Waleed Date: Fri, 6 Feb 2026 13:11:56 -0800 Subject: [PATCH 1/8] improvement(ui): improved skills UI, validation, and permissions (#3156) * improvement(ui): improved skills UI, validation, and permissions * stronger typing for Skill interface * added missing docs description * ack comment --- apps/docs/components/icons.tsx | 21 ++++++ apps/docs/content/docs/en/skills/index.mdx | 63 ++++++++++++++-- apps/docs/content/docs/en/tools/airweave.mdx | 15 ++++ apps/docs/public/static/skills/add-skill.png | Bin 0 -> 28530 bytes .../public/static/skills/manage-skills.png | Bin 0 -> 57505 bytes .../components/skill-input/skill-input.tsx | 61 +++++++++------ .../hooks/use-editor-subblock-layout.ts | 6 ++ .../workflow-block/workflow-block.tsx | 44 +++++++++++ .../skills/components/skill-modal.tsx | 70 ++++++++++++------ apps/sim/components/icons.tsx | 16 ++-- 10 files changed, 235 insertions(+), 61 deletions(-) create mode 100644 apps/docs/public/static/skills/add-skill.png create mode 100644 apps/docs/public/static/skills/manage-skills.png diff --git a/apps/docs/components/icons.tsx b/apps/docs/components/icons.tsx index f5d604d1d..d62410d7f 100644 --- a/apps/docs/components/icons.tsx +++ b/apps/docs/components/icons.tsx @@ -5462,3 +5462,24 @@ export function EnrichSoIcon(props: SVGProps) { ) } + +export function AgentSkillsIcon(props: SVGProps) { + return ( + + + + + ) +} diff --git a/apps/docs/content/docs/en/skills/index.mdx b/apps/docs/content/docs/en/skills/index.mdx index 1af685ceb..6f5a95d3f 100644 --- a/apps/docs/content/docs/en/skills/index.mdx +++ b/apps/docs/content/docs/en/skills/index.mdx @@ -18,7 +18,9 @@ This means you can attach many skills to an agent without bloating its context w ## Creating Skills -Go to **Settings** (gear icon) and select **Skills** under the Tools section. +Go to **Settings** and select **Skills** under the Tools section. + +![Manage Skills](/static/skills/manage-skills.png) Click **Add** to create a new skill with three fields: @@ -52,11 +54,22 @@ Use when the user asks you to write, optimize, or debug SQL queries. ... ``` +**Recommended structure:** +- **When to use** — Specific triggers and scenarios +- **Instructions** — Step-by-step guidance with numbered lists +- **Examples** — Input/output samples showing expected behavior +- **Common Patterns** — Reusable approaches for frequent tasks +- **Edge Cases** — Gotchas and special considerations + +Keep skills focused and under 500 lines. If a skill grows too large, split it into multiple specialized skills. + ## Adding Skills to an Agent Open any **Agent** block and find the **Skills** dropdown below the tools section. Select the skills you want the agent to have access to. -Selected skills appear as chips that you can click to edit or remove. +![Add Skill](/static/skills/add-skill.png) + +Selected skills appear as cards that you can click to edit or remove. ### What Happens at Runtime @@ -69,12 +82,50 @@ When the workflow runs: This works across all supported LLM providers — the `load_skill` tool uses standard tool-calling, so no provider-specific configuration is needed. -## Tips +## Common Use Cases -- **Keep descriptions actionable** — Instead of "Helps with SQL", write "Write optimized SQL queries for PostgreSQL, MySQL, and SQLite, including index recommendations and query plan analysis" +Skills are most valuable when agents need specialized knowledge or multi-step workflows: + +**Domain Expertise** +- `api-integration-expert` — Best practices for calling specific APIs (authentication, rate limiting, error handling) +- `data-transformation` — ETL patterns, data cleaning, and validation rules +- `code-reviewer` — Code review guidelines specific to your team's standards + +**Workflow Templates** +- `bug-investigation` — Step-by-step debugging methodology (reproduce → isolate → test → fix) +- `feature-implementation` — Development workflow from requirements to deployment +- `document-generator` — Templates and formatting rules for technical documentation + +**Company-Specific Knowledge** +- `our-architecture` — System architecture diagrams, service dependencies, and deployment processes +- `style-guide` — Brand guidelines, writing tone, UI/UX patterns +- `customer-onboarding` — Standard procedures and common customer questions + +**When to use skills vs. agent instructions:** +- Use **skills** for knowledge that applies across multiple workflows or changes frequently +- Use **agent instructions** for task-specific context that's unique to a single agent + +## Best Practices + +**Writing Effective Descriptions** +- **Be specific and keyword-rich** — Instead of "Helps with SQL", write "Write optimized SQL queries for PostgreSQL, MySQL, and SQLite, including index recommendations and query plan analysis" +- **Include activation triggers** — Mention specific words or phrases that should prompt the skill (e.g., "Use when the user mentions PDFs, forms, or document extraction") +- **Keep it under 200 words** — Agents scan descriptions quickly; make every word count + +**Skill Scope and Organization** - **One skill per domain** — A focused `sql-expert` skill works better than a broad `database-everything` skill -- **Use markdown structure** — Headers, lists, and code blocks help the agent parse and follow instructions -- **Test iteratively** — Run your workflow and check if the agent activates the skill when expected +- **Limit to 5-10 skills per agent** — More skills = more decision overhead; start small and add as needed +- **Split large skills** — If a skill exceeds 500 lines, break it into focused sub-skills + +**Content Structure** +- **Use markdown formatting** — Headers, lists, and code blocks help agents parse and follow instructions +- **Provide examples** — Show input/output pairs so agents understand expected behavior +- **Be explicit about edge cases** — Don't assume agents will infer special handling + +**Testing and Iteration** +- **Test activation** — Run your workflow and verify the agent loads the skill when expected +- **Check for false positives** — Make sure skills aren't activating when they shouldn't +- **Refine descriptions** — If a skill isn't loading when needed, add more keywords to the description ## Learn More diff --git a/apps/docs/content/docs/en/tools/airweave.mdx b/apps/docs/content/docs/en/tools/airweave.mdx index f5ce4994f..59764a4c0 100644 --- a/apps/docs/content/docs/en/tools/airweave.mdx +++ b/apps/docs/content/docs/en/tools/airweave.mdx @@ -10,6 +10,21 @@ import { BlockInfoCard } from "@/components/ui/block-info-card" color="#6366F1" /> +{/* MANUAL-CONTENT-START:intro */} +[Airweave](https://airweave.ai/) is an AI-powered semantic search platform that helps you discover and retrieve knowledge across all your synced data sources. Built for modern teams, Airweave enables fast, relevant search results using neural, hybrid, or keyword-based strategies tailored to your needs. + +With Airweave, you can: + +- **Search smarter**: Use natural language queries to uncover information stored across your connected tools and databases +- **Unify your data**: Seamlessly access content from sources like code, docs, chat, emails, cloud files, and more +- **Customize retrieval**: Select between hybrid (semantic + keyword), neural, or keyword search strategies for optimal results +- **Boost recall**: Expand search queries with AI to find more comprehensive answers +- **Rerank results using AI**: Prioritize the most relevant answers with powerful language models +- **Get instant answers**: Generate clear, AI-powered responses synthesized from your data + +In Sim, the Airweave integration empowers your agents to search, summarize, and extract insights from all your organization’s data via a single tool. Use Airweave to drive rich, contextual knowledge retrieval within your workflows—whether answering questions, generating summaries, or supporting dynamic decision-making. +{/* MANUAL-CONTENT-END */} + ## Usage Instructions Search across your synced data sources using Airweave. Supports semantic search with hybrid, neural, or keyword retrieval strategies. Optionally generate AI-powered answers from search results. diff --git a/apps/docs/public/static/skills/add-skill.png b/apps/docs/public/static/skills/add-skill.png new file mode 100644 index 0000000000000000000000000000000000000000..80428e88ae88183edbb73f53bc9136931b20ffb4 GIT binary patch literal 28530 zcmeFYbyQqU@HU8B&|txd;TGJPgaiTv3GVLhE|~-gNq`8!WeCCDU4jN5+&#eHHrQa_ z<$d!e^V|Jr&)GkA&+f-L!_3^d-CbQ>U0u&pb;DJZWC`%7@la4u2;`nWRYgHTgQK9J z=Hp-iS4!9UNKjDl6>X%YRpg|l8C6`JEN$#9P*9$Sf7Qa)R_mfj(NmSfA%6QR8k)#> z@8PRxVqKK=XT)DWV&FXN2!@!-Qj+V}y)}NO^_a}S09D66JFk%A-E0L1g?h9{iLusP zFiPzf`@Gn^(8<+FD&KXI+s+Ix3XdoTuMSr(CMbp9h@R$lbIQl07A6TyoMu!4Z&YtJLsN&&ih=M*~;awo~^?p5UO|CUB{Jez*6{DKpBRW!j4rB9xa{ zKJVAhc*zZKl@!uq;kZ=bS>?Kv;brCRw+E)4YSXt7p)w9*p!qPNBuIR;qQv1#BSg2n zm6UNWoXj-nZNT9{<~zm|q7qIx*o{{mkpy>g=e^F1m;BC3Y))w6!F4G^7|mi{^E&?8 zO600)WrYoUtr#2;^N=V)V+DWnn8(Vt8gG~}kXbS6!)tA96tdX2h)a#QuNnA?D(C5y zPcVtb@QWGgvwlV_6YZ7Udu%M+CPQrX-0l8-EdO`B4}P#QXiJsre;$Ym(`Hz*ExE_y z*t}NlZ@aZnKhFD0dX349?E=Kjuj^Sjkn~a_psbZ!qMN1)GV8q@ZVMHTSk;#ywX0>o-vG} zkywbre(NT!UN6$N|L%45j}pu?XP4ZgeN&x4_j*yK`g?lB6a|sk^F;Shh%nFuRa#;Q zGhf>?+H5+)LbWzhj2Tf}KjOAEyS$>J{WLOvKcrJw1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jR>FoMYI$X?o6+O3{ybR{GhwPQ4H7AOTN-3;3grPH>NWk>$+ ec9tL4Hg1jBbS=YAy&d_70_Qb!&K9cK-1!f6Y4qp- literal 0 HcmV?d00001 diff --git a/apps/docs/public/static/skills/manage-skills.png b/apps/docs/public/static/skills/manage-skills.png new file mode 100644 index 0000000000000000000000000000000000000000..67f7ccd2045518f056969038041507c94594c6eb GIT binary patch literal 57505 zcmeFZcR-WRwkR4z@TW8p14t32Dph(13snqA38AA@X`u$B+vrWe&_YpKAR$CRKnO*o zgkFTuL+`zd)Ejp>`|Nx7K5xH&-o59(y^?&hW@gQ-HIu1p&3xy>=Tm^IkJU8Q0AyqU z02%26IG-UK)_nBH@~NJVn&uPLKS#6zNO18U0N?`k^3YR%c+1GxRj4S-c zeZ1VfNHkA>;~oZjk4U%;3BP0ipKz=Hgj>6L{HBj4(I~h$!+!Jn4ZkI(wuOTAN$ww{ z9~;0Epa)O~Jp5gLlAi>w*#LmdJ^(=e{%>JcsQ^G_2mru5`nNFdj{pGOI{=`f=Wk(u zs}r~99?$=j-9^&#f}I@zu!95uXp8{>hF$>Ris_%?NRNLa+bvQQ8%Zu#(#Ia)46p^< z0%!uD0Be9S2@?a{1Be2o&c^_c0OS`g{Qi>QBI!%<2L;8&ixgKbU84Mh`U*8Q)fFl# z8ro}DX=v$bsi>|pUZrQa4g>6n-quQOk}4!r(56EbpAnu`>dDJU*qr=g;`{{I@z zzX9m~xM2SWfSimIaDkqToSy8w3BXRO?hE8(B=~D-0hE`1%Sd+NGAY{VDuC=F*#&Y+ zatd;iv==X40+4(cDJbbLUAxV2UG#x&{2zMHImO&xmjD?(xgHuMewx0_#LO*j<Un1=MpAUee=YYkw({NAi&RW)M!KYGZum0K=|I4)h{UWa*J_0;m0mw??@S`2( zp&9%;W0m6Z@eingoBqiS^bDv%H<1SHjl`>|9OHsn&oB$~BQ+;D*LvaO*IIAwd7>-B zY83?tc}VCb0iHK@0v33_NPdymMWl)#m*m%<8hl^$)juKq?;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V z(hH7soS{37InNc9kS(TXk+>b_hASoDSD=CLffdw~&yJTZe%8Q;N;ifn3!3!((9 z!ok7qoF^2ZwPq|7BG~wYg>&MI(#0-IH=!OAPlzceW*1 zetv1>ad`Z;$$7mhD*^MU>)z;UBb;zl6Q-gF@&}o&s$s-sOe^0rXG)b_^!2Tv4~=zF zM(|eMkn2f&b>cv>Rw0V5^0#N~-MB%^T4;KTL{6JwO1+S0xk268`BH$F=`67y9?(^3PM`&Yu^D@q_mN0C*Vaj{pDw literal 0 HcmV?d00001 diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/skill-input/skill-input.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/skill-input/skill-input.tsx index b61a96414..713cbf183 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/skill-input/skill-input.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/skill-input/skill-input.tsx @@ -130,39 +130,52 @@ export function SkillInput({ onOpenChange={setOpen} /> - {selectedSkills.length > 0 && ( -

- {selectedSkills.map((stored) => { - const fullSkill = workspaceSkills.find((s) => s.id === stored.skillId) - return ( + {selectedSkills.length > 0 && + selectedSkills.map((stored) => { + const fullSkill = workspaceSkills.find((s) => s.id === stored.skillId) + return ( +
{ if (fullSkill && !disabled && !isPreview) { setEditingSkill(fullSkill) } }} > - - {resolveSkillName(stored)} - {!disabled && !isPreview && ( - - )} + +
+ + {resolveSkillName(stored)} + +
+
+ {!disabled && !isPreview && ( + + )} +
- ) - })} - - )} + + ) + })} state.blocks?.[blockId]?.data, [blockId]) ) + const { config: permissionConfig } = usePermissionConfig() return useMemo(() => { // Guard against missing config or block selection @@ -100,6 +102,9 @@ export function useEditorSubblockLayout( const visibleSubBlocks = (config.subBlocks || []).filter((block) => { if (block.hidden) return false + // Hide skill-input subblock when skills are disabled via permissions + if (block.type === 'skill-input' && permissionConfig.disableSkills) return false + // Check required feature if specified - declarative feature gating if (!isSubBlockFeatureEnabled(block)) return false @@ -149,5 +154,6 @@ export function useEditorSubblockLayout( activeWorkflowId, isSnapshotView, blockDataFromStore, + permissionConfig.disableSkills, ]) } diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/workflow-block/workflow-block.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/workflow-block/workflow-block.tsx index 636fd559d..c0f89e2b3 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/workflow-block/workflow-block.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/workflow-block/workflow-block.tsx @@ -40,6 +40,7 @@ import { useCustomTools } from '@/hooks/queries/custom-tools' import { useMcpServers, useMcpToolsQuery } from '@/hooks/queries/mcp' import { useCredentialName } from '@/hooks/queries/oauth-credentials' import { useReactivateSchedule, useScheduleInfo } from '@/hooks/queries/schedules' +import { useSkills } from '@/hooks/queries/skills' import { useDeployChildWorkflow } from '@/hooks/queries/workflows' import { useSelectorDisplayName } from '@/hooks/use-selector-display-name' import { useVariablesStore } from '@/stores/panel' @@ -618,6 +619,48 @@ const SubBlockRow = memo(function SubBlockRow({ return `${toolNames[0]}, ${toolNames[1]} +${toolNames.length - 2}` }, [subBlock?.type, rawValue, customTools, workspaceId]) + /** + * Hydrates skill references to display names. + * Resolves skill IDs to their current names from the skills query. + */ + const { data: workspaceSkills = [] } = useSkills(workspaceId || '') + + const skillsDisplayValue = useMemo(() => { + if (subBlock?.type !== 'skill-input' || !Array.isArray(rawValue) || rawValue.length === 0) { + return null + } + + interface StoredSkill { + skillId: string + name?: string + } + + const skillNames = rawValue + .map((skill: StoredSkill) => { + if (!skill || typeof skill !== 'object') return null + + // Priority 1: Resolve skill name from the skills query (fresh data) + if (skill.skillId) { + const foundSkill = workspaceSkills.find((s) => s.id === skill.skillId) + if (foundSkill?.name) return foundSkill.name + } + + // Priority 2: Fall back to stored name (for deleted skills) + if (skill.name && typeof skill.name === 'string') return skill.name + + // Priority 3: Use skillId as last resort + if (skill.skillId) return skill.skillId + + return null + }) + .filter((name): name is string => !!name) + + if (skillNames.length === 0) return null + if (skillNames.length === 1) return skillNames[0] + if (skillNames.length === 2) return `${skillNames[0]}, ${skillNames[1]}` + return `${skillNames[0]}, ${skillNames[1]} +${skillNames.length - 2}` + }, [subBlock?.type, rawValue, workspaceSkills]) + const isPasswordField = subBlock?.password === true const maskedValue = isPasswordField && value && value !== '-' ? '•••' : null @@ -627,6 +670,7 @@ const SubBlockRow = memo(function SubBlockRow({ dropdownLabel || variablesDisplayValue || toolsDisplayValue || + skillsDisplayValue || knowledgeBaseDisplayName || workflowSelectionName || mcpServerDisplayName || diff --git a/apps/sim/app/workspace/[workspaceId]/w/components/sidebar/components/settings-modal/components/skills/components/skill-modal.tsx b/apps/sim/app/workspace/[workspaceId]/w/components/sidebar/components/settings-modal/components/skills/components/skill-modal.tsx index 36b7c9ddd..99a473fd2 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/components/sidebar/components/settings-modal/components/skills/components/skill-modal.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/components/sidebar/components/settings-modal/components/skills/components/skill-modal.tsx @@ -27,6 +27,13 @@ interface SkillModalProps { const KEBAB_CASE_REGEX = /^[a-z0-9]+(-[a-z0-9]+)*$/ +interface FieldErrors { + name?: string + description?: string + content?: string + general?: string +} + export function SkillModal({ open, onOpenChange, @@ -43,7 +50,7 @@ export function SkillModal({ const [name, setName] = useState('') const [description, setDescription] = useState('') const [content, setContent] = useState('') - const [formError, setFormError] = useState('') + const [errors, setErrors] = useState({}) const [saving, setSaving] = useState(false) useEffect(() => { @@ -57,7 +64,7 @@ export function SkillModal({ setDescription('') setContent('') } - setFormError('') + setErrors({}) } }, [open, initialValues]) @@ -71,24 +78,26 @@ export function SkillModal({ }, [name, description, content, initialValues]) const handleSave = async () => { + const newErrors: FieldErrors = {} + if (!name.trim()) { - setFormError('Name is required') - return - } - if (name.length > 64) { - setFormError('Name must be 64 characters or less') - return - } - if (!KEBAB_CASE_REGEX.test(name)) { - setFormError('Name must be kebab-case (e.g. my-skill)') - return + newErrors.name = 'Name is required' + } else if (name.length > 64) { + newErrors.name = 'Name must be 64 characters or less' + } else if (!KEBAB_CASE_REGEX.test(name)) { + newErrors.name = 'Name must be kebab-case (e.g. my-skill)' } + if (!description.trim()) { - setFormError('Description is required') - return + newErrors.description = 'Description is required' } + if (!content.trim()) { - setFormError('Content is required') + newErrors.content = 'Content is required' + } + + if (Object.keys(newErrors).length > 0) { + setErrors(newErrors) return } @@ -113,7 +122,7 @@ export function SkillModal({ error instanceof Error && error.message.includes('already exists') ? error.message : 'Failed to save skill. Please try again.' - setFormError(message) + setErrors({ general: message }) } finally { setSaving(false) } @@ -135,12 +144,17 @@ export function SkillModal({ value={name} onChange={(e) => { setName(e.target.value) - if (formError) setFormError('') + if (errors.name || errors.general) + setErrors((prev) => ({ ...prev, name: undefined, general: undefined })) }} /> - - Lowercase letters, numbers, and hyphens (e.g. my-skill) - + {errors.name ? ( +

{errors.name}

+ ) : ( + + Lowercase letters, numbers, and hyphens (e.g. my-skill) + + )}
@@ -153,10 +167,14 @@ export function SkillModal({ value={description} onChange={(e) => { setDescription(e.target.value) - if (formError) setFormError('') + if (errors.description || errors.general) + setErrors((prev) => ({ ...prev, description: undefined, general: undefined })) }} maxLength={1024} /> + {errors.description && ( +

{errors.description}

+ )}
@@ -169,13 +187,19 @@ export function SkillModal({ value={content} onChange={(e: ChangeEvent) => { setContent(e.target.value) - if (formError) setFormError('') + if (errors.content || errors.general) + setErrors((prev) => ({ ...prev, content: undefined, general: undefined })) }} className='min-h-[200px] resize-y font-mono text-[13px]' /> + {errors.content && ( +

{errors.content}

+ )}
- {formError && {formError}} + {errors.general && ( +

{errors.general}

+ )} diff --git a/apps/sim/components/icons.tsx b/apps/sim/components/icons.tsx index 969f5be13..d62410d7f 100644 --- a/apps/sim/components/icons.tsx +++ b/apps/sim/components/icons.tsx @@ -5468,18 +5468,18 @@ export function AgentSkillsIcon(props: SVGProps) { - + ) } From 1edaf197b28b7aee84d5a83eb331d0fce8c2c4fb Mon Sep 17 00:00:00 2001 From: Waleed Date: Fri, 6 Feb 2026 15:26:10 -0800 Subject: [PATCH 2/8] fix(azure): add azure-anthropic support to router, evaluator, copilot, and tokenization (#3158) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(azure): add azure-anthropic support to router, evaluator, copilot, and tokenization * added azure anthropic values to env * fix(azure): make anthropic-version configurable for azure-anthropic provider * fix(azure): thread provider credentials through guardrails and fix translate missing bedrockAccessKeyId * updated guardrails * ack'd PR comments * fix(azure): unify credential passing pattern across all LLM handlers - Pass all provider credentials unconditionally in router, evaluator (matching agent pattern) - Remove conditional if-branching on providerId for credential fields - Thread workspaceId through guardrails → hallucination validator for BYOK key resolution - Remove getApiKey() from hallucination validator, let executeProviderRequest handle it - Resolve vertex OAuth credentials in hallucination validator matching agent handler pattern Co-Authored-By: Claude Opus 4.6 --------- Co-authored-by: Claude Opus 4.6 --- apps/sim/app/api/copilot/chat/route.ts | 8 ++ apps/sim/app/api/guardrails/validate/route.ts | 33 ++++++++ apps/sim/blocks/blocks/agent.ts | 6 +- apps/sim/blocks/blocks/translate.ts | 3 +- apps/sim/blocks/utils.ts | 14 ++-- .../handlers/evaluator/evaluator-handler.ts | 23 ++---- .../handlers/router/router-handler.ts | 46 ++++------- apps/sim/lib/copilot/config.ts | 1 + apps/sim/lib/copilot/types.ts | 9 ++- apps/sim/lib/core/config/env.ts | 3 + .../lib/guardrails/validate_hallucination.ts | 77 +++++++++++++++---- apps/sim/lib/tokenization/constants.ts | 5 ++ apps/sim/lib/tokenization/estimators.ts | 1 + apps/sim/providers/azure-anthropic/index.ts | 4 +- apps/sim/tools/guardrails/validate.ts | 16 ++++ 15 files changed, 171 insertions(+), 78 deletions(-) diff --git a/apps/sim/app/api/copilot/chat/route.ts b/apps/sim/app/api/copilot/chat/route.ts index 9d31bf5c3..72c959d9a 100644 --- a/apps/sim/app/api/copilot/chat/route.ts +++ b/apps/sim/app/api/copilot/chat/route.ts @@ -285,6 +285,14 @@ export async function POST(req: NextRequest) { apiVersion: 'preview', endpoint: env.AZURE_OPENAI_ENDPOINT, } + } else if (providerEnv === 'azure-anthropic') { + providerConfig = { + provider: 'azure-anthropic', + model: envModel, + apiKey: env.AZURE_ANTHROPIC_API_KEY, + apiVersion: env.AZURE_ANTHROPIC_API_VERSION, + endpoint: env.AZURE_ANTHROPIC_ENDPOINT, + } } else if (providerEnv === 'vertex') { providerConfig = { provider: 'vertex', diff --git a/apps/sim/app/api/guardrails/validate/route.ts b/apps/sim/app/api/guardrails/validate/route.ts index 5f4738339..6e1b65750 100644 --- a/apps/sim/app/api/guardrails/validate/route.ts +++ b/apps/sim/app/api/guardrails/validate/route.ts @@ -23,7 +23,16 @@ export async function POST(request: NextRequest) { topK, model, apiKey, + azureEndpoint, + azureApiVersion, + vertexProject, + vertexLocation, + vertexCredential, + bedrockAccessKeyId, + bedrockSecretKey, + bedrockRegion, workflowId, + workspaceId, piiEntityTypes, piiMode, piiLanguage, @@ -110,7 +119,18 @@ export async function POST(request: NextRequest) { topK, model, apiKey, + { + azureEndpoint, + azureApiVersion, + vertexProject, + vertexLocation, + vertexCredential, + bedrockAccessKeyId, + bedrockSecretKey, + bedrockRegion, + }, workflowId, + workspaceId, piiEntityTypes, piiMode, piiLanguage, @@ -178,7 +198,18 @@ async function executeValidation( topK: string | undefined, model: string, apiKey: string | undefined, + providerCredentials: { + azureEndpoint?: string + azureApiVersion?: string + vertexProject?: string + vertexLocation?: string + vertexCredential?: string + bedrockAccessKeyId?: string + bedrockSecretKey?: string + bedrockRegion?: string + }, workflowId: string | undefined, + workspaceId: string | undefined, piiEntityTypes: string[] | undefined, piiMode: string | undefined, piiLanguage: string | undefined, @@ -219,7 +250,9 @@ async function executeValidation( topK: topK ? Number.parseInt(topK) : 10, // Default topK is 10 model: model, apiKey, + providerCredentials, workflowId, + workspaceId, requestId, }) } diff --git a/apps/sim/blocks/blocks/agent.ts b/apps/sim/blocks/blocks/agent.ts index 395efec87..bf8ec0d66 100644 --- a/apps/sim/blocks/blocks/agent.ts +++ b/apps/sim/blocks/blocks/agent.ts @@ -333,11 +333,11 @@ Return ONLY the JSON array.`, id: 'azureApiVersion', title: 'Azure API Version', type: 'short-input', - placeholder: '2024-07-01-preview', + placeholder: 'Enter API version', connectionDroppable: false, condition: { field: 'model', - value: providers['azure-openai'].models, + value: [...providers['azure-openai'].models, ...providers['azure-anthropic'].models], }, }, { @@ -715,7 +715,7 @@ Example 3 (Array Input): }, model: { type: 'string', description: 'AI model to use' }, apiKey: { type: 'string', description: 'Provider API key' }, - azureEndpoint: { type: 'string', description: 'Azure OpenAI endpoint URL' }, + azureEndpoint: { type: 'string', description: 'Azure endpoint URL' }, azureApiVersion: { type: 'string', description: 'Azure API version' }, vertexProject: { type: 'string', description: 'Google Cloud project ID for Vertex AI' }, vertexLocation: { type: 'string', description: 'Google Cloud location for Vertex AI' }, diff --git a/apps/sim/blocks/blocks/translate.ts b/apps/sim/blocks/blocks/translate.ts index d0d647765..1385075c7 100644 --- a/apps/sim/blocks/blocks/translate.ts +++ b/apps/sim/blocks/blocks/translate.ts @@ -76,8 +76,9 @@ export const TranslateBlock: BlockConfig = { vertexProject: params.vertexProject, vertexLocation: params.vertexLocation, vertexCredential: params.vertexCredential, - bedrockRegion: params.bedrockRegion, + bedrockAccessKeyId: params.bedrockAccessKeyId, bedrockSecretKey: params.bedrockSecretKey, + bedrockRegion: params.bedrockRegion, }), }, }, diff --git a/apps/sim/blocks/utils.ts b/apps/sim/blocks/utils.ts index 7de0b518a..eed4a5c37 100644 --- a/apps/sim/blocks/utils.ts +++ b/apps/sim/blocks/utils.ts @@ -80,7 +80,7 @@ export function getApiKeyCondition() { /** * Returns the standard provider credential subblocks used by LLM-based blocks. - * This includes: Vertex AI OAuth, API Key, Azure OpenAI, Vertex AI config, and Bedrock config. + * This includes: Vertex AI OAuth, API Key, Azure (OpenAI + Anthropic), Vertex AI config, and Bedrock config. * * Usage: Spread into your block's subBlocks array after block-specific fields */ @@ -111,25 +111,25 @@ export function getProviderCredentialSubBlocks(): SubBlockConfig[] { }, { id: 'azureEndpoint', - title: 'Azure OpenAI Endpoint', + title: 'Azure Endpoint', type: 'short-input', password: true, - placeholder: 'https://your-resource.openai.azure.com', + placeholder: 'https://your-resource.services.ai.azure.com', connectionDroppable: false, condition: { field: 'model', - value: providers['azure-openai'].models, + value: [...providers['azure-openai'].models, ...providers['azure-anthropic'].models], }, }, { id: 'azureApiVersion', title: 'Azure API Version', type: 'short-input', - placeholder: '2024-07-01-preview', + placeholder: 'Enter API version', connectionDroppable: false, condition: { field: 'model', - value: providers['azure-openai'].models, + value: [...providers['azure-openai'].models, ...providers['azure-anthropic'].models], }, }, { @@ -202,7 +202,7 @@ export function getProviderCredentialSubBlocks(): SubBlockConfig[] { */ export const PROVIDER_CREDENTIAL_INPUTS = { apiKey: { type: 'string', description: 'Provider API key' }, - azureEndpoint: { type: 'string', description: 'Azure OpenAI endpoint URL' }, + azureEndpoint: { type: 'string', description: 'Azure endpoint URL' }, azureApiVersion: { type: 'string', description: 'Azure API version' }, vertexProject: { type: 'string', description: 'Google Cloud project ID for Vertex AI' }, vertexLocation: { type: 'string', description: 'Google Cloud location for Vertex AI' }, diff --git a/apps/sim/executor/handlers/evaluator/evaluator-handler.ts b/apps/sim/executor/handlers/evaluator/evaluator-handler.ts index 3e95b2f85..8c432f1da 100644 --- a/apps/sim/executor/handlers/evaluator/evaluator-handler.ts +++ b/apps/sim/executor/handlers/evaluator/evaluator-handler.ts @@ -121,26 +121,17 @@ export class EvaluatorBlockHandler implements BlockHandler { temperature: EVALUATOR.DEFAULT_TEMPERATURE, apiKey: finalApiKey, + azureEndpoint: inputs.azureEndpoint, + azureApiVersion: inputs.azureApiVersion, + vertexProject: evaluatorConfig.vertexProject, + vertexLocation: evaluatorConfig.vertexLocation, + bedrockAccessKeyId: evaluatorConfig.bedrockAccessKeyId, + bedrockSecretKey: evaluatorConfig.bedrockSecretKey, + bedrockRegion: evaluatorConfig.bedrockRegion, workflowId: ctx.workflowId, workspaceId: ctx.workspaceId, } - if (providerId === 'vertex') { - providerRequest.vertexProject = evaluatorConfig.vertexProject - providerRequest.vertexLocation = evaluatorConfig.vertexLocation - } - - if (providerId === 'azure-openai') { - providerRequest.azureEndpoint = inputs.azureEndpoint - providerRequest.azureApiVersion = inputs.azureApiVersion - } - - if (providerId === 'bedrock') { - providerRequest.bedrockAccessKeyId = evaluatorConfig.bedrockAccessKeyId - providerRequest.bedrockSecretKey = evaluatorConfig.bedrockSecretKey - providerRequest.bedrockRegion = evaluatorConfig.bedrockRegion - } - const response = await fetch(url.toString(), { method: 'POST', headers: await buildAuthHeaders(), diff --git a/apps/sim/executor/handlers/router/router-handler.ts b/apps/sim/executor/handlers/router/router-handler.ts index 766a4aac6..541cdccca 100644 --- a/apps/sim/executor/handlers/router/router-handler.ts +++ b/apps/sim/executor/handlers/router/router-handler.ts @@ -96,26 +96,17 @@ export class RouterBlockHandler implements BlockHandler { context: JSON.stringify(messages), temperature: ROUTER.INFERENCE_TEMPERATURE, apiKey: finalApiKey, + azureEndpoint: inputs.azureEndpoint, + azureApiVersion: inputs.azureApiVersion, + vertexProject: routerConfig.vertexProject, + vertexLocation: routerConfig.vertexLocation, + bedrockAccessKeyId: routerConfig.bedrockAccessKeyId, + bedrockSecretKey: routerConfig.bedrockSecretKey, + bedrockRegion: routerConfig.bedrockRegion, workflowId: ctx.workflowId, workspaceId: ctx.workspaceId, } - if (providerId === 'vertex') { - providerRequest.vertexProject = routerConfig.vertexProject - providerRequest.vertexLocation = routerConfig.vertexLocation - } - - if (providerId === 'azure-openai') { - providerRequest.azureEndpoint = inputs.azureEndpoint - providerRequest.azureApiVersion = inputs.azureApiVersion - } - - if (providerId === 'bedrock') { - providerRequest.bedrockAccessKeyId = routerConfig.bedrockAccessKeyId - providerRequest.bedrockSecretKey = routerConfig.bedrockSecretKey - providerRequest.bedrockRegion = routerConfig.bedrockRegion - } - const response = await fetch(url.toString(), { method: 'POST', headers: await buildAuthHeaders(), @@ -234,6 +225,13 @@ export class RouterBlockHandler implements BlockHandler { context: JSON.stringify(messages), temperature: ROUTER.INFERENCE_TEMPERATURE, apiKey: finalApiKey, + azureEndpoint: inputs.azureEndpoint, + azureApiVersion: inputs.azureApiVersion, + vertexProject: routerConfig.vertexProject, + vertexLocation: routerConfig.vertexLocation, + bedrockAccessKeyId: routerConfig.bedrockAccessKeyId, + bedrockSecretKey: routerConfig.bedrockSecretKey, + bedrockRegion: routerConfig.bedrockRegion, workflowId: ctx.workflowId, workspaceId: ctx.workspaceId, responseFormat: { @@ -257,22 +255,6 @@ export class RouterBlockHandler implements BlockHandler { }, } - if (providerId === 'vertex') { - providerRequest.vertexProject = routerConfig.vertexProject - providerRequest.vertexLocation = routerConfig.vertexLocation - } - - if (providerId === 'azure-openai') { - providerRequest.azureEndpoint = inputs.azureEndpoint - providerRequest.azureApiVersion = inputs.azureApiVersion - } - - if (providerId === 'bedrock') { - providerRequest.bedrockAccessKeyId = routerConfig.bedrockAccessKeyId - providerRequest.bedrockSecretKey = routerConfig.bedrockSecretKey - providerRequest.bedrockRegion = routerConfig.bedrockRegion - } - const response = await fetch(url.toString(), { method: 'POST', headers: await buildAuthHeaders(), diff --git a/apps/sim/lib/copilot/config.ts b/apps/sim/lib/copilot/config.ts index 4b9c89274..5700e9930 100644 --- a/apps/sim/lib/copilot/config.ts +++ b/apps/sim/lib/copilot/config.ts @@ -12,6 +12,7 @@ const VALID_PROVIDER_IDS: readonly ProviderId[] = [ 'openai', 'azure-openai', 'anthropic', + 'azure-anthropic', 'google', 'deepseek', 'xai', diff --git a/apps/sim/lib/copilot/types.ts b/apps/sim/lib/copilot/types.ts index 6ed813308..68e097039 100644 --- a/apps/sim/lib/copilot/types.ts +++ b/apps/sim/lib/copilot/types.ts @@ -147,6 +147,13 @@ export type CopilotProviderConfig = apiVersion?: string endpoint?: string } + | { + provider: 'azure-anthropic' + model: string + apiKey?: string + apiVersion?: string + endpoint?: string + } | { provider: 'vertex' model: string @@ -155,7 +162,7 @@ export type CopilotProviderConfig = vertexLocation?: string } | { - provider: Exclude + provider: Exclude model?: string apiKey?: string } diff --git a/apps/sim/lib/core/config/env.ts b/apps/sim/lib/core/config/env.ts index 8440de3bc..48e1a630d 100644 --- a/apps/sim/lib/core/config/env.ts +++ b/apps/sim/lib/core/config/env.ts @@ -95,6 +95,9 @@ export const env = createEnv({ AZURE_OPENAI_ENDPOINT: z.string().url().optional(), // Shared Azure OpenAI service endpoint AZURE_OPENAI_API_VERSION: z.string().optional(), // Shared Azure OpenAI API version AZURE_OPENAI_API_KEY: z.string().min(1).optional(), // Shared Azure OpenAI API key + AZURE_ANTHROPIC_ENDPOINT: z.string().url().optional(), // Azure Anthropic service endpoint + AZURE_ANTHROPIC_API_KEY: z.string().min(1).optional(), // Azure Anthropic API key + AZURE_ANTHROPIC_API_VERSION: z.string().min(1).optional(), // Azure Anthropic API version (e.g. 2023-06-01) KB_OPENAI_MODEL_NAME: z.string().optional(), // Knowledge base OpenAI model name (works with both regular OpenAI and Azure OpenAI) WAND_OPENAI_MODEL_NAME: z.string().optional(), // Wand generation OpenAI model name (works with both regular OpenAI and Azure OpenAI) OCR_AZURE_ENDPOINT: z.string().url().optional(), // Azure Mistral OCR service endpoint diff --git a/apps/sim/lib/guardrails/validate_hallucination.ts b/apps/sim/lib/guardrails/validate_hallucination.ts index b2668f248..48a91fb81 100644 --- a/apps/sim/lib/guardrails/validate_hallucination.ts +++ b/apps/sim/lib/guardrails/validate_hallucination.ts @@ -1,7 +1,11 @@ +import { db } from '@sim/db' +import { account } from '@sim/db/schema' import { createLogger } from '@sim/logger' +import { eq } from 'drizzle-orm' import { getBaseUrl } from '@/lib/core/utils/urls' +import { refreshTokenIfNeeded } from '@/app/api/auth/oauth/utils' import { executeProviderRequest } from '@/providers' -import { getApiKey, getProviderFromModel } from '@/providers/utils' +import { getProviderFromModel } from '@/providers/utils' const logger = createLogger('HallucinationValidator') @@ -19,7 +23,18 @@ export interface HallucinationValidationInput { topK: number // Number of chunks to retrieve, default 10 model: string apiKey?: string + providerCredentials?: { + azureEndpoint?: string + azureApiVersion?: string + vertexProject?: string + vertexLocation?: string + vertexCredential?: string + bedrockAccessKeyId?: string + bedrockSecretKey?: string + bedrockRegion?: string + } workflowId?: string + workspaceId?: string requestId: string } @@ -89,7 +104,9 @@ async function scoreHallucinationWithLLM( userInput: string, ragContext: string[], model: string, - apiKey: string, + apiKey: string | undefined, + providerCredentials: HallucinationValidationInput['providerCredentials'], + workspaceId: string | undefined, requestId: string ): Promise<{ score: number; reasoning: string }> { try { @@ -127,6 +144,23 @@ Evaluate the consistency and provide your score and reasoning in JSON format.` const providerId = getProviderFromModel(model) + let finalApiKey: string | undefined = apiKey + if (providerId === 'vertex' && providerCredentials?.vertexCredential) { + const credential = await db.query.account.findFirst({ + where: eq(account.id, providerCredentials.vertexCredential), + }) + if (credential) { + const { accessToken } = await refreshTokenIfNeeded( + requestId, + credential, + providerCredentials.vertexCredential + ) + if (accessToken) { + finalApiKey = accessToken + } + } + } + const response = await executeProviderRequest(providerId, { model, systemPrompt, @@ -137,7 +171,15 @@ Evaluate the consistency and provide your score and reasoning in JSON format.` }, ], temperature: 0.1, // Low temperature for consistent scoring - apiKey, + apiKey: finalApiKey, + azureEndpoint: providerCredentials?.azureEndpoint, + azureApiVersion: providerCredentials?.azureApiVersion, + vertexProject: providerCredentials?.vertexProject, + vertexLocation: providerCredentials?.vertexLocation, + bedrockAccessKeyId: providerCredentials?.bedrockAccessKeyId, + bedrockSecretKey: providerCredentials?.bedrockSecretKey, + bedrockRegion: providerCredentials?.bedrockRegion, + workspaceId, }) if (response instanceof ReadableStream || ('stream' in response && 'execution' in response)) { @@ -184,8 +226,18 @@ Evaluate the consistency and provide your score and reasoning in JSON format.` export async function validateHallucination( input: HallucinationValidationInput ): Promise { - const { userInput, knowledgeBaseId, threshold, topK, model, apiKey, workflowId, requestId } = - input + const { + userInput, + knowledgeBaseId, + threshold, + topK, + model, + apiKey, + providerCredentials, + workflowId, + workspaceId, + requestId, + } = input try { if (!userInput || userInput.trim().length === 0) { @@ -202,17 +254,6 @@ export async function validateHallucination( } } - let finalApiKey: string - try { - const providerId = getProviderFromModel(model) - finalApiKey = getApiKey(providerId, model, apiKey) - } catch (error: any) { - return { - passed: false, - error: `API key error: ${error.message}`, - } - } - // Step 1: Query knowledge base with RAG const ragContext = await queryKnowledgeBase( knowledgeBaseId, @@ -234,7 +275,9 @@ export async function validateHallucination( userInput, ragContext, model, - finalApiKey, + apiKey, + providerCredentials, + workspaceId, requestId ) diff --git a/apps/sim/lib/tokenization/constants.ts b/apps/sim/lib/tokenization/constants.ts index 010ef4743..a10b1995d 100644 --- a/apps/sim/lib/tokenization/constants.ts +++ b/apps/sim/lib/tokenization/constants.ts @@ -21,6 +21,11 @@ export const TOKENIZATION_CONFIG = { confidence: 'high', supportedMethods: ['heuristic', 'fallback'], }, + 'azure-anthropic': { + avgCharsPerToken: 4.5, + confidence: 'high', + supportedMethods: ['heuristic', 'fallback'], + }, google: { avgCharsPerToken: 5, confidence: 'medium', diff --git a/apps/sim/lib/tokenization/estimators.ts b/apps/sim/lib/tokenization/estimators.ts index 53ce71965..01aed1c1e 100644 --- a/apps/sim/lib/tokenization/estimators.ts +++ b/apps/sim/lib/tokenization/estimators.ts @@ -204,6 +204,7 @@ export function estimateTokenCount(text: string, providerId?: string): TokenEsti estimatedTokens = estimateOpenAITokens(text) break case 'anthropic': + case 'azure-anthropic': estimatedTokens = estimateAnthropicTokens(text) break case 'google': diff --git a/apps/sim/providers/azure-anthropic/index.ts b/apps/sim/providers/azure-anthropic/index.ts index efb131be1..721e36339 100644 --- a/apps/sim/providers/azure-anthropic/index.ts +++ b/apps/sim/providers/azure-anthropic/index.ts @@ -35,6 +35,8 @@ export const azureAnthropicProvider: ProviderConfig = { // The SDK appends /v1/messages automatically const baseURL = `${request.azureEndpoint.replace(/\/$/, '')}/anthropic` + const anthropicVersion = request.azureApiVersion || '2023-06-01' + return executeAnthropicProviderRequest( { ...request, @@ -49,7 +51,7 @@ export const azureAnthropicProvider: ProviderConfig = { apiKey, defaultHeaders: { 'api-key': apiKey, - 'anthropic-version': '2023-06-01', + 'anthropic-version': anthropicVersion, ...(useNativeStructuredOutputs ? { 'anthropic-beta': 'structured-outputs-2025-11-13' } : {}), diff --git a/apps/sim/tools/guardrails/validate.ts b/apps/sim/tools/guardrails/validate.ts index f791fa89c..124795c44 100644 --- a/apps/sim/tools/guardrails/validate.ts +++ b/apps/sim/tools/guardrails/validate.ts @@ -9,6 +9,14 @@ export interface GuardrailsValidateInput { topK?: string model?: string apiKey?: string + azureEndpoint?: string + azureApiVersion?: string + vertexProject?: string + vertexLocation?: string + vertexCredential?: string + bedrockAccessKeyId?: string + bedrockSecretKey?: string + bedrockRegion?: string piiEntityTypes?: string[] piiMode?: string piiLanguage?: string @@ -166,6 +174,14 @@ export const guardrailsValidateTool: ToolConfig Date: Fri, 6 Feb 2026 18:34:03 -0800 Subject: [PATCH 3/8] fix(function): isolated-vm worker pool to prevent single-worker bottleneck + execution user id resolution (#3155) * fix(executor): isolated-vm worker pool to prevent single-worker bottleneck * chore(helm): add isolated-vm worker pool env vars to values.yaml * fix(userid): resolution for fair scheduling * add fallback back * add to helm charts * remove constant fallbacks * fix * address bugbot comments * fix fallbacks * one more bugbot comment --------- Co-authored-by: Vikhyath Mondreti --- apps/sim/app/api/function/execute/route.ts | 2 + .../app/api/workflows/[id]/execute/route.ts | 6 + .../executor/handlers/agent/agent-handler.ts | 1 + apps/sim/executor/handlers/api/api-handler.ts | 1 + .../handlers/condition/condition-handler.ts | 1 + .../handlers/function/function-handler.ts | 1 + .../handlers/generic/generic-handler.ts | 1 + .../human-in-the-loop-handler.ts | 1 + apps/sim/executor/orchestrators/loop.ts | 2 + apps/sim/lib/auth/hybrid.ts | 32 +- apps/sim/lib/core/config/env.ts | 18 + .../core/security/input-validation.server.ts | 22 +- apps/sim/lib/execution/isolated-vm-worker.cjs | 54 +- apps/sim/lib/execution/isolated-vm.test.ts | 500 ++++++++ apps/sim/lib/execution/isolated-vm.ts | 1042 ++++++++++++++--- apps/sim/lib/execution/preprocessing.ts | 11 +- apps/sim/tools/index.ts | 20 +- apps/sim/tools/utils.ts | 12 +- helm/sim/values.yaml | 20 +- 19 files changed, 1530 insertions(+), 217 deletions(-) create mode 100644 apps/sim/lib/execution/isolated-vm.test.ts diff --git a/apps/sim/app/api/function/execute/route.ts b/apps/sim/app/api/function/execute/route.ts index 4ccbd8d7c..441bf788d 100644 --- a/apps/sim/app/api/function/execute/route.ts +++ b/apps/sim/app/api/function/execute/route.ts @@ -845,6 +845,8 @@ export async function POST(req: NextRequest) { contextVariables, timeoutMs: timeout, requestId, + ownerKey: `user:${auth.userId}`, + ownerWeight: 1, }) const executionTime = Date.now() - startTime diff --git a/apps/sim/app/api/workflows/[id]/execute/route.ts b/apps/sim/app/api/workflows/[id]/execute/route.ts index 7c4cdc9db..06984a3e2 100644 --- a/apps/sim/app/api/workflows/[id]/execute/route.ts +++ b/apps/sim/app/api/workflows/[id]/execute/route.ts @@ -325,6 +325,11 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id: requestId ) + // Client-side sessions and personal API keys bill/permission-check the + // authenticated user, not the workspace billed account. + const useAuthenticatedUserAsActor = + isClientSession || (auth.authType === 'api_key' && auth.apiKeyType === 'personal') + const preprocessResult = await preprocessExecution({ workflowId, userId, @@ -334,6 +339,7 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id: checkDeployment: !shouldUseDraftState, loggingSession, useDraftState: shouldUseDraftState, + useAuthenticatedUserAsActor, }) if (!preprocessResult.success) { diff --git a/apps/sim/executor/handlers/agent/agent-handler.ts b/apps/sim/executor/handlers/agent/agent-handler.ts index b4c2794a8..a1f0cee0d 100644 --- a/apps/sim/executor/handlers/agent/agent-handler.ts +++ b/apps/sim/executor/handlers/agent/agent-handler.ts @@ -326,6 +326,7 @@ export class AgentBlockHandler implements BlockHandler { _context: { workflowId: ctx.workflowId, workspaceId: ctx.workspaceId, + userId: ctx.userId, isDeployedContext: ctx.isDeployedContext, }, }, diff --git a/apps/sim/executor/handlers/api/api-handler.ts b/apps/sim/executor/handlers/api/api-handler.ts index 562067cdf..83c710bef 100644 --- a/apps/sim/executor/handlers/api/api-handler.ts +++ b/apps/sim/executor/handlers/api/api-handler.ts @@ -72,6 +72,7 @@ export class ApiBlockHandler implements BlockHandler { workflowId: ctx.workflowId, workspaceId: ctx.workspaceId, executionId: ctx.executionId, + userId: ctx.userId, isDeployedContext: ctx.isDeployedContext, }, }, diff --git a/apps/sim/executor/handlers/condition/condition-handler.ts b/apps/sim/executor/handlers/condition/condition-handler.ts index 96fe0db4b..0c88e0e78 100644 --- a/apps/sim/executor/handlers/condition/condition-handler.ts +++ b/apps/sim/executor/handlers/condition/condition-handler.ts @@ -48,6 +48,7 @@ export async function evaluateConditionExpression( _context: { workflowId: ctx.workflowId, workspaceId: ctx.workspaceId, + userId: ctx.userId, isDeployedContext: ctx.isDeployedContext, }, }, diff --git a/apps/sim/executor/handlers/function/function-handler.ts b/apps/sim/executor/handlers/function/function-handler.ts index 624a262d3..d8e1209e5 100644 --- a/apps/sim/executor/handlers/function/function-handler.ts +++ b/apps/sim/executor/handlers/function/function-handler.ts @@ -39,6 +39,7 @@ export class FunctionBlockHandler implements BlockHandler { _context: { workflowId: ctx.workflowId, workspaceId: ctx.workspaceId, + userId: ctx.userId, isDeployedContext: ctx.isDeployedContext, }, }, diff --git a/apps/sim/executor/handlers/generic/generic-handler.ts b/apps/sim/executor/handlers/generic/generic-handler.ts index 558a37dee..c6a6b7e9f 100644 --- a/apps/sim/executor/handlers/generic/generic-handler.ts +++ b/apps/sim/executor/handlers/generic/generic-handler.ts @@ -66,6 +66,7 @@ export class GenericBlockHandler implements BlockHandler { workflowId: ctx.workflowId, workspaceId: ctx.workspaceId, executionId: ctx.executionId, + userId: ctx.userId, isDeployedContext: ctx.isDeployedContext, }, }, diff --git a/apps/sim/executor/handlers/human-in-the-loop/human-in-the-loop-handler.ts b/apps/sim/executor/handlers/human-in-the-loop/human-in-the-loop-handler.ts index dd53a0a0e..2a23c622c 100644 --- a/apps/sim/executor/handlers/human-in-the-loop/human-in-the-loop-handler.ts +++ b/apps/sim/executor/handlers/human-in-the-loop/human-in-the-loop-handler.ts @@ -605,6 +605,7 @@ export class HumanInTheLoopBlockHandler implements BlockHandler { _context: { workflowId: ctx.workflowId, workspaceId: ctx.workspaceId, + userId: ctx.userId, isDeployedContext: ctx.isDeployedContext, }, blockData: blockDataWithPause, diff --git a/apps/sim/executor/orchestrators/loop.ts b/apps/sim/executor/orchestrators/loop.ts index 8bdf8edd2..456838d1e 100644 --- a/apps/sim/executor/orchestrators/loop.ts +++ b/apps/sim/executor/orchestrators/loop.ts @@ -511,6 +511,8 @@ export class LoopOrchestrator { contextVariables: {}, timeoutMs: LOOP_CONDITION_TIMEOUT_MS, requestId, + ownerKey: `user:${ctx.userId}`, + ownerWeight: 1, }) if (vmResult.error) { diff --git a/apps/sim/lib/auth/hybrid.ts b/apps/sim/lib/auth/hybrid.ts index 2b49d7158..1c34286f6 100644 --- a/apps/sim/lib/auth/hybrid.ts +++ b/apps/sim/lib/auth/hybrid.ts @@ -1,7 +1,4 @@ -import { db } from '@sim/db' -import { workflow } from '@sim/db/schema' import { createLogger } from '@sim/logger' -import { eq } from 'drizzle-orm' import type { NextRequest } from 'next/server' import { authenticateApiKeyFromHeader, updateApiKeyLastUsed } from '@/lib/api-key/service' import { getSession } from '@/lib/auth' @@ -13,35 +10,33 @@ export interface AuthResult { success: boolean userId?: string authType?: 'session' | 'api_key' | 'internal_jwt' + apiKeyType?: 'personal' | 'workspace' error?: string } /** * Resolves userId from a verified internal JWT token. - * Extracts workflowId/userId from URL params or POST body, then looks up userId if needed. + * Extracts userId from the JWT payload, URL search params, or POST body. */ async function resolveUserFromJwt( request: NextRequest, verificationUserId: string | null, options: { requireWorkflowId?: boolean } ): Promise { - let workflowId: string | null = null let userId: string | null = verificationUserId - const { searchParams } = new URL(request.url) - workflowId = searchParams.get('workflowId') if (!userId) { + const { searchParams } = new URL(request.url) userId = searchParams.get('userId') } - if (!workflowId && !userId && request.method === 'POST') { + if (!userId && request.method === 'POST') { try { const clonedRequest = request.clone() const bodyText = await clonedRequest.text() if (bodyText) { const body = JSON.parse(bodyText) - workflowId = body.workflowId || body._context?.workflowId - userId = userId || body.userId || body._context?.userId + userId = body.userId || body._context?.userId || null } } catch { // Ignore JSON parse errors @@ -52,22 +47,8 @@ async function resolveUserFromJwt( return { success: true, userId, authType: 'internal_jwt' } } - if (workflowId) { - const [workflowData] = await db - .select({ userId: workflow.userId }) - .from(workflow) - .where(eq(workflow.id, workflowId)) - .limit(1) - - if (!workflowData) { - return { success: false, error: 'Workflow not found' } - } - - return { success: true, userId: workflowData.userId, authType: 'internal_jwt' } - } - if (options.requireWorkflowId !== false) { - return { success: false, error: 'workflowId or userId required for internal JWT calls' } + return { success: false, error: 'userId required for internal JWT calls' } } return { success: true, authType: 'internal_jwt' } @@ -222,6 +203,7 @@ export async function checkHybridAuth( success: true, userId: result.userId!, authType: 'api_key', + apiKeyType: result.keyType, } } diff --git a/apps/sim/lib/core/config/env.ts b/apps/sim/lib/core/config/env.ts index 48e1a630d..685cf0e9d 100644 --- a/apps/sim/lib/core/config/env.ts +++ b/apps/sim/lib/core/config/env.ts @@ -183,6 +183,24 @@ export const env = createEnv({ EXECUTION_TIMEOUT_ASYNC_TEAM: z.string().optional().default('5400'), // 90 minutes EXECUTION_TIMEOUT_ASYNC_ENTERPRISE: z.string().optional().default('5400'), // 90 minutes + // Isolated-VM Worker Pool Configuration + IVM_POOL_SIZE: z.string().optional().default('4'), // Max worker processes in pool + IVM_MAX_CONCURRENT: z.string().optional().default('10000'), // Max concurrent executions globally + IVM_MAX_PER_WORKER: z.string().optional().default('2500'), // Max concurrent executions per worker + IVM_WORKER_IDLE_TIMEOUT_MS: z.string().optional().default('60000'), // Worker idle cleanup timeout (ms) + IVM_MAX_QUEUE_SIZE: z.string().optional().default('10000'), // Max pending queued executions in memory + IVM_MAX_FETCH_RESPONSE_BYTES: z.string().optional().default('8388608'),// Max bytes read from sandbox fetch responses + IVM_MAX_FETCH_RESPONSE_CHARS: z.string().optional().default('4000000'),// Max chars returned to sandbox from fetch body + IVM_MAX_FETCH_OPTIONS_JSON_CHARS: z.string().optional().default('262144'), // Max JSON payload size for sandbox fetch options + IVM_MAX_FETCH_URL_LENGTH: z.string().optional().default('8192'), // Max URL length accepted by sandbox fetch + IVM_MAX_STDOUT_CHARS: z.string().optional().default('200000'), // Max captured stdout characters per execution + IVM_MAX_ACTIVE_PER_OWNER: z.string().optional().default('200'), // Max active executions per owner (per process) + IVM_MAX_QUEUED_PER_OWNER: z.string().optional().default('2000'), // Max queued executions per owner (per process) + IVM_MAX_OWNER_WEIGHT: z.string().optional().default('5'), // Max accepted weight for weighted owner scheduling + IVM_DISTRIBUTED_MAX_INFLIGHT_PER_OWNER:z.string().optional().default('2200'), // Max owner in-flight leases across replicas + IVM_DISTRIBUTED_LEASE_MIN_TTL_MS: z.string().optional().default('120000'), // Min TTL for distributed in-flight leases (ms) + IVM_QUEUE_TIMEOUT_MS: z.string().optional().default('300000'), // Max queue wait before rejection (ms) + // Knowledge Base Processing Configuration - Shared across all processing methods KB_CONFIG_MAX_DURATION: z.number().optional().default(600), // Max processing duration in seconds (10 minutes) KB_CONFIG_MAX_ATTEMPTS: z.number().optional().default(3), // Max retry attempts diff --git a/apps/sim/lib/core/security/input-validation.server.ts b/apps/sim/lib/core/security/input-validation.server.ts index e8c0ec861..2a912240c 100644 --- a/apps/sim/lib/core/security/input-validation.server.ts +++ b/apps/sim/lib/core/security/input-validation.server.ts @@ -103,6 +103,7 @@ export interface SecureFetchOptions { body?: string | Buffer | Uint8Array timeout?: number maxRedirects?: number + maxResponseBytes?: number } export class SecureFetchHeaders { @@ -165,6 +166,7 @@ export async function secureFetchWithPinnedIP( redirectCount = 0 ): Promise { const maxRedirects = options.maxRedirects ?? DEFAULT_MAX_REDIRECTS + const maxResponseBytes = options.maxResponseBytes return new Promise((resolve, reject) => { const parsed = new URL(url) @@ -237,14 +239,32 @@ export async function secureFetchWithPinnedIP( } const chunks: Buffer[] = [] + let totalBytes = 0 + let responseTerminated = false - res.on('data', (chunk: Buffer) => chunks.push(chunk)) + res.on('data', (chunk: Buffer) => { + if (responseTerminated) return + + totalBytes += chunk.length + if ( + typeof maxResponseBytes === 'number' && + maxResponseBytes > 0 && + totalBytes > maxResponseBytes + ) { + responseTerminated = true + res.destroy(new Error(`Response exceeded maximum size of ${maxResponseBytes} bytes`)) + return + } + + chunks.push(chunk) + }) res.on('error', (error) => { reject(error) }) res.on('end', () => { + if (responseTerminated) return const bodyBuffer = Buffer.concat(chunks) const body = bodyBuffer.toString('utf-8') const headersRecord: Record = {} diff --git a/apps/sim/lib/execution/isolated-vm-worker.cjs b/apps/sim/lib/execution/isolated-vm-worker.cjs index 3deb76166..2641b80e1 100644 --- a/apps/sim/lib/execution/isolated-vm-worker.cjs +++ b/apps/sim/lib/execution/isolated-vm-worker.cjs @@ -9,6 +9,21 @@ const USER_CODE_START_LINE = 4 const pendingFetches = new Map() let fetchIdCounter = 0 const FETCH_TIMEOUT_MS = 300000 // 5 minutes +const MAX_STDOUT_CHARS = Number.parseInt(process.env.IVM_MAX_STDOUT_CHARS || '', 10) || 200000 +const MAX_FETCH_OPTIONS_JSON_CHARS = + Number.parseInt(process.env.IVM_MAX_FETCH_OPTIONS_JSON_CHARS || '', 10) || 256 * 1024 + +function stringifyLogValue(value) { + if (typeof value !== 'object' || value === null) { + return String(value) + } + + try { + return JSON.stringify(value) + } catch { + return '[unserializable]' + } +} /** * Extract line and column from error stack or message @@ -101,8 +116,32 @@ function convertToCompatibleError(errorInfo, userCode) { async function executeCode(request) { const { code, params, envVars, contextVariables, timeoutMs, requestId } = request const stdoutChunks = [] + let stdoutLength = 0 + let stdoutTruncated = false let isolate = null + const appendStdout = (line) => { + if (stdoutTruncated || !line) return + + const remaining = MAX_STDOUT_CHARS - stdoutLength + if (remaining <= 0) { + stdoutTruncated = true + stdoutChunks.push('[stdout truncated]\n') + return + } + + if (line.length <= remaining) { + stdoutChunks.push(line) + stdoutLength += line.length + return + } + + stdoutChunks.push(line.slice(0, remaining)) + stdoutChunks.push('\n[stdout truncated]\n') + stdoutLength = MAX_STDOUT_CHARS + stdoutTruncated = true + } + try { isolate = new ivm.Isolate({ memoryLimit: 128 }) const context = await isolate.createContext() @@ -111,18 +150,14 @@ async function executeCode(request) { await jail.set('global', jail.derefInto()) const logCallback = new ivm.Callback((...args) => { - const message = args - .map((arg) => (typeof arg === 'object' ? JSON.stringify(arg) : String(arg))) - .join(' ') - stdoutChunks.push(`${message}\n`) + const message = args.map((arg) => stringifyLogValue(arg)).join(' ') + appendStdout(`${message}\n`) }) await jail.set('__log', logCallback) const errorCallback = new ivm.Callback((...args) => { - const message = args - .map((arg) => (typeof arg === 'object' ? JSON.stringify(arg) : String(arg))) - .join(' ') - stdoutChunks.push(`ERROR: ${message}\n`) + const message = args.map((arg) => stringifyLogValue(arg)).join(' ') + appendStdout(`ERROR: ${message}\n`) }) await jail.set('__error', errorCallback) @@ -178,6 +213,9 @@ async function executeCode(request) { } catch { throw new Error('fetch options must be JSON-serializable'); } + if (optionsJson.length > ${MAX_FETCH_OPTIONS_JSON_CHARS}) { + throw new Error('fetch options exceed maximum payload size'); + } } const resultJson = await __fetchRef.apply(undefined, [url, optionsJson], { result: { promise: true } }); let result; diff --git a/apps/sim/lib/execution/isolated-vm.test.ts b/apps/sim/lib/execution/isolated-vm.test.ts new file mode 100644 index 000000000..17fb20c0d --- /dev/null +++ b/apps/sim/lib/execution/isolated-vm.test.ts @@ -0,0 +1,500 @@ +import { EventEmitter } from 'node:events' +import { afterEach, describe, expect, it, vi } from 'vitest' + +type MockProc = EventEmitter & { + connected: boolean + stderr: EventEmitter + send: (message: unknown) => boolean + kill: () => boolean +} + +type SpawnFactory = () => MockProc +type RedisEval = (...args: any[]) => unknown | Promise +type SecureFetchImpl = (...args: any[]) => unknown | Promise + +function createBaseProc(): MockProc { + const proc = new EventEmitter() as MockProc + proc.connected = true + proc.stderr = new EventEmitter() + proc.send = () => true + proc.kill = () => { + if (!proc.connected) return true + proc.connected = false + setImmediate(() => proc.emit('exit', 0)) + return true + } + return proc +} + +function createStartupFailureProc(): MockProc { + const proc = createBaseProc() + setImmediate(() => { + proc.connected = false + proc.emit('exit', 1) + }) + return proc +} + +function createReadyProc(result: unknown): MockProc { + const proc = createBaseProc() + proc.send = (message: unknown) => { + const msg = message as { type?: string; executionId?: number } + if (msg.type === 'execute') { + setImmediate(() => { + proc.emit('message', { + type: 'result', + executionId: msg.executionId, + result: { result, stdout: '' }, + }) + }) + } + return true + } + setImmediate(() => proc.emit('message', { type: 'ready' })) + return proc +} + +function createReadyProcWithDelay(delayMs: number): MockProc { + const proc = createBaseProc() + proc.send = (message: unknown) => { + const msg = message as { type?: string; executionId?: number; request?: { requestId?: string } } + if (msg.type === 'execute') { + setTimeout(() => { + proc.emit('message', { + type: 'result', + executionId: msg.executionId, + result: { result: msg.request?.requestId ?? 'unknown', stdout: '' }, + }) + }, delayMs) + } + return true + } + setImmediate(() => proc.emit('message', { type: 'ready' })) + return proc +} + +function createReadyFetchProxyProc(fetchMessage: { url: string; optionsJson?: string }): MockProc { + const proc = createBaseProc() + let currentExecutionId = 0 + + proc.send = (message: unknown) => { + const msg = message as { type?: string; executionId?: number; request?: { requestId?: string } } + + if (msg.type === 'execute') { + currentExecutionId = msg.executionId ?? 0 + setImmediate(() => { + proc.emit('message', { + type: 'fetch', + fetchId: 1, + requestId: msg.request?.requestId ?? 'fetch-test', + url: fetchMessage.url, + optionsJson: fetchMessage.optionsJson, + }) + }) + return true + } + + if (msg.type === 'fetchResponse') { + const fetchResponse = message as { response?: string } + setImmediate(() => { + proc.emit('message', { + type: 'result', + executionId: currentExecutionId, + result: { result: fetchResponse.response ?? '', stdout: '' }, + }) + }) + return true + } + + return true + } + + setImmediate(() => proc.emit('message', { type: 'ready' })) + return proc +} + +async function loadExecutionModule(options: { + envOverrides?: Record + spawns: SpawnFactory[] + redisEvalImpl?: RedisEval + secureFetchImpl?: SecureFetchImpl +}) { + vi.resetModules() + + const spawnQueue = [...options.spawns] + const spawnMock = vi.fn(() => { + const next = spawnQueue.shift() + if (!next) { + throw new Error('No mock spawn factory configured') + } + return next() as any + }) + + vi.doMock('@sim/logger', () => ({ + createLogger: () => ({ + info: vi.fn(), + warn: vi.fn(), + error: vi.fn(), + }), + })) + + const secureFetchMock = vi.fn( + options.secureFetchImpl ?? + (async () => ({ + ok: true, + status: 200, + statusText: 'OK', + headers: new Map(), + text: async () => '', + json: async () => ({}), + arrayBuffer: async () => new ArrayBuffer(0), + })) + ) + vi.doMock('@/lib/core/security/input-validation.server', () => ({ + secureFetchWithValidation: secureFetchMock, + })) + + vi.doMock('@/lib/core/config/env', () => ({ + env: { + IVM_POOL_SIZE: '1', + IVM_MAX_CONCURRENT: '100', + IVM_MAX_PER_WORKER: '100', + IVM_WORKER_IDLE_TIMEOUT_MS: '60000', + IVM_MAX_QUEUE_SIZE: '10', + IVM_MAX_ACTIVE_PER_OWNER: '100', + IVM_MAX_QUEUED_PER_OWNER: '10', + IVM_MAX_OWNER_WEIGHT: '5', + IVM_DISTRIBUTED_MAX_INFLIGHT_PER_OWNER: '100', + IVM_DISTRIBUTED_LEASE_MIN_TTL_MS: '1000', + IVM_QUEUE_TIMEOUT_MS: '1000', + ...(options.envOverrides ?? {}), + }, + })) + + const redisEval = options.redisEvalImpl ? vi.fn(options.redisEvalImpl) : undefined + vi.doMock('@/lib/core/config/redis', () => ({ + getRedisClient: vi.fn(() => + redisEval + ? ({ + eval: redisEval, + } as any) + : null + ), + })) + + vi.doMock('node:child_process', () => ({ + execSync: vi.fn(() => Buffer.from('v23.11.0')), + spawn: spawnMock, + })) + + const mod = await import('./isolated-vm') + return { ...mod, spawnMock, secureFetchMock } +} + +describe('isolated-vm scheduler', () => { + afterEach(() => { + vi.restoreAllMocks() + vi.resetModules() + }) + + it('recovers from an initial spawn failure and drains queued work', async () => { + const { executeInIsolatedVM, spawnMock } = await loadExecutionModule({ + spawns: [createStartupFailureProc, () => createReadyProc('ok')], + }) + + const result = await executeInIsolatedVM({ + code: 'return "ok"', + params: {}, + envVars: {}, + contextVariables: {}, + timeoutMs: 100, + requestId: 'req-1', + }) + + expect(result.error).toBeUndefined() + expect(result.result).toBe('ok') + expect(spawnMock).toHaveBeenCalledTimes(2) + }) + + it('rejects new requests when the queue is full', async () => { + const { executeInIsolatedVM } = await loadExecutionModule({ + envOverrides: { + IVM_MAX_QUEUE_SIZE: '1', + IVM_QUEUE_TIMEOUT_MS: '200', + }, + spawns: [createStartupFailureProc, createStartupFailureProc, createStartupFailureProc], + }) + + const firstPromise = executeInIsolatedVM({ + code: 'return 1', + params: {}, + envVars: {}, + contextVariables: {}, + timeoutMs: 100, + requestId: 'req-2', + ownerKey: 'user:a', + }) + + await new Promise((resolve) => setTimeout(resolve, 25)) + + const second = await executeInIsolatedVM({ + code: 'return 2', + params: {}, + envVars: {}, + contextVariables: {}, + timeoutMs: 100, + requestId: 'req-3', + ownerKey: 'user:b', + }) + + expect(second.error?.message).toContain('at capacity') + + const first = await firstPromise + expect(first.error?.message).toContain('timed out waiting') + }) + + it('enforces per-owner queued limit', async () => { + const { executeInIsolatedVM } = await loadExecutionModule({ + envOverrides: { + IVM_MAX_QUEUED_PER_OWNER: '1', + IVM_QUEUE_TIMEOUT_MS: '200', + }, + spawns: [createStartupFailureProc, createStartupFailureProc, createStartupFailureProc], + }) + + const firstPromise = executeInIsolatedVM({ + code: 'return 1', + params: {}, + envVars: {}, + contextVariables: {}, + timeoutMs: 100, + requestId: 'req-4', + ownerKey: 'user:hog', + }) + + await new Promise((resolve) => setTimeout(resolve, 25)) + + const second = await executeInIsolatedVM({ + code: 'return 2', + params: {}, + envVars: {}, + contextVariables: {}, + timeoutMs: 100, + requestId: 'req-5', + ownerKey: 'user:hog', + }) + + expect(second.error?.message).toContain('Too many concurrent') + + const first = await firstPromise + expect(first.error?.message).toContain('timed out waiting') + }) + + it('enforces distributed owner in-flight lease limit when Redis is configured', async () => { + const { executeInIsolatedVM } = await loadExecutionModule({ + envOverrides: { + IVM_DISTRIBUTED_MAX_INFLIGHT_PER_OWNER: '1', + REDIS_URL: 'redis://localhost:6379', + }, + spawns: [() => createReadyProc('ok')], + redisEvalImpl: (...args: any[]) => { + const script = String(args[0] ?? '') + if (script.includes('ZREMRANGEBYSCORE')) { + return 0 + } + return 1 + }, + }) + + const result = await executeInIsolatedVM({ + code: 'return "blocked"', + params: {}, + envVars: {}, + contextVariables: {}, + timeoutMs: 100, + requestId: 'req-6', + ownerKey: 'user:distributed', + }) + + expect(result.error?.message).toContain('Too many concurrent') + }) + + it('fails closed when Redis is configured but unavailable', async () => { + const { executeInIsolatedVM } = await loadExecutionModule({ + envOverrides: { + REDIS_URL: 'redis://localhost:6379', + }, + spawns: [() => createReadyProc('ok')], + }) + + const result = await executeInIsolatedVM({ + code: 'return "blocked"', + params: {}, + envVars: {}, + contextVariables: {}, + timeoutMs: 100, + requestId: 'req-7', + ownerKey: 'user:redis-down', + }) + + expect(result.error?.message).toContain('temporarily unavailable') + }) + + it('fails closed when Redis lease evaluation errors', async () => { + const { executeInIsolatedVM } = await loadExecutionModule({ + envOverrides: { + REDIS_URL: 'redis://localhost:6379', + }, + spawns: [() => createReadyProc('ok')], + redisEvalImpl: (...args: any[]) => { + const script = String(args[0] ?? '') + if (script.includes('ZREMRANGEBYSCORE')) { + throw new Error('redis timeout') + } + return 1 + }, + }) + + const result = await executeInIsolatedVM({ + code: 'return "blocked"', + params: {}, + envVars: {}, + contextVariables: {}, + timeoutMs: 100, + requestId: 'req-8', + ownerKey: 'user:redis-error', + }) + + expect(result.error?.message).toContain('temporarily unavailable') + }) + + it('applies weighted owner scheduling when draining queued executions', async () => { + const { executeInIsolatedVM } = await loadExecutionModule({ + envOverrides: { + IVM_MAX_PER_WORKER: '1', + }, + spawns: [() => createReadyProcWithDelay(10)], + }) + + const completionOrder: string[] = [] + const pushCompletion = (label: string) => (res: { result: unknown }) => { + completionOrder.push(String(res.result ?? label)) + return res + } + + const p1 = executeInIsolatedVM({ + code: 'return 1', + params: {}, + envVars: {}, + contextVariables: {}, + timeoutMs: 500, + requestId: 'a-1', + ownerKey: 'user:a', + ownerWeight: 2, + }).then(pushCompletion('a-1')) + + const p2 = executeInIsolatedVM({ + code: 'return 2', + params: {}, + envVars: {}, + contextVariables: {}, + timeoutMs: 500, + requestId: 'a-2', + ownerKey: 'user:a', + ownerWeight: 2, + }).then(pushCompletion('a-2')) + + const p3 = executeInIsolatedVM({ + code: 'return 3', + params: {}, + envVars: {}, + contextVariables: {}, + timeoutMs: 500, + requestId: 'b-1', + ownerKey: 'user:b', + ownerWeight: 1, + }).then(pushCompletion('b-1')) + + const p4 = executeInIsolatedVM({ + code: 'return 4', + params: {}, + envVars: {}, + contextVariables: {}, + timeoutMs: 500, + requestId: 'b-2', + ownerKey: 'user:b', + ownerWeight: 1, + }).then(pushCompletion('b-2')) + + const p5 = executeInIsolatedVM({ + code: 'return 5', + params: {}, + envVars: {}, + contextVariables: {}, + timeoutMs: 500, + requestId: 'a-3', + ownerKey: 'user:a', + ownerWeight: 2, + }).then(pushCompletion('a-3')) + + await Promise.all([p1, p2, p3, p4, p5]) + + expect(completionOrder.slice(0, 3)).toEqual(['a-1', 'a-2', 'a-3']) + expect(completionOrder).toEqual(['a-1', 'a-2', 'a-3', 'b-1', 'b-2']) + }) + + it('rejects oversized fetch options payloads before outbound call', async () => { + const { executeInIsolatedVM, secureFetchMock } = await loadExecutionModule({ + envOverrides: { + IVM_MAX_FETCH_OPTIONS_JSON_CHARS: '50', + }, + spawns: [ + () => + createReadyFetchProxyProc({ + url: 'https://example.com', + optionsJson: 'x'.repeat(100), + }), + ], + }) + + const result = await executeInIsolatedVM({ + code: 'return "fetch-options"', + params: {}, + envVars: {}, + contextVariables: {}, + timeoutMs: 100, + requestId: 'req-fetch-options', + }) + + const payload = JSON.parse(String(result.result)) + expect(payload.error).toContain('Fetch options exceed maximum payload size') + expect(secureFetchMock).not.toHaveBeenCalled() + }) + + it('rejects overly long fetch URLs before outbound call', async () => { + const { executeInIsolatedVM, secureFetchMock } = await loadExecutionModule({ + envOverrides: { + IVM_MAX_FETCH_URL_LENGTH: '30', + }, + spawns: [ + () => + createReadyFetchProxyProc({ + url: 'https://example.com/path/to/a/very/long/resource', + }), + ], + }) + + const result = await executeInIsolatedVM({ + code: 'return "fetch-url"', + params: {}, + envVars: {}, + contextVariables: {}, + timeoutMs: 100, + requestId: 'req-fetch-url', + }) + + const payload = JSON.parse(String(result.result)) + expect(payload.error).toContain('fetch URL exceeds maximum length') + expect(secureFetchMock).not.toHaveBeenCalled() + }) +}) diff --git a/apps/sim/lib/execution/isolated-vm.ts b/apps/sim/lib/execution/isolated-vm.ts index 472fc12b2..75567aed5 100644 --- a/apps/sim/lib/execution/isolated-vm.ts +++ b/apps/sim/lib/execution/isolated-vm.ts @@ -3,7 +3,13 @@ import fs from 'node:fs' import path from 'node:path' import { fileURLToPath } from 'node:url' import { createLogger } from '@sim/logger' -import { validateProxyUrl } from '@/lib/core/security/input-validation' +import { env } from '@/lib/core/config/env' +import { getRedisClient } from '@/lib/core/config/redis' +import { + type SecureFetchOptions, + secureFetchWithValidation, +} from '@/lib/core/security/input-validation.server' +import { sanitizeUrlForLog } from '@/lib/core/utils/logging' const logger = createLogger('IsolatedVMExecution') @@ -27,6 +33,8 @@ export interface IsolatedVMExecutionRequest { contextVariables: Record timeoutMs: number requestId: string + ownerKey?: string + ownerWeight?: number } export interface IsolatedVMExecutionResult { @@ -44,90 +52,478 @@ export interface IsolatedVMError { lineContent?: string } +const POOL_SIZE = Number.parseInt(env.IVM_POOL_SIZE) || 4 +const MAX_CONCURRENT = Number.parseInt(env.IVM_MAX_CONCURRENT) || 10000 +const MAX_PER_WORKER = Number.parseInt(env.IVM_MAX_PER_WORKER) || 2500 +const WORKER_IDLE_TIMEOUT_MS = Number.parseInt(env.IVM_WORKER_IDLE_TIMEOUT_MS) || 60000 +const QUEUE_TIMEOUT_MS = Number.parseInt(env.IVM_QUEUE_TIMEOUT_MS) || 300000 +const MAX_QUEUE_SIZE = Number.parseInt(env.IVM_MAX_QUEUE_SIZE) || 10000 +const MAX_FETCH_RESPONSE_BYTES = Number.parseInt(env.IVM_MAX_FETCH_RESPONSE_BYTES) || 8_388_608 +const MAX_FETCH_RESPONSE_CHARS = Number.parseInt(env.IVM_MAX_FETCH_RESPONSE_CHARS) || 4_000_000 +const MAX_FETCH_URL_LENGTH = Number.parseInt(env.IVM_MAX_FETCH_URL_LENGTH) || 8192 +const MAX_FETCH_OPTIONS_JSON_CHARS = + Number.parseInt(env.IVM_MAX_FETCH_OPTIONS_JSON_CHARS) || 262_144 +const MAX_ACTIVE_PER_OWNER = Number.parseInt(env.IVM_MAX_ACTIVE_PER_OWNER) || 200 +const MAX_QUEUED_PER_OWNER = Number.parseInt(env.IVM_MAX_QUEUED_PER_OWNER) || 2000 +const MAX_OWNER_WEIGHT = Number.parseInt(env.IVM_MAX_OWNER_WEIGHT) || 5 +const DISTRIBUTED_MAX_INFLIGHT_PER_OWNER = + Number.parseInt(env.IVM_DISTRIBUTED_MAX_INFLIGHT_PER_OWNER) || + MAX_ACTIVE_PER_OWNER + MAX_QUEUED_PER_OWNER +const DISTRIBUTED_LEASE_MIN_TTL_MS = Number.parseInt(env.IVM_DISTRIBUTED_LEASE_MIN_TTL_MS) || 120000 +const DISTRIBUTED_KEY_PREFIX = 'ivm:fair:v1:owner' +const QUEUE_RETRY_DELAY_MS = 1000 +const DISTRIBUTED_LEASE_GRACE_MS = 30000 + interface PendingExecution { resolve: (result: IsolatedVMExecutionResult) => void timeout: ReturnType + ownerKey: string } -let worker: ChildProcess | null = null -let workerReady = false -let workerReadyPromise: Promise | null = null -let workerIdleTimeout: ReturnType | null = null -const pendingExecutions = new Map() +interface WorkerInfo { + process: ChildProcess + ready: boolean + readyPromise: Promise | null + activeExecutions: number + pendingExecutions: Map + idleTimeout: ReturnType | null + id: number +} + +interface QueuedExecution { + id: number + ownerKey: string + req: IsolatedVMExecutionRequest + resolve: (result: IsolatedVMExecutionResult) => void + queueTimeout: ReturnType +} + +interface QueueNode { + ownerKey: string + value: QueuedExecution + prev: QueueNode | null + next: QueueNode | null +} + +interface OwnerState { + ownerKey: string + weight: number + activeExecutions: number + queueHead: QueueNode | null + queueTail: QueueNode | null + queueLength: number + burstRemaining: number +} + +const workers: Map = new Map() +const ownerStates: Map = new Map() +const queuedOwnerRing: string[] = [] +let queuedOwnerCursor = 0 +let queueSize = 0 +const queueNodes: Map = new Map() +let totalActiveExecutions = 0 let executionIdCounter = 0 +let queueIdCounter = 0 +let nextWorkerId = 0 +let spawnInProgress = 0 +let queueDrainRetryTimeout: ReturnType | null = null -const WORKER_IDLE_TIMEOUT_MS = 60000 - -function cleanupWorker() { - if (workerIdleTimeout) { - clearTimeout(workerIdleTimeout) - workerIdleTimeout = null - } - if (worker) { - worker.kill() - worker = null - } - workerReady = false - workerReadyPromise = null +type IsolatedFetchOptions = RequestInit & { + timeout?: number + maxRedirects?: number } -function resetIdleTimeout() { - if (workerIdleTimeout) { - clearTimeout(workerIdleTimeout) +function truncateString(value: string, maxChars: number): { value: string; truncated: boolean } { + if (value.length <= maxChars) { + return { value, truncated: false } } - workerIdleTimeout = setTimeout(() => { - if (pendingExecutions.size === 0) { - logger.info('Cleaning up idle isolated-vm worker') - cleanupWorker() + return { + value: `${value.slice(0, maxChars)}... [truncated ${value.length - maxChars} chars]`, + truncated: true, + } +} + +function normalizeFetchOptions(options?: IsolatedFetchOptions): SecureFetchOptions { + if (!options) return { maxResponseBytes: MAX_FETCH_RESPONSE_BYTES } + + const normalized: SecureFetchOptions = { + maxResponseBytes: MAX_FETCH_RESPONSE_BYTES, + } + + if (typeof options.method === 'string' && options.method.length > 0) { + normalized.method = options.method + } + + if ( + typeof options.timeout === 'number' && + Number.isFinite(options.timeout) && + options.timeout > 0 + ) { + normalized.timeout = Math.floor(options.timeout) + } + + if ( + typeof options.maxRedirects === 'number' && + Number.isFinite(options.maxRedirects) && + options.maxRedirects >= 0 + ) { + normalized.maxRedirects = Math.floor(options.maxRedirects) + } + + if (options.headers) { + const headers: Record = {} + if (options.headers instanceof Headers) { + options.headers.forEach((value, key) => { + headers[key] = value + }) + } else if (Array.isArray(options.headers)) { + for (const [key, value] of options.headers) { + headers[String(key)] = String(value) + } + } else { + for (const [key, value] of Object.entries(options.headers)) { + headers[key] = String(value) + } } - }, WORKER_IDLE_TIMEOUT_MS) + normalized.headers = headers + } + + if ( + typeof options.body === 'string' || + options.body instanceof Buffer || + options.body instanceof Uint8Array + ) { + normalized.body = options.body + } else if (options.body !== undefined && options.body !== null) { + normalized.body = String(options.body) + } + + return normalized } -/** - * Secure fetch wrapper that validates URLs to prevent SSRF attacks - */ -async function secureFetch(requestId: string, url: string, options?: RequestInit): Promise { - const validation = validateProxyUrl(url) - if (!validation.isValid) { - logger.warn(`[${requestId}] Blocked fetch request due to SSRF validation`, { - url: url.substring(0, 100), - error: validation.error, +async function secureFetch( + requestId: string, + url: string, + options?: IsolatedFetchOptions +): Promise { + if (url.length > MAX_FETCH_URL_LENGTH) { + return JSON.stringify({ + error: `Security Error: fetch URL exceeds maximum length (${MAX_FETCH_URL_LENGTH})`, }) - return JSON.stringify({ error: `Security Error: ${validation.error}` }) } try { - const response = await fetch(url, options) - const body = await response.text() + const response = await secureFetchWithValidation( + url, + normalizeFetchOptions(options), + 'fetchUrl' + ) + const bodyResult = truncateString(await response.text(), MAX_FETCH_RESPONSE_CHARS) const headers: Record = {} - response.headers.forEach((value, key) => { + for (const [key, value] of response.headers) { headers[key] = value - }) + } return JSON.stringify({ ok: response.ok, status: response.status, statusText: response.statusText, - body, + body: bodyResult.value, + bodyTruncated: bodyResult.truncated, headers, }) } catch (error: unknown) { + logger.warn(`[${requestId}] Isolated fetch failed`, { + url: sanitizeUrlForLog(url), + error: error instanceof Error ? error.message : String(error), + }) return JSON.stringify({ error: error instanceof Error ? error.message : 'Unknown fetch error' }) } } -/** - * Handle IPC messages from the Node.js worker - */ -function handleWorkerMessage(message: unknown) { +function normalizeOwnerKey(ownerKey?: string): string { + if (!ownerKey) return 'anonymous' + const normalized = ownerKey.trim() + return normalized || 'anonymous' +} + +function normalizeOwnerWeight(ownerWeight?: number): number { + if (!Number.isFinite(ownerWeight) || ownerWeight === undefined) return 1 + return Math.max(1, Math.min(MAX_OWNER_WEIGHT, Math.floor(ownerWeight))) +} + +function ownerRedisKey(ownerKey: string): string { + return `${DISTRIBUTED_KEY_PREFIX}:${ownerKey}` +} + +type LeaseAcquireResult = 'acquired' | 'limit_exceeded' | 'unavailable' + +async function tryAcquireDistributedLease( + ownerKey: string, + leaseId: string, + timeoutMs: number +): Promise { + // Redis not configured: explicit local-mode fallback is allowed. + if (!env.REDIS_URL) return 'acquired' + + const redis = getRedisClient() + if (!redis) { + logger.error('Redis is configured but unavailable for distributed lease acquisition', { + ownerKey, + }) + return 'unavailable' + } + + const now = Date.now() + const leaseTtlMs = Math.max( + timeoutMs + QUEUE_TIMEOUT_MS + DISTRIBUTED_LEASE_GRACE_MS, + DISTRIBUTED_LEASE_MIN_TTL_MS + ) + const expiresAt = now + leaseTtlMs + const key = ownerRedisKey(ownerKey) + + const script = ` + redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', ARGV[1]) + local current = redis.call('ZCARD', KEYS[1]) + if current >= tonumber(ARGV[2]) then + return 0 + end + redis.call('ZADD', KEYS[1], ARGV[3], ARGV[4]) + redis.call('PEXPIRE', KEYS[1], ARGV[5]) + return 1 + ` + + try { + const result = await redis.eval( + script, + 1, + key, + now.toString(), + DISTRIBUTED_MAX_INFLIGHT_PER_OWNER.toString(), + expiresAt.toString(), + leaseId, + leaseTtlMs.toString() + ) + return Number(result) === 1 ? 'acquired' : 'limit_exceeded' + } catch (error) { + logger.error('Failed to acquire distributed owner lease', { ownerKey, error }) + return 'unavailable' + } +} + +async function releaseDistributedLease(ownerKey: string, leaseId: string): Promise { + const redis = getRedisClient() + if (!redis) return + + const key = ownerRedisKey(ownerKey) + const script = ` + redis.call('ZREM', KEYS[1], ARGV[1]) + if redis.call('ZCARD', KEYS[1]) == 0 then + redis.call('DEL', KEYS[1]) + end + return 1 + ` + + try { + await redis.eval(script, 1, key, leaseId) + } catch (error) { + logger.error('Failed to release distributed owner lease', { ownerKey, error }) + } +} + +function queueLength(): number { + return queueSize +} + +function maybeClearDrainRetry() { + if (queueSize === 0 && queueDrainRetryTimeout) { + clearTimeout(queueDrainRetryTimeout) + queueDrainRetryTimeout = null + } +} + +function getOrCreateOwnerState(ownerKey: string, ownerWeight: number): OwnerState { + const existing = ownerStates.get(ownerKey) + if (existing) { + existing.weight = Math.max(existing.weight, ownerWeight) + return existing + } + + const ownerState: OwnerState = { + ownerKey, + weight: ownerWeight, + activeExecutions: 0, + queueHead: null, + queueTail: null, + queueLength: 0, + burstRemaining: 0, + } + ownerStates.set(ownerKey, ownerState) + return ownerState +} + +function addOwnerToRing(ownerKey: string) { + if (queuedOwnerRing.includes(ownerKey)) return + queuedOwnerRing.push(ownerKey) +} + +function removeOwnerFromRing(ownerKey: string) { + const idx = queuedOwnerRing.indexOf(ownerKey) + if (idx === -1) return + queuedOwnerRing.splice(idx, 1) + if (queuedOwnerRing.length === 0) { + queuedOwnerCursor = 0 + return + } + if (idx < queuedOwnerCursor) { + queuedOwnerCursor-- + } else if (queuedOwnerCursor >= queuedOwnerRing.length) { + queuedOwnerCursor = 0 + } +} + +function maybeCleanupOwner(ownerKey: string) { + const owner = ownerStates.get(ownerKey) + if (!owner) return + if (owner.queueLength === 0) { + removeOwnerFromRing(ownerKey) + } + if (owner.queueLength === 0 && owner.activeExecutions === 0) { + ownerStates.delete(ownerKey) + } +} + +function removeQueueNode(node: QueueNode): QueuedExecution { + const owner = ownerStates.get(node.ownerKey) + if (!owner) { + queueNodes.delete(node.value.id) + queueSize = Math.max(0, queueSize - 1) + maybeClearDrainRetry() + return node.value + } + + const { prev, next, value } = node + if (prev) prev.next = next + else owner.queueHead = next + if (next) next.prev = prev + else owner.queueTail = prev + + node.prev = null + node.next = null + + queueNodes.delete(value.id) + owner.queueLength-- + queueSize-- + maybeCleanupOwner(owner.ownerKey) + maybeClearDrainRetry() + return value +} + +function shiftQueuedExecutionForOwner(owner: OwnerState): QueuedExecution | null { + if (!owner.queueHead) return null + return removeQueueNode(owner.queueHead) +} + +function removeQueuedExecutionById(queueId: number): QueuedExecution | null { + const node = queueNodes.get(queueId) + if (!node) return null + return removeQueueNode(node) +} + +function pushQueuedExecution(owner: OwnerState, queued: QueuedExecution) { + const node: QueueNode = { + ownerKey: owner.ownerKey, + value: queued, + prev: owner.queueTail, + next: null, + } + if (owner.queueTail) { + owner.queueTail.next = node + } else { + owner.queueHead = node + } + owner.queueTail = node + owner.queueLength++ + owner.burstRemaining = 0 + addOwnerToRing(owner.ownerKey) + queueNodes.set(queued.id, node) + queueSize++ +} + +function selectOwnerForDispatch(): OwnerState | null { + if (queuedOwnerRing.length === 0) return null + + let visited = 0 + while (queuedOwnerRing.length > 0 && visited < queuedOwnerRing.length) { + if (queuedOwnerCursor >= queuedOwnerRing.length) { + queuedOwnerCursor = 0 + } + const ownerKey = queuedOwnerRing[queuedOwnerCursor] + if (!ownerKey) return null + + const owner = ownerStates.get(ownerKey) + if (!owner) { + removeOwnerFromRing(ownerKey) + continue + } + + if (owner.queueLength === 0) { + owner.burstRemaining = 0 + removeOwnerFromRing(ownerKey) + continue + } + + if (owner.activeExecutions >= MAX_ACTIVE_PER_OWNER) { + owner.burstRemaining = 0 + queuedOwnerCursor = (queuedOwnerCursor + 1) % queuedOwnerRing.length + visited++ + continue + } + + if (owner.burstRemaining <= 0) { + owner.burstRemaining = owner.weight + } + + owner.burstRemaining-- + if (owner.burstRemaining <= 0) { + queuedOwnerCursor = (queuedOwnerCursor + 1) % queuedOwnerRing.length + } + + return owner + } + + return null +} + +function scheduleDrainRetry() { + if (queueDrainRetryTimeout || queueSize === 0) return + queueDrainRetryTimeout = setTimeout(() => { + queueDrainRetryTimeout = null + if (queueSize === 0) return + drainQueue() + }, QUEUE_RETRY_DELAY_MS) +} + +function handleWorkerMessage(workerId: number, message: unknown) { if (typeof message !== 'object' || message === null) return const msg = message as Record + const workerInfo = workers.get(workerId) if (msg.type === 'result') { - const pending = pendingExecutions.get(msg.executionId as number) + const execId = msg.executionId as number + const pending = workerInfo?.pendingExecutions.get(execId) if (pending) { clearTimeout(pending.timeout) - pendingExecutions.delete(msg.executionId as number) + workerInfo!.pendingExecutions.delete(execId) + workerInfo!.activeExecutions-- + totalActiveExecutions-- + const owner = ownerStates.get(pending.ownerKey) + if (owner) { + owner.activeExecutions = Math.max(0, owner.activeExecutions - 1) + maybeCleanupOwner(owner.ownerKey) + } pending.resolve(msg.result as IsolatedVMExecutionResult) + resetWorkerIdleTimeout(workerId) + drainQueue() } return } @@ -139,12 +535,31 @@ function handleWorkerMessage(message: unknown) { url: string optionsJson?: string } - let options: RequestInit | undefined + if (typeof url !== 'string' || url.length === 0) { + workerInfo?.process.send({ + type: 'fetchResponse', + fetchId, + response: JSON.stringify({ error: 'Invalid fetch URL' }), + }) + return + } + if (optionsJson && optionsJson.length > MAX_FETCH_OPTIONS_JSON_CHARS) { + workerInfo?.process.send({ + type: 'fetchResponse', + fetchId, + response: JSON.stringify({ + error: `Fetch options exceed maximum payload size (${MAX_FETCH_OPTIONS_JSON_CHARS} chars)`, + }), + }) + return + } + + let options: IsolatedFetchOptions | undefined if (optionsJson) { try { options = JSON.parse(optionsJson) } catch { - worker?.send({ + workerInfo?.process.send({ type: 'fetchResponse', fetchId, response: JSON.stringify({ error: 'Invalid fetch options JSON' }), @@ -155,14 +570,14 @@ function handleWorkerMessage(message: unknown) { secureFetch(requestId, url, options) .then((response) => { try { - worker?.send({ type: 'fetchResponse', fetchId, response }) + workerInfo?.process.send({ type: 'fetchResponse', fetchId, response }) } catch (err) { - logger.error('Failed to send fetch response to worker', { err, fetchId }) + logger.error('Failed to send fetch response to worker', { err, fetchId, workerId }) } }) .catch((err) => { try { - worker?.send({ + workerInfo?.process.send({ type: 'fetchResponse', fetchId, response: JSON.stringify({ @@ -170,21 +585,90 @@ function handleWorkerMessage(message: unknown) { }), }) } catch (sendErr) { - logger.error('Failed to send fetch error to worker', { sendErr, fetchId }) + logger.error('Failed to send fetch error to worker', { sendErr, fetchId, workerId }) } }) } } -/** - * Start the Node.js worker process - */ -async function ensureWorker(): Promise { - if (workerReady && worker) return - if (workerReadyPromise) return workerReadyPromise +function cleanupWorker(workerId: number) { + const workerInfo = workers.get(workerId) + if (!workerInfo) return - workerReadyPromise = new Promise((resolve, reject) => { + if (workerInfo.idleTimeout) { + clearTimeout(workerInfo.idleTimeout) + } + + workerInfo.process.kill() + + for (const [id, pending] of workerInfo.pendingExecutions) { + clearTimeout(pending.timeout) + totalActiveExecutions-- + const owner = ownerStates.get(pending.ownerKey) + if (owner) { + owner.activeExecutions = Math.max(0, owner.activeExecutions - 1) + maybeCleanupOwner(owner.ownerKey) + } + pending.resolve({ + result: null, + stdout: '', + error: { message: 'Code execution failed unexpectedly. Please try again.', name: 'Error' }, + }) + workerInfo.pendingExecutions.delete(id) + } + workerInfo.activeExecutions = 0 + + workers.delete(workerId) + logger.info('Worker removed from pool', { workerId, poolSize: workers.size }) +} + +function resetWorkerIdleTimeout(workerId: number) { + const workerInfo = workers.get(workerId) + if (!workerInfo) return + + if (workerInfo.idleTimeout) { + clearTimeout(workerInfo.idleTimeout) + workerInfo.idleTimeout = null + } + + if (workerInfo.activeExecutions === 0) { + workerInfo.idleTimeout = setTimeout(() => { + const w = workers.get(workerId) + if (w && w.activeExecutions === 0) { + logger.info('Cleaning up idle worker', { workerId }) + cleanupWorker(workerId) + } + }, WORKER_IDLE_TIMEOUT_MS) + } +} + +function spawnWorker(): Promise { + const workerId = nextWorkerId++ + spawnInProgress++ + let spawnSettled = false + + const settleSpawnInProgress = () => { + if (spawnSettled) { + return false + } + spawnSettled = true + spawnInProgress-- + return true + } + + const workerInfo: WorkerInfo = { + process: null as unknown as ChildProcess, + ready: false, + readyPromise: null, + activeExecutions: 0, + pendingExecutions: new Map(), + idleTimeout: null, + id: workerId, + } + + workerInfo.readyPromise = new Promise((resolve, reject) => { if (!checkNodeAvailable()) { + settleSpawnInProgress() reject( new Error( 'Node.js is required for code execution but was not found. ' + @@ -198,141 +682,361 @@ async function ensureWorker(): Promise { const workerPath = path.join(currentDir, 'isolated-vm-worker.cjs') if (!fs.existsSync(workerPath)) { + settleSpawnInProgress() reject(new Error(`Worker file not found at ${workerPath}`)) return } - import('node:child_process').then(({ spawn }) => { - worker = spawn('node', [workerPath], { - stdio: ['ignore', 'pipe', 'pipe', 'ipc'], - serialization: 'json', + import('node:child_process') + .then(({ spawn }) => { + const proc = spawn('node', [workerPath], { + stdio: ['ignore', 'pipe', 'pipe', 'ipc'], + serialization: 'json', + }) + workerInfo.process = proc + + proc.on('message', (message: unknown) => handleWorkerMessage(workerId, message)) + + let stderrData = '' + proc.stderr?.on('data', (data: Buffer) => { + stderrData += data.toString() + }) + + const startTimeout = setTimeout(() => { + proc.kill() + workers.delete(workerId) + if (!settleSpawnInProgress()) return + reject(new Error('Worker failed to start within timeout')) + }, 10000) + + const readyHandler = (message: unknown) => { + if ( + typeof message === 'object' && + message !== null && + (message as { type?: string }).type === 'ready' + ) { + if (!settleSpawnInProgress()) { + proc.off('message', readyHandler) + return + } + workerInfo.ready = true + clearTimeout(startTimeout) + proc.off('message', readyHandler) + workers.set(workerId, workerInfo) + resetWorkerIdleTimeout(workerId) + logger.info('Worker spawned and ready', { workerId, poolSize: workers.size }) + resolve() + } + } + proc.on('message', readyHandler) + + proc.on('exit', () => { + const wasStartupFailure = !workerInfo.ready + + if (wasStartupFailure) { + clearTimeout(startTimeout) + if (!settleSpawnInProgress()) return + + let errorMessage = 'Worker process exited unexpectedly' + if (stderrData.includes('isolated_vm') || stderrData.includes('MODULE_NOT_FOUND')) { + errorMessage = + 'Code execution requires the isolated-vm native module which failed to load. ' + + 'This usually means the module needs to be rebuilt for your Node.js version. ' + + 'Please run: cd node_modules/isolated-vm && npm rebuild' + logger.error('isolated-vm module failed to load', { stderr: stderrData, workerId }) + } else if (stderrData) { + errorMessage = `Worker process failed: ${stderrData.slice(0, 500)}` + logger.error('Worker process failed', { stderr: stderrData, workerId }) + } + + reject(new Error(errorMessage)) + return + } + + cleanupWorker(workerId) + drainQueue() + }) }) - - worker.on('message', handleWorkerMessage) - - let stderrData = '' - worker.stderr?.on('data', (data: Buffer) => { - stderrData += data.toString() + .catch((error) => { + if (!settleSpawnInProgress()) return + reject(error instanceof Error ? error : new Error('Failed to load child_process module')) }) - - const startTimeout = setTimeout(() => { - worker?.kill() - worker = null - workerReady = false - workerReadyPromise = null - reject(new Error('Worker failed to start within timeout')) - }, 10000) - - const readyHandler = (message: unknown) => { - if ( - typeof message === 'object' && - message !== null && - (message as { type?: string }).type === 'ready' - ) { - workerReady = true - clearTimeout(startTimeout) - worker?.off('message', readyHandler) - resolve() - } - } - worker.on('message', readyHandler) - - worker.on('exit', (code) => { - if (workerIdleTimeout) { - clearTimeout(workerIdleTimeout) - workerIdleTimeout = null - } - - const wasStartupFailure = !workerReady && workerReadyPromise - - worker = null - workerReady = false - workerReadyPromise = null - - let errorMessage = 'Worker process exited unexpectedly' - if (stderrData.includes('isolated_vm') || stderrData.includes('MODULE_NOT_FOUND')) { - errorMessage = - 'Code execution requires the isolated-vm native module which failed to load. ' + - 'This usually means the module needs to be rebuilt for your Node.js version. ' + - 'Please run: cd node_modules/isolated-vm && npm rebuild' - logger.error('isolated-vm module failed to load', { stderr: stderrData }) - } else if (stderrData) { - errorMessage = `Worker process failed: ${stderrData.slice(0, 500)}` - logger.error('Worker process failed', { stderr: stderrData }) - } - - if (wasStartupFailure) { - clearTimeout(startTimeout) - reject(new Error(errorMessage)) - return - } - - for (const [id, pending] of pendingExecutions) { - clearTimeout(pending.timeout) - pending.resolve({ - result: null, - stdout: '', - error: { message: errorMessage, name: 'WorkerError' }, - }) - pendingExecutions.delete(id) - } - }) - }) }) - return workerReadyPromise + return workerInfo.readyPromise.then(() => workerInfo) +} + +/** + * Returns the ready worker with the fewest active executions that still + * has capacity, or null if none available. + */ +function selectWorker(): WorkerInfo | null { + let best: WorkerInfo | null = null + for (const w of workers.values()) { + if (!w.ready) continue + if (w.activeExecutions >= MAX_PER_WORKER) continue + if (!best || w.activeExecutions < best.activeExecutions) { + best = w + } + } + return best +} + +/** + * Tries to get an existing worker with capacity, or spawns a new one if the + * pool is not full. Returns null when the pool is at capacity and all workers + * are saturated (caller should enqueue). + */ +async function acquireWorker(): Promise { + const existing = selectWorker() + if (existing) return existing + + const currentPoolSize = workers.size + spawnInProgress + if (currentPoolSize < POOL_SIZE) { + try { + return await spawnWorker() + } catch (error) { + logger.error('Failed to spawn worker', { error }) + return null + } + } + + return null +} + +function dispatchToWorker( + workerInfo: WorkerInfo, + ownerState: OwnerState, + req: IsolatedVMExecutionRequest, + resolve: (result: IsolatedVMExecutionResult) => void +) { + const execId = ++executionIdCounter + + if (workerInfo.idleTimeout) { + clearTimeout(workerInfo.idleTimeout) + workerInfo.idleTimeout = null + } + + const timeout = setTimeout(() => { + workerInfo.pendingExecutions.delete(execId) + workerInfo.activeExecutions-- + totalActiveExecutions-- + ownerState.activeExecutions = Math.max(0, ownerState.activeExecutions - 1) + maybeCleanupOwner(ownerState.ownerKey) + resolve({ + result: null, + stdout: '', + error: { message: `Execution timed out after ${req.timeoutMs}ms`, name: 'TimeoutError' }, + }) + resetWorkerIdleTimeout(workerInfo.id) + drainQueue() + }, req.timeoutMs + 1000) + + workerInfo.pendingExecutions.set(execId, { resolve, timeout, ownerKey: ownerState.ownerKey }) + workerInfo.activeExecutions++ + totalActiveExecutions++ + ownerState.activeExecutions++ + + try { + workerInfo.process.send({ type: 'execute', executionId: execId, request: req }) + } catch { + clearTimeout(timeout) + workerInfo.pendingExecutions.delete(execId) + workerInfo.activeExecutions-- + totalActiveExecutions-- + ownerState.activeExecutions = Math.max(0, ownerState.activeExecutions - 1) + maybeCleanupOwner(ownerState.ownerKey) + resolve({ + result: null, + stdout: '', + error: { message: 'Code execution failed to start. Please try again.', name: 'Error' }, + }) + resetWorkerIdleTimeout(workerInfo.id) + // Defer to break synchronous recursion: drainQueue → dispatchToWorker → catch → drainQueue + queueMicrotask(() => drainQueue()) + } +} + +function enqueueExecution( + ownerState: OwnerState, + req: IsolatedVMExecutionRequest, + resolve: (result: IsolatedVMExecutionResult) => void +) { + if (queueLength() >= MAX_QUEUE_SIZE) { + resolve({ + result: null, + stdout: '', + error: { + message: 'Code execution is at capacity. Please try again in a moment.', + name: 'Error', + }, + }) + return + } + if (ownerState.queueLength >= MAX_QUEUED_PER_OWNER) { + resolve({ + result: null, + stdout: '', + error: { + message: + 'Too many concurrent code executions. Please wait for some to complete before running more.', + name: 'Error', + }, + }) + return + } + + const queueId = ++queueIdCounter + const queueTimeout = setTimeout(() => { + const queued = removeQueuedExecutionById(queueId) + if (!queued) return + resolve({ + result: null, + stdout: '', + error: { + message: 'Code execution timed out waiting for an available worker. Please try again.', + name: 'Error', + }, + }) + }, QUEUE_TIMEOUT_MS) + + pushQueuedExecution(ownerState, { + id: queueId, + ownerKey: ownerState.ownerKey, + req, + resolve, + queueTimeout, + }) + logger.info('Execution queued', { + queueLength: queueLength(), + ownerKey: ownerState.ownerKey, + ownerQueueLength: ownerState.queueLength, + totalActive: totalActiveExecutions, + poolSize: workers.size, + }) + drainQueue() +} + +/** + * Called after every completion or worker spawn — dispatches queued + * executions to available workers. + */ +function drainQueue() { + while (queueLength() > 0 && totalActiveExecutions < MAX_CONCURRENT) { + const worker = selectWorker() + if (!worker) { + const currentPoolSize = workers.size + spawnInProgress + if (currentPoolSize < POOL_SIZE) { + spawnWorker() + .then(() => drainQueue()) + .catch((err) => { + logger.error('Failed to spawn worker during drain', { err }) + scheduleDrainRetry() + }) + } + break + } + + const owner = selectOwnerForDispatch() + if (!owner) { + scheduleDrainRetry() + break + } + + const queued = shiftQueuedExecutionForOwner(owner) + if (!queued) { + owner.burstRemaining = 0 + maybeCleanupOwner(owner.ownerKey) + continue + } + clearTimeout(queued.queueTimeout) + dispatchToWorker(worker, owner, queued.req, queued.resolve) + } } /** * Execute JavaScript code in an isolated V8 isolate via Node.js subprocess. - * The worker's V8 isolate enforces timeoutMs internally. The parent timeout - * (timeoutMs + 1000) is a safety buffer for IPC communication. */ export async function executeInIsolatedVM( req: IsolatedVMExecutionRequest ): Promise { - if (workerIdleTimeout) { - clearTimeout(workerIdleTimeout) - workerIdleTimeout = null - } + const ownerKey = normalizeOwnerKey(req.ownerKey) + const ownerWeight = normalizeOwnerWeight(req.ownerWeight) + const ownerState = getOrCreateOwnerState(ownerKey, ownerWeight) - await ensureWorker() - - if (!worker) { + const distributedLeaseId = `${req.requestId}:${Date.now()}:${Math.random().toString(36).slice(2, 10)}` + const leaseAcquireResult = await tryAcquireDistributedLease( + ownerKey, + distributedLeaseId, + req.timeoutMs + ) + if (leaseAcquireResult === 'limit_exceeded') { + maybeCleanupOwner(ownerKey) return { result: null, stdout: '', - error: { message: 'Failed to start isolated-vm worker', name: 'WorkerError' }, + error: { + message: + 'Too many concurrent code executions. Please wait for some to complete before running more.', + name: 'Error', + }, + } + } + if (leaseAcquireResult === 'unavailable') { + maybeCleanupOwner(ownerKey) + return { + result: null, + stdout: '', + error: { + message: 'Code execution is temporarily unavailable. Please try again in a moment.', + name: 'Error', + }, } } - const executionId = ++executionIdCounter + let settled = false + const releaseLease = () => { + if (settled) return + settled = true + releaseDistributedLease(ownerKey, distributedLeaseId).catch((error) => { + logger.error('Failed to release distributed lease', { ownerKey, error }) + }) + } - return new Promise((resolve) => { - const timeout = setTimeout(() => { - pendingExecutions.delete(executionId) - resolve({ - result: null, - stdout: '', - error: { message: `Execution timed out after ${req.timeoutMs}ms`, name: 'TimeoutError' }, - }) - }, req.timeoutMs + 1000) + return new Promise((resolve) => { + const resolveWithRelease = (result: IsolatedVMExecutionResult) => { + releaseLease() + resolve(result) + } - pendingExecutions.set(executionId, { resolve, timeout }) - - try { - worker!.send({ type: 'execute', executionId, request: req }) - } catch { - clearTimeout(timeout) - pendingExecutions.delete(executionId) - resolve({ - result: null, - stdout: '', - error: { message: 'Failed to send execution request to worker', name: 'WorkerError' }, - }) + if ( + totalActiveExecutions >= MAX_CONCURRENT || + ownerState.activeExecutions >= MAX_ACTIVE_PER_OWNER + ) { + enqueueExecution(ownerState, req, resolveWithRelease) return } - resetIdleTimeout() + acquireWorker() + .then((workerInfo) => { + if (!workerInfo) { + enqueueExecution(ownerState, req, resolveWithRelease) + return + } + + dispatchToWorker(workerInfo, ownerState, req, resolveWithRelease) + if (queueLength() > 0) { + drainQueue() + } + }) + .catch((error) => { + logger.error('Failed to acquire worker for execution', { error, ownerKey }) + enqueueExecution(ownerState, req, resolveWithRelease) + }) + }).finally(() => { + releaseLease() + if (ownerState.queueLength === 0 && ownerState.activeExecutions === 0) { + maybeCleanupOwner(ownerState.ownerKey) + } }) } diff --git a/apps/sim/lib/execution/preprocessing.ts b/apps/sim/lib/execution/preprocessing.ts index 9a0236fd1..3eb14813e 100644 --- a/apps/sim/lib/execution/preprocessing.ts +++ b/apps/sim/lib/execution/preprocessing.ts @@ -124,6 +124,7 @@ export interface PreprocessExecutionOptions { workspaceId?: string // If known, used for billing resolution loggingSession?: LoggingSession // If provided, will be used for error logging isResumeContext?: boolean // If true, allows fallback billing on resolution failure (for paused workflow resumes) + useAuthenticatedUserAsActor?: boolean // If true, use the authenticated userId as actorUserId (for client-side executions and personal API keys) /** @deprecated No longer used - background/async executions always use deployed state */ useDraftState?: boolean } @@ -170,6 +171,7 @@ export async function preprocessExecution( workspaceId: providedWorkspaceId, loggingSession: providedLoggingSession, isResumeContext = false, + useAuthenticatedUserAsActor = false, } = options logger.info(`[${requestId}] Starting execution preprocessing`, { @@ -257,7 +259,14 @@ export async function preprocessExecution( let actorUserId: string | null = null try { - if (workspaceId) { + // For client-side executions and personal API keys, the authenticated + // user is the billing and permission actor — not the workspace owner. + if (useAuthenticatedUserAsActor && userId) { + actorUserId = userId + logger.info(`[${requestId}] Using authenticated user as actor: ${actorUserId}`) + } + + if (!actorUserId && workspaceId) { actorUserId = await getWorkspaceBilledAccountUserId(workspaceId) if (actorUserId) { logger.info(`[${requestId}] Using workspace billed account: ${actorUserId}`) diff --git a/apps/sim/tools/index.ts b/apps/sim/tools/index.ts index 1670b5520..09c3ac616 100644 --- a/apps/sim/tools/index.ts +++ b/apps/sim/tools/index.ts @@ -247,7 +247,8 @@ export async function executeTool( // If it's a custom tool, use the async version with workflowId if (isCustomTool(normalizedToolId)) { const workflowId = params._context?.workflowId - tool = await getToolAsync(normalizedToolId, workflowId) + const userId = params._context?.userId + tool = await getToolAsync(normalizedToolId, workflowId, userId) if (!tool) { logger.error(`[${requestId}] Custom tool not found: ${normalizedToolId}`) } @@ -286,26 +287,25 @@ export async function executeTool( try { const baseUrl = getBaseUrl() + const workflowId = contextParams._context?.workflowId + const userId = contextParams._context?.userId + const tokenPayload: OAuthTokenPayload = { credentialId: contextParams.credential as string, } - - // Add workflowId if it exists in params, context, or executionContext - const workflowId = - contextParams.workflowId || - contextParams._context?.workflowId || - executionContext?.workflowId if (workflowId) { tokenPayload.workflowId = workflowId } logger.info(`[${requestId}] Fetching access token from ${baseUrl}/api/auth/oauth/token`) - // Build token URL and also include workflowId in query so server auth can read it const tokenUrlObj = new URL('/api/auth/oauth/token', baseUrl) if (workflowId) { tokenUrlObj.searchParams.set('workflowId', workflowId) } + if (userId) { + tokenUrlObj.searchParams.set('userId', userId) + } // Always send Content-Type; add internal auth on server-side runs const tokenHeaders: Record = { 'Content-Type': 'application/json' } @@ -609,6 +609,10 @@ async function executeToolRequest( if (workflowId) { fullUrlObj.searchParams.set('workflowId', workflowId) } + const userId = params._context?.userId + if (userId) { + fullUrlObj.searchParams.set('userId', userId) + } } const fullUrl = fullUrlObj.toString() diff --git a/apps/sim/tools/utils.ts b/apps/sim/tools/utils.ts index e5364e415..0a7b635fa 100644 --- a/apps/sim/tools/utils.ts +++ b/apps/sim/tools/utils.ts @@ -311,7 +311,8 @@ export function getTool(toolId: string): ToolConfig | undefined { // Get a tool by its ID asynchronously (supports server-side) export async function getToolAsync( toolId: string, - workflowId?: string + workflowId?: string, + userId?: string ): Promise { // Check for built-in tools const builtInTool = tools[toolId] @@ -319,7 +320,7 @@ export async function getToolAsync( // Check if it's a custom tool if (isCustomTool(toolId)) { - return fetchCustomToolFromAPI(toolId, workflowId) + return fetchCustomToolFromAPI(toolId, workflowId, userId) } return undefined @@ -366,7 +367,8 @@ function createToolConfig(customTool: any, customToolId: string): ToolConfig { // Create a tool config from a custom tool definition by fetching from API async function fetchCustomToolFromAPI( customToolId: string, - workflowId?: string + workflowId?: string, + userId?: string ): Promise { const identifier = customToolId.replace('custom_', '') @@ -374,10 +376,12 @@ async function fetchCustomToolFromAPI( const baseUrl = getBaseUrl() const url = new URL('/api/tools/custom', baseUrl) - // Add workflowId as a query parameter if available if (workflowId) { url.searchParams.append('workflowId', workflowId) } + if (userId) { + url.searchParams.append('userId', userId) + } // For server-side calls (during workflow execution), use internal JWT token const headers: Record = {} diff --git a/helm/sim/values.yaml b/helm/sim/values.yaml index 86e6c9079..d5eecb51e 100644 --- a/helm/sim/values.yaml +++ b/helm/sim/values.yaml @@ -139,7 +139,25 @@ app: EXECUTION_TIMEOUT_ASYNC_PRO: "5400" # Pro tier async timeout (90 minutes) EXECUTION_TIMEOUT_ASYNC_TEAM: "5400" # Team tier async timeout (90 minutes) EXECUTION_TIMEOUT_ASYNC_ENTERPRISE: "5400" # Enterprise tier async timeout (90 minutes) - + + # Isolated-VM Worker Pool Configuration + IVM_POOL_SIZE: "4" # Max worker processes in pool + IVM_MAX_CONCURRENT: "10000" # Max concurrent executions globally + IVM_MAX_PER_WORKER: "2500" # Max concurrent executions per worker + IVM_WORKER_IDLE_TIMEOUT_MS: "60000" # Worker idle cleanup timeout (ms) + IVM_QUEUE_TIMEOUT_MS: "300000" # Max queue wait before rejection (ms) + IVM_MAX_QUEUE_SIZE: "10000" # Max queued executions globally + IVM_MAX_ACTIVE_PER_OWNER: "200" # Max concurrent executions per user + IVM_MAX_QUEUED_PER_OWNER: "2000" # Max queued executions per user + IVM_MAX_OWNER_WEIGHT: "5" # Max scheduling weight per user + IVM_DISTRIBUTED_MAX_INFLIGHT_PER_OWNER: "2200" # Max in-flight per user across instances (Redis) + IVM_DISTRIBUTED_LEASE_MIN_TTL_MS: "120000" # Min distributed lease TTL (ms) + IVM_MAX_FETCH_RESPONSE_BYTES: "8388608" # Max fetch response size (8MB) + IVM_MAX_FETCH_RESPONSE_CHARS: "4000000" # Max fetch response chars + IVM_MAX_FETCH_URL_LENGTH: "8192" # Max fetch URL length + IVM_MAX_FETCH_OPTIONS_JSON_CHARS: "262144" # Max fetch options payload (256KB) + IVM_MAX_STDOUT_CHARS: "200000" # Max stdout capture per execution + # UI Branding & Whitelabeling Configuration NEXT_PUBLIC_BRAND_NAME: "Sim" # Custom brand name NEXT_PUBLIC_BRAND_LOGO_URL: "" # Custom logo URL (leave empty for default) From 193b95cfec8e2c20dd134d2812b76c2106bd998f Mon Sep 17 00:00:00 2001 From: Vikhyath Mondreti Date: Fri, 6 Feb 2026 22:07:55 -0800 Subject: [PATCH 4/8] fix(auth): swap out hybrid auth in relevant callsites (#3160) * fix(logs): execution files should always use our internal route * correct degree of access control * fix tests * fix tag defs flag * fix type check * fix mcp tools * make webhooks consistent * fix ollama and vllm visibility * remove dup test --- .../sim/app/api/a2a/agents/[agentId]/route.ts | 10 +-- apps/sim/app/api/a2a/agents/route.ts | 6 +- .../app/api/auth/oauth/credentials/route.ts | 4 +- .../app/api/auth/oauth/token/route.test.ts | 48 ++++-------- apps/sim/app/api/auth/oauth/token/route.ts | 6 +- apps/sim/app/api/files/delete/route.test.ts | 2 +- apps/sim/app/api/files/delete/route.ts | 4 +- apps/sim/app/api/files/download/route.ts | 4 +- apps/sim/app/api/files/parse/route.test.ts | 2 +- apps/sim/app/api/files/parse/route.ts | 4 +- .../api/files/serve/[...path]/route.test.ts | 10 +-- .../app/api/files/serve/[...path]/route.ts | 4 +- .../knowledge/[id]/tag-definitions/route.ts | 22 +----- .../api/logs/execution/[executionId]/route.ts | 4 +- apps/sim/app/api/memory/[id]/route.ts | 4 +- apps/sim/app/api/memory/route.ts | 8 +- .../app/api/tools/a2a/cancel-task/route.ts | 4 +- .../a2a/delete-push-notification/route.ts | 4 +- .../app/api/tools/a2a/get-agent-card/route.ts | 4 +- .../tools/a2a/get-push-notification/route.ts | 4 +- apps/sim/app/api/tools/a2a/get-task/route.ts | 4 +- .../app/api/tools/a2a/resubscribe/route.ts | 4 +- .../app/api/tools/a2a/send-message/route.ts | 4 +- .../tools/a2a/set-push-notification/route.ts | 4 +- apps/sim/app/api/users/me/usage-logs/route.ts | 4 +- .../file-download/file-download.tsx | 18 +---- apps/sim/blocks/blocks/agent.ts | 30 +------- apps/sim/blocks/types.ts | 4 +- apps/sim/blocks/utils.ts | 76 +++++++++++++------ .../executor/handlers/agent/agent-handler.ts | 13 +++- .../handlers/evaluator/evaluator-handler.ts | 2 +- .../handlers/router/router-handler.ts | 2 + apps/sim/lib/auth/credential-access.ts | 20 ++--- apps/sim/lib/mcp/middleware.ts | 4 +- apps/sim/lib/webhooks/processor.ts | 18 ++++- .../workflows/subblocks/visibility.test.ts | 9 +++ .../sim/lib/workflows/subblocks/visibility.ts | 7 +- apps/sim/tools/index.ts | 8 +- 38 files changed, 196 insertions(+), 193 deletions(-) diff --git a/apps/sim/app/api/a2a/agents/[agentId]/route.ts b/apps/sim/app/api/a2a/agents/[agentId]/route.ts index 65f22e5b6..1c8eea273 100644 --- a/apps/sim/app/api/a2a/agents/[agentId]/route.ts +++ b/apps/sim/app/api/a2a/agents/[agentId]/route.ts @@ -5,7 +5,7 @@ import { eq } from 'drizzle-orm' import { type NextRequest, NextResponse } from 'next/server' import { generateAgentCard, generateSkillsFromWorkflow } from '@/lib/a2a/agent-card' import type { AgentCapabilities, AgentSkill } from '@/lib/a2a/types' -import { checkHybridAuth } from '@/lib/auth/hybrid' +import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import { getRedisClient } from '@/lib/core/config/redis' import { loadWorkflowFromNormalizedTables } from '@/lib/workflows/persistence/utils' import { checkWorkspaceAccess } from '@/lib/workspaces/permissions/utils' @@ -40,7 +40,7 @@ export async function GET(request: NextRequest, { params }: { params: Promise { const mockRefreshTokenIfNeeded = vi.fn() const mockGetOAuthToken = vi.fn() const mockAuthorizeCredentialUse = vi.fn() - const mockCheckHybridAuth = vi.fn() + const mockCheckSessionOrInternalAuth = vi.fn() const mockLogger = createMockLogger() @@ -42,7 +42,7 @@ describe('OAuth Token API Routes', () => { })) vi.doMock('@/lib/auth/hybrid', () => ({ - checkHybridAuth: mockCheckHybridAuth, + checkSessionOrInternalAuth: mockCheckSessionOrInternalAuth, })) }) @@ -235,7 +235,7 @@ describe('OAuth Token API Routes', () => { describe('credentialAccountUserId + providerId path', () => { it('should reject unauthenticated requests', async () => { - mockCheckHybridAuth.mockResolvedValueOnce({ + mockCheckSessionOrInternalAuth.mockResolvedValueOnce({ success: false, error: 'Authentication required', }) @@ -255,30 +255,8 @@ describe('OAuth Token API Routes', () => { expect(mockGetOAuthToken).not.toHaveBeenCalled() }) - it('should reject API key authentication', async () => { - mockCheckHybridAuth.mockResolvedValueOnce({ - success: true, - authType: 'api_key', - userId: 'test-user-id', - }) - - const req = createMockRequest('POST', { - credentialAccountUserId: 'test-user-id', - providerId: 'google', - }) - - const { POST } = await import('@/app/api/auth/oauth/token/route') - - const response = await POST(req) - const data = await response.json() - - expect(response.status).toBe(401) - expect(data).toHaveProperty('error', 'User not authenticated') - expect(mockGetOAuthToken).not.toHaveBeenCalled() - }) - it('should reject internal JWT authentication', async () => { - mockCheckHybridAuth.mockResolvedValueOnce({ + mockCheckSessionOrInternalAuth.mockResolvedValueOnce({ success: true, authType: 'internal_jwt', userId: 'test-user-id', @@ -300,7 +278,7 @@ describe('OAuth Token API Routes', () => { }) it('should reject requests for other users credentials', async () => { - mockCheckHybridAuth.mockResolvedValueOnce({ + mockCheckSessionOrInternalAuth.mockResolvedValueOnce({ success: true, authType: 'session', userId: 'attacker-user-id', @@ -322,7 +300,7 @@ describe('OAuth Token API Routes', () => { }) it('should allow session-authenticated users to access their own credentials', async () => { - mockCheckHybridAuth.mockResolvedValueOnce({ + mockCheckSessionOrInternalAuth.mockResolvedValueOnce({ success: true, authType: 'session', userId: 'test-user-id', @@ -345,7 +323,7 @@ describe('OAuth Token API Routes', () => { }) it('should return 404 when credential not found for user', async () => { - mockCheckHybridAuth.mockResolvedValueOnce({ + mockCheckSessionOrInternalAuth.mockResolvedValueOnce({ success: true, authType: 'session', userId: 'test-user-id', @@ -373,7 +351,7 @@ describe('OAuth Token API Routes', () => { */ describe('GET handler', () => { it('should return access token successfully', async () => { - mockCheckHybridAuth.mockResolvedValueOnce({ + mockCheckSessionOrInternalAuth.mockResolvedValueOnce({ success: true, authType: 'session', userId: 'test-user-id', @@ -402,7 +380,7 @@ describe('OAuth Token API Routes', () => { expect(response.status).toBe(200) expect(data).toHaveProperty('accessToken', 'fresh-token') - expect(mockCheckHybridAuth).toHaveBeenCalled() + expect(mockCheckSessionOrInternalAuth).toHaveBeenCalled() expect(mockGetCredential).toHaveBeenCalledWith(mockRequestId, 'credential-id', 'test-user-id') expect(mockRefreshTokenIfNeeded).toHaveBeenCalled() }) @@ -421,7 +399,7 @@ describe('OAuth Token API Routes', () => { }) it('should handle authentication failure', async () => { - mockCheckHybridAuth.mockResolvedValueOnce({ + mockCheckSessionOrInternalAuth.mockResolvedValueOnce({ success: false, error: 'Authentication required', }) @@ -440,7 +418,7 @@ describe('OAuth Token API Routes', () => { }) it('should handle credential not found', async () => { - mockCheckHybridAuth.mockResolvedValueOnce({ + mockCheckSessionOrInternalAuth.mockResolvedValueOnce({ success: true, authType: 'session', userId: 'test-user-id', @@ -461,7 +439,7 @@ describe('OAuth Token API Routes', () => { }) it('should handle missing access token', async () => { - mockCheckHybridAuth.mockResolvedValueOnce({ + mockCheckSessionOrInternalAuth.mockResolvedValueOnce({ success: true, authType: 'session', userId: 'test-user-id', @@ -487,7 +465,7 @@ describe('OAuth Token API Routes', () => { }) it('should handle token refresh failure', async () => { - mockCheckHybridAuth.mockResolvedValueOnce({ + mockCheckSessionOrInternalAuth.mockResolvedValueOnce({ success: true, authType: 'session', userId: 'test-user-id', diff --git a/apps/sim/app/api/auth/oauth/token/route.ts b/apps/sim/app/api/auth/oauth/token/route.ts index 7c7d1f463..f6728fe69 100644 --- a/apps/sim/app/api/auth/oauth/token/route.ts +++ b/apps/sim/app/api/auth/oauth/token/route.ts @@ -2,7 +2,7 @@ import { createLogger } from '@sim/logger' import { type NextRequest, NextResponse } from 'next/server' import { z } from 'zod' import { authorizeCredentialUse } from '@/lib/auth/credential-access' -import { checkHybridAuth } from '@/lib/auth/hybrid' +import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import { generateRequestId } from '@/lib/core/utils/request' import { getCredential, getOAuthToken, refreshTokenIfNeeded } from '@/app/api/auth/oauth/utils' @@ -71,7 +71,7 @@ export async function POST(request: NextRequest) { providerId, }) - const auth = await checkHybridAuth(request, { requireWorkflowId: false }) + const auth = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) if (!auth.success || auth.authType !== 'session' || !auth.userId) { logger.warn(`[${requestId}] Unauthorized request for credentialAccountUserId path`, { success: auth.success, @@ -187,7 +187,7 @@ export async function GET(request: NextRequest) { const { credentialId } = parseResult.data // For GET requests, we only support session-based authentication - const auth = await checkHybridAuth(request, { requireWorkflowId: false }) + const auth = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) if (!auth.success || auth.authType !== 'session' || !auth.userId) { return NextResponse.json({ error: 'User not authenticated' }, { status: 401 }) } diff --git a/apps/sim/app/api/files/delete/route.test.ts b/apps/sim/app/api/files/delete/route.test.ts index 669ea86ad..0cc9824f7 100644 --- a/apps/sim/app/api/files/delete/route.test.ts +++ b/apps/sim/app/api/files/delete/route.test.ts @@ -29,7 +29,7 @@ function setupFileApiMocks( } vi.doMock('@/lib/auth/hybrid', () => ({ - checkHybridAuth: vi.fn().mockResolvedValue({ + checkSessionOrInternalAuth: vi.fn().mockResolvedValue({ success: authenticated, userId: authenticated ? 'test-user-id' : undefined, error: authenticated ? undefined : 'Unauthorized', diff --git a/apps/sim/app/api/files/delete/route.ts b/apps/sim/app/api/files/delete/route.ts index 1a5f49138..273500461 100644 --- a/apps/sim/app/api/files/delete/route.ts +++ b/apps/sim/app/api/files/delete/route.ts @@ -1,7 +1,7 @@ import { createLogger } from '@sim/logger' import type { NextRequest } from 'next/server' import { NextResponse } from 'next/server' -import { checkHybridAuth } from '@/lib/auth/hybrid' +import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import type { StorageContext } from '@/lib/uploads/config' import { deleteFile, hasCloudStorage } from '@/lib/uploads/core/storage-service' import { extractStorageKey, inferContextFromKey } from '@/lib/uploads/utils/file-utils' @@ -24,7 +24,7 @@ const logger = createLogger('FilesDeleteAPI') */ export async function POST(request: NextRequest) { try { - const authResult = await checkHybridAuth(request, { requireWorkflowId: false }) + const authResult = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) if (!authResult.success || !authResult.userId) { logger.warn('Unauthorized file delete request', { diff --git a/apps/sim/app/api/files/download/route.ts b/apps/sim/app/api/files/download/route.ts index bd718ed8f..45f9ebb24 100644 --- a/apps/sim/app/api/files/download/route.ts +++ b/apps/sim/app/api/files/download/route.ts @@ -1,6 +1,6 @@ import { createLogger } from '@sim/logger' import { type NextRequest, NextResponse } from 'next/server' -import { checkHybridAuth } from '@/lib/auth/hybrid' +import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import type { StorageContext } from '@/lib/uploads/config' import { hasCloudStorage } from '@/lib/uploads/core/storage-service' import { verifyFileAccess } from '@/app/api/files/authorization' @@ -12,7 +12,7 @@ export const dynamic = 'force-dynamic' export async function POST(request: NextRequest) { try { - const authResult = await checkHybridAuth(request, { requireWorkflowId: false }) + const authResult = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) if (!authResult.success || !authResult.userId) { logger.warn('Unauthorized download URL request', { diff --git a/apps/sim/app/api/files/parse/route.test.ts b/apps/sim/app/api/files/parse/route.test.ts index 801795570..bfdc3bbe7 100644 --- a/apps/sim/app/api/files/parse/route.test.ts +++ b/apps/sim/app/api/files/parse/route.test.ts @@ -35,7 +35,7 @@ function setupFileApiMocks( } vi.doMock('@/lib/auth/hybrid', () => ({ - checkHybridAuth: vi.fn().mockResolvedValue({ + checkInternalAuth: vi.fn().mockResolvedValue({ success: authenticated, userId: authenticated ? 'test-user-id' : undefined, error: authenticated ? undefined : 'Unauthorized', diff --git a/apps/sim/app/api/files/parse/route.ts b/apps/sim/app/api/files/parse/route.ts index 25112133f..4b1882f86 100644 --- a/apps/sim/app/api/files/parse/route.ts +++ b/apps/sim/app/api/files/parse/route.ts @@ -5,7 +5,7 @@ import path from 'path' import { createLogger } from '@sim/logger' import binaryExtensionsList from 'binary-extensions' import { type NextRequest, NextResponse } from 'next/server' -import { checkHybridAuth } from '@/lib/auth/hybrid' +import { checkInternalAuth } from '@/lib/auth/hybrid' import { secureFetchWithPinnedIP, validateUrlWithDNS, @@ -66,7 +66,7 @@ export async function POST(request: NextRequest) { const startTime = Date.now() try { - const authResult = await checkHybridAuth(request, { requireWorkflowId: true }) + const authResult = await checkInternalAuth(request, { requireWorkflowId: true }) if (!authResult.success) { logger.warn('Unauthorized file parse request', { diff --git a/apps/sim/app/api/files/serve/[...path]/route.test.ts b/apps/sim/app/api/files/serve/[...path]/route.test.ts index fe833f3aa..d09adf048 100644 --- a/apps/sim/app/api/files/serve/[...path]/route.test.ts +++ b/apps/sim/app/api/files/serve/[...path]/route.test.ts @@ -55,7 +55,7 @@ describe('File Serve API Route', () => { }) vi.doMock('@/lib/auth/hybrid', () => ({ - checkHybridAuth: vi.fn().mockResolvedValue({ + checkSessionOrInternalAuth: vi.fn().mockResolvedValue({ success: true, userId: 'test-user-id', }), @@ -165,7 +165,7 @@ describe('File Serve API Route', () => { })) vi.doMock('@/lib/auth/hybrid', () => ({ - checkHybridAuth: vi.fn().mockResolvedValue({ + checkSessionOrInternalAuth: vi.fn().mockResolvedValue({ success: true, userId: 'test-user-id', }), @@ -226,7 +226,7 @@ describe('File Serve API Route', () => { })) vi.doMock('@/lib/auth/hybrid', () => ({ - checkHybridAuth: vi.fn().mockResolvedValue({ + checkSessionOrInternalAuth: vi.fn().mockResolvedValue({ success: true, userId: 'test-user-id', }), @@ -291,7 +291,7 @@ describe('File Serve API Route', () => { })) vi.doMock('@/lib/auth/hybrid', () => ({ - checkHybridAuth: vi.fn().mockResolvedValue({ + checkSessionOrInternalAuth: vi.fn().mockResolvedValue({ success: true, userId: 'test-user-id', }), @@ -350,7 +350,7 @@ describe('File Serve API Route', () => { for (const test of contentTypeTests) { it(`should serve ${test.ext} file with correct content type`, async () => { vi.doMock('@/lib/auth/hybrid', () => ({ - checkHybridAuth: vi.fn().mockResolvedValue({ + checkSessionOrInternalAuth: vi.fn().mockResolvedValue({ success: true, userId: 'test-user-id', }), diff --git a/apps/sim/app/api/files/serve/[...path]/route.ts b/apps/sim/app/api/files/serve/[...path]/route.ts index e339615f8..9c562fb26 100644 --- a/apps/sim/app/api/files/serve/[...path]/route.ts +++ b/apps/sim/app/api/files/serve/[...path]/route.ts @@ -2,7 +2,7 @@ import { readFile } from 'fs/promises' import { createLogger } from '@sim/logger' import type { NextRequest } from 'next/server' import { NextResponse } from 'next/server' -import { checkHybridAuth } from '@/lib/auth/hybrid' +import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import { CopilotFiles, isUsingCloudStorage } from '@/lib/uploads' import type { StorageContext } from '@/lib/uploads/config' import { downloadFile } from '@/lib/uploads/core/storage-service' @@ -49,7 +49,7 @@ export async function GET( return await handleLocalFilePublic(fullPath) } - const authResult = await checkHybridAuth(request, { requireWorkflowId: false }) + const authResult = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) if (!authResult.success || !authResult.userId) { logger.warn('Unauthorized file access attempt', { diff --git a/apps/sim/app/api/knowledge/[id]/tag-definitions/route.ts b/apps/sim/app/api/knowledge/[id]/tag-definitions/route.ts index ba52994c8..cbc5ac90e 100644 --- a/apps/sim/app/api/knowledge/[id]/tag-definitions/route.ts +++ b/apps/sim/app/api/knowledge/[id]/tag-definitions/route.ts @@ -2,7 +2,7 @@ import { randomUUID } from 'crypto' import { createLogger } from '@sim/logger' import { type NextRequest, NextResponse } from 'next/server' import { z } from 'zod' -import { checkHybridAuth } from '@/lib/auth/hybrid' +import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import { SUPPORTED_FIELD_TYPES } from '@/lib/knowledge/constants' import { createTagDefinition, getTagDefinitions } from '@/lib/knowledge/tags/service' import { checkKnowledgeBaseAccess } from '@/app/api/knowledge/utils' @@ -19,19 +19,11 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ id: try { logger.info(`[${requestId}] Getting tag definitions for knowledge base ${knowledgeBaseId}`) - const auth = await checkHybridAuth(req, { requireWorkflowId: false }) + const auth = await checkSessionOrInternalAuth(req, { requireWorkflowId: false }) if (!auth.success) { return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 }) } - // Only allow session and internal JWT auth (not API key) - if (auth.authType === 'api_key') { - return NextResponse.json( - { error: 'API key auth not supported for this endpoint' }, - { status: 401 } - ) - } - // For session auth, verify KB access. Internal JWT is trusted. if (auth.authType === 'session' && auth.userId) { const accessCheck = await checkKnowledgeBaseAccess(knowledgeBaseId, auth.userId) @@ -64,19 +56,11 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id: try { logger.info(`[${requestId}] Creating tag definition for knowledge base ${knowledgeBaseId}`) - const auth = await checkHybridAuth(req, { requireWorkflowId: false }) + const auth = await checkSessionOrInternalAuth(req, { requireWorkflowId: false }) if (!auth.success) { return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 }) } - // Only allow session and internal JWT auth (not API key) - if (auth.authType === 'api_key') { - return NextResponse.json( - { error: 'API key auth not supported for this endpoint' }, - { status: 401 } - ) - } - // For session auth, verify KB access. Internal JWT is trusted. if (auth.authType === 'session' && auth.userId) { const accessCheck = await checkKnowledgeBaseAccess(knowledgeBaseId, auth.userId) diff --git a/apps/sim/app/api/logs/execution/[executionId]/route.ts b/apps/sim/app/api/logs/execution/[executionId]/route.ts index 8d7004ef5..27a75298d 100644 --- a/apps/sim/app/api/logs/execution/[executionId]/route.ts +++ b/apps/sim/app/api/logs/execution/[executionId]/route.ts @@ -8,7 +8,7 @@ import { import { createLogger } from '@sim/logger' import { and, eq, inArray } from 'drizzle-orm' import { type NextRequest, NextResponse } from 'next/server' -import { checkHybridAuth } from '@/lib/auth/hybrid' +import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import { generateRequestId } from '@/lib/core/utils/request' import type { TraceSpan, WorkflowExecutionLog } from '@/lib/logs/types' @@ -23,7 +23,7 @@ export async function GET( try { const { executionId } = await params - const authResult = await checkHybridAuth(request, { requireWorkflowId: false }) + const authResult = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) if (!authResult.success || !authResult.userId) { logger.warn(`[${requestId}] Unauthorized execution data access attempt for: ${executionId}`) return NextResponse.json( diff --git a/apps/sim/app/api/memory/[id]/route.ts b/apps/sim/app/api/memory/[id]/route.ts index 2f5b5ae1c..4a4c96b11 100644 --- a/apps/sim/app/api/memory/[id]/route.ts +++ b/apps/sim/app/api/memory/[id]/route.ts @@ -4,7 +4,7 @@ import { createLogger } from '@sim/logger' import { and, eq } from 'drizzle-orm' import { type NextRequest, NextResponse } from 'next/server' import { z } from 'zod' -import { checkHybridAuth } from '@/lib/auth/hybrid' +import { checkInternalAuth } from '@/lib/auth/hybrid' import { generateRequestId } from '@/lib/core/utils/request' import { checkWorkspaceAccess } from '@/lib/workspaces/permissions/utils' @@ -36,7 +36,7 @@ async function validateMemoryAccess( requestId: string, action: 'read' | 'write' ): Promise<{ userId: string } | { error: NextResponse }> { - const authResult = await checkHybridAuth(request, { requireWorkflowId: false }) + const authResult = await checkInternalAuth(request, { requireWorkflowId: false }) if (!authResult.success || !authResult.userId) { logger.warn(`[${requestId}] Unauthorized memory ${action} attempt`) return { diff --git a/apps/sim/app/api/memory/route.ts b/apps/sim/app/api/memory/route.ts index 072756c7a..c5a4638d7 100644 --- a/apps/sim/app/api/memory/route.ts +++ b/apps/sim/app/api/memory/route.ts @@ -3,7 +3,7 @@ import { memory } from '@sim/db/schema' import { createLogger } from '@sim/logger' import { and, eq, isNull, like } from 'drizzle-orm' import { type NextRequest, NextResponse } from 'next/server' -import { checkHybridAuth } from '@/lib/auth/hybrid' +import { checkInternalAuth } from '@/lib/auth/hybrid' import { generateRequestId } from '@/lib/core/utils/request' import { checkWorkspaceAccess } from '@/lib/workspaces/permissions/utils' @@ -16,7 +16,7 @@ export async function GET(request: NextRequest) { const requestId = generateRequestId() try { - const authResult = await checkHybridAuth(request) + const authResult = await checkInternalAuth(request) if (!authResult.success || !authResult.userId) { logger.warn(`[${requestId}] Unauthorized memory access attempt`) return NextResponse.json( @@ -89,7 +89,7 @@ export async function POST(request: NextRequest) { const requestId = generateRequestId() try { - const authResult = await checkHybridAuth(request) + const authResult = await checkInternalAuth(request) if (!authResult.success || !authResult.userId) { logger.warn(`[${requestId}] Unauthorized memory creation attempt`) return NextResponse.json( @@ -228,7 +228,7 @@ export async function DELETE(request: NextRequest) { const requestId = generateRequestId() try { - const authResult = await checkHybridAuth(request) + const authResult = await checkInternalAuth(request) if (!authResult.success || !authResult.userId) { logger.warn(`[${requestId}] Unauthorized memory deletion attempt`) return NextResponse.json( diff --git a/apps/sim/app/api/tools/a2a/cancel-task/route.ts b/apps/sim/app/api/tools/a2a/cancel-task/route.ts index 9298273ce..d36b63e6b 100644 --- a/apps/sim/app/api/tools/a2a/cancel-task/route.ts +++ b/apps/sim/app/api/tools/a2a/cancel-task/route.ts @@ -3,7 +3,7 @@ import { createLogger } from '@sim/logger' import { type NextRequest, NextResponse } from 'next/server' import { z } from 'zod' import { createA2AClient } from '@/lib/a2a/utils' -import { checkHybridAuth } from '@/lib/auth/hybrid' +import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import { generateRequestId } from '@/lib/core/utils/request' const logger = createLogger('A2ACancelTaskAPI') @@ -20,7 +20,7 @@ export async function POST(request: NextRequest) { const requestId = generateRequestId() try { - const authResult = await checkHybridAuth(request, { requireWorkflowId: false }) + const authResult = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) if (!authResult.success) { logger.warn(`[${requestId}] Unauthorized A2A cancel task attempt`) diff --git a/apps/sim/app/api/tools/a2a/delete-push-notification/route.ts b/apps/sim/app/api/tools/a2a/delete-push-notification/route.ts index f222ef883..e2ed939c5 100644 --- a/apps/sim/app/api/tools/a2a/delete-push-notification/route.ts +++ b/apps/sim/app/api/tools/a2a/delete-push-notification/route.ts @@ -2,7 +2,7 @@ import { createLogger } from '@sim/logger' import { type NextRequest, NextResponse } from 'next/server' import { z } from 'zod' import { createA2AClient } from '@/lib/a2a/utils' -import { checkHybridAuth } from '@/lib/auth/hybrid' +import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import { generateRequestId } from '@/lib/core/utils/request' export const dynamic = 'force-dynamic' @@ -20,7 +20,7 @@ export async function POST(request: NextRequest) { const requestId = generateRequestId() try { - const authResult = await checkHybridAuth(request, { requireWorkflowId: false }) + const authResult = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) if (!authResult.success) { logger.warn( diff --git a/apps/sim/app/api/tools/a2a/get-agent-card/route.ts b/apps/sim/app/api/tools/a2a/get-agent-card/route.ts index c26ed764b..8562b651b 100644 --- a/apps/sim/app/api/tools/a2a/get-agent-card/route.ts +++ b/apps/sim/app/api/tools/a2a/get-agent-card/route.ts @@ -2,7 +2,7 @@ import { createLogger } from '@sim/logger' import { type NextRequest, NextResponse } from 'next/server' import { z } from 'zod' import { createA2AClient } from '@/lib/a2a/utils' -import { checkHybridAuth } from '@/lib/auth/hybrid' +import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import { generateRequestId } from '@/lib/core/utils/request' export const dynamic = 'force-dynamic' @@ -18,7 +18,7 @@ export async function POST(request: NextRequest) { const requestId = generateRequestId() try { - const authResult = await checkHybridAuth(request, { requireWorkflowId: false }) + const authResult = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) if (!authResult.success) { logger.warn(`[${requestId}] Unauthorized A2A get agent card attempt: ${authResult.error}`) diff --git a/apps/sim/app/api/tools/a2a/get-push-notification/route.ts b/apps/sim/app/api/tools/a2a/get-push-notification/route.ts index 5feedf4de..337e79a9d 100644 --- a/apps/sim/app/api/tools/a2a/get-push-notification/route.ts +++ b/apps/sim/app/api/tools/a2a/get-push-notification/route.ts @@ -2,7 +2,7 @@ import { createLogger } from '@sim/logger' import { type NextRequest, NextResponse } from 'next/server' import { z } from 'zod' import { createA2AClient } from '@/lib/a2a/utils' -import { checkHybridAuth } from '@/lib/auth/hybrid' +import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import { generateRequestId } from '@/lib/core/utils/request' export const dynamic = 'force-dynamic' @@ -19,7 +19,7 @@ export async function POST(request: NextRequest) { const requestId = generateRequestId() try { - const authResult = await checkHybridAuth(request, { requireWorkflowId: false }) + const authResult = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) if (!authResult.success) { logger.warn( diff --git a/apps/sim/app/api/tools/a2a/get-task/route.ts b/apps/sim/app/api/tools/a2a/get-task/route.ts index 35aa5e278..eda09dfd0 100644 --- a/apps/sim/app/api/tools/a2a/get-task/route.ts +++ b/apps/sim/app/api/tools/a2a/get-task/route.ts @@ -3,7 +3,7 @@ import { createLogger } from '@sim/logger' import { type NextRequest, NextResponse } from 'next/server' import { z } from 'zod' import { createA2AClient } from '@/lib/a2a/utils' -import { checkHybridAuth } from '@/lib/auth/hybrid' +import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import { generateRequestId } from '@/lib/core/utils/request' export const dynamic = 'force-dynamic' @@ -21,7 +21,7 @@ export async function POST(request: NextRequest) { const requestId = generateRequestId() try { - const authResult = await checkHybridAuth(request, { requireWorkflowId: false }) + const authResult = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) if (!authResult.success) { logger.warn(`[${requestId}] Unauthorized A2A get task attempt: ${authResult.error}`) diff --git a/apps/sim/app/api/tools/a2a/resubscribe/route.ts b/apps/sim/app/api/tools/a2a/resubscribe/route.ts index 75c0d24ae..38ac95a3c 100644 --- a/apps/sim/app/api/tools/a2a/resubscribe/route.ts +++ b/apps/sim/app/api/tools/a2a/resubscribe/route.ts @@ -10,7 +10,7 @@ import { createLogger } from '@sim/logger' import { type NextRequest, NextResponse } from 'next/server' import { z } from 'zod' import { createA2AClient, extractTextContent, isTerminalState } from '@/lib/a2a/utils' -import { checkHybridAuth } from '@/lib/auth/hybrid' +import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import { generateRequestId } from '@/lib/core/utils/request' const logger = createLogger('A2AResubscribeAPI') @@ -27,7 +27,7 @@ export async function POST(request: NextRequest) { const requestId = generateRequestId() try { - const authResult = await checkHybridAuth(request, { requireWorkflowId: false }) + const authResult = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) if (!authResult.success) { logger.warn(`[${requestId}] Unauthorized A2A resubscribe attempt`) diff --git a/apps/sim/app/api/tools/a2a/send-message/route.ts b/apps/sim/app/api/tools/a2a/send-message/route.ts index 4c98dc67a..1cf7f966e 100644 --- a/apps/sim/app/api/tools/a2a/send-message/route.ts +++ b/apps/sim/app/api/tools/a2a/send-message/route.ts @@ -3,7 +3,7 @@ import { createLogger } from '@sim/logger' import { type NextRequest, NextResponse } from 'next/server' import { z } from 'zod' import { createA2AClient, extractTextContent, isTerminalState } from '@/lib/a2a/utils' -import { checkHybridAuth } from '@/lib/auth/hybrid' +import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import { validateUrlWithDNS } from '@/lib/core/security/input-validation.server' import { generateRequestId } from '@/lib/core/utils/request' @@ -32,7 +32,7 @@ export async function POST(request: NextRequest) { const requestId = generateRequestId() try { - const authResult = await checkHybridAuth(request, { requireWorkflowId: false }) + const authResult = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) if (!authResult.success) { logger.warn(`[${requestId}] Unauthorized A2A send message attempt: ${authResult.error}`) diff --git a/apps/sim/app/api/tools/a2a/set-push-notification/route.ts b/apps/sim/app/api/tools/a2a/set-push-notification/route.ts index 132bb6be2..e12fbd6d9 100644 --- a/apps/sim/app/api/tools/a2a/set-push-notification/route.ts +++ b/apps/sim/app/api/tools/a2a/set-push-notification/route.ts @@ -2,7 +2,7 @@ import { createLogger } from '@sim/logger' import { type NextRequest, NextResponse } from 'next/server' import { z } from 'zod' import { createA2AClient } from '@/lib/a2a/utils' -import { checkHybridAuth } from '@/lib/auth/hybrid' +import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import { validateUrlWithDNS } from '@/lib/core/security/input-validation.server' import { generateRequestId } from '@/lib/core/utils/request' @@ -22,7 +22,7 @@ export async function POST(request: NextRequest) { const requestId = generateRequestId() try { - const authResult = await checkHybridAuth(request, { requireWorkflowId: false }) + const authResult = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) if (!authResult.success) { logger.warn(`[${requestId}] Unauthorized A2A set push notification attempt`, { diff --git a/apps/sim/app/api/users/me/usage-logs/route.ts b/apps/sim/app/api/users/me/usage-logs/route.ts index 3c4f1229f..038cf2ece 100644 --- a/apps/sim/app/api/users/me/usage-logs/route.ts +++ b/apps/sim/app/api/users/me/usage-logs/route.ts @@ -1,7 +1,7 @@ import { createLogger } from '@sim/logger' import { type NextRequest, NextResponse } from 'next/server' import { z } from 'zod' -import { checkHybridAuth } from '@/lib/auth/hybrid' +import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import { getUserUsageLogs, type UsageLogSource } from '@/lib/billing/core/usage-log' const logger = createLogger('UsageLogsAPI') @@ -20,7 +20,7 @@ const QuerySchema = z.object({ */ export async function GET(req: NextRequest) { try { - const auth = await checkHybridAuth(req, { requireWorkflowId: false }) + const auth = await checkSessionOrInternalAuth(req, { requireWorkflowId: false }) if (!auth.success || !auth.userId) { return NextResponse.json({ error: 'Unauthorized' }, { status: 401 }) diff --git a/apps/sim/app/workspace/[workspaceId]/logs/components/log-details/components/file-download/file-download.tsx b/apps/sim/app/workspace/[workspaceId]/logs/components/log-details/components/file-download/file-download.tsx index 3dd05f8d8..5985a00c0 100644 --- a/apps/sim/app/workspace/[workspaceId]/logs/components/log-details/components/file-download/file-download.tsx +++ b/apps/sim/app/workspace/[workspaceId]/logs/components/log-details/components/file-download/file-download.tsx @@ -74,8 +74,7 @@ function FileCard({ file, isExecutionFile = false, workspaceId }: FileCardProps) } if (isExecutionFile) { - const serveUrl = - file.url || `/api/files/serve/${encodeURIComponent(file.key)}?context=execution` + const serveUrl = `/api/files/serve/${encodeURIComponent(file.key)}?context=execution` window.open(serveUrl, '_blank') logger.info(`Opened execution file serve URL: ${serveUrl}`) } else { @@ -88,16 +87,12 @@ function FileCard({ file, isExecutionFile = false, workspaceId }: FileCardProps) logger.warn( `Could not construct viewer URL for file: ${file.name}, falling back to serve URL` ) - const serveUrl = - file.url || `/api/files/serve/${encodeURIComponent(file.key)}?context=workspace` + const serveUrl = `/api/files/serve/${encodeURIComponent(file.key)}?context=workspace` window.open(serveUrl, '_blank') } } } catch (error) { logger.error(`Failed to download file ${file.name}:`, error) - if (file.url) { - window.open(file.url, '_blank') - } } finally { setIsDownloading(false) } @@ -198,8 +193,7 @@ export function FileDownload({ } if (isExecutionFile) { - const serveUrl = - file.url || `/api/files/serve/${encodeURIComponent(file.key)}?context=execution` + const serveUrl = `/api/files/serve/${encodeURIComponent(file.key)}?context=execution` window.open(serveUrl, '_blank') logger.info(`Opened execution file serve URL: ${serveUrl}`) } else { @@ -212,16 +206,12 @@ export function FileDownload({ logger.warn( `Could not construct viewer URL for file: ${file.name}, falling back to serve URL` ) - const serveUrl = - file.url || `/api/files/serve/${encodeURIComponent(file.key)}?context=workspace` + const serveUrl = `/api/files/serve/${encodeURIComponent(file.key)}?context=workspace` window.open(serveUrl, '_blank') } } } catch (error) { logger.error(`Failed to download file ${file.name}:`, error) - if (file.url) { - window.open(file.url, '_blank') - } } finally { setIsDownloading(false) } diff --git a/apps/sim/blocks/blocks/agent.ts b/apps/sim/blocks/blocks/agent.ts index bf8ec0d66..7e7b12f96 100644 --- a/apps/sim/blocks/blocks/agent.ts +++ b/apps/sim/blocks/blocks/agent.ts @@ -1,11 +1,10 @@ import { createLogger } from '@sim/logger' import { AgentIcon } from '@/components/icons' -import { isHosted } from '@/lib/core/config/feature-flags' import type { BlockConfig } from '@/blocks/types' import { AuthMode } from '@/blocks/types' +import { getApiKeyCondition } from '@/blocks/utils' import { getBaseModelProviders, - getHostedModels, getMaxTemperature, getProviderIcon, getReasoningEffortValuesForModel, @@ -17,15 +16,6 @@ import { providers, supportsTemperature, } from '@/providers/utils' - -const getCurrentOllamaModels = () => { - return useProvidersStore.getState().providers.ollama.models -} - -const getCurrentVLLMModels = () => { - return useProvidersStore.getState().providers.vllm.models -} - import { useProvidersStore } from '@/stores/providers' import type { ToolResponse } from '@/tools/types' @@ -421,23 +411,7 @@ Return ONLY the JSON array.`, password: true, connectionDroppable: false, required: true, - // Hide API key for hosted models, Ollama models, vLLM models, Vertex models (uses OAuth), and Bedrock (uses AWS credentials) - condition: isHosted - ? { - field: 'model', - value: [...getHostedModels(), ...providers.vertex.models, ...providers.bedrock.models], - not: true, // Show for all models EXCEPT those listed - } - : () => ({ - field: 'model', - value: [ - ...getCurrentOllamaModels(), - ...getCurrentVLLMModels(), - ...providers.vertex.models, - ...providers.bedrock.models, - ], - not: true, // Show for all models EXCEPT Ollama, vLLM, Vertex, and Bedrock models - }), + condition: getApiKeyCondition(), }, { id: 'memoryType', diff --git a/apps/sim/blocks/types.ts b/apps/sim/blocks/types.ts index a9904dd2e..08a716925 100644 --- a/apps/sim/blocks/types.ts +++ b/apps/sim/blocks/types.ts @@ -208,7 +208,7 @@ export interface SubBlockConfig { not?: boolean } } - | (() => { + | ((values?: Record) => { field: string value: string | number | boolean | Array not?: boolean @@ -261,7 +261,7 @@ export interface SubBlockConfig { not?: boolean } } - | (() => { + | ((values?: Record) => { field: string value: string | number | boolean | Array not?: boolean diff --git a/apps/sim/blocks/utils.ts b/apps/sim/blocks/utils.ts index eed4a5c37..8c003e0ad 100644 --- a/apps/sim/blocks/utils.ts +++ b/apps/sim/blocks/utils.ts @@ -1,6 +1,6 @@ import { isHosted } from '@/lib/core/config/feature-flags' import type { BlockOutput, OutputFieldDefinition, SubBlockConfig } from '@/blocks/types' -import { getHostedModels, providers } from '@/providers/utils' +import { getHostedModels, getProviderFromModel, providers } from '@/providers/utils' import { useProvidersStore } from '@/stores/providers/store' /** @@ -48,11 +48,54 @@ const getCurrentOllamaModels = () => { return useProvidersStore.getState().providers.ollama.models } -/** - * Helper to get current vLLM models from store - */ -const getCurrentVLLMModels = () => { - return useProvidersStore.getState().providers.vllm.models +function buildModelVisibilityCondition(model: string, shouldShow: boolean) { + if (!model) { + return { field: 'model', value: '__no_model_selected__' } + } + + return shouldShow ? { field: 'model', value: model } : { field: 'model', value: model, not: true } +} + +function shouldRequireApiKeyForModel(model: string): boolean { + const normalizedModel = model.trim().toLowerCase() + if (!normalizedModel) return false + + const hostedModels = getHostedModels() + const isHostedModel = hostedModels.some( + (hostedModel) => hostedModel.toLowerCase() === normalizedModel + ) + if (isHosted && isHostedModel) return false + + if (normalizedModel.startsWith('vertex/') || normalizedModel.startsWith('bedrock/')) { + return false + } + + if (normalizedModel.startsWith('vllm/')) { + return false + } + + const currentOllamaModels = getCurrentOllamaModels() + if (currentOllamaModels.some((ollamaModel) => ollamaModel.toLowerCase() === normalizedModel)) { + return false + } + + if (!isHosted) { + try { + const providerId = getProviderFromModel(model) + if ( + providerId === 'ollama' || + providerId === 'vllm' || + providerId === 'vertex' || + providerId === 'bedrock' + ) { + return false + } + } catch { + // If model resolution fails, fall through and require an API key. + } + } + + return true } /** @@ -60,22 +103,11 @@ const getCurrentVLLMModels = () => { * Handles hosted vs self-hosted environments and excludes providers that don't need API key. */ export function getApiKeyCondition() { - return isHosted - ? { - field: 'model', - value: [...getHostedModels(), ...providers.vertex.models, ...providers.bedrock.models], - not: true, - } - : () => ({ - field: 'model', - value: [ - ...getCurrentOllamaModels(), - ...getCurrentVLLMModels(), - ...providers.vertex.models, - ...providers.bedrock.models, - ], - not: true, - }) + return (values?: Record) => { + const model = typeof values?.model === 'string' ? values.model : '' + const shouldShow = shouldRequireApiKeyForModel(model) + return buildModelVisibilityCondition(model, shouldShow) + } } /** diff --git a/apps/sim/executor/handlers/agent/agent-handler.ts b/apps/sim/executor/handlers/agent/agent-handler.ts index a1f0cee0d..524407506 100644 --- a/apps/sim/executor/handlers/agent/agent-handler.ts +++ b/apps/sim/executor/handlers/agent/agent-handler.ts @@ -378,6 +378,9 @@ export class AgentBlockHandler implements BlockHandler { if (ctx.workflowId) { params.workflowId = ctx.workflowId } + if (ctx.userId) { + params.userId = ctx.userId + } const url = buildAPIUrl('/api/tools/custom', params) const response = await fetch(url.toString(), { @@ -488,7 +491,9 @@ export class AgentBlockHandler implements BlockHandler { usageControl: tool.usageControl || 'auto', executeFunction: async (callParams: Record) => { const headers = await buildAuthHeaders() - const execUrl = buildAPIUrl('/api/mcp/tools/execute') + const execParams: Record = {} + if (ctx.userId) execParams.userId = ctx.userId + const execUrl = buildAPIUrl('/api/mcp/tools/execute', execParams) const execResponse = await fetch(execUrl.toString(), { method: 'POST', @@ -597,6 +602,7 @@ export class AgentBlockHandler implements BlockHandler { serverId, workspaceId: ctx.workspaceId, workflowId: ctx.workflowId, + ...(ctx.userId ? { userId: ctx.userId } : {}), }) const maxAttempts = 2 @@ -671,7 +677,9 @@ export class AgentBlockHandler implements BlockHandler { usageControl: tool.usageControl || 'auto', executeFunction: async (callParams: Record) => { const headers = await buildAuthHeaders() - const execUrl = buildAPIUrl('/api/mcp/tools/execute') + const discoverExecParams: Record = {} + if (ctx.userId) discoverExecParams.userId = ctx.userId + const execUrl = buildAPIUrl('/api/mcp/tools/execute', discoverExecParams) const execResponse = await fetch(execUrl.toString(), { method: 'POST', @@ -1056,6 +1064,7 @@ export class AgentBlockHandler implements BlockHandler { responseFormat: providerRequest.responseFormat, workflowId: providerRequest.workflowId, workspaceId: ctx.workspaceId, + userId: ctx.userId, stream: providerRequest.stream, messages: 'messages' in providerRequest ? providerRequest.messages : undefined, environmentVariables: ctx.environmentVariables || {}, diff --git a/apps/sim/executor/handlers/evaluator/evaluator-handler.ts b/apps/sim/executor/handlers/evaluator/evaluator-handler.ts index 8c432f1da..65ea2f9ea 100644 --- a/apps/sim/executor/handlers/evaluator/evaluator-handler.ts +++ b/apps/sim/executor/handlers/evaluator/evaluator-handler.ts @@ -104,7 +104,7 @@ export class EvaluatorBlockHandler implements BlockHandler { } try { - const url = buildAPIUrl('/api/providers') + const url = buildAPIUrl('/api/providers', ctx.userId ? { userId: ctx.userId } : {}) const providerRequest: Record = { provider: providerId, diff --git a/apps/sim/executor/handlers/router/router-handler.ts b/apps/sim/executor/handlers/router/router-handler.ts index 541cdccca..a42956c66 100644 --- a/apps/sim/executor/handlers/router/router-handler.ts +++ b/apps/sim/executor/handlers/router/router-handler.ts @@ -80,6 +80,7 @@ export class RouterBlockHandler implements BlockHandler { try { const url = new URL('/api/providers', getBaseUrl()) + if (ctx.userId) url.searchParams.set('userId', ctx.userId) const messages = [{ role: 'user', content: routerConfig.prompt }] const systemPrompt = generateRouterPrompt(routerConfig.prompt, targetBlocks) @@ -209,6 +210,7 @@ export class RouterBlockHandler implements BlockHandler { try { const url = new URL('/api/providers', getBaseUrl()) + if (ctx.userId) url.searchParams.set('userId', ctx.userId) const messages = [{ role: 'user', content: routerConfig.context }] const systemPrompt = generateRouterV2Prompt(routerConfig.context, routes) diff --git a/apps/sim/lib/auth/credential-access.ts b/apps/sim/lib/auth/credential-access.ts index be7b7e1bd..61b0f655a 100644 --- a/apps/sim/lib/auth/credential-access.ts +++ b/apps/sim/lib/auth/credential-access.ts @@ -2,13 +2,13 @@ import { db } from '@sim/db' import { account, workflow as workflowTable } from '@sim/db/schema' import { eq } from 'drizzle-orm' import type { NextRequest } from 'next/server' -import { checkHybridAuth } from '@/lib/auth/hybrid' +import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import { getUserEntityPermissions } from '@/lib/workspaces/permissions/utils' export interface CredentialAccessResult { ok: boolean error?: string - authType?: 'session' | 'api_key' | 'internal_jwt' + authType?: 'session' | 'internal_jwt' requesterUserId?: string credentialOwnerUserId?: string workspaceId?: string @@ -16,10 +16,10 @@ export interface CredentialAccessResult { /** * Centralizes auth + collaboration rules for credential use. - * - Uses checkHybridAuth to authenticate the caller + * - Uses checkSessionOrInternalAuth to authenticate the caller * - Fetches credential owner * - Authorization rules: - * - session/api_key: allow if requester owns the credential; otherwise require workflowId and + * - session: allow if requester owns the credential; otherwise require workflowId and * verify BOTH requester and owner have access to the workflow's workspace * - internal_jwt: require workflowId (by default) and verify credential owner has access to the * workflow's workspace (requester identity is the system/workflow) @@ -30,7 +30,9 @@ export async function authorizeCredentialUse( ): Promise { const { credentialId, workflowId, requireWorkflowIdForInternal = true } = params - const auth = await checkHybridAuth(request, { requireWorkflowId: requireWorkflowIdForInternal }) + const auth = await checkSessionOrInternalAuth(request, { + requireWorkflowId: requireWorkflowIdForInternal, + }) if (!auth.success || !auth.userId) { return { ok: false, error: auth.error || 'Authentication required' } } @@ -52,7 +54,7 @@ export async function authorizeCredentialUse( if (auth.authType !== 'internal_jwt' && auth.userId === credentialOwnerUserId) { return { ok: true, - authType: auth.authType, + authType: auth.authType as CredentialAccessResult['authType'], requesterUserId: auth.userId, credentialOwnerUserId, } @@ -85,14 +87,14 @@ export async function authorizeCredentialUse( } return { ok: true, - authType: auth.authType, + authType: auth.authType as CredentialAccessResult['authType'], requesterUserId: auth.userId, credentialOwnerUserId, workspaceId: wf.workspaceId, } } - // Session/API key: verify BOTH requester and owner belong to the workflow's workspace + // Session: verify BOTH requester and owner belong to the workflow's workspace const requesterPerm = await getUserEntityPermissions(auth.userId, 'workspace', wf.workspaceId) const ownerPerm = await getUserEntityPermissions( credentialOwnerUserId, @@ -105,7 +107,7 @@ export async function authorizeCredentialUse( return { ok: true, - authType: auth.authType, + authType: auth.authType as CredentialAccessResult['authType'], requesterUserId: auth.userId, credentialOwnerUserId, workspaceId: wf.workspaceId, diff --git a/apps/sim/lib/mcp/middleware.ts b/apps/sim/lib/mcp/middleware.ts index f994990c6..f95e4eac7 100644 --- a/apps/sim/lib/mcp/middleware.ts +++ b/apps/sim/lib/mcp/middleware.ts @@ -1,6 +1,6 @@ import { createLogger } from '@sim/logger' import type { NextRequest, NextResponse } from 'next/server' -import { checkHybridAuth } from '@/lib/auth/hybrid' +import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid' import { generateRequestId } from '@/lib/core/utils/request' import { createMcpErrorResponse } from '@/lib/mcp/utils' import { getUserEntityPermissions } from '@/lib/workspaces/permissions/utils' @@ -43,7 +43,7 @@ async function validateMcpAuth( const requestId = generateRequestId() try { - const auth = await checkHybridAuth(request, { requireWorkflowId: false }) + const auth = await checkSessionOrInternalAuth(request, { requireWorkflowId: false }) if (!auth.success || !auth.userId) { logger.warn(`[${requestId}] Authentication failed: ${auth.error}`) return { diff --git a/apps/sim/lib/webhooks/processor.ts b/apps/sim/lib/webhooks/processor.ts index 6f738855f..15013ab2f 100644 --- a/apps/sim/lib/webhooks/processor.ts +++ b/apps/sim/lib/webhooks/processor.ts @@ -24,6 +24,7 @@ import { validateTypeformSignature, verifyProviderWebhook, } from '@/lib/webhooks/utils.server' +import { getWorkspaceBilledAccountUserId } from '@/lib/workspaces/utils' import { executeWebhookJob } from '@/background/webhook-execution' import { resolveEnvVarReferences } from '@/executor/utils/reference-validation' import { isGitHubEventMatch } from '@/triggers/github/utils' @@ -1003,10 +1004,23 @@ export async function queueWebhookExecution( } } + if (!foundWorkflow.workspaceId) { + logger.error(`[${options.requestId}] Workflow ${foundWorkflow.id} has no workspaceId`) + return NextResponse.json({ error: 'Workflow has no associated workspace' }, { status: 500 }) + } + + const actorUserId = await getWorkspaceBilledAccountUserId(foundWorkflow.workspaceId) + if (!actorUserId) { + logger.error( + `[${options.requestId}] No billing account for workspace ${foundWorkflow.workspaceId}` + ) + return NextResponse.json({ error: 'Unable to resolve billing account' }, { status: 500 }) + } + const payload = { webhookId: foundWebhook.id, workflowId: foundWorkflow.id, - userId: foundWorkflow.userId, + userId: actorUserId, provider: foundWebhook.provider, body, headers, @@ -1017,7 +1031,7 @@ export async function queueWebhookExecution( const jobQueue = await getJobQueue() const jobId = await jobQueue.enqueue('webhook-execution', payload, { - metadata: { workflowId: foundWorkflow.id, userId: foundWorkflow.userId }, + metadata: { workflowId: foundWorkflow.id, userId: actorUserId }, }) logger.info( `[${options.requestId}] Queued webhook execution task ${jobId} for ${foundWebhook.provider} webhook` diff --git a/apps/sim/lib/workflows/subblocks/visibility.test.ts b/apps/sim/lib/workflows/subblocks/visibility.test.ts index 07b1f1818..b55bfad5f 100644 --- a/apps/sim/lib/workflows/subblocks/visibility.test.ts +++ b/apps/sim/lib/workflows/subblocks/visibility.test.ts @@ -156,6 +156,15 @@ describe('evaluateSubBlockCondition', () => { expect(evaluateSubBlockCondition(condition, values)).toBe(true) }) + it.concurrent('passes current values into function conditions', () => { + const condition = (values?: Record) => ({ + field: 'model', + value: typeof values?.model === 'string' ? values.model : '__no_model_selected__', + }) + const values = { model: 'ollama/gemma3:4b' } + expect(evaluateSubBlockCondition(condition, values)).toBe(true) + }) + it.concurrent('handles boolean values', () => { const condition = { field: 'enabled', value: true } const values = { enabled: true } diff --git a/apps/sim/lib/workflows/subblocks/visibility.ts b/apps/sim/lib/workflows/subblocks/visibility.ts index 74eda40fd..1ce0076b4 100644 --- a/apps/sim/lib/workflows/subblocks/visibility.ts +++ b/apps/sim/lib/workflows/subblocks/visibility.ts @@ -100,11 +100,14 @@ export function resolveCanonicalMode( * Evaluate a subblock condition against a map of raw values. */ export function evaluateSubBlockCondition( - condition: SubBlockCondition | (() => SubBlockCondition) | undefined, + condition: + | SubBlockCondition + | ((values?: Record) => SubBlockCondition) + | undefined, values: Record ): boolean { if (!condition) return true - const actual = typeof condition === 'function' ? condition() : condition + const actual = typeof condition === 'function' ? condition(values) : condition const fieldValue = values[actual.field] const valueMatch = Array.isArray(actual.value) ? fieldValue != null && diff --git a/apps/sim/tools/index.ts b/apps/sim/tools/index.ts index 09c3ac616..040a40a27 100644 --- a/apps/sim/tools/index.ts +++ b/apps/sim/tools/index.ts @@ -961,6 +961,7 @@ async function executeMcpTool( const workspaceId = params._context?.workspaceId || executionContext?.workspaceId const workflowId = params._context?.workflowId || executionContext?.workflowId + const userId = params._context?.userId || executionContext?.userId if (!workspaceId) { return { @@ -1002,7 +1003,12 @@ async function executeMcpTool( hasToolSchema: !!toolSchema, }) - const response = await fetch(`${baseUrl}/api/mcp/tools/execute`, { + const mcpUrl = new URL('/api/mcp/tools/execute', baseUrl) + if (userId) { + mcpUrl.searchParams.set('userId', userId) + } + + const response = await fetch(mcpUrl.toString(), { method: 'POST', headers, body, From 925f06add77e6e1b526a353c93ac7158825c24fc Mon Sep 17 00:00:00 2001 From: Vikhyath Mondreti Date: Fri, 6 Feb 2026 22:12:40 -0800 Subject: [PATCH 5/8] improvement(preview): render nested values like input format correctly in workflow execution preview (#3154) * improvement(preview): nested workflow snapshots/preview when not executed * improvements to resolve nested subblock values * few more things * add try catch * fix fallback case * deps --- .../credential-selector.tsx | 8 ++- .../document-selector/document-selector.tsx | 5 +- .../document-tag-entry/document-tag-entry.tsx | 5 +- .../file-selector/file-selector-input.tsx | 49 ++++++++++++------- .../components/folder-selector-input.tsx | 14 +++++- .../input-mapping/input-mapping.tsx | 9 +++- .../knowledge-tag-filters.tsx | 5 +- .../mcp-dynamic-args/mcp-dynamic-args.tsx | 13 ++++- .../mcp-server-modal/mcp-tool-selector.tsx | 8 ++- .../project-selector-input.tsx | 16 ++++-- .../sheet-selector/sheet-selector-input.tsx | 8 ++- .../slack-selector/slack-selector-input.tsx | 13 +++-- .../components/tool-input/tool-input.tsx | 1 + .../editor/components/sub-block/sub-block.tsx | 10 ++++ .../editor/components/sub-block/utils.ts | 18 +++++++ .../preview-editor/preview-editor.tsx | 16 ++++-- .../lib/logs/execution/snapshot/service.ts | 16 +++++- 17 files changed, 171 insertions(+), 43 deletions(-) create mode 100644 apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/utils.ts diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/credential-selector/credential-selector.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/credential-selector/credential-selector.tsx index 79087c7c4..378a9baed 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/credential-selector/credential-selector.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/credential-selector/credential-selector.tsx @@ -35,6 +35,7 @@ interface CredentialSelectorProps { disabled?: boolean isPreview?: boolean previewValue?: any | null + previewContextValues?: Record } export function CredentialSelector({ @@ -43,6 +44,7 @@ export function CredentialSelector({ disabled = false, isPreview = false, previewValue, + previewContextValues, }: CredentialSelectorProps) { const [showOAuthModal, setShowOAuthModal] = useState(false) const [editingValue, setEditingValue] = useState('') @@ -67,7 +69,11 @@ export function CredentialSelector({ canUseCredentialSets ) - const { depsSatisfied, dependsOn } = useDependsOnGate(blockId, subBlock, { disabled, isPreview }) + const { depsSatisfied, dependsOn } = useDependsOnGate(blockId, subBlock, { + disabled, + isPreview, + previewContextValues, + }) const hasDependencies = dependsOn.length > 0 const effectiveDisabled = disabled || (hasDependencies && !depsSatisfied) diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/document-selector/document-selector.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/document-selector/document-selector.tsx index 012c78338..f1e47ab71 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/document-selector/document-selector.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/document-selector/document-selector.tsx @@ -5,6 +5,7 @@ import { Tooltip } from '@/components/emcn' import { SelectorCombobox } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/selector-combobox/selector-combobox' import { useDependsOnGate } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-depends-on-gate' import { useSubBlockValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-value' +import { resolvePreviewContextValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/utils' import type { SubBlockConfig } from '@/blocks/types' import type { SelectorContext } from '@/hooks/selectors/types' @@ -33,7 +34,9 @@ export function DocumentSelector({ previewContextValues, }) const [knowledgeBaseIdFromStore] = useSubBlockValue(blockId, 'knowledgeBaseId') - const knowledgeBaseIdValue = previewContextValues?.knowledgeBaseId ?? knowledgeBaseIdFromStore + const knowledgeBaseIdValue = previewContextValues + ? resolvePreviewContextValue(previewContextValues.knowledgeBaseId) + : knowledgeBaseIdFromStore const normalizedKnowledgeBaseId = typeof knowledgeBaseIdValue === 'string' && knowledgeBaseIdValue.trim().length > 0 ? knowledgeBaseIdValue diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/document-tag-entry/document-tag-entry.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/document-tag-entry/document-tag-entry.tsx index ffb5122db..b21c6f9d4 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/document-tag-entry/document-tag-entry.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/document-tag-entry/document-tag-entry.tsx @@ -17,6 +17,7 @@ import { formatDisplayText } from '@/app/workspace/[workspaceId]/w/[workflowId]/ import { TagDropdown } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tag-dropdown/tag-dropdown' import { useSubBlockInput } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-input' import { useSubBlockValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-value' +import { resolvePreviewContextValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/utils' import { useAccessibleReferencePrefixes } from '@/app/workspace/[workspaceId]/w/[workflowId]/hooks/use-accessible-reference-prefixes' import type { SubBlockConfig } from '@/blocks/types' import { useKnowledgeBaseTagDefinitions } from '@/hooks/kb/use-knowledge-base-tag-definitions' @@ -77,7 +78,9 @@ export function DocumentTagEntry({ }) const [knowledgeBaseIdFromStore] = useSubBlockValue(blockId, 'knowledgeBaseId') - const knowledgeBaseIdValue = previewContextValues?.knowledgeBaseId ?? knowledgeBaseIdFromStore + const knowledgeBaseIdValue = previewContextValues + ? resolvePreviewContextValue(previewContextValues.knowledgeBaseId) + : knowledgeBaseIdFromStore const knowledgeBaseId = typeof knowledgeBaseIdValue === 'string' && knowledgeBaseIdValue.trim().length > 0 ? knowledgeBaseIdValue diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/file-selector/file-selector-input.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/file-selector/file-selector-input.tsx index 6805e2ec4..730f01b24 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/file-selector/file-selector-input.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/file-selector/file-selector-input.tsx @@ -9,6 +9,7 @@ import { SelectorCombobox } from '@/app/workspace/[workspaceId]/w/[workflowId]/c import { useDependsOnGate } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-depends-on-gate' import { useForeignCredential } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-foreign-credential' import { useSubBlockValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-value' +import { resolvePreviewContextValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/utils' import { getBlock } from '@/blocks/registry' import type { SubBlockConfig } from '@/blocks/types' import { isDependency } from '@/blocks/utils' @@ -62,42 +63,56 @@ export function FileSelectorInput({ const [domainValueFromStore] = useSubBlockValue(blockId, 'domain') - const connectedCredential = previewContextValues?.credential ?? blockValues.credential - const domainValue = previewContextValues?.domain ?? domainValueFromStore + const connectedCredential = previewContextValues + ? resolvePreviewContextValue(previewContextValues.credential) + : blockValues.credential + const domainValue = previewContextValues + ? resolvePreviewContextValue(previewContextValues.domain) + : domainValueFromStore const teamIdValue = useMemo( () => - previewContextValues?.teamId ?? - resolveDependencyValue('teamId', blockValues, canonicalIndex, canonicalModeOverrides), - [previewContextValues?.teamId, blockValues, canonicalIndex, canonicalModeOverrides] + previewContextValues + ? resolvePreviewContextValue(previewContextValues.teamId) + : resolveDependencyValue('teamId', blockValues, canonicalIndex, canonicalModeOverrides), + [previewContextValues, blockValues, canonicalIndex, canonicalModeOverrides] ) const siteIdValue = useMemo( () => - previewContextValues?.siteId ?? - resolveDependencyValue('siteId', blockValues, canonicalIndex, canonicalModeOverrides), - [previewContextValues?.siteId, blockValues, canonicalIndex, canonicalModeOverrides] + previewContextValues + ? resolvePreviewContextValue(previewContextValues.siteId) + : resolveDependencyValue('siteId', blockValues, canonicalIndex, canonicalModeOverrides), + [previewContextValues, blockValues, canonicalIndex, canonicalModeOverrides] ) const collectionIdValue = useMemo( () => - previewContextValues?.collectionId ?? - resolveDependencyValue('collectionId', blockValues, canonicalIndex, canonicalModeOverrides), - [previewContextValues?.collectionId, blockValues, canonicalIndex, canonicalModeOverrides] + previewContextValues + ? resolvePreviewContextValue(previewContextValues.collectionId) + : resolveDependencyValue( + 'collectionId', + blockValues, + canonicalIndex, + canonicalModeOverrides + ), + [previewContextValues, blockValues, canonicalIndex, canonicalModeOverrides] ) const projectIdValue = useMemo( () => - previewContextValues?.projectId ?? - resolveDependencyValue('projectId', blockValues, canonicalIndex, canonicalModeOverrides), - [previewContextValues?.projectId, blockValues, canonicalIndex, canonicalModeOverrides] + previewContextValues + ? resolvePreviewContextValue(previewContextValues.projectId) + : resolveDependencyValue('projectId', blockValues, canonicalIndex, canonicalModeOverrides), + [previewContextValues, blockValues, canonicalIndex, canonicalModeOverrides] ) const planIdValue = useMemo( () => - previewContextValues?.planId ?? - resolveDependencyValue('planId', blockValues, canonicalIndex, canonicalModeOverrides), - [previewContextValues?.planId, blockValues, canonicalIndex, canonicalModeOverrides] + previewContextValues + ? resolvePreviewContextValue(previewContextValues.planId) + : resolveDependencyValue('planId', blockValues, canonicalIndex, canonicalModeOverrides), + [previewContextValues, blockValues, canonicalIndex, canonicalModeOverrides] ) const normalizedCredentialId = diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/folder-selector/components/folder-selector-input.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/folder-selector/components/folder-selector-input.tsx index fa9a48bb4..4be4a8da3 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/folder-selector/components/folder-selector-input.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/folder-selector/components/folder-selector-input.tsx @@ -6,6 +6,7 @@ import { SelectorCombobox } from '@/app/workspace/[workspaceId]/w/[workflowId]/c import { useDependsOnGate } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-depends-on-gate' import { useForeignCredential } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-foreign-credential' import { useSubBlockValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-value' +import { resolvePreviewContextValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/utils' import type { SubBlockConfig } from '@/blocks/types' import { resolveSelectorForSubBlock } from '@/hooks/selectors/resolution' import { useCollaborativeWorkflow } from '@/hooks/use-collaborative-workflow' @@ -17,6 +18,7 @@ interface FolderSelectorInputProps { disabled?: boolean isPreview?: boolean previewValue?: any | null + previewContextValues?: Record } export function FolderSelectorInput({ @@ -25,9 +27,13 @@ export function FolderSelectorInput({ disabled = false, isPreview = false, previewValue, + previewContextValues, }: FolderSelectorInputProps) { const [storeValue] = useSubBlockValue(blockId, subBlock.id) - const [connectedCredential] = useSubBlockValue(blockId, 'credential') + const [credentialFromStore] = useSubBlockValue(blockId, 'credential') + const connectedCredential = previewContextValues + ? resolvePreviewContextValue(previewContextValues.credential) + : credentialFromStore const { collaborativeSetSubblockValue } = useCollaborativeWorkflow() const { activeWorkflowId } = useWorkflowRegistry() const [selectedFolderId, setSelectedFolderId] = useState('') @@ -47,7 +53,11 @@ export function FolderSelectorInput({ ) // Central dependsOn gating - const { finalDisabled } = useDependsOnGate(blockId, subBlock, { disabled, isPreview }) + const { finalDisabled } = useDependsOnGate(blockId, subBlock, { + disabled, + isPreview, + previewContextValues, + }) // Get the current value from the store or prop value if in preview mode useEffect(() => { diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/input-mapping/input-mapping.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/input-mapping/input-mapping.tsx index 55c37277b..69189c762 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/input-mapping/input-mapping.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/input-mapping/input-mapping.tsx @@ -7,6 +7,7 @@ import { formatDisplayText } from '@/app/workspace/[workspaceId]/w/[workflowId]/ import { TagDropdown } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tag-dropdown/tag-dropdown' import { useSubBlockInput } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-input' import { useSubBlockValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-value' +import { resolvePreviewContextValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/utils' import { useAccessibleReferencePrefixes } from '@/app/workspace/[workspaceId]/w/[workflowId]/hooks/use-accessible-reference-prefixes' import { useWorkflowState } from '@/hooks/queries/workflows' @@ -37,6 +38,8 @@ interface InputMappingProps { isPreview?: boolean previewValue?: Record disabled?: boolean + /** Sub-block values from the preview context for resolving sibling sub-block values */ + previewContextValues?: Record } /** @@ -50,9 +53,13 @@ export function InputMapping({ isPreview = false, previewValue, disabled = false, + previewContextValues, }: InputMappingProps) { const [mapping, setMapping] = useSubBlockValue(blockId, subBlockId) - const [selectedWorkflowId] = useSubBlockValue(blockId, 'workflowId') + const [storeWorkflowId] = useSubBlockValue(blockId, 'workflowId') + const selectedWorkflowId = previewContextValues + ? resolvePreviewContextValue(previewContextValues.workflowId) + : storeWorkflowId const inputController = useSubBlockInput({ blockId, diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/knowledge-tag-filters/knowledge-tag-filters.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/knowledge-tag-filters/knowledge-tag-filters.tsx index 2198555fc..d297252ab 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/knowledge-tag-filters/knowledge-tag-filters.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/knowledge-tag-filters/knowledge-tag-filters.tsx @@ -17,6 +17,7 @@ import { type FilterFieldType, getOperatorsForFieldType } from '@/lib/knowledge/ import { formatDisplayText } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/formatted-text' import { TagDropdown } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tag-dropdown/tag-dropdown' import { useSubBlockInput } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-input' +import { resolvePreviewContextValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/utils' import { useAccessibleReferencePrefixes } from '@/app/workspace/[workspaceId]/w/[workflowId]/hooks/use-accessible-reference-prefixes' import type { SubBlockConfig } from '@/blocks/types' import { useKnowledgeBaseTagDefinitions } from '@/hooks/kb/use-knowledge-base-tag-definitions' @@ -69,7 +70,9 @@ export function KnowledgeTagFilters({ const overlayRefs = useRef>({}) const [knowledgeBaseIdFromStore] = useSubBlockValue(blockId, 'knowledgeBaseId') - const knowledgeBaseIdValue = previewContextValues?.knowledgeBaseId ?? knowledgeBaseIdFromStore + const knowledgeBaseIdValue = previewContextValues + ? resolvePreviewContextValue(previewContextValues.knowledgeBaseId) + : knowledgeBaseIdFromStore const knowledgeBaseId = typeof knowledgeBaseIdValue === 'string' && knowledgeBaseIdValue.trim().length > 0 ? knowledgeBaseIdValue diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/mcp-dynamic-args/mcp-dynamic-args.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/mcp-dynamic-args/mcp-dynamic-args.tsx index 41527a516..5271ecb33 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/mcp-dynamic-args/mcp-dynamic-args.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/mcp-dynamic-args/mcp-dynamic-args.tsx @@ -6,6 +6,7 @@ import { cn } from '@/lib/core/utils/cn' import { LongInput } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/long-input/long-input' import { ShortInput } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/short-input/short-input' import { useSubBlockValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-value' +import { resolvePreviewContextValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/utils' import type { SubBlockConfig } from '@/blocks/types' import { useMcpTools } from '@/hooks/mcp/use-mcp-tools' import { formatParameterLabel } from '@/tools/params' @@ -18,6 +19,7 @@ interface McpDynamicArgsProps { disabled?: boolean isPreview?: boolean previewValue?: any + previewContextValues?: Record } /** @@ -47,12 +49,19 @@ export function McpDynamicArgs({ disabled = false, isPreview = false, previewValue, + previewContextValues, }: McpDynamicArgsProps) { const params = useParams() const workspaceId = params.workspaceId as string const { mcpTools, isLoading } = useMcpTools(workspaceId) - const [selectedTool] = useSubBlockValue(blockId, 'tool') - const [cachedSchema] = useSubBlockValue(blockId, '_toolSchema') + const [toolFromStore] = useSubBlockValue(blockId, 'tool') + const selectedTool = previewContextValues + ? resolvePreviewContextValue(previewContextValues.tool) + : toolFromStore + const [schemaFromStore] = useSubBlockValue(blockId, '_toolSchema') + const cachedSchema = previewContextValues + ? resolvePreviewContextValue(previewContextValues._toolSchema) + : schemaFromStore const [toolArgs, setToolArgs] = useSubBlockValue(blockId, subBlockId) const selectedToolConfig = mcpTools.find((tool) => tool.id === selectedTool) diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/mcp-server-modal/mcp-tool-selector.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/mcp-server-modal/mcp-tool-selector.tsx index fa5fcd496..ca4ff45b1 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/mcp-server-modal/mcp-tool-selector.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/mcp-server-modal/mcp-tool-selector.tsx @@ -4,6 +4,7 @@ import { useEffect, useMemo, useState } from 'react' import { useParams } from 'next/navigation' import { Combobox } from '@/components/emcn/components' import { useSubBlockValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-value' +import { resolvePreviewContextValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/utils' import type { SubBlockConfig } from '@/blocks/types' import { useMcpTools } from '@/hooks/mcp/use-mcp-tools' @@ -13,6 +14,7 @@ interface McpToolSelectorProps { disabled?: boolean isPreview?: boolean previewValue?: string | null + previewContextValues?: Record } export function McpToolSelector({ @@ -21,6 +23,7 @@ export function McpToolSelector({ disabled = false, isPreview = false, previewValue, + previewContextValues, }: McpToolSelectorProps) { const params = useParams() const workspaceId = params.workspaceId as string @@ -31,7 +34,10 @@ export function McpToolSelector({ const [storeValue, setStoreValue] = useSubBlockValue(blockId, subBlock.id) const [, setSchemaCache] = useSubBlockValue(blockId, '_toolSchema') - const [serverValue] = useSubBlockValue(blockId, 'server') + const [serverFromStore] = useSubBlockValue(blockId, 'server') + const serverValue = previewContextValues + ? resolvePreviewContextValue(previewContextValues.server) + : serverFromStore const label = subBlock.placeholder || 'Select tool' diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/project-selector/project-selector-input.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/project-selector/project-selector-input.tsx index 9d5e35320..e5b7c5d93 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/project-selector/project-selector-input.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/project-selector/project-selector-input.tsx @@ -9,6 +9,7 @@ import { SelectorCombobox } from '@/app/workspace/[workspaceId]/w/[workflowId]/c import { useDependsOnGate } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-depends-on-gate' import { useForeignCredential } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-foreign-credential' import { useSubBlockValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-value' +import { resolvePreviewContextValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/utils' import { getBlock } from '@/blocks/registry' import type { SubBlockConfig } from '@/blocks/types' import { resolveSelectorForSubBlock } from '@/hooks/selectors/resolution' @@ -55,14 +56,19 @@ export function ProjectSelectorInput({ return (workflowValues as Record>)[blockId] || {} }) - const connectedCredential = previewContextValues?.credential ?? blockValues.credential - const jiraDomain = previewContextValues?.domain ?? jiraDomainFromStore + const connectedCredential = previewContextValues + ? resolvePreviewContextValue(previewContextValues.credential) + : blockValues.credential + const jiraDomain = previewContextValues + ? resolvePreviewContextValue(previewContextValues.domain) + : jiraDomainFromStore const linearTeamId = useMemo( () => - previewContextValues?.teamId ?? - resolveDependencyValue('teamId', blockValues, canonicalIndex, canonicalModeOverrides), - [previewContextValues?.teamId, blockValues, canonicalIndex, canonicalModeOverrides] + previewContextValues + ? resolvePreviewContextValue(previewContextValues.teamId) + : resolveDependencyValue('teamId', blockValues, canonicalIndex, canonicalModeOverrides), + [previewContextValues, blockValues, canonicalIndex, canonicalModeOverrides] ) const serviceId = subBlock.serviceId || '' diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/sheet-selector/sheet-selector-input.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/sheet-selector/sheet-selector-input.tsx index cd2a5adf5..bfb9dbe4f 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/sheet-selector/sheet-selector-input.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/sheet-selector/sheet-selector-input.tsx @@ -8,6 +8,7 @@ import { buildCanonicalIndex, resolveDependencyValue } from '@/lib/workflows/sub import { SelectorCombobox } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/selector-combobox/selector-combobox' import { useDependsOnGate } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-depends-on-gate' import { useForeignCredential } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-foreign-credential' +import { resolvePreviewContextValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/utils' import { getBlock } from '@/blocks/registry' import type { SubBlockConfig } from '@/blocks/types' import { resolveSelectorForSubBlock, type SelectorResolution } from '@/hooks/selectors/resolution' @@ -66,9 +67,12 @@ export function SheetSelectorInput({ [blockValues, canonicalIndex, canonicalModeOverrides] ) - const connectedCredential = previewContextValues?.credential ?? connectedCredentialFromStore + const connectedCredential = previewContextValues + ? resolvePreviewContextValue(previewContextValues.credential) + : connectedCredentialFromStore const spreadsheetId = previewContextValues - ? (previewContextValues.spreadsheetId ?? previewContextValues.manualSpreadsheetId) + ? (resolvePreviewContextValue(previewContextValues.spreadsheetId) ?? + resolvePreviewContextValue(previewContextValues.manualSpreadsheetId)) : spreadsheetIdFromStore const normalizedCredentialId = diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/slack-selector/slack-selector-input.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/slack-selector/slack-selector-input.tsx index 9a7e4ebfa..b99c26bff 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/slack-selector/slack-selector-input.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/slack-selector/slack-selector-input.tsx @@ -8,6 +8,7 @@ import { SelectorCombobox } from '@/app/workspace/[workspaceId]/w/[workflowId]/c import { useDependsOnGate } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-depends-on-gate' import { useForeignCredential } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-foreign-credential' import { useSubBlockValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/hooks/use-sub-block-value' +import { resolvePreviewContextValue } from '@/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/utils' import type { SubBlockConfig } from '@/blocks/types' import type { SelectorContext, SelectorKey } from '@/hooks/selectors/types' @@ -58,9 +59,15 @@ export function SlackSelectorInput({ const [botToken] = useSubBlockValue(blockId, 'botToken') const [connectedCredential] = useSubBlockValue(blockId, 'credential') - const effectiveAuthMethod = previewContextValues?.authMethod ?? authMethod - const effectiveBotToken = previewContextValues?.botToken ?? botToken - const effectiveCredential = previewContextValues?.credential ?? connectedCredential + const effectiveAuthMethod = previewContextValues + ? resolvePreviewContextValue(previewContextValues.authMethod) + : authMethod + const effectiveBotToken = previewContextValues + ? resolvePreviewContextValue(previewContextValues.botToken) + : botToken + const effectiveCredential = previewContextValues + ? resolvePreviewContextValue(previewContextValues.credential) + : connectedCredential const [_selectedValue, setSelectedValue] = useState(null) const serviceId = subBlock.serviceId || '' diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.tsx index cd2f342a3..8f03f4b2e 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/components/tool-input/tool-input.tsx @@ -332,6 +332,7 @@ function FolderSelectorSyncWrapper({ dependsOn: uiComponent.dependsOn, }} disabled={disabled} + previewContextValues={previewContextValues} /> ) diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/sub-block.tsx b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/sub-block.tsx index 800ed5f93..c8422f0e7 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/sub-block.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/sub-block.tsx @@ -797,6 +797,7 @@ function SubBlockComponent({ disabled={isDisabled} isPreview={isPreview} previewValue={previewValue} + previewContextValues={isPreview ? subBlockValues : undefined} /> ) @@ -832,6 +833,7 @@ function SubBlockComponent({ disabled={isDisabled} isPreview={isPreview} previewValue={previewValue} + previewContextValues={isPreview ? subBlockValues : undefined} /> ) @@ -843,6 +845,7 @@ function SubBlockComponent({ disabled={isDisabled} isPreview={isPreview} previewValue={previewValue} + previewContextValues={isPreview ? subBlockValues : undefined} /> ) @@ -865,6 +868,7 @@ function SubBlockComponent({ disabled={isDisabled} isPreview={isPreview} previewValue={previewValue as any} + previewContextValues={isPreview ? subBlockValues : undefined} /> ) @@ -876,6 +880,7 @@ function SubBlockComponent({ disabled={isDisabled} isPreview={isPreview} previewValue={previewValue as any} + previewContextValues={isPreview ? subBlockValues : undefined} /> ) @@ -887,6 +892,7 @@ function SubBlockComponent({ disabled={isDisabled} isPreview={isPreview} previewValue={previewValue as any} + previewContextValues={isPreview ? subBlockValues : undefined} /> ) @@ -911,6 +917,7 @@ function SubBlockComponent({ isPreview={isPreview} previewValue={previewValue as any} disabled={isDisabled} + previewContextValues={isPreview ? subBlockValues : undefined} /> ) @@ -946,6 +953,7 @@ function SubBlockComponent({ disabled={isDisabled} isPreview={isPreview} previewValue={previewValue} + previewContextValues={isPreview ? subBlockValues : undefined} /> ) @@ -979,6 +987,7 @@ function SubBlockComponent({ disabled={isDisabled} isPreview={isPreview} previewValue={previewValue as any} + previewContextValues={isPreview ? subBlockValues : undefined} /> ) @@ -990,6 +999,7 @@ function SubBlockComponent({ disabled={isDisabled} isPreview={isPreview} previewValue={previewValue} + previewContextValues={isPreview ? subBlockValues : undefined} /> ) diff --git a/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/utils.ts b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/utils.ts new file mode 100644 index 000000000..181299221 --- /dev/null +++ b/apps/sim/app/workspace/[workspaceId]/w/[workflowId]/components/panel/components/editor/components/sub-block/utils.ts @@ -0,0 +1,18 @@ +/** + * Extracts the raw value from a preview context entry. + * + * @remarks + * In the sub-block preview context, values are wrapped as `{ value: T }` objects + * (the full sub-block state). In the tool-input preview context, values are already + * raw. This function normalizes both cases to return the underlying value. + * + * @param raw - The preview context entry, which may be a raw value or a `{ value: T }` wrapper + * @returns The unwrapped value, or `null` if the input is nullish + */ +export function resolvePreviewContextValue(raw: unknown): unknown { + if (raw === null || raw === undefined) return null + if (typeof raw === 'object' && !Array.isArray(raw) && 'value' in raw) { + return (raw as Record).value ?? null + } + return raw +} diff --git a/apps/sim/app/workspace/[workspaceId]/w/components/preview/components/preview-editor/preview-editor.tsx b/apps/sim/app/workspace/[workspaceId]/w/components/preview/components/preview-editor/preview-editor.tsx index 90831de45..bfc86ec20 100644 --- a/apps/sim/app/workspace/[workspaceId]/w/components/preview/components/preview-editor/preview-editor.tsx +++ b/apps/sim/app/workspace/[workspaceId]/w/components/preview/components/preview-editor/preview-editor.tsx @@ -784,8 +784,12 @@ function PreviewEditorContent({ ? childWorkflowSnapshotState : childWorkflowState const resolvedIsLoadingChildWorkflow = isExecutionMode ? false : isLoadingChildWorkflow + const isBlockNotExecuted = isExecutionMode && !executionData const isMissingChildWorkflow = - Boolean(childWorkflowId) && !resolvedIsLoadingChildWorkflow && !resolvedChildWorkflowState + Boolean(childWorkflowId) && + !isBlockNotExecuted && + !resolvedIsLoadingChildWorkflow && + !resolvedChildWorkflowState /** Drills down into the child workflow or opens it in a new tab */ const handleExpandChildWorkflow = useCallback(() => { @@ -1192,7 +1196,7 @@ function PreviewEditorContent({
{/* Not Executed Banner - shown when in execution mode but block wasn't executed */} - {isExecutionMode && !executionData && ( + {isBlockNotExecuted && (
@@ -1419,9 +1423,11 @@ function PreviewEditorContent({ ) : (
- {isMissingChildWorkflow - ? DELETED_WORKFLOW_LABEL - : 'Unable to load preview'} + {isBlockNotExecuted + ? 'Not Executed' + : isMissingChildWorkflow + ? DELETED_WORKFLOW_LABEL + : 'Unable to load preview'}
)} diff --git a/apps/sim/lib/logs/execution/snapshot/service.ts b/apps/sim/lib/logs/execution/snapshot/service.ts index cad4c259c..856c3a185 100644 --- a/apps/sim/lib/logs/execution/snapshot/service.ts +++ b/apps/sim/lib/logs/execution/snapshot/service.ts @@ -33,11 +33,25 @@ export class SnapshotService implements ISnapshotService { const existingSnapshot = await this.getSnapshotByHash(workflowId, stateHash) if (existingSnapshot) { + let refreshedState: WorkflowState = existingSnapshot.stateData + try { + await db + .update(workflowExecutionSnapshots) + .set({ stateData: state }) + .where(eq(workflowExecutionSnapshots.id, existingSnapshot.id)) + refreshedState = state + } catch (error) { + logger.warn( + `Failed to refresh snapshot stateData for ${existingSnapshot.id}, continuing with existing data`, + error + ) + } + logger.info( `Reusing existing snapshot for workflow ${workflowId} (hash: ${stateHash.slice(0, 12)}...)` ) return { - snapshot: existingSnapshot, + snapshot: { ...existingSnapshot, stateData: refreshedState }, isNew: false, } } From 99ae5435e349e53a4fff8302db1ded4f7b39e1e2 Mon Sep 17 00:00:00 2001 From: Waleed Date: Fri, 6 Feb 2026 22:35:57 -0800 Subject: [PATCH 6/8] feat(models): updated model configs, updated anthropic provider to propagate errors back to user if any (#3159) * feat(models): updated model configs, updated anthropic provider to propagate errors back to user if any * moved max tokens to advanced * updated model configs and testesd * removed default in max config for output tokens * moved more stuff to advanced mode in the agent block * stronger typing * move api key under model, update mistral and groq * update openrouter, fixed serializer to allow ollama/vllm models without api key * removed ollama handling --- .../workflow-selector/workflow-selector.tsx | 2 +- apps/sim/blocks/blocks/agent.ts | 65 +-- .../executor/handlers/agent/agent-handler.ts | 14 +- apps/sim/executor/handlers/agent/types.ts | 1 + apps/sim/providers/anthropic/core.ts | 371 +++++++++++------- apps/sim/providers/azure-openai/index.ts | 49 ++- apps/sim/providers/azure-openai/utils.ts | 5 +- apps/sim/providers/bedrock/index.ts | 10 + apps/sim/providers/gemini/core.ts | 9 +- apps/sim/providers/mistral/index.ts | 2 - apps/sim/providers/models.ts | 236 ++++------- apps/sim/providers/openai/core.ts | 58 +-- apps/sim/providers/openai/utils.ts | 117 ++++-- apps/sim/providers/openrouter/index.ts | 10 +- apps/sim/providers/utils.test.ts | 322 +++++++++++---- apps/sim/providers/utils.ts | 14 +- apps/sim/serializer/index.ts | 1 + 17 files changed, 766 insertions(+), 520 deletions(-) diff --git a/apps/sim/app/workspace/[workspaceId]/logs/components/logs-toolbar/components/notifications/components/workflow-selector/workflow-selector.tsx b/apps/sim/app/workspace/[workspaceId]/logs/components/logs-toolbar/components/notifications/components/workflow-selector/workflow-selector.tsx index fe8b66356..35f40657e 100644 --- a/apps/sim/app/workspace/[workspaceId]/logs/components/logs-toolbar/components/notifications/components/workflow-selector/workflow-selector.tsx +++ b/apps/sim/app/workspace/[workspaceId]/logs/components/logs-toolbar/components/notifications/components/workflow-selector/workflow-selector.tsx @@ -89,7 +89,7 @@ export function WorkflowSelector({ onMouseDown={(e) => handleRemove(e, w.id)} > {w.name} - +
))} {selectedWorkflows.length > 2 && ( diff --git a/apps/sim/blocks/blocks/agent.ts b/apps/sim/blocks/blocks/agent.ts index 7e7b12f96..1dd36a2b2 100644 --- a/apps/sim/blocks/blocks/agent.ts +++ b/apps/sim/blocks/blocks/agent.ts @@ -154,6 +154,7 @@ Return ONLY the JSON array.`, type: 'dropdown', placeholder: 'Select reasoning effort...', options: [ + { label: 'auto', id: 'auto' }, { label: 'low', id: 'low' }, { label: 'medium', id: 'medium' }, { label: 'high', id: 'high' }, @@ -163,9 +164,12 @@ Return ONLY the JSON array.`, const { useSubBlockStore } = await import('@/stores/workflows/subblock/store') const { useWorkflowRegistry } = await import('@/stores/workflows/registry/store') + const autoOption = { label: 'auto', id: 'auto' } + const activeWorkflowId = useWorkflowRegistry.getState().activeWorkflowId if (!activeWorkflowId) { return [ + autoOption, { label: 'low', id: 'low' }, { label: 'medium', id: 'medium' }, { label: 'high', id: 'high' }, @@ -178,6 +182,7 @@ Return ONLY the JSON array.`, if (!modelValue) { return [ + autoOption, { label: 'low', id: 'low' }, { label: 'medium', id: 'medium' }, { label: 'high', id: 'high' }, @@ -187,15 +192,16 @@ Return ONLY the JSON array.`, const validOptions = getReasoningEffortValuesForModel(modelValue) if (!validOptions) { return [ + autoOption, { label: 'low', id: 'low' }, { label: 'medium', id: 'medium' }, { label: 'high', id: 'high' }, ] } - return validOptions.map((opt) => ({ label: opt, id: opt })) + return [autoOption, ...validOptions.map((opt) => ({ label: opt, id: opt }))] }, - value: () => 'medium', + mode: 'advanced', condition: { field: 'model', value: MODELS_WITH_REASONING_EFFORT, @@ -207,6 +213,7 @@ Return ONLY the JSON array.`, type: 'dropdown', placeholder: 'Select verbosity...', options: [ + { label: 'auto', id: 'auto' }, { label: 'low', id: 'low' }, { label: 'medium', id: 'medium' }, { label: 'high', id: 'high' }, @@ -216,9 +223,12 @@ Return ONLY the JSON array.`, const { useSubBlockStore } = await import('@/stores/workflows/subblock/store') const { useWorkflowRegistry } = await import('@/stores/workflows/registry/store') + const autoOption = { label: 'auto', id: 'auto' } + const activeWorkflowId = useWorkflowRegistry.getState().activeWorkflowId if (!activeWorkflowId) { return [ + autoOption, { label: 'low', id: 'low' }, { label: 'medium', id: 'medium' }, { label: 'high', id: 'high' }, @@ -231,6 +241,7 @@ Return ONLY the JSON array.`, if (!modelValue) { return [ + autoOption, { label: 'low', id: 'low' }, { label: 'medium', id: 'medium' }, { label: 'high', id: 'high' }, @@ -240,15 +251,16 @@ Return ONLY the JSON array.`, const validOptions = getVerbosityValuesForModel(modelValue) if (!validOptions) { return [ + autoOption, { label: 'low', id: 'low' }, { label: 'medium', id: 'medium' }, { label: 'high', id: 'high' }, ] } - return validOptions.map((opt) => ({ label: opt, id: opt })) + return [autoOption, ...validOptions.map((opt) => ({ label: opt, id: opt }))] }, - value: () => 'medium', + mode: 'advanced', condition: { field: 'model', value: MODELS_WITH_VERBOSITY, @@ -260,6 +272,7 @@ Return ONLY the JSON array.`, type: 'dropdown', placeholder: 'Select thinking level...', options: [ + { label: 'none', id: 'none' }, { label: 'minimal', id: 'minimal' }, { label: 'low', id: 'low' }, { label: 'medium', id: 'medium' }, @@ -271,12 +284,11 @@ Return ONLY the JSON array.`, const { useSubBlockStore } = await import('@/stores/workflows/subblock/store') const { useWorkflowRegistry } = await import('@/stores/workflows/registry/store') + const noneOption = { label: 'none', id: 'none' } + const activeWorkflowId = useWorkflowRegistry.getState().activeWorkflowId if (!activeWorkflowId) { - return [ - { label: 'low', id: 'low' }, - { label: 'high', id: 'high' }, - ] + return [noneOption, { label: 'low', id: 'low' }, { label: 'high', id: 'high' }] } const workflowValues = useSubBlockStore.getState().workflowValues[activeWorkflowId] @@ -284,23 +296,17 @@ Return ONLY the JSON array.`, const modelValue = blockValues?.model as string if (!modelValue) { - return [ - { label: 'low', id: 'low' }, - { label: 'high', id: 'high' }, - ] + return [noneOption, { label: 'low', id: 'low' }, { label: 'high', id: 'high' }] } const validOptions = getThinkingLevelsForModel(modelValue) if (!validOptions) { - return [ - { label: 'low', id: 'low' }, - { label: 'high', id: 'high' }, - ] + return [noneOption, { label: 'low', id: 'low' }, { label: 'high', id: 'high' }] } - return validOptions.map((opt) => ({ label: opt, id: opt })) + return [noneOption, ...validOptions.map((opt) => ({ label: opt, id: opt }))] }, - value: () => 'high', + mode: 'advanced', condition: { field: 'model', value: MODELS_WITH_THINKING, @@ -391,6 +397,16 @@ Return ONLY the JSON array.`, value: providers.bedrock.models, }, }, + { + id: 'apiKey', + title: 'API Key', + type: 'short-input', + placeholder: 'Enter your API key', + password: true, + connectionDroppable: false, + required: true, + condition: getApiKeyCondition(), + }, { id: 'tools', title: 'Tools', @@ -403,16 +419,6 @@ Return ONLY the JSON array.`, type: 'skill-input', defaultValue: [], }, - { - id: 'apiKey', - title: 'API Key', - type: 'short-input', - placeholder: 'Enter your API key', - password: true, - connectionDroppable: false, - required: true, - condition: getApiKeyCondition(), - }, { id: 'memoryType', title: 'Memory', @@ -467,6 +473,7 @@ Return ONLY the JSON array.`, min: 0, max: 1, defaultValue: 0.3, + mode: 'advanced', condition: () => ({ field: 'model', value: (() => { @@ -484,6 +491,7 @@ Return ONLY the JSON array.`, min: 0, max: 2, defaultValue: 0.3, + mode: 'advanced', condition: () => ({ field: 'model', value: (() => { @@ -499,6 +507,7 @@ Return ONLY the JSON array.`, title: 'Max Output Tokens', type: 'short-input', placeholder: 'Enter max tokens (e.g., 4096)...', + mode: 'advanced', }, { id: 'responseFormat', diff --git a/apps/sim/executor/handlers/agent/agent-handler.ts b/apps/sim/executor/handlers/agent/agent-handler.ts index 524407506..0de77719b 100644 --- a/apps/sim/executor/handlers/agent/agent-handler.ts +++ b/apps/sim/executor/handlers/agent/agent-handler.ts @@ -915,24 +915,17 @@ export class AgentBlockHandler implements BlockHandler { } } - // Find first system message const firstSystemIndex = messages.findIndex((msg) => msg.role === 'system') if (firstSystemIndex === -1) { - // No system message exists - add at position 0 messages.unshift({ role: 'system', content }) } else if (firstSystemIndex === 0) { - // System message already at position 0 - replace it - // Explicit systemPrompt parameter takes precedence over memory/messages messages[0] = { role: 'system', content } } else { - // System message exists but not at position 0 - move it to position 0 - // and update with new content messages.splice(firstSystemIndex, 1) messages.unshift({ role: 'system', content }) } - // Remove any additional system messages (keep only the first one) for (let i = messages.length - 1; i >= 1; i--) { if (messages[i].role === 'system') { messages.splice(i, 1) @@ -998,13 +991,14 @@ export class AgentBlockHandler implements BlockHandler { workflowId: ctx.workflowId, workspaceId: ctx.workspaceId, stream: streaming, - messages, + messages: messages?.map(({ executionId, ...msg }) => msg), environmentVariables: ctx.environmentVariables || {}, workflowVariables: ctx.workflowVariables || {}, blockData, blockNameMapping, reasoningEffort: inputs.reasoningEffort, verbosity: inputs.verbosity, + thinkingLevel: inputs.thinkingLevel, } } @@ -1074,6 +1068,7 @@ export class AgentBlockHandler implements BlockHandler { isDeployedContext: ctx.isDeployedContext, reasoningEffort: providerRequest.reasoningEffort, verbosity: providerRequest.verbosity, + thinkingLevel: providerRequest.thinkingLevel, }) return this.processProviderResponse(response, block, responseFormat) @@ -1091,8 +1086,6 @@ export class AgentBlockHandler implements BlockHandler { logger.info(`[${requestId}] Resolving Vertex AI credential: ${credentialId}`) - // Get the credential - we need to find the owner - // Since we're in a workflow context, we can query the credential directly const credential = await db.query.account.findFirst({ where: eq(account.id, credentialId), }) @@ -1101,7 +1094,6 @@ export class AgentBlockHandler implements BlockHandler { throw new Error(`Vertex AI credential not found: ${credentialId}`) } - // Refresh the token if needed const { accessToken } = await refreshTokenIfNeeded(requestId, credential, credentialId) if (!accessToken) { diff --git a/apps/sim/executor/handlers/agent/types.ts b/apps/sim/executor/handlers/agent/types.ts index 36002b7b0..c0731d9ee 100644 --- a/apps/sim/executor/handlers/agent/types.ts +++ b/apps/sim/executor/handlers/agent/types.ts @@ -34,6 +34,7 @@ export interface AgentInputs { bedrockRegion?: string reasoningEffort?: string verbosity?: string + thinkingLevel?: string } export interface ToolInput { diff --git a/apps/sim/providers/anthropic/core.ts b/apps/sim/providers/anthropic/core.ts index 3cd16eb4d..dcb2b9c14 100644 --- a/apps/sim/providers/anthropic/core.ts +++ b/apps/sim/providers/anthropic/core.ts @@ -1,5 +1,6 @@ import type Anthropic from '@anthropic-ai/sdk' import { transformJSONSchema } from '@anthropic-ai/sdk/lib/transform-json-schema' +import type { RawMessageStreamEvent } from '@anthropic-ai/sdk/resources/messages/messages' import type { Logger } from '@sim/logger' import type { StreamingExecution } from '@/executor/types' import { MAX_TOOL_ITERATIONS } from '@/providers' @@ -34,11 +35,21 @@ export interface AnthropicProviderConfig { logger: Logger } +/** + * Custom payload type extending the SDK's base message creation params. + * Adds fields not yet in the SDK: adaptive thinking, output_format, output_config. + */ +interface AnthropicPayload extends Omit { + thinking?: Anthropic.Messages.ThinkingConfigParam | { type: 'adaptive' } + output_format?: { type: 'json_schema'; schema: Record } + output_config?: { effort: string } +} + /** * Generates prompt-based schema instructions for older models that don't support native structured outputs. * This is a fallback approach that adds schema requirements to the system prompt. */ -function generateSchemaInstructions(schema: any, schemaName?: string): string { +function generateSchemaInstructions(schema: Record, schemaName?: string): string { const name = schemaName || 'response' return `IMPORTANT: You must respond with a valid JSON object that conforms to the following schema. Do not include any text before or after the JSON object. Only output the JSON. @@ -113,6 +124,30 @@ function buildThinkingConfig( } } +/** + * The Anthropic SDK requires streaming for non-streaming requests when max_tokens exceeds + * this threshold, to avoid HTTP timeouts. When thinking is enabled and pushes max_tokens + * above this limit, we use streaming internally and collect the final message. + */ +const ANTHROPIC_SDK_NON_STREAMING_MAX_TOKENS = 21333 + +/** + * Creates an Anthropic message, automatically using streaming internally when max_tokens + * exceeds the SDK's non-streaming threshold. Returns the same Message object either way. + */ +async function createMessage( + anthropic: Anthropic, + payload: AnthropicPayload +): Promise { + if (payload.max_tokens > ANTHROPIC_SDK_NON_STREAMING_MAX_TOKENS && !payload.stream) { + const stream = anthropic.messages.stream(payload as Anthropic.Messages.MessageStreamParams) + return stream.finalMessage() + } + return anthropic.messages.create( + payload as Anthropic.Messages.MessageCreateParamsNonStreaming + ) as Promise +} + /** * Executes a request using the Anthropic API with full tool loop support. * This is the shared core implementation used by both the standard Anthropic provider @@ -135,7 +170,7 @@ export async function executeAnthropicProviderRequest( const anthropic = config.createClient(request.apiKey, useNativeStructuredOutputs) - const messages: any[] = [] + const messages: Anthropic.Messages.MessageParam[] = [] let systemPrompt = request.systemPrompt || '' if (request.context) { @@ -153,8 +188,8 @@ export async function executeAnthropicProviderRequest( content: [ { type: 'tool_result', - tool_use_id: msg.name, - content: msg.content, + tool_use_id: msg.name || '', + content: msg.content || undefined, }, ], }) @@ -188,12 +223,12 @@ export async function executeAnthropicProviderRequest( systemPrompt = '' } - let anthropicTools = request.tools?.length + let anthropicTools: Anthropic.Messages.Tool[] | undefined = request.tools?.length ? request.tools.map((tool) => ({ name: tool.id, description: tool.description, input_schema: { - type: 'object', + type: 'object' as const, properties: tool.parameters.properties, required: tool.parameters.required, }, @@ -238,13 +273,12 @@ export async function executeAnthropicProviderRequest( } } - const payload: any = { + const payload: AnthropicPayload = { model: request.model, messages, system: systemPrompt, max_tokens: - Number.parseInt(String(request.maxTokens)) || - getMaxOutputTokensForModel(request.model, request.stream ?? false), + Number.parseInt(String(request.maxTokens)) || getMaxOutputTokensForModel(request.model), temperature: Number.parseFloat(String(request.temperature ?? 0.7)), } @@ -268,13 +302,35 @@ export async function executeAnthropicProviderRequest( } // Add extended thinking configuration if supported and requested - if (request.thinkingLevel) { + // The 'none' sentinel means "disable thinking" — skip configuration entirely. + if (request.thinkingLevel && request.thinkingLevel !== 'none') { const thinkingConfig = buildThinkingConfig(request.model, request.thinkingLevel) if (thinkingConfig) { payload.thinking = thinkingConfig.thinking if (thinkingConfig.outputConfig) { payload.output_config = thinkingConfig.outputConfig } + + // Per Anthropic docs: budget_tokens must be less than max_tokens. + // Ensure max_tokens leaves room for both thinking and text output. + if ( + thinkingConfig.thinking.type === 'enabled' && + 'budget_tokens' in thinkingConfig.thinking + ) { + const budgetTokens = thinkingConfig.thinking.budget_tokens + const minMaxTokens = budgetTokens + 4096 + if (payload.max_tokens < minMaxTokens) { + const modelMax = getMaxOutputTokensForModel(request.model) + payload.max_tokens = Math.min(minMaxTokens, modelMax) + logger.info( + `Adjusted max_tokens to ${payload.max_tokens} to satisfy budget_tokens (${budgetTokens}) constraint` + ) + } + } + + // Per Anthropic docs: thinking is not compatible with temperature or top_k modifications. + payload.temperature = undefined + const isAdaptive = thinkingConfig.thinking.type === 'adaptive' logger.info( `Using ${isAdaptive ? 'adaptive' : 'extended'} thinking for model: ${modelId} with ${isAdaptive ? `effort: ${request.thinkingLevel}` : `budget: ${(thinkingConfig.thinking as { budget_tokens: number }).budget_tokens}`}` @@ -288,7 +344,16 @@ export async function executeAnthropicProviderRequest( if (anthropicTools?.length) { payload.tools = anthropicTools - if (toolChoice !== 'auto') { + // Per Anthropic docs: forced tool_choice (type: "tool" or "any") is incompatible with + // thinking. Only auto and none are supported when thinking is enabled. + if (payload.thinking) { + // Per Anthropic docs: only 'auto' (default) and 'none' work with thinking. + if (toolChoice === 'none') { + payload.tool_choice = { type: 'none' } + } + } else if (toolChoice === 'none') { + payload.tool_choice = { type: 'none' } + } else if (toolChoice !== 'auto') { payload.tool_choice = toolChoice } } @@ -301,42 +366,46 @@ export async function executeAnthropicProviderRequest( const providerStartTime = Date.now() const providerStartTimeISO = new Date(providerStartTime).toISOString() - const streamResponse: any = await anthropic.messages.create({ + const streamResponse = await anthropic.messages.create({ ...payload, stream: true, - }) + } as Anthropic.Messages.MessageCreateParamsStreaming) const streamingResult = { - stream: createReadableStreamFromAnthropicStream(streamResponse, (content, usage) => { - streamingResult.execution.output.content = content - streamingResult.execution.output.tokens = { - input: usage.input_tokens, - output: usage.output_tokens, - total: usage.input_tokens + usage.output_tokens, - } + stream: createReadableStreamFromAnthropicStream( + streamResponse as AsyncIterable, + (content, usage) => { + streamingResult.execution.output.content = content + streamingResult.execution.output.tokens = { + input: usage.input_tokens, + output: usage.output_tokens, + total: usage.input_tokens + usage.output_tokens, + } - const costResult = calculateCost(request.model, usage.input_tokens, usage.output_tokens) - streamingResult.execution.output.cost = { - input: costResult.input, - output: costResult.output, - total: costResult.total, - } + const costResult = calculateCost(request.model, usage.input_tokens, usage.output_tokens) + streamingResult.execution.output.cost = { + input: costResult.input, + output: costResult.output, + total: costResult.total, + } - const streamEndTime = Date.now() - const streamEndTimeISO = new Date(streamEndTime).toISOString() + const streamEndTime = Date.now() + const streamEndTimeISO = new Date(streamEndTime).toISOString() - if (streamingResult.execution.output.providerTiming) { - streamingResult.execution.output.providerTiming.endTime = streamEndTimeISO - streamingResult.execution.output.providerTiming.duration = - streamEndTime - providerStartTime - - if (streamingResult.execution.output.providerTiming.timeSegments?.[0]) { - streamingResult.execution.output.providerTiming.timeSegments[0].endTime = streamEndTime - streamingResult.execution.output.providerTiming.timeSegments[0].duration = + if (streamingResult.execution.output.providerTiming) { + streamingResult.execution.output.providerTiming.endTime = streamEndTimeISO + streamingResult.execution.output.providerTiming.duration = streamEndTime - providerStartTime + + if (streamingResult.execution.output.providerTiming.timeSegments?.[0]) { + streamingResult.execution.output.providerTiming.timeSegments[0].endTime = + streamEndTime + streamingResult.execution.output.providerTiming.timeSegments[0].duration = + streamEndTime - providerStartTime + } } } - }), + ), execution: { success: true, output: { @@ -385,21 +454,13 @@ export async function executeAnthropicProviderRequest( const providerStartTime = Date.now() const providerStartTimeISO = new Date(providerStartTime).toISOString() - // Cap intermediate calls at non-streaming limit to avoid SDK timeout errors, - // but allow users to set lower values if desired - const nonStreamingLimit = getMaxOutputTokensForModel(request.model, false) - const nonStreamingMaxTokens = request.maxTokens - ? Math.min(Number.parseInt(String(request.maxTokens)), nonStreamingLimit) - : nonStreamingLimit - const intermediatePayload = { ...payload, max_tokens: nonStreamingMaxTokens } - try { const initialCallTime = Date.now() - const originalToolChoice = intermediatePayload.tool_choice + const originalToolChoice = payload.tool_choice const forcedTools = preparedTools?.forcedTools || [] let usedForcedTools: string[] = [] - let currentResponse = await anthropic.messages.create(intermediatePayload) + let currentResponse = await createMessage(anthropic, payload) const firstResponseTime = Date.now() - initialCallTime let content = '' @@ -468,10 +529,10 @@ export async function executeAnthropicProviderRequest( const toolExecutionPromises = toolUses.map(async (toolUse) => { const toolCallStartTime = Date.now() const toolName = toolUse.name - const toolArgs = toolUse.input as Record + const toolArgs = toolUse.input as Record try { - const tool = request.tools?.find((t: any) => t.id === toolName) + const tool = request.tools?.find((t) => t.id === toolName) if (!tool) return null const { toolParams, executionParams } = prepareToolExecution(tool, toolArgs, request) @@ -512,17 +573,8 @@ export async function executeAnthropicProviderRequest( const executionResults = await Promise.allSettled(toolExecutionPromises) // Collect all tool_use and tool_result blocks for batching - const toolUseBlocks: Array<{ - type: 'tool_use' - id: string - name: string - input: Record - }> = [] - const toolResultBlocks: Array<{ - type: 'tool_result' - tool_use_id: string - content: string - }> = [] + const toolUseBlocks: Anthropic.Messages.ToolUseBlockParam[] = [] + const toolResultBlocks: Anthropic.Messages.ToolResultBlockParam[] = [] for (const settledResult of executionResults) { if (settledResult.status === 'rejected' || !settledResult.value) continue @@ -583,11 +635,25 @@ export async function executeAnthropicProviderRequest( }) } - // Add ONE assistant message with ALL tool_use blocks + // Per Anthropic docs: thinking blocks must be preserved in assistant messages + // during tool use to maintain reasoning continuity. + const thinkingBlocks = currentResponse.content.filter( + ( + item + ): item is + | Anthropic.Messages.ThinkingBlock + | Anthropic.Messages.RedactedThinkingBlock => + item.type === 'thinking' || item.type === 'redacted_thinking' + ) + + // Add ONE assistant message with thinking + tool_use blocks if (toolUseBlocks.length > 0) { currentMessages.push({ role: 'assistant', - content: toolUseBlocks as unknown as Anthropic.Messages.ContentBlock[], + content: [ + ...thinkingBlocks, + ...toolUseBlocks, + ] as Anthropic.Messages.ContentBlockParam[], }) } @@ -595,19 +661,23 @@ export async function executeAnthropicProviderRequest( if (toolResultBlocks.length > 0) { currentMessages.push({ role: 'user', - content: toolResultBlocks as unknown as Anthropic.Messages.ContentBlockParam[], + content: toolResultBlocks as Anthropic.Messages.ContentBlockParam[], }) } const thisToolsTime = Date.now() - toolsStartTime toolsTime += thisToolsTime - const nextPayload = { - ...intermediatePayload, + const nextPayload: AnthropicPayload = { + ...payload, messages: currentMessages, } + // Per Anthropic docs: forced tool_choice is incompatible with thinking. + // Only auto and none are supported when thinking is enabled. + const thinkingEnabled = !!payload.thinking if ( + !thinkingEnabled && typeof originalToolChoice === 'object' && hasUsedForcedTool && forcedTools.length > 0 @@ -624,7 +694,11 @@ export async function executeAnthropicProviderRequest( nextPayload.tool_choice = undefined logger.info('All forced tools have been used, removing tool_choice parameter') } - } else if (hasUsedForcedTool && typeof originalToolChoice === 'object') { + } else if ( + !thinkingEnabled && + hasUsedForcedTool && + typeof originalToolChoice === 'object' + ) { nextPayload.tool_choice = undefined logger.info( 'Removing tool_choice parameter for subsequent requests after forced tool was used' @@ -633,7 +707,7 @@ export async function executeAnthropicProviderRequest( const nextModelStartTime = Date.now() - currentResponse = await anthropic.messages.create(nextPayload) + currentResponse = await createMessage(anthropic, nextPayload) const nextCheckResult = checkForForcedToolUsage( currentResponse, @@ -682,33 +756,38 @@ export async function executeAnthropicProviderRequest( tool_choice: undefined, } - const streamResponse: any = await anthropic.messages.create(streamingPayload) + const streamResponse = await anthropic.messages.create( + streamingPayload as Anthropic.Messages.MessageCreateParamsStreaming + ) const streamingResult = { - stream: createReadableStreamFromAnthropicStream(streamResponse, (streamContent, usage) => { - streamingResult.execution.output.content = streamContent - streamingResult.execution.output.tokens = { - input: tokens.input + usage.input_tokens, - output: tokens.output + usage.output_tokens, - total: tokens.total + usage.input_tokens + usage.output_tokens, - } + stream: createReadableStreamFromAnthropicStream( + streamResponse as AsyncIterable, + (streamContent, usage) => { + streamingResult.execution.output.content = streamContent + streamingResult.execution.output.tokens = { + input: tokens.input + usage.input_tokens, + output: tokens.output + usage.output_tokens, + total: tokens.total + usage.input_tokens + usage.output_tokens, + } - const streamCost = calculateCost(request.model, usage.input_tokens, usage.output_tokens) - streamingResult.execution.output.cost = { - input: accumulatedCost.input + streamCost.input, - output: accumulatedCost.output + streamCost.output, - total: accumulatedCost.total + streamCost.total, - } + const streamCost = calculateCost(request.model, usage.input_tokens, usage.output_tokens) + streamingResult.execution.output.cost = { + input: accumulatedCost.input + streamCost.input, + output: accumulatedCost.output + streamCost.output, + total: accumulatedCost.total + streamCost.total, + } - const streamEndTime = Date.now() - const streamEndTimeISO = new Date(streamEndTime).toISOString() + const streamEndTime = Date.now() + const streamEndTimeISO = new Date(streamEndTime).toISOString() - if (streamingResult.execution.output.providerTiming) { - streamingResult.execution.output.providerTiming.endTime = streamEndTimeISO - streamingResult.execution.output.providerTiming.duration = - streamEndTime - providerStartTime + if (streamingResult.execution.output.providerTiming) { + streamingResult.execution.output.providerTiming.endTime = streamEndTimeISO + streamingResult.execution.output.providerTiming.duration = + streamEndTime - providerStartTime + } } - }), + ), execution: { success: true, output: { @@ -778,21 +857,13 @@ export async function executeAnthropicProviderRequest( const providerStartTime = Date.now() const providerStartTimeISO = new Date(providerStartTime).toISOString() - // Cap intermediate calls at non-streaming limit to avoid SDK timeout errors, - // but allow users to set lower values if desired - const nonStreamingLimit = getMaxOutputTokensForModel(request.model, false) - const toolLoopMaxTokens = request.maxTokens - ? Math.min(Number.parseInt(String(request.maxTokens)), nonStreamingLimit) - : nonStreamingLimit - const toolLoopPayload = { ...payload, max_tokens: toolLoopMaxTokens } - try { const initialCallTime = Date.now() - const originalToolChoice = toolLoopPayload.tool_choice + const originalToolChoice = payload.tool_choice const forcedTools = preparedTools?.forcedTools || [] let usedForcedTools: string[] = [] - let currentResponse = await anthropic.messages.create(toolLoopPayload) + let currentResponse = await createMessage(anthropic, payload) const firstResponseTime = Date.now() - initialCallTime let content = '' @@ -872,7 +943,7 @@ export async function executeAnthropicProviderRequest( const toolExecutionPromises = toolUses.map(async (toolUse) => { const toolCallStartTime = Date.now() const toolName = toolUse.name - const toolArgs = toolUse.input as Record + const toolArgs = toolUse.input as Record // Preserve the original tool_use ID from Claude's response const toolUseId = toolUse.id @@ -918,17 +989,8 @@ export async function executeAnthropicProviderRequest( const executionResults = await Promise.allSettled(toolExecutionPromises) // Collect all tool_use and tool_result blocks for batching - const toolUseBlocks: Array<{ - type: 'tool_use' - id: string - name: string - input: Record - }> = [] - const toolResultBlocks: Array<{ - type: 'tool_result' - tool_use_id: string - content: string - }> = [] + const toolUseBlocks: Anthropic.Messages.ToolUseBlockParam[] = [] + const toolResultBlocks: Anthropic.Messages.ToolResultBlockParam[] = [] for (const settledResult of executionResults) { if (settledResult.status === 'rejected' || !settledResult.value) continue @@ -989,11 +1051,23 @@ export async function executeAnthropicProviderRequest( }) } - // Add ONE assistant message with ALL tool_use blocks + // Per Anthropic docs: thinking blocks must be preserved in assistant messages + // during tool use to maintain reasoning continuity. + const thinkingBlocks = currentResponse.content.filter( + ( + item + ): item is Anthropic.Messages.ThinkingBlock | Anthropic.Messages.RedactedThinkingBlock => + item.type === 'thinking' || item.type === 'redacted_thinking' + ) + + // Add ONE assistant message with thinking + tool_use blocks if (toolUseBlocks.length > 0) { currentMessages.push({ role: 'assistant', - content: toolUseBlocks as unknown as Anthropic.Messages.ContentBlock[], + content: [ + ...thinkingBlocks, + ...toolUseBlocks, + ] as Anthropic.Messages.ContentBlockParam[], }) } @@ -1001,19 +1075,27 @@ export async function executeAnthropicProviderRequest( if (toolResultBlocks.length > 0) { currentMessages.push({ role: 'user', - content: toolResultBlocks as unknown as Anthropic.Messages.ContentBlockParam[], + content: toolResultBlocks as Anthropic.Messages.ContentBlockParam[], }) } const thisToolsTime = Date.now() - toolsStartTime toolsTime += thisToolsTime - const nextPayload = { - ...toolLoopPayload, + const nextPayload: AnthropicPayload = { + ...payload, messages: currentMessages, } - if (typeof originalToolChoice === 'object' && hasUsedForcedTool && forcedTools.length > 0) { + // Per Anthropic docs: forced tool_choice is incompatible with thinking. + // Only auto and none are supported when thinking is enabled. + const thinkingEnabled = !!payload.thinking + if ( + !thinkingEnabled && + typeof originalToolChoice === 'object' && + hasUsedForcedTool && + forcedTools.length > 0 + ) { const remainingTools = forcedTools.filter((tool) => !usedForcedTools.includes(tool)) if (remainingTools.length > 0) { @@ -1026,7 +1108,11 @@ export async function executeAnthropicProviderRequest( nextPayload.tool_choice = undefined logger.info('All forced tools have been used, removing tool_choice parameter') } - } else if (hasUsedForcedTool && typeof originalToolChoice === 'object') { + } else if ( + !thinkingEnabled && + hasUsedForcedTool && + typeof originalToolChoice === 'object' + ) { nextPayload.tool_choice = undefined logger.info( 'Removing tool_choice parameter for subsequent requests after forced tool was used' @@ -1035,7 +1121,7 @@ export async function executeAnthropicProviderRequest( const nextModelStartTime = Date.now() - currentResponse = await anthropic.messages.create(nextPayload) + currentResponse = await createMessage(anthropic, nextPayload) const nextCheckResult = checkForForcedToolUsage( currentResponse, @@ -1098,33 +1184,38 @@ export async function executeAnthropicProviderRequest( tool_choice: undefined, } - const streamResponse: any = await anthropic.messages.create(streamingPayload) + const streamResponse = await anthropic.messages.create( + streamingPayload as Anthropic.Messages.MessageCreateParamsStreaming + ) const streamingResult = { - stream: createReadableStreamFromAnthropicStream(streamResponse, (streamContent, usage) => { - streamingResult.execution.output.content = streamContent - streamingResult.execution.output.tokens = { - input: tokens.input + usage.input_tokens, - output: tokens.output + usage.output_tokens, - total: tokens.total + usage.input_tokens + usage.output_tokens, - } + stream: createReadableStreamFromAnthropicStream( + streamResponse as AsyncIterable, + (streamContent, usage) => { + streamingResult.execution.output.content = streamContent + streamingResult.execution.output.tokens = { + input: tokens.input + usage.input_tokens, + output: tokens.output + usage.output_tokens, + total: tokens.total + usage.input_tokens + usage.output_tokens, + } - const streamCost = calculateCost(request.model, usage.input_tokens, usage.output_tokens) - streamingResult.execution.output.cost = { - input: cost.input + streamCost.input, - output: cost.output + streamCost.output, - total: cost.total + streamCost.total, - } + const streamCost = calculateCost(request.model, usage.input_tokens, usage.output_tokens) + streamingResult.execution.output.cost = { + input: cost.input + streamCost.input, + output: cost.output + streamCost.output, + total: cost.total + streamCost.total, + } - const streamEndTime = Date.now() - const streamEndTimeISO = new Date(streamEndTime).toISOString() + const streamEndTime = Date.now() + const streamEndTimeISO = new Date(streamEndTime).toISOString() - if (streamingResult.execution.output.providerTiming) { - streamingResult.execution.output.providerTiming.endTime = streamEndTimeISO - streamingResult.execution.output.providerTiming.duration = - streamEndTime - providerStartTime + if (streamingResult.execution.output.providerTiming) { + streamingResult.execution.output.providerTiming.endTime = streamEndTimeISO + streamingResult.execution.output.providerTiming.duration = + streamEndTime - providerStartTime + } } - }), + ), execution: { success: true, output: { @@ -1179,7 +1270,7 @@ export async function executeAnthropicProviderRequest( toolCalls.length > 0 ? toolCalls.map((tc) => ({ name: tc.name, - arguments: tc.arguments as Record, + arguments: tc.arguments as Record, startTime: tc.startTime, endTime: tc.endTime, duration: tc.duration, diff --git a/apps/sim/providers/azure-openai/index.ts b/apps/sim/providers/azure-openai/index.ts index ca63904df..d8b6c268c 100644 --- a/apps/sim/providers/azure-openai/index.ts +++ b/apps/sim/providers/azure-openai/index.ts @@ -1,6 +1,14 @@ import { createLogger } from '@sim/logger' import { AzureOpenAI } from 'openai' -import type { ChatCompletionCreateParamsStreaming } from 'openai/resources/chat/completions' +import type { + ChatCompletion, + ChatCompletionCreateParamsBase, + ChatCompletionCreateParamsStreaming, + ChatCompletionMessageParam, + ChatCompletionTool, + ChatCompletionToolChoiceOption, +} from 'openai/resources/chat/completions' +import type { ReasoningEffort } from 'openai/resources/shared' import { env } from '@/lib/core/config/env' import type { StreamingExecution } from '@/executor/types' import { MAX_TOOL_ITERATIONS } from '@/providers' @@ -16,6 +24,7 @@ import { import { getProviderDefaultModel, getProviderModels } from '@/providers/models' import { executeResponsesProviderRequest } from '@/providers/openai/core' import type { + FunctionCallResponse, ProviderConfig, ProviderRequest, ProviderResponse, @@ -59,7 +68,7 @@ async function executeChatCompletionsRequest( endpoint: azureEndpoint, }) - const allMessages: any[] = [] + const allMessages: ChatCompletionMessageParam[] = [] if (request.systemPrompt) { allMessages.push({ @@ -76,12 +85,12 @@ async function executeChatCompletionsRequest( } if (request.messages) { - allMessages.push(...request.messages) + allMessages.push(...(request.messages as ChatCompletionMessageParam[])) } - const tools = request.tools?.length + const tools: ChatCompletionTool[] | undefined = request.tools?.length ? request.tools.map((tool) => ({ - type: 'function', + type: 'function' as const, function: { name: tool.id, description: tool.description, @@ -90,7 +99,7 @@ async function executeChatCompletionsRequest( })) : undefined - const payload: any = { + const payload: ChatCompletionCreateParamsBase & { verbosity?: string } = { model: deploymentName, messages: allMessages, } @@ -98,8 +107,10 @@ async function executeChatCompletionsRequest( if (request.temperature !== undefined) payload.temperature = request.temperature if (request.maxTokens != null) payload.max_completion_tokens = request.maxTokens - if (request.reasoningEffort !== undefined) payload.reasoning_effort = request.reasoningEffort - if (request.verbosity !== undefined) payload.verbosity = request.verbosity + if (request.reasoningEffort !== undefined && request.reasoningEffort !== 'auto') + payload.reasoning_effort = request.reasoningEffort as ReasoningEffort + if (request.verbosity !== undefined && request.verbosity !== 'auto') + payload.verbosity = request.verbosity if (request.responseFormat) { payload.response_format = { @@ -121,8 +132,8 @@ async function executeChatCompletionsRequest( const { tools: filteredTools, toolChoice } = preparedTools if (filteredTools?.length && toolChoice) { - payload.tools = filteredTools - payload.tool_choice = toolChoice + payload.tools = filteredTools as ChatCompletionTool[] + payload.tool_choice = toolChoice as ChatCompletionToolChoiceOption logger.info('Azure OpenAI request configuration:', { toolCount: filteredTools.length, @@ -231,7 +242,7 @@ async function executeChatCompletionsRequest( const forcedTools = preparedTools?.forcedTools || [] let usedForcedTools: string[] = [] - let currentResponse = await azureOpenAI.chat.completions.create(payload) + let currentResponse = (await azureOpenAI.chat.completions.create(payload)) as ChatCompletion const firstResponseTime = Date.now() - initialCallTime let content = currentResponse.choices[0]?.message?.content || '' @@ -240,8 +251,8 @@ async function executeChatCompletionsRequest( output: currentResponse.usage?.completion_tokens || 0, total: currentResponse.usage?.total_tokens || 0, } - const toolCalls = [] - const toolResults = [] + const toolCalls: (FunctionCallResponse & { success: boolean })[] = [] + const toolResults: Record[] = [] const currentMessages = [...allMessages] let iterationCount = 0 let modelTime = firstResponseTime @@ -260,7 +271,7 @@ async function executeChatCompletionsRequest( const firstCheckResult = checkForForcedToolUsage( currentResponse, - originalToolChoice, + originalToolChoice ?? 'auto', logger, forcedTools, usedForcedTools @@ -356,10 +367,10 @@ async function executeChatCompletionsRequest( duration: duration, }) - let resultContent: any + let resultContent: Record if (result.success) { - toolResults.push(result.output) - resultContent = result.output + toolResults.push(result.output as Record) + resultContent = result.output as Record } else { resultContent = { error: true, @@ -409,11 +420,11 @@ async function executeChatCompletionsRequest( } const nextModelStartTime = Date.now() - currentResponse = await azureOpenAI.chat.completions.create(nextPayload) + currentResponse = (await azureOpenAI.chat.completions.create(nextPayload)) as ChatCompletion const nextCheckResult = checkForForcedToolUsage( currentResponse, - nextPayload.tool_choice, + nextPayload.tool_choice ?? 'auto', logger, forcedTools, usedForcedTools diff --git a/apps/sim/providers/azure-openai/utils.ts b/apps/sim/providers/azure-openai/utils.ts index 36e65e678..fec1e862e 100644 --- a/apps/sim/providers/azure-openai/utils.ts +++ b/apps/sim/providers/azure-openai/utils.ts @@ -1,4 +1,5 @@ import type { Logger } from '@sim/logger' +import type OpenAI from 'openai' import type { ChatCompletionChunk } from 'openai/resources/chat/completions' import type { CompletionUsage } from 'openai/resources/completions' import type { Stream } from 'openai/streaming' @@ -20,8 +21,8 @@ export function createReadableStreamFromAzureOpenAIStream( * Uses the shared OpenAI-compatible forced tool usage helper. */ export function checkForForcedToolUsage( - response: any, - toolChoice: string | { type: string; function?: { name: string }; name?: string; any?: any }, + response: OpenAI.Chat.Completions.ChatCompletion, + toolChoice: string | { type: string; function?: { name: string }; name?: string }, _logger: Logger, forcedTools: string[], usedForcedTools: string[] diff --git a/apps/sim/providers/bedrock/index.ts b/apps/sim/providers/bedrock/index.ts index 57935394a..e602627b7 100644 --- a/apps/sim/providers/bedrock/index.ts +++ b/apps/sim/providers/bedrock/index.ts @@ -197,6 +197,9 @@ export const bedrockProvider: ProviderConfig = { } else if (tc.type === 'function' && tc.function?.name) { toolChoice = { tool: { name: tc.function.name } } logger.info(`Using Bedrock tool_choice format: force tool "${tc.function.name}"`) + } else if (tc.type === 'any') { + toolChoice = { any: {} } + logger.info('Using Bedrock tool_choice format: any tool') } else { toolChoice = { auto: {} } } @@ -413,6 +416,7 @@ export const bedrockProvider: ProviderConfig = { input: initialCost.input, output: initialCost.output, total: initialCost.total, + pricing: initialCost.pricing, } const toolCalls: any[] = [] @@ -860,6 +864,12 @@ export const bedrockProvider: ProviderConfig = { content, model: request.model, tokens, + cost: { + input: cost.input, + output: cost.output, + total: cost.total, + pricing: cost.pricing, + }, toolCalls: toolCalls.length > 0 ? toolCalls.map((tc) => ({ diff --git a/apps/sim/providers/gemini/core.ts b/apps/sim/providers/gemini/core.ts index 5050672ea..4e7164b82 100644 --- a/apps/sim/providers/gemini/core.ts +++ b/apps/sim/providers/gemini/core.ts @@ -24,7 +24,6 @@ import { extractTextContent, mapToThinkingLevel, } from '@/providers/google/utils' -import { getThinkingCapability } from '@/providers/models' import type { FunctionCallResponse, ProviderRequest, ProviderResponse } from '@/providers/types' import { calculateCost, @@ -432,13 +431,11 @@ export async function executeGeminiRequest( logger.warn('Gemini does not support responseFormat with tools. Structured output ignored.') } - // Configure thinking for models that support it - const thinkingCapability = getThinkingCapability(model) - if (thinkingCapability) { - const level = request.thinkingLevel ?? thinkingCapability.default ?? 'high' + // Configure thinking only when the user explicitly selects a thinking level + if (request.thinkingLevel && request.thinkingLevel !== 'none') { const thinkingConfig: ThinkingConfig = { includeThoughts: false, - thinkingLevel: mapToThinkingLevel(level), + thinkingLevel: mapToThinkingLevel(request.thinkingLevel), } geminiConfig.thinkingConfig = thinkingConfig } diff --git a/apps/sim/providers/mistral/index.ts b/apps/sim/providers/mistral/index.ts index fb3e701ed..0195c04fb 100644 --- a/apps/sim/providers/mistral/index.ts +++ b/apps/sim/providers/mistral/index.ts @@ -141,7 +141,6 @@ export const mistralProvider: ProviderConfig = { const streamingParams: ChatCompletionCreateParamsStreaming = { ...payload, stream: true, - stream_options: { include_usage: true }, } const streamResponse = await mistral.chat.completions.create(streamingParams) @@ -453,7 +452,6 @@ export const mistralProvider: ProviderConfig = { messages: currentMessages, tool_choice: 'auto', stream: true, - stream_options: { include_usage: true }, } const streamResponse = await mistral.chat.completions.create(streamingParams) diff --git a/apps/sim/providers/models.ts b/apps/sim/providers/models.ts index 3662e1ca5..cbced7ffe 100644 --- a/apps/sim/providers/models.ts +++ b/apps/sim/providers/models.ts @@ -34,17 +34,8 @@ export interface ModelCapabilities { toolUsageControl?: boolean computerUse?: boolean nativeStructuredOutputs?: boolean - /** - * Max output tokens configuration for Anthropic SDK's streaming timeout workaround. - * The Anthropic SDK throws an error for non-streaming requests that may take >10 minutes. - * This only applies to direct Anthropic API calls, not Bedrock (which uses AWS SDK). - */ - maxOutputTokens?: { - /** Maximum tokens for streaming requests */ - max: number - /** Safe default for non-streaming requests (to avoid Anthropic SDK timeout errors) */ - default: number - } + /** Maximum supported output tokens for this model */ + maxOutputTokens?: number reasoningEffort?: { values: string[] } @@ -109,7 +100,7 @@ export const PROVIDER_DEFINITIONS: Record = { name: 'OpenAI', description: "OpenAI's models", defaultModel: 'gpt-4o', - modelPatterns: [/^gpt/, /^o1/, /^text-embedding/], + modelPatterns: [/^gpt/, /^o\d/, /^text-embedding/], icon: OpenAIIcon, capabilities: { toolUsageControl: true, @@ -138,7 +129,7 @@ export const PROVIDER_DEFINITIONS: Record = { }, capabilities: { reasoningEffort: { - values: ['none', 'minimal', 'low', 'medium', 'high', 'xhigh'], + values: ['none', 'low', 'medium', 'high', 'xhigh'], }, verbosity: { values: ['low', 'medium', 'high'], @@ -164,60 +155,6 @@ export const PROVIDER_DEFINITIONS: Record = { }, contextWindow: 400000, }, - // { - // id: 'gpt-5.1-mini', - // pricing: { - // input: 0.25, - // cachedInput: 0.025, - // output: 2.0, - // updatedAt: '2025-11-14', - // }, - // capabilities: { - // reasoningEffort: { - // values: ['none', 'low', 'medium', 'high'], - // }, - // verbosity: { - // values: ['low', 'medium', 'high'], - // }, - // }, - // contextWindow: 400000, - // }, - // { - // id: 'gpt-5.1-nano', - // pricing: { - // input: 0.05, - // cachedInput: 0.005, - // output: 0.4, - // updatedAt: '2025-11-14', - // }, - // capabilities: { - // reasoningEffort: { - // values: ['none', 'low', 'medium', 'high'], - // }, - // verbosity: { - // values: ['low', 'medium', 'high'], - // }, - // }, - // contextWindow: 400000, - // }, - // { - // id: 'gpt-5.1-codex', - // pricing: { - // input: 1.25, - // cachedInput: 0.125, - // output: 10.0, - // updatedAt: '2025-11-14', - // }, - // capabilities: { - // reasoningEffort: { - // values: ['none', 'medium', 'high'], - // }, - // verbosity: { - // values: ['low', 'medium', 'high'], - // }, - // }, - // contextWindow: 400000, - // }, { id: 'gpt-5', pricing: { @@ -280,8 +217,10 @@ export const PROVIDER_DEFINITIONS: Record = { output: 10.0, updatedAt: '2025-08-07', }, - capabilities: {}, - contextWindow: 400000, + capabilities: { + temperature: { min: 0, max: 2 }, + }, + contextWindow: 128000, }, { id: 'o1', @@ -311,7 +250,7 @@ export const PROVIDER_DEFINITIONS: Record = { values: ['low', 'medium', 'high'], }, }, - contextWindow: 128000, + contextWindow: 200000, }, { id: 'o4-mini', @@ -326,7 +265,7 @@ export const PROVIDER_DEFINITIONS: Record = { values: ['low', 'medium', 'high'], }, }, - contextWindow: 128000, + contextWindow: 200000, }, { id: 'gpt-4.1', @@ -391,7 +330,7 @@ export const PROVIDER_DEFINITIONS: Record = { capabilities: { temperature: { min: 0, max: 1 }, nativeStructuredOutputs: true, - maxOutputTokens: { max: 128000, default: 8192 }, + maxOutputTokens: 128000, thinking: { levels: ['low', 'medium', 'high', 'max'], default: 'high', @@ -410,10 +349,10 @@ export const PROVIDER_DEFINITIONS: Record = { capabilities: { temperature: { min: 0, max: 1 }, nativeStructuredOutputs: true, - maxOutputTokens: { max: 64000, default: 8192 }, + maxOutputTokens: 64000, thinking: { levels: ['low', 'medium', 'high'], - default: 'medium', + default: 'high', }, }, contextWindow: 200000, @@ -429,10 +368,10 @@ export const PROVIDER_DEFINITIONS: Record = { capabilities: { temperature: { min: 0, max: 1 }, nativeStructuredOutputs: true, - maxOutputTokens: { max: 64000, default: 8192 }, + maxOutputTokens: 64000, thinking: { levels: ['low', 'medium', 'high'], - default: 'medium', + default: 'high', }, }, contextWindow: 200000, @@ -447,10 +386,10 @@ export const PROVIDER_DEFINITIONS: Record = { }, capabilities: { temperature: { min: 0, max: 1 }, - maxOutputTokens: { max: 64000, default: 8192 }, + maxOutputTokens: 64000, thinking: { levels: ['low', 'medium', 'high'], - default: 'medium', + default: 'high', }, }, contextWindow: 200000, @@ -466,10 +405,10 @@ export const PROVIDER_DEFINITIONS: Record = { capabilities: { temperature: { min: 0, max: 1 }, nativeStructuredOutputs: true, - maxOutputTokens: { max: 64000, default: 8192 }, + maxOutputTokens: 64000, thinking: { levels: ['low', 'medium', 'high'], - default: 'medium', + default: 'high', }, }, contextWindow: 200000, @@ -484,10 +423,10 @@ export const PROVIDER_DEFINITIONS: Record = { }, capabilities: { temperature: { min: 0, max: 1 }, - maxOutputTokens: { max: 64000, default: 8192 }, + maxOutputTokens: 64000, thinking: { levels: ['low', 'medium', 'high'], - default: 'medium', + default: 'high', }, }, contextWindow: 200000, @@ -503,10 +442,10 @@ export const PROVIDER_DEFINITIONS: Record = { capabilities: { temperature: { min: 0, max: 1 }, nativeStructuredOutputs: true, - maxOutputTokens: { max: 64000, default: 8192 }, + maxOutputTokens: 64000, thinking: { levels: ['low', 'medium', 'high'], - default: 'medium', + default: 'high', }, }, contextWindow: 200000, @@ -515,13 +454,13 @@ export const PROVIDER_DEFINITIONS: Record = { id: 'claude-3-haiku-20240307', pricing: { input: 0.25, - cachedInput: 0.025, + cachedInput: 0.03, output: 1.25, updatedAt: '2026-02-05', }, capabilities: { temperature: { min: 0, max: 1 }, - maxOutputTokens: { max: 4096, default: 4096 }, + maxOutputTokens: 4096, }, contextWindow: 200000, }, @@ -536,10 +475,10 @@ export const PROVIDER_DEFINITIONS: Record = { capabilities: { temperature: { min: 0, max: 1 }, computerUse: true, - maxOutputTokens: { max: 8192, default: 8192 }, + maxOutputTokens: 64000, thinking: { levels: ['low', 'medium', 'high'], - default: 'medium', + default: 'high', }, }, contextWindow: 200000, @@ -580,7 +519,7 @@ export const PROVIDER_DEFINITIONS: Record = { }, capabilities: { reasoningEffort: { - values: ['none', 'minimal', 'low', 'medium', 'high', 'xhigh'], + values: ['none', 'low', 'medium', 'high', 'xhigh'], }, verbosity: { values: ['low', 'medium', 'high'], @@ -606,42 +545,6 @@ export const PROVIDER_DEFINITIONS: Record = { }, contextWindow: 400000, }, - { - id: 'azure/gpt-5.1-mini', - pricing: { - input: 0.25, - cachedInput: 0.025, - output: 2.0, - updatedAt: '2025-11-14', - }, - capabilities: { - reasoningEffort: { - values: ['none', 'low', 'medium', 'high'], - }, - verbosity: { - values: ['low', 'medium', 'high'], - }, - }, - contextWindow: 400000, - }, - { - id: 'azure/gpt-5.1-nano', - pricing: { - input: 0.05, - cachedInput: 0.005, - output: 0.4, - updatedAt: '2025-11-14', - }, - capabilities: { - reasoningEffort: { - values: ['none', 'low', 'medium', 'high'], - }, - verbosity: { - values: ['low', 'medium', 'high'], - }, - }, - contextWindow: 400000, - }, { id: 'azure/gpt-5.1-codex', pricing: { @@ -652,7 +555,7 @@ export const PROVIDER_DEFINITIONS: Record = { }, capabilities: { reasoningEffort: { - values: ['none', 'medium', 'high'], + values: ['none', 'low', 'medium', 'high'], }, verbosity: { values: ['low', 'medium', 'high'], @@ -722,23 +625,25 @@ export const PROVIDER_DEFINITIONS: Record = { output: 10.0, updatedAt: '2025-08-07', }, - capabilities: {}, - contextWindow: 400000, + capabilities: { + temperature: { min: 0, max: 2 }, + }, + contextWindow: 128000, }, { id: 'azure/o3', pricing: { - input: 10, - cachedInput: 2.5, - output: 40, - updatedAt: '2025-06-15', + input: 2, + cachedInput: 0.5, + output: 8, + updatedAt: '2026-02-06', }, capabilities: { reasoningEffort: { values: ['low', 'medium', 'high'], }, }, - contextWindow: 128000, + contextWindow: 200000, }, { id: 'azure/o4-mini', @@ -753,7 +658,7 @@ export const PROVIDER_DEFINITIONS: Record = { values: ['low', 'medium', 'high'], }, }, - contextWindow: 128000, + contextWindow: 200000, }, { id: 'azure/gpt-4.1', @@ -763,7 +668,35 @@ export const PROVIDER_DEFINITIONS: Record = { output: 8.0, updatedAt: '2025-06-15', }, - capabilities: {}, + capabilities: { + temperature: { min: 0, max: 2 }, + }, + contextWindow: 1000000, + }, + { + id: 'azure/gpt-4.1-mini', + pricing: { + input: 0.4, + cachedInput: 0.1, + output: 1.6, + updatedAt: '2025-06-15', + }, + capabilities: { + temperature: { min: 0, max: 2 }, + }, + contextWindow: 1000000, + }, + { + id: 'azure/gpt-4.1-nano', + pricing: { + input: 0.1, + cachedInput: 0.025, + output: 0.4, + updatedAt: '2025-06-15', + }, + capabilities: { + temperature: { min: 0, max: 2 }, + }, contextWindow: 1000000, }, { @@ -775,7 +708,7 @@ export const PROVIDER_DEFINITIONS: Record = { updatedAt: '2025-06-15', }, capabilities: {}, - contextWindow: 1000000, + contextWindow: 200000, }, ], }, @@ -801,7 +734,7 @@ export const PROVIDER_DEFINITIONS: Record = { capabilities: { temperature: { min: 0, max: 1 }, nativeStructuredOutputs: true, - maxOutputTokens: { max: 128000, default: 8192 }, + maxOutputTokens: 128000, thinking: { levels: ['low', 'medium', 'high', 'max'], default: 'high', @@ -820,10 +753,10 @@ export const PROVIDER_DEFINITIONS: Record = { capabilities: { temperature: { min: 0, max: 1 }, nativeStructuredOutputs: true, - maxOutputTokens: { max: 64000, default: 8192 }, + maxOutputTokens: 64000, thinking: { levels: ['low', 'medium', 'high'], - default: 'medium', + default: 'high', }, }, contextWindow: 200000, @@ -839,10 +772,10 @@ export const PROVIDER_DEFINITIONS: Record = { capabilities: { temperature: { min: 0, max: 1 }, nativeStructuredOutputs: true, - maxOutputTokens: { max: 64000, default: 8192 }, + maxOutputTokens: 64000, thinking: { levels: ['low', 'medium', 'high'], - default: 'medium', + default: 'high', }, }, contextWindow: 200000, @@ -858,10 +791,10 @@ export const PROVIDER_DEFINITIONS: Record = { capabilities: { temperature: { min: 0, max: 1 }, nativeStructuredOutputs: true, - maxOutputTokens: { max: 64000, default: 8192 }, + maxOutputTokens: 64000, thinking: { levels: ['low', 'medium', 'high'], - default: 'medium', + default: 'high', }, }, contextWindow: 200000, @@ -877,10 +810,10 @@ export const PROVIDER_DEFINITIONS: Record = { capabilities: { temperature: { min: 0, max: 1 }, nativeStructuredOutputs: true, - maxOutputTokens: { max: 64000, default: 8192 }, + maxOutputTokens: 64000, thinking: { levels: ['low', 'medium', 'high'], - default: 'medium', + default: 'high', }, }, contextWindow: 200000, @@ -2548,14 +2481,11 @@ export function getThinkingLevelsForModel(modelId: string): string[] | null { } /** - * Get the max output tokens for a specific model - * Returns the model's max capacity for streaming requests, - * or the model's safe default for non-streaming requests to avoid timeout issues. + * Get the max output tokens for a specific model. * * @param modelId - The model ID - * @param streaming - Whether the request is streaming (default: false) */ -export function getMaxOutputTokensForModel(modelId: string, streaming = false): number { +export function getMaxOutputTokensForModel(modelId: string): number { const normalizedModelId = modelId.toLowerCase() const STANDARD_MAX_OUTPUT_TOKENS = 4096 @@ -2563,11 +2493,7 @@ export function getMaxOutputTokensForModel(modelId: string, streaming = false): for (const model of provider.models) { const baseModelId = model.id.toLowerCase() if (normalizedModelId === baseModelId || normalizedModelId.startsWith(`${baseModelId}-`)) { - const outputTokens = model.capabilities.maxOutputTokens - if (outputTokens) { - return streaming ? outputTokens.max : outputTokens.default - } - return STANDARD_MAX_OUTPUT_TOKENS + return model.capabilities.maxOutputTokens || STANDARD_MAX_OUTPUT_TOKENS } } } diff --git a/apps/sim/providers/openai/core.ts b/apps/sim/providers/openai/core.ts index 8ed4c9386..6e6d42cb4 100644 --- a/apps/sim/providers/openai/core.ts +++ b/apps/sim/providers/openai/core.ts @@ -1,4 +1,5 @@ import type { Logger } from '@sim/logger' +import type OpenAI from 'openai' import type { StreamingExecution } from '@/executor/types' import { MAX_TOOL_ITERATIONS } from '@/providers' import type { Message, ProviderRequest, ProviderResponse, TimeSegment } from '@/providers/types' @@ -30,7 +31,7 @@ type ToolChoice = PreparedTools['toolChoice'] * - Sets additionalProperties: false on all object types. * - Ensures required includes ALL property keys. */ -function enforceStrictSchema(schema: any): any { +function enforceStrictSchema(schema: Record): Record { if (!schema || typeof schema !== 'object') return schema const result = { ...schema } @@ -41,23 +42,26 @@ function enforceStrictSchema(schema: any): any { // Recursively process properties and ensure required includes all keys if (result.properties && typeof result.properties === 'object') { - const propKeys = Object.keys(result.properties) + const propKeys = Object.keys(result.properties as Record) result.required = propKeys // Strict mode requires ALL properties result.properties = Object.fromEntries( - Object.entries(result.properties).map(([key, value]) => [key, enforceStrictSchema(value)]) + Object.entries(result.properties as Record).map(([key, value]) => [ + key, + enforceStrictSchema(value as Record), + ]) ) } } // Handle array items if (result.type === 'array' && result.items) { - result.items = enforceStrictSchema(result.items) + result.items = enforceStrictSchema(result.items as Record) } // Handle anyOf, oneOf, allOf for (const keyword of ['anyOf', 'oneOf', 'allOf']) { if (Array.isArray(result[keyword])) { - result[keyword] = result[keyword].map(enforceStrictSchema) + result[keyword] = (result[keyword] as Record[]).map(enforceStrictSchema) } } @@ -65,7 +69,10 @@ function enforceStrictSchema(schema: any): any { for (const defKey of ['$defs', 'definitions']) { if (result[defKey] && typeof result[defKey] === 'object') { result[defKey] = Object.fromEntries( - Object.entries(result[defKey]).map(([key, value]) => [key, enforceStrictSchema(value)]) + Object.entries(result[defKey] as Record).map(([key, value]) => [ + key, + enforceStrictSchema(value as Record), + ]) ) } } @@ -123,29 +130,29 @@ export async function executeResponsesProviderRequest( const initialInput = buildResponsesInputFromMessages(allMessages) - const basePayload: Record = { + const basePayload: Record = { model: config.modelName, } if (request.temperature !== undefined) basePayload.temperature = request.temperature if (request.maxTokens != null) basePayload.max_output_tokens = request.maxTokens - if (request.reasoningEffort !== undefined) { + if (request.reasoningEffort !== undefined && request.reasoningEffort !== 'auto') { basePayload.reasoning = { effort: request.reasoningEffort, summary: 'auto', } } - if (request.verbosity !== undefined) { + if (request.verbosity !== undefined && request.verbosity !== 'auto') { basePayload.text = { - ...(basePayload.text ?? {}), + ...((basePayload.text as Record) ?? {}), verbosity: request.verbosity, } } // Store response format config - for Azure with tools, we defer applying it until after tool calls complete - let deferredTextFormat: { type: string; name: string; schema: any; strict: boolean } | undefined + let deferredTextFormat: OpenAI.Responses.ResponseFormatTextJSONSchemaConfig | undefined const hasTools = !!request.tools?.length const isAzure = config.providerId === 'azure-openai' @@ -171,7 +178,7 @@ export async function executeResponsesProviderRequest( ) } else { basePayload.text = { - ...(basePayload.text ?? {}), + ...((basePayload.text as Record) ?? {}), format: textFormat, } logger.info(`Added JSON schema response format to ${config.providerLabel} request`) @@ -231,7 +238,10 @@ export async function executeResponsesProviderRequest( } } - const createRequestBody = (input: ResponsesInputItem[], overrides: Record = {}) => ({ + const createRequestBody = ( + input: ResponsesInputItem[], + overrides: Record = {} + ) => ({ ...basePayload, input, ...overrides, @@ -247,7 +257,9 @@ export async function executeResponsesProviderRequest( } } - const postResponses = async (body: Record) => { + const postResponses = async ( + body: Record + ): Promise => { const response = await fetch(config.endpoint, { method: 'POST', headers: config.headers, @@ -496,10 +508,10 @@ export async function executeResponsesProviderRequest( duration: duration, }) - let resultContent: any + let resultContent: Record if (result.success) { toolResults.push(result.output) - resultContent = result.output + resultContent = result.output as Record } else { resultContent = { error: true, @@ -615,11 +627,11 @@ export async function executeResponsesProviderRequest( } // Make final call with the response format - build payload without tools - const finalPayload: Record = { + const finalPayload: Record = { model: config.modelName, input: formattedInput, text: { - ...(basePayload.text ?? {}), + ...((basePayload.text as Record) ?? {}), format: deferredTextFormat, }, } @@ -627,15 +639,15 @@ export async function executeResponsesProviderRequest( // Copy over non-tool related settings if (request.temperature !== undefined) finalPayload.temperature = request.temperature if (request.maxTokens != null) finalPayload.max_output_tokens = request.maxTokens - if (request.reasoningEffort !== undefined) { + if (request.reasoningEffort !== undefined && request.reasoningEffort !== 'auto') { finalPayload.reasoning = { effort: request.reasoningEffort, summary: 'auto', } } - if (request.verbosity !== undefined) { + if (request.verbosity !== undefined && request.verbosity !== 'auto') { finalPayload.text = { - ...finalPayload.text, + ...((finalPayload.text as Record) ?? {}), verbosity: request.verbosity, } } @@ -679,10 +691,10 @@ export async function executeResponsesProviderRequest( const accumulatedCost = calculateCost(request.model, tokens.input, tokens.output) // For Azure with deferred format in streaming mode, include the format in the streaming call - const streamOverrides: Record = { stream: true, tool_choice: 'auto' } + const streamOverrides: Record = { stream: true, tool_choice: 'auto' } if (deferredTextFormat) { streamOverrides.text = { - ...(basePayload.text ?? {}), + ...((basePayload.text as Record) ?? {}), format: deferredTextFormat, } } diff --git a/apps/sim/providers/openai/utils.ts b/apps/sim/providers/openai/utils.ts index 664c0d8fc..f1575473a 100644 --- a/apps/sim/providers/openai/utils.ts +++ b/apps/sim/providers/openai/utils.ts @@ -1,4 +1,5 @@ import { createLogger } from '@sim/logger' +import type OpenAI from 'openai' import type { Message } from '@/providers/types' const logger = createLogger('ResponsesUtils') @@ -38,7 +39,7 @@ export interface ResponsesToolDefinition { type: 'function' name: string description?: string - parameters?: Record + parameters?: Record } /** @@ -85,7 +86,15 @@ export function buildResponsesInputFromMessages(messages: Message[]): ResponsesI /** * Converts tool definitions to the Responses API format. */ -export function convertToolsToResponses(tools: any[]): ResponsesToolDefinition[] { +export function convertToolsToResponses( + tools: Array<{ + type?: string + name?: string + description?: string + parameters?: Record + function?: { name: string; description?: string; parameters?: Record } + }> +): ResponsesToolDefinition[] { return tools .map((tool) => { const name = tool.function?.name ?? tool.name @@ -131,7 +140,7 @@ export function toResponsesToolChoice( return 'auto' } -function extractTextFromMessageItem(item: any): string { +function extractTextFromMessageItem(item: Record): string { if (!item) { return '' } @@ -170,7 +179,7 @@ function extractTextFromMessageItem(item: any): string { /** * Extracts plain text from Responses API output items. */ -export function extractResponseText(output: unknown): string { +export function extractResponseText(output: OpenAI.Responses.ResponseOutputItem[]): string { if (!Array.isArray(output)) { return '' } @@ -181,7 +190,7 @@ export function extractResponseText(output: unknown): string { continue } - const text = extractTextFromMessageItem(item) + const text = extractTextFromMessageItem(item as unknown as Record) if (text) { textParts.push(text) } @@ -193,7 +202,9 @@ export function extractResponseText(output: unknown): string { /** * Converts Responses API output items into input items for subsequent calls. */ -export function convertResponseOutputToInputItems(output: unknown): ResponsesInputItem[] { +export function convertResponseOutputToInputItems( + output: OpenAI.Responses.ResponseOutputItem[] +): ResponsesInputItem[] { if (!Array.isArray(output)) { return [] } @@ -205,7 +216,7 @@ export function convertResponseOutputToInputItems(output: unknown): ResponsesInp } if (item.type === 'message') { - const text = extractTextFromMessageItem(item) + const text = extractTextFromMessageItem(item as unknown as Record) if (text) { items.push({ role: 'assistant', @@ -213,18 +224,20 @@ export function convertResponseOutputToInputItems(output: unknown): ResponsesInp }) } - const toolCalls = Array.isArray(item.tool_calls) ? item.tool_calls : [] + // Handle Chat Completions-style tool_calls nested under message items + const msgRecord = item as unknown as Record + const toolCalls = Array.isArray(msgRecord.tool_calls) ? msgRecord.tool_calls : [] for (const toolCall of toolCalls) { - const callId = toolCall?.id - const name = toolCall?.function?.name ?? toolCall?.name + const tc = toolCall as Record + const fn = tc.function as Record | undefined + const callId = tc.id as string | undefined + const name = (fn?.name ?? tc.name) as string | undefined if (!callId || !name) { continue } const argumentsValue = - typeof toolCall?.function?.arguments === 'string' - ? toolCall.function.arguments - : JSON.stringify(toolCall?.function?.arguments ?? {}) + typeof fn?.arguments === 'string' ? fn.arguments : JSON.stringify(fn?.arguments ?? {}) items.push({ type: 'function_call', @@ -238,14 +251,18 @@ export function convertResponseOutputToInputItems(output: unknown): ResponsesInp } if (item.type === 'function_call') { - const callId = item.call_id ?? item.id - const name = item.name ?? item.function?.name + const fc = item as OpenAI.Responses.ResponseFunctionToolCall + const fcRecord = item as unknown as Record + const callId = fc.call_id ?? (fcRecord.id as string | undefined) + const name = + fc.name ?? + ((fcRecord.function as Record | undefined)?.name as string | undefined) if (!callId || !name) { continue } const argumentsValue = - typeof item.arguments === 'string' ? item.arguments : JSON.stringify(item.arguments ?? {}) + typeof fc.arguments === 'string' ? fc.arguments : JSON.stringify(fc.arguments ?? {}) items.push({ type: 'function_call', @@ -262,7 +279,9 @@ export function convertResponseOutputToInputItems(output: unknown): ResponsesInp /** * Extracts tool calls from Responses API output items. */ -export function extractResponseToolCalls(output: unknown): ResponsesToolCall[] { +export function extractResponseToolCalls( + output: OpenAI.Responses.ResponseOutputItem[] +): ResponsesToolCall[] { if (!Array.isArray(output)) { return [] } @@ -275,14 +294,18 @@ export function extractResponseToolCalls(output: unknown): ResponsesToolCall[] { } if (item.type === 'function_call') { - const callId = item.call_id ?? item.id - const name = item.name ?? item.function?.name + const fc = item as OpenAI.Responses.ResponseFunctionToolCall + const fcRecord = item as unknown as Record + const callId = fc.call_id ?? (fcRecord.id as string | undefined) + const name = + fc.name ?? + ((fcRecord.function as Record | undefined)?.name as string | undefined) if (!callId || !name) { continue } const argumentsValue = - typeof item.arguments === 'string' ? item.arguments : JSON.stringify(item.arguments ?? {}) + typeof fc.arguments === 'string' ? fc.arguments : JSON.stringify(fc.arguments ?? {}) toolCalls.push({ id: callId, @@ -292,18 +315,20 @@ export function extractResponseToolCalls(output: unknown): ResponsesToolCall[] { continue } - if (item.type === 'message' && Array.isArray(item.tool_calls)) { - for (const toolCall of item.tool_calls) { - const callId = toolCall?.id - const name = toolCall?.function?.name ?? toolCall?.name + // Handle Chat Completions-style tool_calls nested under message items + const msgRecord = item as unknown as Record + if (item.type === 'message' && Array.isArray(msgRecord.tool_calls)) { + for (const toolCall of msgRecord.tool_calls) { + const tc = toolCall as Record + const fn = tc.function as Record | undefined + const callId = tc.id as string | undefined + const name = (fn?.name ?? tc.name) as string | undefined if (!callId || !name) { continue } const argumentsValue = - typeof toolCall?.function?.arguments === 'string' - ? toolCall.function.arguments - : JSON.stringify(toolCall?.function?.arguments ?? {}) + typeof fn?.arguments === 'string' ? fn.arguments : JSON.stringify(fn?.arguments ?? {}) toolCalls.push({ id: callId, @@ -323,15 +348,17 @@ export function extractResponseToolCalls(output: unknown): ResponsesToolCall[] { * Note: output_tokens is expected to include reasoning tokens; fall back to reasoning_tokens * when output_tokens is missing or zero. */ -export function parseResponsesUsage(usage: any): ResponsesUsageTokens | undefined { - if (!usage || typeof usage !== 'object') { +export function parseResponsesUsage( + usage: OpenAI.Responses.ResponseUsage | undefined +): ResponsesUsageTokens | undefined { + if (!usage) { return undefined } - const inputTokens = Number(usage.input_tokens ?? 0) - const outputTokens = Number(usage.output_tokens ?? 0) - const cachedTokens = Number(usage.input_tokens_details?.cached_tokens ?? 0) - const reasoningTokens = Number(usage.output_tokens_details?.reasoning_tokens ?? 0) + const inputTokens = usage.input_tokens ?? 0 + const outputTokens = usage.output_tokens ?? 0 + const cachedTokens = usage.input_tokens_details?.cached_tokens ?? 0 + const reasoningTokens = usage.output_tokens_details?.reasoning_tokens ?? 0 const completionTokens = Math.max(outputTokens, reasoningTokens) const totalTokens = inputTokens + completionTokens @@ -398,7 +425,7 @@ export function createReadableStreamFromResponses( continue } - let event: any + let event: Record try { event = JSON.parse(data) } catch (error) { @@ -416,7 +443,8 @@ export function createReadableStreamFromResponses( eventType === 'error' || eventType === 'response.failed' ) { - const message = event?.error?.message || 'Responses API stream error' + const errorObj = event.error as Record | undefined + const message = (errorObj?.message as string) || 'Responses API stream error' controller.error(new Error(message)) return } @@ -426,12 +454,13 @@ export function createReadableStreamFromResponses( eventType === 'response.output_json.delta' ) { let deltaText = '' - if (typeof event.delta === 'string') { - deltaText = event.delta - } else if (event.delta && typeof event.delta.text === 'string') { - deltaText = event.delta.text - } else if (event.delta && event.delta.json !== undefined) { - deltaText = JSON.stringify(event.delta.json) + const delta = event.delta as string | Record | undefined + if (typeof delta === 'string') { + deltaText = delta + } else if (delta && typeof delta.text === 'string') { + deltaText = delta.text + } else if (delta && delta.json !== undefined) { + deltaText = JSON.stringify(delta.json) } else if (event.json !== undefined) { deltaText = JSON.stringify(event.json) } else if (typeof event.text === 'string') { @@ -445,7 +474,11 @@ export function createReadableStreamFromResponses( } if (eventType === 'response.completed') { - finalUsage = parseResponsesUsage(event?.response?.usage ?? event?.usage) + const responseObj = event.response as Record | undefined + const usageData = (responseObj?.usage ?? event.usage) as + | OpenAI.Responses.ResponseUsage + | undefined + finalUsage = parseResponsesUsage(usageData) } } } diff --git a/apps/sim/providers/openrouter/index.ts b/apps/sim/providers/openrouter/index.ts index 57246c437..0444fc35e 100644 --- a/apps/sim/providers/openrouter/index.ts +++ b/apps/sim/providers/openrouter/index.ts @@ -431,19 +431,13 @@ export const openRouterProvider: ProviderConfig = { const accumulatedCost = calculateCost(requestedModel, tokens.input, tokens.output) const streamingParams: ChatCompletionCreateParamsStreaming & { provider?: any } = { - model: payload.model, + ...payload, messages: [...currentMessages], + tool_choice: 'auto', stream: true, stream_options: { include_usage: true }, } - if (payload.temperature !== undefined) { - streamingParams.temperature = payload.temperature - } - if (payload.max_tokens !== undefined) { - streamingParams.max_tokens = payload.max_tokens - } - if (request.responseFormat) { ;(streamingParams as any).messages = await applyResponseFormat( streamingParams as any, diff --git a/apps/sim/providers/utils.test.ts b/apps/sim/providers/utils.test.ts index 68575b875..e8fa79917 100644 --- a/apps/sim/providers/utils.test.ts +++ b/apps/sim/providers/utils.test.ts @@ -12,16 +12,22 @@ import { getApiKey, getBaseModelProviders, getHostedModels, + getMaxOutputTokensForModel, getMaxTemperature, + getModelPricing, getProvider, getProviderConfigFromModel, getProviderFromModel, getProviderModels, + getReasoningEffortValuesForModel, + getThinkingLevelsForModel, + getVerbosityValuesForModel, isProviderBlacklisted, MODELS_TEMP_RANGE_0_1, MODELS_TEMP_RANGE_0_2, MODELS_WITH_REASONING_EFFORT, MODELS_WITH_TEMPERATURE_SUPPORT, + MODELS_WITH_THINKING, MODELS_WITH_VERBOSITY, PROVIDERS_WITH_TOOL_USAGE_CONTROL, prepareToolExecution, @@ -169,6 +175,8 @@ describe('Model Capabilities', () => { 'gpt-4.1', 'gpt-4.1-mini', 'gpt-4.1-nano', + 'gpt-5-chat-latest', + 'azure/gpt-5-chat-latest', 'gemini-2.5-flash', 'claude-sonnet-4-0', 'claude-opus-4-0', @@ -186,34 +194,27 @@ describe('Model Capabilities', () => { it.concurrent('should return false for models that do not support temperature', () => { const unsupportedModels = [ 'unsupported-model', - 'cerebras/llama-3.3-70b', // Cerebras models don't have temperature defined - 'groq/meta-llama/llama-4-scout-17b-16e-instruct', // Groq models don't have temperature defined - // Reasoning models that don't support temperature + 'cerebras/llama-3.3-70b', + 'groq/meta-llama/llama-4-scout-17b-16e-instruct', 'o1', 'o3', 'o4-mini', 'azure/o3', 'azure/o4-mini', 'deepseek-r1', - // Chat models that don't support temperature 'deepseek-chat', - 'azure/gpt-4.1', 'azure/model-router', - // GPT-5.1 models don't support temperature (removed in our implementation) 'gpt-5.1', 'azure/gpt-5.1', 'azure/gpt-5.1-mini', 'azure/gpt-5.1-nano', 'azure/gpt-5.1-codex', - // GPT-5 models don't support temperature (removed in our implementation) 'gpt-5', 'gpt-5-mini', 'gpt-5-nano', - 'gpt-5-chat-latest', 'azure/gpt-5', 'azure/gpt-5-mini', 'azure/gpt-5-nano', - 'azure/gpt-5-chat-latest', ] for (const model of unsupportedModels) { @@ -240,6 +241,8 @@ describe('Model Capabilities', () => { const modelsRange02 = [ 'gpt-4o', 'azure/gpt-4o', + 'gpt-5-chat-latest', + 'azure/gpt-5-chat-latest', 'gemini-2.5-pro', 'gemini-2.5-flash', 'deepseek-v3', @@ -268,28 +271,23 @@ describe('Model Capabilities', () => { expect(getMaxTemperature('unsupported-model')).toBeUndefined() expect(getMaxTemperature('cerebras/llama-3.3-70b')).toBeUndefined() expect(getMaxTemperature('groq/meta-llama/llama-4-scout-17b-16e-instruct')).toBeUndefined() - // Reasoning models that don't support temperature expect(getMaxTemperature('o1')).toBeUndefined() expect(getMaxTemperature('o3')).toBeUndefined() expect(getMaxTemperature('o4-mini')).toBeUndefined() expect(getMaxTemperature('azure/o3')).toBeUndefined() expect(getMaxTemperature('azure/o4-mini')).toBeUndefined() expect(getMaxTemperature('deepseek-r1')).toBeUndefined() - // GPT-5.1 models don't support temperature expect(getMaxTemperature('gpt-5.1')).toBeUndefined() expect(getMaxTemperature('azure/gpt-5.1')).toBeUndefined() expect(getMaxTemperature('azure/gpt-5.1-mini')).toBeUndefined() expect(getMaxTemperature('azure/gpt-5.1-nano')).toBeUndefined() expect(getMaxTemperature('azure/gpt-5.1-codex')).toBeUndefined() - // GPT-5 models don't support temperature expect(getMaxTemperature('gpt-5')).toBeUndefined() expect(getMaxTemperature('gpt-5-mini')).toBeUndefined() expect(getMaxTemperature('gpt-5-nano')).toBeUndefined() - expect(getMaxTemperature('gpt-5-chat-latest')).toBeUndefined() expect(getMaxTemperature('azure/gpt-5')).toBeUndefined() expect(getMaxTemperature('azure/gpt-5-mini')).toBeUndefined() expect(getMaxTemperature('azure/gpt-5-nano')).toBeUndefined() - expect(getMaxTemperature('azure/gpt-5-chat-latest')).toBeUndefined() }) it.concurrent('should be case insensitive', () => { @@ -340,13 +338,13 @@ describe('Model Capabilities', () => { expect(MODELS_TEMP_RANGE_0_2).toContain('gpt-4o') expect(MODELS_TEMP_RANGE_0_2).toContain('gemini-2.5-flash') expect(MODELS_TEMP_RANGE_0_2).toContain('deepseek-v3') - expect(MODELS_TEMP_RANGE_0_2).not.toContain('claude-sonnet-4-0') // Should be in 0-1 range + expect(MODELS_TEMP_RANGE_0_2).not.toContain('claude-sonnet-4-0') }) it.concurrent('should have correct models in MODELS_TEMP_RANGE_0_1', () => { expect(MODELS_TEMP_RANGE_0_1).toContain('claude-sonnet-4-0') expect(MODELS_TEMP_RANGE_0_1).toContain('grok-3-latest') - expect(MODELS_TEMP_RANGE_0_1).not.toContain('gpt-4o') // Should be in 0-2 range + expect(MODELS_TEMP_RANGE_0_1).not.toContain('gpt-4o') }) it.concurrent('should have correct providers in PROVIDERS_WITH_TOOL_USAGE_CONTROL', () => { @@ -363,20 +361,19 @@ describe('Model Capabilities', () => { expect(MODELS_WITH_TEMPERATURE_SUPPORT.length).toBe( MODELS_TEMP_RANGE_0_2.length + MODELS_TEMP_RANGE_0_1.length ) - expect(MODELS_WITH_TEMPERATURE_SUPPORT).toContain('gpt-4o') // From 0-2 range - expect(MODELS_WITH_TEMPERATURE_SUPPORT).toContain('claude-sonnet-4-0') // From 0-1 range + expect(MODELS_WITH_TEMPERATURE_SUPPORT).toContain('gpt-4o') + expect(MODELS_WITH_TEMPERATURE_SUPPORT).toContain('claude-sonnet-4-0') } ) it.concurrent('should have correct models in MODELS_WITH_REASONING_EFFORT', () => { - // Should contain GPT-5.1 models that support reasoning effort expect(MODELS_WITH_REASONING_EFFORT).toContain('gpt-5.1') expect(MODELS_WITH_REASONING_EFFORT).toContain('azure/gpt-5.1') - expect(MODELS_WITH_REASONING_EFFORT).toContain('azure/gpt-5.1-mini') - expect(MODELS_WITH_REASONING_EFFORT).toContain('azure/gpt-5.1-nano') expect(MODELS_WITH_REASONING_EFFORT).toContain('azure/gpt-5.1-codex') - // Should contain GPT-5 models that support reasoning effort + expect(MODELS_WITH_REASONING_EFFORT).not.toContain('azure/gpt-5.1-mini') + expect(MODELS_WITH_REASONING_EFFORT).not.toContain('azure/gpt-5.1-nano') + expect(MODELS_WITH_REASONING_EFFORT).toContain('gpt-5') expect(MODELS_WITH_REASONING_EFFORT).toContain('gpt-5-mini') expect(MODELS_WITH_REASONING_EFFORT).toContain('gpt-5-nano') @@ -384,35 +381,30 @@ describe('Model Capabilities', () => { expect(MODELS_WITH_REASONING_EFFORT).toContain('azure/gpt-5-mini') expect(MODELS_WITH_REASONING_EFFORT).toContain('azure/gpt-5-nano') - // Should contain gpt-5.2 models expect(MODELS_WITH_REASONING_EFFORT).toContain('gpt-5.2') expect(MODELS_WITH_REASONING_EFFORT).toContain('azure/gpt-5.2') - // Should contain o-series reasoning models (reasoning_effort added Dec 17, 2024) expect(MODELS_WITH_REASONING_EFFORT).toContain('o1') expect(MODELS_WITH_REASONING_EFFORT).toContain('o3') expect(MODELS_WITH_REASONING_EFFORT).toContain('o4-mini') expect(MODELS_WITH_REASONING_EFFORT).toContain('azure/o3') expect(MODELS_WITH_REASONING_EFFORT).toContain('azure/o4-mini') - // Should NOT contain non-reasoning GPT-5 models expect(MODELS_WITH_REASONING_EFFORT).not.toContain('gpt-5-chat-latest') expect(MODELS_WITH_REASONING_EFFORT).not.toContain('azure/gpt-5-chat-latest') - // Should NOT contain other models expect(MODELS_WITH_REASONING_EFFORT).not.toContain('gpt-4o') expect(MODELS_WITH_REASONING_EFFORT).not.toContain('claude-sonnet-4-0') }) it.concurrent('should have correct models in MODELS_WITH_VERBOSITY', () => { - // Should contain GPT-5.1 models that support verbosity expect(MODELS_WITH_VERBOSITY).toContain('gpt-5.1') expect(MODELS_WITH_VERBOSITY).toContain('azure/gpt-5.1') - expect(MODELS_WITH_VERBOSITY).toContain('azure/gpt-5.1-mini') - expect(MODELS_WITH_VERBOSITY).toContain('azure/gpt-5.1-nano') expect(MODELS_WITH_VERBOSITY).toContain('azure/gpt-5.1-codex') - // Should contain GPT-5 models that support verbosity + expect(MODELS_WITH_VERBOSITY).not.toContain('azure/gpt-5.1-mini') + expect(MODELS_WITH_VERBOSITY).not.toContain('azure/gpt-5.1-nano') + expect(MODELS_WITH_VERBOSITY).toContain('gpt-5') expect(MODELS_WITH_VERBOSITY).toContain('gpt-5-mini') expect(MODELS_WITH_VERBOSITY).toContain('gpt-5-nano') @@ -420,26 +412,39 @@ describe('Model Capabilities', () => { expect(MODELS_WITH_VERBOSITY).toContain('azure/gpt-5-mini') expect(MODELS_WITH_VERBOSITY).toContain('azure/gpt-5-nano') - // Should contain gpt-5.2 models expect(MODELS_WITH_VERBOSITY).toContain('gpt-5.2') expect(MODELS_WITH_VERBOSITY).toContain('azure/gpt-5.2') - // Should NOT contain non-reasoning GPT-5 models expect(MODELS_WITH_VERBOSITY).not.toContain('gpt-5-chat-latest') expect(MODELS_WITH_VERBOSITY).not.toContain('azure/gpt-5-chat-latest') - // Should NOT contain o-series models (they support reasoning_effort but not verbosity) expect(MODELS_WITH_VERBOSITY).not.toContain('o1') expect(MODELS_WITH_VERBOSITY).not.toContain('o3') expect(MODELS_WITH_VERBOSITY).not.toContain('o4-mini') - // Should NOT contain other models expect(MODELS_WITH_VERBOSITY).not.toContain('gpt-4o') expect(MODELS_WITH_VERBOSITY).not.toContain('claude-sonnet-4-0') }) + it.concurrent('should have correct models in MODELS_WITH_THINKING', () => { + expect(MODELS_WITH_THINKING).toContain('claude-opus-4-6') + expect(MODELS_WITH_THINKING).toContain('claude-opus-4-5') + expect(MODELS_WITH_THINKING).toContain('claude-opus-4-1') + expect(MODELS_WITH_THINKING).toContain('claude-opus-4-0') + expect(MODELS_WITH_THINKING).toContain('claude-sonnet-4-5') + expect(MODELS_WITH_THINKING).toContain('claude-sonnet-4-0') + + expect(MODELS_WITH_THINKING).toContain('gemini-3-pro-preview') + expect(MODELS_WITH_THINKING).toContain('gemini-3-flash-preview') + + expect(MODELS_WITH_THINKING).toContain('claude-haiku-4-5') + + expect(MODELS_WITH_THINKING).not.toContain('gpt-4o') + expect(MODELS_WITH_THINKING).not.toContain('gpt-5') + expect(MODELS_WITH_THINKING).not.toContain('o3') + }) + it.concurrent('should have GPT-5 models in both reasoning effort and verbosity arrays', () => { - // GPT-5 series models support both reasoning effort and verbosity const gpt5ModelsWithReasoningEffort = MODELS_WITH_REASONING_EFFORT.filter( (m) => m.includes('gpt-5') && !m.includes('chat-latest') ) @@ -448,11 +453,201 @@ describe('Model Capabilities', () => { ) expect(gpt5ModelsWithReasoningEffort.sort()).toEqual(gpt5ModelsWithVerbosity.sort()) - // o-series models have reasoning effort but NOT verbosity expect(MODELS_WITH_REASONING_EFFORT).toContain('o1') expect(MODELS_WITH_VERBOSITY).not.toContain('o1') }) }) + describe('Reasoning Effort Values Per Model', () => { + it.concurrent('should return correct values for GPT-5.2', () => { + const values = getReasoningEffortValuesForModel('gpt-5.2') + expect(values).toBeDefined() + expect(values).toContain('none') + expect(values).toContain('low') + expect(values).toContain('medium') + expect(values).toContain('high') + expect(values).toContain('xhigh') + expect(values).not.toContain('minimal') + }) + + it.concurrent('should return correct values for GPT-5', () => { + const values = getReasoningEffortValuesForModel('gpt-5') + expect(values).toBeDefined() + expect(values).toContain('minimal') + expect(values).toContain('low') + expect(values).toContain('medium') + expect(values).toContain('high') + }) + + it.concurrent('should return correct values for o-series models', () => { + for (const model of ['o1', 'o3', 'o4-mini']) { + const values = getReasoningEffortValuesForModel(model) + expect(values).toBeDefined() + expect(values).toContain('low') + expect(values).toContain('medium') + expect(values).toContain('high') + expect(values).not.toContain('none') + expect(values).not.toContain('minimal') + } + }) + + it.concurrent('should return null for non-reasoning models', () => { + expect(getReasoningEffortValuesForModel('gpt-4o')).toBeNull() + expect(getReasoningEffortValuesForModel('claude-sonnet-4-5')).toBeNull() + expect(getReasoningEffortValuesForModel('gemini-2.5-flash')).toBeNull() + }) + + it.concurrent('should return correct values for Azure GPT-5.2', () => { + const values = getReasoningEffortValuesForModel('azure/gpt-5.2') + expect(values).toBeDefined() + expect(values).not.toContain('minimal') + expect(values).toContain('xhigh') + }) + }) + + describe('Verbosity Values Per Model', () => { + it.concurrent('should return correct values for GPT-5 family', () => { + for (const model of ['gpt-5.2', 'gpt-5.1', 'gpt-5', 'gpt-5-mini', 'gpt-5-nano']) { + const values = getVerbosityValuesForModel(model) + expect(values).toBeDefined() + expect(values).toContain('low') + expect(values).toContain('medium') + expect(values).toContain('high') + } + }) + + it.concurrent('should return null for o-series models', () => { + expect(getVerbosityValuesForModel('o1')).toBeNull() + expect(getVerbosityValuesForModel('o3')).toBeNull() + expect(getVerbosityValuesForModel('o4-mini')).toBeNull() + }) + + it.concurrent('should return null for non-reasoning models', () => { + expect(getVerbosityValuesForModel('gpt-4o')).toBeNull() + expect(getVerbosityValuesForModel('claude-sonnet-4-5')).toBeNull() + }) + }) + + describe('Thinking Levels Per Model', () => { + it.concurrent('should return correct levels for Claude Opus 4.6 (adaptive)', () => { + const levels = getThinkingLevelsForModel('claude-opus-4-6') + expect(levels).toBeDefined() + expect(levels).toContain('low') + expect(levels).toContain('medium') + expect(levels).toContain('high') + expect(levels).toContain('max') + }) + + it.concurrent('should return correct levels for other Claude models (budget_tokens)', () => { + for (const model of ['claude-opus-4-5', 'claude-sonnet-4-5', 'claude-sonnet-4-0']) { + const levels = getThinkingLevelsForModel(model) + expect(levels).toBeDefined() + expect(levels).toContain('low') + expect(levels).toContain('medium') + expect(levels).toContain('high') + expect(levels).not.toContain('max') + } + }) + + it.concurrent('should return correct levels for Gemini 3 models', () => { + const proLevels = getThinkingLevelsForModel('gemini-3-pro-preview') + expect(proLevels).toBeDefined() + expect(proLevels).toContain('low') + expect(proLevels).toContain('high') + + const flashLevels = getThinkingLevelsForModel('gemini-3-flash-preview') + expect(flashLevels).toBeDefined() + expect(flashLevels).toContain('minimal') + expect(flashLevels).toContain('low') + expect(flashLevels).toContain('medium') + expect(flashLevels).toContain('high') + }) + + it.concurrent('should return correct levels for Claude Haiku 4.5', () => { + const levels = getThinkingLevelsForModel('claude-haiku-4-5') + expect(levels).toBeDefined() + expect(levels).toContain('low') + expect(levels).toContain('medium') + expect(levels).toContain('high') + }) + + it.concurrent('should return null for non-thinking models', () => { + expect(getThinkingLevelsForModel('gpt-4o')).toBeNull() + expect(getThinkingLevelsForModel('gpt-5')).toBeNull() + expect(getThinkingLevelsForModel('o3')).toBeNull() + }) + }) +}) + +describe('Max Output Tokens', () => { + describe('getMaxOutputTokensForModel', () => { + it.concurrent('should return correct max for Claude Opus 4.6', () => { + expect(getMaxOutputTokensForModel('claude-opus-4-6')).toBe(128000) + }) + + it.concurrent('should return correct max for Claude Sonnet 4.5', () => { + expect(getMaxOutputTokensForModel('claude-sonnet-4-5')).toBe(64000) + }) + + it.concurrent('should return correct max for Claude Opus 4.1', () => { + expect(getMaxOutputTokensForModel('claude-opus-4-1')).toBe(64000) + }) + + it.concurrent('should return standard default for models without maxOutputTokens', () => { + expect(getMaxOutputTokensForModel('gpt-4o')).toBe(4096) + }) + + it.concurrent('should return standard default for unknown models', () => { + expect(getMaxOutputTokensForModel('unknown-model')).toBe(4096) + }) + }) +}) + +describe('Model Pricing Validation', () => { + it.concurrent('should have correct pricing for key Anthropic models', () => { + const opus46 = getModelPricing('claude-opus-4-6') + expect(opus46).toBeDefined() + expect(opus46.input).toBe(5.0) + expect(opus46.output).toBe(25.0) + + const sonnet45 = getModelPricing('claude-sonnet-4-5') + expect(sonnet45).toBeDefined() + expect(sonnet45.input).toBe(3.0) + expect(sonnet45.output).toBe(15.0) + }) + + it.concurrent('should have correct pricing for key OpenAI models', () => { + const gpt4o = getModelPricing('gpt-4o') + expect(gpt4o).toBeDefined() + expect(gpt4o.input).toBe(2.5) + expect(gpt4o.output).toBe(10.0) + + const o3 = getModelPricing('o3') + expect(o3).toBeDefined() + expect(o3.input).toBe(2.0) + expect(o3.output).toBe(8.0) + }) + + it.concurrent('should have correct pricing for Azure OpenAI o3', () => { + const azureO3 = getModelPricing('azure/o3') + expect(azureO3).toBeDefined() + expect(azureO3.input).toBe(2.0) + expect(azureO3.output).toBe(8.0) + }) + + it.concurrent('should return null for unknown models', () => { + expect(getModelPricing('unknown-model')).toBeNull() + }) +}) + +describe('Context Window Validation', () => { + it.concurrent('should have correct context windows for key models', () => { + const allModels = getAllModels() + + expect(allModels).toContain('gpt-5-chat-latest') + + expect(allModels).toContain('o3') + expect(allModels).toContain('o4-mini') + }) }) describe('Cost Calculation', () => { @@ -464,7 +659,7 @@ describe('Cost Calculation', () => { expect(result.output).toBeGreaterThan(0) expect(result.total).toBeCloseTo(result.input + result.output, 6) expect(result.pricing).toBeDefined() - expect(result.pricing.input).toBe(2.5) // GPT-4o pricing + expect(result.pricing.input).toBe(2.5) }) it.concurrent('should handle cached input pricing when enabled', () => { @@ -472,7 +667,7 @@ describe('Cost Calculation', () => { const cachedCost = calculateCost('gpt-4o', 1000, 500, true) expect(cachedCost.input).toBeLessThan(regularCost.input) - expect(cachedCost.output).toBe(regularCost.output) // Output cost should be same + expect(cachedCost.output).toBe(regularCost.output) }) it.concurrent('should return default pricing for unknown models', () => { @@ -481,7 +676,7 @@ describe('Cost Calculation', () => { expect(result.input).toBe(0) expect(result.output).toBe(0) expect(result.total).toBe(0) - expect(result.pricing.input).toBe(1.0) // Default pricing + expect(result.pricing.input).toBe(1.0) }) it.concurrent('should handle zero tokens', () => { @@ -528,19 +723,15 @@ describe('getHostedModels', () => { it.concurrent('should return OpenAI, Anthropic, and Google models as hosted', () => { const hostedModels = getHostedModels() - // OpenAI models expect(hostedModels).toContain('gpt-4o') expect(hostedModels).toContain('o1') - // Anthropic models expect(hostedModels).toContain('claude-sonnet-4-0') expect(hostedModels).toContain('claude-opus-4-0') - // Google models expect(hostedModels).toContain('gemini-2.5-pro') expect(hostedModels).toContain('gemini-2.5-flash') - // Should not contain models from other providers expect(hostedModels).not.toContain('deepseek-v3') expect(hostedModels).not.toContain('grok-4-latest') }) @@ -558,31 +749,24 @@ describe('getHostedModels', () => { describe('shouldBillModelUsage', () => { it.concurrent('should return true for exact matches of hosted models', () => { - // OpenAI models expect(shouldBillModelUsage('gpt-4o')).toBe(true) expect(shouldBillModelUsage('o1')).toBe(true) - // Anthropic models expect(shouldBillModelUsage('claude-sonnet-4-0')).toBe(true) expect(shouldBillModelUsage('claude-opus-4-0')).toBe(true) - // Google models expect(shouldBillModelUsage('gemini-2.5-pro')).toBe(true) expect(shouldBillModelUsage('gemini-2.5-flash')).toBe(true) }) it.concurrent('should return false for non-hosted models', () => { - // Other providers expect(shouldBillModelUsage('deepseek-v3')).toBe(false) expect(shouldBillModelUsage('grok-4-latest')).toBe(false) - // Unknown models expect(shouldBillModelUsage('unknown-model')).toBe(false) }) it.concurrent('should return false for versioned model names not in hosted list', () => { - // Versioned model names that are NOT in the hosted list - // These should NOT be billed (user provides own API key) expect(shouldBillModelUsage('claude-sonnet-4-20250514')).toBe(false) expect(shouldBillModelUsage('gpt-4o-2024-08-06')).toBe(false) expect(shouldBillModelUsage('claude-3-5-sonnet-20241022')).toBe(false) @@ -595,8 +779,7 @@ describe('shouldBillModelUsage', () => { }) it.concurrent('should not match partial model names', () => { - // Should not match partial/prefix models - expect(shouldBillModelUsage('gpt-4')).toBe(false) // gpt-4o is hosted, not gpt-4 + expect(shouldBillModelUsage('gpt-4')).toBe(false) expect(shouldBillModelUsage('claude-sonnet')).toBe(false) expect(shouldBillModelUsage('gemini')).toBe(false) }) @@ -612,8 +795,8 @@ describe('Provider Management', () => { }) it.concurrent('should use model patterns for pattern matching', () => { - expect(getProviderFromModel('gpt-5-custom')).toBe('openai') // Matches /^gpt/ pattern - expect(getProviderFromModel('claude-custom-model')).toBe('anthropic') // Matches /^claude/ pattern + expect(getProviderFromModel('gpt-5-custom')).toBe('openai') + expect(getProviderFromModel('claude-custom-model')).toBe('anthropic') }) it.concurrent('should default to ollama for unknown models', () => { @@ -667,7 +850,6 @@ describe('Provider Management', () => { expect(Array.isArray(allModels)).toBe(true) expect(allModels.length).toBeGreaterThan(0) - // Should contain models from different providers expect(allModels).toContain('gpt-4o') expect(allModels).toContain('claude-sonnet-4-0') expect(allModels).toContain('gemini-2.5-pro') @@ -712,7 +894,6 @@ describe('Provider Management', () => { const baseProviders = getBaseModelProviders() expect(typeof baseProviders).toBe('object') - // Should exclude ollama models }) }) @@ -720,10 +901,8 @@ describe('Provider Management', () => { it.concurrent('should update ollama models', () => { const mockModels = ['llama2', 'codellama', 'mistral'] - // This should not throw expect(() => updateOllamaProviderModels(mockModels)).not.toThrow() - // Verify the models were updated const ollamaModels = getProviderModels('ollama') expect(ollamaModels).toEqual(mockModels) }) @@ -754,7 +933,7 @@ describe('JSON and Structured Output', () => { }) it.concurrent('should clean up common JSON issues', () => { - const content = '{\n "key": "value",\n "number": 42,\n}' // Trailing comma + const content = '{\n "key": "value",\n "number": 42,\n}' const result = extractAndParseJSON(content) expect(result).toEqual({ key: 'value', number: 42 }) }) @@ -945,13 +1124,13 @@ describe('prepareToolExecution', () => { const { toolParams } = prepareToolExecution(tool, llmArgs, request) expect(toolParams.apiKey).toBe('user-key') - expect(toolParams.channel).toBe('#general') // User value wins + expect(toolParams.channel).toBe('#general') expect(toolParams.message).toBe('Hello world') }) it.concurrent('should filter out empty string user params', () => { const tool = { - params: { apiKey: 'user-key', channel: '' }, // Empty channel + params: { apiKey: 'user-key', channel: '' }, } const llmArgs = { message: 'Hello', channel: '#llm-channel' } const request = {} @@ -959,7 +1138,7 @@ describe('prepareToolExecution', () => { const { toolParams } = prepareToolExecution(tool, llmArgs, request) expect(toolParams.apiKey).toBe('user-key') - expect(toolParams.channel).toBe('#llm-channel') // LLM value used since user is empty + expect(toolParams.channel).toBe('#llm-channel') expect(toolParams.message).toBe('Hello') }) }) @@ -969,7 +1148,7 @@ describe('prepareToolExecution', () => { const tool = { params: { workflowId: 'child-workflow-123', - inputMapping: '{}', // Empty JSON string from UI + inputMapping: '{}', }, } const llmArgs = { @@ -979,7 +1158,6 @@ describe('prepareToolExecution', () => { const { toolParams } = prepareToolExecution(tool, llmArgs, request) - // LLM values should be used since user object is empty expect(toolParams.inputMapping).toEqual({ query: 'search term', limit: 10 }) expect(toolParams.workflowId).toBe('child-workflow-123') }) @@ -988,7 +1166,7 @@ describe('prepareToolExecution', () => { const tool = { params: { workflowId: 'child-workflow', - inputMapping: '{"query": "", "customField": "user-value"}', // Partial values + inputMapping: '{"query": "", "customField": "user-value"}', }, } const llmArgs = { @@ -998,7 +1176,6 @@ describe('prepareToolExecution', () => { const { toolParams } = prepareToolExecution(tool, llmArgs, request) - // LLM fills empty query, user's customField preserved, LLM's limit included expect(toolParams.inputMapping).toEqual({ query: 'llm-search', limit: 10, @@ -1020,7 +1197,6 @@ describe('prepareToolExecution', () => { const { toolParams } = prepareToolExecution(tool, llmArgs, request) - // User values win, but LLM's extra field is included expect(toolParams.inputMapping).toEqual({ query: 'user-search', limit: 5, @@ -1032,7 +1208,7 @@ describe('prepareToolExecution', () => { const tool = { params: { workflowId: 'child-workflow', - inputMapping: { query: '', customField: 'user-value' }, // Object, not string + inputMapping: { query: '', customField: 'user-value' }, }, } const llmArgs = { @@ -1051,7 +1227,7 @@ describe('prepareToolExecution', () => { it.concurrent('should use LLM inputMapping when user does not provide it', () => { const tool = { - params: { workflowId: 'child-workflow' }, // No inputMapping + params: { workflowId: 'child-workflow' }, } const llmArgs = { inputMapping: { query: 'llm-search', limit: 10 }, @@ -1070,7 +1246,7 @@ describe('prepareToolExecution', () => { inputMapping: '{"query": "user-search"}', }, } - const llmArgs = {} // No inputMapping from LLM + const llmArgs = {} const request = {} const { toolParams } = prepareToolExecution(tool, llmArgs, request) @@ -1092,7 +1268,6 @@ describe('prepareToolExecution', () => { const { toolParams } = prepareToolExecution(tool, llmArgs, request) - // Should use LLM values since user JSON is invalid expect(toolParams.inputMapping).toEqual({ query: 'llm-search' }) }) @@ -1105,9 +1280,8 @@ describe('prepareToolExecution', () => { const { toolParams } = prepareToolExecution(tool, llmArgs, request) - // Normal behavior: user values override LLM values expect(toolParams.apiKey).toBe('user-key') - expect(toolParams.channel).toBe('#general') // User value wins + expect(toolParams.channel).toBe('#general') expect(toolParams.message).toBe('Hello') }) @@ -1125,8 +1299,6 @@ describe('prepareToolExecution', () => { const { toolParams } = prepareToolExecution(tool, llmArgs, request) - // 0 and false should be preserved (they're valid values) - // empty string should be filled by LLM expect(toolParams.inputMapping).toEqual({ limit: 0, enabled: false, diff --git a/apps/sim/providers/utils.ts b/apps/sim/providers/utils.ts index 50bcec5c6..5b6481cbe 100644 --- a/apps/sim/providers/utils.ts +++ b/apps/sim/providers/utils.ts @@ -1,4 +1,5 @@ import { createLogger, type Logger } from '@sim/logger' +import type OpenAI from 'openai' import type { ChatCompletionChunk } from 'openai/resources/chat/completions' import type { CompletionUsage } from 'openai/resources/completions' import { env } from '@/lib/core/config/env' @@ -995,15 +996,12 @@ export function getThinkingLevelsForModel(model: string): string[] | null { } /** - * Get max output tokens for a specific model - * Returns the model's maxOutputTokens capability for streaming requests, - * or a conservative default (8192) for non-streaming requests to avoid timeout issues. + * Get max output tokens for a specific model. * * @param model - The model ID - * @param streaming - Whether the request is streaming (default: false) */ -export function getMaxOutputTokensForModel(model: string, streaming = false): number { - return getMaxOutputTokensForModelFromDefinitions(model, streaming) +export function getMaxOutputTokensForModel(model: string): number { + return getMaxOutputTokensForModelFromDefinitions(model) } /** @@ -1126,8 +1124,8 @@ export function createOpenAICompatibleStream( * @returns Object with hasUsedForcedTool flag and updated usedForcedTools array */ export function checkForForcedToolUsageOpenAI( - response: any, - toolChoice: string | { type: string; function?: { name: string }; name?: string; any?: any }, + response: OpenAI.Chat.Completions.ChatCompletion, + toolChoice: string | { type: string; function?: { name: string }; name?: string }, providerName: string, forcedTools: string[], usedForcedTools: string[], diff --git a/apps/sim/serializer/index.ts b/apps/sim/serializer/index.ts index 622667d9f..66f4568a4 100644 --- a/apps/sim/serializer/index.ts +++ b/apps/sim/serializer/index.ts @@ -70,6 +70,7 @@ function shouldSerializeSubBlock( : group.basicId === subBlockConfig.id return matchesMode && evaluateSubBlockCondition(subBlockConfig.condition, values) } + console.log('[FUCK] subBlockConfig.condition', subBlockConfig.condition, values) return evaluateSubBlockCondition(subBlockConfig.condition, values) } From 7b36f9257ef06c0327c5e102156b0cea1db9cd1c Mon Sep 17 00:00:00 2001 From: Waleed Date: Sat, 7 Feb 2026 12:05:10 -0800 Subject: [PATCH 7/8] improvement(models): reorder models dropdown (#3164) --- apps/sim/providers/utils.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/apps/sim/providers/utils.ts b/apps/sim/providers/utils.ts index 5b6481cbe..5d49dc53d 100644 --- a/apps/sim/providers/utils.ts +++ b/apps/sim/providers/utils.ts @@ -114,6 +114,8 @@ function buildProviderMetadata(providerId: ProviderId): ProviderMetadata { } export const providers: Record = { + ollama: buildProviderMetadata('ollama'), + vllm: buildProviderMetadata('vllm'), openai: { ...buildProviderMetadata('openai'), computerUseModels: ['computer-use-preview'], @@ -124,19 +126,17 @@ export const providers: Record = { getProviderModelsFromDefinitions('anthropic').includes(model) ), }, - 'azure-anthropic': buildProviderMetadata('azure-anthropic'), google: buildProviderMetadata('google'), vertex: buildProviderMetadata('vertex'), + 'azure-openai': buildProviderMetadata('azure-openai'), + 'azure-anthropic': buildProviderMetadata('azure-anthropic'), deepseek: buildProviderMetadata('deepseek'), xai: buildProviderMetadata('xai'), cerebras: buildProviderMetadata('cerebras'), groq: buildProviderMetadata('groq'), - vllm: buildProviderMetadata('vllm'), mistral: buildProviderMetadata('mistral'), - 'azure-openai': buildProviderMetadata('azure-openai'), - openrouter: buildProviderMetadata('openrouter'), - ollama: buildProviderMetadata('ollama'), bedrock: buildProviderMetadata('bedrock'), + openrouter: buildProviderMetadata('openrouter'), } export function updateOllamaProviderModels(models: string[]): void { From 0cb671449658e0e9a62e49ae3d4512ebd12f27fa Mon Sep 17 00:00:00 2001 From: Vikhyath Mondreti Date: Sat, 7 Feb 2026 12:18:07 -0800 Subject: [PATCH 8/8] fix(rooms): cleanup edge case for 1hr ttl (#3163) * fix(rooms): cleanup edge case for 1hr ttl * revert feature flags * address comments * remove console log --- apps/sim/serializer/index.ts | 1 - apps/sim/socket/handlers/connection.ts | 3 +- apps/sim/socket/handlers/workflow.ts | 70 +++++++++++++++++++------ apps/sim/socket/rooms/memory-manager.ts | 2 +- apps/sim/socket/rooms/redis-manager.ts | 52 ++++++++++++++---- apps/sim/socket/rooms/types.ts | 5 +- 6 files changed, 104 insertions(+), 29 deletions(-) diff --git a/apps/sim/serializer/index.ts b/apps/sim/serializer/index.ts index 66f4568a4..622667d9f 100644 --- a/apps/sim/serializer/index.ts +++ b/apps/sim/serializer/index.ts @@ -70,7 +70,6 @@ function shouldSerializeSubBlock( : group.basicId === subBlockConfig.id return matchesMode && evaluateSubBlockCondition(subBlockConfig.condition, values) } - console.log('[FUCK] subBlockConfig.condition', subBlockConfig.condition, values) return evaluateSubBlockCondition(subBlockConfig.condition, values) } diff --git a/apps/sim/socket/handlers/connection.ts b/apps/sim/socket/handlers/connection.ts index 5444c9a83..ee7a9a774 100644 --- a/apps/sim/socket/handlers/connection.ts +++ b/apps/sim/socket/handlers/connection.ts @@ -21,7 +21,8 @@ export function setupConnectionHandlers(socket: AuthenticatedSocket, roomManager cleanupPendingSubblocksForSocket(socket.id) cleanupPendingVariablesForSocket(socket.id) - const workflowId = await roomManager.removeUserFromRoom(socket.id) + const workflowIdHint = [...socket.rooms].find((roomId) => roomId !== socket.id) + const workflowId = await roomManager.removeUserFromRoom(socket.id, workflowIdHint) if (workflowId) { await roomManager.broadcastPresenceUpdate(workflowId) diff --git a/apps/sim/socket/handlers/workflow.ts b/apps/sim/socket/handlers/workflow.ts index c59316d1e..8353f0a38 100644 --- a/apps/sim/socket/handlers/workflow.ts +++ b/apps/sim/socket/handlers/workflow.ts @@ -51,26 +51,66 @@ export function setupWorkflowHandlers(socket: AuthenticatedSocket, roomManager: const currentWorkflowId = await roomManager.getWorkflowIdForSocket(socket.id) if (currentWorkflowId) { socket.leave(currentWorkflowId) - await roomManager.removeUserFromRoom(socket.id) + await roomManager.removeUserFromRoom(socket.id, currentWorkflowId) await roomManager.broadcastPresenceUpdate(currentWorkflowId) } - const STALE_THRESHOLD_MS = 60_000 + // Keep this above Redis socket key TTL (1h) so a normal idle user is not evicted too aggressively. + const STALE_THRESHOLD_MS = 75 * 60 * 1000 const now = Date.now() const existingUsers = await roomManager.getWorkflowUsers(workflowId) - for (const existingUser of existingUsers) { - if (existingUser.userId === userId && existingUser.socketId !== socket.id) { - const isSameTab = tabSessionId && existingUser.tabSessionId === tabSessionId - const isStale = - now - (existingUser.lastActivity || existingUser.joinedAt || 0) > STALE_THRESHOLD_MS + let liveSocketIds = new Set() + let canCheckLiveness = false - if (isSameTab || isStale) { - logger.info( - `Cleaning up socket ${existingUser.socketId} for user ${userId} (${isSameTab ? 'same tab' : 'stale'})` - ) - await roomManager.removeUserFromRoom(existingUser.socketId) - roomManager.io.in(existingUser.socketId).socketsLeave(workflowId) + try { + const liveSockets = await roomManager.io.in(workflowId).fetchSockets() + liveSocketIds = new Set(liveSockets.map((liveSocket) => liveSocket.id)) + canCheckLiveness = true + } catch (error) { + logger.warn( + `Skipping stale cleanup for ${workflowId} due to live socket lookup failure`, + error + ) + } + + for (const existingUser of existingUsers) { + try { + if (existingUser.socketId === socket.id) { + continue } + + const isSameTab = Boolean( + existingUser.userId === userId && + tabSessionId && + existingUser.tabSessionId === tabSessionId + ) + + if (isSameTab) { + logger.info( + `Cleaning up socket ${existingUser.socketId} for user ${existingUser.userId} (same tab)` + ) + await roomManager.removeUserFromRoom(existingUser.socketId, workflowId) + await roomManager.io.in(existingUser.socketId).socketsLeave(workflowId) + continue + } + + if (!canCheckLiveness || liveSocketIds.has(existingUser.socketId)) { + continue + } + + const isStaleByActivity = + now - (existingUser.lastActivity || existingUser.joinedAt || 0) > STALE_THRESHOLD_MS + if (!isStaleByActivity) { + continue + } + + logger.info( + `Cleaning up socket ${existingUser.socketId} for user ${existingUser.userId} (stale activity)` + ) + await roomManager.removeUserFromRoom(existingUser.socketId, workflowId) + await roomManager.io.in(existingUser.socketId).socketsLeave(workflowId) + } catch (error) { + logger.warn(`Best-effort cleanup failed for socket ${existingUser.socketId}`, error) } } @@ -136,7 +176,7 @@ export function setupWorkflowHandlers(socket: AuthenticatedSocket, roomManager: logger.error('Error joining workflow:', error) // Undo socket.join and room manager entry if any operation failed socket.leave(workflowId) - await roomManager.removeUserFromRoom(socket.id) + await roomManager.removeUserFromRoom(socket.id, workflowId) const isReady = roomManager.isReady() socket.emit('join-workflow-error', { error: isReady ? 'Failed to join workflow' : 'Realtime unavailable', @@ -156,7 +196,7 @@ export function setupWorkflowHandlers(socket: AuthenticatedSocket, roomManager: if (workflowId && session) { socket.leave(workflowId) - await roomManager.removeUserFromRoom(socket.id) + await roomManager.removeUserFromRoom(socket.id, workflowId) await roomManager.broadcastPresenceUpdate(workflowId) logger.info(`User ${session.userId} (${session.userName}) left workflow ${workflowId}`) diff --git a/apps/sim/socket/rooms/memory-manager.ts b/apps/sim/socket/rooms/memory-manager.ts index 908ee13f7..fa631ff68 100644 --- a/apps/sim/socket/rooms/memory-manager.ts +++ b/apps/sim/socket/rooms/memory-manager.ts @@ -66,7 +66,7 @@ export class MemoryRoomManager implements IRoomManager { logger.debug(`Added user ${presence.userId} to workflow ${workflowId} (socket: ${socketId})`) } - async removeUserFromRoom(socketId: string): Promise { + async removeUserFromRoom(socketId: string, _workflowIdHint?: string): Promise { const workflowId = this.socketToWorkflow.get(socketId) if (!workflowId) { diff --git a/apps/sim/socket/rooms/redis-manager.ts b/apps/sim/socket/rooms/redis-manager.ts index 9288a4762..fb0d0d104 100644 --- a/apps/sim/socket/rooms/redis-manager.ts +++ b/apps/sim/socket/rooms/redis-manager.ts @@ -10,9 +10,11 @@ const KEYS = { workflowMeta: (wfId: string) => `workflow:${wfId}:meta`, socketWorkflow: (socketId: string) => `socket:${socketId}:workflow`, socketSession: (socketId: string) => `socket:${socketId}:session`, + socketPresenceWorkflow: (socketId: string) => `socket:${socketId}:presence-workflow`, } as const const SOCKET_KEY_TTL = 3600 +const SOCKET_PRESENCE_WORKFLOW_KEY_TTL = 24 * 60 * 60 /** * Lua script for atomic user removal from room. @@ -22,11 +24,21 @@ const SOCKET_KEY_TTL = 3600 const REMOVE_USER_SCRIPT = ` local socketWorkflowKey = KEYS[1] local socketSessionKey = KEYS[2] +local socketPresenceWorkflowKey = KEYS[3] local workflowUsersPrefix = ARGV[1] local workflowMetaPrefix = ARGV[2] local socketId = ARGV[3] +local workflowIdHint = ARGV[4] local workflowId = redis.call('GET', socketWorkflowKey) +if not workflowId then + workflowId = redis.call('GET', socketPresenceWorkflowKey) +end + +if not workflowId and workflowIdHint ~= '' then + workflowId = workflowIdHint +end + if not workflowId then return nil end @@ -35,7 +47,7 @@ local workflowUsersKey = workflowUsersPrefix .. workflowId .. ':users' local workflowMetaKey = workflowMetaPrefix .. workflowId .. ':meta' redis.call('HDEL', workflowUsersKey, socketId) -redis.call('DEL', socketWorkflowKey, socketSessionKey) +redis.call('DEL', socketWorkflowKey, socketSessionKey, socketPresenceWorkflowKey) local remaining = redis.call('HLEN', workflowUsersKey) if remaining == 0 then @@ -54,11 +66,13 @@ const UPDATE_ACTIVITY_SCRIPT = ` local workflowUsersKey = KEYS[1] local socketWorkflowKey = KEYS[2] local socketSessionKey = KEYS[3] +local socketPresenceWorkflowKey = KEYS[4] local socketId = ARGV[1] local cursorJson = ARGV[2] local selectionJson = ARGV[3] local lastActivity = ARGV[4] local ttl = tonumber(ARGV[5]) +local presenceWorkflowTtl = tonumber(ARGV[6]) local existingJson = redis.call('HGET', workflowUsersKey, socketId) if not existingJson then @@ -78,6 +92,7 @@ existing.lastActivity = tonumber(lastActivity) redis.call('HSET', workflowUsersKey, socketId, cjson.encode(existing)) redis.call('EXPIRE', socketWorkflowKey, ttl) redis.call('EXPIRE', socketSessionKey, ttl) +redis.call('EXPIRE', socketPresenceWorkflowKey, presenceWorkflowTtl) return 1 ` @@ -164,6 +179,8 @@ export class RedisRoomManager implements IRoomManager { pipeline.hSet(KEYS.workflowMeta(workflowId), 'lastModified', Date.now().toString()) pipeline.set(KEYS.socketWorkflow(socketId), workflowId) pipeline.expire(KEYS.socketWorkflow(socketId), SOCKET_KEY_TTL) + pipeline.set(KEYS.socketPresenceWorkflow(socketId), workflowId) + pipeline.expire(KEYS.socketPresenceWorkflow(socketId), SOCKET_PRESENCE_WORKFLOW_KEY_TTL) pipeline.hSet(KEYS.socketSession(socketId), { userId: presence.userId, userName: presence.userName, @@ -187,7 +204,11 @@ export class RedisRoomManager implements IRoomManager { } } - async removeUserFromRoom(socketId: string, retried = false): Promise { + async removeUserFromRoom( + socketId: string, + workflowIdHint?: string, + retried = false + ): Promise { if (!this.removeUserScriptSha) { logger.error('removeUserFromRoom called before initialize()') return null @@ -195,19 +216,25 @@ export class RedisRoomManager implements IRoomManager { try { const workflowId = await this.redis.evalSha(this.removeUserScriptSha, { - keys: [KEYS.socketWorkflow(socketId), KEYS.socketSession(socketId)], - arguments: ['workflow:', 'workflow:', socketId], + keys: [ + KEYS.socketWorkflow(socketId), + KEYS.socketSession(socketId), + KEYS.socketPresenceWorkflow(socketId), + ], + arguments: ['workflow:', 'workflow:', socketId, workflowIdHint ?? ''], }) - if (workflowId) { + if (typeof workflowId === 'string' && workflowId.length > 0) { logger.debug(`Removed socket ${socketId} from workflow ${workflowId}`) + return workflowId } - return workflowId as string | null + + return null } catch (error) { if ((error as Error).message?.includes('NOSCRIPT') && !retried) { logger.warn('Lua script not found, reloading...') this.removeUserScriptSha = await this.redis.scriptLoad(REMOVE_USER_SCRIPT) - return this.removeUserFromRoom(socketId, true) + return this.removeUserFromRoom(socketId, workflowIdHint, true) } logger.error(`Failed to remove user from room: ${socketId}`, error) return null @@ -215,7 +242,12 @@ export class RedisRoomManager implements IRoomManager { } async getWorkflowIdForSocket(socketId: string): Promise { - return this.redis.get(KEYS.socketWorkflow(socketId)) + const workflowId = await this.redis.get(KEYS.socketWorkflow(socketId)) + if (workflowId) { + return workflowId + } + + return this.redis.get(KEYS.socketPresenceWorkflow(socketId)) } async getUserSession(socketId: string): Promise { @@ -278,6 +310,7 @@ export class RedisRoomManager implements IRoomManager { KEYS.workflowUsers(workflowId), KEYS.socketWorkflow(socketId), KEYS.socketSession(socketId), + KEYS.socketPresenceWorkflow(socketId), ], arguments: [ socketId, @@ -285,6 +318,7 @@ export class RedisRoomManager implements IRoomManager { updates.selection !== undefined ? JSON.stringify(updates.selection) : '', (updates.lastActivity ?? Date.now()).toString(), SOCKET_KEY_TTL.toString(), + SOCKET_PRESENCE_WORKFLOW_KEY_TTL.toString(), ], }) } catch (error) { @@ -348,7 +382,7 @@ export class RedisRoomManager implements IRoomManager { // Remove all users from Redis state for (const user of users) { - await this.removeUserFromRoom(user.socketId) + await this.removeUserFromRoom(user.socketId, workflowId) } // Clean up room data diff --git a/apps/sim/socket/rooms/types.ts b/apps/sim/socket/rooms/types.ts index b294646f6..5c755a739 100644 --- a/apps/sim/socket/rooms/types.ts +++ b/apps/sim/socket/rooms/types.ts @@ -65,9 +65,10 @@ export interface IRoomManager { /** * Remove a user from their current room - * Returns the workflowId they were in, or null if not in any room + * Optional workflowIdHint is used when socket mapping keys are missing/expired. + * Returns the workflowId they were in, or null if not in any room. */ - removeUserFromRoom(socketId: string): Promise + removeUserFromRoom(socketId: string, workflowIdHint?: string): Promise /** * Get the workflow ID for a socket