### User Script: Model Selection Example Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/model.md Demonstrates how to list available models, get the default model ID, and create a new conversation with a selected model. Requires `CAT.agent.model` and `CAT.agent.conversation` grants. ```javascript // ==UserScript== // @name 模型选择示例 // @grant CAT.agent.model // @grant CAT.agent.conversation // ==/UserScript== const models = await CAT.agent.model.list(); const defaultId = await CAT.agent.model.getDefault(); // 展示给用户选择 const selectedModel = models.find(m => m.supportsVision) || models[0]; const conv = await CAT.agent.conversation.create({ model: selectedModel.id }); ``` -------------------------------- ### SkillScript Implementation Example Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/skill-dev.md A practical example of a SkillScript for fetching weather data. It demonstrates accessing arguments, user configurations, making API calls, and returning results. ```javascript // ==SkillScript== // @name get_weather // @description 查询指定城市的天气信息 // @param city string [required] 城市名称 // @param days number 预报天数 // @timeout 30 // ==SkillScript== // 1. 通过 arguments[0] 接收 AI 传入的参数 const { city, days = 3 } = arguments[0]; // 2. CAT_CONFIG 提供用户在管理页面填写的 Skill 配置 const apiKey = CAT_CONFIG.apiKey; const unit = CAT_CONFIG.unit || "celsius"; // 3. 执行业务逻辑 const url = `https://api.openweathermap.org/data/2.5/forecast?q=${city}&cnt=${days}&units=${unit === "celsius" ? "metric" : "imperial"}&appid=${apiKey}`; const response = await fetch(url); if (!response.ok) { throw new Error(`API 请求失败: ${response.status}`); } const data = await response.json(); // 4. 通过 return 将结果返回给 AI return { city: data.city.name, country: data.city.country, forecasts: data.list.map(item => ({ date: item.dt_txt, temp: item.main.temp, description: item.weather[0].description })) }; ``` -------------------------------- ### Install Skill via URL Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/skill-install.md Use this URL directly in your browser or paste it into the ScriptCat management page to install a Skill. Ensure the URL points to a valid SKILL.cat.md file. ```url https://raw.githubusercontent.com/scriptscat/skills/main/browser-automation/SKILL.cat.md ``` -------------------------------- ### Install Skill Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/skill.md Installs or updates a Skill extension from provided content. ```APIDOC ## install — Install Skill Installs or updates a Skill extension using its core markdown content and optional script/reference files. ### Method ```javascript await CAT.agent.skills.install(skillMd: string, scripts?: Array<{ name: string, code: string }>, references?: Array<{ name: string, content: string }>) ``` ### Parameters #### Path Parameters - **skillMd** (string) - Required - The content of the SKILL.cat.md file. - **scripts** (Array<{ name: string, code: string }>) - Optional - A list of SkillScript files. - **references** (Array<{ name: string, content: string }>) - Optional - A list of reference files. ### Example ```javascript await CAT.agent.skills.install( `--- name: my-search description: Custom search tool --- When the user needs to search, use the search tool.`, [{ name: "search.js", code: skillScriptCode }], [{ name: "api-docs.md", content: "# API Docs\n..." }] ); ``` ### Returns `SkillRecord` - The installed or updated Skill's record. ``` -------------------------------- ### List Installed Skills Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/skill.md Retrieve a summary of all installed skills. Each summary includes basic information like name, version, and enabled status. ```javascript const skills = await CAT.agent.skills.list(); ``` -------------------------------- ### Install a New Skill Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/skill.md Install a new skill or update an existing one. Provide the skill's main markdown file, optional scripts, and optional reference files. ```javascript const record = await CAT.agent.skills.install(skillMd, scripts?, references?); ``` ```javascript const record = await CAT.agent.skills.install( `--- name: my-search description: 自定义搜索工具 --- 当用户需要搜索时,使用 search 工具。`, [{ name: "search.js", code: skillScriptCode }], [{ name: "api-docs.md", content: "# API 文档\n..." }] ); ``` -------------------------------- ### Package Multiple Scripts with UserSubscribe Source: https://context7.com/scriptscat/scriptcat.org/llms.txt Use `==UserSubscribe==` metadata to bundle multiple scripts into a single subscription file. Subscribed scripts install and update silently. This example shows how to list script URLs and metadata for a suite of scripts. ```javascript // ==UserSubscribe== // @name My Script Suite // @description Collection of productivity scripts for example.com // @version 1.2.0 // @author Dev // @connect api.example.com // @connect cdn.example.com // @scriptUrl https://example.com/scripts/enhancer.user.js // @scriptUrl https://example.com/scripts/dark-mode.user.js // @scriptUrl https://example.com/scripts/auto-fill.user.js // ==/UserSubscribe== // Install via: open the .user.sub.js URL in a browser with ScriptCat installed. // - First install: shows confirmation dialog // - Subsequent updates: silent, no confirmation (unless @connect changes) // - Scripts removed from @scriptUrl list are auto-uninstalled on next update check ``` -------------------------------- ### Example: Auto Form Filling User Script Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/dom.md A complete example demonstrating how to use various DOM agent functions within a userscript to automate form filling, interaction, and submission. ```javascript // ==UserScript== // @name 自动表单填写 // @match https://example.com/form // @grant CAT.agent.dom // ==/UserScript== // 等待表单加载 await CAT.agent.dom.waitFor("form#signup", { timeout: 5000 }); // 填写表单 await CAT.agent.dom.fill("input[name=username]", "test_user"); await CAT.agent.dom.fill("input[name=email]", "test@example.com"); // 勾选协议 await CAT.agent.dom.click("input[type=checkbox]#agree"); // 截图保存填写结果 await CAT.agent.dom.screenshot({ selector: "form#signup", saveTo: "screenshots/form-filled.png" }); // 点击提交 const result = await CAT.agent.dom.click("button[type=submit]", { trusted: true }); if (result.navigated) { console.log("表单提交成功,跳转到:", result.url); } ``` -------------------------------- ### GM_download Usage Example (Callback) Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/api.md Demonstrates how to use GM_download with a callback for the onload event and how to abort the download. This is useful for initiating file downloads with custom configurations. ```javascript // 回调形式 const dl = GM_download({ url: "https://example.com/file.zip", name: "file.zip", onload: () => alert("完成") }); dl.abort(); ``` -------------------------------- ### List Installed Skills Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/skill.md Retrieves a summary of all installed Skill extensions. ```APIDOC ## list — List Installed Skills Retrieves a summary of all installed Skill extensions. ### Method ```javascript await CAT.agent.skills.list() ``` ### Returns `SkillSummary[]` - An array of skill summary objects. **SkillSummary Structure:** | Field | Type | Description | |------|------|------| | `name` | `string` | Skill name | | `description` | `string` | Skill description | | `version` | `string` | Version number (semver) | | `toolNames` | `string[]` | List of included SkillScript tool names | | `referenceNames` | `string[]` | List of included reference file names | | `hasConfig` | `boolean` | Whether there are configuration fields declared | | `enabled` | `boolean` | Whether it is enabled (default `true`) | | `installUrl` | `string` | Installation source URL (for checking updates) | | `installtime` | `number` | Installation timestamp | | `updatetime` | `number` | Update timestamp | ``` -------------------------------- ### UserSubscribe Metadata Example Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/subscribe.md This metadata block is used at the beginning of a subscription script. It defines properties like name, description, version, author, connect permissions, and the URLs of scripts to be subscribed to. Use `UserSubscribe` instead of `UserScript` at the file's start. ```javascript // ==UserSubscribe== // @name xxx // @description 订阅xxx系列脚本 // @version 0.1.0 // @author You // @connect www.baidu.com // @scriptUrl https://script.tampermonkey.net.cn/48.user.js // @scriptUrl https://script.tampermonkey.net.cn/49.user.js // ==/UserSubscribe== ``` -------------------------------- ### startMonitor Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/dom.md Starts monitoring DOM changes and dialog events (alert/confirm/prompt) for a specified tab. ```APIDOC ## startMonitor — 开始监控 ```javascript await CAT.agent.dom.startMonitor(tabId); ``` 开始监控指定标签页的 DOM 变化和弹窗(alert/confirm/prompt)。 ``` -------------------------------- ### Full Example: MCP Tool Management Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/mcp.md Demonstrates adding an MCP server, testing its connection, listing its tools, and then using a tool in a conversation. MCP tools are automatically registered for AI use. ```javascript // ==UserScript== // @name MCP 工具管理 // @match *://*/* // @grant CAT.agent.mcp // @grant CAT.agent.conversation // ==/UserScript== // 添加一个 MCP 服务器 const server = await CAT.agent.mcp.addServer({ name: "Knowledge Base", url: "https://my-kb.example.com/mcp", apiKey: "my-api-key", enabled: true }); // 测试连接 try { await CAT.agent.mcp.testConnection(server.id); console.log("连接成功!"); } catch (e) { console.error("连接失败:", e); } // 查看可用工具 const tools = await CAT.agent.mcp.listTools(server.id); console.log("可用工具:", tools.map(t => t.name)); // 在对话中使用 — MCP 工具会自动注册,AI 可以直接调用 const conv = await CAT.agent.conversation.create(); const reply = await conv.chat("请使用知识库搜索关于 ScriptCat 的信息"); ``` -------------------------------- ### Create and Chat with an Agent Conversation Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/index.md A basic example demonstrating how to create a new conversation with the Agent and send a message. Ensure the `CAT.agent.conversation` permission is granted. ```javascript // ==UserScript== // @name Hello Agent // @match *://*/* // @grant CAT.agent.conversation // ==/UserScript== const conv = await CAT.agent.conversation.create(); const reply = await conv.chat("你好,请介绍一下你自己"); console.log(reply.content); ``` -------------------------------- ### SkillScript Parameter Definition Examples Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/skill-dev.md Illustrates different ways to define parameters for SkillScripts, including required strings, enums, optional numbers, and booleans. ```javascript // 必填字符串参数 // @param city string [required] 城市名称 // 带枚举的字符串参数 // @param unit string [celsius,fahrenheit] 温度单位 // 可选数字参数 // @param days number 预报天数 // 布尔参数 // @param detailed boolean 是否返回详细信息 ``` -------------------------------- ### Get Application URL with Ingress Source: https://github.com/scriptscat/scriptcat.org/blob/main/deploy/helm/templates/NOTES.txt If Ingress is enabled, this snippet shows how to construct the application URL using configured hosts and paths. ```go-template {{- if .Values.ingress.enabled }} {{- range $host := .Values.ingress.hosts }} {{- range .paths }} http{{ if $.Values.ingress.tls }}s{{ end }}://{{ $host.host }}{{ .path }} {{- end }} {{- end }} {{- end }} ``` -------------------------------- ### GM_cookie Usage Example (Promise) Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/api.md Demonstrates the Promise-based usage of GM_cookie for listing, setting, and deleting cookies using async/await syntax. Requires '@connect' declaration in metadata for the specified domain. ```javascript // Promise 形式 const cookies = await GM.cookie.list({ url: "https://example.com" }); await GM.cookie.set({ name: "foo", value: "bar", domain: "example.com" }); await GM.cookie.delete("foo", { domain: "example.com" }); ``` -------------------------------- ### Start DOM Monitoring with startMonitor Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/dom.md Initiates monitoring for DOM changes and dialog events (alert, confirm, prompt) on a specified tab. ```javascript await CAT.agent.dom.startMonitor(tabId); ``` -------------------------------- ### Get Model List Summary Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/model.md Obtain a text summary of all configured models, suitable for direct injection into prompts for AI reference. ```javascript const summary = await CAT.agent.model.getSummary(); ``` -------------------------------- ### Get MCP Server Prompt Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/mcp.md Fetches a prompt template from an MCP server, optionally with arguments to fill in parameters. ```javascript const messages = await CAT.agent.mcp.getPrompt(serverId, promptName, args?); ``` -------------------------------- ### GM_cookie Usage Example (Callback) Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/api.md Demonstrates the callback-based usage of GM_cookie for listing, setting, and deleting cookies. Requires '@connect' declaration in metadata for the specified domain. ```javascript // 回调形式 GM_cookie("list", { url: "https://example.com" }, (cookies) => { console.log(cookies); GM_cookie("set", { name: "foo", value: "bar", domain: "example.com" }, (result) => { console.log(result); GM_cookie("delete", { name: "foo", domain: "example.com" }, (result) => { console.log(result); }); }); }); ``` -------------------------------- ### Save Screenshot to OPFS - JavaScript Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/dom.md Example demonstrating how to save a screenshot directly to the Origin Private File System (OPFS). It logs the save path and file size upon completion. ```javascript // 保存截图到 OPFS const shot = await CAT.agent.dom.screenshot({ saveTo: "screenshots/page.png", quality: 90 }); console.log(`已保存到 ${shot.path},大小 ${shot.size} 字节`); ``` -------------------------------- ### Script Subscription Mode (`==UserSubscribe==`) Source: https://context7.com/scriptscat/scriptcat.org/llms.txt Package multiple scripts into a single subscription file. Subscribed scripts install and update silently without per-script confirmations. ```APIDOC ## Script Subscription Mode (`==UserSubscribe==`) Package multiple scripts into a single subscription file. Subscribed scripts install and update silently without per-script confirmations. ```js // ==UserSubscribe== // @name My Script Suite // @description Collection of productivity scripts for example.com // @version 1.2.0 // @author Dev // @connect api.example.com // @connect cdn.example.com // @scriptUrl https://example.com/scripts/enhancer.user.js // @scriptUrl https://example.com/scripts/dark-mode.user.js // @scriptUrl https://example.com/scripts/auto-fill.user.js // ==/UserSubscribe== // Install via: open the .user.sub.js URL in a browser with ScriptCat installed. // - First install: shows confirmation dialog // - Subsequent updates: silent, no confirmation (unless @connect changes) // - Scripts removed from @scriptUrl list are auto-uninstalled on next update check ``` ``` -------------------------------- ### SkillScript Metadata Example Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/skill-dev.md Define SkillScript metadata using special comments. This includes the tool's name, description, parameters, required permissions, external libraries, and timeout. ```javascript // ==SkillScript== // @name get_weather // @description 查询指定城市的天气信息 // @param city string [required] 城市名称,支持中英文 // @param days number 预报天数,默认3天 // @param format string [json,text] 输出格式 // @grant CAT.agent.opfs // @require https://cdn.example.com/utils.js // @timeout 60 // ==SkillScript== ``` -------------------------------- ### Define User Configuration UI with YAML Source: https://context7.com/scriptscat/scriptcat.org/llms.txt Use a YAML block after `==UserConfig==` to define a configuration UI for end users. Values are read using `GM_getValue("group.key")`. This example shows various input types like text, select, number, checkbox, multi-select, and textarea. ```javascript // ==UserScript== // @name Config Demo // @match *://*/* // @grant GM_getValue // @grant CAT_userConfig // ==/UserScript== /* ==UserConfig== general: apiKey: title: API Key description: Your API key for the service type: text password: true language: title: Language type: select default: en values: [en, zh, ja, fr, de] maxResults: title: Max Results type: number default: 10 min: 1 max: 100 unit: items autoRun: title: Auto Run on Load type: checkbox default: false tags: title: Filter Tags type: mult-select default: [news, tech] values: [news, tech, sports, science, entertainment] notes: title: Custom Notes type: textarea default: "" ==/UserConfig== */ // Read configuration values using "group.key" path const apiKey = GM_getValue("general.apiKey", ""); const lang = GM_getValue("general.language", "en"); const maxItems = GM_getValue("general.maxResults", 10); const autoRun = GM_getValue("general.autoRun", false); const tags = GM_getValue("general.tags", []); console.log({ apiKey, lang, maxItems, autoRun, tags }); // Open the config UI programmatically GM_registerMenuCommand("⚙️ Settings", CAT_userConfig); ``` -------------------------------- ### getSummary — 获取模型列表摘要 Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/model.md Returns a text summary of all configured models, suitable for direct injection into prompts for AI reference. ```APIDOC ## getSummary — 获取模型列表摘要 ### Description Returns a text summary of all configured models, suitable for direct injection into prompts for AI reference. ### Method `CAT.agent.model.getSummary()` ### Parameters None ### Response #### Success Response (string) - Returns a string containing a summary of all configured models. ### Response Example ```json "Available models: GPT-4o (OpenAI), Claude 3 Sonnet (Anthropic)" ``` ``` -------------------------------- ### Get Skill Details Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/skill.md Retrieves detailed information about a specific Skill extension. ```APIDOC ## get — Get Skill Details Retrieves detailed information about a specific Skill extension by its name. ### Method ```javascript await CAT.agent.skills.get(name: string) ``` ### Parameters #### Path Parameters - **name** (string) - Required - The name of the Skill to retrieve. ### Returns `SkillRecord | null` - The complete SkillRecord if found, otherwise `null`. **SkillRecord Structure:** Inherits all fields from `SkillSummary` and includes: | Field | Type | Description | |------|------|------| | `prompt` | `string` | The Markdown body content from SKILL.cat.md (prompt for AI) | | `config` | `Record` | Configuration field definitions (schema) | **SkillConfigField Structure:** | Field | Type | Description | |------|------|------| | `title` | `string` | Display title | | `type` | `"text" | "number" | "select" | "switch"` | Field type | | `secret` | `boolean` | Whether it is sensitive information (masked in UI) | | `required` | `boolean` | Whether it is required | | `default` | `unknown` | Default value | | `values` | `string[]` | List of options (only for `select` type) | ``` -------------------------------- ### SKILL.cat.md Metadata and Prompt Format Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/skill-dev.md Define Skill metadata using YAML frontmatter and provide AI instructions in the Markdown body. The frontmatter includes name, description, and configuration. ```markdown --- name: "weather-assistant" description: "天气查询助手,支持全球城市天气查询和预报" config: apiKey: title: "OpenWeather API Key" type: "text" secret: true required: true unit: title: "温度单位" type: "select" values: ["celsius", "fahrenheit"] default: "celsius" detailed: title: "详细模式" type: "switch" default: false maxDays: title: "预报天数" type: "number" default: 7 --- # 天气查询助手 你可以使用以下工具查询天气信息: ## 工具说明 - **get_weather**: 查询指定城市的当前天气和未来预报 - 参数 `city` 为城市名称(支持中英文) - 参数 `days` 为预报天数 ## 使用规则 1. 用户询问天气时,先确认城市名称 2. 默认返回当前天气 + 3 天预报 3. 温度根据配置的单位显示 ``` -------------------------------- ### addServer Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/mcp.md Adds a new MCP server configuration. ```APIDOC ## addServer — Add Server ### Description Adds a new MCP server configuration. ### Method `CAT.agent.mcp.addServer(config: MCPServerConfig)` ### Parameters #### Request Body - **config** (`MCPServerConfig`) - Required - The configuration for the new MCP server. - **name** (`string`) - Required - Display name for the server. - **url** (`string`) - Required - HTTP endpoint URL of the MCP server. - **apiKey** (`string`) - Optional - API Key for authentication. - **headers** (`Record`) - Optional - Custom request headers. - **enabled** (`boolean`) - Optional - Whether the server should be enabled by default (defaults to true). ### Request Example ```json { "name": "My MCP Server", "url": "https://mcp.example.com/api", "apiKey": "sk-xxx", "headers": { "X-Custom": "value" }, "enabled": true } ``` ``` -------------------------------- ### get — 获取指定模型 Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/model.md Retrieves the details of a specific model by its ID. Returns null if the model is not found. ```APIDOC ## get — 获取指定模型 ### Description Retrieves the details of a specific model by its ID. Returns null if the model is not found. ### Method `CAT.agent.model.get(modelId)` ### Parameters #### Path Parameters - **modelId** (string) - Required - The ID of the model to retrieve. ### Response #### Success Response (ModelSummary | null) - **id** (string) - 模型 ID - **name** (string) - 显示名称 - **provider** ("openai" | "anthropic" | "zhipu") - Provider 类型 - **apiBaseUrl** (string) - API 基础地址 - **model** (string) - 模型标识符(如 `gpt-4o`、`claude-sonnet-4-20250514`) - **maxTokens** (number) - 最大输出 Token 数 - **contextWindow** (number) - 上下文窗口大小 - **supportsVision** (boolean) - 是否支持视觉输入(图片) - **supportsImageOutput** (boolean) - 是否支持图片生成 ### Response Example ```json { "id": "model-1", "name": "GPT-4o", "provider": "openai", "apiBaseUrl": "https://api.openai.com", "model": "gpt-4o", "maxTokens": 128000, "contextWindow": 128000, "supportsVision": true, "supportsImageOutput": false } ``` ``` -------------------------------- ### Get Default Model ID Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/model.md Retrieve the ID of the user's currently set default model. ```javascript const defaultId = await CAT.agent.model.getDefault(); ``` -------------------------------- ### Skill Directory Structure Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/skill-dev.md Organize your Skill's components within a dedicated directory. SKILL.cat.md is the mandatory entry point. ```tree my-skill/ ├── SKILL.cat.md # 必须:元数据 + 提示词(入口文件) ├── scripts/ # 可选:SkillScript 工具脚本 │ ├── search.js │ └── export.js └── references/ # 可选:参考资料文件 ├── api-docs.md └── examples.json ``` -------------------------------- ### Get MCP Server Details Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/mcp.md Fetches the configuration details for a specific MCP server using its ID. ```javascript const server = await CAT.agent.mcp.getServer(serverId); ``` -------------------------------- ### Get Application URL with NodePort Source: https://github.com/scriptscat/scriptcat.org/blob/main/deploy/helm/templates/NOTES.txt When the service type is NodePort, this command exports the NodePort and Node IP to access the application. ```bash export NODE_PORT=$(kubectl get --namespace {{ .Release.Namespace }} -o jsonpath="{.spec.ports[0].nodePort}" services {{ include "scriptcat-docs.fullname" . }}) export NODE_IP=$(kubectl get nodes --namespace {{ .Release.Namespace }} -o jsonpath="{.items[0].status.addresses[0].address}") echo http://$NODE_IP:$NODE_PORT ``` -------------------------------- ### CAT_scriptLoaded - Early-Start Completion Source: https://context7.com/scriptscat/scriptcat.org/llms.txt When a script uses `@early-start` to inject before page load, use `CAT_scriptLoaded()` to wait until the DOM and dependencies are fully available. ```APIDOC ## `CAT_scriptLoaded` — Early-Start Completion When a script uses `@early-start` to inject before page load, use `CAT_scriptLoaded()` to wait until the DOM and dependencies are fully available. ```js // ==UserScript== // @name Early Start Demo // @match *://*/* // @run-at document-start // @early-start // @grant GM_setValue // ==/UserScript== // This runs before the page — intercept XHR immediately const origOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function(method, url, ...args) { console.log("[early] Intercepted:", method, url); return origOpen.call(this, method, url, ...args); }; // Wait for full script environment before reading storage CAT_scriptLoaded().then(() => { const savedData = GM_getValue("cache", null); console.log("Script fully loaded, cache:", savedData); }); ``` ``` -------------------------------- ### Get Specific Model Details Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/model.md Retrieve detailed information for a specific model using its ID. Returns `null` if the model does not exist. ```javascript const model = await CAT.agent.model.get(modelId); ``` -------------------------------- ### listServers Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/mcp.md Lists all configured MCP servers. ```APIDOC ## listServers — List Servers ### Description Lists all configured MCP servers. ### Method `CAT.agent.mcp.listServers()` ### Returns `MCPServerConfig[]` - An array of MCP server configurations. #### MCPServerConfig Fields - **id** (`string`) - Server ID - **name** (`string`) - Display name - **url** (`string`) - HTTP endpoint URL - **apiKey** (`string`) - API Key (optional) - **headers** (`Record`) - Custom request headers (optional) - **enabled** (`boolean`) - Whether the server is enabled - **createtime** (`number`) - Creation timestamp - **updatetime** (`number`) - Update timestamp ``` -------------------------------- ### list — 列出所有模型 Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/model.md Lists all configured models and their details. The returned list does not include the API key. ```APIDOC ## list — 列出所有模型 ### Description Lists all configured models and their details. The returned list does not include the API key. ### Method `CAT.agent.model.list()` ### Parameters None ### Response #### Success Response (ModelSummary[]) - **id** (string) - 模型 ID - **name** (string) - 显示名称 - **provider** ("openai" | "anthropic" | "zhipu") - Provider 类型 - **apiBaseUrl** (string) - API 基础地址 - **model** (string) - 模型标识符(如 `gpt-4o`、`claude-sonnet-4-20250514`) - **maxTokens** (number) - 最大输出 Token 数 - **contextWindow** (number) - 上下文窗口大小 - **supportsVision** (boolean) - 是否支持视觉输入(图片) - **supportsImageOutput** (boolean) - 是否支持图片生成 ### Response Example ```json [ { "id": "model-1", "name": "GPT-4o", "provider": "openai", "apiBaseUrl": "https://api.openai.com", "model": "gpt-4o", "maxTokens": 128000, "contextWindow": 128000, "supportsVision": true, "supportsImageOutput": false } ] ``` ``` -------------------------------- ### List All Models Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/model.md Retrieve a list of all configured models. The returned `ModelSummary[]` does not include the `apiKey` field. ```javascript const models = await CAT.agent.model.list(); ``` -------------------------------- ### Background Script Example Source: https://context7.com/scriptscat/scriptcat.org/llms.txt Background scripts run persistently in the service worker context without DOM access. They must return a Promise to indicate completion. ```javascript // ==UserScript== // @name Session Heartbeat // @namespace https://example.com/ // @version 1.0.0 // @author Dev // @background // @grant GM_xmlhttpRequest // @grant GM_notification // @connect api.example.com // ==/UserScript== return new Promise((resolve, reject) => { GM_xmlhttpRequest({ method: "POST", url: "https://api.example.com/heartbeat", headers: { "Content-Type": "application/json" }, data: JSON.stringify({ ts: Date.now() }), onload(res) { if (res.status === 200) { resolve("ok"); } else { reject(new CATRetryError("Heartbeat failed", 30)); // retry in 30s } }, onerror() { reject(new CATRetryError("Network error", 60)); } }); }); ``` -------------------------------- ### Wait for Full Script Environment with CAT_scriptLoaded Source: https://context7.com/scriptscat/scriptcat.org/llms.txt When using `@early-start`, `CAT_scriptLoaded()` ensures that the DOM and dependencies are fully available before proceeding. This is useful for scripts that need to interact with the page's environment after initial injection. ```javascript // ==UserScript== // @name Early Start Demo // @match *://*/* // @run-at document-start // @early-start // @grant GM_setValue // ==/UserScript== // This runs before the page — intercept XHR immediately const origOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function(method, url, ...args) { console.log("[early] Intercepted:", method, url); return origOpen.call(this, method, url, ...args); }; // Wait for full script environment before reading storage CAT_scriptLoaded().then(() => { const savedData = GM_getValue("cache", null); console.log("Script fully loaded, cache:", savedData); }); ``` -------------------------------- ### listPrompts Source: https://github.com/scriptscat/scriptcat.org/blob/main/docs/dev/agent/mcp.md Lists the prompt templates available on a specific MCP server. ```APIDOC ## listPrompts — List Prompts ### Description Lists the prompt templates available on a specific MCP server. ### Method `CAT.agent.mcp.listPrompts(serverId: string)` ### Parameters #### Path Parameters - **serverId** (`string`) - Required - The ID of the MCP server. ### Returns `Prompt[]` - An array of prompt template objects. ```