{
  "canonical_name": "simstudioai/sim",
  "compilation_id": "pack_e0399d2856714166b1f79c3912263a38",
  "created_at": "2026-05-15T20:01:20.539621+00:00",
  "created_by": "project-pack-compiler",
  "feedback": {
    "carrier_selection_notes": [
      "viable_asset_types=mcp_config, recipe, host_instruction, eval, preflight",
      "recommended_asset_types=mcp_config, recipe, host_instruction, eval, preflight"
    ],
    "evidence_delta": {
      "confirmed_claims": [
        "identity_anchor_present",
        "capability_and_host_targets_present",
        "install_path_declared_or_better"
      ],
      "missing_required_fields": [],
      "must_verify_forwarded": [
        "Run or inspect `npx simstudio` in an isolated environment.",
        "Confirm the project exposes the claimed capability to at least one target host."
      ],
      "quickstart_execution_scope": "allowlisted_sandbox_smoke",
      "sandbox_command": "npx simstudio",
      "sandbox_container_image": "node:22-slim",
      "sandbox_execution_backend": "docker",
      "sandbox_planner_decision": "deterministic_isolated_install",
      "sandbox_validation_id": "sbx_76146d00441145cf9d86c788d213ebd7"
    },
    "feedback_event_type": "project_pack_compilation_feedback",
    "learning_candidate_reasons": [],
    "template_gaps": []
  },
  "identity": {
    "canonical_id": "project_836115f0eb2ccacd7a3846d42f15427b",
    "canonical_name": "simstudioai/sim",
    "homepage_url": null,
    "license": "unknown",
    "repo_url": "https://github.com/simstudioai/sim",
    "slug": "sim",
    "source_packet_id": "phit_89db729c17574a4ba5b4aedb0c2564e1",
    "source_validation_id": "dval_e4a6850475664ddc95ab003825de16a5"
  },
  "merchandising": {
    "best_for": "需要软件开发与交付能力，并使用 cursor的用户",
    "github_forks": null,
    "github_stars": null,
    "one_liner_en": "<p align=\"center\">",
    "one_liner_zh": "<p align=\"center\">",
    "primary_category": {
      "category_id": "software-development",
      "confidence": "medium",
      "name_en": "Software Development",
      "name_zh": "软件开发与交付",
      "reason": "matched_keywords:git"
    },
    "target_user": "使用 cursor 等宿主 AI 的用户",
    "title_en": "sim",
    "title_zh": "sim 能力包",
    "visible_tags": [
      {
        "label_en": "Browser Agents",
        "label_zh": "浏览器 Agent",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "product_domain-browser-agents",
        "type": "product_domain"
      },
      {
        "label_en": "Web Task Automation",
        "label_zh": "网页任务自动化",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "user_job-web-task-automation",
        "type": "user_job"
      },
      {
        "label_en": "Natural-language Web Actions",
        "label_zh": "自然语言网页操作",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "core_capability-natural-language-web-actions",
        "type": "core_capability"
      },
      {
        "label_en": "Checkpoint Resume",
        "label_zh": "断点恢复流程",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "workflow_pattern-checkpoint-resume",
        "type": "workflow_pattern"
      },
      {
        "label_en": "Evaluation Suite",
        "label_zh": "评测体系",
        "source": "repo_evidence_project_characteristics",
        "tag_id": "selection_signal-evaluation-suite",
        "type": "selection_signal"
      }
    ]
  },
  "packet_id": "phit_89db729c17574a4ba5b4aedb0c2564e1",
  "page_model": {
    "artifacts": {
      "artifact_slug": "sim",
      "files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json",
        "REPO_INSPECTION.md",
        "CAPABILITY_CONTRACT.json",
        "EVIDENCE_INDEX.json",
        "CLAIM_GRAPH.json"
      ],
      "required_files": [
        "PROJECT_PACK.json",
        "QUICK_START.md",
        "PROMPT_PREVIEW.md",
        "HUMAN_MANUAL.md",
        "AI_CONTEXT_PACK.md",
        "BOUNDARY_RISK_CARD.md",
        "PITFALL_LOG.md",
        "REPO_INSPECTION.json"
      ]
    },
    "detail": {
      "capability_source": "Project Hit Packet + DownstreamValidationResult",
      "commands": [
        {
          "command": "npx simstudio",
          "label": "Node.js / npx · 官方安装入口",
          "source": "https://github.com/simstudioai/sim#readme",
          "verified": true
        }
      ],
      "display_tags": [
        "浏览器 Agent",
        "网页任务自动化",
        "自然语言网页操作",
        "断点恢复流程",
        "评测体系"
      ],
      "eyebrow": "软件开发与交付",
      "glance": [
        {
          "body": "判断自己是不是目标用户。",
          "label": "最适合谁",
          "value": "需要软件开发与交付能力，并使用 cursor的用户"
        },
        {
          "body": "先理解能力边界，再决定是否继续。",
          "label": "核心价值",
          "value": "<p align=\"center\">"
        },
        {
          "body": "未完成验证前保持审慎。",
          "label": "继续前",
          "value": "publish to Doramagic.ai project surfaces"
        }
      ],
      "guardrail_source": "Boundary & Risk Card",
      "guardrails": [
        {
          "body": "Prompt Preview 只展示流程，不证明项目已安装或运行。",
          "label": "Check 1",
          "value": "不要把试用当真实运行"
        },
        {
          "body": "cursor",
          "label": "Check 2",
          "value": "确认宿主兼容"
        },
        {
          "body": "publish to Doramagic.ai project surfaces",
          "label": "Check 3",
          "value": "先隔离验证"
        }
      ],
      "mode": "mcp_config, recipe, host_instruction, eval, preflight",
      "pitfall_log": {
        "items": [
          {
            "body": "Open-source general purpose agent with built-in MCPToolkit support 15 May 2025 · ... MCP for local-agent workflows · r/LocalLLaMA - A visual ... r/commandline - CLI tool to simplify open source monitoring agent installation.",
            "category": "安装坑",
            "evidence": [
              "social_signal:reddit | ssig_7a250aac9fa1441c8186a7b73d669d8f | https://www.reddit.com/r/LocalLLaMA/comments/1kn8m8t/opensource_general_purpose_agent_with_builtin/ | Open-source general purpose agent with built-in MCPToolkit support"
            ],
            "severity": "medium",
            "suggested_check": "Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。",
            "title": "社区讨论暴露的待验证问题：Open-source general purpose agent with built-in MCPToolkit support",
            "user_impact": "这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。"
          },
          {
            "body": "项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。",
            "category": "配置坑",
            "evidence": [
              "capability.host_targets | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | host_targets=cursor"
            ],
            "severity": "medium",
            "suggested_check": "列出会写入的配置文件、目录和卸载/回滚步骤。",
            "title": "可能修改宿主 AI 配置",
            "user_impact": "安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。"
          },
          {
            "body": "README/documentation is current enough for a first validation pass.",
            "category": "能力坑",
            "evidence": [
              "capability.assumptions | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | README/documentation is current enough for a first validation pass."
            ],
            "severity": "medium",
            "suggested_check": "将假设转成下游验证清单。",
            "title": "能力判断依赖假设",
            "user_impact": "假设不成立时，用户拿不到承诺的能力。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.6.63",
            "category": "运行坑",
            "evidence": [
              "community_evidence:github | cevd_5a97e1d742fe4d7f918e0b42f27b87c3 | https://github.com/simstudioai/sim/releases/tag/v0.6.63 | 来源类型 github_release 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v0.6.63",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.6.65",
            "category": "运行坑",
            "evidence": [
              "community_evidence:github | cevd_03f18559029c4724b11011ef96259161 | https://github.com/simstudioai/sim/releases/tag/v0.6.65 | 来源类型 github_release 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v0.6.65",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.6.67",
            "category": "运行坑",
            "evidence": [
              "community_evidence:github | cevd_048d1506c1d645b0be435841a26b93ed | https://github.com/simstudioai/sim/releases/tag/v0.6.67 | 来源类型 github_release 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v0.6.67",
            "user_impact": "可能增加新用户试用和生产接入成本。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.6.73",
            "category": "运行坑",
            "evidence": [
              "community_evidence:github | cevd_048864e1cdcc44d2b2a30917b7c4adc2 | https://github.com/simstudioai/sim/releases/tag/v0.6.73 | 来源类型 github_release 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v0.6.73",
            "user_impact": "可能阻塞安装或首次运行。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v0.6.71",
            "category": "维护坑",
            "evidence": [
              "community_evidence:github | cevd_9c30d794fb7344489f96a6ac47cd1d6e | https://github.com/simstudioai/sim/releases/tag/v0.6.71 | 来源类型 github_release 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v0.6.71",
            "user_impact": "可能阻塞安装或首次运行。"
          },
          {
            "body": "未记录 last_activity_observed。",
            "category": "维护坑",
            "evidence": [
              "evidence.maintainer_signals | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | last_activity_observed missing"
            ],
            "severity": "medium",
            "suggested_check": "补 GitHub 最近 commit、release、issue/PR 响应信号。",
            "title": "维护活跃度未知",
            "user_impact": "新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "downstream_validation.risk_items | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "进入安全/权限治理复核队列。",
            "title": "下游验证发现风险项",
            "user_impact": "下游已经要求复核，不能在页面中弱化。"
          },
          {
            "body": "No sandbox install has been executed yet; downstream must verify before user use.",
            "category": "安全/权限坑",
            "evidence": [
              "risks.safety_notes | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | No sandbox install has been executed yet; downstream must verify before user use."
            ],
            "severity": "medium",
            "suggested_check": "转成明确权限清单和安全审查提示。",
            "title": "存在安全注意事项",
            "user_impact": "用户安装前需要知道权限边界和敏感操作。"
          },
          {
            "body": "no_demo",
            "category": "安全/权限坑",
            "evidence": [
              "risks.scoring_risks | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | no_demo; severity=medium"
            ],
            "severity": "medium",
            "suggested_check": "把风险写入边界卡，并确认是否需要人工复核。",
            "title": "存在评分风险",
            "user_impact": "风险会影响是否适合普通用户安装。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Unable to Access Files from Private GitHub Repository in Self-Hosted Setup",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_ed1c9f64533441f5826c1fe98fa9ce49 | https://github.com/simstudioai/sim/issues/4555 | 来源类型 github_issue 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。",
            "title": "来源证据：Unable to Access Files from Private GitHub Repository in Self-Hosted Setup",
            "user_impact": "可能影响授权、密钥配置或安全边界。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.6.64",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_5e2aa5311b1748cea446771920242668 | https://github.com/simstudioai/sim/releases/tag/v0.6.64 | 来源类型 github_release 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v0.6.64",
            "user_impact": "可能阻塞安装或首次运行。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.6.66",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_7d42c79fecf54003b117f76d49873223 | https://github.com/simstudioai/sim/releases/tag/v0.6.66 | 来源讨论提到 api key 相关条件，需在安装/试用前复核。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v0.6.66",
            "user_impact": "可能阻塞安装或首次运行。"
          },
          {
            "body": "GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.6.68",
            "category": "安全/权限坑",
            "evidence": [
              "community_evidence:github | cevd_c8fe17ce7ba6424c88017ed644620915 | https://github.com/simstudioai/sim/releases/tag/v0.6.68 | 来源类型 github_release 暴露的待验证使用条件。"
            ],
            "severity": "medium",
            "suggested_check": "来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。",
            "title": "来源证据：v0.6.68",
            "user_impact": "可能阻塞安装或首次运行。"
          }
        ],
        "source": "ProjectPitfallLog + ProjectHitPacket + validation + community signals",
        "summary": "发现 20 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：安装坑 - 社区讨论暴露的待验证问题：Open-source general purpose agent with built-in MCPToolkit support。",
        "title": "踩坑日志"
      },
      "snapshot": {
        "contributors": null,
        "forks": null,
        "license": "unknown",
        "note": "站点快照，非实时质量证明；用于开工前背景判断。",
        "stars": null
      },
      "source_url": "https://github.com/simstudioai/sim",
      "steps": [
        {
          "body": "不安装项目，先体验能力节奏。",
          "code": "preview",
          "title": "先试 Prompt"
        },
        {
          "body": "理解输入、输出、失败模式和边界。",
          "code": "manual",
          "title": "读说明书"
        },
        {
          "body": "把上下文交给宿主 AI 继续工作。",
          "code": "context",
          "title": "带给 AI"
        },
        {
          "body": "进入主力环境前先完成安装入口与风险边界验证。",
          "code": "verify",
          "title": "沙箱验证"
        }
      ],
      "subtitle": "<p align=\"center\">",
      "title": "sim 能力包",
      "trial_prompt": "# sim - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for simstudioai/sim.\n\nProject:\n- Name: sim\n- Repository: https://github.com/simstudioai/sim\n- Summary: <p align=\"center\">\n- Host target: cursor\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: <p align=\"center\">\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. project-introduction: Project Introduction. Produce one small intermediate artifact and wait for confirmation.\n2. tech-stack: Technology Stack. Produce one small intermediate artifact and wait for confirmation.\n3. architecture-overview: Architecture Overview. Produce one small intermediate artifact and wait for confirmation.\n4. executor-engine: Workflow Executor Engine. Produce one small intermediate artifact and wait for confirmation.\n5. workflow-blocks: Workflow Blocks System. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/simstudioai/sim#readme\n- .agents/skills/add-block/SKILL.md\n- .agents/skills/add-connector/SKILL.md\n- .agents/skills/add-integration/SKILL.md\n- .agents/skills/add-tools/SKILL.md\n- .agents/skills/add-trigger/SKILL.md\n- .agents/skills/cleanup/SKILL.md\n- .agents/skills/emcn-design-review/SKILL.md\n- .agents/skills/react-query-best-practices/SKILL.md\n- .agents/skills/ship/SKILL.md\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "voices": [
        {
          "body": "来源平台：github, x。github/github_issue: Unable to Access Files from Private GitHub Repository in Self-Hosted Set（https://github.com/simstudioai/sim/issues/4555）；github/github_release: v0.6.73（https://github.com/simstudioai/sim/releases/tag/v0.6.73）；github/github_release: v0.6.72（https://github.com/simstudioai/sim/releases/tag/v0.6.72）；github/github_release: v0.6.71（https://github.com/simstudioai/sim/releases/tag/v0.6.71）；github/github_release: v0.6.69（https://github.com/simstudioai/sim/releases/tag/v0.6.69）；github/github_release: v0.6.68（https://github.com/simstudioai/sim/releases/tag/v0.6.68）；github/github_release: v0.6.67（https://github.com/simstudioai/sim/releases/tag/v0.6.67）；github/github_release: v0.6.66（https://github.com/simstudioai/sim/releases/tag/v0.6.66）；github/github_release: v0.6.65（https://github.com/simstudioai/sim/releases/tag/v0.6.65）；github/github_release: v0.6.64（https://github.com/simstudioai/sim/releases/tag/v0.6.64）；github/github_release: v0.6.63（https://github.com/simstudioai/sim/releases/tag/v0.6.63）；x: Morgan (@morganlinton) on X（https://x.com/morganlinton/status/2033564052312801694）。这些是项目级外部声音，不作为单独质量证明。",
          "items": [
            {
              "kind": "github_issue",
              "source": "github",
              "title": "Unable to Access Files from Private GitHub Repository in Self-Hosted Set",
              "url": "https://github.com/simstudioai/sim/issues/4555"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.6.73",
              "url": "https://github.com/simstudioai/sim/releases/tag/v0.6.73"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.6.72",
              "url": "https://github.com/simstudioai/sim/releases/tag/v0.6.72"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.6.71",
              "url": "https://github.com/simstudioai/sim/releases/tag/v0.6.71"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.6.69",
              "url": "https://github.com/simstudioai/sim/releases/tag/v0.6.69"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.6.68",
              "url": "https://github.com/simstudioai/sim/releases/tag/v0.6.68"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.6.67",
              "url": "https://github.com/simstudioai/sim/releases/tag/v0.6.67"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.6.66",
              "url": "https://github.com/simstudioai/sim/releases/tag/v0.6.66"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.6.65",
              "url": "https://github.com/simstudioai/sim/releases/tag/v0.6.65"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.6.64",
              "url": "https://github.com/simstudioai/sim/releases/tag/v0.6.64"
            },
            {
              "kind": "github_release",
              "source": "github",
              "title": "v0.6.63",
              "url": "https://github.com/simstudioai/sim/releases/tag/v0.6.63"
            },
            {
              "kind": "searxng_indexed",
              "source": "x",
              "title": "Morgan (@morganlinton) on X",
              "url": "https://x.com/morganlinton/status/2033564052312801694"
            }
          ],
          "status": "已收录 17 条来源",
          "title": "社区讨论"
        }
      ]
    },
    "homepage_card": {
      "category": "软件开发与交付",
      "desc": "<p align=\"center\">",
      "effort": "安装已验证",
      "forks": null,
      "icon": "code",
      "name": "sim 能力包",
      "risk": "可发布",
      "slug": "sim",
      "stars": null,
      "tags": [
        "浏览器 Agent",
        "网页任务自动化",
        "自然语言网页操作",
        "断点恢复流程",
        "评测体系"
      ],
      "thumb": "gray",
      "type": "MCP 配置"
    },
    "manual": {
      "markdown": "# https://github.com/simstudioai/sim 项目说明书\n\n生成时间：2026-05-15 19:37:50 UTC\n\n## 目录\n\n- [Project Introduction](#project-introduction)\n- [Technology Stack](#tech-stack)\n- [Architecture Overview](#architecture-overview)\n- [Workflow Executor Engine](#executor-engine)\n- [Workflow Blocks System](#workflow-blocks)\n- [Integrations and Connectors](#integrations-connectors)\n- [Agent System](#agent-system)\n- [Copilot System](#copilot-system)\n- [Deployment Guide](#deployment-guide)\n- [Background Jobs and Background Processing](#background-jobs)\n\n<a id='project-introduction'></a>\n\n## Project Introduction\n\n### 相关页面\n\n相关主题：[Technology Stack](#tech-stack), [Architecture Overview](#architecture-overview)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/simstudioai/sim/blob/main/README.md)\n- [apps/sim/package.json](https://github.com/simstudioai/sim/blob/main/apps/sim/package.json)\n- [packages/python-sdk/README.md](https://github.com/simstudioai/sim/blob/main/packages/python-sdk/README.md)\n- [packages/ts-sdk/README.md](https://github.com/simstudioai/sim/blob/main/packages/ts-sdk/README.md)\n- [scripts/README.md](https://github.com/simstudioai/sim/blob/main/scripts/README.md)\n</details>\n\n# Project Introduction\n\nSim is an AI-powered workflow automation platform that enables users to build, deploy, and manage intelligent automation pipelines. The platform combines visual workflow design with AI capabilities, allowing teams to create sophisticated automation workflows without extensive coding knowledge.\n\n## Overview\n\nSim Studio provides a modern approach to workflow automation by integrating large language models (LLMs) directly into the automation pipeline. The platform supports both cloud-hosted and self-hosted deployment options, giving organizations flexibility in how they manage their automation infrastructure.\n\nThe project is structured as a monorepo containing multiple packages:\n\n| Package | Purpose |\n|---------|---------|\n| `apps/sim` | Main web application |\n| `packages/python-sdk` | Python SDK for programmatic access |\n| `packages/ts-sdk` | TypeScript SDK for programmatic access |\n| `scripts` | Automation and utility scripts |\n\n资料来源：[README.md:1-20]()\n\n## Key Features\n\n### AI-Native Automation\n\nSim leverages AI capabilities throughout the platform, enabling intelligent decision-making within workflows. The system supports integration with various AI providers including Ollama and vLLM for local model deployment.\n\n资料来源：[README.md:45-48]()\n\n### Multiple SDK Support\n\nThe platform provides official SDKs for both Python and TypeScript ecosystems, enabling developers to:\n\n- Execute workflows programmatically\n- Manage workflow deployments\n- Monitor execution status and results\n- Handle async job execution with polling\n\n资料来源：[packages/python-sdk/README.md:1-50]()\n资料来源：[packages/ts-sdk/README.md:1-40]()\n\n### Extensible Architecture\n\nSim includes support for various webhook providers and integrations:\n\n| Provider | Integration Type |\n|----------|------------------|\n| Webflow | CMS Webhook |\n| Typeform | Form Response |\n| Gong | Call Recording |\n| Vercel | Deployment Events |\n| Ashby | ATS Events |\n| Grain | Meeting Recording |\n| Salesforce | CRM Events |\n\n资料来源：[apps/sim/lib/webhooks/providers/webflow.ts:1-50]()\n资料来源：[apps/sim/lib/webhooks/providers/typeform.ts:1-40]()\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[Client Application] --> B[Next.js Web App]\n    B --> C[Workflow Engine]\n    C --> D[Sandbox Executor]\n    C --> E[Webhook System]\n    D --> F[AI Providers]\n    E --> G[External Services]\n    F --> H[Ollama / vLLM]\n    F --> I[Cloud LLM APIs]\n```\n\n### Core Components\n\n#### Web Application (`apps/sim`)\n\nThe main React-based web application built with Next.js that provides:\n\n- Visual workflow editor\n- Block-based workflow construction\n- Trigger configuration\n- Execution monitoring\n- Workspace management\n\nThe application uses TypeScript with strict type checking enabled via `tsc --noEmit`.\n\n资料来源：[apps/sim/package.json:1-30]()\n\n#### Workflow Engine\n\nThe workflow engine handles:\n\n- Workflow parsing and validation\n- Execution scheduling\n- State management\n- Error handling and retries\n\n#### Sandbox Executor\n\nSandboxed execution environment for running workflow blocks safely with resource isolation.\n\n资料来源：[apps/sim/package.json:8-12]()\n\n## Deployment Options\n\nSim supports three primary self-hosted deployment methods.\n\n### Comparison Matrix\n\n| Method | Docker Required | Manual Setup | Use Case |\n|--------|-----------------|--------------|----------|\n| NPM Package | Yes | Minimal | Quick local testing |\n| Docker Compose | Yes | Moderate | Production deployments |\n| Manual Setup | No | Extensive | Custom infrastructure |\n\n资料来源：[README.md:25-50]()\n\n### Option 1: NPM Package (Quick Start)\n\nThe fastest way to get started locally:\n\n```bash\nnpx simstudio\n```\n\nThis command pulls the latest Docker images and starts Sim at http://localhost:3000.\n\n**Options:**\n\n| Flag | Description | Default |\n|------|-------------|---------|\n| `-p, --port <port>` | Port to run Sim on | `3000` |\n| `--no-pull` | Skip pulling latest Docker images | `false` |\n\n资料来源：[README.md:25-32]()\n\n### Option 2: Docker Compose\n\nFor production-ready deployments with persistent storage:\n\n```bash\ngit clone https://github.com/simstudioai/sim.git && cd sim\ndocker compose -f docker-compose.prod.yml up -d\n```\n\n资料来源：[README.md:34-38]()\n\n### Option 3: Manual Setup\n\nFor custom infrastructure configurations. Requires manual installation of all dependencies.\n\n资料来源：[README.md:40-45]()\n\n## System Requirements\n\n### Hardware Requirements\n\n| Component | Minimum | Recommended |\n|-----------|---------|-------------|\n| CPU | 2 cores | 4+ cores |\n| RAM | 4 GB | 8+ GB |\n| Disk | 10 GB | 20+ GB |\n\n### Software Requirements\n\n| Software | Version | Notes |\n|----------|---------|-------|\n| Docker | Latest | Required for NPM and Docker Compose methods |\n| Bun | Latest | Required for manual setup |\n| Node.js | v20+ | Required for manual setup |\n| PostgreSQL | 12+ | Must include pgvector extension |\n\n资料来源：[README.md:40-45]()\n\n### Database Configuration\n\nPostgreSQL with pgvector is required for vector storage capabilities:\n\n```bash\ndocker run --name simstudio-db \\\n  -e POSTGRES_PASSWORD=your_password \\\n  -e POSTGRES_DB=simstudio \\\n  -p 5432:5432 -d \\\n  pgvector/pgvector:pg16\n```\n\n资料来源：[README.md:50-55]()\n\n## SDK Data Structures\n\n### WorkflowExecutionResult\n\n```python\n@dataclass\nclass WorkflowExecutionResult:\n    success: bool\n    output: Optional[Any] = None\n    error: Optional[str] = None\n    logs: Optional[list] = None\n    metadata: Optional[Dict[str, Any]] = None\n    trace_spans: Optional[list] = None\n    total_duration: Optional[float] = None\n```\n\n资料来源：[packages/python-sdk/README.md:80-90]()\n\n### WorkflowStatus\n\n```python\n@dataclass\nclass WorkflowStatus:\n    is_deployed: bool\n    deployed_at: Optional[str] = None\n    needs_redeployment: bool = False\n```\n\n资料来源：[packages/python-sdk/README.md:100-105]()\n\n### RateLimitInfo\n\n```python\n@dataclass\nclass RateLimitInfo:\n    limit: int\n    remaining: int\n    reset: int\n    retry_after: Optional[int] = None\n```\n\n资料来源：[packages/python-sdk/README.md:125-130]()\n\n## Development Workflow\n\n### Code Quality Tools\n\nThe project enforces code quality through Biome:\n\n| Command | Purpose |\n|---------|---------|\n| `bun run lint` | Format and lint with auto-fix |\n| `bun run lint:check` | Check linting without auto-fix |\n| `bun run format` | Format code files |\n| `bun run format:check` | Check formatting without changes |\n| `bun run type-check` | Run TypeScript type checking |\n\n资料来源：[apps/sim/package.json:15-22]()\n\n### Testing\n\nTests are run using Vitest:\n\n| Command | Purpose |\n|---------|---------|\n| `bun run test` | Run tests once |\n| `bun run test:watch` | Run tests in watch mode |\n| `bun run test:coverage` | Generate coverage report |\n\n资料来源：[apps/sim/package.json:14-17]()\n\n## Local Model Support\n\nSim supports self-hosted AI models through two providers:\n\n### Ollama\n\nIntegration with [Ollama](https://ollama.ai) for running local LLMs including Llama 2, Mistral, and other open-source models.\n\n### vLLM\n\nIntegration with [vLLM](https://docs.vllm.ai/) for high-performance inference serving.\n\n资料来源：[README.md:45-48]()\n\n## Documentation Generation\n\nThe project includes automated documentation generation:\n\n```bash\nbun run generate-docs\n```\n\nThis script preserves manual content markers within the codebase for custom documentation sections.\n\n资料来源：[scripts/README.md:1-30]()\n\n## Community and Support\n\n| Resource | Link |\n|----------|------|\n| Documentation | https://docs.sim.ai |\n| Discord Community | Discord |\n| Twitter | @simdotai |\n| DeepWiki | DeepWiki |\n\n资料来源：[README.md:1-15]()\n\n## License\n\nThe project is licensed under Apache-2.0.\n\n资料来源：[packages/python-sdk/README.md:70]()\n资料来源：[packages/ts-sdk/README.md:45]()\n\n---\n\n<a id='tech-stack'></a>\n\n## Technology Stack\n\n### 相关页面\n\n相关主题：[Project Introduction](#project-introduction), [Deployment Guide](#deployment-guide)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [apps/sim/package.json](https://github.com/simstudioai/sim/blob/main/apps/sim/package.json)\n- [apps/realtime/package.json](https://github.com/simstudioai/sim/blob/main/apps/realtime/package.json)\n- [packages/ts-sdk/README.md](https://github.com/simstudioai/sim/blob/main/packages/ts-sdk/README.md)\n- [packages/python-sdk/README.md](https://github.com/simstudioai/sim/blob/main/packages/python-sdk/README.md)\n- [packages/db/drizzle.config.ts](https://github.com/simstudioai/sim/blob/main/packages/db/drizzle.config.ts)\n- [README.md](https://github.com/simstudioai/sim/blob/main/README.md)\n- [apps/sim/lib/knowledge/documents/document-processor.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/knowledge/documents/document-processor.ts)\n- [apps/sim/lib/core/security/input-validation.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/core/security/input-validation.ts)\n</details>\n\n# Technology Stack\n\n## Overview\n\nThe Sim platform is built on a modern, polyglot technology stack designed to support both frontend and backend development with a focus on developer productivity, type safety, and scalable deployment options. The system leverages TypeScript as the primary language for the core application, Python for the SDK ecosystem, and Docker for containerization and self-hosted deployments.\n\n## Core Runtime Environment\n\n### Bun\n\nBun serves as the primary package manager and runtime for the project. All build scripts, dependency installations, and development workflows are configured to use Bun workspaces for efficient monorepo management.\n\n```bash\nbun install\nbun run build\nbun run test\n```\n\n资料来源：[apps/sim/package.json:11-30]()\n\n### Node.js Requirements\n\nThe main application requires Node.js v20+ for runtime compatibility. The TypeScript SDK specifies Node.js 18+ as the minimum requirement.\n\n| Component | Minimum Version | Recommended Version |\n|-----------|-----------------|---------------------|\n| Main App (apps/sim) | Node.js v20+ | Latest LTS |\n| TypeScript SDK | Node.js 18+ | Node.js 20+ |\n| Python SDK | Python 3.8+ | Python 3.11+ |\n\n资料来源：[README.md:35-45](), [packages/ts-sdk/README.md:42]()\n\n## Frontend Architecture\n\n### Next.js Framework\n\nThe main Sim application is built on Next.js, providing server-side rendering, API routes, and static generation capabilities.\n\n**Build Configuration:**\n\n```json\n{\n  \"build\": \"bun run build:sandbox-bundles && NODE_OPTIONS='--max-old-space-size=8192' next build\",\n  \"start\": \"next start\"\n}\n```\n\n资料来源：[apps/sim/package.json:15-16]()\n\n### Testing Framework\n\n| Tool | Purpose | Command |\n|------|---------|---------|\n| Vitest | Unit and integration testing | `bun run test` |\n| Vitest (watch mode) | Development testing | `bun run test:watch` |\n| Vitest (coverage) | Coverage reports | `bun run test:coverage` |\n\n资料来源：[apps/sim/package.json:19-21]()\n\n### Code Quality Tools\n\n| Tool | Purpose | Commands |\n|------|---------|----------|\n| Biome | Linting and formatting | `lint`, `lint:check`, `format`, `format:check` |\n| TypeScript Compiler | Type checking | `type-check` |\n\nBiome is configured for both linting (with unsafe auto-fixes) and code formatting:\n\n```bash\nbun run lint        # Apply lint fixes\nbun run lint:check # Check only\nbun run format     # Apply formatting\nbun run format:check\n```\n\n资料来源：[apps/sim/package.json:22-25]()\n\n## Backend and Database\n\n### PostgreSQL with pgvector\n\nThe platform requires PostgreSQL 12+ with the pgvector extension for vector similarity search capabilities. This enables knowledge base and document embedding features.\n\n**Docker Setup:**\n\n```bash\ndocker run --name simstudio-db \\\n  -e POSTGRES_PASSWORD=your_password \\\n  -e POSTGRES_DB=simstudio \\\n  -p 5432:5432 \\\n  -d pgvector/pgvector:pg16\n```\n\n资料来源：[README.md:45-50]()\n\n### Drizzle ORM\n\nDatabase operations are managed through Drizzle ORM, configured via `drizzle.config.ts`. This provides type-safe database queries and migrations.\n\n```typescript\nimport { defineConfig } from 'drizzle-kit'\n```\n\n资料来源：[packages/db/drizzle.config.ts]()\n\n## Document Processing\n\n### OCR Integration\n\nThe document processor integrates with multiple OCR providers for extracting content from PDFs and images:\n\n| Provider | Configuration | Timeout |\n|----------|---------------|---------|\n| Mistral OCR API | API Key + Endpoint | 30 seconds |\n| Azure Mistral OCR | API Key + Endpoint + Model | 30 seconds |\n\n资料来源：[apps/sim/lib/knowledge/documents/document-processor.ts:1-80]()\n\nThe OCR system uses:\n\n- Native `fetch` API for HTTP requests\n- AbortController for timeout management\n- Base64 encoding for file uploads\n\n## SDK Ecosystem\n\n### TypeScript SDK\n\nThe TypeScript SDK (`packages/ts-sdk`) provides programmatic access to Sim features:\n\n| Requirement | Version |\n|-------------|---------|\n| Node.js | 18+ |\n| TypeScript | 5.0+ |\n\n**Development Commands:**\n\n```bash\nbun run test    # Run tests\nbun run build  # Compile to dist/\nbun run dev    # Development mode with auto-rebuild\n```\n\n资料来源：[packages/ts-sdk/README.md:1-45]()\n\n### Python SDK\n\nThe Python SDK (`packages/python-sdk`) offers Python integration:\n\n| Requirement | Version |\n|-------------|---------|\n| Python | 3.8+ |\n| requests | >= 2.25.0 |\n\n**Code Quality Tools:**\n\n```bash\nblack simstudio/           # Code formatting\nflake8 simstudio/          # Linting\nmypy simstudio/            # Type checking\nisort simstudio/           # Import sorting\n```\n\n资料来源：[packages/python-sdk/README.md:1-50]()\n\n## Security Infrastructure\n\n### Input Validation\n\nThe platform implements comprehensive input validation for security:\n\n- **Enum Validation**: Validates values against allowed lists\n- **Hostname Validation**: Prevents SSRF attacks by checking for private IPs, localhost, and reserved addresses\n- **Proxy URL Validation**: Secure proxy configuration validation\n\n资料来源：[apps/sim/lib/core/security/input-validation.ts:1-100]()\n\n## Deployment Options\n\n### Docker Containerization\n\nSim supports multiple deployment scenarios:\n\n```mermaid\ngraph TD\n    A[Sim Deployment Options] --> B[Docker (NPM Package)]\n    A --> C[Docker Compose]\n    A --> D[Manual Setup]\n    \n    B --> B1[npx simstudio]\n    C --> C1[docker compose up]\n    D --> D1[Bun + PostgreSQL]\n```\n\n资料来源：[README.md:25-50]()\n\n### Local Model Support\n\nThe platform supports self-hosted AI models through:\n\n| Runtime | Description |\n|---------|-------------|\n| Ollama | Local model inference |\n| vLLM | High-performance LLM serving |\n\n## Realtime Application\n\nThe `apps/realtime` package provides WebSocket-based communication features with its own independent package.json configuration.\n\n资料来源：[apps/realtime/package.json]()\n\n## Load Testing Infrastructure\n\nThe project includes Artillery-based load testing for workflow performance validation:\n\n| Script | Purpose |\n|--------|---------|\n| `load:workflow:waves` | Wave-based load testing |\n| `load:workflow:isolation` | Workspace isolation testing |\n\n**Configuration Options:**\n\n| Environment Variable | Default | Description |\n|---------------------|---------|-------------|\n| `WAVE_ONE_DURATION` | 60 | Wave 1 duration in seconds |\n| `WAVE_ONE_RATE` | 10 | Wave 1 request rate |\n| `WORKSPACE_A_WEIGHT` | 8 | Workspace A load weight |\n| `WORKSPACE_B_WEIGHT` | 1 | Workspace B load weight |\n\n资料来源：[apps/sim/package.json:8-14]()\n\n## Webhook Integrations\n\nThe platform provides webhook providers for third-party integrations:\n\n| Provider | Purpose |\n|----------|---------|\n| Gong | Meeting/call automation |\n| Vercel | Deployment events |\n| Typeform | Form responses |\n| Webflow | CMS events |\n| WhatsApp | Messaging events |\n\nEach provider implements signature verification for security:\n\n```typescript\nverifyAuth: createHmacVerifier({\n  configKey: 'secret',\n  headerName: 'Provider-Signature',\n  validateFn: validateProviderSignature,\n  providerLabel: 'ProviderName',\n})\n```\n\n资料来源：[apps/sim/lib/webhooks/providers/gong.ts](), [apps/sim/lib/webhooks/providers/vercel.ts](), [apps/sim/lib/webhooks/providers/typeform.ts](), [apps/sim/lib/webhooks/providers/webflow.ts](), [apps/sim/lib/webhooks/providers/whatsapp.ts]()\n\n## Architecture Diagram\n\n```mermaid\ngraph TB\n    subgraph \"Client Layer\"\n        WebApp[Web Application<br/>Next.js]\n        TS_SDK[TypeScript SDK<br/>Node.js 18+]\n    end\n    \n    subgraph \"Runtime\"\n        Bun[Bun Runtime<br/>Workspaces]\n        Node[Node.js v20+]\n    end\n    \n    subgraph \"Backend Services\"\n        API[API Routes]\n        Webhooks[Webhook Providers]\n        Security[Input Validation]\n    end\n    \n    subgraph \"Data Layer\"\n        Postgres[PostgreSQL + pgvector<br/>Drizzle ORM]\n        Knowledge[Document Processor<br/>OCR Integration]\n    end\n    \n    subgraph \"Deployment\"\n        Docker[Docker Container]\n        Ollama[Ollama]\n        VLLM[vLLM]\n    end\n    \n    WebApp --> API\n    TS_SDK --> API\n    API --> Postgres\n    API --> Knowledge\n    WebApp --> Webhooks\n    Security --> API\n    Docker --> Postgres\n    Ollama --> API\n    VLLM --> API\n```\n\n## Summary Table\n\n| Category | Technology | Version/Notes |\n|----------|------------|---------------|\n| Runtime | Bun | Workspaces for monorepo |\n| Runtime | Node.js | v20+ for main app |\n| Runtime | Python | 3.8+ for Python SDK |\n| Framework | Next.js | Full-stack React framework |\n| Database | PostgreSQL | 12+ with pgvector |\n| ORM | Drizzle | Type-safe queries |\n| Testing | Vitest | Unit and integration tests |\n| Linting | Biome | Fast JS/TS linter |\n| OCR | Mistral/Azure | Document processing |\n| SDKs | TypeScript/Python | Multi-language support |\n| Deployment | Docker | Self-hosted option |\n| AI Runtime | Ollama/vLLM | Local model support |\n\n---\n\n<a id='architecture-overview'></a>\n\n## Architecture Overview\n\n### 相关页面\n\n相关主题：[Workflow Executor Engine](#executor-engine), [Workflow Blocks System](#workflow-blocks)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [apps/sim/blocks/registry.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/blocks/registry.ts)\n- [apps/sim/blocks/index.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/blocks/index.ts)\n- [apps/sim/executor/index.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/executor/index.ts)\n- [apps/sim/lib/workflows/triggers/triggers.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/triggers/triggers.ts)\n- [apps/sim/lib/workflows/diff/diff-engine.test.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/diff/diff-engine.test.ts)\n- [apps/sim/lib/api/contracts/types.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/api/contracts/types.ts)\n- [apps/sim/lib/webhooks/providers/gong.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/webhooks/providers/gong.ts)\n- [apps/sim/lib/webhooks/pending-verification.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/webhooks/pending-verification.ts)\n\n</details>\n\n# Architecture Overview\n\nSim is an open-source platform for building AI agents and orchestrating agentic workflows. It connects over 1,000 integrations and LLMs to enable sophisticated automation scenarios. The platform is built with a modular architecture centered around **blocks**, **workflows**, **triggers**, and an **execution engine**.\n\n## High-Level Architecture\n\nThe Sim platform follows a layered architecture:\n\n```mermaid\ngraph TD\n    subgraph \"Presentation Layer\"\n        UI[Next.js Application]\n    end\n    \n    subgraph \"API Layer\"\n        API[API Routes]\n        Contracts[Contract Types]\n    end\n    \n    subgraph \"Workflow Engine\"\n        WE[Workflow Engine]\n        Diff[Diff Engine]\n        Registry[Block Registry]\n    end\n    \n    subgraph \"Execution Layer\"\n        Executor[Executor]\n        Sandbox[Sandbox Runner]\n    end\n    \n    subgraph \"Integration Layer\"\n        Webhooks[Webhook Providers]\n        Triggers[Trigger System]\n        Tools[Tool System]\n    end\n    \n    UI --> API\n    API --> Contracts\n    Contracts --> WE\n    WE --> Registry\n    WE --> Diff\n    Registry --> Executor\n    Executor --> Sandbox\n    Webhooks --> Triggers\n    Triggers --> WE\n```\n\n## Core Components\n\n### Block Registry System\n\nThe Block Registry is the central component that manages all available blocks in the system. Blocks are the fundamental building units of workflows, representing discrete operations like data transformation, API calls, or AI interactions.\n\n**Key Files:**\n- `apps/sim/blocks/registry.ts` - Block registration and retrieval\n- `apps/sim/blocks/index.ts` - Block exports and public API\n\n**Registry Functions:**\n\n| Function | Purpose |\n|----------|---------|\n| `getBlock(type)` | Retrieve a specific block by type identifier |\n| `getAllBlocks()` | Get all registered blocks |\n| `getAllBlockTypes()` | Get list of all block type identifiers |\n| `getBlockByToolName(name)` | Find block by associated tool name |\n| `getBlocksByCategory(category)` | Filter blocks by category |\n| `isValidBlockType(type)` | Validate if a block type exists |\n| `registry` | The underlying registry data structure |\n\n资料来源：[apps/sim/blocks/index.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/blocks/index.ts)\n\n**Block Configuration Interface:**\n\nThe registry is mocked in tests to return null or empty values for blocks, indicating dynamic resolution at runtime:\n\n```typescript\nvi.mock('@/blocks', () => ({\n  getBlock: () => null,\n  getAllBlocks: () => ({}),\n  getAllBlockTypes: () => [],\n  getBlockByToolName: () => null,\n  getBlocksByCategory: () => [],\n  isValidBlockType: () => false,\n  registry: {},\n}))\n```\n\n资料来源：[apps/sim/lib/workflows/diff/diff-engine.test.ts:1-20](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/diff/diff-engine.test.ts)\n\n### Trigger System\n\nThe Trigger System manages how workflows are initiated. Triggers can be manual, API-based, chat-based, or event-driven.\n\n**Trigger Types:**\n\n| Type | Identifier | Description |\n|------|------------|-------------|\n| Manual | `TRIGGER_TYPES.START` | User-initiated workflow start |\n| API | `TRIGGER_TYPES.API` | Programmatic workflow invocation |\n| Chat | `TRIGGER_TYPES.CHAT` | Chat-triggered workflows |\n| Starter | `TRIGGER_TYPES.STARTER` | Legacy starter block support |\n\n资料来源：[apps/sim/lib/workflows/triggers/triggers.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/triggers/triggers.ts)\n\n**Trigger Reference Alias Map:**\n\nThe system maps reference aliases to concrete trigger block types:\n\n```typescript\nexport const TRIGGER_REFERENCE_ALIAS_MAP = {\n  start: TRIGGER_TYPES.START,\n  api: TRIGGER_TYPES.API,\n  chat: TRIGGER_TYPES.CHAT,\n  manual: TRIGGER_TYPES.START,\n} as const\n```\n\n**TriggerUtils Class:**\n\nThe `TriggerUtils` class provides static methods for trigger identification:\n\n```typescript\nexport class TriggerUtils {\n  static isTriggerBlock(block: { type: string; triggerMode?: boolean }): boolean {\n    const blockConfig = getBlock(block.type)\n    return (\n      blockConfig?.category === 'triggers' ||\n      block.triggerMode === true ||\n      block.type === TRIGGER_TYPES.STARTER\n    )\n  }\n\n  static isTriggerType(block: { type: string }, triggerType: TriggerType): boolean {\n    return block.type === triggerType\n  }\n}\n```\n\n资料来源：[apps/sim/lib/workflows/triggers/triggers.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/triggers/triggers.ts)\n\n### Workflow Engine\n\nThe Workflow Engine orchestrates the execution of blocks within a workflow context.\n\n**Workflow Components:**\n\n| Component | File | Purpose |\n|-----------|------|---------|\n| Diff Engine | `lib/workflows/diff/diff-engine.test.ts` | Computes differences between workflow versions |\n| Block Outputs | `lib/workflows/blocks/block-outputs` | Manages output data flow between blocks |\n| Visibility | `lib/workflows/subblocks/visibility` | Controls block visibility and canonical modes |\n| Triggers | `lib/workflows/triggers/triggers.ts` | Workflow initiation logic |\n\n资料来源：[apps/sim/lib/workflows/diff/diff-engine.test.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/diff/diff-engine.test.ts)\n\n**Workflow Registry Store:**\n\nThe engine integrates with a workflow registry store for state management:\n\n```typescript\nvi.mock('@/stores/workflows/registry/store', () => ({\n  useWorkflowRegistry: {\n    getState: () => ({\n      activeWorkflowId: null,\n    }),\n  },\n}))\n```\n\n### Execution Engine\n\nThe Execution Engine is responsible for running workflows and blocks in a sandboxed environment.\n\n**Execution Constants:**\n\n| Constant | Purpose |\n|----------|---------|\n| `BLOCK_DIMENSIONS` | Defines minimum block height and dimensions |\n| `HANDLE_POSITIONS` | Manages connection handle placement |\n| `isAnnotationOnlyBlock()` | Determines if a block is annotation-only |\n\n```typescript\nvi.mock('@/executor/constants', () => ({\n  isAnnotationOnlyBlock: () => false,\n  BLOCK_DIMENSIONS: { MIN_HEIGHT: 100 },\n  HANDLE_POSITIONS: {},\n}))\n```\n\n资料来源：[apps/sim/lib/workflows/diff/diff-engine.test.ts:1-20](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/diff/diff-engine.test.ts)\n\n### API Contract System\n\nThe API Contract System provides type-safe API route definitions and type inference utilities.\n\n**Contract Type Generics:**\n\n| Type | Description |\n|------|-------------|\n| `ContractParams<C>` | Extracts URL parameters from contract |\n| `ContractQuery<C>` | Extracts query parameters from contract |\n| `ContractBody<C>` | Extracts request body from contract |\n| `ContractHeaders<C>` | Extracts headers from contract |\n\n```typescript\nexport type ContractParams<C extends AnyApiRouteContract> = C extends ApiRouteContract<\n  infer TParams,\n  ApiSchema | undefined,\n  ApiSchema | undefined,\n  ApiSchema | undefined,\n  ResponseMode,\n  ApiSchema | undefined\n>\n  ? EmptySchemaOutput<TParams>\n  : undefined\n```\n\n资料来源：[apps/sim/lib/api/contracts/types.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/api/contracts/types.ts)\n\n## Webhook Integration\n\nSim supports multiple webhook providers for event-driven workflow triggering.\n\n**Supported Providers:**\n\n| Provider | File | Key Features |\n|----------|------|--------------|\n| Gong | `lib/webhooks/providers/gong.ts` | Automation rules, call data |\n| Webflow | `lib/webhooks/providers/webflow.ts` | Collection filtering, CMS events |\n| Typeform | `lib/webhooks/providers/typeform.ts` | Form responses, HMAC verification |\n| Vercel | `lib/webhooks/providers/vercel.ts` | Deployment events |\n\n**Gong Provider Structure:**\n\n```typescript\n{\n  eventType: 'gong.automation_rule',\n  callId,\n  metaData,\n  parties: (callData?.parties as unknown[]) || [],\n  context: (callData?.context as unknown[]) || [],\n  trackers: (content?.trackers as unknown[]) || [],\n  topics: (content?.topics as unknown[]) || [],\n  highlights: (content?.highlights as unknown[]) || [],\n}\n```\n\n资料来源：[apps/sim/lib/webhooks/providers/gong.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/webhooks/providers/gong.ts)\n\n**Webhook Event Filtering:**\n\nProviders implement event filtering logic:\n\n```typescript\nshouldSkipEvent({ webhook, body, requestId, providerConfig }: EventFilterContext) {\n  const configuredCollectionId = providerConfig.collectionId as string | undefined\n  if (configuredCollectionId) {\n    const obj = body as Record<string, unknown>\n    const payload = obj.payload as Record<string, unknown> | undefined\n    const payloadCollectionId = (payload?.collectionId ?? obj.collectionId) as string | undefined\n\n    if (payloadCollectionId && payloadCollectionId !== configuredCollectionId) {\n      return true\n    }\n  }\n  return false\n}\n```\n\n资料来源：[apps/sim/lib/webhooks/providers/webflow.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/webhooks/providers/webflow.ts)\n\n**Pending Verification System:**\n\nWebhook verification is handled through a pending verification mechanism:\n\n| Provider | Verification Method |\n|----------|---------------------|\n| Ashby | Always valid |\n| Grain | GET/HEAD or POST without body |\n| Generic | GET/HEAD or POST without body |\n| Salesforce | GET/HEAD or POST without body |\n\n```typescript\nconst pendingWebhookVerificationProbeMatchers: Record<\n  string,\n  PendingWebhookVerificationProbeMatcher\n> = {\n  ashby: ({ method, body }) => method === 'POST' && body?.action === 'ping',\n  grain: ({ method, body }) =>\n    method === 'GET' ||\n    method === 'HEAD' ||\n    (method === 'POST' && (!body || Object.keys(body).length === 0 || !body.type)),\n  generic: ({ method, body }) =>\n    method === 'GET' ||\n    method === 'HEAD' ||\n    (method === 'POST' && (!body || Object.keys(body).length === 0)),\n  salesforce: ({ method, body }) =>\n    method === 'GET' ||\n    method === 'HEAD' ||\n    (method === 'POST' && (!body || Object.keys(body).length === 0)),\n}\n```\n\n资料来源：[apps/sim/lib/webhooks/pending-verification.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/webhooks/pending-verification.ts)\n\n## Data Flow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant API\n    participant Registry\n    participant Workflow\n    participant Executor\n    participant Sandbox\n\n    User->>API: Trigger Workflow\n    API->>Registry: Validate Block Types\n    Registry-->>API: Block Configs\n    API->>Workflow: Initialize Workflow\n    Workflow->>Registry: Get Block Implementations\n    Registry-->>Workflow: Blocks\n    Workflow->>Executor: Execute Blocks\n    Executor->>Sandbox: Run in Sandbox\n    Sandbox-->>Executor: Results\n    Executor-->>Workflow: Block Outputs\n    Workflow-->>API: Workflow Complete\n    API-->>User: Response\n```\n\n## Block Execution Flow\n\n```mermaid\ngraph TD\n    Start[Workflow Start] --> Trigger{Trigger Type}\n    \n    Trigger -->|Manual| Manual[Manual Trigger]\n    Trigger -->|API| API[API Trigger]\n    Trigger -->|Chat| Chat[Chat Trigger]\n    \n    Manual --> Validate{Validate Block Types}\n    API --> Validate\n    Chat --> Validate\n    \n    Validate -->|Valid| GetBlocks[Get Blocks from Registry]\n    Validate -->|Invalid| Error[Error Handling]\n    \n    GetBlocks --> Execute[Execute Block]\n    Execute --> Sandbox{Run in Sandbox?}\n    \n    Sandbox -->|Yes| Sandboxed[Sandbox Execution]\n    Sandbox -->|No| Direct[Direct Execution]\n    \n    Sandboxed --> Output[Block Output]\n    Direct --> Output\n    \n    Output --> NextBlock{Next Block?}\n    NextBlock -->|Yes| Execute\n    NextBlock -->|No| Complete[Workflow Complete]\n```\n\n## Type Safety\n\nSim leverages TypeScript's type system extensively for compile-time safety:\n\n1. **API Contracts**: Type-safe route definitions with generic type parameters\n2. **Block Registry**: Type-checked block retrieval and validation\n3. **Trigger Classification**: Type-safe trigger type checking\n4. **Webhook Payloads**: Typed webhook event data structures\n\n## Documentation Generation\n\nThe platform includes an automated documentation generator:\n\n```mermaid\ngraph LR\n    A[Block Files] --> B[Scan Directory]\n    B --> C[Extract Metadata]\n    C --> D[Generate Markdown]\n    D --> E[Update meta.json]\n    E --> F[Commit to Repo]\n```\n\nThe generator is integrated into CI/CD and preserves manual content during regeneration.\n\n资料来源：[scripts/README.md](https://github.com/simstudioai/sim/blob/main/scripts/README.md)\n\n---\n\n<a id='executor-engine'></a>\n\n## Workflow Executor Engine\n\n### 相关页面\n\n相关主题：[Architecture Overview](#architecture-overview), [Workflow Blocks System](#workflow-blocks)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [apps/sim/executor/dag/builder.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/executor/dag/builder.ts)\n- [apps/sim/executor/execution/engine.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/executor/execution/engine.ts)\n- [apps/sim/executor/execution/executor.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/executor/execution/executor.ts)\n- [apps/sim/executor/orchestrators/parallel.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/executor/orchestrators/parallel.ts)\n- [apps/sim/executor/orchestrators/loop.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/executor/orchestrators/loop.ts)\n- [packages/testing/src/factories/executor-context.factory.ts](https://github.com/simstudioai/sim/blob/main/packages/testing/src/factories/executor-context.factory.ts)\n- [apps/sim/lib/workflows/triggers/triggers.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/triggers/triggers.ts)\n- [apps/sim/lib/copilot/tools/client/run-tool-execution.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/copilot/tools/client/run-tool-execution.ts)\n</details>\n\n# Workflow Executor Engine\n\nThe Workflow Executor Engine is the core runtime system responsible for executing workflows built in the Sim platform. It transforms serialized workflow definitions into executable execution plans, manages block-level execution with proper dependency resolution, and orchestrates complex control flow patterns including parallel execution and looping constructs.\n\n## Architecture Overview\n\nThe executor engine follows a layered architecture that separates concerns between DAG construction, execution planning, and runtime orchestration.\n\n```mermaid\ngraph TD\n    A[Workflow Definition] --> B[DAG Builder]\n    B --> C[Execution Plan]\n    C --> D[Execution Engine]\n    D --> E[Block Executor]\n    E --> F[Parallel Orchestrator]\n    E --> G[Loop Orchestrator]\n    D --> H[Trigger System]\n    H --> I[Manual Triggers]\n    H --> J[API Triggers]\n    H --> K[Scheduled Triggers]\n```\n\n### Core Components\n\n| Component | File | Responsibility |\n|-----------|------|----------------|\n| DAG Builder | `executor/dag/builder.ts` | Converts workflow blocks into a directed acyclic graph |\n| Execution Engine | `executor/execution/engine.ts` | Coordinates overall execution flow and state management |\n| Block Executor | `executor/execution/executor.ts` | Executes individual blocks and manages block states |\n| Parallel Orchestrator | `executor/orchestrators/parallel.ts` | Manages concurrent block execution |\n| Loop Orchestrator | `executor/orchestrators/loop.ts` | Handles iterative block execution |\n\n## Executor Context\n\nThe executor maintains a comprehensive context object that tracks the state of the entire workflow execution.\n\n```typescript\ninterface ExecutorContext {\n  workflow: SerializedWorkflow\n  blocks: SerializedBlock[]\n  connections: SerializedConnection[]\n  blockStates: Map<string, ExecutorBlockState>\n  executedBlocks: Set<string>\n  abortSignal?: AbortSignal\n  workspaceId: string\n  executionId: string\n}\n```\n\n### Block State Management\n\nEach block maintains its execution state through the `ExecutorBlockState` interface:\n\n```typescript\ninterface ExecutorBlockState {\n  output: Record<string, any>\n  executed: boolean\n  executionTime: number\n}\n```\n\n资料来源：[packages/testing/src/factories/executor-context.factory.ts:1-80]()\n\nThe testing factory provides utilities for creating executor contexts with pre-configured blocks:\n\n```typescript\nexport function createExecutorContextWithBlocks(\n  blockOutputs: Record<string, Record<string, any>>,\n  options?: ExecutorContextFactoryOptions\n): ExecutorContext\n```\n\n资料来源：[packages/testing/src/factories/executor-context.factory.ts:44-70]()\n\n## DAG Builder\n\nThe DAG (Directed Acyclic Graph) builder transforms the linear block definitions into a dependency graph that the execution engine can traverse.\n\n### Responsibilities\n\n- Parse workflow block definitions and connection specifications\n- Build adjacency lists representing block dependencies\n- Validate graph structure to ensure no cycles\n- Resolve input/output mappings between connected blocks\n- Generate execution order using topological sorting\n\n### Key Functions\n\n| Function | Purpose |\n|----------|---------|\n| `buildDAG(blocks, connections)` | Constructs the dependency graph |\n| `topologicalSort()` | Determines safe execution order |\n| `getDependencies(blockId)` | Retrieves all blocks that must execute first |\n| `getDependents(blockId)` | Finds blocks that depend on this block |\n\n## Execution Engine\n\nThe execution engine is the central coordinator that manages the lifecycle of workflow execution from start to completion.\n\n### Execution Flow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Engine\n    participant Executor\n    participant Orchestrator\n    participant Block\n\n    Client->>Engine: execute(workflow, context)\n    Engine->>Executor: prepare(workflow)\n    Executor->>Engine: DAG Ready\n    Engine->>Engine: determineStartBlocks()\n    Engine->>Orchestrator: executeNextBatch()\n    Orchestrator->>Block: execute(block)\n    Block-->>Orchestrator: result\n    Orchestrator->>Engine: blockComplete()\n    Engine->>Engine: updateContext()\n    Engine->>Orchestrator: executeNextBatch()\n    Orchestrator-->>Engine: batchComplete\n    Engine-->>Client: executionResult\n```\n\n### Trigger Classification\n\nThe engine classifies workflow start conditions to determine execution entry points:\n\n```typescript\nclass TriggerClassifier {\n  static isManualTrigger(block: { type: string; subBlocks?: any }): boolean\n  static isApiTrigger(block: { type: string; subBlocks?: any }, isChildWorkflow?: boolean): boolean\n}\n```\n\n资料来源：[apps/sim/lib/workflows/triggers/triggers.ts:1-60]()\n\nSupported trigger types:\n\n| Trigger Type | Description | Entry Mode |\n|--------------|-------------|------------|\n| `INPUT` | Form or manual input trigger | Manual |\n| `MANUAL` | Explicit manual execution | Manual |\n| `START` | New unified start block | Manual/API |\n| `API` | API endpoint trigger | API |\n| `STARTER` | Legacy starter block | Manual/API based on `startWorkflow` value |\n\n资料来源：[apps/sim/lib/workflows/triggers/triggers.ts:1-75]()\n\n## Block Executor\n\nThe block executor handles the actual execution of individual workflow blocks, managing their lifecycle from initialization through completion.\n\n### Execution Pipeline\n\n1. **Block Identification** - Resolve block type and configuration\n2. **Input Resolution** - Collect outputs from dependent blocks\n3. **Sandbox Preparation** - Set up isolated execution environment\n4. **Execution** - Run the block's logic\n5. **Output Capture** - Collect and store block results\n6. **State Update** - Update executor context with results\n\n### Block States\n\n```mermaid\nstateDiagram-v2\n    [*] --> Pending\n    Pending --> Running: executionStart\n    Running --> Completed: success\n    Running --> Failed: error\n    Running --> Cancelled: abortSignal\n    Completed --> [*]\n    Failed --> [*]\n    Cancelled --> [*]\n```\n\n### Async Tool Execution\n\nFor client-executable tools (running in the browser), the executor uses an async confirmation pattern:\n\n```typescript\nasync function reportCompletion(\n  toolCallId: string,\n  status: AsyncConfirmationStatus,\n  message?: string,\n  data?: AsyncCompletionData\n): Promise<void>\n```\n\n资料来源：[apps/sim/lib/copilot/tools/client/run-tool-execution.ts:1-50]()\n\nThe executor reports completion via the `/api/copilot/confirm` endpoint, which persists the durable async-tool row and wakes server-side waiters.\n\n## Parallel Orchestrator\n\nThe parallel orchestrator manages concurrent execution of independent blocks, maximizing throughput while respecting dependency constraints.\n\n### Concurrency Model\n\n```mermaid\ngraph LR\n    A[Block A] --> C[Block C]\n    B[Block B] --> C\n    A --> D[Block D]\n    B --> D\n    C --> E[Block E]\n    D --> E\n```\n\n### Configuration Options\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `maxConcurrency` | number | 10 | Maximum parallel block executions |\n| `timeout` | number | 300000 | Per-block execution timeout (ms) |\n| `failFast` | boolean | true | Stop on first failure |\n\n## Loop Orchestrator\n\nThe loop orchestrator handles iterative execution patterns, supporting standard loops and parallel-for constructs.\n\n### Loop Types\n\n| Loop Type | Description |\n|-----------|-------------|\n| `for` | Standard iteration over items |\n| `while` | Conditional iteration |\n| `parallel-for` | Concurrent iteration with result aggregation |\n\n### Loop Configuration\n\n```typescript\ninterface LoopConfig {\n  loopType: 'for' | 'while' | 'parallel-for'\n  iterations?: number\n  items?: any[]\n  condition?: string\n  maxConcurrency?: number\n}\n```\n\n资料来源：[apps/realtime/src/database/operations.ts:1-50]()\n\n### Loop Block Structure\n\n```typescript\ninterface LoopBlock {\n  id: string\n  type: 'loop'\n  config: LoopConfig\n  nodes: SerializedBlock[]  // Blocks inside the loop\n}\n```\n\nDefault loop configuration:\n\n```typescript\nconst DEFAULT_LOOP_ITERATIONS = 10\n```\n\n资料来源：[apps/realtime/src/database/operations.ts:1-50]()\n\n## Execution Context Factory\n\nThe testing framework provides factory functions for creating executor contexts with predefined states:\n\n### Core Factory Functions\n\n| Function | Purpose |\n|----------|---------|\n| `createExecutorContext()` | Creates a base executor context |\n| `createExecutorContextWithBlocks()` | Creates context with pre-executed blocks |\n| `addBlockState()` | Adds block state to existing context (chainable) |\n| `createMinimalWorkflow()` | Creates a minimal workflow for testing |\n\n### Usage Example\n\n```typescript\nconst ctx = createExecutorContextWithBlocks({\n  'source-block': { value: 10, text: 'hello' },\n  'other-block': { result: true }\n})\n```\n\n资料来源：[packages/testing/src/factories/executor-context.factory.ts:44-70]()\n\n## Error Handling & Resilience\n\n### Cancellation Guards\n\nThe executor implements SQL-level guards to prevent race conditions during state updates:\n\n```typescript\nconst cancellationGuard = bypassStaleWorker ? undefined : { groupId, executionId }\n```\n\n资料来源：[apps/sim/lib/table/cell-write.ts:1-40]()\n\n### Abort Signal Support\n\nAll executor operations respect `AbortSignal` for graceful cancellation:\n\n```typescript\ninterface ExecutorContext {\n  abortSignal?: AbortSignal\n}\n```\n\n### Skip Conditions\n\nThe executor skips writes under specific conditions to maintain consistency:\n\n| Condition | Action |\n|-----------|--------|\n| Same execution already running | Skip queued stamp |\n| Cancelled state with newer execution | Skip group write |\n| SQL guard conflict | Skip with logging |\n\n## Configuration Constants\n\n| Constant | Value | Description |\n|----------|-------|-------------|\n| `BLOCK_DIMENSIONS.MIN_HEIGHT` | 100 | Minimum block visual height |\n| `DEFAULT_LOOP_ITERATIONS` | 10 | Default loop iteration count |\n| `DEFAULT_TIMEOUT` | 300000 | Default block execution timeout |\n\n资料来源：[apps/sim/executor/constants](from mocks)\n\n## Extension Points\n\n### Custom Orchestrators\n\nThe orchestrator system is designed for extensibility. New orchestrators can be registered by implementing the `Orchestrator` interface:\n\n```typescript\ninterface Orchestrator {\n  execute(blocks: SerializedBlock[], context: ExecutorContext): Promise<void>\n  cancel(): void\n}\n```\n\n### Block Output Handlers\n\nBlock output handling can be customized through the `getEffectiveBlockOutputs` extension point.\n\n## Related Documentation\n\n- [Workflow Triggers](triggers.md) - Trigger system integration\n- [DAG Builder](dag-builder.md) - Graph construction details\n- [Execution API](../api/execution.md) - Runtime API reference\n- [Testing Utilities](../testing/executor.md) - Test factory documentation\n\n---\n\n<a id='workflow-blocks'></a>\n\n## Workflow Blocks System\n\n### 相关页面\n\n相关主题：[Integrations and Connectors](#integrations-connectors), [Workflow Executor Engine](#executor-engine)\n\n<details>\n<summary>Related Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [apps/sim/lib/workflows/triggers/triggers.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/triggers/triggers.ts)\n- [apps/sim/lib/workflows/triggers/trigger-utils.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/triggers/trigger-utils.ts)\n- [apps/sim/lib/workflows/subblocks/visibility.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/subblocks/visibility.ts)\n- [apps/sim/lib/workflows/blocks/block-reference-tags.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/blocks/block-reference-tags.ts)\n- [apps/sim/lib/execution/files.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/execution/files.ts)\n- [apps/sim/lib/copilot/tools/server/workflow/edit-workflow/builders.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/copilot/tools/server/workflow/edit-workflow/builders.ts)\n- [packages/workflow-persistence/src/load.ts](https://github.com/simstudioai/sim/blob/main/packages/workflow-persistence/src/load.ts)\n- [packages/testing/src/assertions/workflow.assertions.ts](https://github.com/simstudioai/sim/blob/main/packages/testing/src/assertions/workflow.assertions.ts)\n- [apps/realtime/src/database/operations.ts](https://github.com/simstudioai/sim/blob/main/apps/realtime/src/database/operations.ts)\n</details>\n\n# Workflow Blocks System\n\n## Overview\n\nThe Workflow Blocks System is the foundational architecture for building and executing automation workflows in the Sim platform. Blocks are the atomic units of execution that represent discrete operations, triggers, or control flow structures within a workflow. Each block encapsulates its own configuration, state, inputs, and outputs, allowing complex business logic to be constructed through visual composition or programmatically.\n\nThe system provides a declarative model where workflows are composed of interconnected blocks, with edges defining the data flow and execution order between them. This architecture enables both visual workflow design in the Sim editor and programmatic workflow manipulation through APIs.\n\n资料来源：[apps/sim/lib/copilot/tools/server/workflow/edit-workflow/builders.ts:1-50]()\n\n## Block Architecture\n\n### Core Components\n\nA block in the system consists of several key components:\n\n| Component | Description |\n|-----------|-------------|\n| `id` | Unique identifier for the block within a workflow |\n| `type` | The block type identifier (e.g., 'agent', 'trigger', 'loop') |\n| `name` | Display name shown in the UI |\n| `position` | Coordinates for visual placement (x, y) |\n| `enabled` | Boolean flag controlling whether the block executes |\n| `subBlocks` | Nested configuration objects with mode-based visibility |\n| `outputs` | Execution results produced by the block |\n| `data` | Arbitrary data associated with the block |\n| `metadata` | Additional metadata including block type references |\n\n资料来源：[packages/workflow-persistence/src/load.ts:20-45]()\n\n### Block State Model\n\nThe block state represents the complete runtime and configuration state of a block:\n\n```typescript\ninterface BlockState {\n  id: string\n  type: string\n  name: string\n  position: { x: number; y: number }\n  enabled: boolean\n  horizontalHandles: boolean\n  advancedMode: boolean\n  triggerMode: boolean\n  height: number\n  subBlocks: Record<string, SubBlockState>\n  outputs: Record<string, any>\n  data: Record<string, any>\n  locked: boolean\n}\n```\n\n资料来源：[packages/workflow-persistence/src/load.ts:18-35]()\n\n## Block Types\n\n### Trigger Blocks\n\nTrigger blocks initiate workflow execution and define how workflows can be started. The system supports multiple trigger types:\n\n| Trigger Type | Constant | Description |\n|--------------|----------|-------------|\n| Start | `TRIGGER_TYPES.START` | Primary entry point for workflows |\n| API | `TRIGGER_TYPES.API` | HTTP API triggered execution |\n| Chat | `TRIGGER_TYPES.CHAT` | Conversational trigger |\n| Manual | `TRIGGER_TYPES.MANUAL` | Manual invocation |\n| Input | `TRIGGER_TYPES.INPUT` | Input parameter trigger |\n| Webhook | `TRIGGER_TYPES.WEBHOOK` | Webhook-based triggers |\n| Schedule | `TRIGGER_TYPES.SCHEDULE` | Time-based triggers |\n| Generic Webhook | `TRIGGER_TYPES.GENERIC_WEBHOOK` | Universal webhook receiver |\n\n资料来源：[apps/sim/lib/workflows/triggers/triggers.ts:1-30]()\n\n### Control Flow Blocks\n\nControl flow blocks manage execution logic and flow:\n\n| Block Type | Purpose |\n|------------|---------|\n| `loop` | Iteration control (for loops) |\n| `parallel` | Parallel execution branches |\n\nThe loop block stores its configuration in a separate `workflowSubflows` table with structure:\n\n```typescript\n{\n  id: string\n  workflowId: string\n  type: 'loop'\n  config: {\n    loopType: 'for'\n    iterations: number\n    nodes: string[]\n  }\n}\n```\n\n资料来源：[apps/realtime/src/database/operations.ts:1-40]()\n\n### SubBlock Modes\n\nSubBlocks support different visibility modes that control their appearance in the UI:\n\n| Mode | Behavior |\n|------|----------|\n| `basic` | Shown in basic mode, hidden in advanced mode |\n| `advanced` | Shown in advanced mode, hidden in basic mode |\n| `trigger` | Visible only when trigger mode is enabled |\n| `trigger-advanced` | Visible in trigger mode with advanced options |\n\nThe visibility logic is implemented in the `shouldUseSubBlockForTriggerModeCanonicalIndex` function:\n\n```typescript\nexport function isTriggerModeSubBlock(subBlock: Pick<SubBlockConfig, 'mode'>): boolean {\n  return subBlock.mode === 'trigger' || subBlock.mode === 'trigger-advanced'\n}\n\nexport function isTriggerConfigSubBlock(subBlock: Pick<SubBlockConfig, 'type'>): boolean {\n  return String(subBlock.type) === 'trigger-config'\n}\n```\n\n资料来源：[apps/sim/lib/workflows/subblocks/visibility.ts:1-35]()\n\n## Trigger System\n\n### Trigger Classification\n\nThe trigger system classifies blocks based on their execution context:\n\n```mermaid\ngraph TD\n    A[Block Type] --> B{is Trigger Block?}\n    B -->|Yes| C[Explicit Trigger]\n    B -->|No| D{has triggerMode?}\n    D -->|Yes| E[Tool with Trigger]\n    D -->|No| F[Regular Block]\n```\n\nThe `TriggerUtils` class provides static methods for trigger identification:\n\n```typescript\nexport class TriggerUtils {\n  static isTriggerBlock(block: { type: string; triggerMode?: boolean }): boolean {\n    const blockConfig = getBlock(block.type)\n    return (\n      blockConfig?.category === 'triggers' ||\n      block.triggerMode === true ||\n      block.type === TRIGGER_TYPES.STARTER\n    )\n  }\n\n  static isTriggerType(block: { type: string }, triggerType: TriggerType): boolean {\n    return block.type === triggerType\n  }\n}\n```\n\n资料来源：[apps/sim/lib/workflows/triggers/triggers.ts:80-100]()\n\n### Start Block Resolution\n\nThe system uses a priority-based approach to resolve start candidates for workflow execution:\n\n```mermaid\ngraph TD\n    A[Blocks Collection] --> B[Filter Disabled Blocks]\n    B --> C[Classify Start Block Path]\n    C --> D{Is Child Workflow?}\n    D -->|Yes| E[Apply CHILD_PRIORITIES]\n    D -->|No| F[Apply EXECUTION_PRIORITIES]\n    E --> G[Return Sorted Candidates]\n    F --> G\n```\n\nThe `resolveStartCandidates` function implements this logic:\n\n```typescript\nexport function resolveStartCandidates<T extends MinimalBlock>(\n  blocks: Record<string, T> | T[],\n  options: ResolveStartOptions\n): StartBlockCandidate<T>[] {\n  const entries = toEntries(blocks)\n  if (entries.length === 0) return []\n\n  const priorities = options.isChildWorkflow\n    ? CHILD_PRIORITIES\n    : EXECUTION_PRIORITIES[options.execution]\n  \n  // ... filtering and candidate creation logic\n}\n```\n\n资料来源：[apps/sim/lib/workflows/triggers/triggers.ts:150-180]()\n\n### Trigger Reference Aliases\n\nThe system maps reference aliases to concrete trigger types:\n\n```typescript\nexport const TRIGGER_REFERENCE_ALIAS_MAP = {\n  start: TRIGGER_TYPES.START,\n  api: TRIGGER_TYPES.API,\n  chat: TRIGGER_TYPES.CHAT,\n  manual: TRIGGER_TYPES.START,\n} as const\n```\n\nThese aliases are used in inline references like `<api.*>`, `<chat.*>`, enabling flexible trigger referencing within workflows.\n\n资料来源：[apps/sim/lib/workflows/triggers/triggers.ts:60-68]()\n\n## Block Configuration\n\n### SubBlock Structure\n\nSubBlocks allow nested configuration within blocks:\n\n```typescript\nexport function applyTriggerConfigToBlockSubblocks(\n  block: any, \n  triggerConfig: Record<string, any>\n) {\n  if (!block?.subBlocks || !triggerConfig) return\n\n  Object.entries(triggerConfig).forEach(([configKey, configValue]) => {\n    const existingSubblock = block.subBlocks[configKey]\n    if (existingSubblock) {\n      // Compare values to avoid unnecessary updates\n      const valuesEqual = /* comparison logic */\n      \n      if (!valuesEqual) {\n        block.subBlocks[configKey] = {\n          ...existingSubblock,\n          value: configValue,\n        }\n      }\n    } else {\n      // Create new subblock\n      block.subBlocks[configKey] = { /* new subblock */ }\n    }\n  })\n}\n```\n\n资料来源：[apps/sim/lib/copilot/tools/server/workflow/edit-workflow/builders.ts:60-95]()\n\n### Trigger Mode Visibility\n\nThe system determines which blocks appear in different toolbar sections:\n\n```mermaid\ngraph TD\n    A[All Blocks] --> B{Is Hidden?}\n    B -->|Yes| C[Exclude]\n    B -->|No| D{Category === 'triggers'?}\n    D -->|Yes| E[Include in Triggers Tab]\n    D -->|No| F{Has Trigger Capability?}\n    F -->|Yes| G[Include in Both Tabs]\n    F -->|No| H[Include in Blocks Tab]\n```\n\nFunctions `getTriggersForSidebar()` and `getBlocksForSidebar()` implement this filtering logic, excluding blocks with `hideFromToolbar: true` and treating blocks with trigger capability differently from those with explicit trigger category.\n\n资料来源：[apps/sim/lib/workflows/triggers/trigger-utils.ts:1-40]()\n\n## Block Reference Tags\n\nBlock tags control how blocks are referenced in the system:\n\n```typescript\nexport function getBlockTags(block: BlockConfig): string[] {\n  const normalizedBlockName = /* normalization logic */\n  let blockTags = allTags\n\n  const shouldShowRootTag =\n    block.type === TRIGGER_TYPES.GENERIC_WEBHOOK || \n    block.type === 'start_trigger'\n  \n  if (!shouldShowRootTag) {\n    blockTags = blockTags.filter((tag) => tag !== normalizedBlockName)\n  }\n\n  return blockTags\n}\n```\n\n资料来源：[apps/sim/lib/workflows/blocks/block-reference-tags.ts:1-30]()\n\n## File Input Processing\n\nBlocks can handle file inputs through a specialized processing system:\n\n```typescript\nexport async function processInputFileFields(\n  input: unknown,\n  blocks: SerializedBlock[],\n  executionContext: { workspaceId: string; workflowId: string; executionId: string },\n  requestId: string,\n  userId?: string\n): Promise<unknown> {\n  // Find start block to extract input format\n  const startBlock = blocks.find((block) => {\n    const blockType = block.metadata?.id\n    return (\n      blockType === TRIGGER_TYPES.START ||\n      blockType === TRIGGER_TYPES.API ||\n      blockType === TRIGGER_TYPES.INPUT ||\n      blockType === TRIGGER_TYPES.GENERIC_WEBHOOK ||\n      blockType === TRIGGER_TYPES.STARTER\n    )\n  })\n\n  // Process file fields from input format\n  const fileFields = inputFormat.filter((field) => field.type === 'file[]')\n  // ... file processing logic\n}\n```\n\n资料来源：[apps/sim/lib/execution/files.ts:1-60]()\n\n## Persistence Layer\n\n### Database Schema\n\nBlock data is persisted using a hybrid approach:\n\n| Table | Purpose |\n|-------|---------|\n| `workflowBlocks` | Core block configuration and state |\n| `workflowSubflows` | Loop and parallel block specific configs |\n| `workflowEdges` | Connections between blocks |\n\nThe upsert operation for blocks:\n\n```typescript\nawait tx\n  .insert(workflowBlocks)\n  .values(blockValues)\n  .onConflictDoUpdate({\n    target: workflowBlocks.id,\n    set: {\n      type: sql`excluded.type`,\n      name: sql`excluded.name`,\n      positionX: sql`excluded.position_x`,\n      positionY: sql`excluded.position_y`,\n      enabled: sql`excluded.enabled`,\n      subBlocks: sql`excluded.sub_blocks`,\n      outputs: sql`excluded.outputs`,\n      data: sql`excluded.data`,\n      updatedAt: sql`now()`,\n    },\n  })\n```\n\n资料来源：[apps/realtime/src/database/operations.ts:1-50]()\n\n### Loading and Assembly\n\nWhen loading a workflow, blocks are assembled from database records:\n\n```typescript\nblocks.forEach((block) => {\n  const blockData = (block.data ?? {}) as BlockState['data']\n\n  const assembled: BlockState = {\n    id: block.id,\n    type: block.type,\n    name: block.name,\n    position: {\n      x: Number(block.positionX),\n      y: Number(block.positionY),\n    },\n    enabled: block.enabled,\n    subBlocks: (block.subBlocks as BlockState['subBlocks']) || {},\n    outputs: (block.outputs as BlockState['outputs']) || {},\n    data: blockData,\n    locked: block.locked,\n  }\n\n  blocksMap[block.id] = assembled\n})\n```\n\nSubflows (loops and parallels) are loaded separately:\n\n```typescript\nsubflows.forEach((subflow) => {\n  const config = (subflow.config ?? {}) as Partial<Loop & Parallel>\n\n  if (subflow.type === SUBFLOW_TYPES.LOOP) {\n    loops[subflow.id] = config as Loop\n  } else if (subflow.type === SUBFLOW_TYPES.PARALLEL) {\n    parallels[subflow.id] = config as Parallel\n  }\n})\n```\n\n资料来源：[packages/workflow-persistence/src/load.ts:40-80]()\n\n## Testing Infrastructure\n\n### Block Assertions\n\nThe testing package provides assertion utilities for workflow validation:\n\n```typescript\nexport function expectBlockEnabled(\n  blocks: Record<string, any>, \n  blockId: string\n): void {\n  const block = blocks[blockId]\n  expect(block, `Block \"${blockId}\" should exist`).toBeDefined()\n  expect(block.enabled, `Block \"${blockId}\" should be enabled`).toBe(true)\n}\n\nexport function expectBlockPosition(\n  blocks: Record<string, any>,\n  blockId: string,\n  expectedPosition: { x: number; y: number }\n): void {\n  const block = blocks[blockId]\n  expect(block, `Block \"${blockId}\" should exist`).toBeDefined()\n  expect(block.position.x, `Block \"${blockId}\" x position`)\n    .toBeCloseTo(expectedPosition.x, 0)\n  expect(block.position.y, `Block \"${blockId}\" y position`)\n    .toBeCloseTo(expectedPosition.y, 0)\n}\n```\n\n资料来源：[packages/testing/src/assertions/workflow.assertions.ts:1-60]()\n\n### Workflow Factories\n\nTest utilities create standard workflow structures:\n\n```typescript\nexport function createLinearWorkflow(\n  blockCount: number, \n  spacing = 200\n): any {\n  const blocks: Record<string, any> = {}\n  const blockIds: string[] = []\n\n  for (let i = 0; i < blockCount; i++) {\n    const id = `block-${i}`\n    blockIds.push(id)\n\n    if (i === 0) {\n      blocks[id] = createStarterBlock({ id, position: { x: i * spacing, y: 0 } })\n    } else {\n      blocks[id] = createFunctionBlock({ id, name: `Step ${i}`, position: { x: i * spacing, y: 0 } })\n    }\n  }\n\n  return createWorkflowState({ blocks, edges: createLinearEdges(blockIds) })\n}\n```\n\n资料来源：[packages/testing/src/factories/workflow.factory.ts:1-40]()\n\n## Summary\n\nThe Workflow Blocks System provides a comprehensive foundation for building automation workflows through:\n\n1. **Declarative Block Model**: Each block encapsulates its own configuration, state, and outputs\n2. **Flexible Trigger System**: Multiple trigger types support various execution entry points\n3. **Mode-Based Visibility**: SubBlocks can be shown/hidden based on basic, advanced, or trigger modes\n4. **Persistent State**: Blocks are persisted to the database with proper upsert semantics\n5. **Type-Safe Testing**: Comprehensive assertion utilities enable robust workflow testing\n\nThe architecture separates concerns between block definition, execution, persistence, and testing, enabling a clean and maintainable codebase for workflow automation.\n\n---\n\n<a id='integrations-connectors'></a>\n\n## Integrations and Connectors\n\n### 相关页面\n\n相关主题：[Workflow Blocks System](#workflow-blocks), [Background Jobs and Background Processing](#background-jobs)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [apps/sim/connectors/registry.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/connectors/registry.ts)\n- [apps/sim/connectors/slack/slack.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/connectors/slack/slack.ts)\n- [apps/sim/connectors/github/github.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/connectors/github/github.ts)\n- [apps/sim/connectors/types.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/connectors/types.ts)\n- [apps/sim/lib/api/contracts/tools/communication/slack.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/api/contracts/tools/communication/slack.ts)\n- [apps/sim/lib/webhooks/providers/gong.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/webhooks/providers/gong.ts)\n- [apps/sim/lib/webhooks/providers/vercel.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/webhooks/providers/vercel.ts)\n- [apps/sim/lib/copilot/vfs/workspace-vfs.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/copilot/vfs/workspace-vfs.ts)\n- [apps/sim/lib/workflows/triggers/triggers.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/triggers/triggers.ts)\n- [apps/sim/lib/api/contracts/types.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/api/contracts/types.ts)\n</details>\n\n# Integrations and Connectors\n\n## Overview\n\nSim provides a comprehensive integrations and connectors system that enables AI agents to interact with external services, APIs, and platforms. This system forms the backbone of Sim's workflow automation capabilities, allowing users to connect 1,000+ integrations and LLMs to orchestrate agentic workflows.\n\nThe connector architecture is designed around a plugin-based system where each integration is implemented as a self-contained module with standardized interfaces for authentication, API communication, and data transformation.\n\n## Architecture\n\nThe Sim integration system consists of several interconnected layers:\n\n```mermaid\ngraph TD\n    A[Workflows / Agents] --> B[Trigger System]\n    B --> C[Connectors Registry]\n    C --> D[Individual Connectors]\n    D --> E[Slack Connector]\n    D --> F[GitHub Connector]\n    D --> G[Custom Connectors]\n    A --> H[Webhook Providers]\n    H --> I[Gong Webhook]\n    H --> J[Vercel Webhook]\n    C --> K[API Contracts]\n    K --> L[Type Definitions]\n    D --> M[External APIs]\n```\n\n### Core Components\n\n| Component | Purpose | Location |\n|-----------|---------|----------|\n| Connectors Registry | Central hub for managing all connector instances | `apps/sim/connectors/registry.ts` |\n| Type Definitions | Shared interfaces and types for connectors | `apps/sim/connectors/types.ts` |\n| API Contracts | Zod schemas defining API request/response shapes | `apps/sim/lib/api/contracts/types.ts` |\n| Trigger System | Event-driven connector activation | `apps/sim/lib/workflows/triggers/triggers.ts` |\n| Webhook Providers | Inbound integration handlers | `apps/sim/lib/webhooks/providers/` |\n\n## Connector Registry\n\nThe connector registry (`apps/sim/connectors/registry.ts`) serves as the central management system for all connectors in the platform. It provides:\n\n- Registration and lookup of connector instances\n- Configuration management for each connector\n- Lifecycle management (initialize, authenticate, execute, cleanup)\n- Unified interface for accessing connector functionality\n\n```mermaid\ngraph LR\n    A[Request] --> B[Registry Lookup]\n    B --> C{Connector Found?}\n    C -->|Yes| D[Execute Connector]\n    C -->|No| E[Return Error]\n    D --> F[Transform Response]\n    F --> G[Return to Caller]\n```\n\n## Trigger System\n\nTriggers work in conjunction with connectors to activate workflows based on external events. The trigger system classifies different activation modes:\n\n```mermaid\ngraph TD\n    A[Block] --> B{Start Workflow Mode}\n    B -->|chat| C[Chat Trigger]\n    B -->|api| D[API Trigger]\n    B -->|run| E[API Trigger]\n    B -->|manual| F[Manual Trigger]\n    B -->|undefined| F\n```\n\n### Trigger Types\n\n| Trigger Type | Classification | Use Case |\n|--------------|----------------|----------|\n| `start` | Manual/API | Initial workflow activation |\n| `api` | API-based | Programmatic workflow execution |\n| `chat` | Conversational | Chat-initiated workflows |\n| `manual` | User-initiated | Manual workflow triggers |\n\nThe trigger reference alias map provides convenient access to trigger types:\n\n```typescript\nexport const TRIGGER_REFERENCE_ALIAS_MAP = {\n  start: TRIGGER_TYPES.START,\n  api: TRIGGER_TYPES.API,\n  chat: TRIGGER_TYPES.CHAT,\n  manual: TRIGGER_TYPES.START,\n} as const\n```\n资料来源：[apps/sim/lib/workflows/triggers/triggers.ts:32-37]()\n\n## Webhook Providers\n\nSim integrates with external services through webhook providers that normalize incoming events into a standardized format.\n\n### Gong Webhook Integration\n\nThe Gong webhook provider handles call recording and analytics data:\n\n```typescript\ninterface GongWebhookPayload {\n  callId: string\n  metaData: Record<string, unknown>\n  parties: unknown[]\n  context: unknown[]\n  trackers: unknown[]\n  topics: unknown[]\n  highlights: unknown[]\n  eventType: 'gong.automation_rule'\n}\n```\n资料来源：[apps/sim/lib/webhooks/providers/gong.ts:1-15]()\n\n### Vercel Webhook Integration\n\nThe Vercel webhook provider processes deployment events with comprehensive metadata extraction:\n\n```typescript\ninterface VercelDeploymentData {\n  id: string\n  url: string\n  name: string\n  meta: Record<string, unknown>\n  project?: {\n    id: string\n    name: string\n  }\n  team?: {\n    id: string\n  }\n  user?: {\n    id: string\n  }\n  target?: string\n  plan?: string\n}\n```\n资料来源：[apps/sim/lib/webhooks/providers/vercel.ts:25-40]()\n\n## Slack Integration\n\nSlack is a first-class citizen in Sim's connector ecosystem, with comprehensive API contract definitions:\n\n### Slack API Contracts\n\n| Contract | Purpose | Response Type |\n|----------|---------|---------------|\n| `slackReadMessagesContract` | Fetch messages from channels | `SlackReadMessagesResponse` |\n| `slackAddReactionContract` | Add reactions to messages | `SlackReactionResponse` |\n| `slackDeleteMessageContract` | Delete messages | `SlackDeleteMessageResponse` |\n| `slackUpdateMessageContract` | Edit existing messages | `SlackUpdateMessageResponse` |\n| `slackSendEphemeralContract` | Send ephemeral messages | `SlackSendEphemeralResponse` |\n| `slackDownloadContract` | Download files/content | `SlackDownloadResponse` |\n\n```typescript\nexport type SlackReadMessagesResponse = ContractJsonResponse<typeof slackReadMessagesContract>\nexport type SlackReactionResponse = ContractJsonResponse<typeof slackAddReactionContract>\nexport type SlackDeleteMessageResponse = ContractJsonResponse<typeof slackDeleteMessageContract>\nexport type SlackUpdateMessageResponse = ContractJsonResponse<typeof slackUpdateMessageContract>\nexport type SlackSendEphemeralResponse = ContractJsonResponse<typeof slackSendEphemeralContract>\nexport type SlackDownloadResponse = ContractJsonResponse<typeof slackDownloadContract>\n```\n资料来源：[apps/sim/lib/api/contracts/tools/communication/slack.ts:1-10]()\n\n## API Contract System\n\nThe API contract system uses Zod schemas for runtime validation of all API interactions:\n\n### Contract Type Utilities\n\n```typescript\nexport type ContractParams<C extends AnyApiRouteContract> = C extends ApiRouteContract<\n  infer TParams,\n  ApiSchema | undefined,\n  ApiSchema | undefined,\n  ApiSchema | undefined,\n  ResponseMode,\n  ApiSchema | undefined\n>\n  ? EmptySchemaOutput<TParams>\n  : undefined\n\nexport type ContractBody<C extends AnyApiRouteContract> = C extends ApiRouteContract<\n  ApiSchema | undefined,\n  ApiSchema | undefined,\n  infer TBody,\n  ApiSchema | undefined,\n  ResponseMode,\n  ApiSchema | undefined\n>\n  ? EmptySchemaOutput<TBody>\n  : undefined\n```\n资料来源：[apps/sim/lib/api/contracts/types.ts:1-30]()\n\n### Generic Contract Types\n\n| Type | Description |\n|------|-------------|\n| `ContractParams<C>` | Extracted URL parameter types from contract |\n| `ContractQuery<C>` | Extracted query string types from contract |\n| `ContractBody<C>` | Extracted request body types from contract |\n| `ContractHeaders<C>` | Extracted header types from contract |\n| `ContractParamsInput<C>` | Input types for contract parameters |\n\n## Virtual Filesystem Integration\n\nConnectors are exposed to AI agents through the virtual filesystem (VFS), which materializes workspace data into an in-memory file system structure:\n\n```mermaid\ngraph TD\n    A[Workspace] --> B[Virtual Filesystem]\n    B --> C[workflows/{name}/meta.json]\n    B --> D[workflows/{name}/state.json]\n    B --> E[workflows/{name}/executions.json]\n    B --> F[knowledgebases/{name}/meta.json]\n    B --> G[connectors.json]\n    B --> H[triggers/{id}.json]\n```\n\nThe VFS exposes connector configurations to agents:\n\n```typescript\nfiles.set(\n  'knowledgebases/{name}/connectors.json',\n  serializeConnectorConfigs(connectorConfigs)\n)\n```\n资料来源：[apps/sim/lib/copilot/vfs/workspace-vfs.ts:1-50]()\n\n## Connector Configuration\n\nConnectors follow a standardized configuration schema defined in `apps/sim/connectors/types.ts`. Each connector instance includes:\n\n- **Provider**: The external service name (e.g., `slack`, `github`)\n- **Credentials**: Authentication tokens and secrets\n- **Settings**: Connector-specific configuration options\n- **Metadata**: Display name, description, category\n\n## Adding New Connectors\n\nTo add a new connector to the Sim platform:\n\n1. Create a new directory under `apps/sim/connectors/{provider}/`\n2. Implement the connector class with required interface methods\n3. Register the connector in the registry\n4. Define API contracts in `apps/sim/lib/api/contracts/`\n5. Add webhook handler if inbound events are needed\n6. Update the VFS serialization logic if agent access is required\n\n## Best Practices\n\n- Always use API contracts for type-safe API calls\n- Implement proper error handling and retry logic\n- Store credentials securely (never commit to repository)\n- Follow the trigger classification pattern for event-driven workflows\n- Use the virtual filesystem for any data that should be accessible to agents\n\n---\n\n<a id='agent-system'></a>\n\n## Agent System\n\n### 相关页面\n\n相关主题：[Copilot System](#copilot-system), [Workflow Blocks System](#workflow-blocks)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [apps/sim/executor/handlers/agent/agent-handler.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/executor/handlers/agent/agent-handler.ts)\n- [apps/sim/executor/handlers/agent/memory.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/executor/handlers/agent/memory.ts)\n- [apps/sim/executor/handlers/agent/skills-resolver.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/executor/handlers/agent/skills-resolver.ts)\n- [apps/sim/executor/handlers/agent/types.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/executor/handlers/agent/types.ts)\n- [apps/sim/blocks/blocks/agent.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/blocks/blocks/agent.ts)\n</details>\n\n# Agent System\n\nThe Agent System is a core component of the Sim platform that enables the execution of AI agents within workflow automation. It provides the infrastructure for creating, managing, and executing agents that can interact with tools, maintain conversation context, and process complex multi-step tasks.\n\n## Overview\n\nThe Agent System serves as the execution layer for AI-driven automation within Sim workflows. It handles the lifecycle of agent execution, including initialization, tool invocation, state management, memory handling, and result processing.\n\n### Core Responsibilities\n\n- **Agent Execution Pipeline**: Orchestrates the execution of agent logic within workflow contexts\n- **Memory Management**: Maintains conversation history and context across agent interactions\n- **Skills Resolution**: Resolves and binds available skills and tools to agent instances\n- **State Coordination**: Manages agent state transitions and execution checkpoints\n- **Tool Integration**: Handles the invocation and management of external tools and APIs\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[Workflow Engine] --> B[Agent Handler]\n    B --> C[Memory Manager]\n    B --> D[Skills Resolver]\n    B --> E[Tool Executor]\n    C --> F[Context Store]\n    D --> G[Block Registry]\n    E --> H[Execution Context]\n    H --> I[Streaming Response]\n    F --> H\n```\n\n## Agent Handler\n\nThe `agent-handler.ts` serves as the primary orchestrator for agent execution. It manages the interaction between the workflow engine and the agent's internal components.\n\n### Key Functions\n\n| Function | Purpose | Source |\n|----------|---------|--------|\n| `handleAgentExecution` | Main entry point for agent processing | [agent-handler.ts]() |\n| `executeToolAndReport` | Invokes tools and streams results back | [tool.ts:52]() |\n| `registerPendingToolPromise` | Tracks async tool executions | [tool.ts:45]() |\n| `abortPendingToolIfStreamDead` | Handles stalled tool executions | [tool.ts:66]() |\n\n### Execution Flow\n\n```mermaid\nsequenceDiagram\n    participant Workflow\n    participant AgentHandler\n    participant ToolExecutor\n    participant Memory\n    participant SkillsResolver\n\n    Workflow->>AgentHandler: Execute Agent\n    AgentHandler->>SkillsResolver: Resolve Available Skills\n    SkillsResolver-->>AgentHandler: Skill Bindings\n    AgentHandler->>Memory: Initialize Context\n    Memory-->>AgentHandler: Context State\n    AgentHandler->>ToolExecutor: Invoke Tool\n    ToolExecutor-->>AgentHandler: Tool Result\n    AgentHandler->>Memory: Update State\n    AgentHandler-->>Workflow: Execution Result\n```\n\n### Tool Execution Modes\n\nThe agent handler supports multiple execution modes for tool invocation:\n\n| Mode | Description | Configuration |\n|------|-------------|---------------|\n| `autoExecuteTools` | Automatically execute tools without user confirmation | `options.autoExecuteTools !== false` |\n| `interactive` | Require user confirmation before tool execution | `options.interactive === true` |\n| `parallel` | Execute multiple tools concurrently | Parallel promise registration |\n| `clientExecutable` | Delegate execution to client workflow | `clientExecutable === true` |\n\n## Memory System\n\nThe Memory System (`memory.ts`) maintains conversation context and execution history for agents, enabling stateful interactions across multiple workflow steps.\n\n### Memory Operations\n\n```typescript\ninterface AgentMemory {\n  conversationHistory: ConversationTurn[]\n  executionContext: Record<string, any>\n  blockOutputs: Map<string, BlockOutput>\n  timestamps: MemoryTimestamps\n}\n```\n\n### Context Management\n\n| Operation | Description | Source Reference |\n|-----------|-------------|------------------|\n| Store Turn | Save a conversation interaction | [memory.ts]() |\n| Retrieve Context | Load previous state for agent | [memory.ts]() |\n| Clear Memory | Reset context for new session | [memory.ts]() |\n| Merge Context | Combine multiple context sources | [memory.ts]() |\n\n## Skills Resolver\n\nThe Skills Resolver (`skills-resolver.ts`) binds available tools and capabilities to agent instances based on workflow configuration and agent requirements.\n\n### Resolution Process\n\n1. **Skill Discovery**: Scan available tool registry for compatible skills\n2. **Capability Matching**: Match agent requirements with available tools\n3. **Binding**: Create stable references between agent and tools\n4. **Validation**: Verify all required skills are available\n\n### Skill Configuration\n\n```typescript\ninterface SkillBinding {\n  skillId: string\n  toolName: string\n  parameters: SkillParameters\n  enabled: boolean\n  priority: number\n}\n```\n\n## Type System\n\nThe Agent System defines comprehensive TypeScript types in `types.ts` to ensure type safety across all components.\n\n### Core Types\n\n| Type | Description | Usage |\n|------|-------------|-------|\n| `StreamingContext` | Manages streaming response state | Tool execution tracking |\n| `ExecutionContext` | Holds runtime execution data | Block state, outputs |\n| `OrchestratorOptions` | Configuration for agent behavior | Execution parameters |\n| `ToolScope` | Defines execution scope | `main` or `subagent` |\n| `ToolCallState` | Tracks individual tool call status | Execution monitoring |\n\n### Tool Call States\n\n```mermaid\nstateDiagram-v2\n    [*] --> pending: Tool Call Created\n    pending --> executing: Execution Started\n    executing --> success: Completed Successfully\n    executing --> error: Execution Failed\n    executing --> cancelled: User Cancelled\n    success --> skipped: Result Not Needed\n    error --> retry: Retry Attempt\n```\n\n## Agent Block Definition\n\nThe Agent Block (`agent.ts`) defines the block-level configuration and metadata for agents within the Sim workflow system.\n\n### Block Structure\n\n```typescript\ninterface AgentBlockConfig {\n  name: string\n  description: string\n  category: BlockCategory\n  inputs: InputSpecification[]\n  outputs: OutputSpecification[]\n  parameters: AgentParameters\n}\n```\n\n### Block Categories\n\n| Category | Description | Example Usage |\n|----------|-------------|---------------|\n| `agent` | Primary agent implementation | Main workflow agent |\n| `subagent` | Nested agent for delegation | Specialized task agents |\n| `client` | Client-delegated execution | External system integration |\n\n## Execution Context Factory\n\nThe `executor-context.factory.ts` provides utilities for creating and manipulating executor contexts used throughout the agent system.\n\n### Factory Functions\n\n| Function | Purpose | Source |\n|----------|---------|--------|\n| `createExecutorContext` | Initialize new execution context | [executor-context.factory.ts]() |\n| `createExecutorContextWithBlocks` | Create context with pre-executed blocks | [executor-context.factory.ts]() |\n| `addBlockState` | Add block state to existing context | [executor-context.factory.ts]() |\n| `createMinimalWorkflow` | Create workflow for context | [executor-context.factory.ts]() |\n\n### Executor Context Structure\n\n```typescript\ninterface ExecutorContext {\n  blockStates: Map<string, ExecutorBlockState>\n  executedBlocks: Set<string>\n  workflow: SerializedWorkflow\n  connections: SerializedConnection[]\n  requestId: string\n  abortSignal?: AbortSignal\n}\n```\n\n## Tool Execution Pipeline\n\n```mermaid\ngraph LR\n    A[Tool Call Request] --> B{Interactive Mode?}\n    B -->|Yes| C{Client Executable?}\n    B -->|No| D{Auto Execute?}\n    C -->|Workflow Tool| E[Delegate to Client]\n    C -->|Sim Executed| F[Execute Tool]\n    D -->|Yes| G[Fire Tool Execution]\n    D -->|No| H[Wait for Confirmation]\n    E --> I[Update Tool State]\n    F --> I\n    G --> I\n    H --> I\n    I --> J[Report Result]\n    J --> K[Update Memory]\n```\n\n### Result Handling\n\nThe agent system handles multiple outcome types for tool executions:\n\n| Outcome | Status | Description |\n|---------|--------|-------------|\n| `success` | Completed successfully | Tool executed without errors |\n| `error` | Execution failed | Tool encountered an error |\n| `cancelled` | User cancelled | Execution was manually stopped |\n| `skipped` | Not needed | Result was no longer required |\n\n## Configuration Options\n\n### Orchestrator Options\n\n```typescript\ninterface OrchestratorOptions {\n  interactive?: boolean        // Require user confirmation\n  autoExecuteTools?: boolean   // Auto-execute without prompt\n  abortSignal?: AbortSignal    // Cancellation token\n  timeout?: number             // Execution timeout\n}\n```\n\n### Streaming Context\n\n```typescript\ninterface StreamingContext {\n  requestId: string\n  toolCalls: Map<string, ToolCallState>\n  pendingPromises: Map<string, Promise<ToolResult>>\n  onToolResult?: (result: ToolResult) => void\n}\n```\n\n## Error Handling\n\nThe agent system implements comprehensive error handling across all execution paths:\n\n1. **Tool Execution Errors**: Caught and wrapped in standard error format\n2. **Stream Dead Detection**: Aborts pending tools when stream becomes unresponsive\n3. **Timeout Handling**: Respects abort signals for long-running operations\n4. **State Validation**: Ensures consistency before state transitions\n\n### Error Response Format\n\n```typescript\ninterface ToolErrorResponse {\n  status: MothershipStreamV1ToolOutcome.error\n  message: string\n  data: {\n    error: string\n  }\n}\n```\n\n## Integration Points\n\nThe Agent System integrates with multiple platform components:\n\n| Component | Integration Type | Data Flow |\n|-----------|------------------|-----------|\n| Workflow Engine | Parent orchestrator | Initializes agent execution |\n| Block Registry | Tool resolution | Discovers available skills |\n| Memory Store | State persistence | Maintains conversation history |\n| Webhook Providers | External triggers | Receives external events |\n| Billing System | Usage tracking | Records execution metrics |\n\n## Testing\n\nThe Agent System includes comprehensive test coverage in `agent-handler.test.ts` and related test files, covering:\n\n- Tool execution scenarios (success, failure, cancellation)\n- Memory state management\n- Skills resolution logic\n- Streaming response handling\n- Error propagation paths\n\n---\n\n<a id='copilot-system'></a>\n\n## Copilot System\n\n### 相关页面\n\n相关主题：[Agent System](#agent-system), [Architecture Overview](#architecture-overview)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [apps/sim/lib/copilot/generated/trace-spans-v1.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/copilot/generated/trace-spans-v1.ts)\n- [README.md](https://github.com/simstudioai/sim/blob/main/README.md)\n- [apps/sim/package.json](https://github.com/simstudioai/sim/blob/main/apps/sim/package.json)\n- [apps/sim/lib/workflows/diff/diff-engine.test.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/diff/diff-engine.test.ts)\n- [apps/sim/lib/api/contracts/types.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/api/contracts/types.ts)\n</details>\n\n# Copilot System\n\nThe Copilot System is a Sim-managed AI-powered service that enables users to generate workflow nodes, fix errors, and iterate on flows directly from natural language instructions. It serves as an intelligent assistant embedded within the Sim platform, providing real-time assistance for workflow creation and modification.\n\n## Overview\n\nCopilot acts as an intelligent layer between users and the workflow engine, translating natural language inputs into executable workflow components. The system leverages large language models to understand user intent and generate appropriate code blocks, connections, and configurations within the Sim workflow environment.\n\n### Key Capabilities\n\n| Capability | Description |\n|------------|-------------|\n| Node Generation | Create new workflow blocks from natural language descriptions |\n| Error Resolution | Identify and fix issues in existing workflows |\n| Flow Iteration | Modify and improve workflow structures through conversational commands |\n| Analytics Tracking | Monitor all Copilot operations for performance and billing |\n\n## Architecture\n\nThe Copilot System consists of multiple API endpoints and tracking components that work together to provide a seamless AI-assisted experience.\n\n```mermaid\ngraph TD\n    A[User Input] --> B[Copilot API Layer]\n    B --> C[Chat Stream Route]\n    B --> D[Checkpoints Route]\n    B --> E[Models Route]\n    B --> F[Training Route]\n    C --> G[Trace Span Tracking]\n    G --> H[Analytics Collection]\n    H --> I[Billing System]\n```\n\n## API Endpoints\n\nThe Copilot System exposes several REST API endpoints for different operations:\n\n### Chat Stream Endpoint\n\nHandles real-time streaming of chat responses for Copilot interactions. This endpoint manages the bidirectional communication between the client and the AI model, providing immediate feedback as the Copilot processes natural language requests.\n\n### Checkpoints Route\n\nProvides functionality for saving and retrieving workflow checkpoints during Copilot-assisted editing. This allows users to maintain version history and revert to previous states if needed.\n\n### Models Route\n\nManages the available AI models that power Copilot functionality. The system supports multiple model configurations and allows for dynamic model selection based on task requirements.\n\n### Training Route\n\nHandles model fine-tuning and custom training workflows. This endpoint enables the system to learn from user interactions and improve response accuracy over time.\n\n## Trace Span Instrumentation\n\nThe Copilot System implements comprehensive OpenTelemetry trace spans for observability and monitoring. All trace span identifiers are defined in a generated contract file that ensures type safety and consistency between the frontend and backend.\n\n### Trace Span Categories\n\n| Category | Spans | Purpose |\n|----------|-------|---------|\n| Chat Operations | `chat.*` | Track conversation flow and tool usage |\n| Analytics | `copilot.analytics.*` | Monitor request metrics and billing |\n| Context Management | `context.*` | Track context window operations |\n| Authentication | `auth.*` | Security and rate limiting events |\n\n### Key Trace Span Identifiers\n\n| Identifier | Description |\n|------------|-------------|\n| `copilot.analytics.flush` | Analytics batch flush operation |\n| `copilot.analytics.save_request` | Persist individual request data |\n| `copilot.analytics.update_billing` | Update billing metrics |\n| `chat.setup` | Initialize chat session |\n| `chat.continue_with_tool_results` | Process tool execution results |\n| `context.reduce` | Context window reduction |\n| `context.summarize_chunk` | Summarize large context chunks |\n| `auth.validate_key` | API key validation |\n| `auth.rate_limit.record` | Rate limit tracking |\n\n## Integration with Workflows\n\nCopilot integrates deeply with the Sim workflow engine through the block system. When generating nodes or fixing errors, Copilot communicates with the workflow registry to validate and persist changes.\n\n### Workflow Registry Integration\n\nThe system uses Zustand for state management when interacting with workflow data:\n\n```typescript\n// Mock structure from test files\nuseWorkflowRegistry: {\n  getState: () => ({\n    activeWorkflowId: null,\n  }),\n}\n```\n\n### Block Generation\n\nCopilot generates workflow blocks by:\n\n1. Parsing natural language input\n2. Identifying required block types from the registry\n3. Validating block configurations against schema definitions\n4. Persisting generated blocks to the workflow state\n\n## Self-Hosted Deployment\n\nFor self-hosted Sim instances, Copilot requires separate configuration:\n\n### API Key Setup\n\n1. Navigate to [https://sim.ai](https://sim.ai)\n2. Go to Settings → Copilot\n3. Generate a Copilot API key\n4. Set the `COPILOT_API_KEY` environment variable in `apps/sim/.env`\n\n```bash\n# Example environment variable\nCOPILOT_API_KEY=your_generated_api_key_here\n```\n\n### Environment Configuration\n\nThe Copilot API key must be configured alongside other environment variables defined in the project's `.env.example` file. The system validates the API key on each request through the `auth.validate_key` trace span.\n\n## Analytics and Billing\n\nThe Copilot System implements a comprehensive analytics pipeline:\n\n### Analytics Flow\n\n```mermaid\ngraph LR\n    A[User Request] --> B[Save Request]\n    B --> C[Update Billing]\n    C --> D[Flush Analytics]\n    D --> E[Persist to Storage]\n```\n\n### Tracked Metrics\n\n| Metric | Trace Span | Description |\n|--------|------------|-------------|\n| Request Count | `copilot.analytics.save_request` | Individual Copilot invocations |\n| Billing Units | `copilot.analytics.update_billing` | Usage-based billing data |\n| Flush Events | `copilot.analytics.flush` | Batch processing completion |\n\n## Error Handling\n\nThe Copilot System handles various error scenarios through dedicated trace spans:\n\n| Error Type | Trace Span | Handling |\n|------------|------------|----------|\n| Explicit Abort | `chat.explicit_abort.*` | Graceful termination of requests |\n| Rate Limiting | `auth.rate_limit.record` | Throttling and quota enforcement |\n| Auth Failures | `auth.validate_key` | Invalid API key rejection |\n\n## Dependencies\n\nThe Copilot functionality is managed through the Bun workspace and depends on the following core packages:\n\n- **Next.js** (App Router) - API route handling\n- **Drizzle ORM** - Data persistence\n- **Zod** - Schema validation for API contracts\n- **Zustand** - Client-side state management\n\nDevelopment dependencies include the documentation generator script located at `scripts/generate-docs.ts` which can be run with `bun run generate-docs`.\n\n## Summary\n\nThe Copilot System provides intelligent assistance for workflow creation and modification within Sim. Through a combination of streaming chat APIs, comprehensive trace instrumentation, and deep workflow integration, it enables natural language-driven development experiences. The system is designed for both cloud-hosted and self-hosted deployments, with full observability through OpenTelemetry trace spans and analytics tracking.\n\n---\n\n<a id='deployment-guide'></a>\n\n## Deployment Guide\n\n### 相关页面\n\n相关主题：[Technology Stack](#tech-stack), [Background Jobs and Background Processing](#background-jobs)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [docker-compose.prod.yml](https://github.com/simstudioai/sim/blob/main/docker-compose.prod.yml)\n- [docker-compose.ollama.yml](https://github.com/simstudioai/sim/blob/main/docker-compose.ollama.yml)\n- [apps/sim/.env.example](https://github.com/simstudioai/sim/blob/main/apps/sim/.env.example)\n- [apps/realtime/.env.example](https://github.com/simstudioai/sim/blob/main/apps/realtime/.env.example)\n- [.devcontainer/docker-compose.yml](https://github.com/simstudioai/sim/blob/main/.devcontainer/docker-compose.yml)\n</details>\n\n# Deployment Guide\n\nSim is a workflow automation platform that supports multiple deployment configurations. This guide covers self-hosted deployment options including Docker, Docker Compose, manual setup, and Kubernetes via Helm charts.\n\n## Overview\n\nSim can be deployed in several ways depending on your infrastructure requirements and operational capabilities:\n\n| Deployment Method | Use Case | Complexity |\n|-------------------|----------|------------|\n| NPM Package (Docker) | Quick local testing | Low |\n| Docker Compose | Single-server production | Medium |\n| Manual Setup | Custom infrastructure | High |\n| Helm Chart | Kubernetes clusters | Medium-High |\n\n## Prerequisites\n\n### Hardware Requirements\n\n| Component | Minimum | Recommended |\n|-----------|---------|-------------|\n| CPU | 2 cores | 4+ cores |\n| Memory | 4 GB RAM | 8+ GB RAM |\n| Disk | 20 GB | 50+ GB SSD |\n| Docker | 20.10+ | Latest |\n\n### Software Requirements\n\n- **Docker** must be installed and running\n- **Bun** runtime (for manual setup)\n- **Node.js** v20+ (for manual setup)\n- **PostgreSQL** 12+ with **pgvector** extension (for manual setup)\n\n## Self-Hosted: NPM Package (Docker)\n\nThe fastest way to get started with Sim using Docker.\n\n### Quick Start\n\n```bash\nnpx simstudio\n```\n\nThis launches Sim at `http://localhost:3000` 资料来源：[README.md]()\n\n### Command Options\n\n| Flag | Description | Default |\n|------|-------------|---------|\n| `-p, --port <port>` | Port to run Sim on | `3000` |\n| `--no-pull` | Skip pulling latest Docker images | - |\n\n### Example Usage\n\n```bash\n# Run on custom port\nnpx simstudio --port 8080\n\n# Skip image pull (use cached images)\nnpx simstudio --no-pull\n```\n\n## Self-Hosted: Docker Compose\n\nFor production deployments on a single server, use the production Docker Compose configuration.\n\n### Standard Deployment\n\n```bash\ngit clone https://github.com/simstudioai/sim.git && cd sim\ndocker compose -f docker-compose.prod.yml up -d\n```\n\nOpen [http://localhost:3000](http://localhost:3000) to access Sim 资料来源：[README.md]()\n\n### Architecture\n\n```mermaid\ngraph TB\n    subgraph \"Docker Compose Stack\"\n        A[\"Next.js App<br>:3000\"] --> B[\"PostgreSQL<br>:5432\"]\n        A --> C[\"Redis<br>:6379\"]\n        A --> D[\"Realtime Service<br>:3001\"]\n        D --> B\n        D --> C\n    end\n    E[\"External Services\"] --> A\n```\n\n### Services\n\n| Service | Image | Port | Purpose |\n|---------|-------|------|---------|\n| app | simstudio/sim-app | 3000 | Main Next.js application |\n| realtime | simstudio/sim-realtime | 3001 | WebSocket/real-time events |\n| postgres | pgvector/pgvector | 5432 | Database with vector support |\n| redis | redis:alpine | 6379 | Caching and session storage |\n\n## Self-Hosted: Local Models (Ollama/vLLM)\n\nSim supports local AI models via Ollama and vLLM for privacy-focused or offline deployments.\n\n### Ollama Integration\n\nSim integrates with Ollama to run local models for workflow execution.\n\n```bash\ngit clone https://github.com/simstudioai/sim.git && cd sim\ndocker compose -f docker-compose.ollama.yml up -d\n```\n\n#### Ollama Configuration\n\n```mermaid\ngraph LR\n    A[\"Sim App\"] --> B[\"Ollama Service\"]\n    B --> C[\"Local Models<br>llama2, mistral, etc.\"]\n```\n\n#### Supported Ollama Environment Variables\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `OLLAMA_HOST` | Ollama server URL | `http://localhost:11434` |\n| `OLLAMA_MODEL` | Default model to use | - |\n\n### vLLM Integration\n\nFor high-performance local inference, configure vLLM:\n\n```yaml\n# docker-compose.override.yml\nservices:\n  app:\n    environment:\n      VLLM_HOST: \"http://vllm:8000\"\n      VLLM_MODEL: \"meta-llama/Llama-2-7b-hf\"\n```\n\nSee the [Docker self-hosting docs](https://docs.sim.ai/self-hosting/docker) for detailed setup instructions 资料来源：[README.md]()\n\n## Self-Hosted: Manual Setup\n\nFor custom infrastructure or development environments, install Sim manually.\n\n### Step 1: Clone and Install Dependencies\n\n```bash\ngit clone https://github.com/simstudioai/sim.git\ncd sim\nbun install\nbun run prepare  # Set up pre-commit hooks\n```\n\n### Step 2: PostgreSQL with pgvector Setup\n\n```bash\ndocker run --name simstudio-db \\\n  -e POSTGRES_PASSWORD=your_password \\\n  -e POSTGRES_DB=simstudio \\\n  -p 5432:5432 \\\n  -d \\\n  pgvector/pgvector:pg16\n```\n\n### Step 3: Environment Configuration\n\nCopy the example environment file and configure:\n\n```bash\ncd apps/sim\ncp .env.example .env\n# Edit .env with your configuration\n```\n\n#### Application Environment Variables\n\n| Variable | Description | Required |\n|----------|-------------|----------|\n| `DATABASE_URL` | PostgreSQL connection string | Yes |\n| `BETTER_AUTH_SECRET` | Secret for authentication | Yes |\n| `ENCRYPTION_KEY` | Data encryption key | Yes |\n| `NEXT_PUBLIC_APP_URL` | Public application URL | Yes |\n| `BETTER_AUTH_URL` | Authentication service URL | Yes |\n| `INTERNAL_API_SECRET` | Internal API authentication | Yes |\n| `CRON_SECRET` | Cron job authentication | Yes |\n\n### Step 4: Build and Start\n\n```bash\nbun run build\nbun run start\n```\n\n## Development Environment (Dev Container)\n\nThe repository includes a pre-configured development container.\n\n### Structure\n\n```mermaid\ngraph TB\n    subgraph \".devcontainer\"\n        A[\"Dev Container\"] --> B[\"PostgreSQL\"]\n        A --> C[\"Redis\"]\n        A --> D[\"MailHog\"]\n    end\n    A --> E[\"Sim App\"]\n    A --> F[\"Realtime Service\"]\n```\n\n### Dev Container Services\n\n| Service | Port | Purpose |\n|---------|------|---------|\n| Sim App | 3000 | Main application |\n| PostgreSQL | 5432 | Database |\n| Redis | 6379 | Caching |\n| MailHog | 8025 | Email testing |\n\n## Helm Chart Deployment\n\nFor Kubernetes clusters, use the official Helm chart.\n\n### Installation\n\n```bash\nhelm install sim ./helm/sim \\\n  --namespace sim \\\n  --create-namespace\n```\n\n### Production Configuration\n\n```yaml\n# values.yaml\napp:\n  replicaCount: 3\n  env:\n    NEXT_PUBLIC_APP_URL: \"https://sim.example.com\"\n    BETTER_AUTH_URL: \"https://sim.example.com\"\n\npostgresql:\n  auth:\n    database: simstudio\n  primary:\n    persistence:\n      size: 50Gi\n\nmonitoring:\n  enabled: true\n  prometheus:\n    enabled: true\n```\n\n### Secrets Management\n\nThe Helm chart supports three methods for managing secrets, in order of production-readiness:\n\n#### Method 1: Inline `--set` (Development Only)\n\n```bash\nhelm install sim ./helm/sim --set app.env.BETTER_AUTH_SECRET=...\n```\n\n> ⚠️ **Warning**: Values set this way appear in `helm get values` output. Not recommended for production.\n\n#### Method 2: Pre-existing Kubernetes Secret\n\n```bash\nkubectl create secret generic sim-app-secrets --namespace sim \\\n  --from-literal=BETTER_AUTH_SECRET=$(openssl rand -hex 32) \\\n  --from-literal=ENCRYPTION_KEY=$(openssl rand -hex 32) \\\n  --from-literal=INTERNAL_API_SECRET=$(openssl rand -hex 32) \\\n  --from-literal=CRON_SECRET=$(openssl rand -hex 32)\n\nkubectl create secret generic sim-postgres-secret --namespace sim \\\n  --from-literal=POSTGRES_PASSWORD=$(openssl rand -base64 24 | tr -d '/+=')\n```\n\nReference secrets in values:\n\n```yaml\napp:\n  secrets:\n    existingSecret:\n      enabled: true\n      name: sim-app-secrets\n\npostgresql:\n  auth:\n    existingSecret:\n      enabled: true\n      name: sim-postgres-secret\n      passwordKey: POSTGRES_PASSWORD\n```\n\n#### Method 3: External Secrets Operator (Recommended for Production)\n\nIntegrate with AWS Secrets Manager, HashiCorp Vault, or Azure Key Vault.\n\n### Autoscaling Configuration\n\n```yaml\nautoscaling:\n  enabled: true\n  minReplicas: 2\n  maxReplicas: 20\n  targetCPUUtilizationPercentage: 70\n  targetMemoryUtilizationPercentage: 80\n```\n\nWhen `autoscaling.enabled=true`, the chart omits `spec.replicas` from the Deployment so the HPA owns replica count. Requires `metrics-server` in the cluster 资料来源：[helm/sim/README.md]()\n\n### Network Policy\n\nEnable east-west isolation and block cloud metadata endpoints:\n\n```yaml\nnetworkPolicy:\n  enabled: true\n```\n\n### Key Helm Configuration Reference\n\n| Parameter | Description | Default |\n|-----------|-------------|---------|\n| `app.replicaCount` | Number of app replicas | 1 |\n| `app.image.repository` | App image repository | simstudio/sim-app |\n| `app.image.tag` | App image tag | appVersion |\n| `app.env.NEXT_PUBLIC_APP_URL` | Public app URL | localhost:3000 |\n| `app.env.BETTER_AUTH_URL` | Auth service URL | localhost:3000 |\n| `autoscaling.enabled` | Enable HPA | false |\n| `monitoring.enabled` | Enable monitoring | false |\n| `networkPolicy.enabled` | Enable network policies | false |\n\n### Important URLs Configuration\n\n> ⚠️ **Critical**: `app.env.NEXT_PUBLIC_APP_URL` and `app.env.BETTER_AUTH_URL` must match your public origin (e.g., `https://sim.example.com`). Leaving them as `localhost` breaks sign-in functionality.\n\n## Environment Variables Reference\n\n### Application (.env.example)\n\n| Variable | Required | Description |\n|----------|----------|-------------|\n| `DATABASE_URL` | Yes | PostgreSQL connection string |\n| `BETTER_AUTH_SECRET` | Yes | Authentication secret |\n| `BETTER_AUTH_URL` | Yes | Authentication service URL |\n| `NEXT_PUBLIC_APP_URL` | Yes | Public application URL |\n| `ENCRYPTION_KEY` | Yes | Data encryption key |\n| `INTERNAL_API_SECRET` | Yes | Internal API secret |\n| `CRON_SECRET` | Yes | Cron job secret |\n| `REDIS_URL` | No | Redis connection URL |\n| `SOCKET_SERVER_URL` | No | WebSocket server URL |\n| `OLLAMA_URL` | No | Ollama server URL |\n| `SMTP_*` | No | Email configuration |\n\n### Realtime Service (.env.example)\n\n| Variable | Required | Description |\n|----------|----------|-------------|\n| `REDIS_URL` | Yes | Redis connection URL |\n| `DATABASE_URL` | Yes | PostgreSQL connection string |\n| `INTERNAL_API_SECRET` | Yes | Internal API secret |\n\n## Testing Deployments\n\n### Load Testing\n\nThe repository includes Artillery load testing configurations:\n\n```bash\n# Workflow load testing\nbunx artillery run scripts/load/workflow-waves.yml\n\n# Isolation testing\nbunx artillery run scripts/load/workflow-isolation.yml\n```\n\n### Docker Health Checks\n\n```bash\n# Check service status\ndocker compose ps\n\n# View logs\ndocker compose logs -f app\n\n# Restart services\ndocker compose restart\n```\n\n## Troubleshooting\n\n### Common Issues\n\n| Issue | Solution |\n|-------|----------|\n| Sign-in fails | Verify `NEXT_PUBLIC_APP_URL` and `BETTER_AUTH_URL` match public origin |\n| Database connection failed | Check `DATABASE_URL` and ensure PostgreSQL is running |\n| WebSocket connection failed | Verify `SOCKET_SERVER_URL` is accessible |\n| Image pull fails | Use `--no-pull` flag or check Docker registry access |\n| Autoscaling not working | Ensure `metrics-server` is installed in cluster |\n\n### Log Locations\n\n| Environment | Log Command |\n|-------------|-------------|\n| Docker Compose | `docker compose logs -f [service]` |\n| Kubernetes | `kubectl logs -n sim -l app=sim` |\n| Helm | `helm status sim -n sim` |\n\n## Next Steps\n\n- [Configuration Reference](https://docs.sim.ai/configuration) - Complete environment variable documentation\n- [Local Model Setup](https://docs.sim.ai/self-hosting/docker) - Ollama and vLLM configuration\n- [Monitoring Setup](https://docs.sim.ai/monitoring) - Prometheus and Grafana integration\n- [Security Hardening](https://docs.sim.ai/security) - Production security recommendations\n\n---\n\n<a id='background-jobs'></a>\n\n## Background Jobs and Background Processing\n\n### 相关页面\n\n相关主题：[Workflow Executor Engine](#executor-engine), [Deployment Guide](#deployment-guide)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [apps/sim/background/workflow-execution.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/background/workflow-execution.ts)\n- [apps/sim/background/schedule-execution.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/background/schedule-execution.ts)\n- [apps/sim/background/webhook-execution.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/background/webhook-execution.ts)\n- [apps/sim/background/knowledge-connector-sync.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/background/knowledge-connector-sync.ts)\n- [apps/sim/background/resume-execution.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/background/resume-execution.ts)\n- [apps/sim/lib/core/async-jobs/types.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/core/async-jobs/types.ts)\n- [apps/sim/lib/table/workflow-columns.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/table/workflow-columns.ts)\n</details>\n\n# Background Jobs and Background Processing\n\n## Overview\n\nThe Sim platform uses a robust background job system to handle asynchronous, long-running, and resource-intensive operations outside the request-response cycle. This architecture enables workflows, schedules, webhooks, and other processing tasks to execute reliably without blocking user interactions.\n\nThe background processing system is designed around a **job queue abstraction** that supports multiple backend implementations, allowing the platform to scale horizontally and handle high-throughput scenarios with proper concurrency control.\n\n## Architecture\n\n### System Components\n\nThe background processing architecture consists of three main layers:\n\n1. **Job Queue Interface** - A unified abstraction for enqueuing, monitoring, and managing jobs\n2. **Backend Implementations** - Pluggable backends (database, trigger.dev) that handle actual job processing\n3. **Job Handlers** - Specific implementations for different job types (workflow, schedule, webhook, etc.)\n\n```mermaid\ngraph TD\n    subgraph \"Job Producers\"\n        API[API Request]\n        Schedule[Scheduled Trigger]\n        Webhook[Webhook Trigger]\n        Table[Table Cell Execution]\n    end\n\n    subgraph \"Job Queue Interface\"\n        Queue[JobQueue API]\n        Enqueue[enqueue / batchEnqueue]\n        GetJob[getJob / startJob]\n        Cancel[cancelJob]\n    end\n\n    subgraph \"Backends\"\n        DB[(Database Backend)]\n        TD[Trigger.dev Backend]\n    end\n\n    subgraph \"Job Handlers\"\n        WE[Workflow Execution]\n        SE[Schedule Execution]\n        HE[Webhook Execution]\n        KC[Knowledge Connector Sync]\n        RE[Resume Execution]\n    end\n\n    API --> Queue\n    Schedule --> Queue\n    Webhook --> Queue\n    Table --> Queue\n\n    Queue --> Enqueue\n    Queue --> GetJob\n    Queue --> Cancel\n\n    Enqueue --> DB\n    Enqueue --> TD\n\n    DB --> WE\n    DB --> SE\n    DB --> HE\n    DB --> KC\n    DB --> RE\n\n    TD --> WE\n```\n\n### Backend Types\n\nThe system supports two backend implementations for job queues:\n\n| Backend Type | Identifier | Description |\n|--------------|------------|-------------|\n| Database | `database` | Built-in queue using database storage, suitable for self-hosted deployments |\n| Trigger.dev | `trigger-dev` | External job processing service for cloud deployments |\n\n资料来源：[apps/sim/lib/core/async-jobs/types.ts:40]()\n\n## Job Queue Interface\n\n### Core Interface Methods\n\nThe `JobQueue` interface provides a unified API for all job operations:\n\n| Method | Parameters | Returns | Description |\n|--------|------------|---------|-------------|\n| `enqueue` | `type: JobType`, `payload: TPayload`, `options?: EnqueueOptions` | `Promise<string>` | Add a single job to the queue |\n| `batchEnqueue` | `type: JobType`, `items: Array<{payload, options?}>` | `Promise<string[]>` | Add multiple jobs as a batch |\n| `getJob` | `jobId: string` | `Promise<Job \\| null>` | Retrieve job by ID |\n| `startJob` | `jobId: string` | `Promise<void>` | Mark job as started/processing |\n| `completeJob` | `jobId: string`, `output: unknown` | `Promise<void>` | Mark job as completed with output |\n| `markJobFailed` | `jobId: string`, `error: string` | `Promise<void>` | Mark job as failed with error |\n| `cancelJob` | `jobId: string` | `Promise<void>` | Request job cancellation |\n\n资料来源：[apps/sim/lib/core/async-jobs/types.ts:1-30]()\n\n### Job Configuration Options\n\nJobs can be configured with the following options:\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `metadata` | `object` | Additional metadata including workflow ID, workspace ID, and correlation data |\n| `concurrencyKey` | `string` | Key for per-key concurrency limiting |\n| `concurrencyLimit` | `number` | Maximum concurrent jobs for this key (database backend only) |\n| `tags` | `string[]` | Tags for categorization (e.g., `tableId:xxx`, `rowId:yyy`) |\n| `runner` | `function` | Custom job body for database backend when no external worker exists |\n\n资料来源：[apps/sim/lib/core/async-jobs/types.ts:55-75]()\n\n## Job Types\n\nThe platform defines several job types for different processing scenarios:\n\n```typescript\nexport type JobType = \n  | 'workflow'\n  | 'workflow-group-cell'\n  | 'schedule'\n  | 'webhook'\n  | 'knowledge-connector-sync'\n  | 'resume'\n```\n\n### Workflow Execution (`workflow`)\n\nThe core job type for executing workflows. Handles the full lifecycle from triggering to completion.\n\n**Handler:** `executeWorkflowJob`\n\n**Payload includes:**\n- `workflowId` - Target workflow identifier\n- `workspaceId` - Workspace containing the workflow\n- `input` - Input data for the workflow\n- `executionId` - Unique execution identifier\n- `source` - Trigger source (e.g., `'api'`, `'table'`, `'schedule'`)\n\n资料来源：[apps/sim/background/workflow-execution.ts]()\n\n### Workflow Group Cell (`workflow-group-cell`)\n\nExecutes workflow groups for table rows. Supports high-concurrency table-based workflow execution.\n\n**Handler:** `executeWorkflowGroupCellJob`\n\n**Key Features:**\n- Table concurrency limiting (`TABLE_CONCURRENCY_LIMIT`)\n- Per-row execution tracking\n- Correlation with table and row identifiers\n\n```mermaid\nsequenceDiagram\n    participant Table as Table Scheduler\n    participant Queue as Job Queue\n    participant Worker as Cell Worker\n    \n    Table->>Queue: batchEnqueue(workflow-group-cell, runs[])\n    Queue-->>Table: jobIds[]\n    Worker->>Queue: getJob(jobId)\n    Worker->>Worker: executeWorkflowGroupCellJob(payload)\n    Worker->>Queue: completeJob(jobId, output)\n```\n\n资料来源：[apps/sim/lib/table/workflow-columns.ts:30-60]()\n\n### Schedule Execution (`schedule`)\n\nHandles time-based workflow triggers defined by schedules.\n\n**Handler:** `executeScheduleJob`\n\n资料来源：[apps/sim/background/schedule-execution.ts]()\n\n### Webhook Execution (`webhook`)\n\nProcesses incoming webhook payloads and triggers associated workflows.\n\n**Handler:** `executeWebhookJob`\n\n资料来源：[apps/sim/background/webhook-execution.ts]()\n\n### Knowledge Connector Sync (`knowledge-connector-sync`)\n\nSynchronizes data between external knowledge sources and the platform.\n\n**Handler:** `executeKnowledgeConnectorSyncJob`\n\n资料来源：[apps/sim/background/knowledge-connector-sync.ts]()\n\n### Resume Execution (`resume`)\n\nResumes previously paused or checkpointed workflow executions.\n\n**Handler:** `executeResumeJob`\n\n资料来源：[apps/sim/background/resume-execution.ts]()\n\n## Concurrency Control\n\n### Table Concurrency\n\nFor table-based workflow execution, the system enforces a concurrency limit to prevent resource exhaustion:\n\n```typescript\nconst TABLE_CONCURRENCY_LIMIT = 5\n```\n\nJobs for the same table are grouped by `concurrencyKey` to ensure ordered processing while allowing parallel execution across different tables.\n\n资料来源：[apps/sim/lib/table/workflow-columns.ts:50]()\n\n### Job Tagging\n\nJobs are tagged for tracking and monitoring:\n\n| Tag Format | Example | Purpose |\n|------------|---------|---------|\n| `tableId:{id}` | `tableId:abc123` | Identifies the source table |\n| `rowId:{id}` | `rowId:row456` | Identifies the source row |\n| `group:{id}` | `group:grp789` | Identifies the workflow group |\n\n资料来源：[apps/sim/lib/table/workflow-columns.ts:55]()\n\n## Job Correlation and Tracing\n\n### Metadata Structure\n\nEach job carries correlation metadata for distributed tracing:\n\n```typescript\ninterface CorrelationData {\n  executionId: string\n  requestId: string\n  source: 'workflow' | 'api' | 'schedule' | 'webhook' | 'table'\n  workflowId: string\n  triggerType: string\n}\n```\n\n### Request ID Format\n\nRequest IDs follow a consistent naming convention based on job type:\n\n| Job Type | Request ID Format | Example |\n|----------|-------------------|---------|\n| Workflow Group Cell | `wfgrp-{executionId}` | `wfgrp-exec-123` |\n\n资料来源：[apps/sim/lib/table/workflow-columns.ts:43]()\n\n## Job Lifecycle\n\n### State Transitions\n\n```mermaid\nstateDiagram-v2\n    [*] --> Queued: enqueue()\n    Queued --> Processing: startJob()\n    Processing --> Completed: completeJob()\n    Processing --> Failed: markJobFailed()\n    Processing --> Cancelled: cancelJob()\n    Queued --> Cancelled: cancelJob()\n    Cancelled --> [*]\n    Completed --> [*]\n    Failed --> [*]\n```\n\n### Status Definitions\n\n| Status | Description |\n|--------|-------------|\n| `pending` | Job is queued but not yet picked up |\n| `queued` | Job is in the queue (alternative state) |\n| `processing` | Job is currently being executed |\n| `completed` | Job finished successfully |\n| `failed` | Job encountered an error |\n| `cancelled` | Job was cancelled before completion |\n\n## Error Handling and Cancellation\n\n### Best-Effort Cancellation\n\nThe `cancelJob` method implements best-effort cancellation:\n- Unknown or already-completed jobs resolve quietly (no error thrown)\n- Underlying provider rejections fail loudly to alert operators\n\n```typescript\n/**\n * Request cancellation of a queued or running job. Best-effort: backends should\n * fail loudly if the underlying provider rejects, but a missing/unknown jobId\n * should resolve quietly so callers can drive cancel from possibly-stale state.\n */\ncancelJob(jobId: string): Promise<void>\n```\n\n资料来源：[apps/sim/lib/core/async-jobs/types.ts:28-33]()\n\n### Runner Functions\n\nFor the database backend, jobs include a `runner` function that is executed as a fire-and-forget IIFE (Immediately Invoked Function Expression). This allows the database row to drive the job through processing states:\n\n```typescript\nrunner?: <TPayload>(\n  payload: TPayload, \n  signal: AbortSignal\n) => Promise<void>\n```\n\nThe `AbortSignal` is driven by `cancelJob`, enabling graceful shutdown of cancelled jobs.\n\n资料来源：[apps/sim/lib/core/async-jobs/types.ts:62-69]()\n\n## Batch Enqueue Operations\n\n### Batch Processing Flow\n\n```mermaid\ngraph LR\n    A[Pending Runs] --> B[Map to Job Items]\n    B --> C{Backend Type}\n    C -->|Database| D[Single Multi-Row INSERT]\n    C -->|Trigger.dev| E[tasks.batchTrigger]\n    D --> F[Return jobIds in input order]\n    E --> F\n    F --> G[Promise.allSettled Fallback]\n    G -->|If batch fails| H[Individual Enqueue]\n```\n\nThe batch enqueue operation:\n1. Maps pending runs to job items with full metadata and options\n2. Attempts batch enqueue via the queue backend\n3. Falls back to individual enqueue if batch fails\n4. Returns one jobId per item in input order\n\n资料来源：[apps/sim/lib/table/workflow-columns.ts:60-75]()\n\n## Integration with SDKs\n\n### Python SDK Async Execution\n\nThe Python SDK provides async execution support through the `execute_workflow` method with `async_execution=True`:\n\n```python\nresult = client.execute_workflow(\n    'workflow-id',\n    {'message': 'Hello'},\n    async_execution=True\n)\n# Returns AsyncExecutionResult with job_id and status_url\n```\n\n### TypeScript SDK Async Execution\n\nSimilarly, the TypeScript SDK supports async execution:\n\n```typescript\nconst result = await client.executeWorkflow('workflow-id', { data: 'input' }, {\n  asyncExecution: true\n});\n// Returns AsyncExecutionResult with jobId\n```\n\nJob status can be monitored via `getJobStatus(jobId)`.\n\n资料来源：[packages/python-sdk/README.md](), [packages/ts-sdk/README.md]()\n\n## Testing Support\n\nThe testing utilities in `packages/testing` provide factories for creating workflow test fixtures:\n\n- `createWorkflowState()` - Base workflow state\n- `createLinearWorkflow(n)` - Sequential workflow with n blocks\n- `createBranchingWorkflow()` - Conditional branching workflow\n\n资料来源：[packages/testing/src/factories/workflow.factory.ts]()\n\n## Summary\n\nThe background job system in Sim provides:\n\n1. **Unified Queue Interface** - Consistent API across different job types and backends\n2. **Multiple Backend Support** - Database for self-hosted, Trigger.dev for cloud deployments\n3. **Rich Job Metadata** - Correlation data, tags, and concurrency controls for observability\n4. **Reliable Execution** - State management, cancellation support, and retry capabilities\n5. **Batch Operations** - Efficient bulk enqueue with fallback to individual operations\n6. **SDK Integration** - Async execution support in both Python and TypeScript SDKs\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：simstudioai/sim\n\n摘要：发现 20 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：安装坑 - 社区讨论暴露的待验证问题：Open-source general purpose agent with built-in MCPToolkit support。\n\n## 1. 安装坑 · 社区讨论暴露的待验证问题：Open-source general purpose agent with built-in MCPToolkit support\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Open-source general purpose agent with built-in MCPToolkit support 15 May 2025 · ... MCP for local-agent workflows · r/LocalLLaMA - A visual ... r/commandline - CLI tool to simplify open source monitoring agent installation.\n- 对用户的影响：这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- 建议检查：Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- 证据：social_signal:reddit | ssig_7a250aac9fa1441c8186a7b73d669d8f | https://www.reddit.com/r/LocalLLaMA/comments/1kn8m8t/opensource_general_purpose_agent_with_builtin/ | Open-source general purpose agent with built-in MCPToolkit support\n\n## 2. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | host_targets=cursor\n\n## 3. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | README/documentation is current enough for a first validation pass.\n\n## 4. 运行坑 · 来源证据：v0.6.63\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.6.63\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_5a97e1d742fe4d7f918e0b42f27b87c3 | https://github.com/simstudioai/sim/releases/tag/v0.6.63 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 5. 运行坑 · 来源证据：v0.6.65\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.6.65\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_03f18559029c4724b11011ef96259161 | https://github.com/simstudioai/sim/releases/tag/v0.6.65 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 6. 运行坑 · 来源证据：v0.6.67\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.6.67\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_048d1506c1d645b0be435841a26b93ed | https://github.com/simstudioai/sim/releases/tag/v0.6.67 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 7. 运行坑 · 来源证据：v0.6.73\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.6.73\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_048864e1cdcc44d2b2a30917b7c4adc2 | https://github.com/simstudioai/sim/releases/tag/v0.6.73 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 8. 维护坑 · 来源证据：v0.6.71\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v0.6.71\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_9c30d794fb7344489f96a6ac47cd1d6e | https://github.com/simstudioai/sim/releases/tag/v0.6.71 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 9. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | last_activity_observed missing\n\n## 10. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | no_demo; severity=medium\n\n## 11. 安全/权限坑 · 存在安全注意事项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：No sandbox install has been executed yet; downstream must verify before user use.\n- 对用户的影响：用户安装前需要知道权限边界和敏感操作。\n- 建议检查：转成明确权限清单和安全审查提示。\n- 防护动作：安全注意事项必须面向用户前置展示。\n- 证据：risks.safety_notes | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | No sandbox install has been executed yet; downstream must verify before user use.\n\n## 12. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | no_demo; severity=medium\n\n## 13. 安全/权限坑 · 来源证据：Unable to Access Files from Private GitHub Repository in Self-Hosted Setup\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Unable to Access Files from Private GitHub Repository in Self-Hosted Setup\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_ed1c9f64533441f5826c1fe98fa9ce49 | https://github.com/simstudioai/sim/issues/4555 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 14. 安全/权限坑 · 来源证据：v0.6.64\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.6.64\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_5e2aa5311b1748cea446771920242668 | https://github.com/simstudioai/sim/releases/tag/v0.6.64 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 15. 安全/权限坑 · 来源证据：v0.6.66\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.6.66\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_7d42c79fecf54003b117f76d49873223 | https://github.com/simstudioai/sim/releases/tag/v0.6.66 | 来源讨论提到 api key 相关条件，需在安装/试用前复核。\n\n## 16. 安全/权限坑 · 来源证据：v0.6.68\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.6.68\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_c8fe17ce7ba6424c88017ed644620915 | https://github.com/simstudioai/sim/releases/tag/v0.6.68 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 17. 安全/权限坑 · 来源证据：v0.6.69\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.6.69\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_a47b6988921146ac8fa66d73b0574c88 | https://github.com/simstudioai/sim/releases/tag/v0.6.69 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 18. 安全/权限坑 · 来源证据：v0.6.72\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.6.72\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_f13817452da14b5d97c64bde45647685 | https://github.com/simstudioai/sim/releases/tag/v0.6.72 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 19. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | issue_or_pr_quality=unknown\n\n## 20. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | release_recency=unknown\n\n<!-- canonical_name: simstudioai/sim; human_manual_source: deepwiki_human_wiki -->\n",
      "markdown_key": "sim",
      "pages": "draft",
      "source_refs": [
        {
          "evidence_id": "art_4c769793e2db44b09c3ad8f55672a2ea",
          "kind": "docs",
          "supports_claim_ids": [
            "claim_identity",
            "claim_distribution",
            "claim_capability"
          ],
          "url": "https://github.com/simstudioai/sim#readme"
        }
      ],
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "sim 说明书",
      "toc": [
        "https://github.com/simstudioai/sim 项目说明书",
        "目录",
        "Project Introduction",
        "Overview",
        "Key Features",
        "Architecture Overview",
        "Deployment Options",
        "System Requirements",
        "Doramagic 踩坑日志"
      ]
    }
  },
  "quality_gate": {
    "blocking_gaps": [],
    "category_confidence": "medium",
    "compile_status": "ready_for_review",
    "five_assets_present": true,
    "install_sandbox_verified": true,
    "missing_evidence": [],
    "next_action": "publish to Doramagic.ai project surfaces",
    "prompt_preview_boundary_ok": true,
    "publish_status": "publishable",
    "quick_start_verified": true,
    "repo_clone_verified": true,
    "repo_commit": "4efe99970c72e310ad86673e6557bd0b58cf76a5",
    "repo_inspection_error": null,
    "repo_inspection_files": [
      "package.json",
      "README.md",
      "packages/README.md",
      "packages/cli/package.json",
      "packages/cli/README.md",
      "packages/cli/tsconfig.json",
      "packages/testing/package.json",
      "packages/testing/tsconfig.json",
      "packages/audit/vitest.config.ts",
      "packages/audit/package.json",
      "packages/audit/tsconfig.json",
      "packages/workflow-authz/package.json",
      "packages/workflow-authz/tsconfig.json",
      "packages/tsconfig/library.json",
      "packages/tsconfig/package.json",
      "packages/tsconfig/nextjs.json",
      "packages/tsconfig/library-build.json",
      "packages/tsconfig/base.json",
      "packages/utils/vitest.config.ts",
      "packages/utils/package.json",
      "packages/utils/tsconfig.json",
      "packages/realtime-protocol/package.json",
      "packages/realtime-protocol/tsconfig.json",
      "packages/db/schema.ts",
      "packages/db/db.ts",
      "packages/db/constants.ts",
      "packages/db/vitest.config.ts",
      "packages/db/index.ts",
      "packages/db/package.json",
      "packages/db/triggers.ts",
      "packages/db/tsconfig.json",
      "packages/db/drizzle.config.ts",
      "packages/python-sdk/setup.py",
      "packages/python-sdk/pyproject.toml",
      "packages/python-sdk/README.md",
      "packages/workflow-types/package.json",
      "packages/workflow-types/tsconfig.json",
      "packages/workflow-persistence/package.json",
      "packages/workflow-persistence/tsconfig.json",
      "packages/logger/vitest.config.ts"
    ],
    "repo_inspection_verified": true,
    "review_reasons": [],
    "tag_count_ok": true,
    "unsupported_claims": []
  },
  "schema_version": "0.1",
  "user_assets": {
    "ai_context_pack": {
      "asset_id": "ai_context_pack",
      "filename": "AI_CONTEXT_PACK.md",
      "markdown": "# simstudio - Doramagic AI Context Pack\n\n> 定位：安装前体验与判断资产。它帮助宿主 AI 有一个好的开始，但不代表已经安装、执行或验证目标项目。\n\n## 充分原则\n\n- **充分原则，不是压缩原则**：AI Context Pack 应该充分到让宿主 AI 在开工前理解项目价值、能力边界、使用入口、风险和证据来源；它可以分层组织，但不以最短摘要为目标。\n- **压缩策略**：只压缩噪声和重复内容，不压缩会影响判断和开工质量的上下文。\n\n## 给宿主 AI 的使用方式\n\n你正在读取 Doramagic 为 simstudio 编译的 AI Context Pack。请把它当作开工前上下文：帮助用户理解适合谁、能做什么、如何开始、哪些必须安装后验证、风险在哪里。不要声称你已经安装、运行或执行了目标项目。\n\n## Claim 消费规则\n\n- **事实来源**：Repo Evidence + Claim/Evidence Graph；Human Wiki 只提供显著性、术语和叙事结构。\n- **事实最低状态**：`supported`\n- `supported`：可以作为项目事实使用，但回答中必须引用 claim_id 和证据路径。\n- `weak`：只能作为低置信度线索，必须要求用户继续核实。\n- `inferred`：只能用于风险提示或待确认问题，不能包装成项目事实。\n- `unverified`：不得作为事实使用，应明确说证据不足。\n- `contradicted`：必须展示冲突来源，不得替用户强行选择一个版本。\n\n## 它最适合谁\n\n- **正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**：README 或插件配置提到多个宿主 AI。 证据：`README.md` Claim：`clm_0003` supported 0.86\n- **希望把专业流程带进宿主 AI 的用户**：仓库包含 Skill 文档。 证据：`.agents/skills/add-block/SKILL.md`, `.agents/skills/add-connector/SKILL.md`, `.agents/skills/add-integration/SKILL.md`, `.agents/skills/add-tools/SKILL.md` 等 Claim：`clm_0004` supported 0.86\n\n## 它能做什么\n\n- **AI Skill / Agent 指令资产库**（可做安装前预览）：项目包含可被宿主 AI 读取的 Skill 或 Agent 指令文件，可用于把专业流程带入 Claude、Codex、Cursor 等宿主。 证据：`.agents/skills/add-block/SKILL.md`, `.agents/skills/add-connector/SKILL.md`, `.agents/skills/add-integration/SKILL.md`, `.agents/skills/add-tools/SKILL.md` 等 Claim：`clm_0001` supported 0.86\n- **命令行启动或安装流程**（需要安装后验证）：项目文档中存在可执行命令，真实使用需要在本地或宿主环境中运行这些命令。 证据：`README.md`, `packages/cli/README.md`, `packages/python-sdk/README.md`, `packages/ts-sdk/README.md` Claim：`clm_0002` supported 0.86\n\n## 怎么开始\n\n- `npx simstudio` 证据：`README.md` Claim：`clm_0005` supported 0.86\n- `git clone https://github.com/simstudioai/sim.git && cd sim` 证据：`README.md` Claim：`clm_0006` supported 0.86\n- `git clone https://github.com/simstudioai/sim.git` 证据：`README.md` Claim：`clm_0006` supported 0.86, `clm_0007` supported 0.86\n- `npm install -g simstudio` 证据：`packages/cli/README.md` Claim：`clm_0008` supported 0.86\n- `pip install simstudio-sdk` 证据：`packages/python-sdk/README.md` Claim：`clm_0009` supported 0.86\n- `pip install -e \".[dev]\"` 证据：`packages/python-sdk/README.md` Claim：`clm_0010` supported 0.86\n- `npm install simstudio-ts-sdk` 证据：`packages/ts-sdk/README.md` Claim：`clm_0011` supported 0.86\n- `yarn add simstudio-ts-sdk` 证据：`packages/ts-sdk/README.md` Claim：`clm_0012` supported 0.86\n\n## 继续前判断卡\n\n- **当前建议**：先做权限沙盒试用\n- **为什么**：项目存在安装命令、宿主配置或本地写入线索，不建议直接进入主力环境，应先在隔离环境试装。\n\n### 30 秒判断\n\n- **现在怎么做**：先做权限沙盒试用\n- **最小安全下一步**：先跑 Prompt Preview；若仍要安装，只在隔离环境试装\n- **先别相信**：工具权限边界不能在安装前相信。\n- **继续会触碰**：命令执行、宿主 AI 配置、本地环境或项目文件\n\n### 现在可以相信\n\n- **适合人群线索：正在使用 Claude/Codex/Cursor/Gemini 等宿主 AI 的开发者**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`README.md` Claim：`clm_0003` supported 0.86\n- **适合人群线索：希望把专业流程带进宿主 AI 的用户**（supported）：有 supported claim 或项目证据支撑，但仍不等于真实安装效果。 证据：`.agents/skills/add-block/SKILL.md`, `.agents/skills/add-connector/SKILL.md`, `.agents/skills/add-integration/SKILL.md`, `.agents/skills/add-tools/SKILL.md` 等 Claim：`clm_0004` supported 0.86\n- **能力存在：AI Skill / Agent 指令资产库**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`.agents/skills/add-block/SKILL.md`, `.agents/skills/add-connector/SKILL.md`, `.agents/skills/add-integration/SKILL.md`, `.agents/skills/add-tools/SKILL.md` 等 Claim：`clm_0001` supported 0.86\n- **能力存在：命令行启动或安装流程**（supported）：可以相信项目包含这类能力线索；是否适合你的具体任务仍要试用或安装后验证。 证据：`README.md`, `packages/cli/README.md`, `packages/python-sdk/README.md`, `packages/ts-sdk/README.md` Claim：`clm_0002` supported 0.86\n- **存在 Quick Start / 安装命令线索**（supported）：可以相信项目文档出现过启动或安装入口；不要因此直接在主力环境运行。 证据：`README.md` Claim：`clm_0005` supported 0.86\n\n### 现在还不能相信\n\n- **工具权限边界不能在安装前相信。**（unverified）：MCP/tool 类项目通常会触碰文件、网络、浏览器或外部 API，必须真实检查权限和日志。\n- **真实输出质量不能在安装前相信。**（unverified）：Prompt Preview 只能展示引导方式，不能证明真实项目中的结果质量。\n- **宿主 AI 版本兼容性不能在安装前相信。**（unverified）：Claude、Cursor、Codex、Gemini 等宿主加载规则和版本差异必须在真实环境验证。\n- **不会污染现有宿主 AI 行为，不能直接相信。**（inferred）：Skill、plugin、AGENTS/CLAUDE/GEMINI 指令可能改变宿主 AI 的默认行为。 证据：`.agents/skills/add-block/SKILL.md`, `.agents/skills/add-connector/SKILL.md`, `.agents/skills/add-integration/SKILL.md`, `.agents/skills/add-tools/SKILL.md` 等\n- **可安全回滚不能默认相信。**（unverified）：除非项目明确提供卸载和恢复说明，否则必须先在隔离环境验证。\n- **真实安装后是否与用户当前宿主 AI 版本兼容？**（unverified）：兼容性只能通过实际宿主环境验证。\n- **项目输出质量是否满足用户具体任务？**（unverified）：安装前预览只能展示流程和边界，不能替代真实评测。\n- **安装命令是否需要网络、权限或全局写入？**（unverified）：这影响企业环境和个人环境的安装风险。 证据：`README.md`\n\n### 继续会触碰什么\n\n- **命令执行**：包管理器、网络下载、本地插件目录、项目配置或用户主目录。 原因：运行第一条命令就可能产生环境改动；必须先判断是否值得跑。 证据：`README.md`, `packages/cli/README.md`, `packages/python-sdk/README.md`, `packages/ts-sdk/README.md`\n- **宿主 AI 配置**：Claude/Codex/Cursor/Gemini/OpenCode 等宿主的 plugin、Skill 或规则加载配置。 原因：宿主配置会改变 AI 后续工作方式，可能和用户已有规则冲突。 证据：`.agents/skills/add-block/SKILL.md`, `.agents/skills/add-connector/SKILL.md`, `.agents/skills/add-integration/SKILL.md`, `.agents/skills/add-tools/SKILL.md` 等\n- **本地环境或项目文件**：安装结果、插件缓存、项目配置或本地依赖目录。 原因：安装前无法证明写入范围和回滚方式，需要隔离验证。 证据：`README.md`, `packages/cli/README.md`, `packages/python-sdk/README.md`, `packages/ts-sdk/README.md`\n- **宿主 AI 上下文**：AI Context Pack、Prompt Preview、Skill 路由、风险规则和项目事实。 原因：导入上下文会影响宿主 AI 后续判断，必须避免把未验证项包装成事实。\n\n### 最小安全下一步\n\n- **先跑 Prompt Preview**：用安装前交互式试用判断工作方式是否匹配，不需要授权或改环境。（适用：任何项目都适用，尤其是输出质量未知时。）\n- **只在隔离目录或测试账号试装**：避免安装命令污染主力宿主 AI、真实项目或用户主目录。（适用：存在命令执行、插件配置或本地写入线索时。）\n- **先备份宿主 AI 配置**：Skill、plugin、规则文件可能改变 Claude/Cursor/Codex 的默认行为。（适用：存在插件 manifest、Skill 或宿主规则入口时。）\n- **安装后只验证一个最小任务**：先验证加载、兼容、输出质量和回滚，再决定是否深用。（适用：准备从试用进入真实工作流时。）\n\n### 退出方式\n\n- **保留安装前状态**：记录原始宿主配置和项目状态，后续才能判断是否可恢复。\n- **准备移除宿主 plugin / Skill / 规则入口**：如果试装后行为异常，可以把宿主 AI 恢复到试装前状态。\n- **记录安装命令和写入路径**：没有明确卸载说明时，至少要知道哪些目录或配置需要手动清理。\n- **如果没有回滚路径，不进入主力环境**：不可回滚是继续前阻断项，不应靠信任或运气继续。\n\n## 哪些只能预览\n\n- 解释项目适合谁和能做什么\n- 基于项目文档演示典型对话流程\n- 帮助用户判断是否值得安装或继续研究\n\n## 哪些必须安装后验证\n\n- 真实安装 Skill、插件或 CLI\n- 执行脚本、修改本地文件或访问外部服务\n- 验证真实输出质量、性能和兼容性\n\n## 边界与风险判断卡\n\n- **把安装前预览误认为真实运行**：用户可能高估项目已经完成的配置、权限和兼容性验证。 处理方式：明确区分 prompt_preview_can_do 与 runtime_required。 Claim：`clm_0013` inferred 0.45\n- **命令执行会修改本地环境**：安装命令可能写入用户主目录、宿主插件目录或项目配置。 处理方式：先在隔离环境或测试账号中运行。 证据：`README.md`, `packages/cli/README.md`, `packages/python-sdk/README.md`, `packages/ts-sdk/README.md` Claim：`clm_0014` supported 0.86\n- **待确认**：真实安装后是否与用户当前宿主 AI 版本兼容？。原因：兼容性只能通过实际宿主环境验证。\n- **待确认**：项目输出质量是否满足用户具体任务？。原因：安装前预览只能展示流程和边界，不能替代真实评测。\n- **待确认**：安装命令是否需要网络、权限或全局写入？。原因：这影响企业环境和个人环境的安装风险。\n\n## 开工前工作上下文\n\n### 加载顺序\n\n- 先读取 how_to_use.host_ai_instruction，建立安装前判断资产的边界。\n- 读取 claim_graph_summary，确认事实来自 Claim/Evidence Graph，而不是 Human Wiki 叙事。\n- 再读取 intended_users、capabilities 和 quick_start_candidates，判断用户是否匹配。\n- 需要执行具体任务时，优先查 role_skill_index，再查 evidence_index。\n- 遇到真实安装、文件修改、网络访问、性能或兼容性问题时，转入 risk_card 和 boundaries.runtime_required。\n\n### 任务路由\n\n- **AI Skill / Agent 指令资产库**：先基于 role_skill_index / evidence_index 帮用户挑选可用角色、Skill 或工作流。 边界：可做安装前 Prompt 体验。 证据：`.agents/skills/add-block/SKILL.md`, `.agents/skills/add-connector/SKILL.md`, `.agents/skills/add-integration/SKILL.md`, `.agents/skills/add-tools/SKILL.md` 等 Claim：`clm_0001` supported 0.86\n- **命令行启动或安装流程**：先说明这是安装后验证能力，再给出安装前检查清单。 边界：必须真实安装或运行后验证。 证据：`README.md`, `packages/cli/README.md`, `packages/python-sdk/README.md`, `packages/ts-sdk/README.md` Claim：`clm_0002` supported 0.86\n\n### 上下文规模\n\n- 文件总数：9619\n- 重要文件覆盖：40/9619\n- 证据索引条目：80\n- 角色 / Skill 条目：18\n\n### 证据不足时的处理\n\n- **missing_evidence**：说明证据不足，要求用户提供目标文件、README 段落或安装后验证记录；不要补全事实。\n- **out_of_scope_request**：说明该任务超出当前 AI Context Pack 证据范围，并建议用户先查看 Human Manual 或真实安装后验证。\n- **runtime_request**：给出安装前检查清单和命令来源，但不要替用户执行命令或声称已执行。\n- **source_conflict**：同时展示冲突来源，标记为待核实，不要强行选择一个版本。\n\n## Prompt Recipes\n\n### 适配判断\n\n- 目标：判断这个项目是否适合用户当前任务。\n- 预期输出：适配结论、关键理由、证据引用、安装前可预览内容、必须安装后验证内容、下一步建议。\n\n```text\n请基于 simstudio 的 AI Context Pack，先问我 3 个必要问题，然后判断它是否适合我的任务。回答必须包含：适合谁、能做什么、不能做什么、是否值得安装、证据来自哪里。所有项目事实必须引用 evidence_refs、source_paths 或 claim_id。\n```\n\n### 安装前体验\n\n- 目标：让用户在安装前感受核心工作流，同时避免把预览包装成真实能力或营销承诺。\n- 预期输出：一段带边界标签的体验剧本、安装后验证清单和谨慎建议；不含真实运行承诺或强营销表述。\n\n```text\n请把 simstudio 当作安装前体验资产，而不是已安装工具或真实运行环境。\n\n请严格输出四段：\n1. 先问我 3 个必要问题。\n2. 给出一段“体验剧本”：用 [安装前可预览]、[必须安装后验证]、[证据不足] 三种标签展示它可能如何引导工作流。\n3. 给出安装后验证清单：列出哪些能力只有真实安装、真实宿主加载、真实项目运行后才能确认。\n4. 给出谨慎建议：只能说“值得继续研究/试装”“先补充信息后再判断”或“不建议继续”，不得替项目背书。\n\n硬性边界：\n- 不要声称已经安装、运行、执行测试、修改文件或产生真实结果。\n- 不要写“自动适配”“确保通过”“完美适配”“强烈建议安装”等承诺性表达。\n- 如果描述安装后的工作方式，必须使用“如果安装成功且宿主正确加载 Skill，它可能会……”这种条件句。\n- 体验剧本只能写成“示例台词/假设流程”：使用“可能会询问/可能会建议/可能会展示”，不要写“已写入、已生成、已通过、正在运行、正在生成”。\n- Prompt Preview 不负责给安装命令；如用户准备试装，只能提示先阅读 Quick Start 和 Risk Card，并在隔离环境验证。\n- 所有项目事实必须来自 supported claim、evidence_refs 或 source_paths；inferred/unverified 只能作风险或待确认项。\n\n```\n\n### 角色 / Skill 选择\n\n- 目标：从项目里的角色或 Skill 中挑选最匹配的资产。\n- 预期输出：候选角色或 Skill 列表，每项包含适用场景、证据路径、风险边界和是否需要安装后验证。\n\n```text\n请读取 role_skill_index，根据我的目标任务推荐 3-5 个最相关的角色或 Skill。每个推荐都要说明适用场景、可能输出、风险边界和 evidence_refs。\n```\n\n### 风险预检\n\n- 目标：安装或引入前识别环境、权限、规则冲突和质量风险。\n- 预期输出：环境、权限、依赖、许可、宿主冲突、质量风险和未知项的检查清单。\n\n```text\n请基于 risk_card、boundaries 和 quick_start_candidates，给我一份安装前风险预检清单。不要替我执行命令，只说明我应该检查什么、为什么检查、失败会有什么影响。\n```\n\n### 宿主 AI 开工指令\n\n- 目标：把项目上下文转成一次对话开始前的宿主 AI 指令。\n- 预期输出：一段边界明确、证据引用明确、适合复制给宿主 AI 的开工前指令。\n\n```text\n请基于 simstudio 的 AI Context Pack，生成一段我可以粘贴给宿主 AI 的开工前指令。这段指令必须遵守 not_runtime=true，不能声称项目已经安装、运行或产生真实结果。\n```\n\n\n## 角色 / Skill 索引\n\n- 共索引 18 个角色 / Skill / 项目文档条目。\n\n- **add-block**（skill）：Create or update a Sim integration block with correct subBlocks, conditions, dependsOn, modes, canonicalParamId usage, outputs, and tool wiring. Use when working on apps/sim/blocks/blocks/{service}.ts or aligning a block with its tools. 激活提示：当用户任务与“add-block”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/add-block/SKILL.md`\n- **add-connector**（skill）：Add or update a Sim knowledge base connector for syncing documents from an external source, including auth mode, config fields, pagination, document mapping, tags, and registry wiring. Use when working in apps/sim/connectors/{service}/ or adding a new external document source. 激活提示：当用户任务与“add-connector”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/add-connector/SKILL.md`\n- **add-integration**（skill）：Add a complete Sim integration from API docs, covering tools, block, icon, optional triggers, registrations, and integration conventions. Use when introducing a new service under apps/sim/tools , apps/sim/blocks , and apps/sim/triggers . 激活提示：当用户任务与“add-integration”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/add-integration/SKILL.md`\n- **add-tools**（skill）：Create or update Sim tool configurations from service API docs, including typed params, request mapping, response transforms, outputs, and registry entries. Use when working in apps/sim/tools/{service}/ or fixing tool definitions for an integration. 激活提示：当用户任务与“add-tools”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/add-tools/SKILL.md`\n- **add-trigger**（skill）：Create or update Sim webhook triggers using the generic trigger builder, service-specific setup instructions, outputs, and registry wiring. Use when working in apps/sim/triggers/{service}/ or adding webhook support to an integration. 激活提示：当用户任务与“add-trigger”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/add-trigger/SKILL.md`\n- **cleanup**（skill）：Run all code quality skills in sequence — effects, memo, callbacks, state, React Query, and emcn design review 激活提示：当用户任务与“cleanup”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/cleanup/SKILL.md`\n- **emcn-design-review**（skill）：Review UI code for alignment with the emcn design system — components, tokens, patterns, and conventions 激活提示：当用户任务与“emcn-design-review”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/emcn-design-review/SKILL.md`\n- **react-query-best-practices**（skill）：Audit React Query usage for best practices — key factories, staleTime, mutations, and server state ownership 激活提示：当用户任务与“react-query-best-practices”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/react-query-best-practices/SKILL.md`\n- **ship**（skill）：Commit, push, and open a PR to staging in one shot 激活提示：当用户任务与“ship”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/ship/SKILL.md`\n- **validate-connector**（skill）：Audit an existing Sim knowledge base connector against the service API docs and repository conventions, then report and fix issues in auth, config fields, pagination, document mapping, tags, and registry entries. Use when validating or repairing code in apps/sim/connectors/{service}/ . 激活提示：当用户任务与“validate-connector”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/validate-connector/SKILL.md`\n- **validate-integration**（skill）：Audit an existing Sim integration against the service API docs and repository conventions, then report and fix issues across tools, blocks, outputs, OAuth scopes, triggers, and registry entries. Use when validating or repairing a service integration under apps/sim/tools , apps/sim/blocks , or apps/sim/triggers . 激活提示：当用户任务与“validate-integration”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/validate-integration/SKILL.md`\n- **validate-trigger**（skill）：Audit an existing Sim webhook trigger against the service's webhook API docs and repository conventions, then report and fix issues across trigger definitions, provider handler, output alignment, registration, and security. Use when validating or repairing a trigger under apps/sim/triggers/{service}/ or apps/sim/lib/webhooks/providers/{service}.ts . 激活提示：当用户任务与“validate-trigger”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/validate-trigger/SKILL.md`\n- **you-might-not-need-a-callback**（skill）：Analyze and fix useCallback anti-patterns in your code 激活提示：当用户任务与“you-might-not-need-a-callback”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/you-might-not-need-a-callback/SKILL.md`\n- **you-might-not-need-a-memo**（skill）：Analyze and fix useMemo/React.memo anti-patterns in your code 激活提示：当用户任务与“you-might-not-need-a-memo”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/you-might-not-need-a-memo/SKILL.md`\n- **you-might-not-need-an-effect**（skill）：Analyze and fix useEffect anti-patterns in your code 激活提示：当用户任务与“you-might-not-need-an-effect”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/you-might-not-need-an-effect/SKILL.md`\n- **you-might-not-need-state**（skill）：Analyze and fix unnecessary useState, derived state, and server-state-in-local-state anti-patterns 激活提示：当用户任务与“you-might-not-need-state”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.agents/skills/you-might-not-need-state/SKILL.md`\n- **add-hosted-key**（skill）：Add hosted API key support to a tool so Sim provides the key when users don't bring their own. Use when adding hosted keys, BYOK support, hideWhenHosted, or hosted key pricing to a tool or block. 激活提示：当用户任务与“add-hosted-key”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`.cursor/skills/add-hosted-key/SKILL.md`\n- **sim-helm**（skill）：Install, upgrade, and operate the Sim Helm chart on Kubernetes. Covers install path selection inline / existingSecret / External Secrets Operator , required secret generation, the values.yaml mental model env vs envDefaults vs Secret , and common failure triage. Invoke when a user asks about deploying Sim to a cluster, authoring a Sim values.yaml, debugging a Sim pod that won't start, upgrading a Sim release, or wir… 激活提示：当用户任务与“sim-helm”描述的流程高度相关时，先用它做安装前体验，再决定是否安装。 证据：`helm/sim/.claude/skills/sim-helm/SKILL.md`\n\n## 证据索引\n\n- 共索引 80 条证据。\n\n- **docs**（documentation）：This is a Next.js application generated with Create Fumadocs https://github.com/fuma-nama/fumadocs . 证据：`apps/docs/README.md`\n- **Sim Development Container**（documentation）：Development container configuration for VS Code Dev Containers and GitHub Codespaces. 证据：`.devcontainer/README.md`\n- **Sim Development Guidelines**（documentation）：You are a professional software engineer. All code must follow best practices: accurate, readable, clean, and efficient. 证据：`AGENTS.md`\n- **Sim Development Guidelines**（documentation）：You are a professional software engineer. All code must follow best practices: accurate, readable, clean, and efficient. 证据：`CLAUDE.md`\n- **Build Workflows with Ease**（documentation）：The open-source platform to build AI agents and run your agentic workforce. Connect 1,000+ integrations and LLMs to orchestrate agentic workflows. 证据：`README.md`\n- **Packages**（documentation）：Package Description --------- ------------- @sim/tsconfig ./tsconfig Shared TypeScript configs base, nextjs, library, library-build @sim/db ./db Database schema and Drizzle ORM utilities @sim/logger ./logger Structured logging with colored output @sim/testing ./testing Test factories, builders, and assertions 证据：`packages/README.md`\n- **Block Documentation Generator**（documentation）：This directory contains scripts to automatically generate documentation for all blocks in the Sim platform. 证据：`scripts/README.md`\n- **Sim App Scope**（documentation）：These rules apply to files under apps/sim/ in addition to the repository root AGENTS.md /AGENTS.md . 证据：`apps/sim/AGENTS.md`\n- **Blocks Scope**（documentation）：These rules apply to block definitions under apps/sim/blocks/ . 证据：`apps/sim/blocks/AGENTS.md`\n- **EMCN Components Scope**（documentation）：These rules apply to apps/sim/components/emcn/ . 证据：`apps/sim/components/emcn/AGENTS.md`\n- **Sim Enterprise Edition**（documentation）：This directory contains enterprise features that require a Sim Enterprise subscription for production use. 证据：`apps/sim/ee/README.md`\n- **Hooks Scope**（documentation）：These rules apply to custom hooks under apps/sim/ /hooks/ and apps/sim/ /use- .ts . 证据：`apps/sim/hooks/AGENTS.md`\n- **React Query Scope**（documentation）：These rules apply to apps/sim/hooks/queries/ . 证据：`apps/sim/hooks/queries/AGENTS.md`\n- **Guardrails Validators**（documentation）：Validation scripts for the Guardrails block. 证据：`apps/sim/lib/guardrails/README.md`\n- **Workflow Load Tests**（documentation）：These local-only Artillery scenarios exercise POST /api/workflows/ id /execute in async mode. 证据：`apps/sim/scripts/load/README.md`\n- **Stores Scope**（documentation）：These rules apply to Zustand stores under apps/sim/ /stores/ and apps/sim/ /store.ts . 证据：`apps/sim/stores/AGENTS.md`\n- **Tools Scope**（documentation）：These rules apply to integration tool definitions under apps/sim/tools/ . 证据：`apps/sim/tools/AGENTS.md`\n- **Triggers Scope**（documentation）：These rules apply to trigger definitions under apps/sim/triggers/ . 证据：`apps/sim/triggers/AGENTS.md`\n- **Sim Helm Chart**（documentation）：Deploy Sim https://sim.ai — the open-source AI workspace where teams build, deploy, and manage AI agents — on Kubernetes. 证据：`helm/sim/README.md`\n- **Sim CLI**（documentation）：Sim CLI allows you to run Sim https://sim.ai using Docker with a single command. 证据：`packages/cli/README.md`\n- **Sim Python SDK**（documentation）：The official Python SDK for Sim https://sim.ai , allowing you to execute workflows programmatically from your Python applications. 证据：`packages/python-sdk/README.md`\n- **Sim TypeScript SDK**（documentation）：The official TypeScript/JavaScript SDK for Sim https://sim.ai , allowing you to execute workflows programmatically from your applications. 证据：`packages/ts-sdk/README.md`\n- **Package**（package_manifest）：{ \"name\": \"simstudio\", \"packageManager\": \"bun@1.3.13\", \"version\": \"0.0.0\", \"private\": true, \"license\": \"Apache-2.0\", \"workspaces\": \"apps/ \", \"packages/ \" , \"scripts\": { \"build\": \"turbo run build\", \"dev\": \"turbo run dev\", \"dev:sockets\": \"cd apps/realtime && bun run dev\", \"dev:full\": \"bunx concurrently -n \\\"App,Realtime\\\" -c \\\"cyan,magenta\\\" \\\"cd apps/sim && bun run dev\\\" \\\"cd apps/realtime && bun run dev\\\"\", \"test\": \"turbo run test\", \"format\": \"turbo run format\", \"format:check\": \"turbo run format:check\", \"lint\": \"turbo run lint\", \"lint:check\": \"turbo run lint:check\", \"lint:helm\": \"helm lint ./helm/sim --strict --values ./helm/sim/test/values-lint.yaml\", \"lint:all\": \"turbo run lint && bun run… 证据：`package.json`\n- **Contributing to Sim**（documentation）：Thank you for your interest in contributing to Sim! Our goal is to provide developers with a powerful, user-friendly platform for building, testing, and optimizing agentic workflows. We welcome contributions in all forms—from bug fixes and design improvements to brand-new features. 证据：`.github/CONTRIBUTING.md`\n- **Package**（package_manifest）：{ \"name\": \"docs\", \"version\": \"0.0.0\", \"private\": true, \"license\": \"Apache-2.0\", \"scripts\": { \"dev\": \"next dev --port 3001\", \"build\": \"fumadocs-mdx && NODE OPTIONS='--max-old-space-size=8192' next build\", \"start\": \"next start\", \"postinstall\": \"fumadocs-mdx\", \"type-check\": \"tsc --noEmit\", \"lint\": \"biome check --write --unsafe .\", \"lint:check\": \"biome check .\", \"format\": \"biome format --write .\", \"format:check\": \"biome format .\" }, \"dependencies\": { \"@sim/db\": \"workspace: \", \"@tabler/icons-react\": \"^3.31.0\", \"@vercel/og\": \"^0.6.5\", \"class-variance-authority\": \"^0.7.1\", \"clsx\": \"^2.1.1\", \"drizzle-orm\": \"^0.45.2\", \"fumadocs-core\": \"16.8.5\", \"fumadocs-mdx\": \"14.3.2\", \"fumadocs-openapi\": \"10.8.1\",… 证据：`apps/docs/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@sim/realtime\", \"version\": \"0.1.0\", \"private\": true, \"license\": \"Apache-2.0\", \"type\": \"module\", \"engines\": { \"bun\": \" =1.2.13\", \"node\": \" =20.0.0\" }, \"scripts\": { \"dev\": \"bun --watch src/index.ts\", \"start\": \"bun src/index.ts\", \"type-check\": \"tsc --noEmit\", \"lint\": \"biome check --write --unsafe .\", \"lint:check\": \"biome check .\", \"format\": \"biome format --write .\", \"format:check\": \"biome format .\", \"test\": \"vitest run\", \"test:watch\": \"vitest\" }, \"dependencies\": { \"@sim/audit\": \"workspace: \", \"@sim/auth\": \"workspace: \", \"@sim/db\": \"workspace: \", \"@sim/logger\": \"workspace: \", \"@sim/realtime-protocol\": \"workspace: \", \"@sim/security\": \"workspace: \", \"@sim/utils\": \"workspace: \", \"@sim/w… 证据：`apps/realtime/package.json`\n- **Package**（package_manifest）：{ \"name\": \"sim\", \"version\": \"0.1.0\", \"private\": true, \"license\": \"Apache-2.0\", \"engines\": { \"bun\": \" =1.2.13\", \"node\": \" =20.0.0\" }, \"scripts\": { \"dev\": \"next dev --port 3000\", \"dev:webpack\": \"next dev --webpack\", \"load:workflow\": \"bun run load:workflow:baseline\", \"load:workflow:baseline\": \"BASE URL=${BASE URL:-http://localhost:3000} WARMUP DURATION=${WARMUP DURATION:-10} WARMUP RATE=${WARMUP RATE:-2} PEAK RATE=${PEAK RATE:-8} HOLD DURATION=${HOLD DURATION:-20} bunx artillery run scripts/load/workflow-concurrency.yml\", \"load:workflow:waves\": \"BASE URL=${BASE URL:-http://localhost:3000} WAVE ONE DURATION=${WAVE ONE DURATION:-10} WAVE ONE RATE=${WAVE ONE RATE:-6} QUIET DURATION=${QUIET DURATI… 证据：`apps/sim/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@sim/audit\", \"version\": \"0.1.0\", \"private\": true, \"sideEffects\": false, \"type\": \"module\", \"license\": \"Apache-2.0\", \"engines\": { \"bun\": \" =1.2.13\", \"node\": \" =20.0.0\" }, \"exports\": { \".\": { \"types\": \"./src/index.ts\", \"default\": \"./src/index.ts\" } }, \"scripts\": { \"type-check\": \"tsc --noEmit\", \"lint\": \"biome check --write --unsafe .\", \"lint:check\": \"biome check .\", \"format\": \"biome format --write .\", \"format:check\": \"biome format .\", \"test\": \"vitest run\", \"test:watch\": \"vitest\" }, \"dependencies\": { \"@sim/db\": \"workspace: \", \"@sim/logger\": \"workspace: \", \"@sim/utils\": \"workspace: \", \"drizzle-orm\": \"^0.45.2\" }, \"devDependencies\": { \"@sim/testing\": \"workspace: \", \"@sim/tsconfig\": \"work… 证据：`packages/audit/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@sim/auth\", \"version\": \"0.1.0\", \"private\": true, \"sideEffects\": false, \"type\": \"module\", \"license\": \"Apache-2.0\", \"engines\": { \"bun\": \" =1.2.13\", \"node\": \" =20.0.0\" }, \"exports\": { \"./verify\": { \"types\": \"./src/verify.ts\", \"default\": \"./src/verify.ts\" } }, \"scripts\": { \"type-check\": \"tsc --noEmit\", \"lint\": \"biome check --write --unsafe .\", \"lint:check\": \"biome check .\", \"format\": \"biome format --write .\", \"format:check\": \"biome format .\" }, \"dependencies\": { \"@sim/db\": \"workspace: \", \"better-auth\": \"1.3.12\" }, \"devDependencies\": { \"@sim/tsconfig\": \"workspace: \", \"typescript\": \"^5.7.3\" } } 证据：`packages/auth/package.json`\n- **Package**（package_manifest）：{ \"name\": \"simstudio\", \"version\": \"0.1.19\", \"description\": \"Sim CLI - Run Sim with a single command\", \"type\": \"module\", \"exports\": { \".\": { \"types\": \"./dist/index.d.ts\", \"import\": \"./dist/index.js\" } }, \"bin\": { \"simstudio\": \"dist/index.js\" }, \"scripts\": { \"build\": \"tsc\", \"type-check\": \"tsc --noEmit\", \"lint\": \"biome check --write --unsafe .\", \"lint:check\": \"biome check .\", \"format\": \"biome format --write .\", \"format:check\": \"biome format .\", \"prepublishOnly\": \"bun run build\" }, \"files\": \"dist\" , \"keywords\": \"simstudio\", \"ai\", \"workflow\", \"cli\", \"agent\", \"automation\", \"docker\" , \"author\": \"Sim\", \"license\": \"Apache-2.0\", \"engines\": { \"node\": \" =16\" }, \"dependencies\": { \"chalk\": \"^4.1.2\", \"com… 证据：`packages/cli/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@sim/db\", \"version\": \"0.1.0\", \"private\": true, \"type\": \"module\", \"license\": \"Apache-2.0\", \"engines\": { \"bun\": \" =1.2.13\", \"node\": \" =20.0.0\" }, \"exports\": { \".\": { \"types\": \"./index.ts\", \"default\": \"./index.ts\" }, \"./schema\": { \"types\": \"./schema.ts\", \"default\": \"./schema.ts\" } }, \"scripts\": { \"db:push\": \"bunx drizzle-kit push --config=./drizzle.config.ts\", \"db:migrate\": \"bun --env-file=.env run ./scripts/migrate.ts\", \"db:studio\": \"bunx drizzle-kit studio --config=./drizzle.config.ts\", \"test\": \"vitest run\", \"type-check\": \"tsc --noEmit\", \"lint\": \"biome check --write --unsafe .\", \"lint:check\": \"biome check .\", \"format\": \"biome format --write .\", \"format:check\": \"biome format .\" },… 证据：`packages/db/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@sim/logger\", \"version\": \"0.1.0\", \"private\": true, \"sideEffects\": false, \"type\": \"module\", \"license\": \"Apache-2.0\", \"engines\": { \"bun\": \" =1.2.13\", \"node\": \" =20.0.0\" }, \"exports\": { \".\": { \"types\": \"./src/index.ts\", \"default\": \"./src/index.ts\" } }, \"scripts\": { \"type-check\": \"tsc --noEmit\", \"lint\": \"biome check --write --unsafe .\", \"lint:check\": \"biome check .\", \"format\": \"biome format --write .\", \"format:check\": \"biome format .\", \"test\": \"vitest run\", \"test:watch\": \"vitest\" }, \"dependencies\": { \"chalk\": \"5.6.2\" }, \"devDependencies\": { \"@sim/tsconfig\": \"workspace: \", \"typescript\": \"^5.7.3\", \"vitest\": \"^3.0.8\" } } 证据：`packages/logger/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@sim/realtime-protocol\", \"version\": \"0.1.0\", \"private\": true, \"sideEffects\": false, \"type\": \"module\", \"license\": \"Apache-2.0\", \"engines\": { \"bun\": \" =1.2.13\", \"node\": \" =20.0.0\" }, \"exports\": { \"./constants\": { \"types\": \"./src/constants.ts\", \"default\": \"./src/constants.ts\" }, \"./schemas\": { \"types\": \"./src/schemas.ts\", \"default\": \"./src/schemas.ts\" } }, \"scripts\": { \"type-check\": \"tsc --noEmit\", \"lint\": \"biome check --write --unsafe .\", \"lint:check\": \"biome check .\", \"format\": \"biome format --write .\", \"format:check\": \"biome format .\" }, \"dependencies\": { \"zod\": \"4.3.6\" }, \"devDependencies\": { \"@sim/tsconfig\": \"workspace: \", \"typescript\": \"^5.7.3\" } } 证据：`packages/realtime-protocol/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@sim/security\", \"version\": \"0.1.0\", \"private\": true, \"sideEffects\": false, \"type\": \"module\", \"license\": \"Apache-2.0\", \"engines\": { \"bun\": \" =1.2.13\", \"node\": \" =20.0.0\" }, \"exports\": { \"./compare\": { \"types\": \"./src/compare.ts\", \"default\": \"./src/compare.ts\" }, \"./encryption\": { \"types\": \"./src/encryption.ts\", \"default\": \"./src/encryption.ts\" }, \"./hash\": { \"types\": \"./src/hash.ts\", \"default\": \"./src/hash.ts\" }, \"./hmac\": { \"types\": \"./src/hmac.ts\", \"default\": \"./src/hmac.ts\" }, \"./tokens\": { \"types\": \"./src/tokens.ts\", \"default\": \"./src/tokens.ts\" } }, \"scripts\": { \"type-check\": \"tsc --noEmit\", \"lint\": \"biome check --write --unsafe .\", \"lint:check\": \"biome check .\", \"format\": \"b… 证据：`packages/security/package.json`\n- **Package**（package_manifest）：{ \"name\": \"simstudio-ts-sdk\", \"version\": \"0.1.2\", \"description\": \"Sim SDK - Execute workflows programmatically\", \"type\": \"module\", \"exports\": { \".\": { \"types\": \"./dist/index.d.ts\", \"import\": \"./dist/index.js\" } }, \"scripts\": { \"build\": \"tsc\", \"type-check\": \"tsc --noEmit\", \"lint\": \"biome check --write --unsafe .\", \"lint:check\": \"biome check .\", \"format\": \"biome format --write .\", \"format:check\": \"biome format .\", \"dev:watch\": \"tsc --watch\", \"prepublishOnly\": \"bun run build\", \"test\": \"vitest run\", \"test:watch\": \"vitest\" }, \"files\": \"dist\" , \"keywords\": \"simstudio\", \"ai\", \"workflow\", \"sdk\", \"api\", \"automation\", \"typescript\" , \"author\": \"Sim\", \"license\": \"Apache-2.0\", \"dependencies\": { \"node-fe… 证据：`packages/ts-sdk/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@sim/tsconfig\", \"version\": \"0.0.0\", \"private\": true, \"sideEffects\": false, \"license\": \"Apache-2.0\", \"description\": \"Shared TypeScript configurations for Sim monorepo\", \"exports\": { \"./base.json\": \"./base.json\", \"./nextjs.json\": \"./nextjs.json\", \"./library.json\": \"./library.json\", \"./library-build.json\": \"./library-build.json\" } } 证据：`packages/tsconfig/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@sim/utils\", \"version\": \"0.1.0\", \"private\": true, \"sideEffects\": false, \"type\": \"module\", \"license\": \"Apache-2.0\", \"exports\": { \".\": { \"types\": \"./src/index.ts\", \"default\": \"./src/index.ts\" }, \"./id\": { \"types\": \"./src/id.ts\", \"default\": \"./src/id.ts\" }, \"./errors\": { \"types\": \"./src/errors.ts\", \"default\": \"./src/errors.ts\" }, \"./helpers\": { \"types\": \"./src/helpers.ts\", \"default\": \"./src/helpers.ts\" }, \"./formatting\": { \"types\": \"./src/formatting.ts\", \"default\": \"./src/formatting.ts\" } }, \"scripts\": { \"type-check\": \"tsc --noEmit\", \"lint\": \"biome check --write --unsafe .\", \"lint:check\": \"biome check .\", \"format\": \"biome format --write .\", \"format:check\": \"biome format .\", \"test\":… 证据：`packages/utils/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@sim/workflow-authz\", \"version\": \"0.1.0\", \"private\": true, \"sideEffects\": false, \"type\": \"module\", \"license\": \"Apache-2.0\", \"engines\": { \"bun\": \" =1.2.13\", \"node\": \" =20.0.0\" }, \"exports\": { \".\": { \"types\": \"./src/index.ts\", \"default\": \"./src/index.ts\" } }, \"scripts\": { \"type-check\": \"tsc --noEmit\", \"lint\": \"biome check --write --unsafe .\", \"lint:check\": \"biome check .\", \"format\": \"biome format --write .\", \"format:check\": \"biome format .\" }, \"dependencies\": { \"@sim/db\": \"workspace: \", \"drizzle-orm\": \"^0.45.2\" }, \"devDependencies\": { \"@sim/tsconfig\": \"workspace: \", \"typescript\": \"^5.7.3\" } } 证据：`packages/workflow-authz/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@sim/workflow-persistence\", \"version\": \"0.1.0\", \"private\": true, \"sideEffects\": false, \"type\": \"module\", \"license\": \"Apache-2.0\", \"engines\": { \"bun\": \" =1.2.13\", \"node\": \" =20.0.0\" }, \"exports\": { \".\": { \"types\": \"./src/index.ts\", \"default\": \"./src/index.ts\" }, \"./load\": { \"types\": \"./src/load.ts\", \"default\": \"./src/load.ts\" }, \"./save\": { \"types\": \"./src/save.ts\", \"default\": \"./src/save.ts\" }, \"./subblocks\": { \"types\": \"./src/subblocks.ts\", \"default\": \"./src/subblocks.ts\" }, \"./subflow-helpers\": { \"types\": \"./src/subflow-helpers.ts\", \"default\": \"./src/subflow-helpers.ts\" }, \"./types\": { \"types\": \"./src/types.ts\", \"default\": \"./src/types.ts\" } }, \"scripts\": { \"type-check\": \"tsc -… 证据：`packages/workflow-persistence/package.json`\n- **Package**（package_manifest）：{ \"name\": \"@sim/workflow-types\", \"version\": \"0.1.0\", \"private\": true, \"sideEffects\": false, \"type\": \"module\", \"license\": \"Apache-2.0\", \"engines\": { \"bun\": \" =1.2.13\", \"node\": \" =20.0.0\" }, \"exports\": { \"./blocks\": { \"types\": \"./src/blocks.ts\", \"default\": \"./src/blocks.ts\" }, \"./workflow\": { \"types\": \"./src/workflow.ts\", \"default\": \"./src/workflow.ts\" } }, \"scripts\": { \"type-check\": \"tsc --noEmit\", \"lint\": \"biome check --write --unsafe .\", \"lint:check\": \"biome check .\", \"format\": \"biome format --write .\", \"format:check\": \"biome format .\" }, \"peerDependencies\": { \"reactflow\": \"^11.11.4\" }, \"devDependencies\": { \"@sim/tsconfig\": \"workspace: \", \"reactflow\": \"^11.11.4\", \"typescript\": \"^5.7.3\" } } 证据：`packages/workflow-types/package.json`\n- **Add Block Skill**（skill_instruction）：You are an expert at creating block configurations for Sim. You understand the serializer, subBlock types, conditions, dependsOn, modes, and all UI patterns. 证据：`.agents/skills/add-block/SKILL.md`\n- **Add Connector Skill**（skill_instruction）：You are an expert at adding knowledge base connectors to Sim. A connector syncs documents from an external source Confluence, Google Drive, Notion, etc. into a knowledge base. 证据：`.agents/skills/add-connector/SKILL.md`\n- **Add Integration Skill**（skill_instruction）：You are an expert at adding complete integrations to Sim. This skill orchestrates the full process of adding a new service integration. 证据：`.agents/skills/add-integration/SKILL.md`\n- **Add Tools Skill**（skill_instruction）：You are an expert at creating tool configurations for Sim integrations. Your job is to read API documentation and create properly structured tool files. 证据：`.agents/skills/add-tools/SKILL.md`\n- **Add Trigger**（skill_instruction）：You are an expert at creating webhook triggers for Sim. You understand the trigger system, the generic buildTriggerSubBlocks helper, and how triggers connect to blocks. 证据：`.agents/skills/add-trigger/SKILL.md`\n- **Cleanup**（skill_instruction）：Arguments: - scope: what to review default: your current changes . Examples: \"diff to main\", \"PR 123\", \"src/components/\", \"whole codebase\" - fix: whether to apply fixes default: true . Set to false to only propose changes. 证据：`.agents/skills/cleanup/SKILL.md`\n- **EMCN Design Review**（skill_instruction）：Arguments: - scope: what to review default: your current changes . Examples: \"diff to main\", \"PR 123\", \"src/components/\", \"whole codebase\" - fix: whether to apply fixes default: true . Set to false to only propose changes. 证据：`.agents/skills/emcn-design-review/SKILL.md`\n- **React Query Best Practices**（skill_instruction）：Arguments: - scope: what to analyze default: your current changes . Examples: \"diff to main\", \"PR 123\", \"src/hooks/queries/\", \"whole codebase\" - fix: whether to apply fixes default: true . Set to false to only propose changes. 证据：`.agents/skills/react-query-best-practices/SKILL.md`\n- **Ship Command**（skill_instruction）：You help ship code by creating commits, pushing to the remote branch, and creating PRs in the user's voice. 证据：`.agents/skills/ship/SKILL.md`\n- **Validate Connector Skill**（skill_instruction）：You are an expert auditor for Sim knowledge base connectors. Your job is to thoroughly validate that an existing connector is correct, complete, and follows all conventions. 证据：`.agents/skills/validate-connector/SKILL.md`\n- **Validate Integration Skill**（skill_instruction）：You are an expert auditor for Sim integrations. Your job is to thoroughly validate that an existing integration is correct, complete, and follows all conventions. 证据：`.agents/skills/validate-integration/SKILL.md`\n- **Validate Trigger**（skill_instruction）：You are an expert auditor for Sim webhook triggers. Your job is to validate that an existing trigger implementation is correct, complete, secure, and aligned across all layers. 证据：`.agents/skills/validate-trigger/SKILL.md`\n- **You Might Not Need a Callback**（skill_instruction）：Arguments: - scope: what to analyze default: your current changes . Examples: \"diff to main\", \"PR 123\", \"src/components/\", \"whole codebase\" - fix: whether to apply fixes default: true . Set to false to only propose changes. 证据：`.agents/skills/you-might-not-need-a-callback/SKILL.md`\n- **You Might Not Need a Memo**（skill_instruction）：Arguments: - scope: what to analyze default: your current changes . Examples: \"diff to main\", \"PR 123\", \"src/components/\", \"whole codebase\" - fix: whether to apply fixes default: true . Set to false to only propose changes. 证据：`.agents/skills/you-might-not-need-a-memo/SKILL.md`\n- **You Might Not Need an Effect**（skill_instruction）：Arguments: - scope: what to analyze default: your current changes . Examples: \"diff to main\", \"PR 123\", \"src/components/\", \"whole codebase\" - fix: whether to apply fixes default: true . Set to false to only propose changes. 证据：`.agents/skills/you-might-not-need-an-effect/SKILL.md`\n- **You Might Not Need State**（skill_instruction）：Arguments: - scope: what to analyze default: your current changes . Examples: \"diff to main\", \"PR 123\", \"src/components/\", \"whole codebase\" - fix: whether to apply fixes default: true . Set to false to only propose changes. 证据：`.agents/skills/you-might-not-need-state/SKILL.md`\n- **Adding Hosted Key Support to a Tool**（skill_instruction）：Adding Hosted Key Support to a Tool 证据：`.cursor/skills/add-hosted-key/SKILL.md`\n- **Sim Helm Chart — Operations Skill**（skill_instruction）：This skill helps an agent deploy and operate the Sim Helm chart at helm/sim/ in the simstudioai/sim https://github.com/simstudioai/sim repository. Use it when the user is installing, upgrading, troubleshooting, or authoring values for the Sim chart. 证据：`helm/sim/.claude/skills/sim-helm/SKILL.md`\n- **Package**（package_manifest）：{ \"name\": \"@sim/testing\", \"version\": \"0.1.0\", \"private\": true, \"sideEffects\": \"./src/setup/ \" , \"type\": \"module\", \"license\": \"Apache-2.0\", \"engines\": { \"bun\": \" =1.2.13\", \"node\": \" =20.0.0\" }, \"exports\": { \".\": { \"types\": \"./src/index.ts\", \"default\": \"./src/index.ts\" }, \"./factories\": { \"types\": \"./src/factories/index.ts\", \"default\": \"./src/factories/index.ts\" }, \"./builders\": { \"types\": \"./src/builders/index.ts\", \"default\": \"./src/builders/index.ts\" }, \"./mocks\": { \"types\": \"./src/mocks/index.ts\", \"default\": \"./src/mocks/index.ts\" }, \"./mocks/executor\": { \"types\": \"./src/mocks/executor.mock.ts\", \"default\": \"./src/mocks/executor.mock.ts\" }, \"./assertions\": { \"types\": \"./src/assertions/index… 证据：`packages/testing/package.json`\n- **License**（source_file）：Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ 证据：`LICENSE`\n- 其余 20 条证据见 `AI_CONTEXT_PACK.json` 或 `EVIDENCE_INDEX.json`。\n\n## 宿主 AI 必须遵守的规则\n\n- **把本资产当作开工前上下文，而不是运行环境。**：AI Context Pack 只包含证据化项目理解，不包含目标项目的可执行状态。 证据：`apps/docs/README.md`, `.devcontainer/README.md`, `AGENTS.md`\n- **回答用户时区分可预览内容与必须安装后才能验证的内容。**：安装前体验的消费者价值来自降低误装和误判，而不是伪装成真实运行。 证据：`apps/docs/README.md`, `.devcontainer/README.md`, `AGENTS.md`\n\n## 用户开工前应该回答的问题\n\n- 你准备在哪个宿主 AI 或本地环境中使用它？\n- 你只是想先体验工作流，还是准备真实安装？\n- 你最在意的是安装成本、输出质量、还是和现有规则的冲突？\n\n## 验收标准\n\n- 所有能力声明都能回指到 evidence_refs 中的文件路径。\n- AI_CONTEXT_PACK.md 没有把预览包装成真实运行。\n- 用户能在 3 分钟内看懂适合谁、能做什么、如何开始和风险边界。\n\n---\n\n## Doramagic Context Augmentation\n\n下面内容用于强化 Repomix/AI Context Pack 主体。Human Manual 只提供阅读骨架；踩坑日志会被转成宿主 AI 必须遵守的工作约束。\n\n## Human Manual 骨架\n\n使用规则：这里只是项目阅读路线和显著性信号，不是事实权威。具体事实仍必须回到 repo evidence / Claim Graph。\n\n宿主 AI 硬性规则：\n- 不得把页标题、章节顺序、摘要或 importance 当作项目事实证据。\n- 解释 Human Manual 骨架时，必须明确说它只是阅读路线/显著性信号。\n- 能力、安装、兼容性、运行状态和风险判断必须引用 repo evidence、source path 或 Claim Graph。\n\n- **Project Introduction**：importance `high`\n  - source_paths: README.md, apps/sim/app/page.tsx\n- **Technology Stack**：importance `high`\n  - source_paths: apps/sim/package.json, apps/realtime/package.json, packages/db/drizzle.config.ts\n- **Architecture Overview**：importance `high`\n  - source_paths: apps/sim/blocks/registry.ts, apps/sim/blocks/index.ts, apps/sim/executor/index.ts\n- **Workflow Executor Engine**：importance `high`\n  - source_paths: apps/sim/executor/dag/builder.ts, apps/sim/executor/execution/engine.ts, apps/sim/executor/execution/executor.ts, apps/sim/executor/orchestrators/parallel.ts, apps/sim/executor/orchestrators/loop.ts\n- **Workflow Blocks System**：importance `high`\n  - source_paths: apps/sim/blocks/blocks/agent.ts, apps/sim/blocks/blocks/trigger.ts, apps/sim/blocks/blocks/loop.ts, apps/sim/blocks/blocks/parallel.ts, apps/sim/executor/handlers/registry.ts\n- **Integrations and Connectors**：importance `high`\n  - source_paths: apps/sim/connectors/registry.ts, apps/sim/connectors/slack/slack.ts, apps/sim/connectors/github/github.ts, apps/sim/connectors/types.ts\n- **Agent System**：importance `high`\n  - source_paths: apps/sim/executor/handlers/agent/agent-handler.ts, apps/sim/executor/handlers/agent/memory.ts, apps/sim/executor/handlers/agent/skills-resolver.ts, apps/sim/executor/handlers/agent/types.ts, apps/sim/blocks/blocks/agent.ts\n- **Copilot System**：importance `medium`\n  - source_paths: apps/sim/app/api/copilot/chat/stream/route.ts, apps/sim/app/api/copilot/checkpoints/route.ts, apps/sim/app/api/copilot/models/route.ts, apps/sim/app/api/copilot/training/route.ts\n\n## Repo Inspection Evidence / 源码检查证据\n\n- repo_clone_verified: true\n- repo_inspection_verified: true\n- repo_commit: `4efe99970c72e310ad86673e6557bd0b58cf76a5`\n- inspected_files: `package.json`, `README.md`, `packages/README.md`, `packages/cli/package.json`, `packages/cli/README.md`, `packages/cli/tsconfig.json`, `packages/testing/package.json`, `packages/testing/tsconfig.json`, `packages/audit/vitest.config.ts`, `packages/audit/package.json`, `packages/audit/tsconfig.json`, `packages/workflow-authz/package.json`, `packages/workflow-authz/tsconfig.json`, `packages/tsconfig/library.json`, `packages/tsconfig/package.json`, `packages/tsconfig/nextjs.json`, `packages/tsconfig/library-build.json`, `packages/tsconfig/base.json`, `packages/utils/vitest.config.ts`, `packages/utils/package.json`\n\n宿主 AI 硬性规则：\n- 没有 repo_clone_verified=true 时，不得声称已经读过源码。\n- 没有 repo_inspection_verified=true 时，不得把 README/docs/package 文件判断写成事实。\n- 没有 quick_start_verified=true 时，不得声称 Quick Start 已跑通。\n\n## Doramagic Pitfall Constraints / 踩坑约束\n\n这些规则来自 Doramagic 发现、验证或编译过程中的项目专属坑点。宿主 AI 必须把它们当作工作约束，而不是普通说明文字。\n\n### Constraint 1: 社区讨论暴露的待验证问题：Open-source general purpose agent with built-in MCPToolkit support\n\n- Trigger: Open-source general purpose agent with built-in MCPToolkit support 15 May 2025 · ... MCP for local-agent workflows · r/LocalLLaMA - A visual ... r/commandline - CLI tool to simplify open source monitoring agent installation.\n- Host AI rule: Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- Why it matters: 这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- Evidence: social_signal:reddit | ssig_7a250aac9fa1441c8186a7b73d669d8f | https://www.reddit.com/r/LocalLLaMA/comments/1kn8m8t/opensource_general_purpose_agent_with_builtin/ | Open-source general purpose agent with built-in MCPToolkit support\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 2: 可能修改宿主 AI 配置\n\n- Trigger: 项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- Host AI rule: 列出会写入的配置文件、目录和卸载/回滚步骤。\n- Why it matters: 安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- Evidence: capability.host_targets | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | host_targets=cursor\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 3: 能力判断依赖假设\n\n- Trigger: README/documentation is current enough for a first validation pass.\n- Host AI rule: 将假设转成下游验证清单。\n- Why it matters: 假设不成立时，用户拿不到承诺的能力。\n- Evidence: capability.assumptions | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | README/documentation is current enough for a first validation pass.\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 4: 来源证据：v0.6.63\n\n- Trigger: GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.6.63\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_5a97e1d742fe4d7f918e0b42f27b87c3 | https://github.com/simstudioai/sim/releases/tag/v0.6.63 | 来源类型 github_release 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 5: 来源证据：v0.6.65\n\n- Trigger: GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.6.65\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_03f18559029c4724b11011ef96259161 | https://github.com/simstudioai/sim/releases/tag/v0.6.65 | 来源类型 github_release 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 6: 来源证据：v0.6.67\n\n- Trigger: GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.6.67\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能增加新用户试用和生产接入成本。\n- Evidence: community_evidence:github | cevd_048d1506c1d645b0be435841a26b93ed | https://github.com/simstudioai/sim/releases/tag/v0.6.67 | 来源类型 github_release 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 7: 来源证据：v0.6.73\n\n- Trigger: GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.6.73\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能阻塞安装或首次运行。\n- Evidence: community_evidence:github | cevd_048864e1cdcc44d2b2a30917b7c4adc2 | https://github.com/simstudioai/sim/releases/tag/v0.6.73 | 来源类型 github_release 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 8: 来源证据：v0.6.71\n\n- Trigger: GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v0.6.71\n- Host AI rule: 来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- Why it matters: 可能阻塞安装或首次运行。\n- Evidence: community_evidence:github | cevd_9c30d794fb7344489f96a6ac47cd1d6e | https://github.com/simstudioai/sim/releases/tag/v0.6.71 | 来源类型 github_release 暴露的待验证使用条件。\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 9: 维护活跃度未知\n\n- Trigger: 未记录 last_activity_observed。\n- Host AI rule: 补 GitHub 最近 commit、release、issue/PR 响应信号。\n- Why it matters: 新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- Evidence: evidence.maintainer_signals | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | last_activity_observed missing\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n\n### Constraint 10: 下游验证发现风险项\n\n- Trigger: no_demo\n- Host AI rule: 进入安全/权限治理复核队列。\n- Why it matters: 下游已经要求复核，不能在页面中弱化。\n- Evidence: downstream_validation.risk_items | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | no_demo; severity=medium\n- Hard boundary: 不要把这个坑点包装成已解决、已验证或可忽略，除非后续验证证据明确证明它已经关闭。\n",
      "summary": "给宿主 AI 的上下文和工作边界。",
      "title": "AI Context Pack / 带给我的 AI"
    },
    "boundary_risk_card": {
      "asset_id": "boundary_risk_card",
      "filename": "BOUNDARY_RISK_CARD.md",
      "markdown": "# Boundary & Risk Card / 安装前决策卡\n\n项目：simstudioai/sim\n\n## Doramagic 试用结论\n\n当前结论：可以进入发布前推荐检查；首次使用仍应从最小权限、临时目录和可回滚配置开始。\n\n## 用户现在可以做\n\n- 可以先阅读 Human Manual，理解项目目的和主要工作流。\n- 可以复制 Prompt Preview 做安装前体验；这只验证交互感，不代表真实运行。\n- 可以把官方 Quick Start 命令放到隔离环境中验证，不要直接进主力环境。\n\n## 现在不要做\n\n- 不要把 Prompt Preview 当成项目实际运行结果。\n- 不要把 metadata-only validation 当成沙箱安装验证。\n- 不要把未验证能力写成“已支持、已跑通、可放心安装”。\n- 不要在首次试用时交出生产数据、私人文件、真实密钥或主力配置目录。\n\n## 安装前检查\n\n- 宿主 AI 是否匹配：cursor\n- 官方安装入口状态：已发现官方入口\n- 是否在临时目录、临时宿主或容器中验证：必须是\n- 是否能回滚配置改动：必须能\n- 是否需要 API Key、网络访问、读写文件或修改宿主配置：未确认前按高风险处理\n- 是否记录了安装命令、实际输出和失败日志：必须记录\n\n## 当前阻塞项\n\n- 无阻塞项。\n\n## 项目专属踩坑\n\n- 社区讨论暴露的待验证问题：Open-source general purpose agent with built-in MCPToolkit support（medium）：这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。 建议检查：Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- 可能修改宿主 AI 配置（medium）：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 能力判断依赖假设（medium）：假设不成立时，用户拿不到承诺的能力。 建议检查：将假设转成下游验证清单。\n- 来源证据：v0.6.63（medium）：可能增加新用户试用和生产接入成本。 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 来源证据：v0.6.65（medium）：可能增加新用户试用和生产接入成本。 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n\n## 风险与权限提示\n\n- no_demo: medium\n\n## 证据缺口\n\n- 暂未发现结构化证据缺口。\n",
      "summary": "安装、权限、验证和推荐前风险。",
      "title": "Boundary & Risk Card / 边界与风险卡"
    },
    "human_manual": {
      "asset_id": "human_manual",
      "filename": "HUMAN_MANUAL.md",
      "markdown": "# https://github.com/simstudioai/sim 项目说明书\n\n生成时间：2026-05-15 19:37:50 UTC\n\n## 目录\n\n- [Project Introduction](#project-introduction)\n- [Technology Stack](#tech-stack)\n- [Architecture Overview](#architecture-overview)\n- [Workflow Executor Engine](#executor-engine)\n- [Workflow Blocks System](#workflow-blocks)\n- [Integrations and Connectors](#integrations-connectors)\n- [Agent System](#agent-system)\n- [Copilot System](#copilot-system)\n- [Deployment Guide](#deployment-guide)\n- [Background Jobs and Background Processing](#background-jobs)\n\n<a id='project-introduction'></a>\n\n## Project Introduction\n\n### 相关页面\n\n相关主题：[Technology Stack](#tech-stack), [Architecture Overview](#architecture-overview)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [README.md](https://github.com/simstudioai/sim/blob/main/README.md)\n- [apps/sim/package.json](https://github.com/simstudioai/sim/blob/main/apps/sim/package.json)\n- [packages/python-sdk/README.md](https://github.com/simstudioai/sim/blob/main/packages/python-sdk/README.md)\n- [packages/ts-sdk/README.md](https://github.com/simstudioai/sim/blob/main/packages/ts-sdk/README.md)\n- [scripts/README.md](https://github.com/simstudioai/sim/blob/main/scripts/README.md)\n</details>\n\n# Project Introduction\n\nSim is an AI-powered workflow automation platform that enables users to build, deploy, and manage intelligent automation pipelines. The platform combines visual workflow design with AI capabilities, allowing teams to create sophisticated automation workflows without extensive coding knowledge.\n\n## Overview\n\nSim Studio provides a modern approach to workflow automation by integrating large language models (LLMs) directly into the automation pipeline. The platform supports both cloud-hosted and self-hosted deployment options, giving organizations flexibility in how they manage their automation infrastructure.\n\nThe project is structured as a monorepo containing multiple packages:\n\n| Package | Purpose |\n|---------|---------|\n| `apps/sim` | Main web application |\n| `packages/python-sdk` | Python SDK for programmatic access |\n| `packages/ts-sdk` | TypeScript SDK for programmatic access |\n| `scripts` | Automation and utility scripts |\n\n资料来源：[README.md:1-20]()\n\n## Key Features\n\n### AI-Native Automation\n\nSim leverages AI capabilities throughout the platform, enabling intelligent decision-making within workflows. The system supports integration with various AI providers including Ollama and vLLM for local model deployment.\n\n资料来源：[README.md:45-48]()\n\n### Multiple SDK Support\n\nThe platform provides official SDKs for both Python and TypeScript ecosystems, enabling developers to:\n\n- Execute workflows programmatically\n- Manage workflow deployments\n- Monitor execution status and results\n- Handle async job execution with polling\n\n资料来源：[packages/python-sdk/README.md:1-50]()\n资料来源：[packages/ts-sdk/README.md:1-40]()\n\n### Extensible Architecture\n\nSim includes support for various webhook providers and integrations:\n\n| Provider | Integration Type |\n|----------|------------------|\n| Webflow | CMS Webhook |\n| Typeform | Form Response |\n| Gong | Call Recording |\n| Vercel | Deployment Events |\n| Ashby | ATS Events |\n| Grain | Meeting Recording |\n| Salesforce | CRM Events |\n\n资料来源：[apps/sim/lib/webhooks/providers/webflow.ts:1-50]()\n资料来源：[apps/sim/lib/webhooks/providers/typeform.ts:1-40]()\n\n## Architecture Overview\n\n```mermaid\ngraph TD\n    A[Client Application] --> B[Next.js Web App]\n    B --> C[Workflow Engine]\n    C --> D[Sandbox Executor]\n    C --> E[Webhook System]\n    D --> F[AI Providers]\n    E --> G[External Services]\n    F --> H[Ollama / vLLM]\n    F --> I[Cloud LLM APIs]\n```\n\n### Core Components\n\n#### Web Application (`apps/sim`)\n\nThe main React-based web application built with Next.js that provides:\n\n- Visual workflow editor\n- Block-based workflow construction\n- Trigger configuration\n- Execution monitoring\n- Workspace management\n\nThe application uses TypeScript with strict type checking enabled via `tsc --noEmit`.\n\n资料来源：[apps/sim/package.json:1-30]()\n\n#### Workflow Engine\n\nThe workflow engine handles:\n\n- Workflow parsing and validation\n- Execution scheduling\n- State management\n- Error handling and retries\n\n#### Sandbox Executor\n\nSandboxed execution environment for running workflow blocks safely with resource isolation.\n\n资料来源：[apps/sim/package.json:8-12]()\n\n## Deployment Options\n\nSim supports three primary self-hosted deployment methods.\n\n### Comparison Matrix\n\n| Method | Docker Required | Manual Setup | Use Case |\n|--------|-----------------|--------------|----------|\n| NPM Package | Yes | Minimal | Quick local testing |\n| Docker Compose | Yes | Moderate | Production deployments |\n| Manual Setup | No | Extensive | Custom infrastructure |\n\n资料来源：[README.md:25-50]()\n\n### Option 1: NPM Package (Quick Start)\n\nThe fastest way to get started locally:\n\n```bash\nnpx simstudio\n```\n\nThis command pulls the latest Docker images and starts Sim at http://localhost:3000.\n\n**Options:**\n\n| Flag | Description | Default |\n|------|-------------|---------|\n| `-p, --port <port>` | Port to run Sim on | `3000` |\n| `--no-pull` | Skip pulling latest Docker images | `false` |\n\n资料来源：[README.md:25-32]()\n\n### Option 2: Docker Compose\n\nFor production-ready deployments with persistent storage:\n\n```bash\ngit clone https://github.com/simstudioai/sim.git && cd sim\ndocker compose -f docker-compose.prod.yml up -d\n```\n\n资料来源：[README.md:34-38]()\n\n### Option 3: Manual Setup\n\nFor custom infrastructure configurations. Requires manual installation of all dependencies.\n\n资料来源：[README.md:40-45]()\n\n## System Requirements\n\n### Hardware Requirements\n\n| Component | Minimum | Recommended |\n|-----------|---------|-------------|\n| CPU | 2 cores | 4+ cores |\n| RAM | 4 GB | 8+ GB |\n| Disk | 10 GB | 20+ GB |\n\n### Software Requirements\n\n| Software | Version | Notes |\n|----------|---------|-------|\n| Docker | Latest | Required for NPM and Docker Compose methods |\n| Bun | Latest | Required for manual setup |\n| Node.js | v20+ | Required for manual setup |\n| PostgreSQL | 12+ | Must include pgvector extension |\n\n资料来源：[README.md:40-45]()\n\n### Database Configuration\n\nPostgreSQL with pgvector is required for vector storage capabilities:\n\n```bash\ndocker run --name simstudio-db \\\n  -e POSTGRES_PASSWORD=your_password \\\n  -e POSTGRES_DB=simstudio \\\n  -p 5432:5432 -d \\\n  pgvector/pgvector:pg16\n```\n\n资料来源：[README.md:50-55]()\n\n## SDK Data Structures\n\n### WorkflowExecutionResult\n\n```python\n@dataclass\nclass WorkflowExecutionResult:\n    success: bool\n    output: Optional[Any] = None\n    error: Optional[str] = None\n    logs: Optional[list] = None\n    metadata: Optional[Dict[str, Any]] = None\n    trace_spans: Optional[list] = None\n    total_duration: Optional[float] = None\n```\n\n资料来源：[packages/python-sdk/README.md:80-90]()\n\n### WorkflowStatus\n\n```python\n@dataclass\nclass WorkflowStatus:\n    is_deployed: bool\n    deployed_at: Optional[str] = None\n    needs_redeployment: bool = False\n```\n\n资料来源：[packages/python-sdk/README.md:100-105]()\n\n### RateLimitInfo\n\n```python\n@dataclass\nclass RateLimitInfo:\n    limit: int\n    remaining: int\n    reset: int\n    retry_after: Optional[int] = None\n```\n\n资料来源：[packages/python-sdk/README.md:125-130]()\n\n## Development Workflow\n\n### Code Quality Tools\n\nThe project enforces code quality through Biome:\n\n| Command | Purpose |\n|---------|---------|\n| `bun run lint` | Format and lint with auto-fix |\n| `bun run lint:check` | Check linting without auto-fix |\n| `bun run format` | Format code files |\n| `bun run format:check` | Check formatting without changes |\n| `bun run type-check` | Run TypeScript type checking |\n\n资料来源：[apps/sim/package.json:15-22]()\n\n### Testing\n\nTests are run using Vitest:\n\n| Command | Purpose |\n|---------|---------|\n| `bun run test` | Run tests once |\n| `bun run test:watch` | Run tests in watch mode |\n| `bun run test:coverage` | Generate coverage report |\n\n资料来源：[apps/sim/package.json:14-17]()\n\n## Local Model Support\n\nSim supports self-hosted AI models through two providers:\n\n### Ollama\n\nIntegration with [Ollama](https://ollama.ai) for running local LLMs including Llama 2, Mistral, and other open-source models.\n\n### vLLM\n\nIntegration with [vLLM](https://docs.vllm.ai/) for high-performance inference serving.\n\n资料来源：[README.md:45-48]()\n\n## Documentation Generation\n\nThe project includes automated documentation generation:\n\n```bash\nbun run generate-docs\n```\n\nThis script preserves manual content markers within the codebase for custom documentation sections.\n\n资料来源：[scripts/README.md:1-30]()\n\n## Community and Support\n\n| Resource | Link |\n|----------|------|\n| Documentation | https://docs.sim.ai |\n| Discord Community | Discord |\n| Twitter | @simdotai |\n| DeepWiki | DeepWiki |\n\n资料来源：[README.md:1-15]()\n\n## License\n\nThe project is licensed under Apache-2.0.\n\n资料来源：[packages/python-sdk/README.md:70]()\n资料来源：[packages/ts-sdk/README.md:45]()\n\n---\n\n<a id='tech-stack'></a>\n\n## Technology Stack\n\n### 相关页面\n\n相关主题：[Project Introduction](#project-introduction), [Deployment Guide](#deployment-guide)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [apps/sim/package.json](https://github.com/simstudioai/sim/blob/main/apps/sim/package.json)\n- [apps/realtime/package.json](https://github.com/simstudioai/sim/blob/main/apps/realtime/package.json)\n- [packages/ts-sdk/README.md](https://github.com/simstudioai/sim/blob/main/packages/ts-sdk/README.md)\n- [packages/python-sdk/README.md](https://github.com/simstudioai/sim/blob/main/packages/python-sdk/README.md)\n- [packages/db/drizzle.config.ts](https://github.com/simstudioai/sim/blob/main/packages/db/drizzle.config.ts)\n- [README.md](https://github.com/simstudioai/sim/blob/main/README.md)\n- [apps/sim/lib/knowledge/documents/document-processor.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/knowledge/documents/document-processor.ts)\n- [apps/sim/lib/core/security/input-validation.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/core/security/input-validation.ts)\n</details>\n\n# Technology Stack\n\n## Overview\n\nThe Sim platform is built on a modern, polyglot technology stack designed to support both frontend and backend development with a focus on developer productivity, type safety, and scalable deployment options. The system leverages TypeScript as the primary language for the core application, Python for the SDK ecosystem, and Docker for containerization and self-hosted deployments.\n\n## Core Runtime Environment\n\n### Bun\n\nBun serves as the primary package manager and runtime for the project. All build scripts, dependency installations, and development workflows are configured to use Bun workspaces for efficient monorepo management.\n\n```bash\nbun install\nbun run build\nbun run test\n```\n\n资料来源：[apps/sim/package.json:11-30]()\n\n### Node.js Requirements\n\nThe main application requires Node.js v20+ for runtime compatibility. The TypeScript SDK specifies Node.js 18+ as the minimum requirement.\n\n| Component | Minimum Version | Recommended Version |\n|-----------|-----------------|---------------------|\n| Main App (apps/sim) | Node.js v20+ | Latest LTS |\n| TypeScript SDK | Node.js 18+ | Node.js 20+ |\n| Python SDK | Python 3.8+ | Python 3.11+ |\n\n资料来源：[README.md:35-45](), [packages/ts-sdk/README.md:42]()\n\n## Frontend Architecture\n\n### Next.js Framework\n\nThe main Sim application is built on Next.js, providing server-side rendering, API routes, and static generation capabilities.\n\n**Build Configuration:**\n\n```json\n{\n  \"build\": \"bun run build:sandbox-bundles && NODE_OPTIONS='--max-old-space-size=8192' next build\",\n  \"start\": \"next start\"\n}\n```\n\n资料来源：[apps/sim/package.json:15-16]()\n\n### Testing Framework\n\n| Tool | Purpose | Command |\n|------|---------|---------|\n| Vitest | Unit and integration testing | `bun run test` |\n| Vitest (watch mode) | Development testing | `bun run test:watch` |\n| Vitest (coverage) | Coverage reports | `bun run test:coverage` |\n\n资料来源：[apps/sim/package.json:19-21]()\n\n### Code Quality Tools\n\n| Tool | Purpose | Commands |\n|------|---------|----------|\n| Biome | Linting and formatting | `lint`, `lint:check`, `format`, `format:check` |\n| TypeScript Compiler | Type checking | `type-check` |\n\nBiome is configured for both linting (with unsafe auto-fixes) and code formatting:\n\n```bash\nbun run lint        # Apply lint fixes\nbun run lint:check # Check only\nbun run format     # Apply formatting\nbun run format:check\n```\n\n资料来源：[apps/sim/package.json:22-25]()\n\n## Backend and Database\n\n### PostgreSQL with pgvector\n\nThe platform requires PostgreSQL 12+ with the pgvector extension for vector similarity search capabilities. This enables knowledge base and document embedding features.\n\n**Docker Setup:**\n\n```bash\ndocker run --name simstudio-db \\\n  -e POSTGRES_PASSWORD=your_password \\\n  -e POSTGRES_DB=simstudio \\\n  -p 5432:5432 \\\n  -d pgvector/pgvector:pg16\n```\n\n资料来源：[README.md:45-50]()\n\n### Drizzle ORM\n\nDatabase operations are managed through Drizzle ORM, configured via `drizzle.config.ts`. This provides type-safe database queries and migrations.\n\n```typescript\nimport { defineConfig } from 'drizzle-kit'\n```\n\n资料来源：[packages/db/drizzle.config.ts]()\n\n## Document Processing\n\n### OCR Integration\n\nThe document processor integrates with multiple OCR providers for extracting content from PDFs and images:\n\n| Provider | Configuration | Timeout |\n|----------|---------------|---------|\n| Mistral OCR API | API Key + Endpoint | 30 seconds |\n| Azure Mistral OCR | API Key + Endpoint + Model | 30 seconds |\n\n资料来源：[apps/sim/lib/knowledge/documents/document-processor.ts:1-80]()\n\nThe OCR system uses:\n\n- Native `fetch` API for HTTP requests\n- AbortController for timeout management\n- Base64 encoding for file uploads\n\n## SDK Ecosystem\n\n### TypeScript SDK\n\nThe TypeScript SDK (`packages/ts-sdk`) provides programmatic access to Sim features:\n\n| Requirement | Version |\n|-------------|---------|\n| Node.js | 18+ |\n| TypeScript | 5.0+ |\n\n**Development Commands:**\n\n```bash\nbun run test    # Run tests\nbun run build  # Compile to dist/\nbun run dev    # Development mode with auto-rebuild\n```\n\n资料来源：[packages/ts-sdk/README.md:1-45]()\n\n### Python SDK\n\nThe Python SDK (`packages/python-sdk`) offers Python integration:\n\n| Requirement | Version |\n|-------------|---------|\n| Python | 3.8+ |\n| requests | >= 2.25.0 |\n\n**Code Quality Tools:**\n\n```bash\nblack simstudio/           # Code formatting\nflake8 simstudio/          # Linting\nmypy simstudio/            # Type checking\nisort simstudio/           # Import sorting\n```\n\n资料来源：[packages/python-sdk/README.md:1-50]()\n\n## Security Infrastructure\n\n### Input Validation\n\nThe platform implements comprehensive input validation for security:\n\n- **Enum Validation**: Validates values against allowed lists\n- **Hostname Validation**: Prevents SSRF attacks by checking for private IPs, localhost, and reserved addresses\n- **Proxy URL Validation**: Secure proxy configuration validation\n\n资料来源：[apps/sim/lib/core/security/input-validation.ts:1-100]()\n\n## Deployment Options\n\n### Docker Containerization\n\nSim supports multiple deployment scenarios:\n\n```mermaid\ngraph TD\n    A[Sim Deployment Options] --> B[Docker (NPM Package)]\n    A --> C[Docker Compose]\n    A --> D[Manual Setup]\n    \n    B --> B1[npx simstudio]\n    C --> C1[docker compose up]\n    D --> D1[Bun + PostgreSQL]\n```\n\n资料来源：[README.md:25-50]()\n\n### Local Model Support\n\nThe platform supports self-hosted AI models through:\n\n| Runtime | Description |\n|---------|-------------|\n| Ollama | Local model inference |\n| vLLM | High-performance LLM serving |\n\n## Realtime Application\n\nThe `apps/realtime` package provides WebSocket-based communication features with its own independent package.json configuration.\n\n资料来源：[apps/realtime/package.json]()\n\n## Load Testing Infrastructure\n\nThe project includes Artillery-based load testing for workflow performance validation:\n\n| Script | Purpose |\n|--------|---------|\n| `load:workflow:waves` | Wave-based load testing |\n| `load:workflow:isolation` | Workspace isolation testing |\n\n**Configuration Options:**\n\n| Environment Variable | Default | Description |\n|---------------------|---------|-------------|\n| `WAVE_ONE_DURATION` | 60 | Wave 1 duration in seconds |\n| `WAVE_ONE_RATE` | 10 | Wave 1 request rate |\n| `WORKSPACE_A_WEIGHT` | 8 | Workspace A load weight |\n| `WORKSPACE_B_WEIGHT` | 1 | Workspace B load weight |\n\n资料来源：[apps/sim/package.json:8-14]()\n\n## Webhook Integrations\n\nThe platform provides webhook providers for third-party integrations:\n\n| Provider | Purpose |\n|----------|---------|\n| Gong | Meeting/call automation |\n| Vercel | Deployment events |\n| Typeform | Form responses |\n| Webflow | CMS events |\n| WhatsApp | Messaging events |\n\nEach provider implements signature verification for security:\n\n```typescript\nverifyAuth: createHmacVerifier({\n  configKey: 'secret',\n  headerName: 'Provider-Signature',\n  validateFn: validateProviderSignature,\n  providerLabel: 'ProviderName',\n})\n```\n\n资料来源：[apps/sim/lib/webhooks/providers/gong.ts](), [apps/sim/lib/webhooks/providers/vercel.ts](), [apps/sim/lib/webhooks/providers/typeform.ts](), [apps/sim/lib/webhooks/providers/webflow.ts](), [apps/sim/lib/webhooks/providers/whatsapp.ts]()\n\n## Architecture Diagram\n\n```mermaid\ngraph TB\n    subgraph \"Client Layer\"\n        WebApp[Web Application<br/>Next.js]\n        TS_SDK[TypeScript SDK<br/>Node.js 18+]\n    end\n    \n    subgraph \"Runtime\"\n        Bun[Bun Runtime<br/>Workspaces]\n        Node[Node.js v20+]\n    end\n    \n    subgraph \"Backend Services\"\n        API[API Routes]\n        Webhooks[Webhook Providers]\n        Security[Input Validation]\n    end\n    \n    subgraph \"Data Layer\"\n        Postgres[PostgreSQL + pgvector<br/>Drizzle ORM]\n        Knowledge[Document Processor<br/>OCR Integration]\n    end\n    \n    subgraph \"Deployment\"\n        Docker[Docker Container]\n        Ollama[Ollama]\n        VLLM[vLLM]\n    end\n    \n    WebApp --> API\n    TS_SDK --> API\n    API --> Postgres\n    API --> Knowledge\n    WebApp --> Webhooks\n    Security --> API\n    Docker --> Postgres\n    Ollama --> API\n    VLLM --> API\n```\n\n## Summary Table\n\n| Category | Technology | Version/Notes |\n|----------|------------|---------------|\n| Runtime | Bun | Workspaces for monorepo |\n| Runtime | Node.js | v20+ for main app |\n| Runtime | Python | 3.8+ for Python SDK |\n| Framework | Next.js | Full-stack React framework |\n| Database | PostgreSQL | 12+ with pgvector |\n| ORM | Drizzle | Type-safe queries |\n| Testing | Vitest | Unit and integration tests |\n| Linting | Biome | Fast JS/TS linter |\n| OCR | Mistral/Azure | Document processing |\n| SDKs | TypeScript/Python | Multi-language support |\n| Deployment | Docker | Self-hosted option |\n| AI Runtime | Ollama/vLLM | Local model support |\n\n---\n\n<a id='architecture-overview'></a>\n\n## Architecture Overview\n\n### 相关页面\n\n相关主题：[Workflow Executor Engine](#executor-engine), [Workflow Blocks System](#workflow-blocks)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [apps/sim/blocks/registry.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/blocks/registry.ts)\n- [apps/sim/blocks/index.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/blocks/index.ts)\n- [apps/sim/executor/index.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/executor/index.ts)\n- [apps/sim/lib/workflows/triggers/triggers.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/triggers/triggers.ts)\n- [apps/sim/lib/workflows/diff/diff-engine.test.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/diff/diff-engine.test.ts)\n- [apps/sim/lib/api/contracts/types.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/api/contracts/types.ts)\n- [apps/sim/lib/webhooks/providers/gong.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/webhooks/providers/gong.ts)\n- [apps/sim/lib/webhooks/pending-verification.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/webhooks/pending-verification.ts)\n\n</details>\n\n# Architecture Overview\n\nSim is an open-source platform for building AI agents and orchestrating agentic workflows. It connects over 1,000 integrations and LLMs to enable sophisticated automation scenarios. The platform is built with a modular architecture centered around **blocks**, **workflows**, **triggers**, and an **execution engine**.\n\n## High-Level Architecture\n\nThe Sim platform follows a layered architecture:\n\n```mermaid\ngraph TD\n    subgraph \"Presentation Layer\"\n        UI[Next.js Application]\n    end\n    \n    subgraph \"API Layer\"\n        API[API Routes]\n        Contracts[Contract Types]\n    end\n    \n    subgraph \"Workflow Engine\"\n        WE[Workflow Engine]\n        Diff[Diff Engine]\n        Registry[Block Registry]\n    end\n    \n    subgraph \"Execution Layer\"\n        Executor[Executor]\n        Sandbox[Sandbox Runner]\n    end\n    \n    subgraph \"Integration Layer\"\n        Webhooks[Webhook Providers]\n        Triggers[Trigger System]\n        Tools[Tool System]\n    end\n    \n    UI --> API\n    API --> Contracts\n    Contracts --> WE\n    WE --> Registry\n    WE --> Diff\n    Registry --> Executor\n    Executor --> Sandbox\n    Webhooks --> Triggers\n    Triggers --> WE\n```\n\n## Core Components\n\n### Block Registry System\n\nThe Block Registry is the central component that manages all available blocks in the system. Blocks are the fundamental building units of workflows, representing discrete operations like data transformation, API calls, or AI interactions.\n\n**Key Files:**\n- `apps/sim/blocks/registry.ts` - Block registration and retrieval\n- `apps/sim/blocks/index.ts` - Block exports and public API\n\n**Registry Functions:**\n\n| Function | Purpose |\n|----------|---------|\n| `getBlock(type)` | Retrieve a specific block by type identifier |\n| `getAllBlocks()` | Get all registered blocks |\n| `getAllBlockTypes()` | Get list of all block type identifiers |\n| `getBlockByToolName(name)` | Find block by associated tool name |\n| `getBlocksByCategory(category)` | Filter blocks by category |\n| `isValidBlockType(type)` | Validate if a block type exists |\n| `registry` | The underlying registry data structure |\n\n资料来源：[apps/sim/blocks/index.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/blocks/index.ts)\n\n**Block Configuration Interface:**\n\nThe registry is mocked in tests to return null or empty values for blocks, indicating dynamic resolution at runtime:\n\n```typescript\nvi.mock('@/blocks', () => ({\n  getBlock: () => null,\n  getAllBlocks: () => ({}),\n  getAllBlockTypes: () => [],\n  getBlockByToolName: () => null,\n  getBlocksByCategory: () => [],\n  isValidBlockType: () => false,\n  registry: {},\n}))\n```\n\n资料来源：[apps/sim/lib/workflows/diff/diff-engine.test.ts:1-20](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/diff/diff-engine.test.ts)\n\n### Trigger System\n\nThe Trigger System manages how workflows are initiated. Triggers can be manual, API-based, chat-based, or event-driven.\n\n**Trigger Types:**\n\n| Type | Identifier | Description |\n|------|------------|-------------|\n| Manual | `TRIGGER_TYPES.START` | User-initiated workflow start |\n| API | `TRIGGER_TYPES.API` | Programmatic workflow invocation |\n| Chat | `TRIGGER_TYPES.CHAT` | Chat-triggered workflows |\n| Starter | `TRIGGER_TYPES.STARTER` | Legacy starter block support |\n\n资料来源：[apps/sim/lib/workflows/triggers/triggers.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/triggers/triggers.ts)\n\n**Trigger Reference Alias Map:**\n\nThe system maps reference aliases to concrete trigger block types:\n\n```typescript\nexport const TRIGGER_REFERENCE_ALIAS_MAP = {\n  start: TRIGGER_TYPES.START,\n  api: TRIGGER_TYPES.API,\n  chat: TRIGGER_TYPES.CHAT,\n  manual: TRIGGER_TYPES.START,\n} as const\n```\n\n**TriggerUtils Class:**\n\nThe `TriggerUtils` class provides static methods for trigger identification:\n\n```typescript\nexport class TriggerUtils {\n  static isTriggerBlock(block: { type: string; triggerMode?: boolean }): boolean {\n    const blockConfig = getBlock(block.type)\n    return (\n      blockConfig?.category === 'triggers' ||\n      block.triggerMode === true ||\n      block.type === TRIGGER_TYPES.STARTER\n    )\n  }\n\n  static isTriggerType(block: { type: string }, triggerType: TriggerType): boolean {\n    return block.type === triggerType\n  }\n}\n```\n\n资料来源：[apps/sim/lib/workflows/triggers/triggers.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/triggers/triggers.ts)\n\n### Workflow Engine\n\nThe Workflow Engine orchestrates the execution of blocks within a workflow context.\n\n**Workflow Components:**\n\n| Component | File | Purpose |\n|-----------|------|---------|\n| Diff Engine | `lib/workflows/diff/diff-engine.test.ts` | Computes differences between workflow versions |\n| Block Outputs | `lib/workflows/blocks/block-outputs` | Manages output data flow between blocks |\n| Visibility | `lib/workflows/subblocks/visibility` | Controls block visibility and canonical modes |\n| Triggers | `lib/workflows/triggers/triggers.ts` | Workflow initiation logic |\n\n资料来源：[apps/sim/lib/workflows/diff/diff-engine.test.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/diff/diff-engine.test.ts)\n\n**Workflow Registry Store:**\n\nThe engine integrates with a workflow registry store for state management:\n\n```typescript\nvi.mock('@/stores/workflows/registry/store', () => ({\n  useWorkflowRegistry: {\n    getState: () => ({\n      activeWorkflowId: null,\n    }),\n  },\n}))\n```\n\n### Execution Engine\n\nThe Execution Engine is responsible for running workflows and blocks in a sandboxed environment.\n\n**Execution Constants:**\n\n| Constant | Purpose |\n|----------|---------|\n| `BLOCK_DIMENSIONS` | Defines minimum block height and dimensions |\n| `HANDLE_POSITIONS` | Manages connection handle placement |\n| `isAnnotationOnlyBlock()` | Determines if a block is annotation-only |\n\n```typescript\nvi.mock('@/executor/constants', () => ({\n  isAnnotationOnlyBlock: () => false,\n  BLOCK_DIMENSIONS: { MIN_HEIGHT: 100 },\n  HANDLE_POSITIONS: {},\n}))\n```\n\n资料来源：[apps/sim/lib/workflows/diff/diff-engine.test.ts:1-20](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/diff/diff-engine.test.ts)\n\n### API Contract System\n\nThe API Contract System provides type-safe API route definitions and type inference utilities.\n\n**Contract Type Generics:**\n\n| Type | Description |\n|------|-------------|\n| `ContractParams<C>` | Extracts URL parameters from contract |\n| `ContractQuery<C>` | Extracts query parameters from contract |\n| `ContractBody<C>` | Extracts request body from contract |\n| `ContractHeaders<C>` | Extracts headers from contract |\n\n```typescript\nexport type ContractParams<C extends AnyApiRouteContract> = C extends ApiRouteContract<\n  infer TParams,\n  ApiSchema | undefined,\n  ApiSchema | undefined,\n  ApiSchema | undefined,\n  ResponseMode,\n  ApiSchema | undefined\n>\n  ? EmptySchemaOutput<TParams>\n  : undefined\n```\n\n资料来源：[apps/sim/lib/api/contracts/types.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/api/contracts/types.ts)\n\n## Webhook Integration\n\nSim supports multiple webhook providers for event-driven workflow triggering.\n\n**Supported Providers:**\n\n| Provider | File | Key Features |\n|----------|------|--------------|\n| Gong | `lib/webhooks/providers/gong.ts` | Automation rules, call data |\n| Webflow | `lib/webhooks/providers/webflow.ts` | Collection filtering, CMS events |\n| Typeform | `lib/webhooks/providers/typeform.ts` | Form responses, HMAC verification |\n| Vercel | `lib/webhooks/providers/vercel.ts` | Deployment events |\n\n**Gong Provider Structure:**\n\n```typescript\n{\n  eventType: 'gong.automation_rule',\n  callId,\n  metaData,\n  parties: (callData?.parties as unknown[]) || [],\n  context: (callData?.context as unknown[]) || [],\n  trackers: (content?.trackers as unknown[]) || [],\n  topics: (content?.topics as unknown[]) || [],\n  highlights: (content?.highlights as unknown[]) || [],\n}\n```\n\n资料来源：[apps/sim/lib/webhooks/providers/gong.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/webhooks/providers/gong.ts)\n\n**Webhook Event Filtering:**\n\nProviders implement event filtering logic:\n\n```typescript\nshouldSkipEvent({ webhook, body, requestId, providerConfig }: EventFilterContext) {\n  const configuredCollectionId = providerConfig.collectionId as string | undefined\n  if (configuredCollectionId) {\n    const obj = body as Record<string, unknown>\n    const payload = obj.payload as Record<string, unknown> | undefined\n    const payloadCollectionId = (payload?.collectionId ?? obj.collectionId) as string | undefined\n\n    if (payloadCollectionId && payloadCollectionId !== configuredCollectionId) {\n      return true\n    }\n  }\n  return false\n}\n```\n\n资料来源：[apps/sim/lib/webhooks/providers/webflow.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/webhooks/providers/webflow.ts)\n\n**Pending Verification System:**\n\nWebhook verification is handled through a pending verification mechanism:\n\n| Provider | Verification Method |\n|----------|---------------------|\n| Ashby | Always valid |\n| Grain | GET/HEAD or POST without body |\n| Generic | GET/HEAD or POST without body |\n| Salesforce | GET/HEAD or POST without body |\n\n```typescript\nconst pendingWebhookVerificationProbeMatchers: Record<\n  string,\n  PendingWebhookVerificationProbeMatcher\n> = {\n  ashby: ({ method, body }) => method === 'POST' && body?.action === 'ping',\n  grain: ({ method, body }) =>\n    method === 'GET' ||\n    method === 'HEAD' ||\n    (method === 'POST' && (!body || Object.keys(body).length === 0 || !body.type)),\n  generic: ({ method, body }) =>\n    method === 'GET' ||\n    method === 'HEAD' ||\n    (method === 'POST' && (!body || Object.keys(body).length === 0)),\n  salesforce: ({ method, body }) =>\n    method === 'GET' ||\n    method === 'HEAD' ||\n    (method === 'POST' && (!body || Object.keys(body).length === 0)),\n}\n```\n\n资料来源：[apps/sim/lib/webhooks/pending-verification.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/webhooks/pending-verification.ts)\n\n## Data Flow\n\n```mermaid\nsequenceDiagram\n    participant User\n    participant API\n    participant Registry\n    participant Workflow\n    participant Executor\n    participant Sandbox\n\n    User->>API: Trigger Workflow\n    API->>Registry: Validate Block Types\n    Registry-->>API: Block Configs\n    API->>Workflow: Initialize Workflow\n    Workflow->>Registry: Get Block Implementations\n    Registry-->>Workflow: Blocks\n    Workflow->>Executor: Execute Blocks\n    Executor->>Sandbox: Run in Sandbox\n    Sandbox-->>Executor: Results\n    Executor-->>Workflow: Block Outputs\n    Workflow-->>API: Workflow Complete\n    API-->>User: Response\n```\n\n## Block Execution Flow\n\n```mermaid\ngraph TD\n    Start[Workflow Start] --> Trigger{Trigger Type}\n    \n    Trigger -->|Manual| Manual[Manual Trigger]\n    Trigger -->|API| API[API Trigger]\n    Trigger -->|Chat| Chat[Chat Trigger]\n    \n    Manual --> Validate{Validate Block Types}\n    API --> Validate\n    Chat --> Validate\n    \n    Validate -->|Valid| GetBlocks[Get Blocks from Registry]\n    Validate -->|Invalid| Error[Error Handling]\n    \n    GetBlocks --> Execute[Execute Block]\n    Execute --> Sandbox{Run in Sandbox?}\n    \n    Sandbox -->|Yes| Sandboxed[Sandbox Execution]\n    Sandbox -->|No| Direct[Direct Execution]\n    \n    Sandboxed --> Output[Block Output]\n    Direct --> Output\n    \n    Output --> NextBlock{Next Block?}\n    NextBlock -->|Yes| Execute\n    NextBlock -->|No| Complete[Workflow Complete]\n```\n\n## Type Safety\n\nSim leverages TypeScript's type system extensively for compile-time safety:\n\n1. **API Contracts**: Type-safe route definitions with generic type parameters\n2. **Block Registry**: Type-checked block retrieval and validation\n3. **Trigger Classification**: Type-safe trigger type checking\n4. **Webhook Payloads**: Typed webhook event data structures\n\n## Documentation Generation\n\nThe platform includes an automated documentation generator:\n\n```mermaid\ngraph LR\n    A[Block Files] --> B[Scan Directory]\n    B --> C[Extract Metadata]\n    C --> D[Generate Markdown]\n    D --> E[Update meta.json]\n    E --> F[Commit to Repo]\n```\n\nThe generator is integrated into CI/CD and preserves manual content during regeneration.\n\n资料来源：[scripts/README.md](https://github.com/simstudioai/sim/blob/main/scripts/README.md)\n\n---\n\n<a id='executor-engine'></a>\n\n## Workflow Executor Engine\n\n### 相关页面\n\n相关主题：[Architecture Overview](#architecture-overview), [Workflow Blocks System](#workflow-blocks)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [apps/sim/executor/dag/builder.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/executor/dag/builder.ts)\n- [apps/sim/executor/execution/engine.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/executor/execution/engine.ts)\n- [apps/sim/executor/execution/executor.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/executor/execution/executor.ts)\n- [apps/sim/executor/orchestrators/parallel.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/executor/orchestrators/parallel.ts)\n- [apps/sim/executor/orchestrators/loop.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/executor/orchestrators/loop.ts)\n- [packages/testing/src/factories/executor-context.factory.ts](https://github.com/simstudioai/sim/blob/main/packages/testing/src/factories/executor-context.factory.ts)\n- [apps/sim/lib/workflows/triggers/triggers.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/triggers/triggers.ts)\n- [apps/sim/lib/copilot/tools/client/run-tool-execution.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/copilot/tools/client/run-tool-execution.ts)\n</details>\n\n# Workflow Executor Engine\n\nThe Workflow Executor Engine is the core runtime system responsible for executing workflows built in the Sim platform. It transforms serialized workflow definitions into executable execution plans, manages block-level execution with proper dependency resolution, and orchestrates complex control flow patterns including parallel execution and looping constructs.\n\n## Architecture Overview\n\nThe executor engine follows a layered architecture that separates concerns between DAG construction, execution planning, and runtime orchestration.\n\n```mermaid\ngraph TD\n    A[Workflow Definition] --> B[DAG Builder]\n    B --> C[Execution Plan]\n    C --> D[Execution Engine]\n    D --> E[Block Executor]\n    E --> F[Parallel Orchestrator]\n    E --> G[Loop Orchestrator]\n    D --> H[Trigger System]\n    H --> I[Manual Triggers]\n    H --> J[API Triggers]\n    H --> K[Scheduled Triggers]\n```\n\n### Core Components\n\n| Component | File | Responsibility |\n|-----------|------|----------------|\n| DAG Builder | `executor/dag/builder.ts` | Converts workflow blocks into a directed acyclic graph |\n| Execution Engine | `executor/execution/engine.ts` | Coordinates overall execution flow and state management |\n| Block Executor | `executor/execution/executor.ts` | Executes individual blocks and manages block states |\n| Parallel Orchestrator | `executor/orchestrators/parallel.ts` | Manages concurrent block execution |\n| Loop Orchestrator | `executor/orchestrators/loop.ts` | Handles iterative block execution |\n\n## Executor Context\n\nThe executor maintains a comprehensive context object that tracks the state of the entire workflow execution.\n\n```typescript\ninterface ExecutorContext {\n  workflow: SerializedWorkflow\n  blocks: SerializedBlock[]\n  connections: SerializedConnection[]\n  blockStates: Map<string, ExecutorBlockState>\n  executedBlocks: Set<string>\n  abortSignal?: AbortSignal\n  workspaceId: string\n  executionId: string\n}\n```\n\n### Block State Management\n\nEach block maintains its execution state through the `ExecutorBlockState` interface:\n\n```typescript\ninterface ExecutorBlockState {\n  output: Record<string, any>\n  executed: boolean\n  executionTime: number\n}\n```\n\n资料来源：[packages/testing/src/factories/executor-context.factory.ts:1-80]()\n\nThe testing factory provides utilities for creating executor contexts with pre-configured blocks:\n\n```typescript\nexport function createExecutorContextWithBlocks(\n  blockOutputs: Record<string, Record<string, any>>,\n  options?: ExecutorContextFactoryOptions\n): ExecutorContext\n```\n\n资料来源：[packages/testing/src/factories/executor-context.factory.ts:44-70]()\n\n## DAG Builder\n\nThe DAG (Directed Acyclic Graph) builder transforms the linear block definitions into a dependency graph that the execution engine can traverse.\n\n### Responsibilities\n\n- Parse workflow block definitions and connection specifications\n- Build adjacency lists representing block dependencies\n- Validate graph structure to ensure no cycles\n- Resolve input/output mappings between connected blocks\n- Generate execution order using topological sorting\n\n### Key Functions\n\n| Function | Purpose |\n|----------|---------|\n| `buildDAG(blocks, connections)` | Constructs the dependency graph |\n| `topologicalSort()` | Determines safe execution order |\n| `getDependencies(blockId)` | Retrieves all blocks that must execute first |\n| `getDependents(blockId)` | Finds blocks that depend on this block |\n\n## Execution Engine\n\nThe execution engine is the central coordinator that manages the lifecycle of workflow execution from start to completion.\n\n### Execution Flow\n\n```mermaid\nsequenceDiagram\n    participant Client\n    participant Engine\n    participant Executor\n    participant Orchestrator\n    participant Block\n\n    Client->>Engine: execute(workflow, context)\n    Engine->>Executor: prepare(workflow)\n    Executor->>Engine: DAG Ready\n    Engine->>Engine: determineStartBlocks()\n    Engine->>Orchestrator: executeNextBatch()\n    Orchestrator->>Block: execute(block)\n    Block-->>Orchestrator: result\n    Orchestrator->>Engine: blockComplete()\n    Engine->>Engine: updateContext()\n    Engine->>Orchestrator: executeNextBatch()\n    Orchestrator-->>Engine: batchComplete\n    Engine-->>Client: executionResult\n```\n\n### Trigger Classification\n\nThe engine classifies workflow start conditions to determine execution entry points:\n\n```typescript\nclass TriggerClassifier {\n  static isManualTrigger(block: { type: string; subBlocks?: any }): boolean\n  static isApiTrigger(block: { type: string; subBlocks?: any }, isChildWorkflow?: boolean): boolean\n}\n```\n\n资料来源：[apps/sim/lib/workflows/triggers/triggers.ts:1-60]()\n\nSupported trigger types:\n\n| Trigger Type | Description | Entry Mode |\n|--------------|-------------|------------|\n| `INPUT` | Form or manual input trigger | Manual |\n| `MANUAL` | Explicit manual execution | Manual |\n| `START` | New unified start block | Manual/API |\n| `API` | API endpoint trigger | API |\n| `STARTER` | Legacy starter block | Manual/API based on `startWorkflow` value |\n\n资料来源：[apps/sim/lib/workflows/triggers/triggers.ts:1-75]()\n\n## Block Executor\n\nThe block executor handles the actual execution of individual workflow blocks, managing their lifecycle from initialization through completion.\n\n### Execution Pipeline\n\n1. **Block Identification** - Resolve block type and configuration\n2. **Input Resolution** - Collect outputs from dependent blocks\n3. **Sandbox Preparation** - Set up isolated execution environment\n4. **Execution** - Run the block's logic\n5. **Output Capture** - Collect and store block results\n6. **State Update** - Update executor context with results\n\n### Block States\n\n```mermaid\nstateDiagram-v2\n    [*] --> Pending\n    Pending --> Running: executionStart\n    Running --> Completed: success\n    Running --> Failed: error\n    Running --> Cancelled: abortSignal\n    Completed --> [*]\n    Failed --> [*]\n    Cancelled --> [*]\n```\n\n### Async Tool Execution\n\nFor client-executable tools (running in the browser), the executor uses an async confirmation pattern:\n\n```typescript\nasync function reportCompletion(\n  toolCallId: string,\n  status: AsyncConfirmationStatus,\n  message?: string,\n  data?: AsyncCompletionData\n): Promise<void>\n```\n\n资料来源：[apps/sim/lib/copilot/tools/client/run-tool-execution.ts:1-50]()\n\nThe executor reports completion via the `/api/copilot/confirm` endpoint, which persists the durable async-tool row and wakes server-side waiters.\n\n## Parallel Orchestrator\n\nThe parallel orchestrator manages concurrent execution of independent blocks, maximizing throughput while respecting dependency constraints.\n\n### Concurrency Model\n\n```mermaid\ngraph LR\n    A[Block A] --> C[Block C]\n    B[Block B] --> C\n    A --> D[Block D]\n    B --> D\n    C --> E[Block E]\n    D --> E\n```\n\n### Configuration Options\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `maxConcurrency` | number | 10 | Maximum parallel block executions |\n| `timeout` | number | 300000 | Per-block execution timeout (ms) |\n| `failFast` | boolean | true | Stop on first failure |\n\n## Loop Orchestrator\n\nThe loop orchestrator handles iterative execution patterns, supporting standard loops and parallel-for constructs.\n\n### Loop Types\n\n| Loop Type | Description |\n|-----------|-------------|\n| `for` | Standard iteration over items |\n| `while` | Conditional iteration |\n| `parallel-for` | Concurrent iteration with result aggregation |\n\n### Loop Configuration\n\n```typescript\ninterface LoopConfig {\n  loopType: 'for' | 'while' | 'parallel-for'\n  iterations?: number\n  items?: any[]\n  condition?: string\n  maxConcurrency?: number\n}\n```\n\n资料来源：[apps/realtime/src/database/operations.ts:1-50]()\n\n### Loop Block Structure\n\n```typescript\ninterface LoopBlock {\n  id: string\n  type: 'loop'\n  config: LoopConfig\n  nodes: SerializedBlock[]  // Blocks inside the loop\n}\n```\n\nDefault loop configuration:\n\n```typescript\nconst DEFAULT_LOOP_ITERATIONS = 10\n```\n\n资料来源：[apps/realtime/src/database/operations.ts:1-50]()\n\n## Execution Context Factory\n\nThe testing framework provides factory functions for creating executor contexts with predefined states:\n\n### Core Factory Functions\n\n| Function | Purpose |\n|----------|---------|\n| `createExecutorContext()` | Creates a base executor context |\n| `createExecutorContextWithBlocks()` | Creates context with pre-executed blocks |\n| `addBlockState()` | Adds block state to existing context (chainable) |\n| `createMinimalWorkflow()` | Creates a minimal workflow for testing |\n\n### Usage Example\n\n```typescript\nconst ctx = createExecutorContextWithBlocks({\n  'source-block': { value: 10, text: 'hello' },\n  'other-block': { result: true }\n})\n```\n\n资料来源：[packages/testing/src/factories/executor-context.factory.ts:44-70]()\n\n## Error Handling & Resilience\n\n### Cancellation Guards\n\nThe executor implements SQL-level guards to prevent race conditions during state updates:\n\n```typescript\nconst cancellationGuard = bypassStaleWorker ? undefined : { groupId, executionId }\n```\n\n资料来源：[apps/sim/lib/table/cell-write.ts:1-40]()\n\n### Abort Signal Support\n\nAll executor operations respect `AbortSignal` for graceful cancellation:\n\n```typescript\ninterface ExecutorContext {\n  abortSignal?: AbortSignal\n}\n```\n\n### Skip Conditions\n\nThe executor skips writes under specific conditions to maintain consistency:\n\n| Condition | Action |\n|-----------|--------|\n| Same execution already running | Skip queued stamp |\n| Cancelled state with newer execution | Skip group write |\n| SQL guard conflict | Skip with logging |\n\n## Configuration Constants\n\n| Constant | Value | Description |\n|----------|-------|-------------|\n| `BLOCK_DIMENSIONS.MIN_HEIGHT` | 100 | Minimum block visual height |\n| `DEFAULT_LOOP_ITERATIONS` | 10 | Default loop iteration count |\n| `DEFAULT_TIMEOUT` | 300000 | Default block execution timeout |\n\n资料来源：[apps/sim/executor/constants](from mocks)\n\n## Extension Points\n\n### Custom Orchestrators\n\nThe orchestrator system is designed for extensibility. New orchestrators can be registered by implementing the `Orchestrator` interface:\n\n```typescript\ninterface Orchestrator {\n  execute(blocks: SerializedBlock[], context: ExecutorContext): Promise<void>\n  cancel(): void\n}\n```\n\n### Block Output Handlers\n\nBlock output handling can be customized through the `getEffectiveBlockOutputs` extension point.\n\n## Related Documentation\n\n- [Workflow Triggers](triggers.md) - Trigger system integration\n- [DAG Builder](dag-builder.md) - Graph construction details\n- [Execution API](../api/execution.md) - Runtime API reference\n- [Testing Utilities](../testing/executor.md) - Test factory documentation\n\n---\n\n<a id='workflow-blocks'></a>\n\n## Workflow Blocks System\n\n### 相关页面\n\n相关主题：[Integrations and Connectors](#integrations-connectors), [Workflow Executor Engine](#executor-engine)\n\n<details>\n<summary>Related Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [apps/sim/lib/workflows/triggers/triggers.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/triggers/triggers.ts)\n- [apps/sim/lib/workflows/triggers/trigger-utils.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/triggers/trigger-utils.ts)\n- [apps/sim/lib/workflows/subblocks/visibility.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/subblocks/visibility.ts)\n- [apps/sim/lib/workflows/blocks/block-reference-tags.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/blocks/block-reference-tags.ts)\n- [apps/sim/lib/execution/files.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/execution/files.ts)\n- [apps/sim/lib/copilot/tools/server/workflow/edit-workflow/builders.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/copilot/tools/server/workflow/edit-workflow/builders.ts)\n- [packages/workflow-persistence/src/load.ts](https://github.com/simstudioai/sim/blob/main/packages/workflow-persistence/src/load.ts)\n- [packages/testing/src/assertions/workflow.assertions.ts](https://github.com/simstudioai/sim/blob/main/packages/testing/src/assertions/workflow.assertions.ts)\n- [apps/realtime/src/database/operations.ts](https://github.com/simstudioai/sim/blob/main/apps/realtime/src/database/operations.ts)\n</details>\n\n# Workflow Blocks System\n\n## Overview\n\nThe Workflow Blocks System is the foundational architecture for building and executing automation workflows in the Sim platform. Blocks are the atomic units of execution that represent discrete operations, triggers, or control flow structures within a workflow. Each block encapsulates its own configuration, state, inputs, and outputs, allowing complex business logic to be constructed through visual composition or programmatically.\n\nThe system provides a declarative model where workflows are composed of interconnected blocks, with edges defining the data flow and execution order between them. This architecture enables both visual workflow design in the Sim editor and programmatic workflow manipulation through APIs.\n\n资料来源：[apps/sim/lib/copilot/tools/server/workflow/edit-workflow/builders.ts:1-50]()\n\n## Block Architecture\n\n### Core Components\n\nA block in the system consists of several key components:\n\n| Component | Description |\n|-----------|-------------|\n| `id` | Unique identifier for the block within a workflow |\n| `type` | The block type identifier (e.g., 'agent', 'trigger', 'loop') |\n| `name` | Display name shown in the UI |\n| `position` | Coordinates for visual placement (x, y) |\n| `enabled` | Boolean flag controlling whether the block executes |\n| `subBlocks` | Nested configuration objects with mode-based visibility |\n| `outputs` | Execution results produced by the block |\n| `data` | Arbitrary data associated with the block |\n| `metadata` | Additional metadata including block type references |\n\n资料来源：[packages/workflow-persistence/src/load.ts:20-45]()\n\n### Block State Model\n\nThe block state represents the complete runtime and configuration state of a block:\n\n```typescript\ninterface BlockState {\n  id: string\n  type: string\n  name: string\n  position: { x: number; y: number }\n  enabled: boolean\n  horizontalHandles: boolean\n  advancedMode: boolean\n  triggerMode: boolean\n  height: number\n  subBlocks: Record<string, SubBlockState>\n  outputs: Record<string, any>\n  data: Record<string, any>\n  locked: boolean\n}\n```\n\n资料来源：[packages/workflow-persistence/src/load.ts:18-35]()\n\n## Block Types\n\n### Trigger Blocks\n\nTrigger blocks initiate workflow execution and define how workflows can be started. The system supports multiple trigger types:\n\n| Trigger Type | Constant | Description |\n|--------------|----------|-------------|\n| Start | `TRIGGER_TYPES.START` | Primary entry point for workflows |\n| API | `TRIGGER_TYPES.API` | HTTP API triggered execution |\n| Chat | `TRIGGER_TYPES.CHAT` | Conversational trigger |\n| Manual | `TRIGGER_TYPES.MANUAL` | Manual invocation |\n| Input | `TRIGGER_TYPES.INPUT` | Input parameter trigger |\n| Webhook | `TRIGGER_TYPES.WEBHOOK` | Webhook-based triggers |\n| Schedule | `TRIGGER_TYPES.SCHEDULE` | Time-based triggers |\n| Generic Webhook | `TRIGGER_TYPES.GENERIC_WEBHOOK` | Universal webhook receiver |\n\n资料来源：[apps/sim/lib/workflows/triggers/triggers.ts:1-30]()\n\n### Control Flow Blocks\n\nControl flow blocks manage execution logic and flow:\n\n| Block Type | Purpose |\n|------------|---------|\n| `loop` | Iteration control (for loops) |\n| `parallel` | Parallel execution branches |\n\nThe loop block stores its configuration in a separate `workflowSubflows` table with structure:\n\n```typescript\n{\n  id: string\n  workflowId: string\n  type: 'loop'\n  config: {\n    loopType: 'for'\n    iterations: number\n    nodes: string[]\n  }\n}\n```\n\n资料来源：[apps/realtime/src/database/operations.ts:1-40]()\n\n### SubBlock Modes\n\nSubBlocks support different visibility modes that control their appearance in the UI:\n\n| Mode | Behavior |\n|------|----------|\n| `basic` | Shown in basic mode, hidden in advanced mode |\n| `advanced` | Shown in advanced mode, hidden in basic mode |\n| `trigger` | Visible only when trigger mode is enabled |\n| `trigger-advanced` | Visible in trigger mode with advanced options |\n\nThe visibility logic is implemented in the `shouldUseSubBlockForTriggerModeCanonicalIndex` function:\n\n```typescript\nexport function isTriggerModeSubBlock(subBlock: Pick<SubBlockConfig, 'mode'>): boolean {\n  return subBlock.mode === 'trigger' || subBlock.mode === 'trigger-advanced'\n}\n\nexport function isTriggerConfigSubBlock(subBlock: Pick<SubBlockConfig, 'type'>): boolean {\n  return String(subBlock.type) === 'trigger-config'\n}\n```\n\n资料来源：[apps/sim/lib/workflows/subblocks/visibility.ts:1-35]()\n\n## Trigger System\n\n### Trigger Classification\n\nThe trigger system classifies blocks based on their execution context:\n\n```mermaid\ngraph TD\n    A[Block Type] --> B{is Trigger Block?}\n    B -->|Yes| C[Explicit Trigger]\n    B -->|No| D{has triggerMode?}\n    D -->|Yes| E[Tool with Trigger]\n    D -->|No| F[Regular Block]\n```\n\nThe `TriggerUtils` class provides static methods for trigger identification:\n\n```typescript\nexport class TriggerUtils {\n  static isTriggerBlock(block: { type: string; triggerMode?: boolean }): boolean {\n    const blockConfig = getBlock(block.type)\n    return (\n      blockConfig?.category === 'triggers' ||\n      block.triggerMode === true ||\n      block.type === TRIGGER_TYPES.STARTER\n    )\n  }\n\n  static isTriggerType(block: { type: string }, triggerType: TriggerType): boolean {\n    return block.type === triggerType\n  }\n}\n```\n\n资料来源：[apps/sim/lib/workflows/triggers/triggers.ts:80-100]()\n\n### Start Block Resolution\n\nThe system uses a priority-based approach to resolve start candidates for workflow execution:\n\n```mermaid\ngraph TD\n    A[Blocks Collection] --> B[Filter Disabled Blocks]\n    B --> C[Classify Start Block Path]\n    C --> D{Is Child Workflow?}\n    D -->|Yes| E[Apply CHILD_PRIORITIES]\n    D -->|No| F[Apply EXECUTION_PRIORITIES]\n    E --> G[Return Sorted Candidates]\n    F --> G\n```\n\nThe `resolveStartCandidates` function implements this logic:\n\n```typescript\nexport function resolveStartCandidates<T extends MinimalBlock>(\n  blocks: Record<string, T> | T[],\n  options: ResolveStartOptions\n): StartBlockCandidate<T>[] {\n  const entries = toEntries(blocks)\n  if (entries.length === 0) return []\n\n  const priorities = options.isChildWorkflow\n    ? CHILD_PRIORITIES\n    : EXECUTION_PRIORITIES[options.execution]\n  \n  // ... filtering and candidate creation logic\n}\n```\n\n资料来源：[apps/sim/lib/workflows/triggers/triggers.ts:150-180]()\n\n### Trigger Reference Aliases\n\nThe system maps reference aliases to concrete trigger types:\n\n```typescript\nexport const TRIGGER_REFERENCE_ALIAS_MAP = {\n  start: TRIGGER_TYPES.START,\n  api: TRIGGER_TYPES.API,\n  chat: TRIGGER_TYPES.CHAT,\n  manual: TRIGGER_TYPES.START,\n} as const\n```\n\nThese aliases are used in inline references like `<api.*>`, `<chat.*>`, enabling flexible trigger referencing within workflows.\n\n资料来源：[apps/sim/lib/workflows/triggers/triggers.ts:60-68]()\n\n## Block Configuration\n\n### SubBlock Structure\n\nSubBlocks allow nested configuration within blocks:\n\n```typescript\nexport function applyTriggerConfigToBlockSubblocks(\n  block: any, \n  triggerConfig: Record<string, any>\n) {\n  if (!block?.subBlocks || !triggerConfig) return\n\n  Object.entries(triggerConfig).forEach(([configKey, configValue]) => {\n    const existingSubblock = block.subBlocks[configKey]\n    if (existingSubblock) {\n      // Compare values to avoid unnecessary updates\n      const valuesEqual = /* comparison logic */\n      \n      if (!valuesEqual) {\n        block.subBlocks[configKey] = {\n          ...existingSubblock,\n          value: configValue,\n        }\n      }\n    } else {\n      // Create new subblock\n      block.subBlocks[configKey] = { /* new subblock */ }\n    }\n  })\n}\n```\n\n资料来源：[apps/sim/lib/copilot/tools/server/workflow/edit-workflow/builders.ts:60-95]()\n\n### Trigger Mode Visibility\n\nThe system determines which blocks appear in different toolbar sections:\n\n```mermaid\ngraph TD\n    A[All Blocks] --> B{Is Hidden?}\n    B -->|Yes| C[Exclude]\n    B -->|No| D{Category === 'triggers'?}\n    D -->|Yes| E[Include in Triggers Tab]\n    D -->|No| F{Has Trigger Capability?}\n    F -->|Yes| G[Include in Both Tabs]\n    F -->|No| H[Include in Blocks Tab]\n```\n\nFunctions `getTriggersForSidebar()` and `getBlocksForSidebar()` implement this filtering logic, excluding blocks with `hideFromToolbar: true` and treating blocks with trigger capability differently from those with explicit trigger category.\n\n资料来源：[apps/sim/lib/workflows/triggers/trigger-utils.ts:1-40]()\n\n## Block Reference Tags\n\nBlock tags control how blocks are referenced in the system:\n\n```typescript\nexport function getBlockTags(block: BlockConfig): string[] {\n  const normalizedBlockName = /* normalization logic */\n  let blockTags = allTags\n\n  const shouldShowRootTag =\n    block.type === TRIGGER_TYPES.GENERIC_WEBHOOK || \n    block.type === 'start_trigger'\n  \n  if (!shouldShowRootTag) {\n    blockTags = blockTags.filter((tag) => tag !== normalizedBlockName)\n  }\n\n  return blockTags\n}\n```\n\n资料来源：[apps/sim/lib/workflows/blocks/block-reference-tags.ts:1-30]()\n\n## File Input Processing\n\nBlocks can handle file inputs through a specialized processing system:\n\n```typescript\nexport async function processInputFileFields(\n  input: unknown,\n  blocks: SerializedBlock[],\n  executionContext: { workspaceId: string; workflowId: string; executionId: string },\n  requestId: string,\n  userId?: string\n): Promise<unknown> {\n  // Find start block to extract input format\n  const startBlock = blocks.find((block) => {\n    const blockType = block.metadata?.id\n    return (\n      blockType === TRIGGER_TYPES.START ||\n      blockType === TRIGGER_TYPES.API ||\n      blockType === TRIGGER_TYPES.INPUT ||\n      blockType === TRIGGER_TYPES.GENERIC_WEBHOOK ||\n      blockType === TRIGGER_TYPES.STARTER\n    )\n  })\n\n  // Process file fields from input format\n  const fileFields = inputFormat.filter((field) => field.type === 'file[]')\n  // ... file processing logic\n}\n```\n\n资料来源：[apps/sim/lib/execution/files.ts:1-60]()\n\n## Persistence Layer\n\n### Database Schema\n\nBlock data is persisted using a hybrid approach:\n\n| Table | Purpose |\n|-------|---------|\n| `workflowBlocks` | Core block configuration and state |\n| `workflowSubflows` | Loop and parallel block specific configs |\n| `workflowEdges` | Connections between blocks |\n\nThe upsert operation for blocks:\n\n```typescript\nawait tx\n  .insert(workflowBlocks)\n  .values(blockValues)\n  .onConflictDoUpdate({\n    target: workflowBlocks.id,\n    set: {\n      type: sql`excluded.type`,\n      name: sql`excluded.name`,\n      positionX: sql`excluded.position_x`,\n      positionY: sql`excluded.position_y`,\n      enabled: sql`excluded.enabled`,\n      subBlocks: sql`excluded.sub_blocks`,\n      outputs: sql`excluded.outputs`,\n      data: sql`excluded.data`,\n      updatedAt: sql`now()`,\n    },\n  })\n```\n\n资料来源：[apps/realtime/src/database/operations.ts:1-50]()\n\n### Loading and Assembly\n\nWhen loading a workflow, blocks are assembled from database records:\n\n```typescript\nblocks.forEach((block) => {\n  const blockData = (block.data ?? {}) as BlockState['data']\n\n  const assembled: BlockState = {\n    id: block.id,\n    type: block.type,\n    name: block.name,\n    position: {\n      x: Number(block.positionX),\n      y: Number(block.positionY),\n    },\n    enabled: block.enabled,\n    subBlocks: (block.subBlocks as BlockState['subBlocks']) || {},\n    outputs: (block.outputs as BlockState['outputs']) || {},\n    data: blockData,\n    locked: block.locked,\n  }\n\n  blocksMap[block.id] = assembled\n})\n```\n\nSubflows (loops and parallels) are loaded separately:\n\n```typescript\nsubflows.forEach((subflow) => {\n  const config = (subflow.config ?? {}) as Partial<Loop & Parallel>\n\n  if (subflow.type === SUBFLOW_TYPES.LOOP) {\n    loops[subflow.id] = config as Loop\n  } else if (subflow.type === SUBFLOW_TYPES.PARALLEL) {\n    parallels[subflow.id] = config as Parallel\n  }\n})\n```\n\n资料来源：[packages/workflow-persistence/src/load.ts:40-80]()\n\n## Testing Infrastructure\n\n### Block Assertions\n\nThe testing package provides assertion utilities for workflow validation:\n\n```typescript\nexport function expectBlockEnabled(\n  blocks: Record<string, any>, \n  blockId: string\n): void {\n  const block = blocks[blockId]\n  expect(block, `Block \"${blockId}\" should exist`).toBeDefined()\n  expect(block.enabled, `Block \"${blockId}\" should be enabled`).toBe(true)\n}\n\nexport function expectBlockPosition(\n  blocks: Record<string, any>,\n  blockId: string,\n  expectedPosition: { x: number; y: number }\n): void {\n  const block = blocks[blockId]\n  expect(block, `Block \"${blockId}\" should exist`).toBeDefined()\n  expect(block.position.x, `Block \"${blockId}\" x position`)\n    .toBeCloseTo(expectedPosition.x, 0)\n  expect(block.position.y, `Block \"${blockId}\" y position`)\n    .toBeCloseTo(expectedPosition.y, 0)\n}\n```\n\n资料来源：[packages/testing/src/assertions/workflow.assertions.ts:1-60]()\n\n### Workflow Factories\n\nTest utilities create standard workflow structures:\n\n```typescript\nexport function createLinearWorkflow(\n  blockCount: number, \n  spacing = 200\n): any {\n  const blocks: Record<string, any> = {}\n  const blockIds: string[] = []\n\n  for (let i = 0; i < blockCount; i++) {\n    const id = `block-${i}`\n    blockIds.push(id)\n\n    if (i === 0) {\n      blocks[id] = createStarterBlock({ id, position: { x: i * spacing, y: 0 } })\n    } else {\n      blocks[id] = createFunctionBlock({ id, name: `Step ${i}`, position: { x: i * spacing, y: 0 } })\n    }\n  }\n\n  return createWorkflowState({ blocks, edges: createLinearEdges(blockIds) })\n}\n```\n\n资料来源：[packages/testing/src/factories/workflow.factory.ts:1-40]()\n\n## Summary\n\nThe Workflow Blocks System provides a comprehensive foundation for building automation workflows through:\n\n1. **Declarative Block Model**: Each block encapsulates its own configuration, state, and outputs\n2. **Flexible Trigger System**: Multiple trigger types support various execution entry points\n3. **Mode-Based Visibility**: SubBlocks can be shown/hidden based on basic, advanced, or trigger modes\n4. **Persistent State**: Blocks are persisted to the database with proper upsert semantics\n5. **Type-Safe Testing**: Comprehensive assertion utilities enable robust workflow testing\n\nThe architecture separates concerns between block definition, execution, persistence, and testing, enabling a clean and maintainable codebase for workflow automation.\n\n---\n\n<a id='integrations-connectors'></a>\n\n## Integrations and Connectors\n\n### 相关页面\n\n相关主题：[Workflow Blocks System](#workflow-blocks), [Background Jobs and Background Processing](#background-jobs)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [apps/sim/connectors/registry.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/connectors/registry.ts)\n- [apps/sim/connectors/slack/slack.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/connectors/slack/slack.ts)\n- [apps/sim/connectors/github/github.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/connectors/github/github.ts)\n- [apps/sim/connectors/types.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/connectors/types.ts)\n- [apps/sim/lib/api/contracts/tools/communication/slack.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/api/contracts/tools/communication/slack.ts)\n- [apps/sim/lib/webhooks/providers/gong.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/webhooks/providers/gong.ts)\n- [apps/sim/lib/webhooks/providers/vercel.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/webhooks/providers/vercel.ts)\n- [apps/sim/lib/copilot/vfs/workspace-vfs.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/copilot/vfs/workspace-vfs.ts)\n- [apps/sim/lib/workflows/triggers/triggers.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/triggers/triggers.ts)\n- [apps/sim/lib/api/contracts/types.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/api/contracts/types.ts)\n</details>\n\n# Integrations and Connectors\n\n## Overview\n\nSim provides a comprehensive integrations and connectors system that enables AI agents to interact with external services, APIs, and platforms. This system forms the backbone of Sim's workflow automation capabilities, allowing users to connect 1,000+ integrations and LLMs to orchestrate agentic workflows.\n\nThe connector architecture is designed around a plugin-based system where each integration is implemented as a self-contained module with standardized interfaces for authentication, API communication, and data transformation.\n\n## Architecture\n\nThe Sim integration system consists of several interconnected layers:\n\n```mermaid\ngraph TD\n    A[Workflows / Agents] --> B[Trigger System]\n    B --> C[Connectors Registry]\n    C --> D[Individual Connectors]\n    D --> E[Slack Connector]\n    D --> F[GitHub Connector]\n    D --> G[Custom Connectors]\n    A --> H[Webhook Providers]\n    H --> I[Gong Webhook]\n    H --> J[Vercel Webhook]\n    C --> K[API Contracts]\n    K --> L[Type Definitions]\n    D --> M[External APIs]\n```\n\n### Core Components\n\n| Component | Purpose | Location |\n|-----------|---------|----------|\n| Connectors Registry | Central hub for managing all connector instances | `apps/sim/connectors/registry.ts` |\n| Type Definitions | Shared interfaces and types for connectors | `apps/sim/connectors/types.ts` |\n| API Contracts | Zod schemas defining API request/response shapes | `apps/sim/lib/api/contracts/types.ts` |\n| Trigger System | Event-driven connector activation | `apps/sim/lib/workflows/triggers/triggers.ts` |\n| Webhook Providers | Inbound integration handlers | `apps/sim/lib/webhooks/providers/` |\n\n## Connector Registry\n\nThe connector registry (`apps/sim/connectors/registry.ts`) serves as the central management system for all connectors in the platform. It provides:\n\n- Registration and lookup of connector instances\n- Configuration management for each connector\n- Lifecycle management (initialize, authenticate, execute, cleanup)\n- Unified interface for accessing connector functionality\n\n```mermaid\ngraph LR\n    A[Request] --> B[Registry Lookup]\n    B --> C{Connector Found?}\n    C -->|Yes| D[Execute Connector]\n    C -->|No| E[Return Error]\n    D --> F[Transform Response]\n    F --> G[Return to Caller]\n```\n\n## Trigger System\n\nTriggers work in conjunction with connectors to activate workflows based on external events. The trigger system classifies different activation modes:\n\n```mermaid\ngraph TD\n    A[Block] --> B{Start Workflow Mode}\n    B -->|chat| C[Chat Trigger]\n    B -->|api| D[API Trigger]\n    B -->|run| E[API Trigger]\n    B -->|manual| F[Manual Trigger]\n    B -->|undefined| F\n```\n\n### Trigger Types\n\n| Trigger Type | Classification | Use Case |\n|--------------|----------------|----------|\n| `start` | Manual/API | Initial workflow activation |\n| `api` | API-based | Programmatic workflow execution |\n| `chat` | Conversational | Chat-initiated workflows |\n| `manual` | User-initiated | Manual workflow triggers |\n\nThe trigger reference alias map provides convenient access to trigger types:\n\n```typescript\nexport const TRIGGER_REFERENCE_ALIAS_MAP = {\n  start: TRIGGER_TYPES.START,\n  api: TRIGGER_TYPES.API,\n  chat: TRIGGER_TYPES.CHAT,\n  manual: TRIGGER_TYPES.START,\n} as const\n```\n资料来源：[apps/sim/lib/workflows/triggers/triggers.ts:32-37]()\n\n## Webhook Providers\n\nSim integrates with external services through webhook providers that normalize incoming events into a standardized format.\n\n### Gong Webhook Integration\n\nThe Gong webhook provider handles call recording and analytics data:\n\n```typescript\ninterface GongWebhookPayload {\n  callId: string\n  metaData: Record<string, unknown>\n  parties: unknown[]\n  context: unknown[]\n  trackers: unknown[]\n  topics: unknown[]\n  highlights: unknown[]\n  eventType: 'gong.automation_rule'\n}\n```\n资料来源：[apps/sim/lib/webhooks/providers/gong.ts:1-15]()\n\n### Vercel Webhook Integration\n\nThe Vercel webhook provider processes deployment events with comprehensive metadata extraction:\n\n```typescript\ninterface VercelDeploymentData {\n  id: string\n  url: string\n  name: string\n  meta: Record<string, unknown>\n  project?: {\n    id: string\n    name: string\n  }\n  team?: {\n    id: string\n  }\n  user?: {\n    id: string\n  }\n  target?: string\n  plan?: string\n}\n```\n资料来源：[apps/sim/lib/webhooks/providers/vercel.ts:25-40]()\n\n## Slack Integration\n\nSlack is a first-class citizen in Sim's connector ecosystem, with comprehensive API contract definitions:\n\n### Slack API Contracts\n\n| Contract | Purpose | Response Type |\n|----------|---------|---------------|\n| `slackReadMessagesContract` | Fetch messages from channels | `SlackReadMessagesResponse` |\n| `slackAddReactionContract` | Add reactions to messages | `SlackReactionResponse` |\n| `slackDeleteMessageContract` | Delete messages | `SlackDeleteMessageResponse` |\n| `slackUpdateMessageContract` | Edit existing messages | `SlackUpdateMessageResponse` |\n| `slackSendEphemeralContract` | Send ephemeral messages | `SlackSendEphemeralResponse` |\n| `slackDownloadContract` | Download files/content | `SlackDownloadResponse` |\n\n```typescript\nexport type SlackReadMessagesResponse = ContractJsonResponse<typeof slackReadMessagesContract>\nexport type SlackReactionResponse = ContractJsonResponse<typeof slackAddReactionContract>\nexport type SlackDeleteMessageResponse = ContractJsonResponse<typeof slackDeleteMessageContract>\nexport type SlackUpdateMessageResponse = ContractJsonResponse<typeof slackUpdateMessageContract>\nexport type SlackSendEphemeralResponse = ContractJsonResponse<typeof slackSendEphemeralContract>\nexport type SlackDownloadResponse = ContractJsonResponse<typeof slackDownloadContract>\n```\n资料来源：[apps/sim/lib/api/contracts/tools/communication/slack.ts:1-10]()\n\n## API Contract System\n\nThe API contract system uses Zod schemas for runtime validation of all API interactions:\n\n### Contract Type Utilities\n\n```typescript\nexport type ContractParams<C extends AnyApiRouteContract> = C extends ApiRouteContract<\n  infer TParams,\n  ApiSchema | undefined,\n  ApiSchema | undefined,\n  ApiSchema | undefined,\n  ResponseMode,\n  ApiSchema | undefined\n>\n  ? EmptySchemaOutput<TParams>\n  : undefined\n\nexport type ContractBody<C extends AnyApiRouteContract> = C extends ApiRouteContract<\n  ApiSchema | undefined,\n  ApiSchema | undefined,\n  infer TBody,\n  ApiSchema | undefined,\n  ResponseMode,\n  ApiSchema | undefined\n>\n  ? EmptySchemaOutput<TBody>\n  : undefined\n```\n资料来源：[apps/sim/lib/api/contracts/types.ts:1-30]()\n\n### Generic Contract Types\n\n| Type | Description |\n|------|-------------|\n| `ContractParams<C>` | Extracted URL parameter types from contract |\n| `ContractQuery<C>` | Extracted query string types from contract |\n| `ContractBody<C>` | Extracted request body types from contract |\n| `ContractHeaders<C>` | Extracted header types from contract |\n| `ContractParamsInput<C>` | Input types for contract parameters |\n\n## Virtual Filesystem Integration\n\nConnectors are exposed to AI agents through the virtual filesystem (VFS), which materializes workspace data into an in-memory file system structure:\n\n```mermaid\ngraph TD\n    A[Workspace] --> B[Virtual Filesystem]\n    B --> C[workflows/{name}/meta.json]\n    B --> D[workflows/{name}/state.json]\n    B --> E[workflows/{name}/executions.json]\n    B --> F[knowledgebases/{name}/meta.json]\n    B --> G[connectors.json]\n    B --> H[triggers/{id}.json]\n```\n\nThe VFS exposes connector configurations to agents:\n\n```typescript\nfiles.set(\n  'knowledgebases/{name}/connectors.json',\n  serializeConnectorConfigs(connectorConfigs)\n)\n```\n资料来源：[apps/sim/lib/copilot/vfs/workspace-vfs.ts:1-50]()\n\n## Connector Configuration\n\nConnectors follow a standardized configuration schema defined in `apps/sim/connectors/types.ts`. Each connector instance includes:\n\n- **Provider**: The external service name (e.g., `slack`, `github`)\n- **Credentials**: Authentication tokens and secrets\n- **Settings**: Connector-specific configuration options\n- **Metadata**: Display name, description, category\n\n## Adding New Connectors\n\nTo add a new connector to the Sim platform:\n\n1. Create a new directory under `apps/sim/connectors/{provider}/`\n2. Implement the connector class with required interface methods\n3. Register the connector in the registry\n4. Define API contracts in `apps/sim/lib/api/contracts/`\n5. Add webhook handler if inbound events are needed\n6. Update the VFS serialization logic if agent access is required\n\n## Best Practices\n\n- Always use API contracts for type-safe API calls\n- Implement proper error handling and retry logic\n- Store credentials securely (never commit to repository)\n- Follow the trigger classification pattern for event-driven workflows\n- Use the virtual filesystem for any data that should be accessible to agents\n\n---\n\n<a id='agent-system'></a>\n\n## Agent System\n\n### 相关页面\n\n相关主题：[Copilot System](#copilot-system), [Workflow Blocks System](#workflow-blocks)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [apps/sim/executor/handlers/agent/agent-handler.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/executor/handlers/agent/agent-handler.ts)\n- [apps/sim/executor/handlers/agent/memory.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/executor/handlers/agent/memory.ts)\n- [apps/sim/executor/handlers/agent/skills-resolver.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/executor/handlers/agent/skills-resolver.ts)\n- [apps/sim/executor/handlers/agent/types.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/executor/handlers/agent/types.ts)\n- [apps/sim/blocks/blocks/agent.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/blocks/blocks/agent.ts)\n</details>\n\n# Agent System\n\nThe Agent System is a core component of the Sim platform that enables the execution of AI agents within workflow automation. It provides the infrastructure for creating, managing, and executing agents that can interact with tools, maintain conversation context, and process complex multi-step tasks.\n\n## Overview\n\nThe Agent System serves as the execution layer for AI-driven automation within Sim workflows. It handles the lifecycle of agent execution, including initialization, tool invocation, state management, memory handling, and result processing.\n\n### Core Responsibilities\n\n- **Agent Execution Pipeline**: Orchestrates the execution of agent logic within workflow contexts\n- **Memory Management**: Maintains conversation history and context across agent interactions\n- **Skills Resolution**: Resolves and binds available skills and tools to agent instances\n- **State Coordination**: Manages agent state transitions and execution checkpoints\n- **Tool Integration**: Handles the invocation and management of external tools and APIs\n\n## Architecture\n\n```mermaid\ngraph TD\n    A[Workflow Engine] --> B[Agent Handler]\n    B --> C[Memory Manager]\n    B --> D[Skills Resolver]\n    B --> E[Tool Executor]\n    C --> F[Context Store]\n    D --> G[Block Registry]\n    E --> H[Execution Context]\n    H --> I[Streaming Response]\n    F --> H\n```\n\n## Agent Handler\n\nThe `agent-handler.ts` serves as the primary orchestrator for agent execution. It manages the interaction between the workflow engine and the agent's internal components.\n\n### Key Functions\n\n| Function | Purpose | Source |\n|----------|---------|--------|\n| `handleAgentExecution` | Main entry point for agent processing | [agent-handler.ts]() |\n| `executeToolAndReport` | Invokes tools and streams results back | [tool.ts:52]() |\n| `registerPendingToolPromise` | Tracks async tool executions | [tool.ts:45]() |\n| `abortPendingToolIfStreamDead` | Handles stalled tool executions | [tool.ts:66]() |\n\n### Execution Flow\n\n```mermaid\nsequenceDiagram\n    participant Workflow\n    participant AgentHandler\n    participant ToolExecutor\n    participant Memory\n    participant SkillsResolver\n\n    Workflow->>AgentHandler: Execute Agent\n    AgentHandler->>SkillsResolver: Resolve Available Skills\n    SkillsResolver-->>AgentHandler: Skill Bindings\n    AgentHandler->>Memory: Initialize Context\n    Memory-->>AgentHandler: Context State\n    AgentHandler->>ToolExecutor: Invoke Tool\n    ToolExecutor-->>AgentHandler: Tool Result\n    AgentHandler->>Memory: Update State\n    AgentHandler-->>Workflow: Execution Result\n```\n\n### Tool Execution Modes\n\nThe agent handler supports multiple execution modes for tool invocation:\n\n| Mode | Description | Configuration |\n|------|-------------|---------------|\n| `autoExecuteTools` | Automatically execute tools without user confirmation | `options.autoExecuteTools !== false` |\n| `interactive` | Require user confirmation before tool execution | `options.interactive === true` |\n| `parallel` | Execute multiple tools concurrently | Parallel promise registration |\n| `clientExecutable` | Delegate execution to client workflow | `clientExecutable === true` |\n\n## Memory System\n\nThe Memory System (`memory.ts`) maintains conversation context and execution history for agents, enabling stateful interactions across multiple workflow steps.\n\n### Memory Operations\n\n```typescript\ninterface AgentMemory {\n  conversationHistory: ConversationTurn[]\n  executionContext: Record<string, any>\n  blockOutputs: Map<string, BlockOutput>\n  timestamps: MemoryTimestamps\n}\n```\n\n### Context Management\n\n| Operation | Description | Source Reference |\n|-----------|-------------|------------------|\n| Store Turn | Save a conversation interaction | [memory.ts]() |\n| Retrieve Context | Load previous state for agent | [memory.ts]() |\n| Clear Memory | Reset context for new session | [memory.ts]() |\n| Merge Context | Combine multiple context sources | [memory.ts]() |\n\n## Skills Resolver\n\nThe Skills Resolver (`skills-resolver.ts`) binds available tools and capabilities to agent instances based on workflow configuration and agent requirements.\n\n### Resolution Process\n\n1. **Skill Discovery**: Scan available tool registry for compatible skills\n2. **Capability Matching**: Match agent requirements with available tools\n3. **Binding**: Create stable references between agent and tools\n4. **Validation**: Verify all required skills are available\n\n### Skill Configuration\n\n```typescript\ninterface SkillBinding {\n  skillId: string\n  toolName: string\n  parameters: SkillParameters\n  enabled: boolean\n  priority: number\n}\n```\n\n## Type System\n\nThe Agent System defines comprehensive TypeScript types in `types.ts` to ensure type safety across all components.\n\n### Core Types\n\n| Type | Description | Usage |\n|------|-------------|-------|\n| `StreamingContext` | Manages streaming response state | Tool execution tracking |\n| `ExecutionContext` | Holds runtime execution data | Block state, outputs |\n| `OrchestratorOptions` | Configuration for agent behavior | Execution parameters |\n| `ToolScope` | Defines execution scope | `main` or `subagent` |\n| `ToolCallState` | Tracks individual tool call status | Execution monitoring |\n\n### Tool Call States\n\n```mermaid\nstateDiagram-v2\n    [*] --> pending: Tool Call Created\n    pending --> executing: Execution Started\n    executing --> success: Completed Successfully\n    executing --> error: Execution Failed\n    executing --> cancelled: User Cancelled\n    success --> skipped: Result Not Needed\n    error --> retry: Retry Attempt\n```\n\n## Agent Block Definition\n\nThe Agent Block (`agent.ts`) defines the block-level configuration and metadata for agents within the Sim workflow system.\n\n### Block Structure\n\n```typescript\ninterface AgentBlockConfig {\n  name: string\n  description: string\n  category: BlockCategory\n  inputs: InputSpecification[]\n  outputs: OutputSpecification[]\n  parameters: AgentParameters\n}\n```\n\n### Block Categories\n\n| Category | Description | Example Usage |\n|----------|-------------|---------------|\n| `agent` | Primary agent implementation | Main workflow agent |\n| `subagent` | Nested agent for delegation | Specialized task agents |\n| `client` | Client-delegated execution | External system integration |\n\n## Execution Context Factory\n\nThe `executor-context.factory.ts` provides utilities for creating and manipulating executor contexts used throughout the agent system.\n\n### Factory Functions\n\n| Function | Purpose | Source |\n|----------|---------|--------|\n| `createExecutorContext` | Initialize new execution context | [executor-context.factory.ts]() |\n| `createExecutorContextWithBlocks` | Create context with pre-executed blocks | [executor-context.factory.ts]() |\n| `addBlockState` | Add block state to existing context | [executor-context.factory.ts]() |\n| `createMinimalWorkflow` | Create workflow for context | [executor-context.factory.ts]() |\n\n### Executor Context Structure\n\n```typescript\ninterface ExecutorContext {\n  blockStates: Map<string, ExecutorBlockState>\n  executedBlocks: Set<string>\n  workflow: SerializedWorkflow\n  connections: SerializedConnection[]\n  requestId: string\n  abortSignal?: AbortSignal\n}\n```\n\n## Tool Execution Pipeline\n\n```mermaid\ngraph LR\n    A[Tool Call Request] --> B{Interactive Mode?}\n    B -->|Yes| C{Client Executable?}\n    B -->|No| D{Auto Execute?}\n    C -->|Workflow Tool| E[Delegate to Client]\n    C -->|Sim Executed| F[Execute Tool]\n    D -->|Yes| G[Fire Tool Execution]\n    D -->|No| H[Wait for Confirmation]\n    E --> I[Update Tool State]\n    F --> I\n    G --> I\n    H --> I\n    I --> J[Report Result]\n    J --> K[Update Memory]\n```\n\n### Result Handling\n\nThe agent system handles multiple outcome types for tool executions:\n\n| Outcome | Status | Description |\n|---------|--------|-------------|\n| `success` | Completed successfully | Tool executed without errors |\n| `error` | Execution failed | Tool encountered an error |\n| `cancelled` | User cancelled | Execution was manually stopped |\n| `skipped` | Not needed | Result was no longer required |\n\n## Configuration Options\n\n### Orchestrator Options\n\n```typescript\ninterface OrchestratorOptions {\n  interactive?: boolean        // Require user confirmation\n  autoExecuteTools?: boolean   // Auto-execute without prompt\n  abortSignal?: AbortSignal    // Cancellation token\n  timeout?: number             // Execution timeout\n}\n```\n\n### Streaming Context\n\n```typescript\ninterface StreamingContext {\n  requestId: string\n  toolCalls: Map<string, ToolCallState>\n  pendingPromises: Map<string, Promise<ToolResult>>\n  onToolResult?: (result: ToolResult) => void\n}\n```\n\n## Error Handling\n\nThe agent system implements comprehensive error handling across all execution paths:\n\n1. **Tool Execution Errors**: Caught and wrapped in standard error format\n2. **Stream Dead Detection**: Aborts pending tools when stream becomes unresponsive\n3. **Timeout Handling**: Respects abort signals for long-running operations\n4. **State Validation**: Ensures consistency before state transitions\n\n### Error Response Format\n\n```typescript\ninterface ToolErrorResponse {\n  status: MothershipStreamV1ToolOutcome.error\n  message: string\n  data: {\n    error: string\n  }\n}\n```\n\n## Integration Points\n\nThe Agent System integrates with multiple platform components:\n\n| Component | Integration Type | Data Flow |\n|-----------|------------------|-----------|\n| Workflow Engine | Parent orchestrator | Initializes agent execution |\n| Block Registry | Tool resolution | Discovers available skills |\n| Memory Store | State persistence | Maintains conversation history |\n| Webhook Providers | External triggers | Receives external events |\n| Billing System | Usage tracking | Records execution metrics |\n\n## Testing\n\nThe Agent System includes comprehensive test coverage in `agent-handler.test.ts` and related test files, covering:\n\n- Tool execution scenarios (success, failure, cancellation)\n- Memory state management\n- Skills resolution logic\n- Streaming response handling\n- Error propagation paths\n\n---\n\n<a id='copilot-system'></a>\n\n## Copilot System\n\n### 相关页面\n\n相关主题：[Agent System](#agent-system), [Architecture Overview](#architecture-overview)\n\n<details>\n<summary>Relevant Source Files</summary>\n\n以下源码文件用于生成本页说明：\n\n- [apps/sim/lib/copilot/generated/trace-spans-v1.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/copilot/generated/trace-spans-v1.ts)\n- [README.md](https://github.com/simstudioai/sim/blob/main/README.md)\n- [apps/sim/package.json](https://github.com/simstudioai/sim/blob/main/apps/sim/package.json)\n- [apps/sim/lib/workflows/diff/diff-engine.test.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/workflows/diff/diff-engine.test.ts)\n- [apps/sim/lib/api/contracts/types.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/api/contracts/types.ts)\n</details>\n\n# Copilot System\n\nThe Copilot System is a Sim-managed AI-powered service that enables users to generate workflow nodes, fix errors, and iterate on flows directly from natural language instructions. It serves as an intelligent assistant embedded within the Sim platform, providing real-time assistance for workflow creation and modification.\n\n## Overview\n\nCopilot acts as an intelligent layer between users and the workflow engine, translating natural language inputs into executable workflow components. The system leverages large language models to understand user intent and generate appropriate code blocks, connections, and configurations within the Sim workflow environment.\n\n### Key Capabilities\n\n| Capability | Description |\n|------------|-------------|\n| Node Generation | Create new workflow blocks from natural language descriptions |\n| Error Resolution | Identify and fix issues in existing workflows |\n| Flow Iteration | Modify and improve workflow structures through conversational commands |\n| Analytics Tracking | Monitor all Copilot operations for performance and billing |\n\n## Architecture\n\nThe Copilot System consists of multiple API endpoints and tracking components that work together to provide a seamless AI-assisted experience.\n\n```mermaid\ngraph TD\n    A[User Input] --> B[Copilot API Layer]\n    B --> C[Chat Stream Route]\n    B --> D[Checkpoints Route]\n    B --> E[Models Route]\n    B --> F[Training Route]\n    C --> G[Trace Span Tracking]\n    G --> H[Analytics Collection]\n    H --> I[Billing System]\n```\n\n## API Endpoints\n\nThe Copilot System exposes several REST API endpoints for different operations:\n\n### Chat Stream Endpoint\n\nHandles real-time streaming of chat responses for Copilot interactions. This endpoint manages the bidirectional communication between the client and the AI model, providing immediate feedback as the Copilot processes natural language requests.\n\n### Checkpoints Route\n\nProvides functionality for saving and retrieving workflow checkpoints during Copilot-assisted editing. This allows users to maintain version history and revert to previous states if needed.\n\n### Models Route\n\nManages the available AI models that power Copilot functionality. The system supports multiple model configurations and allows for dynamic model selection based on task requirements.\n\n### Training Route\n\nHandles model fine-tuning and custom training workflows. This endpoint enables the system to learn from user interactions and improve response accuracy over time.\n\n## Trace Span Instrumentation\n\nThe Copilot System implements comprehensive OpenTelemetry trace spans for observability and monitoring. All trace span identifiers are defined in a generated contract file that ensures type safety and consistency between the frontend and backend.\n\n### Trace Span Categories\n\n| Category | Spans | Purpose |\n|----------|-------|---------|\n| Chat Operations | `chat.*` | Track conversation flow and tool usage |\n| Analytics | `copilot.analytics.*` | Monitor request metrics and billing |\n| Context Management | `context.*` | Track context window operations |\n| Authentication | `auth.*` | Security and rate limiting events |\n\n### Key Trace Span Identifiers\n\n| Identifier | Description |\n|------------|-------------|\n| `copilot.analytics.flush` | Analytics batch flush operation |\n| `copilot.analytics.save_request` | Persist individual request data |\n| `copilot.analytics.update_billing` | Update billing metrics |\n| `chat.setup` | Initialize chat session |\n| `chat.continue_with_tool_results` | Process tool execution results |\n| `context.reduce` | Context window reduction |\n| `context.summarize_chunk` | Summarize large context chunks |\n| `auth.validate_key` | API key validation |\n| `auth.rate_limit.record` | Rate limit tracking |\n\n## Integration with Workflows\n\nCopilot integrates deeply with the Sim workflow engine through the block system. When generating nodes or fixing errors, Copilot communicates with the workflow registry to validate and persist changes.\n\n### Workflow Registry Integration\n\nThe system uses Zustand for state management when interacting with workflow data:\n\n```typescript\n// Mock structure from test files\nuseWorkflowRegistry: {\n  getState: () => ({\n    activeWorkflowId: null,\n  }),\n}\n```\n\n### Block Generation\n\nCopilot generates workflow blocks by:\n\n1. Parsing natural language input\n2. Identifying required block types from the registry\n3. Validating block configurations against schema definitions\n4. Persisting generated blocks to the workflow state\n\n## Self-Hosted Deployment\n\nFor self-hosted Sim instances, Copilot requires separate configuration:\n\n### API Key Setup\n\n1. Navigate to [https://sim.ai](https://sim.ai)\n2. Go to Settings → Copilot\n3. Generate a Copilot API key\n4. Set the `COPILOT_API_KEY` environment variable in `apps/sim/.env`\n\n```bash\n# Example environment variable\nCOPILOT_API_KEY=your_generated_api_key_here\n```\n\n### Environment Configuration\n\nThe Copilot API key must be configured alongside other environment variables defined in the project's `.env.example` file. The system validates the API key on each request through the `auth.validate_key` trace span.\n\n## Analytics and Billing\n\nThe Copilot System implements a comprehensive analytics pipeline:\n\n### Analytics Flow\n\n```mermaid\ngraph LR\n    A[User Request] --> B[Save Request]\n    B --> C[Update Billing]\n    C --> D[Flush Analytics]\n    D --> E[Persist to Storage]\n```\n\n### Tracked Metrics\n\n| Metric | Trace Span | Description |\n|--------|------------|-------------|\n| Request Count | `copilot.analytics.save_request` | Individual Copilot invocations |\n| Billing Units | `copilot.analytics.update_billing` | Usage-based billing data |\n| Flush Events | `copilot.analytics.flush` | Batch processing completion |\n\n## Error Handling\n\nThe Copilot System handles various error scenarios through dedicated trace spans:\n\n| Error Type | Trace Span | Handling |\n|------------|------------|----------|\n| Explicit Abort | `chat.explicit_abort.*` | Graceful termination of requests |\n| Rate Limiting | `auth.rate_limit.record` | Throttling and quota enforcement |\n| Auth Failures | `auth.validate_key` | Invalid API key rejection |\n\n## Dependencies\n\nThe Copilot functionality is managed through the Bun workspace and depends on the following core packages:\n\n- **Next.js** (App Router) - API route handling\n- **Drizzle ORM** - Data persistence\n- **Zod** - Schema validation for API contracts\n- **Zustand** - Client-side state management\n\nDevelopment dependencies include the documentation generator script located at `scripts/generate-docs.ts` which can be run with `bun run generate-docs`.\n\n## Summary\n\nThe Copilot System provides intelligent assistance for workflow creation and modification within Sim. Through a combination of streaming chat APIs, comprehensive trace instrumentation, and deep workflow integration, it enables natural language-driven development experiences. The system is designed for both cloud-hosted and self-hosted deployments, with full observability through OpenTelemetry trace spans and analytics tracking.\n\n---\n\n<a id='deployment-guide'></a>\n\n## Deployment Guide\n\n### 相关页面\n\n相关主题：[Technology Stack](#tech-stack), [Background Jobs and Background Processing](#background-jobs)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [docker-compose.prod.yml](https://github.com/simstudioai/sim/blob/main/docker-compose.prod.yml)\n- [docker-compose.ollama.yml](https://github.com/simstudioai/sim/blob/main/docker-compose.ollama.yml)\n- [apps/sim/.env.example](https://github.com/simstudioai/sim/blob/main/apps/sim/.env.example)\n- [apps/realtime/.env.example](https://github.com/simstudioai/sim/blob/main/apps/realtime/.env.example)\n- [.devcontainer/docker-compose.yml](https://github.com/simstudioai/sim/blob/main/.devcontainer/docker-compose.yml)\n</details>\n\n# Deployment Guide\n\nSim is a workflow automation platform that supports multiple deployment configurations. This guide covers self-hosted deployment options including Docker, Docker Compose, manual setup, and Kubernetes via Helm charts.\n\n## Overview\n\nSim can be deployed in several ways depending on your infrastructure requirements and operational capabilities:\n\n| Deployment Method | Use Case | Complexity |\n|-------------------|----------|------------|\n| NPM Package (Docker) | Quick local testing | Low |\n| Docker Compose | Single-server production | Medium |\n| Manual Setup | Custom infrastructure | High |\n| Helm Chart | Kubernetes clusters | Medium-High |\n\n## Prerequisites\n\n### Hardware Requirements\n\n| Component | Minimum | Recommended |\n|-----------|---------|-------------|\n| CPU | 2 cores | 4+ cores |\n| Memory | 4 GB RAM | 8+ GB RAM |\n| Disk | 20 GB | 50+ GB SSD |\n| Docker | 20.10+ | Latest |\n\n### Software Requirements\n\n- **Docker** must be installed and running\n- **Bun** runtime (for manual setup)\n- **Node.js** v20+ (for manual setup)\n- **PostgreSQL** 12+ with **pgvector** extension (for manual setup)\n\n## Self-Hosted: NPM Package (Docker)\n\nThe fastest way to get started with Sim using Docker.\n\n### Quick Start\n\n```bash\nnpx simstudio\n```\n\nThis launches Sim at `http://localhost:3000` 资料来源：[README.md]()\n\n### Command Options\n\n| Flag | Description | Default |\n|------|-------------|---------|\n| `-p, --port <port>` | Port to run Sim on | `3000` |\n| `--no-pull` | Skip pulling latest Docker images | - |\n\n### Example Usage\n\n```bash\n# Run on custom port\nnpx simstudio --port 8080\n\n# Skip image pull (use cached images)\nnpx simstudio --no-pull\n```\n\n## Self-Hosted: Docker Compose\n\nFor production deployments on a single server, use the production Docker Compose configuration.\n\n### Standard Deployment\n\n```bash\ngit clone https://github.com/simstudioai/sim.git && cd sim\ndocker compose -f docker-compose.prod.yml up -d\n```\n\nOpen [http://localhost:3000](http://localhost:3000) to access Sim 资料来源：[README.md]()\n\n### Architecture\n\n```mermaid\ngraph TB\n    subgraph \"Docker Compose Stack\"\n        A[\"Next.js App<br>:3000\"] --> B[\"PostgreSQL<br>:5432\"]\n        A --> C[\"Redis<br>:6379\"]\n        A --> D[\"Realtime Service<br>:3001\"]\n        D --> B\n        D --> C\n    end\n    E[\"External Services\"] --> A\n```\n\n### Services\n\n| Service | Image | Port | Purpose |\n|---------|-------|------|---------|\n| app | simstudio/sim-app | 3000 | Main Next.js application |\n| realtime | simstudio/sim-realtime | 3001 | WebSocket/real-time events |\n| postgres | pgvector/pgvector | 5432 | Database with vector support |\n| redis | redis:alpine | 6379 | Caching and session storage |\n\n## Self-Hosted: Local Models (Ollama/vLLM)\n\nSim supports local AI models via Ollama and vLLM for privacy-focused or offline deployments.\n\n### Ollama Integration\n\nSim integrates with Ollama to run local models for workflow execution.\n\n```bash\ngit clone https://github.com/simstudioai/sim.git && cd sim\ndocker compose -f docker-compose.ollama.yml up -d\n```\n\n#### Ollama Configuration\n\n```mermaid\ngraph LR\n    A[\"Sim App\"] --> B[\"Ollama Service\"]\n    B --> C[\"Local Models<br>llama2, mistral, etc.\"]\n```\n\n#### Supported Ollama Environment Variables\n\n| Variable | Description | Default |\n|----------|-------------|---------|\n| `OLLAMA_HOST` | Ollama server URL | `http://localhost:11434` |\n| `OLLAMA_MODEL` | Default model to use | - |\n\n### vLLM Integration\n\nFor high-performance local inference, configure vLLM:\n\n```yaml\n# docker-compose.override.yml\nservices:\n  app:\n    environment:\n      VLLM_HOST: \"http://vllm:8000\"\n      VLLM_MODEL: \"meta-llama/Llama-2-7b-hf\"\n```\n\nSee the [Docker self-hosting docs](https://docs.sim.ai/self-hosting/docker) for detailed setup instructions 资料来源：[README.md]()\n\n## Self-Hosted: Manual Setup\n\nFor custom infrastructure or development environments, install Sim manually.\n\n### Step 1: Clone and Install Dependencies\n\n```bash\ngit clone https://github.com/simstudioai/sim.git\ncd sim\nbun install\nbun run prepare  # Set up pre-commit hooks\n```\n\n### Step 2: PostgreSQL with pgvector Setup\n\n```bash\ndocker run --name simstudio-db \\\n  -e POSTGRES_PASSWORD=your_password \\\n  -e POSTGRES_DB=simstudio \\\n  -p 5432:5432 \\\n  -d \\\n  pgvector/pgvector:pg16\n```\n\n### Step 3: Environment Configuration\n\nCopy the example environment file and configure:\n\n```bash\ncd apps/sim\ncp .env.example .env\n# Edit .env with your configuration\n```\n\n#### Application Environment Variables\n\n| Variable | Description | Required |\n|----------|-------------|----------|\n| `DATABASE_URL` | PostgreSQL connection string | Yes |\n| `BETTER_AUTH_SECRET` | Secret for authentication | Yes |\n| `ENCRYPTION_KEY` | Data encryption key | Yes |\n| `NEXT_PUBLIC_APP_URL` | Public application URL | Yes |\n| `BETTER_AUTH_URL` | Authentication service URL | Yes |\n| `INTERNAL_API_SECRET` | Internal API authentication | Yes |\n| `CRON_SECRET` | Cron job authentication | Yes |\n\n### Step 4: Build and Start\n\n```bash\nbun run build\nbun run start\n```\n\n## Development Environment (Dev Container)\n\nThe repository includes a pre-configured development container.\n\n### Structure\n\n```mermaid\ngraph TB\n    subgraph \".devcontainer\"\n        A[\"Dev Container\"] --> B[\"PostgreSQL\"]\n        A --> C[\"Redis\"]\n        A --> D[\"MailHog\"]\n    end\n    A --> E[\"Sim App\"]\n    A --> F[\"Realtime Service\"]\n```\n\n### Dev Container Services\n\n| Service | Port | Purpose |\n|---------|------|---------|\n| Sim App | 3000 | Main application |\n| PostgreSQL | 5432 | Database |\n| Redis | 6379 | Caching |\n| MailHog | 8025 | Email testing |\n\n## Helm Chart Deployment\n\nFor Kubernetes clusters, use the official Helm chart.\n\n### Installation\n\n```bash\nhelm install sim ./helm/sim \\\n  --namespace sim \\\n  --create-namespace\n```\n\n### Production Configuration\n\n```yaml\n# values.yaml\napp:\n  replicaCount: 3\n  env:\n    NEXT_PUBLIC_APP_URL: \"https://sim.example.com\"\n    BETTER_AUTH_URL: \"https://sim.example.com\"\n\npostgresql:\n  auth:\n    database: simstudio\n  primary:\n    persistence:\n      size: 50Gi\n\nmonitoring:\n  enabled: true\n  prometheus:\n    enabled: true\n```\n\n### Secrets Management\n\nThe Helm chart supports three methods for managing secrets, in order of production-readiness:\n\n#### Method 1: Inline `--set` (Development Only)\n\n```bash\nhelm install sim ./helm/sim --set app.env.BETTER_AUTH_SECRET=...\n```\n\n> ⚠️ **Warning**: Values set this way appear in `helm get values` output. Not recommended for production.\n\n#### Method 2: Pre-existing Kubernetes Secret\n\n```bash\nkubectl create secret generic sim-app-secrets --namespace sim \\\n  --from-literal=BETTER_AUTH_SECRET=$(openssl rand -hex 32) \\\n  --from-literal=ENCRYPTION_KEY=$(openssl rand -hex 32) \\\n  --from-literal=INTERNAL_API_SECRET=$(openssl rand -hex 32) \\\n  --from-literal=CRON_SECRET=$(openssl rand -hex 32)\n\nkubectl create secret generic sim-postgres-secret --namespace sim \\\n  --from-literal=POSTGRES_PASSWORD=$(openssl rand -base64 24 | tr -d '/+=')\n```\n\nReference secrets in values:\n\n```yaml\napp:\n  secrets:\n    existingSecret:\n      enabled: true\n      name: sim-app-secrets\n\npostgresql:\n  auth:\n    existingSecret:\n      enabled: true\n      name: sim-postgres-secret\n      passwordKey: POSTGRES_PASSWORD\n```\n\n#### Method 3: External Secrets Operator (Recommended for Production)\n\nIntegrate with AWS Secrets Manager, HashiCorp Vault, or Azure Key Vault.\n\n### Autoscaling Configuration\n\n```yaml\nautoscaling:\n  enabled: true\n  minReplicas: 2\n  maxReplicas: 20\n  targetCPUUtilizationPercentage: 70\n  targetMemoryUtilizationPercentage: 80\n```\n\nWhen `autoscaling.enabled=true`, the chart omits `spec.replicas` from the Deployment so the HPA owns replica count. Requires `metrics-server` in the cluster 资料来源：[helm/sim/README.md]()\n\n### Network Policy\n\nEnable east-west isolation and block cloud metadata endpoints:\n\n```yaml\nnetworkPolicy:\n  enabled: true\n```\n\n### Key Helm Configuration Reference\n\n| Parameter | Description | Default |\n|-----------|-------------|---------|\n| `app.replicaCount` | Number of app replicas | 1 |\n| `app.image.repository` | App image repository | simstudio/sim-app |\n| `app.image.tag` | App image tag | appVersion |\n| `app.env.NEXT_PUBLIC_APP_URL` | Public app URL | localhost:3000 |\n| `app.env.BETTER_AUTH_URL` | Auth service URL | localhost:3000 |\n| `autoscaling.enabled` | Enable HPA | false |\n| `monitoring.enabled` | Enable monitoring | false |\n| `networkPolicy.enabled` | Enable network policies | false |\n\n### Important URLs Configuration\n\n> ⚠️ **Critical**: `app.env.NEXT_PUBLIC_APP_URL` and `app.env.BETTER_AUTH_URL` must match your public origin (e.g., `https://sim.example.com`). Leaving them as `localhost` breaks sign-in functionality.\n\n## Environment Variables Reference\n\n### Application (.env.example)\n\n| Variable | Required | Description |\n|----------|----------|-------------|\n| `DATABASE_URL` | Yes | PostgreSQL connection string |\n| `BETTER_AUTH_SECRET` | Yes | Authentication secret |\n| `BETTER_AUTH_URL` | Yes | Authentication service URL |\n| `NEXT_PUBLIC_APP_URL` | Yes | Public application URL |\n| `ENCRYPTION_KEY` | Yes | Data encryption key |\n| `INTERNAL_API_SECRET` | Yes | Internal API secret |\n| `CRON_SECRET` | Yes | Cron job secret |\n| `REDIS_URL` | No | Redis connection URL |\n| `SOCKET_SERVER_URL` | No | WebSocket server URL |\n| `OLLAMA_URL` | No | Ollama server URL |\n| `SMTP_*` | No | Email configuration |\n\n### Realtime Service (.env.example)\n\n| Variable | Required | Description |\n|----------|----------|-------------|\n| `REDIS_URL` | Yes | Redis connection URL |\n| `DATABASE_URL` | Yes | PostgreSQL connection string |\n| `INTERNAL_API_SECRET` | Yes | Internal API secret |\n\n## Testing Deployments\n\n### Load Testing\n\nThe repository includes Artillery load testing configurations:\n\n```bash\n# Workflow load testing\nbunx artillery run scripts/load/workflow-waves.yml\n\n# Isolation testing\nbunx artillery run scripts/load/workflow-isolation.yml\n```\n\n### Docker Health Checks\n\n```bash\n# Check service status\ndocker compose ps\n\n# View logs\ndocker compose logs -f app\n\n# Restart services\ndocker compose restart\n```\n\n## Troubleshooting\n\n### Common Issues\n\n| Issue | Solution |\n|-------|----------|\n| Sign-in fails | Verify `NEXT_PUBLIC_APP_URL` and `BETTER_AUTH_URL` match public origin |\n| Database connection failed | Check `DATABASE_URL` and ensure PostgreSQL is running |\n| WebSocket connection failed | Verify `SOCKET_SERVER_URL` is accessible |\n| Image pull fails | Use `--no-pull` flag or check Docker registry access |\n| Autoscaling not working | Ensure `metrics-server` is installed in cluster |\n\n### Log Locations\n\n| Environment | Log Command |\n|-------------|-------------|\n| Docker Compose | `docker compose logs -f [service]` |\n| Kubernetes | `kubectl logs -n sim -l app=sim` |\n| Helm | `helm status sim -n sim` |\n\n## Next Steps\n\n- [Configuration Reference](https://docs.sim.ai/configuration) - Complete environment variable documentation\n- [Local Model Setup](https://docs.sim.ai/self-hosting/docker) - Ollama and vLLM configuration\n- [Monitoring Setup](https://docs.sim.ai/monitoring) - Prometheus and Grafana integration\n- [Security Hardening](https://docs.sim.ai/security) - Production security recommendations\n\n---\n\n<a id='background-jobs'></a>\n\n## Background Jobs and Background Processing\n\n### 相关页面\n\n相关主题：[Workflow Executor Engine](#executor-engine), [Deployment Guide](#deployment-guide)\n\n<details>\n<summary>相关源码文件</summary>\n\n以下源码文件用于生成本页说明：\n\n- [apps/sim/background/workflow-execution.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/background/workflow-execution.ts)\n- [apps/sim/background/schedule-execution.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/background/schedule-execution.ts)\n- [apps/sim/background/webhook-execution.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/background/webhook-execution.ts)\n- [apps/sim/background/knowledge-connector-sync.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/background/knowledge-connector-sync.ts)\n- [apps/sim/background/resume-execution.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/background/resume-execution.ts)\n- [apps/sim/lib/core/async-jobs/types.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/core/async-jobs/types.ts)\n- [apps/sim/lib/table/workflow-columns.ts](https://github.com/simstudioai/sim/blob/main/apps/sim/lib/table/workflow-columns.ts)\n</details>\n\n# Background Jobs and Background Processing\n\n## Overview\n\nThe Sim platform uses a robust background job system to handle asynchronous, long-running, and resource-intensive operations outside the request-response cycle. This architecture enables workflows, schedules, webhooks, and other processing tasks to execute reliably without blocking user interactions.\n\nThe background processing system is designed around a **job queue abstraction** that supports multiple backend implementations, allowing the platform to scale horizontally and handle high-throughput scenarios with proper concurrency control.\n\n## Architecture\n\n### System Components\n\nThe background processing architecture consists of three main layers:\n\n1. **Job Queue Interface** - A unified abstraction for enqueuing, monitoring, and managing jobs\n2. **Backend Implementations** - Pluggable backends (database, trigger.dev) that handle actual job processing\n3. **Job Handlers** - Specific implementations for different job types (workflow, schedule, webhook, etc.)\n\n```mermaid\ngraph TD\n    subgraph \"Job Producers\"\n        API[API Request]\n        Schedule[Scheduled Trigger]\n        Webhook[Webhook Trigger]\n        Table[Table Cell Execution]\n    end\n\n    subgraph \"Job Queue Interface\"\n        Queue[JobQueue API]\n        Enqueue[enqueue / batchEnqueue]\n        GetJob[getJob / startJob]\n        Cancel[cancelJob]\n    end\n\n    subgraph \"Backends\"\n        DB[(Database Backend)]\n        TD[Trigger.dev Backend]\n    end\n\n    subgraph \"Job Handlers\"\n        WE[Workflow Execution]\n        SE[Schedule Execution]\n        HE[Webhook Execution]\n        KC[Knowledge Connector Sync]\n        RE[Resume Execution]\n    end\n\n    API --> Queue\n    Schedule --> Queue\n    Webhook --> Queue\n    Table --> Queue\n\n    Queue --> Enqueue\n    Queue --> GetJob\n    Queue --> Cancel\n\n    Enqueue --> DB\n    Enqueue --> TD\n\n    DB --> WE\n    DB --> SE\n    DB --> HE\n    DB --> KC\n    DB --> RE\n\n    TD --> WE\n```\n\n### Backend Types\n\nThe system supports two backend implementations for job queues:\n\n| Backend Type | Identifier | Description |\n|--------------|------------|-------------|\n| Database | `database` | Built-in queue using database storage, suitable for self-hosted deployments |\n| Trigger.dev | `trigger-dev` | External job processing service for cloud deployments |\n\n资料来源：[apps/sim/lib/core/async-jobs/types.ts:40]()\n\n## Job Queue Interface\n\n### Core Interface Methods\n\nThe `JobQueue` interface provides a unified API for all job operations:\n\n| Method | Parameters | Returns | Description |\n|--------|------------|---------|-------------|\n| `enqueue` | `type: JobType`, `payload: TPayload`, `options?: EnqueueOptions` | `Promise<string>` | Add a single job to the queue |\n| `batchEnqueue` | `type: JobType`, `items: Array<{payload, options?}>` | `Promise<string[]>` | Add multiple jobs as a batch |\n| `getJob` | `jobId: string` | `Promise<Job \\| null>` | Retrieve job by ID |\n| `startJob` | `jobId: string` | `Promise<void>` | Mark job as started/processing |\n| `completeJob` | `jobId: string`, `output: unknown` | `Promise<void>` | Mark job as completed with output |\n| `markJobFailed` | `jobId: string`, `error: string` | `Promise<void>` | Mark job as failed with error |\n| `cancelJob` | `jobId: string` | `Promise<void>` | Request job cancellation |\n\n资料来源：[apps/sim/lib/core/async-jobs/types.ts:1-30]()\n\n### Job Configuration Options\n\nJobs can be configured with the following options:\n\n| Option | Type | Description |\n|--------|------|-------------|\n| `metadata` | `object` | Additional metadata including workflow ID, workspace ID, and correlation data |\n| `concurrencyKey` | `string` | Key for per-key concurrency limiting |\n| `concurrencyLimit` | `number` | Maximum concurrent jobs for this key (database backend only) |\n| `tags` | `string[]` | Tags for categorization (e.g., `tableId:xxx`, `rowId:yyy`) |\n| `runner` | `function` | Custom job body for database backend when no external worker exists |\n\n资料来源：[apps/sim/lib/core/async-jobs/types.ts:55-75]()\n\n## Job Types\n\nThe platform defines several job types for different processing scenarios:\n\n```typescript\nexport type JobType = \n  | 'workflow'\n  | 'workflow-group-cell'\n  | 'schedule'\n  | 'webhook'\n  | 'knowledge-connector-sync'\n  | 'resume'\n```\n\n### Workflow Execution (`workflow`)\n\nThe core job type for executing workflows. Handles the full lifecycle from triggering to completion.\n\n**Handler:** `executeWorkflowJob`\n\n**Payload includes:**\n- `workflowId` - Target workflow identifier\n- `workspaceId` - Workspace containing the workflow\n- `input` - Input data for the workflow\n- `executionId` - Unique execution identifier\n- `source` - Trigger source (e.g., `'api'`, `'table'`, `'schedule'`)\n\n资料来源：[apps/sim/background/workflow-execution.ts]()\n\n### Workflow Group Cell (`workflow-group-cell`)\n\nExecutes workflow groups for table rows. Supports high-concurrency table-based workflow execution.\n\n**Handler:** `executeWorkflowGroupCellJob`\n\n**Key Features:**\n- Table concurrency limiting (`TABLE_CONCURRENCY_LIMIT`)\n- Per-row execution tracking\n- Correlation with table and row identifiers\n\n```mermaid\nsequenceDiagram\n    participant Table as Table Scheduler\n    participant Queue as Job Queue\n    participant Worker as Cell Worker\n    \n    Table->>Queue: batchEnqueue(workflow-group-cell, runs[])\n    Queue-->>Table: jobIds[]\n    Worker->>Queue: getJob(jobId)\n    Worker->>Worker: executeWorkflowGroupCellJob(payload)\n    Worker->>Queue: completeJob(jobId, output)\n```\n\n资料来源：[apps/sim/lib/table/workflow-columns.ts:30-60]()\n\n### Schedule Execution (`schedule`)\n\nHandles time-based workflow triggers defined by schedules.\n\n**Handler:** `executeScheduleJob`\n\n资料来源：[apps/sim/background/schedule-execution.ts]()\n\n### Webhook Execution (`webhook`)\n\nProcesses incoming webhook payloads and triggers associated workflows.\n\n**Handler:** `executeWebhookJob`\n\n资料来源：[apps/sim/background/webhook-execution.ts]()\n\n### Knowledge Connector Sync (`knowledge-connector-sync`)\n\nSynchronizes data between external knowledge sources and the platform.\n\n**Handler:** `executeKnowledgeConnectorSyncJob`\n\n资料来源：[apps/sim/background/knowledge-connector-sync.ts]()\n\n### Resume Execution (`resume`)\n\nResumes previously paused or checkpointed workflow executions.\n\n**Handler:** `executeResumeJob`\n\n资料来源：[apps/sim/background/resume-execution.ts]()\n\n## Concurrency Control\n\n### Table Concurrency\n\nFor table-based workflow execution, the system enforces a concurrency limit to prevent resource exhaustion:\n\n```typescript\nconst TABLE_CONCURRENCY_LIMIT = 5\n```\n\nJobs for the same table are grouped by `concurrencyKey` to ensure ordered processing while allowing parallel execution across different tables.\n\n资料来源：[apps/sim/lib/table/workflow-columns.ts:50]()\n\n### Job Tagging\n\nJobs are tagged for tracking and monitoring:\n\n| Tag Format | Example | Purpose |\n|------------|---------|---------|\n| `tableId:{id}` | `tableId:abc123` | Identifies the source table |\n| `rowId:{id}` | `rowId:row456` | Identifies the source row |\n| `group:{id}` | `group:grp789` | Identifies the workflow group |\n\n资料来源：[apps/sim/lib/table/workflow-columns.ts:55]()\n\n## Job Correlation and Tracing\n\n### Metadata Structure\n\nEach job carries correlation metadata for distributed tracing:\n\n```typescript\ninterface CorrelationData {\n  executionId: string\n  requestId: string\n  source: 'workflow' | 'api' | 'schedule' | 'webhook' | 'table'\n  workflowId: string\n  triggerType: string\n}\n```\n\n### Request ID Format\n\nRequest IDs follow a consistent naming convention based on job type:\n\n| Job Type | Request ID Format | Example |\n|----------|-------------------|---------|\n| Workflow Group Cell | `wfgrp-{executionId}` | `wfgrp-exec-123` |\n\n资料来源：[apps/sim/lib/table/workflow-columns.ts:43]()\n\n## Job Lifecycle\n\n### State Transitions\n\n```mermaid\nstateDiagram-v2\n    [*] --> Queued: enqueue()\n    Queued --> Processing: startJob()\n    Processing --> Completed: completeJob()\n    Processing --> Failed: markJobFailed()\n    Processing --> Cancelled: cancelJob()\n    Queued --> Cancelled: cancelJob()\n    Cancelled --> [*]\n    Completed --> [*]\n    Failed --> [*]\n```\n\n### Status Definitions\n\n| Status | Description |\n|--------|-------------|\n| `pending` | Job is queued but not yet picked up |\n| `queued` | Job is in the queue (alternative state) |\n| `processing` | Job is currently being executed |\n| `completed` | Job finished successfully |\n| `failed` | Job encountered an error |\n| `cancelled` | Job was cancelled before completion |\n\n## Error Handling and Cancellation\n\n### Best-Effort Cancellation\n\nThe `cancelJob` method implements best-effort cancellation:\n- Unknown or already-completed jobs resolve quietly (no error thrown)\n- Underlying provider rejections fail loudly to alert operators\n\n```typescript\n/**\n * Request cancellation of a queued or running job. Best-effort: backends should\n * fail loudly if the underlying provider rejects, but a missing/unknown jobId\n * should resolve quietly so callers can drive cancel from possibly-stale state.\n */\ncancelJob(jobId: string): Promise<void>\n```\n\n资料来源：[apps/sim/lib/core/async-jobs/types.ts:28-33]()\n\n### Runner Functions\n\nFor the database backend, jobs include a `runner` function that is executed as a fire-and-forget IIFE (Immediately Invoked Function Expression). This allows the database row to drive the job through processing states:\n\n```typescript\nrunner?: <TPayload>(\n  payload: TPayload, \n  signal: AbortSignal\n) => Promise<void>\n```\n\nThe `AbortSignal` is driven by `cancelJob`, enabling graceful shutdown of cancelled jobs.\n\n资料来源：[apps/sim/lib/core/async-jobs/types.ts:62-69]()\n\n## Batch Enqueue Operations\n\n### Batch Processing Flow\n\n```mermaid\ngraph LR\n    A[Pending Runs] --> B[Map to Job Items]\n    B --> C{Backend Type}\n    C -->|Database| D[Single Multi-Row INSERT]\n    C -->|Trigger.dev| E[tasks.batchTrigger]\n    D --> F[Return jobIds in input order]\n    E --> F\n    F --> G[Promise.allSettled Fallback]\n    G -->|If batch fails| H[Individual Enqueue]\n```\n\nThe batch enqueue operation:\n1. Maps pending runs to job items with full metadata and options\n2. Attempts batch enqueue via the queue backend\n3. Falls back to individual enqueue if batch fails\n4. Returns one jobId per item in input order\n\n资料来源：[apps/sim/lib/table/workflow-columns.ts:60-75]()\n\n## Integration with SDKs\n\n### Python SDK Async Execution\n\nThe Python SDK provides async execution support through the `execute_workflow` method with `async_execution=True`:\n\n```python\nresult = client.execute_workflow(\n    'workflow-id',\n    {'message': 'Hello'},\n    async_execution=True\n)\n# Returns AsyncExecutionResult with job_id and status_url\n```\n\n### TypeScript SDK Async Execution\n\nSimilarly, the TypeScript SDK supports async execution:\n\n```typescript\nconst result = await client.executeWorkflow('workflow-id', { data: 'input' }, {\n  asyncExecution: true\n});\n// Returns AsyncExecutionResult with jobId\n```\n\nJob status can be monitored via `getJobStatus(jobId)`.\n\n资料来源：[packages/python-sdk/README.md](), [packages/ts-sdk/README.md]()\n\n## Testing Support\n\nThe testing utilities in `packages/testing` provide factories for creating workflow test fixtures:\n\n- `createWorkflowState()` - Base workflow state\n- `createLinearWorkflow(n)` - Sequential workflow with n blocks\n- `createBranchingWorkflow()` - Conditional branching workflow\n\n资料来源：[packages/testing/src/factories/workflow.factory.ts]()\n\n## Summary\n\nThe background job system in Sim provides:\n\n1. **Unified Queue Interface** - Consistent API across different job types and backends\n2. **Multiple Backend Support** - Database for self-hosted, Trigger.dev for cloud deployments\n3. **Rich Job Metadata** - Correlation data, tags, and concurrency controls for observability\n4. **Reliable Execution** - State management, cancellation support, and retry capabilities\n5. **Batch Operations** - Efficient bulk enqueue with fallback to individual operations\n6. **SDK Integration** - Async execution support in both Python and TypeScript SDKs\n\n---\n\n---\n\n## Doramagic 踩坑日志\n\n项目：simstudioai/sim\n\n摘要：发现 20 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：安装坑 - 社区讨论暴露的待验证问题：Open-source general purpose agent with built-in MCPToolkit support。\n\n## 1. 安装坑 · 社区讨论暴露的待验证问题：Open-source general purpose agent with built-in MCPToolkit support\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Open-source general purpose agent with built-in MCPToolkit support 15 May 2025 · ... MCP for local-agent workflows · r/LocalLLaMA - A visual ... r/commandline - CLI tool to simplify open source monitoring agent installation.\n- 对用户的影响：这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- 建议检查：Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- 证据：social_signal:reddit | ssig_7a250aac9fa1441c8186a7b73d669d8f | https://www.reddit.com/r/LocalLLaMA/comments/1kn8m8t/opensource_general_purpose_agent_with_builtin/ | Open-source general purpose agent with built-in MCPToolkit support\n\n## 2. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | host_targets=cursor\n\n## 3. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | README/documentation is current enough for a first validation pass.\n\n## 4. 运行坑 · 来源证据：v0.6.63\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.6.63\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_5a97e1d742fe4d7f918e0b42f27b87c3 | https://github.com/simstudioai/sim/releases/tag/v0.6.63 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 5. 运行坑 · 来源证据：v0.6.65\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.6.65\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_03f18559029c4724b11011ef96259161 | https://github.com/simstudioai/sim/releases/tag/v0.6.65 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 6. 运行坑 · 来源证据：v0.6.67\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.6.67\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_048d1506c1d645b0be435841a26b93ed | https://github.com/simstudioai/sim/releases/tag/v0.6.67 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 7. 运行坑 · 来源证据：v0.6.73\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.6.73\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_048864e1cdcc44d2b2a30917b7c4adc2 | https://github.com/simstudioai/sim/releases/tag/v0.6.73 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 8. 维护坑 · 来源证据：v0.6.71\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v0.6.71\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_9c30d794fb7344489f96a6ac47cd1d6e | https://github.com/simstudioai/sim/releases/tag/v0.6.71 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 9. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | last_activity_observed missing\n\n## 10. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | no_demo; severity=medium\n\n## 11. 安全/权限坑 · 存在安全注意事项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：No sandbox install has been executed yet; downstream must verify before user use.\n- 对用户的影响：用户安装前需要知道权限边界和敏感操作。\n- 建议检查：转成明确权限清单和安全审查提示。\n- 防护动作：安全注意事项必须面向用户前置展示。\n- 证据：risks.safety_notes | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | No sandbox install has been executed yet; downstream must verify before user use.\n\n## 12. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | no_demo; severity=medium\n\n## 13. 安全/权限坑 · 来源证据：Unable to Access Files from Private GitHub Repository in Self-Hosted Setup\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Unable to Access Files from Private GitHub Repository in Self-Hosted Setup\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_ed1c9f64533441f5826c1fe98fa9ce49 | https://github.com/simstudioai/sim/issues/4555 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 14. 安全/权限坑 · 来源证据：v0.6.64\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.6.64\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_5e2aa5311b1748cea446771920242668 | https://github.com/simstudioai/sim/releases/tag/v0.6.64 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 15. 安全/权限坑 · 来源证据：v0.6.66\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.6.66\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_7d42c79fecf54003b117f76d49873223 | https://github.com/simstudioai/sim/releases/tag/v0.6.66 | 来源讨论提到 api key 相关条件，需在安装/试用前复核。\n\n## 16. 安全/权限坑 · 来源证据：v0.6.68\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.6.68\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_c8fe17ce7ba6424c88017ed644620915 | https://github.com/simstudioai/sim/releases/tag/v0.6.68 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 17. 安全/权限坑 · 来源证据：v0.6.69\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.6.69\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_a47b6988921146ac8fa66d73b0574c88 | https://github.com/simstudioai/sim/releases/tag/v0.6.69 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 18. 安全/权限坑 · 来源证据：v0.6.72\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.6.72\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_f13817452da14b5d97c64bde45647685 | https://github.com/simstudioai/sim/releases/tag/v0.6.72 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 19. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | issue_or_pr_quality=unknown\n\n## 20. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | release_recency=unknown\n\n<!-- canonical_name: simstudioai/sim; human_manual_source: deepwiki_human_wiki -->\n",
      "summary": "DeepWiki/Human Wiki 完整输出，末尾追加 Discovery Agent 踩坑日志。",
      "title": "Human Manual / 人类版说明书"
    },
    "pitfall_log": {
      "asset_id": "pitfall_log",
      "filename": "PITFALL_LOG.md",
      "markdown": "# Pitfall Log / 踩坑日志\n\n项目：simstudioai/sim\n\n摘要：发现 20 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：安装坑 - 社区讨论暴露的待验证问题：Open-source general purpose agent with built-in MCPToolkit support。\n\n## 1. 安装坑 · 社区讨论暴露的待验证问题：Open-source general purpose agent with built-in MCPToolkit support\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：Open-source general purpose agent with built-in MCPToolkit support 15 May 2025 · ... MCP for local-agent workflows · r/LocalLLaMA - A visual ... r/commandline - CLI tool to simplify open source monitoring agent installation.\n- 对用户的影响：这类外部讨论可能代表真实用户在安装、配置、升级或生产使用时遇到阻力；发布前不能只依赖官方 README。\n- 建议检查：Pack Agent 需要打开来源链接，确认问题是否仍然存在，并把验证结论写入说明书和边界卡。\n- 证据：social_signal:reddit | ssig_7a250aac9fa1441c8186a7b73d669d8f | https://www.reddit.com/r/LocalLLaMA/comments/1kn8m8t/opensource_general_purpose_agent_with_builtin/ | Open-source general purpose agent with built-in MCPToolkit support\n\n## 2. 配置坑 · 可能修改宿主 AI 配置\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。\n- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。\n- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。\n- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。\n- 证据：capability.host_targets | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | host_targets=cursor\n\n## 3. 能力坑 · 能力判断依赖假设\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：README/documentation is current enough for a first validation pass.\n- 对用户的影响：假设不成立时，用户拿不到承诺的能力。\n- 建议检查：将假设转成下游验证清单。\n- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。\n- 证据：capability.assumptions | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | README/documentation is current enough for a first validation pass.\n\n## 4. 运行坑 · 来源证据：v0.6.63\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.6.63\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_5a97e1d742fe4d7f918e0b42f27b87c3 | https://github.com/simstudioai/sim/releases/tag/v0.6.63 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 5. 运行坑 · 来源证据：v0.6.65\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.6.65\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_03f18559029c4724b11011ef96259161 | https://github.com/simstudioai/sim/releases/tag/v0.6.65 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 6. 运行坑 · 来源证据：v0.6.67\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.6.67\n- 对用户的影响：可能增加新用户试用和生产接入成本。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_048d1506c1d645b0be435841a26b93ed | https://github.com/simstudioai/sim/releases/tag/v0.6.67 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 7. 运行坑 · 来源证据：v0.6.73\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.6.73\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_048864e1cdcc44d2b2a30917b7c4adc2 | https://github.com/simstudioai/sim/releases/tag/v0.6.73 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 8. 维护坑 · 来源证据：v0.6.71\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：v0.6.71\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_9c30d794fb7344489f96a6ac47cd1d6e | https://github.com/simstudioai/sim/releases/tag/v0.6.71 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 9. 维护坑 · 维护活跃度未知\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：未记录 last_activity_observed。\n- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。\n- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。\n- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。\n- 证据：evidence.maintainer_signals | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | last_activity_observed missing\n\n## 10. 安全/权限坑 · 下游验证发现风险项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：下游已经要求复核，不能在页面中弱化。\n- 建议检查：进入安全/权限治理复核队列。\n- 防护动作：下游风险存在时必须保持 review/recommendation 降级。\n- 证据：downstream_validation.risk_items | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | no_demo; severity=medium\n\n## 11. 安全/权限坑 · 存在安全注意事项\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：No sandbox install has been executed yet; downstream must verify before user use.\n- 对用户的影响：用户安装前需要知道权限边界和敏感操作。\n- 建议检查：转成明确权限清单和安全审查提示。\n- 防护动作：安全注意事项必须面向用户前置展示。\n- 证据：risks.safety_notes | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | No sandbox install has been executed yet; downstream must verify before user use.\n\n## 12. 安全/权限坑 · 存在评分风险\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：no_demo\n- 对用户的影响：风险会影响是否适合普通用户安装。\n- 建议检查：把风险写入边界卡，并确认是否需要人工复核。\n- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。\n- 证据：risks.scoring_risks | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | no_demo; severity=medium\n\n## 13. 安全/权限坑 · 来源证据：Unable to Access Files from Private GitHub Repository in Self-Hosted Setup\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Unable to Access Files from Private GitHub Repository in Self-Hosted Setup\n- 对用户的影响：可能影响授权、密钥配置或安全边界。\n- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_ed1c9f64533441f5826c1fe98fa9ce49 | https://github.com/simstudioai/sim/issues/4555 | 来源类型 github_issue 暴露的待验证使用条件。\n\n## 14. 安全/权限坑 · 来源证据：v0.6.64\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.6.64\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_5e2aa5311b1748cea446771920242668 | https://github.com/simstudioai/sim/releases/tag/v0.6.64 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 15. 安全/权限坑 · 来源证据：v0.6.66\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.6.66\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_7d42c79fecf54003b117f76d49873223 | https://github.com/simstudioai/sim/releases/tag/v0.6.66 | 来源讨论提到 api key 相关条件，需在安装/试用前复核。\n\n## 16. 安全/权限坑 · 来源证据：v0.6.68\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.6.68\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_c8fe17ce7ba6424c88017ed644620915 | https://github.com/simstudioai/sim/releases/tag/v0.6.68 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 17. 安全/权限坑 · 来源证据：v0.6.69\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.6.69\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_a47b6988921146ac8fa66d73b0574c88 | https://github.com/simstudioai/sim/releases/tag/v0.6.69 | 来源讨论提到 docker 相关条件，需在安装/试用前复核。\n\n## 18. 安全/权限坑 · 来源证据：v0.6.72\n\n- 严重度：medium\n- 证据强度：source_linked\n- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：v0.6.72\n- 对用户的影响：可能阻塞安装或首次运行。\n- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。\n- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。\n- 证据：community_evidence:github | cevd_f13817452da14b5d97c64bde45647685 | https://github.com/simstudioai/sim/releases/tag/v0.6.72 | 来源类型 github_release 暴露的待验证使用条件。\n\n## 19. 维护坑 · issue/PR 响应质量未知\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：issue_or_pr_quality=unknown。\n- 对用户的影响：用户无法判断遇到问题后是否有人维护。\n- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。\n- 防护动作：issue/PR 响应未知时，必须提示维护风险。\n- 证据：evidence.maintainer_signals | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | issue_or_pr_quality=unknown\n\n## 20. 维护坑 · 发布节奏不明确\n\n- 严重度：low\n- 证据强度：source_linked\n- 发现：release_recency=unknown。\n- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。\n- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。\n- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。\n- 证据：evidence.maintainer_signals | art_4c769793e2db44b09c3ad8f55672a2ea | https://github.com/simstudioai/sim#readme | release_recency=unknown\n",
      "summary": "用户实践前最可能遇到的身份、安装、配置、运行和安全坑。",
      "title": "Pitfall Log / 踩坑日志"
    },
    "prompt_preview": {
      "asset_id": "prompt_preview",
      "filename": "PROMPT_PREVIEW.md",
      "markdown": "# sim - Prompt Preview\n\n> Copy the prompt below into your AI host before installing anything.\n> Its purpose is to let you safely feel the project's workflow, not to claim the project has already run.\n\n## Copy this prompt\n\n```text\nYou are using an independent Doramagic capability pack for simstudioai/sim.\n\nProject:\n- Name: sim\n- Repository: https://github.com/simstudioai/sim\n- Summary: <p align=\"center\">\n- Host target: cursor\n\nGoal:\nHelp me evaluate this project for the following task without installing it yet: <p align=\"center\">\n\nBefore taking action:\n1. Restate my task, success standard, and boundary.\n2. Identify whether the next step requires tools, browser access, network access, filesystem access, credentials, package installation, or host configuration.\n3. Use only the Doramagic Project Pack, the upstream repository, and the source-linked evidence listed below.\n4. If a real command, install step, API call, file write, or host integration is required, mark it as \"requires post-install verification\" and ask for approval first.\n5. If evidence is missing, say \"evidence is missing\" instead of filling the gap.\n\nPreviewable capabilities:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCapabilities that require post-install verification:\n- Capability 1: Use the source-backed project context to guide one small, checkable workflow step.\n\nCore service flow:\n1. project-introduction: Project Introduction. Produce one small intermediate artifact and wait for confirmation.\n2. tech-stack: Technology Stack. Produce one small intermediate artifact and wait for confirmation.\n3. architecture-overview: Architecture Overview. Produce one small intermediate artifact and wait for confirmation.\n4. executor-engine: Workflow Executor Engine. Produce one small intermediate artifact and wait for confirmation.\n5. workflow-blocks: Workflow Blocks System. Produce one small intermediate artifact and wait for confirmation.\n\nSource-backed evidence to keep in mind:\n- https://github.com/simstudioai/sim#readme\n- .agents/skills/add-block/SKILL.md\n- .agents/skills/add-connector/SKILL.md\n- .agents/skills/add-integration/SKILL.md\n- .agents/skills/add-tools/SKILL.md\n- .agents/skills/add-trigger/SKILL.md\n- .agents/skills/cleanup/SKILL.md\n- .agents/skills/emcn-design-review/SKILL.md\n- .agents/skills/react-query-best-practices/SKILL.md\n- .agents/skills/ship/SKILL.md\n\nFirst response rules:\n1. Start Step 1 only.\n2. Explain the one service action you will perform first.\n3. Ask exactly three questions about my target workflow, success standard, and sandbox boundary.\n4. Stop and wait for my answers.\n\nStep 1 follow-up protocol:\n- After I answer the first three questions, stay in Step 1.\n- Produce six parts only: clarified task, success standard, boundary conditions, two or three options, tradeoffs for each option, and one recommendation.\n- End by asking whether I confirm the recommendation.\n- Do not move to Step 2 until I explicitly confirm.\n\nConversation rules:\n- Advance one step at a time and wait for confirmation after each small artifact.\n- Write outputs as recommendations or planned checks, not as completed execution.\n- Do not claim tests passed, files changed, commands ran, APIs were called, or the project was installed.\n- If the user asks for execution, first provide the sandbox setup, expected output, rollback, and approval checkpoint.\n```\n",
      "summary": "不安装项目也能感受能力节奏的安全试用 Prompt。",
      "title": "Prompt Preview / 安装前试用 Prompt"
    },
    "quick_start": {
      "asset_id": "quick_start",
      "filename": "QUICK_START.md",
      "markdown": "# Quick Start / 官方入口\n\n项目：simstudioai/sim\n\n## 官方安装入口\n\n### Node.js / npx · 官方安装入口\n\n```bash\nnpx simstudio\n```\n\n来源：https://github.com/simstudioai/sim#readme\n\n## 来源\n\n- docs: https://github.com/simstudioai/sim#readme\n",
      "summary": "从项目官方 README 或安装文档提取的开工入口。",
      "title": "Quick Start / 官方入口"
    }
  },
  "validation_id": "dval_e4a6850475664ddc95ab003825de16a5"
}
